@assistant-ui/react-statewire 0.14.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.
@@ -104,9 +104,11 @@ declare namespace StatewireThread {
104
104
  readonly requestId: string;
105
105
  readonly response: InputResponse;
106
106
  };
107
- /** An input request projected out of the host state with its response echo. */
107
+ /** An input request projected out of the host state; a present `response` key marks the entry answered. */
108
108
  export type InputRequestState = InputRequest & {
109
- readonly response: InputResponse | null;
109
+ readonly response?: InputResponse;
110
+ /** The answer's `run/input` meta; absent when the answer carried none. */
111
+ readonly meta?: ReadonlyJSONValue;
110
112
  };
111
113
  export type RunReloadCommand = {
112
114
  readonly type: "run/reload";
@@ -138,15 +140,21 @@ declare namespace StatewireThread {
138
140
  readonly response: InputResponse | null;
139
141
  readonly meta: ReadonlyJSONValue | null;
140
142
  };
141
- /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
143
+ /** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
142
144
  export type RunsDispatch = {
143
145
  readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
144
146
  readonly messages: readonly RunsQueueEntry[];
145
147
  /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
146
148
  readonly rollbackTo?: string | null;
149
+ /** The run-starting op's meta; present only when carried. */
150
+ readonly rootMeta?: ReadonlyJSONValue;
147
151
  /** Present when input outcomes ride the dispatch; visible until the ack. */
148
152
  readonly inputOutcomes?: readonly RunsInputOutcome[];
149
153
  };
154
+ /** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
155
+ export type RunsStopping = {
156
+ readonly reason: "stop" | "message-edit" | "message-reload";
157
+ };
150
158
  /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
151
159
  export type RunsError = {
152
160
  readonly message: string;
@@ -160,10 +168,14 @@ declare namespace StatewireThread {
160
168
  readonly queue: readonly RunsQueueEntry[];
161
169
  readonly steerQueue: readonly RunsQueueEntry[];
162
170
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
163
- readonly dispatching: RunsDispatch | null;
171
+ readonly dispatching?: RunsDispatch;
172
+ readonly stopping?: RunsStopping;
173
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
174
+ readonly nextDispatch?: RunsDispatch;
164
175
  /** The parked pending set; present only in input-required. */
165
176
  readonly inputRequests?: readonly InputRequestState[];
166
- readonly error: RunsError | null;
177
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
178
+ readonly error?: RunsError;
167
179
  };
168
180
  /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
