@assistant-ui/react-statewire 0.6.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/StatewireThread.d.ts +19 -4
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +9 -5
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +2 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/runsOptimistic.d.ts.map +1 -1
- package/dist/runsOptimistic.js +19 -5
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.runs.test.tsx +117 -9
- package/src/StatewireThread.ts +46 -9
- package/src/runsOptimistic.test.ts +37 -6
- package/src/runsOptimistic.ts +31 -15
|
@@ -141,6 +141,21 @@ declare namespace StatewireThread {
|
|
|
141
141
|
/** Host-stamped opaque per-entry metadata. */
|
|
142
142
|
readonly meta?: ReadonlyJSONValue;
|
|
143
143
|
};
|
|
144
|
+
/** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
|
|
145
|
+
type RunsInputOutcome = {
|
|
146
|
+
readonly request: InputRequest;
|
|
147
|
+
readonly response: InputResponse | null;
|
|
148
|
+
readonly meta: ReadonlyJSONValue | null;
|
|
149
|
+
};
|
|
150
|
+
/** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
|
|
151
|
+
type RunsDispatch = {
|
|
152
|
+
readonly trigger: "message-send" | "message-edit" | "message-reload" | "input-resume" | "error-continue" | "stop-continue" | "steer";
|
|
153
|
+
readonly messages: readonly RunsQueueEntry[];
|
|
154
|
+
/** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
|
|
155
|
+
readonly rollbackTo?: string | null;
|
|
156
|
+
/** Present when input outcomes ride the dispatch; visible until the ack. */
|
|
157
|
+
readonly inputOutcomes?: readonly RunsInputOutcome[];
|
|
158
|
+
};
|
|
144
159
|
/** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
|
|
145
160
|
type RunsError = {
|
|
146
161
|
readonly message: string;
|
|
@@ -153,8 +168,8 @@ declare namespace StatewireThread {
|
|
|
153
168
|
readonly status: Exclude<RunStatus, "ready">;
|
|
154
169
|
readonly queue: readonly RunsQueueEntry[];
|
|
155
170
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
156
|
-
/** The
|
|
157
|
-
readonly dispatching:
|
|
171
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
172
|
+
readonly dispatching: RunsDispatch | null;
|
|
158
173
|
/** The parked pending set; present only in input-required. */
|
|
159
174
|
readonly inputRequests?: readonly InputRequestState[];
|
|
160
175
|
readonly error: RunsError | null;
|
|
@@ -174,8 +189,8 @@ declare namespace StatewireThread {
|
|
|
174
189
|
readonly runId: string | null;
|
|
175
190
|
readonly queue: readonly RunsQueueEntry[];
|
|
176
191
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
177
|
-
/** The
|
|
178
|
-
readonly dispatching:
|
|
192
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
193
|
+
readonly dispatching: RunsDispatch | null;
|
|
179
194
|
/** The parked pending set; present only in input-required. */
|
|
180
195
|
readonly inputRequests?: readonly InputRequestState[];
|
|
181
196
|
readonly error: RunsError | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAoXa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;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c;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;IAC1B;;;;;;IAMA;;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;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;;;YAOjB;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -14,7 +14,7 @@ const READY_RUNS = {
|
|
|
14
14
|
runId: null,
|
|
15
15
|
queue: [],
|
|
16
16
|
steerQueue: [],
|
|
17
|
-
dispatching:
|
|
17
|
+
dispatching: null,
|
|
18
18
|
error: null,
|
|
19
19
|
runLeafMessageId: null
|
|
20
20
|
};
|
|
@@ -122,10 +122,14 @@ const useStatewireThread = (options) => {
|
|
|
122
122
|
metadata
|
|
123
123
|
]);
|
|
124
124
|
const messages = useMemo(() => {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
125
|
+
const record = runs?.dispatching ?? null;
|
|
126
|
+
if (record === null) return converted.messages;
|
|
127
|
+
let base = converted.messages;
|
|
128
|
+
if ("rollbackTo" in record) base = record.rollbackTo == null ? [] : base.slice(0, base.findIndex((m) => m.id === record.rollbackTo) + 1);
|
|
129
|
+
const known = new Set(base.map((m_0) => m_0.id));
|
|
130
|
+
const pending_0 = record.messages.filter((e) => !known.has(e.id));
|
|
131
|
+
if (pending_0.length === 0) return base;
|
|
132
|
+
return [...base, ...pending_0.map(toDispatchingMessage)];
|
|
129
133
|
}, [converted.messages, runs]);
|
|
130
134
|
const queueItems = runs !== void 0 ? runs.queue : converted.queue;
|
|
131
135
|
const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toDispatchingMessage","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","runLeafMessageId","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","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","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","known","Set","map","m","id","e","has","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","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","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsError","RunState","Exclude","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Assistant","Commands","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/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\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 ExternalThreadQueueAdapter,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toDispatchingMessage,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: [],\n error: null,\n runLeafMessageId: 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 = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\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 const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\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 runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\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 runLeafMessageId: entry.runLeafMessageId,\n };\n }, [runsOption, 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 !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo renders as in-flight messages; ids already converted win.\n const messages = useMemo((): StatewireThread.State[\"messages\"] => {\n const known = new Set(converted.messages.map((m) => m.id));\n const pending = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));\n if (pending.length === 0) return converted.messages;\n return [...converted.messages, ...pending.map(toDispatchingMessage)];\n }, [converted.messages, runs]);\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\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 && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\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 const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\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 } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\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 ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\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 readonly sourceId: string;\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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\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 /** 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 — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */\n readonly dispatching: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | null;\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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */\n readonly dispatching: readonly RunsQueueEntry[];\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n readonly runLeafMessageId: string | 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; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 initialState: T;\n converter: StateConverter<T>;\n runs?: 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 /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<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 };\n}\n\ndeclare module \"@assistant-ui/react\" {\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":";;;;;;;;;;;AAkDA,MAAM8C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa,CAAA;CACbC,OAAO;CACPC,kBAAkB;AACpB;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrC,kBAAkBkC,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,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS7D,OAAO4D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAc/D,SAC5B,CAAA,CACF;CACA,MAAM,CAACiE,UAAUjE,gBACRkE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAMI,aAAaZ,QAAQa;CAC3B,MAAM,CAACC,YAAYzE,eAAeuE,eAAejB,KAAAA,CAAS;CAC1D,IAAImB,cAAcF,eAAejB,KAAAA,IAC/B,MAAM,IAAIoB,MACR,yDACGD,WAAW,QAAQ,WACpB,oCACJ;CAEF,MAAM,EACJE,OAAOC,gBACPC,UACAC,YAAAA,cACAC,eACE3D,aAAmC;EACrC4D,WAAWrB,QAAQqB;EACnB,GAAIP,YAAY,EACdQ,aAAaC,OAAOhB,WAASiB,QAAQ;GACnC,MAAMC,UAAUxB,OAAOC,QAAQW;GA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version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toDispatchingMessage","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","runLeafMessageId","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","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","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","record","base","rollbackTo","slice","findIndex","m","id","known","Set","map","e","has","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","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","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Assistant","Commands","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/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\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 ExternalThreadQueueAdapter,\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 { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toDispatchingMessage,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n runLeafMessageId: 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 = (options: AnyOptions): 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 runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\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 const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\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 runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\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 runLeafMessageId: entry.runLeafMessageId,\n };\n }, [runsOption, 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 !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo renders as in-flight messages; ids already converted win.\n // A rollbackTo key truncates to the rolled-back view first (null = root).\n const messages = useMemo((): StatewireThread.State[\"messages\"] => {\n const record = runs?.dispatching ?? null;\n if (record === null) return converted.messages;\n let base = converted.messages;\n if (\"rollbackTo\" in record) {\n base =\n record.rollbackTo == null\n ? []\n : base.slice(\n 0,\n base.findIndex((m) => m.id === record.rollbackTo) + 1,\n );\n }\n const known = new Set(base.map((m) => m.id));\n const pending = record.messages.filter((e) => !known.has(e.id));\n if (pending.length === 0) return base;\n return [...base, ...pending.map(toDispatchingMessage)];\n }, [converted.messages, runs]);\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\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 && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\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 const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\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 } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\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 ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\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 readonly sourceId: string;\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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\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 — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\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 readonly runLeafMessageId: string | null;\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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\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 readonly runLeafMessageId: string | 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; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\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 initialState: T;\n converter: StateConverter<T>;\n runs?: 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 /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<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 };\n}\n\ndeclare module \"@assistant-ui/react\" {\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":";;;;;;;;;;;AAkDA,MAAM8C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;CACPC,kBAAkB;AACpB;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrC,kBAAkBkC,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,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS7D,OAAO4D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAc/D,SAC5B,CAAA,CACF;CACA,MAAM,CAACiE,UAAUjE,gBACRkE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ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AAOoI,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIhH,MAAM,mDAAmD;GACrE,MAAM7B,QAAQ2B,SAASlB,KAAAA,IAAYkB,KAAK3B,QAAQwF,UAAUxF;GAC1D,MAAMR,OACJQ,UAAUS,KAAAA,IACNoI,YAAYpI,KAAAA,IACV,CAAA,IACA,CAACoI,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS7I;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACoE,OAAOxD,YAAiB;IAC1DW,OAAOC,QAAQ6C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA8D,UAAUlD,UAAUsG;CACpB,OAAOA;AACT;AAEA,MAAa5H,mBAORoB,YACH1D,SAASyD,kBAAkB,CAAC,CAACC,OAAO;AAwWtCrD,uBACEoD,oBACAtD,eAAekD,KAAAA,CAAkB,CAAC,CAACiN,IACrC"}
|
package/dist/host.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
2
|
import { ModelContext } from "@assistant-ui/core";
|
|
3
|
+
import { Statewire } from "statewire";
|
|
3
4
|
//#region src/host.d.ts
|
|
4
5
|
type SendOptions = {
|
|
5
6
|
schedule?: boolean;
|
|
@@ -32,7 +33,7 @@ type AssistantTransportHostCommands = {
|
|
|
32
33
|
resume(): void;
|
|
33
34
|
importState(state: unknown): void;
|
|
34
35
|
};
|
|
35
|
-
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands>, [options: HostOptions]>;
|
|
36
|
+
declare const AssistantTransportHost: import("@assistant-ui/tap").Resource<Statewire<AssistantTransportHostState, AssistantTransportHostCommands, any>, [options: HostOptions]>;
|
|
36
37
|
//#endregion
|
|
37
38
|
export { AssistantTransportHost, AssistantTransportHostCommands, AssistantTransportHostState, HostOptions, HostQueue, HostQueueCell, HostRunContext, SendOptions };
|
|
38
39
|
//# sourceMappingURL=host.d.ts.map
|
package/dist/host.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../src/host.ts"],"mappings":";;;;KAsBY;EACV;;KAGU;EACV,cAAc;EACd;;KAGU;EACV,QAAQ,yBAAyB;EACjC,WAAW,yBAAyB;;KAM1B;EAAkB,SAAS;;KAE3B,cAAc,yBAAyB;EACjD,qBAAqB;EACrB,WAAW;;KAGD;EACV;EACA;EACA;EACA;;KAGU;EACV,KAAK,SAAS,yBAAyB,SAAS,OAAO;EACvD,YAAY;EACZ;EACA;EACA,YAAY;;cA0XD,oDAAsB,SAAA,UAAA,6BAAA,uCAAA,SAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"runsOptimistic.d.ts","names":[],"sources":["../src/runsOptimistic.ts"],"mappings":";;;cAiIa,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
|
package/dist/runsOptimistic.js
CHANGED
|
@@ -5,7 +5,7 @@ const startRun = (draft, runId) => {
|
|
|
5
5
|
status: "running",
|
|
6
6
|
queue: [],
|
|
7
7
|
steerQueue: [],
|
|
8
|
-
dispatching:
|
|
8
|
+
dispatching: null,
|
|
9
9
|
error: null,
|
|
10
10
|
runLeafMessageId: null
|
|
11
11
|
};
|
|
@@ -22,7 +22,7 @@ const insert = (lane, entry, { insertAfter, insertBefore }) => {
|
|
|
22
22
|
const enqueueOrSteer = (draft, command, runId) => {
|
|
23
23
|
const run = draft.runs[0];
|
|
24
24
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
25
|
-
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
25
|
+
if (run?.dispatching?.messages.some((e) => e.id === id)) return;
|
|
26
26
|
const sourceLane = run === void 0 ? void 0 : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
|
|
27
27
|
let entry;
|
|
28
28
|
let sourceIndex = -1;
|
|
@@ -37,16 +37,30 @@ const enqueueOrSteer = (draft, command, runId) => {
|
|
|
37
37
|
if (!("message" in command)) return;
|
|
38
38
|
entry = { ...command.message };
|
|
39
39
|
}
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
const steer = command.type === "run/steer";
|
|
41
|
+
if (steer ? draft.status === "ready" || draft.status === "input-required" : sourceLane === void 0 && (draft.status === "ready" || (draft.status === "stopped" || draft.status === "error") && run !== void 0 && run.queue.length === 0 && run.steerQueue.length === 0)) {
|
|
42
42
|
startRun(draft, runId);
|
|
43
|
+
const target = draft.runs[0];
|
|
44
|
+
if (steer) {
|
|
45
|
+
if (sourceLane === target.steerQueue) target.steerQueue.splice(sourceIndex, 0, entry);
|
|
46
|
+
else target.steerQueue.push(entry);
|
|
47
|
+
target.dispatching = {
|
|
48
|
+
trigger: "message-send",
|
|
49
|
+
messages: target.steerQueue.splice(0)
|
|
50
|
+
};
|
|
51
|
+
} else target.dispatching = {
|
|
52
|
+
trigger: "message-send",
|
|
53
|
+
messages: [entry]
|
|
54
|
+
};
|
|
43
55
|
return;
|
|
44
56
|
}
|
|
57
|
+
const continues = steer && draft.status !== "running";
|
|
45
58
|
if (run === void 0) return;
|
|
46
|
-
const lane =
|
|
59
|
+
const lane = steer ? run.steerQueue : run.queue;
|
|
47
60
|
const hasPlacement = command.insertAfter !== void 0 || command.insertBefore !== void 0;
|
|
48
61
|
if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
|
|
49
62
|
else insert(lane, entry, command);
|
|
63
|
+
if (continues) startRun(draft, runId);
|
|
50
64
|
};
|
|
51
65
|
/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
|
|
52
66
|
const runsOptimistic = (mount, command, ctx) => {
|
|
@@ -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","inputRequests","response","error","runLeafMessageId","RunsDraft","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","type","hasPlacement","runsOptimistic","mount","Command","args","ctx","OptimisticContext","seq","method","params","RunDequeueCommand","requestId","RunInputCommand","requests","
|
|
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","runLeafMessageId","RunsDraft","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","hasPlacement","runsOptimistic","mount","Command","args","ctx","OptimisticContext","seq","method","params","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 runLeafMessageId: string | null;\n};\n\ntype RunsDraft = {\n status: StatewireThread.RunStatus;\n runs: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): void => {\n const entry = (draft.runs[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n runLeafMessageId: null,\n });\n entry.status = \"running\";\n entry.runId = runId;\n entry.error = null;\n delete entry.inputRequests;\n draft.status = \"running\";\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 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 ? draft.status === \"ready\" || draft.status === \"input-required\"\n : sourceLane === undefined &&\n (draft.status === \"ready\" ||\n ((draft.status === \"stopped\" || draft.status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n startRun(draft, runId);\n const target = draft.runs[0]!;\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 && draft.status !== \"running\";\n\n if (run === undefined) return;\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 runId = `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 case \"run/reload\": {\n startRun(draft, runId);\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 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":";AA+BA,MAAM4B,YAAYC,OAAkBhB,UAAwB;CAC1D,MAAMiB,QAASD,MAAMF,KAAK,OAAO;EAC/Bd,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;EACZC,aAAa;EACbM,OAAO;EACPC,kBAAkB;CACpB;CACAK,MAAMhB,SAAS;CACfgB,MAAMjB,QAAQA;CACdiB,MAAMN,QAAQ;CACd,OAAOM,MAAMR;CACbO,MAAMf,SAAS;AACjB;AAEA,MAAMiB,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAEnC,OAAO6B,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAEnC,OAAO8B,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA9B,UACS;CACT,MAAMiC,MAAMjB,MAAMF,KAAK;CACvB,MAAMvB,KAAK,aAAauC,UAAUA,QAAQI,QAAQ3C,KAAKuC,QAAQK;CAE/D,IAAIF,KAAK5B,aAAaE,SAAS6B,MAAMV,MAAMA,EAAEnC,OAAOA,EAAE,GAAG;CACzD,MAAM8C,aACJJ,QAAQT,KAAAA,IACJA,KAAAA,IACA,CAACS,IAAI9B,OAAO8B,IAAI7B,UAAU,CAAC,CAACkC,MAAMC,MAAMA,EAAEH,MAAMV,MAAMA,EAAEnC,OAAOA,EAAE,CAAC;CAExE,IAAI0B;CACJ,IAAIuB,cAAc;CAClB,IAAIH,eAAeb,KAAAA,GAAW;EAC5BgB,cA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
package/package.json
CHANGED
|
@@ -24,7 +24,11 @@ type ServerRunEntry = {
|
|
|
24
24
|
parts: { type: "text"; text: string }[];
|
|
25
25
|
}[];
|
|
26
26
|
steerQueue: ServerRunEntry["queue"];
|
|
27
|
-
dispatching:
|
|
27
|
+
dispatching: {
|
|
28
|
+
trigger: string;
|
|
29
|
+
messages: ServerRunEntry["queue"];
|
|
30
|
+
rollbackTo?: string | null;
|
|
31
|
+
} | null;
|
|
28
32
|
error: { message: string } | null;
|
|
29
33
|
runLeafMessageId: string | null;
|
|
30
34
|
inputRequests?: {
|
|
@@ -56,7 +60,7 @@ const withRun = (
|
|
|
56
60
|
runId: null,
|
|
57
61
|
queue: [],
|
|
58
62
|
steerQueue: [],
|
|
59
|
-
dispatching:
|
|
63
|
+
dispatching: null,
|
|
60
64
|
error: null,
|
|
61
65
|
runLeafMessageId: null,
|
|
62
66
|
...entry,
|
|
@@ -328,24 +332,27 @@ describe("StatewireThread runs mode", () => {
|
|
|
328
332
|
...withRun({
|
|
329
333
|
status: "running",
|
|
330
334
|
runId: "run-1",
|
|
331
|
-
dispatching:
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
+
dispatching: {
|
|
336
|
+
trigger: "message-send",
|
|
337
|
+
messages: [
|
|
338
|
+
{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
|
|
339
|
+
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
340
|
+
],
|
|
341
|
+
},
|
|
335
342
|
}),
|
|
336
343
|
});
|
|
337
344
|
const { aui, runs } = mountThread({ transport: server.transport });
|
|
338
345
|
|
|
339
|
-
await waitFor(() => expect(runs().dispatching).toHaveLength(2));
|
|
346
|
+
await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(2));
|
|
340
347
|
const messages = aui().thread().getState().messages;
|
|
341
348
|
expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
|
|
342
349
|
expect(messages[1]!.role).toBe("user");
|
|
343
350
|
|
|
344
351
|
act(() => {
|
|
345
352
|
server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
|
|
346
|
-
server.cell.state!.runs[0]!.dispatching =
|
|
353
|
+
server.cell.state!.runs[0]!.dispatching = null;
|
|
347
354
|
});
|
|
348
|
-
await waitFor(() => expect(runs().dispatching).
|
|
355
|
+
await waitFor(() => expect(runs().dispatching).toBeNull());
|
|
349
356
|
expect(
|
|
350
357
|
aui()
|
|
351
358
|
.thread()
|
|
@@ -354,6 +361,101 @@ describe("StatewireThread runs mode", () => {
|
|
|
354
361
|
).toEqual(["m1", "d1"]);
|
|
355
362
|
});
|
|
356
363
|
|
|
364
|
+
it("renders the edit replacement in branch position while it dispatches", async () => {
|
|
365
|
+
const server = createServer({
|
|
366
|
+
messages: [
|
|
367
|
+
{ id: "u1", role: "user", text: "one" },
|
|
368
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
369
|
+
{ id: "u2", role: "user", text: "two" },
|
|
370
|
+
{ id: "a2", role: "assistant", text: "re two" },
|
|
371
|
+
],
|
|
372
|
+
...withRun({
|
|
373
|
+
status: "running",
|
|
374
|
+
runId: "run-1",
|
|
375
|
+
dispatching: {
|
|
376
|
+
trigger: "message-edit",
|
|
377
|
+
messages: [
|
|
378
|
+
{
|
|
379
|
+
id: "u2b",
|
|
380
|
+
role: "user",
|
|
381
|
+
parts: [{ type: "text", text: "two'" }],
|
|
382
|
+
},
|
|
383
|
+
],
|
|
384
|
+
rollbackTo: "a1",
|
|
385
|
+
},
|
|
386
|
+
}),
|
|
387
|
+
});
|
|
388
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
389
|
+
|
|
390
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
391
|
+
expect(
|
|
392
|
+
aui()
|
|
393
|
+
.thread()
|
|
394
|
+
.getState()
|
|
395
|
+
.messages.map((m) => m.id),
|
|
396
|
+
).toEqual(["u1", "a1", "u2b"]);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
it("renders the rolled-back view for a reload dispatch", async () => {
|
|
400
|
+
const server = createServer({
|
|
401
|
+
messages: [
|
|
402
|
+
{ id: "u1", role: "user", text: "one" },
|
|
403
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
404
|
+
],
|
|
405
|
+
...withRun({
|
|
406
|
+
status: "running",
|
|
407
|
+
runId: "run-1",
|
|
408
|
+
dispatching: {
|
|
409
|
+
trigger: "message-reload",
|
|
410
|
+
messages: [],
|
|
411
|
+
rollbackTo: "u1",
|
|
412
|
+
},
|
|
413
|
+
}),
|
|
414
|
+
});
|
|
415
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
416
|
+
|
|
417
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
418
|
+
expect(
|
|
419
|
+
aui()
|
|
420
|
+
.thread()
|
|
421
|
+
.getState()
|
|
422
|
+
.messages.map((m) => m.id),
|
|
423
|
+
).toEqual(["u1"]);
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
it("renders only the record messages for a root rollback", async () => {
|
|
427
|
+
const server = createServer({
|
|
428
|
+
messages: [
|
|
429
|
+
{ id: "u1", role: "user", text: "one" },
|
|
430
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
431
|
+
],
|
|
432
|
+
...withRun({
|
|
433
|
+
status: "running",
|
|
434
|
+
runId: "run-1",
|
|
435
|
+
dispatching: {
|
|
436
|
+
trigger: "message-edit",
|
|
437
|
+
messages: [
|
|
438
|
+
{
|
|
439
|
+
id: "u1b",
|
|
440
|
+
role: "user",
|
|
441
|
+
parts: [{ type: "text", text: "one'" }],
|
|
442
|
+
},
|
|
443
|
+
],
|
|
444
|
+
rollbackTo: null,
|
|
445
|
+
},
|
|
446
|
+
}),
|
|
447
|
+
});
|
|
448
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
449
|
+
|
|
450
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
451
|
+
expect(
|
|
452
|
+
aui()
|
|
453
|
+
.thread()
|
|
454
|
+
.getState()
|
|
455
|
+
.messages.map((m) => m.id),
|
|
456
|
+
).toEqual(["u1b"]);
|
|
457
|
+
});
|
|
458
|
+
|
|
357
459
|
it("folds a pending steer into the lane while running", async () => {
|
|
358
460
|
const server = createRemoteServer(
|
|
359
461
|
withRun({ status: "running", runId: "run-1" }),
|
|
@@ -395,6 +497,12 @@ describe("StatewireThread runs mode", () => {
|
|
|
395
497
|
await waitFor(() => expect(runs().status).toBe("running"));
|
|
396
498
|
expect(runs().runId).toMatch(/^optimistic-/);
|
|
397
499
|
expect(runs().steerQueue).toEqual([]);
|
|
500
|
+
// The predicted dispatching entry renders like a canonical one.
|
|
501
|
+
expect(runs().dispatching!.messages).toHaveLength(1);
|
|
502
|
+
const messages = aui().thread().getState().messages;
|
|
503
|
+
expect(messages.map((m) => m.id)).toEqual([
|
|
504
|
+
runs().dispatching!.messages[0]!.id,
|
|
505
|
+
]);
|
|
398
506
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
399
507
|
});
|
|
400
508
|
|
package/src/StatewireThread.ts
CHANGED
|
@@ -53,7 +53,7 @@ const READY_RUNS: StatewireThread.Runs = {
|
|
|
53
53
|
runId: null,
|
|
54
54
|
queue: [],
|
|
55
55
|
steerQueue: [],
|
|
56
|
-
dispatching:
|
|
56
|
+
dispatching: null,
|
|
57
57
|
error: null,
|
|
58
58
|
runLeafMessageId: null,
|
|
59
59
|
};
|
|
@@ -225,11 +225,24 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
225
225
|
[converter, state, metadata],
|
|
226
226
|
);
|
|
227
227
|
// Dispatch limbo renders as in-flight messages; ids already converted win.
|
|
228
|
+
// A rollbackTo key truncates to the rolled-back view first (null = root).
|
|
228
229
|
const messages = useMemo((): StatewireThread.State["messages"] => {
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
230
|
+
const record = runs?.dispatching ?? null;
|
|
231
|
+
if (record === null) return converted.messages;
|
|
232
|
+
let base = converted.messages;
|
|
233
|
+
if ("rollbackTo" in record) {
|
|
234
|
+
base =
|
|
235
|
+
record.rollbackTo == null
|
|
236
|
+
? []
|
|
237
|
+
: base.slice(
|
|
238
|
+
0,
|
|
239
|
+
base.findIndex((m) => m.id === record.rollbackTo) + 1,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
const known = new Set(base.map((m) => m.id));
|
|
243
|
+
const pending = record.messages.filter((e) => !known.has(e.id));
|
|
244
|
+
if (pending.length === 0) return base;
|
|
245
|
+
return [...base, ...pending.map(toDispatchingMessage)];
|
|
233
246
|
}, [converted.messages, runs]);
|
|
234
247
|
const queueItems = runs !== undefined ? runs.queue : converted.queue;
|
|
235
248
|
const steerQueueItems =
|
|
@@ -544,6 +557,30 @@ export namespace StatewireThread {
|
|
|
544
557
|
readonly meta?: ReadonlyJSONValue;
|
|
545
558
|
};
|
|
546
559
|
|
|
560
|
+
/** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
|
|
561
|
+
export type RunsInputOutcome = {
|
|
562
|
+
readonly request: InputRequest;
|
|
563
|
+
readonly response: InputResponse | null;
|
|
564
|
+
readonly meta: ReadonlyJSONValue | null;
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
/** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
|
|
568
|
+
export type RunsDispatch = {
|
|
569
|
+
readonly trigger:
|
|
570
|
+
| "message-send"
|
|
571
|
+
| "message-edit"
|
|
572
|
+
| "message-reload"
|
|
573
|
+
| "input-resume"
|
|
574
|
+
| "error-continue"
|
|
575
|
+
| "stop-continue"
|
|
576
|
+
| "steer";
|
|
577
|
+
readonly messages: readonly RunsQueueEntry[];
|
|
578
|
+
/** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
|
|
579
|
+
readonly rollbackTo?: string | null;
|
|
580
|
+
/** Present when input outcomes ride the dispatch; visible until the ack. */
|
|
581
|
+
readonly inputOutcomes?: readonly RunsInputOutcome[];
|
|
582
|
+
};
|
|
583
|
+
|
|
547
584
|
/** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
|
|
548
585
|
export type RunsError = {
|
|
549
586
|
readonly message: string;
|
|
@@ -557,8 +594,8 @@ export namespace StatewireThread {
|
|
|
557
594
|
readonly status: Exclude<RunStatus, "ready">;
|
|
558
595
|
readonly queue: readonly RunsQueueEntry[];
|
|
559
596
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
560
|
-
/** The
|
|
561
|
-
readonly dispatching:
|
|
597
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
598
|
+
readonly dispatching: RunsDispatch | null;
|
|
562
599
|
/** The parked pending set; present only in input-required. */
|
|
563
600
|
readonly inputRequests?: readonly InputRequestState[];
|
|
564
601
|
readonly error: RunsError | null;
|
|
@@ -580,8 +617,8 @@ export namespace StatewireThread {
|
|
|
580
617
|
readonly runId: string | null;
|
|
581
618
|
readonly queue: readonly RunsQueueEntry[];
|
|
582
619
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
583
|
-
/** The
|
|
584
|
-
readonly dispatching:
|
|
620
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
621
|
+
readonly dispatching: RunsDispatch | null;
|
|
585
622
|
/** The parked pending set; present only in input-required. */
|
|
586
623
|
readonly inputRequests?: readonly InputRequestState[];
|
|
587
624
|
readonly error: RunsError | null;
|
|
@@ -18,7 +18,7 @@ const mount = (entry?: Draft): Draft =>
|
|
|
18
18
|
runId: null,
|
|
19
19
|
queue: [],
|
|
20
20
|
steerQueue: [],
|
|
21
|
-
dispatching:
|
|
21
|
+
dispatching: null,
|
|
22
22
|
error: null,
|
|
23
23
|
runLeafMessageId: null,
|
|
24
24
|
...entry,
|
|
@@ -55,7 +55,7 @@ describe("runsOptimistic", () => {
|
|
|
55
55
|
expect(run(draft).runId).toBe("run-1");
|
|
56
56
|
});
|
|
57
57
|
|
|
58
|
-
it("
|
|
58
|
+
it("parks a steer in the lane after a stop and predicts the continue run", () => {
|
|
59
59
|
const draft = mount({
|
|
60
60
|
status: "stopped",
|
|
61
61
|
steerQueue: [message("s1")],
|
|
@@ -69,10 +69,33 @@ describe("runsOptimistic", () => {
|
|
|
69
69
|
expect(draft.status).toBe("running");
|
|
70
70
|
expect(run(draft).status).toBe("running");
|
|
71
71
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
72
|
-
expect(run(draft).steerQueue).toEqual([]);
|
|
72
|
+
expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["s1", "s2"]);
|
|
73
|
+
expect(run(draft).dispatching).toBeNull();
|
|
73
74
|
expect(run(draft).error).toBeNull();
|
|
74
75
|
});
|
|
75
76
|
|
|
77
|
+
it("dispatches an idle steer: the whole lane rides dispatching, in lane order", () => {
|
|
78
|
+
const draft = mount({
|
|
79
|
+
status: "input-required",
|
|
80
|
+
runId: "run-1",
|
|
81
|
+
steerQueue: [message("s1")],
|
|
82
|
+
inputRequests: [{ type: "custom", id: "r1", response: null }],
|
|
83
|
+
});
|
|
84
|
+
apply(draft, "run/steer", {
|
|
85
|
+
type: "run/steer",
|
|
86
|
+
message: message("s2"),
|
|
87
|
+
anchorMessageId: null,
|
|
88
|
+
});
|
|
89
|
+
expect(draft.status).toBe("running");
|
|
90
|
+
expect(run(draft).runId).toBe("optimistic-7");
|
|
91
|
+
expect(run(draft).steerQueue).toEqual([]);
|
|
92
|
+
expect(run(draft).dispatching.trigger).toBe("message-send");
|
|
93
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
94
|
+
"s1",
|
|
95
|
+
"s2",
|
|
96
|
+
]);
|
|
97
|
+
});
|
|
98
|
+
|
|
76
99
|
it("dispatches an enqueue add only in ready or in error/stop with empty lanes", () => {
|
|
77
100
|
const ready = mount();
|
|
78
101
|
apply(ready, "run/enqueue", {
|
|
@@ -83,6 +106,9 @@ describe("runsOptimistic", () => {
|
|
|
83
106
|
expect(ready.status).toBe("running");
|
|
84
107
|
expect(run(ready).runId).toBe("optimistic-7");
|
|
85
108
|
expect(run(ready).queue).toEqual([]);
|
|
109
|
+
expect(run(ready).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
110
|
+
"a",
|
|
111
|
+
]);
|
|
86
112
|
|
|
87
113
|
const stopped = mount({ status: "stopped", queue: [message("q1")] });
|
|
88
114
|
apply(stopped, "run/enqueue", {
|
|
@@ -113,7 +139,7 @@ describe("runsOptimistic", () => {
|
|
|
113
139
|
const draft = mount({
|
|
114
140
|
status: "running",
|
|
115
141
|
runId: "r",
|
|
116
|
-
dispatching: [message("d1")],
|
|
142
|
+
dispatching: { trigger: "message-send", messages: [message("d1")] },
|
|
117
143
|
});
|
|
118
144
|
apply(draft, "run/enqueue", {
|
|
119
145
|
type: "run/enqueue",
|
|
@@ -123,7 +149,9 @@ describe("runsOptimistic", () => {
|
|
|
123
149
|
apply(draft, "run/steer", { type: "run/steer", messageId: "d1" });
|
|
124
150
|
expect(run(draft).queue).toEqual([]);
|
|
125
151
|
expect(run(draft).steerQueue).toEqual([]);
|
|
126
|
-
expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual([
|
|
152
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
153
|
+
"d1",
|
|
154
|
+
]);
|
|
127
155
|
});
|
|
128
156
|
|
|
129
157
|
it("applies moves, edits of queued items, and dequeue", () => {
|
|
@@ -183,7 +211,7 @@ describe("runsOptimistic", () => {
|
|
|
183
211
|
status: "running",
|
|
184
212
|
queue: [],
|
|
185
213
|
steerQueue: [],
|
|
186
|
-
dispatching: [],
|
|
214
|
+
dispatching: { trigger: "message-send", messages: [message("s1")] },
|
|
187
215
|
error: null,
|
|
188
216
|
runLeafMessageId: null,
|
|
189
217
|
});
|
|
@@ -233,6 +261,9 @@ describe("runsOptimistic", () => {
|
|
|
233
261
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
234
262
|
expect(run(draft).inputRequests).toBeUndefined();
|
|
235
263
|
expect(run(draft).steerQueue).toEqual([]);
|
|
264
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
265
|
+
"s1",
|
|
266
|
+
]);
|
|
236
267
|
});
|
|
237
268
|
|
|
238
269
|
it("leaves the draft untouched for run/stop and unknown moves", () => {
|
package/src/runsOptimistic.ts
CHANGED
|
@@ -14,7 +14,11 @@ type RunEntry = {
|
|
|
14
14
|
status: StatewireThread.RunStatus;
|
|
15
15
|
queue: LaneEntry[];
|
|
16
16
|
steerQueue: LaneEntry[];
|
|
17
|
-
dispatching:
|
|
17
|
+
dispatching: {
|
|
18
|
+
trigger: string;
|
|
19
|
+
messages: LaneEntry[];
|
|
20
|
+
rollbackTo?: string | null;
|
|
21
|
+
} | null;
|
|
18
22
|
inputRequests?: { id: string; response: unknown }[];
|
|
19
23
|
error: unknown;
|
|
20
24
|
runLeafMessageId: string | null;
|
|
@@ -31,7 +35,7 @@ const startRun = (draft: RunsDraft, runId: string): void => {
|
|
|
31
35
|
status: "running",
|
|
32
36
|
queue: [],
|
|
33
37
|
steerQueue: [],
|
|
34
|
-
dispatching:
|
|
38
|
+
dispatching: null,
|
|
35
39
|
error: null,
|
|
36
40
|
runLeafMessageId: null,
|
|
37
41
|
});
|
|
@@ -66,7 +70,7 @@ const enqueueOrSteer = (
|
|
|
66
70
|
const run = draft.runs[0];
|
|
67
71
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
68
72
|
// In dispatch limbo the canonical state already tells the story: no fold.
|
|
69
|
-
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
73
|
+
if (run?.dispatching?.messages.some((e) => e.id === id)) return;
|
|
70
74
|
const sourceLane =
|
|
71
75
|
run === undefined
|
|
72
76
|
? undefined
|
|
@@ -87,27 +91,39 @@ const enqueueOrSteer = (
|
|
|
87
91
|
entry = { ...command.message };
|
|
88
92
|
}
|
|
89
93
|
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
if (
|
|
100
|
-
if (command.type === "run/steer" && run !== undefined) run.steerQueue = [];
|
|
94
|
+
const steer = command.type === "run/steer";
|
|
95
|
+
const direct = steer
|
|
96
|
+
? draft.status === "ready" || draft.status === "input-required"
|
|
97
|
+
: sourceLane === undefined &&
|
|
98
|
+
(draft.status === "ready" ||
|
|
99
|
+
((draft.status === "stopped" || draft.status === "error") &&
|
|
100
|
+
run !== undefined &&
|
|
101
|
+
run.queue.length === 0 &&
|
|
102
|
+
run.steerQueue.length === 0));
|
|
103
|
+
if (direct) {
|
|
101
104
|
startRun(draft, runId);
|
|
105
|
+
const target = draft.runs[0]!;
|
|
106
|
+
if (steer) {
|
|
107
|
+
// The whole steer lane rides the dispatch, in lane order.
|
|
108
|
+
if (sourceLane === target.steerQueue)
|
|
109
|
+
target.steerQueue.splice(sourceIndex, 0, entry);
|
|
110
|
+
else target.steerQueue.push(entry);
|
|
111
|
+
target.dispatching = {
|
|
112
|
+
trigger: "message-send",
|
|
113
|
+
messages: target.steerQueue.splice(0),
|
|
114
|
+
};
|
|
115
|
+
} else target.dispatching = { trigger: "message-send", messages: [entry] };
|
|
102
116
|
return;
|
|
103
117
|
}
|
|
118
|
+
const continues = steer && draft.status !== "running";
|
|
104
119
|
|
|
105
120
|
if (run === undefined) return;
|
|
106
|
-
const lane =
|
|
121
|
+
const lane = steer ? run.steerQueue : run.queue;
|
|
107
122
|
const hasPlacement =
|
|
108
123
|
command.insertAfter !== undefined || command.insertBefore !== undefined;
|
|
109
124
|
if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
|
|
110
125
|
else insert(lane, entry, command);
|
|
126
|
+
if (continues) startRun(draft, runId);
|
|
111
127
|
};
|
|
112
128
|
|
|
113
129
|
/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
|