@assistant-ui/react-statewire 0.6.3 → 0.8.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 -6
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +11 -9
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runsOptimistic.d.ts.map +1 -1
- package/dist/runsOptimistic.js +11 -6
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.runs.test.tsx +115 -15
- package/src/StatewireThread.ts +46 -13
- package/src/runsOptimistic.test.ts +15 -10
- package/src/runsOptimistic.ts +12 -7
|
@@ -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,12 +168,11 @@ 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;
|
|
161
|
-
readonly runLeafMessageId: string | null;
|
|
162
176
|
};
|
|
163
177
|
/** The runs mount as replicated: the run entries plus the top-level status projection. */
|
|
164
178
|
type RunsState = {
|
|
@@ -174,12 +188,11 @@ declare namespace StatewireThread {
|
|
|
174
188
|
readonly runId: string | null;
|
|
175
189
|
readonly queue: readonly RunsQueueEntry[];
|
|
176
190
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
177
|
-
/** The
|
|
178
|
-
readonly dispatching:
|
|
191
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
192
|
+
readonly dispatching: RunsDispatch | null;
|
|
179
193
|
/** The parked pending set; present only in input-required. */
|
|
180
194
|
readonly inputRequests?: readonly InputRequestState[];
|
|
181
195
|
readonly error: RunsError | null;
|
|
182
|
-
readonly runLeafMessageId: string | null;
|
|
183
196
|
};
|
|
184
197
|
type ConnectionMetadata = {
|
|
185
198
|
pendingCommands: Command[];
|
|
@@ -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":";;;;;;;cAkXa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAA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,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;OAGO;aACD,mBAAmB;aACnB,QAAQ;;OAGP,mBAAmB,MAC7B,OAAO,GACP,oBAAoB;IAAuB,MAAM;QAC9C;;;;;OAMO;aACD;cACC,cAAc;;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,9 +14,8 @@ const READY_RUNS = {
|
|
|
14
14
|
runId: null,
|
|
15
15
|
queue: [],
|
|
16
16
|
steerQueue: [],
|
|
17
|
-
dispatching:
|
|
18
|
-
error: null
|
|
19
|
-
runLeafMessageId: null
|
|
17
|
+
dispatching: null,
|
|
18
|
+
error: null
|
|
20
19
|
};
|
|
21
20
|
const ambientContextOf = (context) => ({
|
|
22
21
|
...context.system !== void 0 && { system: context.system },
|
|
@@ -101,8 +100,7 @@ const useStatewireThread = (options) => {
|
|
|
101
100
|
steerQueue: entry.steerQueue,
|
|
102
101
|
dispatching: entry.dispatching,
|
|
103
102
|
...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
|
|
104
|
-
error: entry.error
|
|
105
|
-
runLeafMessageId: entry.runLeafMessageId
|
|
103
|
+
error: entry.error
|
|
106
104
|
};
|
|
107
105
|
}, [runsOption, state_0]);
|
|
108
106
|
const { converter } = options;
|
|
@@ -122,10 +120,14 @@ const useStatewireThread = (options) => {
|
|
|
122
120
|
metadata
|
|
123
121
|
]);
|
|
124
122
|
const messages = useMemo(() => {
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
123
|
+
const record = runs?.dispatching ?? null;
|
|
124
|
+
if (record === null) return converted.messages;
|
|
125
|
+
let base = converted.messages;
|
|
126
|
+
if ("rollbackTo" in record) base = record.rollbackTo == null ? [] : base.slice(0, base.findIndex((m) => m.id === record.rollbackTo) + 1);
|
|
127
|
+
const known = new Set(base.map((m_0) => m_0.id));
|
|
128
|
+
const pending_0 = record.messages.filter((e) => !known.has(e.id));
|
|
129
|
+
if (pending_0.length === 0) return base;
|
|
130
|
+
return [...base, ...pending_0.map(toDispatchingMessage)];
|
|
129
131
|
}, [converted.messages, runs]);
|
|
130
132
|
const queueItems = runs !== void 0 ? runs.queue : converted.queue;
|
|
131
133
|
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,C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mDAAmD;GACrE,MAAM7B,QAAQ2B,SAASlB,KAAAA,IAAYkB,KAAK3B,QAAQwF,UAAUxF;GAC1D,MAAMR,OACJQ,UAAUS,KAAAA,IACN+H,YAAY/H,KAAAA,IACV,CAAA,IACA,CAAC+H,OAAO,IACV,CAAC;IAAE,GAAGA;IAASxI;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,UAAUiG;CACpB,OAAOA;AACT;AAEA,MAAavH,mBAORoB,YACH1D,SAASyD,kBAAkB,CAAC,CAACC,OAAO;AAgVtCrD,uBACEoD,oBACAtD,eAAekD,KAAAA,CAAkB,CAAC,CAACuM,IACrC"}
|
|
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","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};\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 };\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 };\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 };\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;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOpC,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mH,cAAcG,YAAY,EACpCC,gBAAgBtE,SAAS,EAAEE,MAAM,eAAe,CAAC,EACnD;EACA,GAAInD,QAAQmH,cAAcK,UAAU,EAAEC,UAAUpB,aAAa;EAC7D,GAAIlC,kBAAkBxE,KAAAA,KAAa;GACjC+H,kBAAkBC,gBAChB1E,SAAS1E,uBAAuB4F,eAAewD,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB5E,SAAS3E,yBAAyB6F,eAAe0D,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAU9H,OAAOC,QAAQ8H,cAAc;GAC7C,IACED,YAAYpI,KAAAA,MACX,OAAOoI,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIhH,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQuF,UAAUvF;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACNoI,YAAYpI,KAAAA,IACV,CAAA,IACA,CAACoI,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS5I;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACmE,OAAOvD,YAAiB;IAC1DU,OAAOC,QAAQ6C,UAAUxD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA6D,UAAUlD,UAAUsG;CACpB,OAAOA;AACT;AAEA,MAAa3H,mBAORmB,YACHzD,SAASwD,kBAAkB,CAAC,CAACC,OAAO;AAsWtCpD,uBACEmD,oBACArD,eAAeiD,KAAAA,CAAkB,CAAC,CAACiN,IACrC"}
|
|
@@ -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":";;;cA+Ha,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
|
package/dist/runsOptimistic.js
CHANGED
|
@@ -5,9 +5,8 @@ const startRun = (draft, runId) => {
|
|
|
5
5
|
status: "running",
|
|
6
6
|
queue: [],
|
|
7
7
|
steerQueue: [],
|
|
8
|
-
dispatching:
|
|
9
|
-
error: null
|
|
10
|
-
runLeafMessageId: null
|
|
8
|
+
dispatching: null,
|
|
9
|
+
error: null
|
|
11
10
|
};
|
|
12
11
|
entry.status = "running";
|
|
13
12
|
entry.runId = runId;
|
|
@@ -22,7 +21,7 @@ const insert = (lane, entry, { insertAfter, insertBefore }) => {
|
|
|
22
21
|
const enqueueOrSteer = (draft, command, runId) => {
|
|
23
22
|
const run = draft.runs[0];
|
|
24
23
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
25
|
-
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
24
|
+
if (run?.dispatching?.messages.some((e) => e.id === id)) return;
|
|
26
25
|
const sourceLane = run === void 0 ? void 0 : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
|
|
27
26
|
let entry;
|
|
28
27
|
let sourceIndex = -1;
|
|
@@ -44,8 +43,14 @@ const enqueueOrSteer = (draft, command, runId) => {
|
|
|
44
43
|
if (steer) {
|
|
45
44
|
if (sourceLane === target.steerQueue) target.steerQueue.splice(sourceIndex, 0, entry);
|
|
46
45
|
else target.steerQueue.push(entry);
|
|
47
|
-
target.dispatching
|
|
48
|
-
|
|
46
|
+
target.dispatching = {
|
|
47
|
+
trigger: "message-send",
|
|
48
|
+
messages: target.steerQueue.splice(0)
|
|
49
|
+
};
|
|
50
|
+
} else target.dispatching = {
|
|
51
|
+
trigger: "message-send",
|
|
52
|
+
messages: [entry]
|
|
53
|
+
};
|
|
49
54
|
return;
|
|
50
55
|
}
|
|
51
56
|
const continues = steer && draft.status !== "running";
|
|
@@ -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","
|
|
1
|
+
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","trigger","messages","rollbackTo","inputRequests","response","error","RunsDraft","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};\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 });\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":";AA8BA,MAAM2B,YAAYC,OAAkBf,UAAwB;CAC1D,MAAMgB,QAASD,MAAMF,KAAK,OAAO;EAC/Bb,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;EACZC,aAAa;EACbM,OAAO;CACT;CACAK,MAAMf,SAAS;CACfe,MAAMhB,QAAQA;CACdgB,MAAML,QAAQ;CACd,OAAOK,MAAMP;CACbM,MAAMd,SAAS;AACjB;AAEA,MAAMg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jB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAWS,IAAI5B,aAAa,CAAA;GACxCU,SAASC,OAAOf,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAEkC,cAAcL,QACnB0B,OAAO;GACV,MAAMvB,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI7B,OAAO6B,IAAI5B,UAAU,GAAG;IAC9C,MAAMkB,QAAQJ,KAAKM,WAAWC,MAAMA,EAAElC,OAAO2C,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAEmC,WAAW/C,aAAamB,QAC7B0B,OAAO;GACV,MAAMI,WAAW5C,MAAMF,KAAK,EAAE,EAAEJ;GAChC,MAAMkC,SAASgB,UAAUtB,MAAMuB,MAAMA,EAAErE,OAAOkE,SAAS;GACvD,IAAId,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOjC,WAAWA;GAClB,IAAIiD,SAAUE,OAAOD,MAAMA,EAAElD,aAAa,IAAI,GAAGI,SAASC,OAAOf,KAAK;GACtE;EACF;CAGF;AACF"}
|
package/package.json
CHANGED
|
@@ -24,9 +24,12 @@ 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
|
-
runLeafMessageId: string | null;
|
|
30
33
|
inputRequests?: {
|
|
31
34
|
type: string;
|
|
32
35
|
id: string;
|
|
@@ -56,9 +59,8 @@ const withRun = (
|
|
|
56
59
|
runId: null,
|
|
57
60
|
queue: [],
|
|
58
61
|
steerQueue: [],
|
|
59
|
-
dispatching:
|
|
62
|
+
dispatching: null,
|
|
60
63
|
error: null,
|
|
61
|
-
runLeafMessageId: null,
|
|
62
64
|
...entry,
|
|
63
65
|
},
|
|
64
66
|
],
|
|
@@ -200,7 +202,6 @@ describe("StatewireThread runs mode", () => {
|
|
|
200
202
|
steerQueue: [
|
|
201
203
|
{ id: "s1", role: "user", parts: [{ type: "text", text: "now" }] },
|
|
202
204
|
],
|
|
203
|
-
runLeafMessageId: "m1",
|
|
204
205
|
}),
|
|
205
206
|
});
|
|
206
207
|
const { aui, runs } = mountThread({ transport: server.transport });
|
|
@@ -209,7 +210,6 @@ describe("StatewireThread runs mode", () => {
|
|
|
209
210
|
expect(runs().runId).toBe("run-1");
|
|
210
211
|
expect(runs().queue.map((e) => e.id)).toEqual(["q1"]);
|
|
211
212
|
expect(runs().steerQueue.map((e) => e.id)).toEqual(["s1"]);
|
|
212
|
-
expect(runs().runLeafMessageId).toBe("m1");
|
|
213
213
|
expect(runs().error).toBeNull();
|
|
214
214
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
215
215
|
|
|
@@ -328,24 +328,27 @@ describe("StatewireThread runs mode", () => {
|
|
|
328
328
|
...withRun({
|
|
329
329
|
status: "running",
|
|
330
330
|
runId: "run-1",
|
|
331
|
-
dispatching:
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
331
|
+
dispatching: {
|
|
332
|
+
trigger: "message-send",
|
|
333
|
+
messages: [
|
|
334
|
+
{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
|
|
335
|
+
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
336
|
+
],
|
|
337
|
+
},
|
|
335
338
|
}),
|
|
336
339
|
});
|
|
337
340
|
const { aui, runs } = mountThread({ transport: server.transport });
|
|
338
341
|
|
|
339
|
-
await waitFor(() => expect(runs().dispatching).toHaveLength(2));
|
|
342
|
+
await waitFor(() => expect(runs().dispatching?.messages).toHaveLength(2));
|
|
340
343
|
const messages = aui().thread().getState().messages;
|
|
341
344
|
expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
|
|
342
345
|
expect(messages[1]!.role).toBe("user");
|
|
343
346
|
|
|
344
347
|
act(() => {
|
|
345
348
|
server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
|
|
346
|
-
server.cell.state!.runs[0]!.dispatching =
|
|
349
|
+
server.cell.state!.runs[0]!.dispatching = null;
|
|
347
350
|
});
|
|
348
|
-
await waitFor(() => expect(runs().dispatching).
|
|
351
|
+
await waitFor(() => expect(runs().dispatching).toBeNull());
|
|
349
352
|
expect(
|
|
350
353
|
aui()
|
|
351
354
|
.thread()
|
|
@@ -354,6 +357,101 @@ describe("StatewireThread runs mode", () => {
|
|
|
354
357
|
).toEqual(["m1", "d1"]);
|
|
355
358
|
});
|
|
356
359
|
|
|
360
|
+
it("renders the edit replacement in branch position while it dispatches", async () => {
|
|
361
|
+
const server = createServer({
|
|
362
|
+
messages: [
|
|
363
|
+
{ id: "u1", role: "user", text: "one" },
|
|
364
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
365
|
+
{ id: "u2", role: "user", text: "two" },
|
|
366
|
+
{ id: "a2", role: "assistant", text: "re two" },
|
|
367
|
+
],
|
|
368
|
+
...withRun({
|
|
369
|
+
status: "running",
|
|
370
|
+
runId: "run-1",
|
|
371
|
+
dispatching: {
|
|
372
|
+
trigger: "message-edit",
|
|
373
|
+
messages: [
|
|
374
|
+
{
|
|
375
|
+
id: "u2b",
|
|
376
|
+
role: "user",
|
|
377
|
+
parts: [{ type: "text", text: "two'" }],
|
|
378
|
+
},
|
|
379
|
+
],
|
|
380
|
+
rollbackTo: "a1",
|
|
381
|
+
},
|
|
382
|
+
}),
|
|
383
|
+
});
|
|
384
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
385
|
+
|
|
386
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
387
|
+
expect(
|
|
388
|
+
aui()
|
|
389
|
+
.thread()
|
|
390
|
+
.getState()
|
|
391
|
+
.messages.map((m) => m.id),
|
|
392
|
+
).toEqual(["u1", "a1", "u2b"]);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("renders the rolled-back view for a reload dispatch", async () => {
|
|
396
|
+
const server = createServer({
|
|
397
|
+
messages: [
|
|
398
|
+
{ id: "u1", role: "user", text: "one" },
|
|
399
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
400
|
+
],
|
|
401
|
+
...withRun({
|
|
402
|
+
status: "running",
|
|
403
|
+
runId: "run-1",
|
|
404
|
+
dispatching: {
|
|
405
|
+
trigger: "message-reload",
|
|
406
|
+
messages: [],
|
|
407
|
+
rollbackTo: "u1",
|
|
408
|
+
},
|
|
409
|
+
}),
|
|
410
|
+
});
|
|
411
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
412
|
+
|
|
413
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
414
|
+
expect(
|
|
415
|
+
aui()
|
|
416
|
+
.thread()
|
|
417
|
+
.getState()
|
|
418
|
+
.messages.map((m) => m.id),
|
|
419
|
+
).toEqual(["u1"]);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it("renders only the record messages for a root rollback", async () => {
|
|
423
|
+
const server = createServer({
|
|
424
|
+
messages: [
|
|
425
|
+
{ id: "u1", role: "user", text: "one" },
|
|
426
|
+
{ id: "a1", role: "assistant", text: "re one" },
|
|
427
|
+
],
|
|
428
|
+
...withRun({
|
|
429
|
+
status: "running",
|
|
430
|
+
runId: "run-1",
|
|
431
|
+
dispatching: {
|
|
432
|
+
trigger: "message-edit",
|
|
433
|
+
messages: [
|
|
434
|
+
{
|
|
435
|
+
id: "u1b",
|
|
436
|
+
role: "user",
|
|
437
|
+
parts: [{ type: "text", text: "one'" }],
|
|
438
|
+
},
|
|
439
|
+
],
|
|
440
|
+
rollbackTo: null,
|
|
441
|
+
},
|
|
442
|
+
}),
|
|
443
|
+
});
|
|
444
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
445
|
+
|
|
446
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
447
|
+
expect(
|
|
448
|
+
aui()
|
|
449
|
+
.thread()
|
|
450
|
+
.getState()
|
|
451
|
+
.messages.map((m) => m.id),
|
|
452
|
+
).toEqual(["u1b"]);
|
|
453
|
+
});
|
|
454
|
+
|
|
357
455
|
it("folds a pending steer into the lane while running", async () => {
|
|
358
456
|
const server = createRemoteServer(
|
|
359
457
|
withRun({ status: "running", runId: "run-1" }),
|
|
@@ -396,9 +494,11 @@ describe("StatewireThread runs mode", () => {
|
|
|
396
494
|
expect(runs().runId).toMatch(/^optimistic-/);
|
|
397
495
|
expect(runs().steerQueue).toEqual([]);
|
|
398
496
|
// The predicted dispatching entry renders like a canonical one.
|
|
399
|
-
expect(runs().dispatching).toHaveLength(1);
|
|
497
|
+
expect(runs().dispatching!.messages).toHaveLength(1);
|
|
400
498
|
const messages = aui().thread().getState().messages;
|
|
401
|
-
expect(messages.map((m) => m.id)).toEqual([
|
|
499
|
+
expect(messages.map((m) => m.id)).toEqual([
|
|
500
|
+
runs().dispatching!.messages[0]!.id,
|
|
501
|
+
]);
|
|
402
502
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
403
503
|
});
|
|
404
504
|
|
package/src/StatewireThread.ts
CHANGED
|
@@ -53,9 +53,8 @@ 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
|
-
runLeafMessageId: null,
|
|
59
58
|
};
|
|
60
59
|
|
|
61
60
|
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
@@ -200,7 +199,6 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
200
199
|
inputRequests: entry.inputRequests,
|
|
201
200
|
}),
|
|
202
201
|
error: entry.error,
|
|
203
|
-
runLeafMessageId: entry.runLeafMessageId,
|
|
204
202
|
};
|
|
205
203
|
}, [runsOption, state]);
|
|
206
204
|
|
|
@@ -225,11 +223,24 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
225
223
|
[converter, state, metadata],
|
|
226
224
|
);
|
|
227
225
|
// Dispatch limbo renders as in-flight messages; ids already converted win.
|
|
226
|
+
// A rollbackTo key truncates to the rolled-back view first (null = root).
|
|
228
227
|
const messages = useMemo((): StatewireThread.State["messages"] => {
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
228
|
+
const record = runs?.dispatching ?? null;
|
|
229
|
+
if (record === null) return converted.messages;
|
|
230
|
+
let base = converted.messages;
|
|
231
|
+
if ("rollbackTo" in record) {
|
|
232
|
+
base =
|
|
233
|
+
record.rollbackTo == null
|
|
234
|
+
? []
|
|
235
|
+
: base.slice(
|
|
236
|
+
0,
|
|
237
|
+
base.findIndex((m) => m.id === record.rollbackTo) + 1,
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
const known = new Set(base.map((m) => m.id));
|
|
241
|
+
const pending = record.messages.filter((e) => !known.has(e.id));
|
|
242
|
+
if (pending.length === 0) return base;
|
|
243
|
+
return [...base, ...pending.map(toDispatchingMessage)];
|
|
233
244
|
}, [converted.messages, runs]);
|
|
234
245
|
const queueItems = runs !== undefined ? runs.queue : converted.queue;
|
|
235
246
|
const steerQueueItems =
|
|
@@ -544,6 +555,30 @@ export namespace StatewireThread {
|
|
|
544
555
|
readonly meta?: ReadonlyJSONValue;
|
|
545
556
|
};
|
|
546
557
|
|
|
558
|
+
/** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
|
|
559
|
+
export type RunsInputOutcome = {
|
|
560
|
+
readonly request: InputRequest;
|
|
561
|
+
readonly response: InputResponse | null;
|
|
562
|
+
readonly meta: ReadonlyJSONValue | null;
|
|
563
|
+
};
|
|
564
|
+
|
|
565
|
+
/** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */
|
|
566
|
+
export type RunsDispatch = {
|
|
567
|
+
readonly trigger:
|
|
568
|
+
| "message-send"
|
|
569
|
+
| "message-edit"
|
|
570
|
+
| "message-reload"
|
|
571
|
+
| "input-resume"
|
|
572
|
+
| "error-continue"
|
|
573
|
+
| "stop-continue"
|
|
574
|
+
| "steer";
|
|
575
|
+
readonly messages: readonly RunsQueueEntry[];
|
|
576
|
+
/** Present on rewind dispatches: truncate the thread at this id first; null names the root. */
|
|
577
|
+
readonly rollbackTo?: string | null;
|
|
578
|
+
/** Present when input outcomes ride the dispatch; visible until the ack. */
|
|
579
|
+
readonly inputOutcomes?: readonly RunsInputOutcome[];
|
|
580
|
+
};
|
|
581
|
+
|
|
547
582
|
/** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
|
|
548
583
|
export type RunsError = {
|
|
549
584
|
readonly message: string;
|
|
@@ -557,12 +592,11 @@ export namespace StatewireThread {
|
|
|
557
592
|
readonly status: Exclude<RunStatus, "ready">;
|
|
558
593
|
readonly queue: readonly RunsQueueEntry[];
|
|
559
594
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
560
|
-
/** The
|
|
561
|
-
readonly dispatching:
|
|
595
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
596
|
+
readonly dispatching: RunsDispatch | null;
|
|
562
597
|
/** The parked pending set; present only in input-required. */
|
|
563
598
|
readonly inputRequests?: readonly InputRequestState[];
|
|
564
599
|
readonly error: RunsError | null;
|
|
565
|
-
readonly runLeafMessageId: string | null;
|
|
566
600
|
};
|
|
567
601
|
|
|
568
602
|
/** The runs mount as replicated: the run entries plus the top-level status projection. */
|
|
@@ -580,12 +614,11 @@ export namespace StatewireThread {
|
|
|
580
614
|
readonly runId: string | null;
|
|
581
615
|
readonly queue: readonly RunsQueueEntry[];
|
|
582
616
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
583
|
-
/** The
|
|
584
|
-
readonly dispatching:
|
|
617
|
+
/** The dispatch record — the unacked batch handed to the run, cleared at the ack. */
|
|
618
|
+
readonly dispatching: RunsDispatch | null;
|
|
585
619
|
/** The parked pending set; present only in input-required. */
|
|
586
620
|
readonly inputRequests?: readonly InputRequestState[];
|
|
587
621
|
readonly error: RunsError | null;
|
|
588
|
-
readonly runLeafMessageId: string | null;
|
|
589
622
|
};
|
|
590
623
|
|
|
591
624
|
export type ConnectionMetadata = {
|
|
@@ -18,9 +18,8 @@ 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
|
-
runLeafMessageId: null,
|
|
24
23
|
...entry,
|
|
25
24
|
},
|
|
26
25
|
],
|
|
@@ -70,7 +69,7 @@ describe("runsOptimistic", () => {
|
|
|
70
69
|
expect(run(draft).status).toBe("running");
|
|
71
70
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
72
71
|
expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["s1", "s2"]);
|
|
73
|
-
expect(run(draft).dispatching).
|
|
72
|
+
expect(run(draft).dispatching).toBeNull();
|
|
74
73
|
expect(run(draft).error).toBeNull();
|
|
75
74
|
});
|
|
76
75
|
|
|
@@ -89,7 +88,8 @@ describe("runsOptimistic", () => {
|
|
|
89
88
|
expect(draft.status).toBe("running");
|
|
90
89
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
91
90
|
expect(run(draft).steerQueue).toEqual([]);
|
|
92
|
-
expect(run(draft).dispatching.
|
|
91
|
+
expect(run(draft).dispatching.trigger).toBe("message-send");
|
|
92
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
93
93
|
"s1",
|
|
94
94
|
"s2",
|
|
95
95
|
]);
|
|
@@ -105,7 +105,9 @@ describe("runsOptimistic", () => {
|
|
|
105
105
|
expect(ready.status).toBe("running");
|
|
106
106
|
expect(run(ready).runId).toBe("optimistic-7");
|
|
107
107
|
expect(run(ready).queue).toEqual([]);
|
|
108
|
-
expect(run(ready).dispatching.map((e: Draft) => e.id)).toEqual([
|
|
108
|
+
expect(run(ready).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
109
|
+
"a",
|
|
110
|
+
]);
|
|
109
111
|
|
|
110
112
|
const stopped = mount({ status: "stopped", queue: [message("q1")] });
|
|
111
113
|
apply(stopped, "run/enqueue", {
|
|
@@ -136,7 +138,7 @@ describe("runsOptimistic", () => {
|
|
|
136
138
|
const draft = mount({
|
|
137
139
|
status: "running",
|
|
138
140
|
runId: "r",
|
|
139
|
-
dispatching: [message("d1")],
|
|
141
|
+
dispatching: { trigger: "message-send", messages: [message("d1")] },
|
|
140
142
|
});
|
|
141
143
|
apply(draft, "run/enqueue", {
|
|
142
144
|
type: "run/enqueue",
|
|
@@ -146,7 +148,9 @@ describe("runsOptimistic", () => {
|
|
|
146
148
|
apply(draft, "run/steer", { type: "run/steer", messageId: "d1" });
|
|
147
149
|
expect(run(draft).queue).toEqual([]);
|
|
148
150
|
expect(run(draft).steerQueue).toEqual([]);
|
|
149
|
-
expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual([
|
|
151
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
152
|
+
"d1",
|
|
153
|
+
]);
|
|
150
154
|
});
|
|
151
155
|
|
|
152
156
|
it("applies moves, edits of queued items, and dequeue", () => {
|
|
@@ -206,9 +210,8 @@ describe("runsOptimistic", () => {
|
|
|
206
210
|
status: "running",
|
|
207
211
|
queue: [],
|
|
208
212
|
steerQueue: [],
|
|
209
|
-
dispatching: [message("s1")],
|
|
213
|
+
dispatching: { trigger: "message-send", messages: [message("s1")] },
|
|
210
214
|
error: null,
|
|
211
|
-
runLeafMessageId: null,
|
|
212
215
|
});
|
|
213
216
|
});
|
|
214
217
|
|
|
@@ -256,7 +259,9 @@ describe("runsOptimistic", () => {
|
|
|
256
259
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
257
260
|
expect(run(draft).inputRequests).toBeUndefined();
|
|
258
261
|
expect(run(draft).steerQueue).toEqual([]);
|
|
259
|
-
expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual([
|
|
262
|
+
expect(run(draft).dispatching.messages.map((e: Draft) => e.id)).toEqual([
|
|
263
|
+
"s1",
|
|
264
|
+
]);
|
|
260
265
|
});
|
|
261
266
|
|
|
262
267
|
it("leaves the draft untouched for run/stop and unknown moves", () => {
|
package/src/runsOptimistic.ts
CHANGED
|
@@ -14,10 +14,13 @@ 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
|
-
runLeafMessageId: string | null;
|
|
21
24
|
};
|
|
22
25
|
|
|
23
26
|
type RunsDraft = {
|
|
@@ -31,9 +34,8 @@ const startRun = (draft: RunsDraft, runId: string): void => {
|
|
|
31
34
|
status: "running",
|
|
32
35
|
queue: [],
|
|
33
36
|
steerQueue: [],
|
|
34
|
-
dispatching:
|
|
37
|
+
dispatching: null,
|
|
35
38
|
error: null,
|
|
36
|
-
runLeafMessageId: null,
|
|
37
39
|
});
|
|
38
40
|
entry.status = "running";
|
|
39
41
|
entry.runId = runId;
|
|
@@ -66,7 +68,7 @@ const enqueueOrSteer = (
|
|
|
66
68
|
const run = draft.runs[0];
|
|
67
69
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
68
70
|
// In dispatch limbo the canonical state already tells the story: no fold.
|
|
69
|
-
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
71
|
+
if (run?.dispatching?.messages.some((e) => e.id === id)) return;
|
|
70
72
|
const sourceLane =
|
|
71
73
|
run === undefined
|
|
72
74
|
? undefined
|
|
@@ -104,8 +106,11 @@ const enqueueOrSteer = (
|
|
|
104
106
|
if (sourceLane === target.steerQueue)
|
|
105
107
|
target.steerQueue.splice(sourceIndex, 0, entry);
|
|
106
108
|
else target.steerQueue.push(entry);
|
|
107
|
-
target.dispatching
|
|
108
|
-
|
|
109
|
+
target.dispatching = {
|
|
110
|
+
trigger: "message-send",
|
|
111
|
+
messages: target.steerQueue.splice(0),
|
|
112
|
+
};
|
|
113
|
+
} else target.dispatching = { trigger: "message-send", messages: [entry] };
|
|
109
114
|
return;
|
|
110
115
|
}
|
|
111
116
|
const continues = steer && draft.status !== "running";
|