169
181
  export type MaterializeEffects = {
@@ -186,10 +198,14 @@ declare namespace StatewireThread {
186
198
  readonly queue: readonly RunsQueueEntry[];
187
199
  readonly steerQueue: readonly RunsQueueEntry[];
188
200
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
189
- readonly dispatching: RunsDispatch | null;
201
+ readonly dispatching?: RunsDispatch;
202
+ readonly stopping?: RunsStopping;
203
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
204
+ readonly nextDispatch?: RunsDispatch;
190
205
  /** The parked pending set; present only in input-required. */
191
206
  readonly inputRequests?: readonly InputRequestState[];
192
- readonly error: RunsError | null;
207
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
208
+ readonly error?: RunsError;
193
209
  };
194
210
  export type ConnectionMetadata = {
195
211
  pendingCommands: Command[];
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAiRvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;KACT;IACD,cAA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cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;IACd,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cAqRvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;KACT;IACD,cAAc,SAAS;IACvB;IACA;IACA,QAAQ;IACR,wBAAwB;IACxB,MAAM;;cAGI;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD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I;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -17,9 +17,7 @@ const NO_INPUT_REQUESTS = [];
17
17
  const RESTING_RUNS = {
18
18
  runId: null,
19
19
  queue: [],
20
- steerQueue: [],
21
- dispatching: null,
22
- error: null
20
+ steerQueue: []
23
21
  };
24
22
  const ambientContextOf = (context) => ({
25
23
  ...context.system !== void 0 && { system: context.system },
@@ -99,9 +97,11 @@ const useStatewireThread = (options) => {
99
97
  runId: entry.runId,
100
98
  queue: entry.queue,
101
99
  steerQueue: entry.steerQueue,
102
- dispatching: entry.dispatching,
100
+ ...entry.dispatching !== void 0 && { dispatching: entry.dispatching },
101
+ ...entry.stopping !== void 0 && { stopping: entry.stopping },
102
+ ...entry.nextDispatch !== void 0 && { nextDispatch: entry.nextDispatch },
103
103
  ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
104
- error: entry.error
104
+ ...entry.error !== void 0 && { error: entry.error }
105
105
  }
106
106
  };
107
107
  }, [state_0]);
@@ -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","dispatching","error","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","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","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","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","inputOutcomes","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","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 dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\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 dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n 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 with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** 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; null 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 /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\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 | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\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 | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\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,OAA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MAAM;GACN,GAAI4B,cAAc,QAAQ,EAAExF,OAAOwF,UAAU;EAC/C,CAAC,EACL;EACA,GAAI3E,QAAQ8F,cAAcK,UAAU,EAAEC,UAAUnB,aAAa;EAC7DoB,kBAAkBC,gBAChBzD,SAAS1E,uBAAuB8F,eAAeqC,aAAa3B,SAAS,CAAC;EACxE4B,0BAA0BC,aACxB3D,SAAS3E,yBAAyB+F,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAUxG,OAAOC,QAAQwG,cAAc;GAC7C,IACED,YAAY/G,KAAAA,MACX,OAAO+G,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI5H,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IAAE,GAAG4H;IAASvH,OAAOyE,KAAKzE;GAAM,CAAC,CAAC,CAACuD,OAC3DnD,YAAiB;IAChBW,OAAOC,QAAQwC,UAAUpD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAyD,UAAU7C,UAAUiF;CACpB,OAAOA;AACT;AAEA,MAAaxG,mBACXoB,YAEAzD,SAASwD,kBAAkB,CAAC,CAACC,OAAuC;AAuVtEnD,uBACEkD,oBACArD,eAAeiD,KAAAA,CAAkB,CAAC,CAACyL,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,UA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9H,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,6 +1,6 @@
1
1
  //#region src/inputRequests.ts
2
2
  const assertUnanswered = (request) => {
3
- if (request.response !== null) throw new Error(`statewire: input request "${request.id}" is already answered`);
3
+ if ("response" in request) throw new Error(`statewire: input request "${request.id}" is already answered`);
4
4
  };
5
5
  const resolveToolResultInput = (inputRequests, options, runId) => {
6
6
  const request = inputRequests.find((r) => r.type === "tool-call" && r.toolCallId === options.toolCallId);
@@ -1 +1 @@
1
- {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","StatewireThread","assertUnanswered","request","InputRequestState","response","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","runId","RunInputCommand","find","r","type","undefined","requestId","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst assertUnanswered = (request: StatewireThread.InputRequestState) => {\n if (request.response !== null)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly StatewireThread.InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n runId: string | null,\n): StatewireThread.RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-call input request for tool call \"${options.toolCallId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n ...(runId !== null && { runId }),\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly StatewireThread.InputRequestState[],\n options: RespondToToolApprovalOptions,\n runId: string | null,\n): StatewireThread.RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n ...(runId !== null && { runId }),\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMG,oBAAoBC,YAA+C;CACvE,IAAIA,QAAQE,aAAa,MACvB,MAAM,IAAIC,MACR,6BAA6BH,QAAQI,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,SAMAK,UACoC;CACpC,MAAMZ,UAAUM,cAAcQ,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEP,eAAeD,QAAQC,UAC5D;CACA,IAAIR,YAAYiB,KAAAA,GACd,MAAM,IAAId,MACR,wDAAwDI,QAAQC,WAAU,EAC5E;CACFT,iBAAiBC,OAAO;CACxB,OAAO;EACLgB,MAAM;EACN,GAAIJ,UAAU,QAAQ,EAAEA,MAAM;EAC9BM,WAAWlB,QAAQI;EACnBF,UAAU;GACRiB,QAAQZ,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaM,KAAAA,KAAa,EAAEN,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaS,4BACXd,eACAC,SACAK,UACoC;CACpC,MAAMZ,UAAUM,cAAcQ,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAEX,OAAOG,QAAQc,UACxD;CACA,IAAIrB,YAAYiB,KAAAA,GACd,MAAM,IAAId,MACR,8CAA8CI,QAAQc,WAAU,EAClE;CACFtB,iBAAiBC,OAAO;CACxB,OAAO;EACLgB,MAAM;EACN,GAAIJ,UAAU,QAAQ,EAAEA,MAAM;EAC9BM,WAAWlB,QAAQI;EACnBF,UAAU;GACRoB,UAAUf,QAAQgB,WAAW,YAAY;GACzC,GAAIhB,QAAQiB,WAAWP,KAAAA,KAAa,EAAEQ,SAASlB,QAAQiB,OAAO;EAChE;CACF;AACF"}
1
+ {"version":3,"file":"inputRequests.js","names":["RespondToToolApprovalOptions","ReadonlyJSONValue","StatewireThread","assertUnanswered","request","InputRequestState","Error","id","resolveToolResultInput","inputRequests","options","toolCallId","result","isError","artifact","runId","RunInputCommand","find","r","type","undefined","requestId","response","output","resolveToolApprovalInput","approvalId","decision","approved","reason","message"],"sources":["../src/inputRequests.ts"],"sourcesContent":["import type { RespondToToolApprovalOptions } from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst assertUnanswered = (request: StatewireThread.InputRequestState) => {\n if (\"response\" in request)\n throw new Error(\n `statewire: input request \"${request.id}\" is already answered`,\n );\n};\n\nexport const resolveToolResultInput = (\n inputRequests: readonly StatewireThread.InputRequestState[],\n options: {\n toolCallId: string;\n result: ReadonlyJSONValue;\n isError: boolean;\n artifact?: ReadonlyJSONValue | undefined;\n },\n runId: string | null,\n): StatewireThread.RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-call\" && r.toolCallId === options.toolCallId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-call input request for tool call \"${options.toolCallId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n ...(runId !== null && { runId }),\n requestId: request.id,\n response: {\n output: options.result,\n ...(options.isError && { isError: true }),\n ...(options.artifact !== undefined && { artifact: options.artifact }),\n },\n };\n};\n\nexport const resolveToolApprovalInput = (\n inputRequests: readonly StatewireThread.InputRequestState[],\n options: RespondToToolApprovalOptions,\n runId: string | null,\n): StatewireThread.RunInputCommand => {\n const request = inputRequests.find(\n (r) => r.type === \"tool-approval\" && r.id === options.approvalId,\n );\n if (request === undefined)\n throw new Error(\n `statewire: no tool-approval input request \"${options.approvalId}\"`,\n );\n assertUnanswered(request);\n return {\n type: \"run/input\",\n ...(runId !== null && { runId }),\n requestId: request.id,\n response: {\n decision: options.approved ? \"approve\" : \"reject\",\n ...(options.reason !== undefined && { message: options.reason }),\n },\n };\n};\n"],"mappings":";AAIA,MAAMG,oBAAoBC,YAA+C;CACvE,IAAI,cAAcA,SAChB,MAAM,IAAIE,MACR,6BAA6BF,QAAQG,GAAE,sBACzC;AACJ;AAEA,MAAaC,0BACXC,eACAC,SAMAK,UACoC;CACpC,MAAMX,UAAUK,cAAcQ,MAC3BC,MAAMA,EAAEC,SAAS,eAAeD,EAAEP,eAAeD,QAAQC,UAC5D;CACA,IAAIP,YAAYgB,KAAAA,GACd,MAAM,IAAId,MACR,wDAAwDI,QAAQC,WAAU,EAC5E;CACFR,iBAAiBC,OAAO;CACxB,OAAO;EACLe,MAAM;EACN,GAAIJ,UAAU,QAAQ,EAAEA,MAAM;EAC9BM,WAAWjB,QAAQG;EACnBe,UAAU;GACRC,QAAQb,QAAQE;GAChB,GAAIF,QAAQG,WAAW,EAAEA,SAAS,KAAK;GACvC,GAAIH,QAAQI,aAAaM,KAAAA,KAAa,EAAEN,UAAUJ,QAAQI,SAAS;EACrE;CACF;AACF;AAEA,MAAaU,4BACXf,eACAC,SACAK,UACoC;CACpC,MAAMX,UAAUK,cAAcQ,MAC3BC,MAAMA,EAAEC,SAAS,mBAAmBD,EAAEX,OAAOG,QAAQe,UACxD;CACA,IAAIrB,YAAYgB,KAAAA,GACd,MAAM,IAAId,MACR,8CAA8CI,QAAQe,WAAU,EAClE;CACFtB,iBAAiBC,OAAO;CACxB,OAAO;EACLe,MAAM;EACN,GAAIJ,UAAU,QAAQ,EAAEA,MAAM;EAC9BM,WAAWjB,QAAQG;EACnBe,UAAU;GACRI,UAAUhB,QAAQiB,WAAW,YAAY;GACzC,GAAIjB,QAAQkB,WAAWR,KAAAA,KAAa,EAAES,SAASnB,QAAQkB,OAAO;EAChE;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;cAmIa,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
1
+ {"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;cAkJa,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
@@ -4,13 +4,11 @@ const startRun = (draft, runId) => {
4
4
  runId: null,
5
5
  status: "running",
6
6
  queue: [],
7
- steerQueue: [],
8
- dispatching: null,
9
- error: null
7
+ steerQueue: []
10
8
  };
11
9
  entry.status = "running";
12
10
  if (entry.runId === null) entry.runId = runId;
13
- entry.error = null;
11
+ delete entry.error;
14
12
  delete entry.inputRequests;
15
13
  draft.status = "running";
16
14
  return entry;
@@ -40,16 +38,17 @@ const enqueueOrSteer = (draft, command, runId) => {
40
38
  }
41
39
  const steer = command.type === "run/steer";
42
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" : "message-send";
43
42
  const target = startRun(draft, runId);
44
43
  if (steer) {
45
44
  if (sourceLane === target.steerQueue) target.steerQueue.splice(sourceIndex, 0, entry);
46
45
  else target.steerQueue.push(entry);
47
46
  target.dispatching = {
48
- trigger: "message-send",
47
+ trigger,
49
48
  messages: target.steerQueue.splice(0)
50
49
  };
51
50
  } else target.dispatching = {
52
- trigger: "message-send",
51
+ trigger,
53
52
  messages: [entry]
54
53
  };
55
54
  return;
@@ -62,6 +61,10 @@ const enqueueOrSteer = (draft, command, runId) => {
62
61
  else insert(lane, entry, command);
63
62
  if (continues) startRun(draft, runId);
64
63
  };
64
+ const stageRewind = (run, dispatch) => {
65
+ run.stopping = { reason: dispatch.trigger };
66
+ run.nextDispatch = dispatch;
67
+ };
65
68
  /** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
66
69
  const runsOptimistic = (mount, command, ctx) => {
67
70
  const draft = mount;
@@ -73,20 +76,33 @@ const runsOptimistic = (mount, command, ctx) => {
73
76
  break;
74
77
  case "run/edit": {
75
78
  const { message, runAnchorMessageId } = command.params[0];
76
- startRun(draft, runId).dispatching = {
79
+ const dispatch = {
77
80
  trigger: "message-edit",
78
81
  messages: [{ ...message }],
79
82
  rollbackTo: runAnchorMessageId
80
83
  };
84
+ const run = draft.runs?.[0];
85
+ if (run?.status === "running") stageRewind(run, dispatch);
86
+ else startRun(draft, runId).dispatching = dispatch;
81
87
  break;
82
88
  }
83
89
  case "run/reload": {
84
90
  const { runAnchorMessageId } = command.params[0];
85
- startRun(draft, runId).dispatching = {
91
+ const dispatch = {
86
92
  trigger: "message-reload",
87
93
  messages: [],
88
94
  rollbackTo: runAnchorMessageId
89
95
  };
96
+ const run = draft.runs?.[0];
97
+ if (run?.status === "running") stageRewind(run, dispatch);
98
+ else startRun(draft, runId).dispatching = dispatch;
99
+ break;
100
+ }
101
+ case "run/stop": {
102
+ const run = draft.runs?.[0];
103
+ if (run?.status !== "running") break;
104
+ run.stopping = { reason: "stop" };
105
+ delete run.nextDispatch;
90
106
  break;
91
107
  }
92
108
  case "run/continue": {
@@ -112,7 +128,7 @@ const runsOptimistic = (mount, command, ctx) => {
112
128
  const target = requests.find((r) => r.id === requestId);
113
129
  if (target === void 0) break;
114
130
  target.response = response;
115
- if (requests.every((r) => r.response !== null)) startRun(draft, runId);
131
+ if (requests.every((r) => "response" in r)) startRun(draft, runId);
116
132
  break;
117
133
  }
118
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","trigger","messages","rollbackTo","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","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 RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching: {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n } | null;\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 dispatching: null,\n error: null,\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 entry.error = null;\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 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: \"message-send\",\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger: \"message-send\", 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\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 startRun(draft, runId).dispatching = {\n trigger: \"message-edit\",\n messages: [{ ...message }],\n rollbackTo: runAnchorMessageId,\n };\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n startRun(draft, runId).dispatching = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\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) => r.response !== null)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AA8BA,MAAM6B,YAAYC,OAAkBjB,UAA4B;CAC9D,MAAMkB,QAAS,CAACD,MAAMF,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCf,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;EACZC,aAAa;EACbM,OAAO;CACT;CACAO,MAAMjB,SAAS;CAEf,IAAIiB,MAAMlB,UAAU,MAAMkB,MAAMlB,QAAQA;CACxCkB,MAAMP,QAAQ;CACd,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,EAAEpC,OAAO8B,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAEpC,OAAO+B,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA/B,UACS;CACT,MAAMkC,MAAMjB,MAAMF,OAAO;CAEzB,MAAMd,SAASiC,KAAKjC,UAAU;CAC9B,MAAMV,KAAK,aAAawC,UAAUA,QAAQI,QAAQ5C,KAAKwC,QAAQK;CAE/D,IAAIF,K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,OAAO;GACV,MAAMvB,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,EAAEpC,OAAO6C,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAEwC,WAAWtD,aAAaqB,QAC7B0B,OAAO;GACV,MAAMS,WAAWjD,MAAMF,OAAO,EAAE,EAAEN;GAClC,IAAIyD,aAAazC,KAAAA,GAAW;GAC5B,MAAMoB,SAASqB,SAAS3B,MAAM4B,MAAMA,EAAE5E,OAAOyE,SAAS;GACtD,IAAInB,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOnC,WAAWA;GAClB,IAAIwD,SAASE,OAAOD,MAAMA,EAAEzD,aAAa,IAAI,GAAGM,SAASC,OAAOjB,KAAK;GACrE;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;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,OAAOkC,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAExC,OAAOmC,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA/B,UACS;CACT,MAAMkC,MAAMjB,MAAMF,OAAO;CAEzB,MAAMd,SAASiC,KAAKjC,UAAU;CAC9B,MAAMd,KAAK,aAAa4C,UAAUA,QAAQI,QAAQhD,KAAK4C,QAAQK;CAE/D,IAAIF,KAAK7B,aAAaR,SAASwC,MAAMV,MAAMA,EAAExC,OAAOA,EAAE,GAAG;CACzD,MAAMmD,aACJJ,QAAQT,KAAAA,IACJA,KAAAA,IACA,CAACS,IAAI/B,OAAO+B,IAAI9B,UAAU,CAAC,CAACmC,MAAMC,MAAMA,EAAEH,MAAMV,MAAMA,EAAExC,OAAOA,EAAE,CAAC;CAExE,IAAI+B;CACJ,IAAIuB,cAAc;CAClB,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AKjC,WAAW,WAAW;GAC/BiC,IAAI5B,WAAW,EAAEC,QAAQ,OAAO;GAChC,OAAO2B,IAAI1B;GACX;EACF;EACA,KAAK,gBAAgB;GACnB,MAAM0B,MAAMjB,MAAMF,OAAO;GACzB,IAAImB,QAAQT,KAAAA,GAAWS,IAAI9B,aAAa,CAAA;GACxCY,SAASC,OAAOjB,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,17 +27,19 @@ type ServerRunEntry = {
27
27
  parts: { type: "text"; text: string }[];
28
28
  }[];
29
29
  steerQueue: ServerRunEntry["queue"];
30
- dispatching: {
30
+ dispatching?: {
31
31
  trigger: string;
32
32
  messages: ServerRunEntry["queue"];
33
33
  rollbackTo?: string | null;
34
- } | null;
35
- error: { message: string } | null;
34
+ };
35
+ stopping?: { reason: string };
36
+ nextDispatch?: ServerRunEntry["dispatching"];
37
+ error?: { message: string };
36
38
  inputRequests?: {
37
39
  type: string;
38
40
  id: string;
39
41
  toolCallId?: string;
40
- response: Record<string, unknown> | null;
42
+ response?: Record<string, unknown>;
41
43
  }[];
42
44
  };
43
45
 
@@ -65,8 +67,6 @@ const withRun = (
65
67
  runId: null,
66
68
  queue: [],
67
69
  steerQueue: [],
68
- dispatching: null,
69
- error: null,
70
70
  ...entry,
71
71
  },
72
72
  ],
@@ -245,7 +245,7 @@ describe("StatewireThread runs mode", () => {
245
245
  expect(runs().runId).toBe("run-1");
246
246
  expect(runs().queue.map((e) => e.id)).toEqual(["q1"]);
247
247
  expect(runs().steerQueue.map((e) => e.id)).toEqual(["s1"]);
248
- expect(runs().error).toBeNull();
248
+ expect(runs().error).toBeUndefined();
249
249
  expect(aui().thread().getState().isRunning).toBe(true);
250
250
 
251
251
  act(() => {
@@ -272,6 +272,45 @@ describe("StatewireThread runs mode", () => {
272
272
  expect(threadStatus(aui())).toBe("stopped");
273
273
  });
274
274
 
275
+ it("replicates the stopping window through the runs read", async () => {
276
+ const server = createServer(
277
+ withRun({
278
+ status: "running",
279
+ runId: "run-1",
280
+ stopping: { reason: "message-edit" },
281
+ nextDispatch: {
282
+ trigger: "message-edit",
283
+ messages: [
284
+ { id: "m1b", role: "user", parts: [{ type: "text", text: "b" }] },
285
+ ],
286
+ rollbackTo: "p0",
287
+ },
288
+ }),
289
+ );
290
+ const { aui, runs } = mountThread({ transport: server.transport });
291
+
292
+ await waitFor(() => expect(threadStatus(aui())).toBe("running"));
293
+ expect(runs().stopping).toEqual({ reason: "message-edit" });
294
+ expect(runs().nextDispatch!.trigger).toBe("message-edit");
295
+ expect(runs().dispatching).toBeUndefined();
296
+
297
+ act(() => {
298
+ const entry = server.cell.state!.runs![0]!;
299
+ entry.dispatching = {
300
+ trigger: "message-edit",
301
+ messages: [
302
+ { id: "m1b", role: "user", parts: [{ type: "text", text: "b" }] },
303
+ ],
304
+ rollbackTo: "p0",
305
+ };
306
+ delete entry.stopping;
307
+ delete entry.nextDispatch;
308
+ });
309
+ await waitFor(() => expect(runs().stopping).toBeUndefined());
310
+ expect(runs().nextDispatch).toBeUndefined();
311
+ expect(runs().dispatching!.trigger).toBe("message-edit");
312
+ });
313
+
275
314
  it("stamps the live run's id onto run/stop", async () => {
276
315
  const server = createServer(withRun({ status: "running", runId: "run-7" }));
277
316
  const { aui } = mountThread({ transport: server.transport });
@@ -290,9 +329,7 @@ describe("StatewireThread runs mode", () => {
290
329
  withRun({
291
330
  status: "input-required",
292
331
  runId: "run-1",
293
- inputRequests: [
294
- { type: "tool-approval", id: "r1", toolCallId: "t1", response: null },
295
- ],
332
+ inputRequests: [{ type: "tool-approval", id: "r1", toolCallId: "t1" }],
296
333
  }),
297
334
  );
298
335
  const toolConverter: StatewireThread.StateConverter<
@@ -326,7 +363,7 @@ describe("StatewireThread runs mode", () => {
326
363
 
327
364
  await waitFor(() =>
328
365
  expect(runs().inputRequests).toEqual([
329
- { type: "tool-approval", id: "r1", toolCallId: "t1", response: null },
366
+ { type: "tool-approval", id: "r1", toolCallId: "t1" },
330
367
  ]),
331
368
  );
332
369
  act(() => {
@@ -420,9 +457,9 @@ describe("StatewireThread runs mode", () => {
420
457
 
421
458
  act(() => {
422
459
  server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
423
- server.cell.state!.runs![0]!.dispatching = null;
460
+ delete server.cell.state!.runs![0]!.dispatching;
424
461
  });
425
- await waitFor(() => expect(runs().dispatching).toBeNull());
462
+ await waitFor(() => expect(runs().dispatching).toBeUndefined());
426
463
  expect(
427
464
  aui()
428
465
  .thread()
@@ -35,8 +35,7 @@ type ServerRun = {
35
35
  status: StatewireThread.RunStatus;
36
36
  queue: LaneEntry[];
37
37
  steerQueue: LaneEntry[];
38
- dispatching: null;
39
- error: { message: string } | null;
38
+ error?: { message: string };
40
39
  inputRequests?: StatewireThread.InputRequestState[];
41
40
  };
42
41
 
@@ -64,8 +63,6 @@ const runEntry = (
64
63
  runId: null,
65
64
  queue: [],
66
65
  steerQueue: [],
67
- dispatching: null,
68
- error: null,
69
66
  ...entry,
70
67
  });
71
68
 
@@ -979,7 +976,7 @@ describe("StatewireThread", () => {
979
976
  it("answers a pending tool-call request via run/input", async () => {
980
977
  const server = createServer(
981
978
  withInputRequests([
982
- { type: "tool-call", id: "req1", toolCallId: "tc1", response: null },
979
+ { type: "tool-call", id: "req1", toolCallId: "tc1" },
983
980
  ]),
984
981
  );
985
982
  const { aui } = mountThread({
@@ -1039,12 +1036,7 @@ describe("StatewireThread", () => {
1039
1036
  it("answers tool approvals via run/input decisions", async () => {
1040
1037
  const server = createServer(
1041
1038
  withInputRequests([
1042
- {
1043
- type: "tool-approval",
1044
- id: "req2",
1045
- toolCallId: "tc1",
1046
- response: null,
1047
- },
1039
+ { type: "tool-approval", id: "req2", toolCallId: "tc1" },
1048
1040
  ]),
1049
1041
  );
1050
1042
  const { aui } = mountThread({
@@ -1068,12 +1060,7 @@ describe("StatewireThread", () => {
1068
1060
  it("surfaces custom request types through extras.inputRequests", async () => {
1069
1061
  const server = createServer(
1070
1062
  withInputRequests([
1071
- {
1072
- type: "human-review",
1073
- id: "req9",
1074
- prompt: "check this",
1075
- response: null,
1076
- },
1063
+ { type: "human-review", id: "req9", prompt: "check this" },
1077
1064
  ]),
1078
1065
  );
1079
1066
  const { aui } = mountThread({
@@ -1084,14 +1071,7 @@ describe("StatewireThread", () => {
1084
1071
  await waitFor(() =>
1085
1072
  expect(
1086
1073
  asStatewireExtras(aui().thread().getState().extras).inputRequests,
1087
- ).toEqual([
1088
- {
1089
- type: "human-review",
1090
- id: "req9",
1091
- prompt: "check this",
1092
- response: null,
1093
- },
1094
- ]),
1074
+ ).toEqual([{ type: "human-review", id: "req9", prompt: "check this" }]),
1095
1075
  );
1096
1076
  });
1097
1077
  });
@@ -59,8 +59,6 @@ const RESTING_RUNS: StatewireThread.Runs = {
59
59
  runId: null,
60
60
  queue: [],
61
61
  steerQueue: [],
62
- dispatching: null,
63
- error: null,
64
62
  };
65
63
 
66
64
  const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
@@ -188,11 +186,17 @@ const useStatewireThread = (
188
186
  runId: entry.runId,
189
187
  queue: entry.queue,
190
188
  steerQueue: entry.steerQueue,
191
- dispatching: entry.dispatching,
189
+ ...(entry.dispatching !== undefined && {
190
+ dispatching: entry.dispatching,
191
+ }),
192
+ ...(entry.stopping !== undefined && { stopping: entry.stopping }),
193
+ ...(entry.nextDispatch !== undefined && {
194
+ nextDispatch: entry.nextDispatch,
195
+ }),
192
196
  ...(entry.inputRequests !== undefined && {
193
197
  inputRequests: entry.inputRequests,
194
198
  }),
195
- error: entry.error,
199
+ ...(entry.error !== undefined && { error: entry.error }),
196
200
  },
197
201
  };
198
202
  }, [state]);
@@ -440,9 +444,11 @@ export namespace StatewireThread {
440
444
  readonly response: InputResponse;
441
445
  };
442
446
 
443
- /** An input request projected out of the host state with its response echo. */
447
+ /** An input request projected out of the host state; a present `response` key marks the entry answered. */
444
448
  export type InputRequestState = InputRequest & {
445
- readonly response: InputResponse | null;
449
+ readonly response?: InputResponse;
450
+ /** The answer's `run/input` meta; absent when the answer carried none. */
451
+ readonly meta?: ReadonlyJSONValue;
446
452
  };
447
453
 
448
454
  export type RunReloadCommand = {
@@ -490,7 +496,7 @@ export namespace StatewireThread {
490
496
  readonly meta: ReadonlyJSONValue | null;
491
497
  };
492
498
 
493
- /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
499
+ /** The dispatch record — the unacked batch handed to the run; absent between the ack and the next dispatch or take. */
494
500
  export type RunsDispatch = {
495
501
  readonly trigger:
496
502
  | "message-send"
@@ -503,10 +509,17 @@ export namespace StatewireThread {
503
509
  readonly messages: readonly RunsQueueEntry[];
504
510
  /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
505
511
  readonly rollbackTo?: string | null;
512
+ /** The run-starting op's meta; present only when carried. */
513
+ readonly rootMeta?: ReadonlyJSONValue;
506
514
  /** Present when input outcomes ride the dispatch; visible until the ack. */
507
515
  readonly inputOutcomes?: readonly RunsInputOutcome[];
508
516
  };
509
517
 
518
+ /** The stopping window: present while a stop of the live run is underway; `"message-edit"` / `"message-reload"` pair with `nextDispatch`. */
519
+ export type RunsStopping = {
520
+ readonly reason: "stop" | "message-edit" | "message-reload";
521
+ };
522
+
510
523
  /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
511
524
  export type RunsError = {
512
525
  readonly message: string;
@@ -521,10 +534,14 @@ export namespace StatewireThread {
521
534
  readonly queue: readonly RunsQueueEntry[];
522
535
  readonly steerQueue: readonly RunsQueueEntry[];
523
536
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
524
- readonly dispatching: RunsDispatch | null;
537
+ readonly dispatching?: RunsDispatch;
538
+ readonly stopping?: RunsStopping;
539
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
540
+ readonly nextDispatch?: RunsDispatch;
525
541
  /** The parked pending set; present only in input-required. */
526
542
  readonly inputRequests?: readonly InputRequestState[];
527
- readonly error: RunsError | null;
543
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
544
+ readonly error?: RunsError;
528
545
  };
529
546
 
530
547
  /** App-shaped effects `runsMaterialize` applies for the dispatch record. */
@@ -550,10 +567,14 @@ export namespace StatewireThread {
550
567
  readonly queue: readonly RunsQueueEntry[];
551
568
  readonly steerQueue: readonly RunsQueueEntry[];
552
569
  /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
553
- readonly dispatching: RunsDispatch | null;
570
+ readonly dispatching?: RunsDispatch;
571
+ readonly stopping?: RunsStopping;
572
+ /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */
573
+ readonly nextDispatch?: RunsDispatch;
554
574
  /** The parked pending set; present only in input-required. */
555
575
  readonly inputRequests?: readonly InputRequestState[];
556
- readonly error: RunsError | null;
576
+ /** Set only by an unhandled throw; cleared by the next user-initiated run. */
577
+ readonly error?: RunsError;
557
578
  };
558
579
 
559
580
  export type ConnectionMetadata = {
@@ -3,7 +3,7 @@ import type { ReadonlyJSONValue } from "assistant-stream/utils";
3
3
  import type { StatewireThread } from "./StatewireThread";
4
4
 
5
5
  const assertUnanswered = (request: StatewireThread.InputRequestState) => {
6
- if (request.response !== null)
6
+ if ("response" in request)
7
7
  throw new Error(
8
8
  `statewire: input request "${request.id}" is already answered`,
9
9
  );
@@ -6,7 +6,7 @@ import { runsMaterialize } from "./runsMaterialize";
6
6
 
7
7
  type Draft = Record<string, any>;
8
8
 
9
- const mount = (dispatching: Draft | null): Draft => ({
9
+ const mount = (dispatching?: Draft): Draft => ({
10
10
  status: "running",
11
11
  runs: [
12
12
  {
@@ -14,8 +14,7 @@ const mount = (dispatching: Draft | null): Draft => ({
14
14
  status: "running",
15
15
  queue: [],
16
16
  steerQueue: [],
17
- dispatching,
18
- error: null,
17
+ ...(dispatching !== undefined && { dispatching }),
19
18
  },
20
19
  ],
21
20
  });
@@ -46,7 +45,7 @@ describe("runsMaterialize", () => {
46
45
  it("does nothing while resting or between dispatches", () => {
47
46
  const { appended, effects } = record();
48
47
  runsMaterialize({ status: "ready", runs: [] }, effects);
49
- runsMaterialize(mount(null), effects);
48
+ runsMaterialize(mount(), effects);
50
49
  expect(appended).toEqual([]);
51
50
  });
52
51
 
@@ -18,8 +18,6 @@ const mount = (entry?: Draft): Draft =>
18
18
  runId: null,
19
19
  queue: [],
20
20
  steerQueue: [],
21
- dispatching: null,
22
- error: null,
23
21
  ...entry,
24
22
  },
25
23
  ],
@@ -70,8 +68,8 @@ describe("runsOptimistic", () => {
70
68
  expect(run(draft).status).toBe("running");
71
69
  expect(run(draft).runId).toBe("run-1");
72
70
  expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["s1", "s2"]);
73
- expect(run(draft).dispatching).toBeNull();
74
- expect(run(draft).error).toBeNull();
71
+ expect(run(draft).dispatching).toBeUndefined();
72
+ expect(run(draft).error).toBeUndefined();
75
73
  });
76
74
 
77
75
  it("dispatches an idle steer: the whole lane rides dispatching, in lane order", () => {
@@ -79,7 +77,7 @@ describe("runsOptimistic", () => {
79
77
  status: "input-required",
80
78
  runId: "run-1",
81
79
  steerQueue: [message("s1")],
82
- inputRequests: [{ type: "custom", id: "r1", response: null }],
80
+ inputRequests: [{ type: "custom", id: "r1" }],
83
81
  });
84
82
  apply(draft, "run/steer", {
85
83
  type: "run/steer",
@@ -107,10 +105,23 @@ describe("runsOptimistic", () => {
107
105
  expect(ready.status).toBe("running");
108
106
  expect(run(ready).runId).toBe("mint-1");
109
107
  expect(run(ready).queue).toEqual([]);
108
+ expect(run(ready).dispatching.trigger).toBe("message-send");
110
109
  expect(run(ready).dispatching.messages.map((e: Draft) => e.id)).toEqual([
111
110
  "a",
112
111
  ]);
113
112
 
113
+ const errored = mount({ status: "error", runId: "run-1" });
114
+ apply(errored, "run/enqueue", {
115
+ type: "run/enqueue",
116
+ runId: "run-1",
117
+ message: message("a"),
118
+ });
119
+ expect(errored.status).toBe("running");
120
+ expect(run(errored).dispatching).toEqual({
121
+ trigger: "error-continue",
122
+ messages: [message("a")],
123
+ });
124
+
114
125
  const stopped = mount({
115
126
  status: "stopped",
116
127
  runId: "run-1",
@@ -198,7 +209,7 @@ describe("runsOptimistic", () => {
198
209
  const draft = mount({
199
210
  status: "input-required",
200
211
  runId: "run-1",
201
- inputRequests: [{ type: "custom", id: "r1", response: null }],
212
+ inputRequests: [{ type: "custom", id: "r1" }],
202
213
  });
203
214
  apply(draft, "run/edit", {
204
215
  type: "run/edit",
@@ -217,6 +228,63 @@ describe("runsOptimistic", () => {
217
228
  });
218
229
  });
219
230
 
231
+ it("run/edit while running stages the stopping window", () => {
232
+ const draft = mount({
233
+ status: "running",
234
+ runId: "run-1",
235
+ dispatching: { trigger: "message-send", messages: [message("m1")] },
236
+ });
237
+ apply(draft, "run/edit", {
238
+ type: "run/edit",
239
+ runId: "run-1",
240
+ message: message("m1b"),
241
+ sourceId: "m1",
242
+ runAnchorMessageId: "p0",
243
+ });
244
+ expect(draft.status).toBe("running");
245
+ expect(run(draft).status).toBe("running");
246
+ expect(run(draft).stopping).toEqual({ reason: "message-edit" });
247
+ expect(run(draft).nextDispatch).toEqual({
248
+ trigger: "message-edit",
249
+ messages: [message("m1b")],
250
+ rollbackTo: "p0",
251
+ });
252
+ expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
253
+ "m1",
254
+ ]);
255
+ });
256
+
257
+ it("run/reload while running stages the stopping window", () => {
258
+ const draft = mount({ status: "running", runId: "run-1" });
259
+ apply(draft, "run/reload", {
260
+ type: "run/reload",
261
+ runId: "run-1",
262
+ sourceId: "a1",
263
+ runAnchorMessageId: "m1",
264
+ });
265
+ expect(run(draft).stopping).toEqual({ reason: "message-reload" });
266
+ expect(run(draft).nextDispatch).toEqual({
267
+ trigger: "message-reload",
268
+ messages: [],
269
+ rollbackTo: "m1",
270
+ });
271
+ });
272
+
273
+ it("run/stop opens the window and clears a staged rewind", () => {
274
+ const draft = mount({ status: "running", runId: "run-1" });
275
+ apply(draft, "run/edit", {
276
+ type: "run/edit",
277
+ runId: "run-1",
278
+ message: message("m1b"),
279
+ sourceId: "m1",
280
+ runAnchorMessageId: "p0",
281
+ });
282
+ apply(draft, "run/stop", { runId: "run-1" });
283
+ expect(run(draft).stopping).toEqual({ reason: "stop" });
284
+ expect(run(draft).nextDispatch).toBeUndefined();
285
+ expect(run(draft).status).toBe("running");
286
+ });
287
+
220
288
  it("run/reload predicts the rewind dispatch record", () => {
221
289
  const draft = mount({
222
290
  status: "stopped",
@@ -231,7 +299,7 @@ describe("runsOptimistic", () => {
231
299
  });
232
300
  expect(draft.status).toBe("running");
233
301
  expect(run(draft).runId).toBe("run-1");
234
- expect(run(draft).error).toBeNull();
302
+ expect(run(draft).error).toBeUndefined();
235
303
  expect(run(draft).dispatching).toEqual({
236
304
  trigger: "message-reload",
237
305
  messages: [],
@@ -267,7 +335,6 @@ describe("runsOptimistic", () => {
267
335
  queue: [],
268
336
  steerQueue: [],
269
337
  dispatching: { trigger: "message-send", messages: [message("s1")] },
270
- error: null,
271
338
  });
272
339
  });
273
340
 
@@ -276,8 +343,8 @@ describe("runsOptimistic", () => {
276
343
  status: "input-required",
277
344
  runId: "run-1",
278
345
  inputRequests: [
279
- { type: "custom", id: "r1", response: null },
280
- { type: "custom", id: "r2", response: null },
346
+ { type: "custom", id: "r1" },
347
+ { type: "custom", id: "r2" },
281
348
  ],
282
349
  });
283
350
  apply(draft, "run/input", {
@@ -306,7 +373,7 @@ describe("runsOptimistic", () => {
306
373
  runId: "run-1",
307
374
  inputRequests: [
308
375
  { type: "custom", id: "r1", response: { ok: true } },
309
- { type: "custom", id: "r2", response: null },
376
+ { type: "custom", id: "r2" },
310
377
  ],
311
378
  });
312
379
  apply(draft, "run/steer", {
@@ -323,14 +390,14 @@ describe("runsOptimistic", () => {
323
390
  ]);
324
391
  });
325
392
 
326
- it("leaves the draft untouched for run/stop and unknown moves", () => {
327
- const draft = mount({ status: "running", runId: "run-1" });
393
+ it("leaves the draft untouched for unknown moves and idle run/stop", () => {
394
+ const draft = mount({ status: "stopped", runId: "run-1" });
328
395
  apply(draft, "run/stop", { runId: "run-1" });
329
396
  apply(draft, "run/enqueue", {
330
397
  type: "run/enqueue",
331
398
  runId: "run-1",
332
399
  messageId: "ghost",
333
400
  });
334
- expect(draft).toEqual(mount({ status: "running", runId: "run-1" }));
401
+ expect(draft).toEqual(mount({ status: "stopped", runId: "run-1" }));
335
402
  });
336
403
  });
@@ -9,18 +9,22 @@ type LaneEntry = {
9
9
  meta?: unknown;
10
10
  };
11
11
 
12
+ type Dispatch = {
13
+ trigger: string;
14
+ messages: LaneEntry[];
15
+ rollbackTo?: string | null;
16
+ };
17
+
12
18
  type RunEntry = {
13
19
  runId: string | null;
14
20
  status: StatewireThread.RunStatus;
15
21
  queue: LaneEntry[];
16
22
  steerQueue: LaneEntry[];
17
- dispatching: {
18
- trigger: string;
19
- messages: LaneEntry[];
20
- rollbackTo?: string | null;
21
- } | null;
22
- inputRequests?: { id: string; response: unknown }[];
23
- error: unknown;
23
+ dispatching?: Dispatch;
24
+ stopping?: { reason: "stop" | "message-edit" | "message-reload" };
25
+ nextDispatch?: Dispatch;
26
+ inputRequests?: { id: string; response?: unknown }[];
27
+ error?: unknown;
24
28
  };
25
29
 
26
30
  type RunsDraft = {
@@ -34,13 +38,11 @@ const startRun = (draft: RunsDraft, runId: string): RunEntry => {
34
38
  status: "running",
35
39
  queue: [],
36
40
  steerQueue: [],
37
- dispatching: null,
38
- error: null,
39
41
  });
40
42
  entry.status = "running";
41
43
  // A live run keeps its identity; a mint folds the client-generated id.
42
44
  if (entry.runId === null) entry.runId = runId;
43
- entry.error = null;
45
+ delete entry.error;
44
46
  delete entry.inputRequests;
45
47
  draft.status = "running";
46
48
  return entry;
@@ -103,6 +105,12 @@ const enqueueOrSteer = (
103
105
  run.queue.length === 0 &&
104
106
  run.steerQueue.length === 0));
105
107
  if (direct) {
108
+ const trigger =
109
+ status === "error"
110
+ ? "error-continue"
111
+ : status === "stopped"
112
+ ? "stop-continue"
113
+ : "message-send";
106
114
  const target = startRun(draft, runId);
107
115
  if (steer) {
108
116
  // The whole steer lane rides the dispatch, in lane order.
@@ -110,10 +118,10 @@ const enqueueOrSteer = (
110
118
  target.steerQueue.splice(sourceIndex, 0, entry);
111
119
  else target.steerQueue.push(entry);
112
120
  target.dispatching = {
113
- trigger: "message-send",
121
+ trigger,
114
122
  messages: target.steerQueue.splice(0),
115
123
  };
116
- } else target.dispatching = { trigger: "message-send", messages: [entry] };
124
+ } else target.dispatching = { trigger, messages: [entry] };
117
125
  return;
118
126
  }
119
127
  const continues = steer && status !== "running";
@@ -128,6 +136,13 @@ const enqueueOrSteer = (
128
136
  if (continues) startRun(draft, runId);
129
137
  };
130
138
 
139
+ const stageRewind = (run: RunEntry, dispatch: Dispatch): void => {
140
+ run.stopping = {
141
+ reason: dispatch.trigger as "message-edit" | "message-reload",
142
+ };
143
+ run.nextDispatch = dispatch;
144
+ };
145
+
131
146
  /** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
132
147
  export const runsOptimistic = (
133
148
  mount: unknown,
@@ -153,21 +168,34 @@ export const runsOptimistic = (
153
168
  case "run/edit": {
154
169
  const { message, runAnchorMessageId } = command
155
170
  .params[0] as StatewireThread.RunEditCommand;
156
- startRun(draft, runId).dispatching = {
171
+ const dispatch: Dispatch = {
157
172
  trigger: "message-edit",
158
173
  messages: [{ ...message }],
159
174
  rollbackTo: runAnchorMessageId,
160
175
  };
176
+ const run = draft.runs?.[0];
177
+ if (run?.status === "running") stageRewind(run, dispatch);
178
+ else startRun(draft, runId).dispatching = dispatch;
161
179
  break;
162
180
  }
163
181
  case "run/reload": {
164
182
  const { runAnchorMessageId } = command
165
183
  .params[0] as StatewireThread.RunReloadCommand;
166
- startRun(draft, runId).dispatching = {
184
+ const dispatch: Dispatch = {
167
185
  trigger: "message-reload",
168
186
  messages: [],
169
187
  rollbackTo: runAnchorMessageId,
170
188
  };
189
+ const run = draft.runs?.[0];
190
+ if (run?.status === "running") stageRewind(run, dispatch);
191
+ else startRun(draft, runId).dispatching = dispatch;
192
+ break;
193
+ }
194
+ case "run/stop": {
195
+ const run = draft.runs?.[0];
196
+ if (run?.status !== "running") break;
197
+ run.stopping = { reason: "stop" };
198
+ delete run.nextDispatch;
171
199
  break;
172
200
  }
173
201
  case "run/continue": {
@@ -195,7 +223,7 @@ export const runsOptimistic = (
195
223
  const target = requests.find((r) => r.id === requestId);
196
224
  if (target === undefined) break;
197
225
  target.response = response;
198
- if (requests.every((r) => r.response !== null)) startRun(draft, runId);
226
+ if (requests.every((r) => "response" in r)) startRun(draft, runId);
199
227
  break;
200
228
  }
201
229
  default: