@assistant-ui/react-statewire 0.6.1 → 0.6.3
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 +4 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +14 -6
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runCommands.d.ts +4 -2
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +14 -1
- package/dist/runCommands.js.map +1 -1
- package/dist/runsOptimistic.d.ts.map +1 -1
- package/dist/runsOptimistic.js +13 -3
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.runs.test.tsx +38 -0
- package/src/StatewireThread.ts +19 -5
- package/src/runCommands.ts +22 -0
- package/src/runsOptimistic.test.ts +45 -2
- package/src/runsOptimistic.ts +25 -12
|
@@ -153,6 +153,8 @@ declare namespace StatewireThread {
|
|
|
153
153
|
readonly status: Exclude<RunStatus, "ready">;
|
|
154
154
|
readonly queue: readonly RunsQueueEntry[];
|
|
155
155
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
156
|
+
/** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
|
|
157
|
+
readonly dispatching: readonly RunsQueueEntry[];
|
|
156
158
|
/** The parked pending set; present only in input-required. */
|
|
157
159
|
readonly inputRequests?: readonly InputRequestState[];
|
|
158
160
|
readonly error: RunsError | null;
|
|
@@ -172,6 +174,8 @@ declare namespace StatewireThread {
|
|
|
172
174
|
readonly runId: string | null;
|
|
173
175
|
readonly queue: readonly RunsQueueEntry[];
|
|
174
176
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
177
|
+
/** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
|
|
178
|
+
readonly dispatching: readonly RunsQueueEntry[];
|
|
175
179
|
/** The parked pending set; present only in input-required. */
|
|
176
180
|
readonly inputRequests?: readonly InputRequestState[];
|
|
177
181
|
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":";;;;;;;cAuWa;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;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,yBAAyB,UAAU;;OAG7C;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;aAEA;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;;OAIxB;;OAQA,iBAAiB;;aAElB,OAAO;;;OAIN;aACD;cACC,cAAc;;;OAId;;aAED;aACA,QAAQ,QAAQ;aAChB,gBAAgB;aAChB,qBAAqB;;aAErB,sBAAsB;;aAEtB,yBAAyB;aACzB,OAAO;aACP;;;OAIC;;aAED,QAAQ;;aAER,eAAe;;;OAId;aACD,QAAQ;;aAER;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,sBAAsB;;aAEtB,yBAAyB;aACzB,OAAO;aACP;;OAGC;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,OAAO;;OAGG,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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toWireMessage, viewedLeafId } from "./runCommands.js";
|
|
1
|
+
import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toWireMessage, viewedLeafId } from "./runCommands.js";
|
|
2
2
|
import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
|
|
3
3
|
import { symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
4
4
|
import { runsOptimistic } from "./runsOptimistic.js";
|
|
@@ -14,6 +14,7 @@ const READY_RUNS = {
|
|
|
14
14
|
runId: null,
|
|
15
15
|
queue: [],
|
|
16
16
|
steerQueue: [],
|
|
17
|
+
dispatching: [],
|
|
17
18
|
error: null,
|
|
18
19
|
runLeafMessageId: null
|
|
19
20
|
};
|
|
@@ -98,6 +99,7 @@ const useStatewireThread = (options) => {
|
|
|
98
99
|
runId: entry.runId,
|
|
99
100
|
queue: entry.queue,
|
|
100
101
|
steerQueue: entry.steerQueue,
|
|
102
|
+
dispatching: entry.dispatching,
|
|
101
103
|
...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
|
|
102
104
|
error: entry.error,
|
|
103
105
|
runLeafMessageId: entry.runLeafMessageId
|
|
@@ -119,13 +121,19 @@ const useStatewireThread = (options) => {
|
|
|
119
121
|
state_0,
|
|
120
122
|
metadata
|
|
121
123
|
]);
|
|
124
|
+
const messages = useMemo(() => {
|
|
125
|
+
const known = new Set(converted.messages.map((m) => m.id));
|
|
126
|
+
const pending_0 = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));
|
|
127
|
+
if (pending_0.length === 0) return converted.messages;
|
|
128
|
+
return [...converted.messages, ...pending_0.map(toDispatchingMessage)];
|
|
129
|
+
}, [converted.messages, runs]);
|
|
122
130
|
const queueItems = runs !== void 0 ? runs.queue : converted.queue;
|
|
123
131
|
const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
|
|
124
132
|
if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
|
|
125
133
|
const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
|
|
126
134
|
if (queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
127
|
-
const queue = useMemo(() => queueItems ? createRunQueueAdapter(
|
|
128
|
-
|
|
135
|
+
const queue = useMemo(() => queueItems ? createRunQueueAdapter(messages, queueItems, steerQueueItems, dispatch, dispatchSend) : void 0, [
|
|
136
|
+
messages,
|
|
129
137
|
queueItems,
|
|
130
138
|
steerQueueItems,
|
|
131
139
|
dispatch,
|
|
@@ -152,17 +160,17 @@ const useStatewireThread = (options) => {
|
|
|
152
160
|
dispatchSend(message_0.sourceId != null ? resolveEditCommand(message_0) : {
|
|
153
161
|
type: "run/steer",
|
|
154
162
|
message: toWireMessage(message_0, crypto.randomUUID()),
|
|
155
|
-
anchorMessageId: viewedLeafId(
|
|
163
|
+
anchorMessageId: viewedLeafId(messages)
|
|
156
164
|
}, message_0);
|
|
157
165
|
};
|
|
158
166
|
const handleReload = (parentId) => {
|
|
159
|
-
dispatch(resolveReloadCommand(
|
|
167
|
+
dispatch(resolveReloadCommand(messages, parentId));
|
|
160
168
|
};
|
|
161
169
|
const handleEdit = (message_1) => {
|
|
162
170
|
dispatch(resolveEditCommand(message_1));
|
|
163
171
|
};
|
|
164
172
|
const thread = useResource(ExternalThread({
|
|
165
|
-
messages
|
|
173
|
+
messages,
|
|
166
174
|
isRunning: runs !== void 0 ? runs.status === "running" : converted.isRunning,
|
|
167
175
|
isLoading: !attached,
|
|
168
176
|
state: converted.state,
|
|
@@ -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","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","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","queueItems","steerQueueItems","queueSeam","present","messages","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","id","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 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 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 ...(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 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 converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [converted.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(converted.messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: converted.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 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 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":";;;;;;;;;;;AAiDA,MAAM6C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,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,OAAOnC,kBAAkBgC,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,SAAS3D,OAAO0D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAc7D,SAC5B,CAAA,CACF;CACA,MAAM,CAAC+D,UAAU/D,gBACRgE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAMI,aAAaZ,QAAQa;CAC3B,MAAM,CAACC,YAAYvE,eAAeqE,eAAejB,KAAAA,CAAS;CAC1D,IAAImB,cAAcF,eAAejB,KAAAA,IAC/B,MAAM,IAAIoB,MACR,yDACGD,WAAW,QAAQ,WACpB,oCACJ;CAEF,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ACvD,GAAI3F,QAAQuG,cAAcG,YAAY,EACpCC,gBAAgB1D,SAAS,EAAEE,MAAM,eAAe,CAAC,EACnD;EACA,GAAInD,QAAQuG,cAAcK,UAAU,EAAEC,UAAUpB,aAAa;EAC7D,GAAItB,kBAAkBxE,KAAAA,KAAa;GACjCmH,kBAAkBC,gBAChB9D,SAAS1E,uBAAuB4F,eAAe4C,WAAW,CAAC;GAC7DC,0BAA0BC,aACxBhE,SAAS3E,yBAAyB6F,eAAe8C,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUlH,OAAOC,QAAQkH,cAAc;GAC7C,IACED,YAAYxH,KAAAA,MACX,OAAOwH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAIpG,MAAM,mDAAmD;GACrE,MAAM5B,QAAQ0B,SAASlB,KAAAA,IAAYkB,KAAK1B,QAAQuF,UAAUvF;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACNwH,YAAYxH,KAAAA,IACV,CAAA,IACA,CAACwH,OAAO,IACV,CAAC;IAAE,GAAGA;IAAShI;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACmE,OAAOxD,YAAiB;IAC1DW,OAAOC,QAAQ6C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA8D,UAAUlD,UAAU0F;CACpB,OAAOA;AACT;AAEA,MAAa/G,mBAORmB,YACHxD,SAASuD,kBAAkB,CAAC,CAACC,OAAO;AA4UtCnD,uBACEkD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAACiM,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","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,i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BC,aACxBvE,SAAS5E,yBAAyB8F,eAAeqD,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUzH,OAAOC,QAAQyH,cAAc;GAC7C,IACED,YAAY/H,KAAAA,MACX,OAAO+H,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI3G,MAAM,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"}
|
package/dist/runCommands.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { StatewireThread } from "./StatewireThread.js";
|
|
1
2
|
import { AssistantTransportThread } from "./AssistantTransportThread.js";
|
|
2
|
-
import { AppendMessage, ExternalThreadQueueAdapter } from "@assistant-ui/core";
|
|
3
|
+
import { AppendMessage, ExternalThreadQueueAdapter, ThreadMessage } from "@assistant-ui/core";
|
|
3
4
|
//#region src/runCommands.d.ts
|
|
4
5
|
declare const toWireMessage: (message: AppendMessage, id: string) => AssistantTransportThread.RunUserMessage;
|
|
5
6
|
declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) => {
|
|
@@ -12,6 +13,7 @@ declare const toQueueItemState: (item: AssistantTransportThread.RunQueueItem) =>
|
|
|
12
13
|
mimeType: string;
|
|
13
14
|
})[];
|
|
14
15
|
};
|
|
16
|
+
declare const toDispatchingMessage: (item: StatewireThread.RunsQueueEntry) => ThreadMessage;
|
|
15
17
|
declare const viewedLeafId: (messages: readonly {
|
|
16
18
|
id: string;
|
|
17
19
|
}[]) => string | null;
|
|
@@ -24,5 +26,5 @@ declare const resolveReloadCommand: (messages: readonly {
|
|
|
24
26
|
role: string;
|
|
25
27
|
}[], parentId: string | null) => AssistantTransportThread.RunReloadCommand;
|
|
26
28
|
//#endregion
|
|
27
|
-
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
|
|
29
|
+
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toQueueItemState, toWireMessage, viewedLeafId };
|
|
28
30
|
//# sourceMappingURL=runCommands.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;;cASa,gBACX,SAAS,eACT,eACC,yBAAyB;cAwCf,mBACX,MAAM,yBAAyB;;;UAAA,yBAAA;;;;;;;cAkBpB,uBACX,MAAM,gBAAgB,mBACrB;cA2BU,eACX;EAAqB;;cAGV,qBACX,SAAS,kBACR,yBAAyB;cAUf,wBACX;EAAqB;KACrB,qBAAqB,yBAAyB,gBAC9C,0BAA0B,yBAAyB,4BACnD,WAAW,SAAS,yBAAyB,qBAC7C,eACE,SAAS,yBAAyB,YAClC,SAAS,2BAEV;cAmDU,uBACX;EAAqB;EAAY;KACjC,4BACC,yBAAyB"}
|
package/dist/runCommands.js
CHANGED
|
@@ -38,6 +38,19 @@ const toQueueItemState = (item) => ({
|
|
|
38
38
|
...part.filename !== void 0 && { filename: part.filename }
|
|
39
39
|
})
|
|
40
40
|
});
|
|
41
|
+
const toDispatchingMessage = (item) => ({
|
|
42
|
+
id: item.id,
|
|
43
|
+
role: "user",
|
|
44
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
45
|
+
content: item.parts.map((part) => part.type === "text" ? part : {
|
|
46
|
+
type: "file",
|
|
47
|
+
data: part.url,
|
|
48
|
+
mimeType: part.mediaType,
|
|
49
|
+
...part.filename !== void 0 && { filename: part.filename }
|
|
50
|
+
}),
|
|
51
|
+
attachments: [],
|
|
52
|
+
metadata: { custom: {} }
|
|
53
|
+
});
|
|
41
54
|
const placementFields = (placement) => ({
|
|
42
55
|
...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
|
|
43
56
|
...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
|
|
@@ -117,6 +130,6 @@ const resolveReloadCommand = (messages, parentId) => {
|
|
|
117
130
|
};
|
|
118
131
|
};
|
|
119
132
|
//#endregion
|
|
120
|
-
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
|
|
133
|
+
export { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, toDispatchingMessage, toQueueItemState, toWireMessage, viewedLeafId };
|
|
121
134
|
|
|
122
135
|
//# sourceMappingURL=runCommands.js.map
|
package/dist/runCommands.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","AssistantTransportThread","toWireMessage","message","id","RunUserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","resolveEditCommand","RunEditCommand","sourceId","crypto","randomUUID","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","index","findIndex","target"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): AssistantTransportThread.RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: AssistantTransportThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (\n | AssistantTransportThread.TextPart\n | AssistantTransportThread.FilePart\n )[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (\n item: AssistantTransportThread.RunQueueItem,\n) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const resolveEditCommand = (\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly AssistantTransportThread.RunQueueItem[],\n steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,\n dispatch: (command: AssistantTransportThread.RunCommand) => void,\n dispatchSend: (\n command: AssistantTransportThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): AssistantTransportThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":";AAOA,MAAaI,iBACXC,SACAC,OAC4C;CAC5C,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAA6C,CAAA;CACnD,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAw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AAC;CAC5D;AACF;AAEA,MAAae,wBACX9B,UACA+B,aAC8C;CAC9C,MAAME,QACJF,aAAa,OACT,IACA/B,SAASkC,WAAWzE,YAAYA,QAAQC,OAAOqE,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQE,UAAU,GACjC,MAAM,IAAIpE,MAAM,iCAAiCkE,SAAQ,aAAc;CACzE,MAAMI,SAASnC,SAASiC;CACxB,IAAIE,WAAWnD,KAAAA,KAAamD,OAAOvE,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAc6B,UAAU+B,OAAOzE;CAAG;AACnD"}
|
|
1
|
+
{"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","ThreadMessage","AssistantTransportThread","StatewireThread","toWireMessage","message","id","RunUserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","toDispatchingMessage","RunsQueueEntry","createdAt","Date","metadata","custom","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","resolveEditCommand","RunEditCommand","sourceId","crypto","randomUUID","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","laneOf","queueItemId","some","sendCommand","lane","fields","anchorMessageId","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","RunReloadCommand","index","findIndex","target"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { AssistantTransportThread } from \"./AssistantTransportThread\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): AssistantTransportThread.RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: AssistantTransportThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (\n | AssistantTransportThread.TextPart\n | AssistantTransportThread.FilePart\n )[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nexport const toQueueItemState = (\n item: AssistantTransportThread.RunQueueItem,\n) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nexport const toDispatchingMessage = (\n item: StatewireThread.RunsQueueEntry,\n): ThreadMessage => ({\n id: item.id,\n role: \"user\",\n createdAt: new Date(),\n content: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n attachments: [],\n metadata: { custom: {} },\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nexport const viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const resolveEditCommand = (\n message: AppendMessage,\n): AssistantTransportThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n return {\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly AssistantTransportThread.RunQueueItem[],\n steerQueueItems: readonly AssistantTransportThread.RunQueueItem[] | undefined,\n dispatch: (command: AssistantTransportThread.RunCommand) => void,\n dispatchSend: (\n command: AssistantTransportThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): AssistantTransportThread.RunCommand => {\n if (message.sourceId != null) return resolveEditCommand(message);\n const fields = {\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n };\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): AssistantTransportThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":";AASA,MAAaM,iBACXC,SACAC,OAC4C;CAC5C,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAA6C,CAAA;CACnD,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAGA,CACJ,GAAGnB,OACH,GAAIE,M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;IAAe,GAAGkD;GAAO,CACvC;EACF;EACAQ,OAAOZ,aAAa5D,YAAY;GAC9B,MAAMyE,cAAc1E,cAAcC,SAAS4D,WAAW;GACtDL,SACEI,OAAOC,WAAW,MAAM,UACpB;IAAE9C,MAAM;IAAad,SAASyE;GAAY,IAC1C;IAAE3D,MAAM;IAAed,SAASyE;GAAY,CAClD;EACF;EACAC,SAASd,gBACPL,SAAS;GAAEzC,MAAM;GAAeyD,WAAWX;EAAY,CAAC;CAC5D;AACF;AAEA,MAAae,wBACX9B,UACA+B,aAC8C;CAC9C,MAAME,QACJF,aAAa,OACT,IACA/B,SAASkC,WAAW/E,YAAYA,QAAQC,OAAO2E,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQE,UAAU,GACjC,MAAM,IAAI1E,MAAM,iCAAiCwE,SAAQ,aAAc;CACzE,MAAMI,SAASnC,SAASiC;CACxB,IAAIE,WAAWzD,KAAAA,KAAayD,OAAO7E,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EAAEU,MAAM;EAAcmC,UAAU+B,OAAO/E;CAAG;AACnD"}
|
|
@@ -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":";;;cA0Ha,iBACX,gBACA,SAAS,UAAU,QAAQ,mBAAmB,2BAC9C,KAAK,gBAAgB"}
|
package/dist/runsOptimistic.js
CHANGED
|
@@ -5,6 +5,7 @@ const startRun = (draft, runId) => {
|
|
|
5
5
|
status: "running",
|
|
6
6
|
queue: [],
|
|
7
7
|
steerQueue: [],
|
|
8
|
+
dispatching: [],
|
|
8
9
|
error: null,
|
|
9
10
|
runLeafMessageId: null
|
|
10
11
|
};
|
|
@@ -21,6 +22,7 @@ const insert = (lane, entry, { insertAfter, insertBefore }) => {
|
|
|
21
22
|
const enqueueOrSteer = (draft, command, runId) => {
|
|
22
23
|
const run = draft.runs[0];
|
|
23
24
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
25
|
+
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
24
26
|
const sourceLane = run === void 0 ? void 0 : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
|
|
25
27
|
let entry;
|
|
26
28
|
let sourceIndex = -1;
|
|
@@ -35,16 +37,24 @@ const enqueueOrSteer = (draft, command, runId) => {
|
|
|
35
37
|
if (!("message" in command)) return;
|
|
36
38
|
entry = { ...command.message };
|
|
37
39
|
}
|
|
38
|
-
|
|
39
|
-
|
|
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)) {
|
|
40
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.push(...target.steerQueue.splice(0));
|
|
48
|
+
} else target.dispatching.push(entry);
|
|
41
49
|
return;
|
|
42
50
|
}
|
|
51
|
+
const continues = steer && draft.status !== "running";
|
|
43
52
|
if (run === void 0) return;
|
|
44
|
-
const lane =
|
|
53
|
+
const lane = steer ? run.steerQueue : run.queue;
|
|
45
54
|
const hasPlacement = command.insertAfter !== void 0 || command.insertBefore !== void 0;
|
|
46
55
|
if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
|
|
47
56
|
else insert(lane, entry, command);
|
|
57
|
+
if (continues) startRun(draft, runId);
|
|
48
58
|
};
|
|
49
59
|
/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
|
|
50
60
|
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","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","sourceLane","find","l","
|
|
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","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: LaneEntry[];\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: [],\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.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.push(...target.steerQueue.splice(0));\n } else target.dispatching.push(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":";AA2BA,MAAMyB,YAAYC,OAAkBb,UAAwB;CAC1D,MAAMc,QAASD,MAAMF,KAAK,OAAO;EAC/BX,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;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KAAK;GACH1B,eACEb,OACAc,QAAQ0B,OAAO,IAGfrD,KACF;GACA;EAEF,KAAK;EACL,KAAK;GACHY,SAASC,OAAOb,KAAK;GACrB;EAEF,KAAK,gBAAgB;GACnB,MAAM8B,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAWS,IAAI1B,aAAa,CAAA;GACxCQ,SAASC,OAAOb,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAEgC,cAAcL,QACnB0B,OAAO;GACV,MAAMvB,MAAMjB,MAAMF,KAAK;GACvB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI3B,OAAO2B,IAAI1B,UAAU,GAAG;IAC9C,MAAMgB,QAAQJ,KAAKM,WAAWC,MAAMA,EAAEhC,OAAOyC,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAEmC,WAAWhD,aAAaoB,QAC7B0B,OAAO;GACV,MAAMI,WAAW5C,MAAMF,KAAK,EAAE,EAAEL;GAChC,MAAMmC,SAASgB,UAAUtB,MAAMuB,MAAMA,EAAEnE,OAAOgE,SAAS;GACvD,IAAId,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOlC,WAAWA;GAClB,IAAIkD,SAAUE,OAAOD,MAAMA,EAAEnD,aAAa,IAAI,GAAGK,SAASC,OAAOb,KAAK;GACtE;EACF;CAGF;AACF"}
|
package/package.json
CHANGED
|
@@ -24,6 +24,7 @@ type ServerRunEntry = {
|
|
|
24
24
|
parts: { type: "text"; text: string }[];
|
|
25
25
|
}[];
|
|
26
26
|
steerQueue: ServerRunEntry["queue"];
|
|
27
|
+
dispatching: ServerRunEntry["queue"];
|
|
27
28
|
error: { message: string } | null;
|
|
28
29
|
runLeafMessageId: string | null;
|
|
29
30
|
inputRequests?: {
|
|
@@ -55,6 +56,7 @@ const withRun = (
|
|
|
55
56
|
runId: null,
|
|
56
57
|
queue: [],
|
|
57
58
|
steerQueue: [],
|
|
59
|
+
dispatching: [],
|
|
58
60
|
error: null,
|
|
59
61
|
runLeafMessageId: null,
|
|
60
62
|
...entry,
|
|
@@ -320,6 +322,38 @@ describe("StatewireThread runs mode", () => {
|
|
|
320
322
|
);
|
|
321
323
|
});
|
|
322
324
|
|
|
325
|
+
it("projects dispatching items as in-flight messages, deduped by id", async () => {
|
|
326
|
+
const server = createServer({
|
|
327
|
+
messages: [{ id: "m1", role: "user", text: "hi" }],
|
|
328
|
+
...withRun({
|
|
329
|
+
status: "running",
|
|
330
|
+
runId: "run-1",
|
|
331
|
+
dispatching: [
|
|
332
|
+
{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] },
|
|
333
|
+
{ id: "d1", role: "user", parts: [{ type: "text", text: "go" }] },
|
|
334
|
+
],
|
|
335
|
+
}),
|
|
336
|
+
});
|
|
337
|
+
const { aui, runs } = mountThread({ transport: server.transport });
|
|
338
|
+
|
|
339
|
+
await waitFor(() => expect(runs().dispatching).toHaveLength(2));
|
|
340
|
+
const messages = aui().thread().getState().messages;
|
|
341
|
+
expect(messages.map((m) => m.id)).toEqual(["m1", "d1"]);
|
|
342
|
+
expect(messages[1]!.role).toBe("user");
|
|
343
|
+
|
|
344
|
+
act(() => {
|
|
345
|
+
server.cell.state!.messages.push({ id: "d1", role: "user", text: "go" });
|
|
346
|
+
server.cell.state!.runs[0]!.dispatching = [];
|
|
347
|
+
});
|
|
348
|
+
await waitFor(() => expect(runs().dispatching).toHaveLength(0));
|
|
349
|
+
expect(
|
|
350
|
+
aui()
|
|
351
|
+
.thread()
|
|
352
|
+
.getState()
|
|
353
|
+
.messages.map((m) => m.id),
|
|
354
|
+
).toEqual(["m1", "d1"]);
|
|
355
|
+
});
|
|
356
|
+
|
|
323
357
|
it("folds a pending steer into the lane while running", async () => {
|
|
324
358
|
const server = createRemoteServer(
|
|
325
359
|
withRun({ status: "running", runId: "run-1" }),
|
|
@@ -361,6 +395,10 @@ describe("StatewireThread runs mode", () => {
|
|
|
361
395
|
await waitFor(() => expect(runs().status).toBe("running"));
|
|
362
396
|
expect(runs().runId).toMatch(/^optimistic-/);
|
|
363
397
|
expect(runs().steerQueue).toEqual([]);
|
|
398
|
+
// The predicted dispatching entry renders like a canonical one.
|
|
399
|
+
expect(runs().dispatching).toHaveLength(1);
|
|
400
|
+
const messages = aui().thread().getState().messages;
|
|
401
|
+
expect(messages.map((m) => m.id)).toEqual([runs().dispatching[0]!.id]);
|
|
364
402
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
365
403
|
});
|
|
366
404
|
|
package/src/StatewireThread.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
createRunQueueAdapter,
|
|
33
33
|
resolveEditCommand,
|
|
34
34
|
resolveReloadCommand,
|
|
35
|
+
toDispatchingMessage,
|
|
35
36
|
toWireMessage,
|
|
36
37
|
viewedLeafId,
|
|
37
38
|
} from "./runCommands";
|
|
@@ -52,6 +53,7 @@ const READY_RUNS: StatewireThread.Runs = {
|
|
|
52
53
|
runId: null,
|
|
53
54
|
queue: [],
|
|
54
55
|
steerQueue: [],
|
|
56
|
+
dispatching: [],
|
|
55
57
|
error: null,
|
|
56
58
|
runLeafMessageId: null,
|
|
57
59
|
};
|
|
@@ -193,6 +195,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
193
195
|
runId: entry.runId,
|
|
194
196
|
queue: entry.queue,
|
|
195
197
|
steerQueue: entry.steerQueue,
|
|
198
|
+
dispatching: entry.dispatching,
|
|
196
199
|
...(entry.inputRequests !== undefined && {
|
|
197
200
|
inputRequests: entry.inputRequests,
|
|
198
201
|
}),
|
|
@@ -221,6 +224,13 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
221
224
|
) as StatewireThread.State,
|
|
222
225
|
[converter, state, metadata],
|
|
223
226
|
);
|
|
227
|
+
// Dispatch limbo renders as in-flight messages; ids already converted win.
|
|
228
|
+
const messages = useMemo((): StatewireThread.State["messages"] => {
|
|
229
|
+
const known = new Set(converted.messages.map((m) => m.id));
|
|
230
|
+
const pending = (runs?.dispatching ?? []).filter((e) => !known.has(e.id));
|
|
231
|
+
if (pending.length === 0) return converted.messages;
|
|
232
|
+
return [...converted.messages, ...pending.map(toDispatchingMessage)];
|
|
233
|
+
}, [converted.messages, runs]);
|
|
224
234
|
const queueItems = runs !== undefined ? runs.queue : converted.queue;
|
|
225
235
|
const steerQueueItems =
|
|
226
236
|
runs !== undefined ? runs.steerQueue : converted.steerQueue;
|
|
@@ -242,14 +252,14 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
242
252
|
(): ExternalThreadQueueAdapter | undefined =>
|
|
243
253
|
queueItems
|
|
244
254
|
? createRunQueueAdapter(
|
|
245
|
-
|
|
255
|
+
messages,
|
|
246
256
|
queueItems,
|
|
247
257
|
steerQueueItems,
|
|
248
258
|
dispatch,
|
|
249
259
|
dispatchSend,
|
|
250
260
|
)
|
|
251
261
|
: undefined,
|
|
252
|
-
[
|
|
262
|
+
[messages, queueItems, steerQueueItems, dispatch, dispatchSend],
|
|
253
263
|
);
|
|
254
264
|
|
|
255
265
|
const inputRequests =
|
|
@@ -283,14 +293,14 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
283
293
|
: {
|
|
284
294
|
type: "run/steer",
|
|
285
295
|
message: toWireMessage(message, crypto.randomUUID()),
|
|
286
|
-
anchorMessageId: viewedLeafId(
|
|
296
|
+
anchorMessageId: viewedLeafId(messages),
|
|
287
297
|
},
|
|
288
298
|
message,
|
|
289
299
|
);
|
|
290
300
|
};
|
|
291
301
|
|
|
292
302
|
const handleReload = (parentId: string | null) => {
|
|
293
|
-
dispatch(resolveReloadCommand(
|
|
303
|
+
dispatch(resolveReloadCommand(messages, parentId));
|
|
294
304
|
};
|
|
295
305
|
|
|
296
306
|
const handleEdit = (message: AppendMessage) => {
|
|
@@ -299,7 +309,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
299
309
|
|
|
300
310
|
const thread = useResource(
|
|
301
311
|
ExternalThread({
|
|
302
|
-
messages:
|
|
312
|
+
messages: messages as readonly ExternalThreadMessage[],
|
|
303
313
|
isRunning:
|
|
304
314
|
runs !== undefined ? runs.status === "running" : converted.isRunning,
|
|
305
315
|
isLoading: !attached,
|
|
@@ -547,6 +557,8 @@ export namespace StatewireThread {
|
|
|
547
557
|
readonly status: Exclude<RunStatus, "ready">;
|
|
548
558
|
readonly queue: readonly RunsQueueEntry[];
|
|
549
559
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
560
|
+
/** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
|
|
561
|
+
readonly dispatching: readonly RunsQueueEntry[];
|
|
550
562
|
/** The parked pending set; present only in input-required. */
|
|
551
563
|
readonly inputRequests?: readonly InputRequestState[];
|
|
552
564
|
readonly error: RunsError | null;
|
|
@@ -568,6 +580,8 @@ export namespace StatewireThread {
|
|
|
568
580
|
readonly runId: string | null;
|
|
569
581
|
readonly queue: readonly RunsQueueEntry[];
|
|
570
582
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
583
|
+
/** The current dispatch's unacked messages — handed to the run, cleared at the messages-ack. */
|
|
584
|
+
readonly dispatching: readonly RunsQueueEntry[];
|
|
571
585
|
/** The parked pending set; present only in input-required. */
|
|
572
586
|
readonly inputRequests?: readonly InputRequestState[];
|
|
573
587
|
readonly error: RunsError | null;
|
package/src/runCommands.ts
CHANGED
|
@@ -2,8 +2,10 @@ import type {
|
|
|
2
2
|
AppendMessage,
|
|
3
3
|
ExternalThreadQueueAdapter,
|
|
4
4
|
QueuePlacement,
|
|
5
|
+
ThreadMessage,
|
|
5
6
|
} from "@assistant-ui/core";
|
|
6
7
|
import type { AssistantTransportThread } from "./AssistantTransportThread";
|
|
8
|
+
import type { StatewireThread } from "./StatewireThread";
|
|
7
9
|
|
|
8
10
|
export const toWireMessage = (
|
|
9
11
|
message: AppendMessage,
|
|
@@ -67,6 +69,26 @@ export const toQueueItemState = (
|
|
|
67
69
|
),
|
|
68
70
|
});
|
|
69
71
|
|
|
72
|
+
export const toDispatchingMessage = (
|
|
73
|
+
item: StatewireThread.RunsQueueEntry,
|
|
74
|
+
): ThreadMessage => ({
|
|
75
|
+
id: item.id,
|
|
76
|
+
role: "user",
|
|
77
|
+
createdAt: new Date(),
|
|
78
|
+
content: item.parts.map((part) =>
|
|
79
|
+
part.type === "text"
|
|
80
|
+
? part
|
|
81
|
+
: {
|
|
82
|
+
type: "file" as const,
|
|
83
|
+
data: part.url,
|
|
84
|
+
mimeType: part.mediaType,
|
|
85
|
+
...(part.filename !== undefined && { filename: part.filename }),
|
|
86
|
+
},
|
|
87
|
+
),
|
|
88
|
+
attachments: [],
|
|
89
|
+
metadata: { custom: {} },
|
|
90
|
+
});
|
|
91
|
+
|
|
70
92
|
const placementFields = (placement: QueuePlacement) => ({
|
|
71
93
|
...(placement.insertAfter !== undefined && {
|
|
72
94
|
insertAfter: placement.insertAfter,
|
|
@@ -18,6 +18,7 @@ const mount = (entry?: Draft): Draft =>
|
|
|
18
18
|
runId: null,
|
|
19
19
|
queue: [],
|
|
20
20
|
steerQueue: [],
|
|
21
|
+
dispatching: [],
|
|
21
22
|
error: null,
|
|
22
23
|
runLeafMessageId: null,
|
|
23
24
|
...entry,
|
|
@@ -54,7 +55,7 @@ describe("runsOptimistic", () => {
|
|
|
54
55
|
expect(run(draft).runId).toBe("run-1");
|
|
55
56
|
});
|
|
56
57
|
|
|
57
|
-
it("
|
|
58
|
+
it("parks a steer in the lane after a stop and predicts the continue run", () => {
|
|
58
59
|
const draft = mount({
|
|
59
60
|
status: "stopped",
|
|
60
61
|
steerQueue: [message("s1")],
|
|
@@ -68,10 +69,32 @@ describe("runsOptimistic", () => {
|
|
|
68
69
|
expect(draft.status).toBe("running");
|
|
69
70
|
expect(run(draft).status).toBe("running");
|
|
70
71
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
71
|
-
expect(run(draft).steerQueue).toEqual([]);
|
|
72
|
+
expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["s1", "s2"]);
|
|
73
|
+
expect(run(draft).dispatching).toEqual([]);
|
|
72
74
|
expect(run(draft).error).toBeNull();
|
|
73
75
|
});
|
|
74
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.map((e: Draft) => e.id)).toEqual([
|
|
93
|
+
"s1",
|
|
94
|
+
"s2",
|
|
95
|
+
]);
|
|
96
|
+
});
|
|
97
|
+
|
|
75
98
|
it("dispatches an enqueue add only in ready or in error/stop with empty lanes", () => {
|
|
76
99
|
const ready = mount();
|
|
77
100
|
apply(ready, "run/enqueue", {
|
|
@@ -82,6 +105,7 @@ describe("runsOptimistic", () => {
|
|
|
82
105
|
expect(ready.status).toBe("running");
|
|
83
106
|
expect(run(ready).runId).toBe("optimistic-7");
|
|
84
107
|
expect(run(ready).queue).toEqual([]);
|
|
108
|
+
expect(run(ready).dispatching.map((e: Draft) => e.id)).toEqual(["a"]);
|
|
85
109
|
|
|
86
110
|
const stopped = mount({ status: "stopped", queue: [message("q1")] });
|
|
87
111
|
apply(stopped, "run/enqueue", {
|
|
@@ -108,6 +132,23 @@ describe("runsOptimistic", () => {
|
|
|
108
132
|
expect(run(draft).queue.map((e: Draft) => e.id)).toEqual(["a", "x", "b"]);
|
|
109
133
|
});
|
|
110
134
|
|
|
135
|
+
it("skips the fold for a message in dispatch limbo", () => {
|
|
136
|
+
const draft = mount({
|
|
137
|
+
status: "running",
|
|
138
|
+
runId: "r",
|
|
139
|
+
dispatching: [message("d1")],
|
|
140
|
+
});
|
|
141
|
+
apply(draft, "run/enqueue", {
|
|
142
|
+
type: "run/enqueue",
|
|
143
|
+
message: message("d1"),
|
|
144
|
+
anchorMessageId: null,
|
|
145
|
+
});
|
|
146
|
+
apply(draft, "run/steer", { type: "run/steer", messageId: "d1" });
|
|
147
|
+
expect(run(draft).queue).toEqual([]);
|
|
148
|
+
expect(run(draft).steerQueue).toEqual([]);
|
|
149
|
+
expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual(["d1"]);
|
|
150
|
+
});
|
|
151
|
+
|
|
111
152
|
it("applies moves, edits of queued items, and dequeue", () => {
|
|
112
153
|
const draft = mount({
|
|
113
154
|
status: "running",
|
|
@@ -165,6 +206,7 @@ describe("runsOptimistic", () => {
|
|
|
165
206
|
status: "running",
|
|
166
207
|
queue: [],
|
|
167
208
|
steerQueue: [],
|
|
209
|
+
dispatching: [message("s1")],
|
|
168
210
|
error: null,
|
|
169
211
|
runLeafMessageId: null,
|
|
170
212
|
});
|
|
@@ -214,6 +256,7 @@ describe("runsOptimistic", () => {
|
|
|
214
256
|
expect(run(draft).runId).toBe("optimistic-7");
|
|
215
257
|
expect(run(draft).inputRequests).toBeUndefined();
|
|
216
258
|
expect(run(draft).steerQueue).toEqual([]);
|
|
259
|
+
expect(run(draft).dispatching.map((e: Draft) => e.id)).toEqual(["s1"]);
|
|
217
260
|
});
|
|
218
261
|
|
|
219
262
|
it("leaves the draft untouched for run/stop and unknown moves", () => {
|
package/src/runsOptimistic.ts
CHANGED
|
@@ -14,6 +14,7 @@ type RunEntry = {
|
|
|
14
14
|
status: StatewireThread.RunStatus;
|
|
15
15
|
queue: LaneEntry[];
|
|
16
16
|
steerQueue: LaneEntry[];
|
|
17
|
+
dispatching: LaneEntry[];
|
|
17
18
|
inputRequests?: { id: string; response: unknown }[];
|
|
18
19
|
error: unknown;
|
|
19
20
|
runLeafMessageId: string | null;
|
|
@@ -30,6 +31,7 @@ const startRun = (draft: RunsDraft, runId: string): void => {
|
|
|
30
31
|
status: "running",
|
|
31
32
|
queue: [],
|
|
32
33
|
steerQueue: [],
|
|
34
|
+
dispatching: [],
|
|
33
35
|
error: null,
|
|
34
36
|
runLeafMessageId: null,
|
|
35
37
|
});
|
|
@@ -63,6 +65,8 @@ const enqueueOrSteer = (
|
|
|
63
65
|
): void => {
|
|
64
66
|
const run = draft.runs[0];
|
|
65
67
|
const id = "message" in command ? command.message.id : command.messageId;
|
|
68
|
+
// In dispatch limbo the canonical state already tells the story: no fold.
|
|
69
|
+
if (run?.dispatching.some((e) => e.id === id)) return;
|
|
66
70
|
const sourceLane =
|
|
67
71
|
run === undefined
|
|
68
72
|
? undefined
|
|
@@ -83,27 +87,36 @@ const enqueueOrSteer = (
|
|
|
83
87
|
entry = { ...command.message };
|
|
84
88
|
}
|
|
85
89
|
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
if (
|
|
96
|
-
if (command.type === "run/steer" && run !== undefined) run.steerQueue = [];
|
|
90
|
+
const steer = command.type === "run/steer";
|
|
91
|
+
const direct = steer
|
|
92
|
+
? draft.status === "ready" || draft.status === "input-required"
|
|
93
|
+
: sourceLane === undefined &&
|
|
94
|
+
(draft.status === "ready" ||
|
|
95
|
+
((draft.status === "stopped" || draft.status === "error") &&
|
|
96
|
+
run !== undefined &&
|
|
97
|
+
run.queue.length === 0 &&
|
|
98
|
+
run.steerQueue.length === 0));
|
|
99
|
+
if (direct) {
|
|
97
100
|
startRun(draft, runId);
|
|
101
|
+
const target = draft.runs[0]!;
|
|
102
|
+
if (steer) {
|
|
103
|
+
// The whole steer lane rides the dispatch, in lane order.
|
|
104
|
+
if (sourceLane === target.steerQueue)
|
|
105
|
+
target.steerQueue.splice(sourceIndex, 0, entry);
|
|
106
|
+
else target.steerQueue.push(entry);
|
|
107
|
+
target.dispatching.push(...target.steerQueue.splice(0));
|
|
108
|
+
} else target.dispatching.push(entry);
|
|
98
109
|
return;
|
|
99
110
|
}
|
|
111
|
+
const continues = steer && draft.status !== "running";
|
|
100
112
|
|
|
101
113
|
if (run === undefined) return;
|
|
102
|
-
const lane =
|
|
114
|
+
const lane = steer ? run.steerQueue : run.queue;
|
|
103
115
|
const hasPlacement =
|
|
104
116
|
command.insertAfter !== undefined || command.insertBefore !== undefined;
|
|
105
117
|
if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
|
|
106
118
|
else insert(lane, entry, command);
|
|
119
|
+
if (continues) startRun(draft, runId);
|
|
107
120
|
};
|
|
108
121
|
|
|
109
122
|
/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
|