@assistant-ui/react-statewire 0.28.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/StatewireThread.d.ts +2 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +41 -7
- package/dist/StatewireThread.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.failed.test.tsx +28 -2
- package/src/StatewireThread.retract.test.tsx +175 -0
- package/src/StatewireThread.runs.test.tsx +38 -28
- package/src/StatewireThread.ts +53 -6
- package/src/localStorage.test.ts +1 -8
|
@@ -263,6 +263,8 @@ declare namespace StatewireThread {
|
|
|
263
263
|
transport: Transport<T>;
|
|
264
264
|
/** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
|
|
265
265
|
initialState: T;
|
|
266
|
+
/** Application protocol for optimistic commands; must match the transport's protocol. */
|
|
267
|
+
protocol?: string | undefined;
|
|
266
268
|
converter: StateConverter<T>;
|
|
267
269
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
268
270
|
optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA+fvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IAC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A;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;aAER,iBAAiB;;cAGhB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;;;cAII;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;;IAEd;IACA,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;MAEA;;;;;;;;IASN;MAEM,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB,gBAAgB;;IAGhD;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -37,6 +37,7 @@ const ambientContextOf = (context) => ({
|
|
|
37
37
|
const useStatewireThread = (options) => {
|
|
38
38
|
const latest = useRef(options);
|
|
39
39
|
latest.current = options;
|
|
40
|
+
const retrying = useRef(/* @__PURE__ */ new Set());
|
|
40
41
|
const [pending, setPending] = useState([]);
|
|
41
42
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
42
43
|
const { state: state_1, commands, connection: connection_0, setContext, isBusy, failed, discardFailed } = useStatewire({
|
|
@@ -44,6 +45,7 @@ const useStatewireThread = (options) => {
|
|
|
44
45
|
onError: (error) => latest.current.onError?.(error),
|
|
45
46
|
storage: options.storage,
|
|
46
47
|
initialState: options.initialState,
|
|
48
|
+
...options.protocol !== void 0 && { protocol: options.protocol },
|
|
47
49
|
optimistic: (draft, command_0, ctx) => {
|
|
48
50
|
runsOptimistic(draft, command_0, ctx);
|
|
49
51
|
latest.current.optimistic?.(draft, command_0, ctx);
|
|
@@ -109,6 +111,27 @@ const useStatewireThread = (options) => {
|
|
|
109
111
|
setText((prev_1) => prev_1 === "" ? text : prev_1);
|
|
110
112
|
});
|
|
111
113
|
}, [dispatch]);
|
|
114
|
+
const popRetracted = async (retracted, runId) => {
|
|
115
|
+
if (!Array.isArray(retracted) || retracted.length === 0 || runId === null) return;
|
|
116
|
+
const composerApi = threadRef.current.composer();
|
|
117
|
+
if (composerApi.getState().text !== "") return;
|
|
118
|
+
const texts = [];
|
|
119
|
+
for (const item of retracted) {
|
|
120
|
+
try {
|
|
121
|
+
await dispatch({
|
|
122
|
+
type: "run/dequeue",
|
|
123
|
+
runId,
|
|
124
|
+
messageId: item.id
|
|
125
|
+
});
|
|
126
|
+
} catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
texts.push(item.parts.flatMap((part_0) => part_0.type === "text" ? [part_0.text] : []).join("\n\n"));
|
|
130
|
+
}
|
|
131
|
+
if (texts.length === 0) return;
|
|
132
|
+
const setText_0 = composerApi.setText;
|
|
133
|
+
setText_0((prev_2) => [prev_2, ...texts].filter(Boolean).join("\n\n"));
|
|
134
|
+
};
|
|
112
135
|
const { status, runs } = useMemo(() => {
|
|
113
136
|
const entries = state_1?.runs;
|
|
114
137
|
const entry_1 = entries?.[0];
|
|
@@ -184,10 +207,20 @@ const useStatewireThread = (options) => {
|
|
|
184
207
|
inputRequests,
|
|
185
208
|
runs,
|
|
186
209
|
retryFailed: (messageId_0) => {
|
|
210
|
+
if (retrying.current.has(messageId_0)) return;
|
|
187
211
|
const entry_3 = takeFailed(messageId_0);
|
|
188
212
|
const command_5 = retryCommand(messages_0, liveRunId, failedRunCommand(entry_3));
|
|
189
|
-
|
|
190
|
-
|
|
213
|
+
retrying.current.add(messageId_0);
|
|
214
|
+
const release = () => {
|
|
215
|
+
retrying.current.delete(messageId_0);
|
|
216
|
+
};
|
|
217
|
+
try {
|
|
218
|
+
discardFailed(entry_3);
|
|
219
|
+
dispatch(command_5).then(release, release);
|
|
220
|
+
} catch (error_1) {
|
|
221
|
+
release();
|
|
222
|
+
throw error_1;
|
|
223
|
+
}
|
|
191
224
|
},
|
|
192
225
|
discardFailed: (messageId_1) => discardFailed(takeFailed(messageId_1)),
|
|
193
226
|
popFailed: (messageId_2) => {
|
|
@@ -243,12 +276,13 @@ const useStatewireThread = (options) => {
|
|
|
243
276
|
onCancel: () => {
|
|
244
277
|
const payload = latest.current.stopPayload?.();
|
|
245
278
|
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
|
|
279
|
+
const runId_0 = runs.runId;
|
|
246
280
|
commands["run/stop"]({
|
|
247
281
|
...payload,
|
|
248
|
-
runId:
|
|
282
|
+
runId: runId_0,
|
|
249
283
|
...runs.epoch !== void 0 && { epoch: runs.epoch }
|
|
250
|
-
}).catch((
|
|
251
|
-
latest.current.onError?.(
|
|
284
|
+
}).then((retracted_0) => popRetracted(retracted_0, runId_0)).catch((error_2) => {
|
|
285
|
+
latest.current.onError?.(error_2);
|
|
252
286
|
});
|
|
253
287
|
}
|
|
254
288
|
}));
|
|
@@ -267,8 +301,8 @@ const useStatewireThread = (options) => {
|
|
|
267
301
|
name: attachment.name,
|
|
268
302
|
...attachment.contentType !== void 0 && { contentType: attachment.contentType },
|
|
269
303
|
content: attachment.content
|
|
270
|
-
}).catch((
|
|
271
|
-
latest.current.onError?.(
|
|
304
|
+
}).catch((error_3) => {
|
|
305
|
+
latest.current.onError?.(error_3);
|
|
272
306
|
});
|
|
273
307
|
}, [composerStorage]);
|
|
274
308
|
const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","length","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","messageId","find","f","sendCommand","reconnect","retryFailed","popFailed","parts","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","read","getState","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Promise","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || 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 failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\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 setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | 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 state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, 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 /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\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":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJ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vJ,OAAOqE,SAAS,UAC/B,CAAC,CACAyF,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAarO,gBAAgB,EAAEsO,YAAYvK,KAAAA,EAAqB,EAAE;CACzElE,gBAAgB;EACd,MAAMwG,YAAUiH;EAChB,IAAIjH,cAAYtC,KAAAA,GAAW;EAG3B,MAAMwK,aAAaF,UAAUC,eAAejI;EAC5CgI,UAAUC,aAAajI;EACvB,IAAIyH,cAAc,MAAME,iBAAiBpE,WAAW,GAAG;GACrD,IAAI,CAAC2E,YAAYlI,UAAQmI,MAAM;GAC/B;EACF;EACAnI,UAAQoI,MAAM;GAAE5F,MAAMiF;GAAW/B,aAAaiC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWf;EAAiBQ;EAAWE;CAAgB,CAAC;CAE5D,OAAOrC;AACT;AAEA,MAAahJ,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AA8ZtExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACsP,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Promise","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\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 {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || 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 failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\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 setContextRef.current(value);\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 // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | 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 state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, 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 /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\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":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAA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T;CACpB,MAAMyF,mBAAmBjP,cAErBgP,oBACGjJ,QACE4I,iBACCA,aAAWtK,OAAOwE,SAAS,UAC/B,CAAC,CACAqG,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAapP,gBAAgB,EAAEqP,YAAYtL,KAAAA,EAAqB,EAAE;CACzElE,gBAAgB;EACd,MAAM0G,YAAU+H;EAChB,IAAI/H,cAAYxC,KAAAA,GAAW;EAG3B,MAAMuL,aAAaF,UAAUC,eAAe9I;EAC5C6I,UAAUC,aAAa9I;EACvB,IAAIsI,cAAc,MAAME,iBAAiBlF,WAAW,GAAG;GACrD,IAAI,CAACyF,YAAY/I,UAAQgJ,MAAM;GAC/B;EACF;EACAhJ,UAAQiJ,MAAM;GAAExG,MAAM6F;GAAW5B,aAAa8B;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWd;EAAiBO;EAAWE;CAAgB,CAAC;CAE5D,OAAOlC;AACT;AAEA,MAAalK,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AAgatExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACmQ,IACrC"}
|
package/package.json
CHANGED
|
@@ -80,6 +80,7 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
80
80
|
if (url.endsWith("/stream")) {
|
|
81
81
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
82
82
|
const rec = clients.get(clientId)!;
|
|
83
|
+
rec.ctxSeq = 0;
|
|
83
84
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
84
85
|
const body = new ReadableStream<Uint8Array>({
|
|
85
86
|
start: (c) => {
|
|
@@ -97,7 +98,7 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
97
98
|
],
|
|
98
99
|
syn: {
|
|
99
100
|
seq: rec.seq,
|
|
100
|
-
ctxSeq:
|
|
101
|
+
ctxSeq: 0,
|
|
101
102
|
version: "2026-09-07",
|
|
102
103
|
protocols: [{ name: "default", version: "2026-09-07" }],
|
|
103
104
|
},
|
|
@@ -195,7 +196,7 @@ describe("StatewireThread failed lane", () => {
|
|
|
195
196
|
expect(runs().runId).toBeNull();
|
|
196
197
|
});
|
|
197
198
|
|
|
198
|
-
it("retry
|
|
199
|
+
it("repeated retry actions dispatch once and remove the entry", async () => {
|
|
199
200
|
const { server, aui, runs } = await mountFailed({
|
|
200
201
|
type: "run/enqueue",
|
|
201
202
|
runId: "run-1",
|
|
@@ -205,6 +206,7 @@ describe("StatewireThread failed lane", () => {
|
|
|
205
206
|
server.accept();
|
|
206
207
|
act(() => {
|
|
207
208
|
extras(aui).retryFailed("m1");
|
|
209
|
+
extras(aui).retryFailed("m1");
|
|
208
210
|
});
|
|
209
211
|
await waitFor(() => expect(runs().failed).toHaveLength(0));
|
|
210
212
|
const sends = server.received.filter((r) => r.method === "run/enqueue");
|
|
@@ -216,6 +218,30 @@ describe("StatewireThread failed lane", () => {
|
|
|
216
218
|
expect((sends[1]!.params[0] as { runId: string }).runId).not.toBe("run-1");
|
|
217
219
|
});
|
|
218
220
|
|
|
221
|
+
it("allows another retry after the previous retry is rejected", async () => {
|
|
222
|
+
const { server, aui, runs } = await mountFailed({
|
|
223
|
+
type: "run/enqueue",
|
|
224
|
+
runId: "run-1",
|
|
225
|
+
message: wireMessage("m1", "hello"),
|
|
226
|
+
runAnchorMessageId: null,
|
|
227
|
+
});
|
|
228
|
+
act(() => {
|
|
229
|
+
extras(aui).retryFailed("m1");
|
|
230
|
+
});
|
|
231
|
+
await waitFor(() => {
|
|
232
|
+
expect(server.received).toHaveLength(2);
|
|
233
|
+
expect(runs().failed).toHaveLength(1);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
server.accept();
|
|
237
|
+
act(() => {
|
|
238
|
+
extras(aui).retryFailed("m1");
|
|
239
|
+
extras(aui).retryFailed("m1");
|
|
240
|
+
});
|
|
241
|
+
await waitFor(() => expect(runs().failed).toHaveLength(0));
|
|
242
|
+
expect(server.received).toHaveLength(3);
|
|
243
|
+
});
|
|
244
|
+
|
|
219
245
|
it("a failed steer whose run is gone retries as a plain enqueue", async () => {
|
|
220
246
|
const { server, aui, runs } = await mountFailed({
|
|
221
247
|
type: "run/steer",
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
// Contract tests for the stopping client's pop: the run/stop verdict carries
|
|
4
|
+
// the run's retracted items, and the client that stopped dequeues them into
|
|
5
|
+
// an empty composer. A non-empty composer and rejected dequeues leave them
|
|
6
|
+
// queued.
|
|
7
|
+
|
|
8
|
+
import { act, render, waitFor } from "@testing-library/react";
|
|
9
|
+
import type { FC } from "react";
|
|
10
|
+
import { describe, expect, it } from "vitest";
|
|
11
|
+
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
12
|
+
import { resource } from "@assistant-ui/tap";
|
|
13
|
+
import {
|
|
14
|
+
StatewireReject,
|
|
15
|
+
useStatewireCommands,
|
|
16
|
+
useStatewireState,
|
|
17
|
+
} from "statewire/host";
|
|
18
|
+
import { asStatewireExtras, StatewireThread } from "./StatewireThread";
|
|
19
|
+
import { toThreadMessage } from "./__tests__/testHelpers";
|
|
20
|
+
|
|
21
|
+
type QueueItem = {
|
|
22
|
+
id: string;
|
|
23
|
+
role: "user";
|
|
24
|
+
parts: { type: "text"; text: string }[];
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
type ServerState = {
|
|
28
|
+
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
29
|
+
status: "ready" | StatewireThread.RunStatus;
|
|
30
|
+
runs: {
|
|
31
|
+
runId: string | null;
|
|
32
|
+
status: StatewireThread.RunStatus;
|
|
33
|
+
queue: QueueItem[];
|
|
34
|
+
steerQueue: QueueItem[];
|
|
35
|
+
}[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const item = (id: string, text: string): QueueItem => ({
|
|
39
|
+
id,
|
|
40
|
+
role: "user",
|
|
41
|
+
parts: [{ type: "text", text }],
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const converter: StatewireThread.StateConverter<ServerState> = (state) => ({
|
|
45
|
+
messages: state.messages.map(toThreadMessage),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// A host whose run/stop retracts the given items into the lanes and answers
|
|
49
|
+
// with them; run/dequeue removes an item unless `rejectDequeue` names it.
|
|
50
|
+
const createServer = (opts: {
|
|
51
|
+
retract: { queue?: QueueItem[]; steer?: QueueItem[] };
|
|
52
|
+
rejectDequeue?: string;
|
|
53
|
+
}) => {
|
|
54
|
+
const received: { method: string; params: unknown }[] = [];
|
|
55
|
+
const transport = resource(() => {
|
|
56
|
+
const [state] = useStatewireState<ServerState>(() => ({
|
|
57
|
+
messages: [{ id: "m1", role: "user", text: "hello" }],
|
|
58
|
+
status: "running",
|
|
59
|
+
runs: [{ runId: "run-1", status: "running", queue: [], steerQueue: [] }],
|
|
60
|
+
}));
|
|
61
|
+
const commands = useStatewireCommands({
|
|
62
|
+
"run/stop": (params: unknown) => {
|
|
63
|
+
received.push({ method: "run/stop", params });
|
|
64
|
+
const entry = state.runs[0]!;
|
|
65
|
+
entry.queue = opts.retract.queue ?? [];
|
|
66
|
+
entry.steerQueue = opts.retract.steer ?? [];
|
|
67
|
+
entry.status = "stopped";
|
|
68
|
+
state.status = "stopped";
|
|
69
|
+
state.messages = [];
|
|
70
|
+
return [...entry.queue, ...entry.steerQueue];
|
|
71
|
+
},
|
|
72
|
+
"run/dequeue": (params: { messageId: string }) => {
|
|
73
|
+
received.push({ method: "run/dequeue", params });
|
|
74
|
+
if (params.messageId === opts.rejectDequeue)
|
|
75
|
+
throw new StatewireReject("not yours", {
|
|
76
|
+
payload: { reason: "not-owner" },
|
|
77
|
+
});
|
|
78
|
+
const entry = state.runs[0]!;
|
|
79
|
+
entry.queue = entry.queue.filter((q) => q.id !== params.messageId);
|
|
80
|
+
entry.steerQueue = entry.steerQueue.filter(
|
|
81
|
+
(q) => q.id !== params.messageId,
|
|
82
|
+
);
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
return { state, commands };
|
|
86
|
+
})();
|
|
87
|
+
return { transport, received };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const mountThread = (
|
|
91
|
+
transport: ReturnType<typeof createServer>["transport"],
|
|
92
|
+
) => {
|
|
93
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
94
|
+
const Capture: FC = () => {
|
|
95
|
+
captured.aui = useAui();
|
|
96
|
+
return null;
|
|
97
|
+
};
|
|
98
|
+
const App: FC = () => {
|
|
99
|
+
const aui = useAui({
|
|
100
|
+
thread: StatewireThread<ServerState>({
|
|
101
|
+
initialState: { messages: [], status: "ready", runs: [] },
|
|
102
|
+
converter,
|
|
103
|
+
transport,
|
|
104
|
+
}),
|
|
105
|
+
});
|
|
106
|
+
return (
|
|
107
|
+
<AuiProvider value={aui}>
|
|
108
|
+
<Capture />
|
|
109
|
+
</AuiProvider>
|
|
110
|
+
);
|
|
111
|
+
};
|
|
112
|
+
render(<App />);
|
|
113
|
+
return () => captured.aui!;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const composerText = (aui: () => ReturnType<typeof useAui>) =>
|
|
117
|
+
aui().thread().composer().getState().text;
|
|
118
|
+
|
|
119
|
+
const dequeued = (received: { method: string; params: unknown }[]) =>
|
|
120
|
+
received
|
|
121
|
+
.filter((r) => r.method === "run/dequeue")
|
|
122
|
+
.map((r) => (r.params as { messageId: string }).messageId);
|
|
123
|
+
|
|
124
|
+
describe("StatewireThread retraction pop", () => {
|
|
125
|
+
it("dequeues the retracted items into the empty composer in thread order", async () => {
|
|
126
|
+
const server = createServer({
|
|
127
|
+
retract: {
|
|
128
|
+
queue: [item("m1", "hello")],
|
|
129
|
+
steer: [item("s1", "and this")],
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
const aui = mountThread(server.transport);
|
|
133
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
134
|
+
act(() => {
|
|
135
|
+
aui().thread().cancelRun();
|
|
136
|
+
});
|
|
137
|
+
await waitFor(() => expect(composerText(aui)).toBe("hello\n\nand this"));
|
|
138
|
+
expect(dequeued(server.received)).toEqual(["m1", "s1"]);
|
|
139
|
+
await waitFor(() => {
|
|
140
|
+
const runs = asStatewireExtras(aui().thread().getState().extras).runs;
|
|
141
|
+
expect([...runs.queue, ...runs.steerQueue]).toHaveLength(0);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("leaves the items queued while the composer holds text", async () => {
|
|
146
|
+
const server = createServer({ retract: { queue: [item("m1", "hello")] } });
|
|
147
|
+
const aui = mountThread(server.transport);
|
|
148
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
149
|
+
act(() => {
|
|
150
|
+
aui().thread().composer().setText("draft");
|
|
151
|
+
aui().thread().cancelRun();
|
|
152
|
+
});
|
|
153
|
+
await waitFor(() =>
|
|
154
|
+
expect(aui().thread().getState().isRunning).toBe(false),
|
|
155
|
+
);
|
|
156
|
+
await waitFor(() =>
|
|
157
|
+
expect(server.received.map((r) => r.method)).toEqual(["run/stop"]),
|
|
158
|
+
);
|
|
159
|
+
expect(composerText(aui)).toBe("draft");
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("keeps an item whose dequeue rejects and pops the rest", async () => {
|
|
163
|
+
const server = createServer({
|
|
164
|
+
retract: { queue: [item("m1", "mine")], steer: [item("s1", "theirs")] },
|
|
165
|
+
rejectDequeue: "s1",
|
|
166
|
+
});
|
|
167
|
+
const aui = mountThread(server.transport);
|
|
168
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
169
|
+
act(() => {
|
|
170
|
+
aui().thread().cancelRun();
|
|
171
|
+
});
|
|
172
|
+
await waitFor(() => expect(composerText(aui)).toBe("mine"));
|
|
173
|
+
expect(dequeued(server.received)).toEqual(["m1", "s1"]);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -125,8 +125,9 @@ const createServer = (init?: Partial<RunsServerState>) => {
|
|
|
125
125
|
// snapshot until `release()` to expose the pre-attach window.
|
|
126
126
|
const createRemoteServer = (
|
|
127
127
|
init?: Partial<RunsServerState>,
|
|
128
|
-
opts?: { hold?: boolean },
|
|
128
|
+
opts?: { hold?: boolean; protocol?: string },
|
|
129
129
|
) => {
|
|
130
|
+
const protocol = opts?.protocol ?? "default";
|
|
130
131
|
const received: { method: string; params: unknown[] }[] = [];
|
|
131
132
|
const clients = new Map<string, { seq: number; ctxSeq: number }>();
|
|
132
133
|
const encoder = new TextEncoder();
|
|
@@ -171,6 +172,7 @@ const createRemoteServer = (
|
|
|
171
172
|
if (url.endsWith("/stream")) {
|
|
172
173
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
173
174
|
const rec = clients.get(clientId)!;
|
|
175
|
+
rec.ctxSeq = 0;
|
|
174
176
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
175
177
|
const body = new ReadableStream<Uint8Array>({
|
|
176
178
|
start: (c) => {
|
|
@@ -184,16 +186,16 @@ const createRemoteServer = (
|
|
|
184
186
|
ops: [
|
|
185
187
|
{
|
|
186
188
|
op: "mount",
|
|
187
|
-
protocol
|
|
189
|
+
protocol,
|
|
188
190
|
main: true,
|
|
189
191
|
value: { ...INITIAL_STATE, ...init },
|
|
190
192
|
},
|
|
191
193
|
],
|
|
192
194
|
syn: {
|
|
193
195
|
seq: rec.seq,
|
|
194
|
-
ctxSeq:
|
|
196
|
+
ctxSeq: 0,
|
|
195
197
|
version: "2026-09-07",
|
|
196
|
-
protocols: [{ name:
|
|
198
|
+
protocols: [{ name: protocol, version: "2026-09-07" }],
|
|
197
199
|
},
|
|
198
200
|
}),
|
|
199
201
|
),
|
|
@@ -222,6 +224,7 @@ const createRemoteServer = (
|
|
|
222
224
|
transport: StatewireHttp<RunsServerState>({
|
|
223
225
|
url: "http://fake/api",
|
|
224
226
|
fetch: fetchImpl,
|
|
227
|
+
protocol,
|
|
225
228
|
}),
|
|
226
229
|
};
|
|
227
230
|
};
|
|
@@ -718,34 +721,41 @@ describe("StatewireThread runs mode", () => {
|
|
|
718
721
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
719
722
|
});
|
|
720
723
|
|
|
721
|
-
it(
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
724
|
+
it.each([undefined, "athena"])(
|
|
725
|
+
"preloads initialState: interactive before attach, sends fold in (protocol: %s)",
|
|
726
|
+
async (protocol) => {
|
|
727
|
+
const server = createRemoteServer(
|
|
728
|
+
{},
|
|
729
|
+
{ hold: true, ...(protocol !== undefined && { protocol }) },
|
|
730
|
+
);
|
|
731
|
+
const { aui, runs } = mountThread({
|
|
732
|
+
transport: server.transport,
|
|
733
|
+
materialize: rollbackMaterialize,
|
|
734
|
+
protocol,
|
|
735
|
+
});
|
|
727
736
|
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
737
|
+
expect(threadStatus(aui())).toBe("ready");
|
|
738
|
+
act(() => {
|
|
739
|
+
aui().thread().append("hello");
|
|
740
|
+
});
|
|
732
741
|
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
742
|
+
// The pre-attach send renders through the same optimistic + materialize
|
|
743
|
+
// folds; while connecting, the run presents as disconnected.
|
|
744
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
745
|
+
expect(runs().runId).toEqual(expect.any(String));
|
|
746
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
747
|
+
expect(server.received).toEqual([]);
|
|
739
748
|
|
|
740
|
-
|
|
749
|
+
server.release();
|
|
741
750
|
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
751
|
+
// Attach posts the queued command; the still-unapplied overlay survives the snapshot.
|
|
752
|
+
await waitFor(() =>
|
|
753
|
+
expect(server.received.map((c) => c.method)).toEqual(["run/enqueue"]),
|
|
754
|
+
);
|
|
755
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
756
|
+
expect(threadStatus(aui())).toBe("running");
|
|
757
|
+
},
|
|
758
|
+
);
|
|
749
759
|
|
|
750
760
|
it("preloads again after a transport swap on a persistent thread", async () => {
|
|
751
761
|
const serverA = createRemoteServer({
|
package/src/StatewireThread.ts
CHANGED
|
@@ -125,6 +125,7 @@ const useStatewireThread = (
|
|
|
125
125
|
): ClientOutput<"thread"> => {
|
|
126
126
|
const latest = useRef(options);
|
|
127
127
|
latest.current = options;
|
|
128
|
+
const retrying = useRef(new Set<string>());
|
|
128
129
|
|
|
129
130
|
const [pending, setPending] = useState<readonly StatewireThread.Command[]>(
|
|
130
131
|
[],
|
|
@@ -151,6 +152,7 @@ const useStatewireThread = (
|
|
|
151
152
|
onError: (error) => latest.current.onError?.(error),
|
|
152
153
|
storage: options.storage,
|
|
153
154
|
initialState: options.initialState,
|
|
155
|
+
...(options.protocol !== undefined && { protocol: options.protocol }),
|
|
154
156
|
optimistic: (draft, command, ctx) => {
|
|
155
157
|
runsOptimistic(draft, command, ctx);
|
|
156
158
|
latest.current.optimistic?.(draft, command, ctx);
|
|
@@ -243,6 +245,36 @@ const useStatewireThread = (
|
|
|
243
245
|
[dispatch],
|
|
244
246
|
);
|
|
245
247
|
|
|
248
|
+
// The stop verdict carries the run's retracted items; the stopping client
|
|
249
|
+
// dequeues them into an empty composer. Other clients see them queued.
|
|
250
|
+
const popRetracted = async (
|
|
251
|
+
retracted: unknown,
|
|
252
|
+
runId: string | null,
|
|
253
|
+
): Promise<void> => {
|
|
254
|
+
if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)
|
|
255
|
+
return;
|
|
256
|
+
const composerApi = threadRef.current!.composer();
|
|
257
|
+
if (composerApi.getState().text !== "") return;
|
|
258
|
+
const texts: string[] = [];
|
|
259
|
+
for (const item of retracted as StatewireThread.RunsQueueEntry[]) {
|
|
260
|
+
try {
|
|
261
|
+
await dispatch({ type: "run/dequeue", runId, messageId: item.id });
|
|
262
|
+
} catch {
|
|
263
|
+
continue; // rejected dequeue: the item stays queued
|
|
264
|
+
}
|
|
265
|
+
texts.push(
|
|
266
|
+
item.parts
|
|
267
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
268
|
+
.join("\n\n"),
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
if (texts.length === 0) return;
|
|
272
|
+
const setText = composerApi.setText as (
|
|
273
|
+
next: string | ((prev: string) => string),
|
|
274
|
+
) => void;
|
|
275
|
+
setText((prev) => [prev, ...texts].filter(Boolean).join("\n\n"));
|
|
276
|
+
};
|
|
277
|
+
|
|
246
278
|
const { status, runs } = useMemo((): {
|
|
247
279
|
status: StatewireThread.ThreadStatus;
|
|
248
280
|
runs: StatewireThread.Runs;
|
|
@@ -352,14 +384,24 @@ const useStatewireThread = (
|
|
|
352
384
|
inputRequests,
|
|
353
385
|
runs,
|
|
354
386
|
retryFailed: (messageId) => {
|
|
387
|
+
if (retrying.current.has(messageId)) return;
|
|
355
388
|
const entry = takeFailed(messageId);
|
|
356
389
|
const command = retryCommand(
|
|
357
390
|
messages,
|
|
358
391
|
liveRunId,
|
|
359
392
|
failedRunCommand(entry)!,
|
|
360
393
|
);
|
|
361
|
-
|
|
362
|
-
|
|
394
|
+
retrying.current.add(messageId);
|
|
395
|
+
const release = () => {
|
|
396
|
+
retrying.current.delete(messageId);
|
|
397
|
+
};
|
|
398
|
+
try {
|
|
399
|
+
discardFailed(entry);
|
|
400
|
+
void dispatch(command).then(release, release);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
release();
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
363
405
|
},
|
|
364
406
|
discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
|
|
365
407
|
popFailed: (messageId) => {
|
|
@@ -442,13 +484,16 @@ const useStatewireThread = (
|
|
|
442
484
|
Array.isArray(payload))
|
|
443
485
|
)
|
|
444
486
|
throw new Error("statewire: stopPayload must return a plain object");
|
|
487
|
+
const runId = runs.runId;
|
|
445
488
|
void commands["run/stop"]!({
|
|
446
489
|
...payload,
|
|
447
|
-
runId
|
|
490
|
+
runId,
|
|
448
491
|
...(runs.epoch !== undefined && { epoch: runs.epoch }),
|
|
449
|
-
})
|
|
450
|
-
|
|
451
|
-
|
|
492
|
+
})
|
|
493
|
+
.then((retracted) => popRetracted(retracted, runId))
|
|
494
|
+
.catch((error: Error) => {
|
|
495
|
+
latest.current.onError?.(error);
|
|
496
|
+
});
|
|
452
497
|
},
|
|
453
498
|
}),
|
|
454
499
|
);
|
|
@@ -846,6 +891,8 @@ export namespace StatewireThread {
|
|
|
846
891
|
transport: Transport<T>;
|
|
847
892
|
/** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
|
|
848
893
|
initialState: T;
|
|
894
|
+
/** Application protocol for optimistic commands; must match the transport's protocol. */
|
|
895
|
+
protocol?: string | undefined;
|
|
849
896
|
converter: StateConverter<T>;
|
|
850
897
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
851
898
|
optimistic?:
|
package/src/localStorage.test.ts
CHANGED
|
@@ -175,7 +175,6 @@ describe("LocalStorageSession", () => {
|
|
|
175
175
|
const record = {
|
|
176
176
|
clientId: "c-1",
|
|
177
177
|
nextSeq: 3,
|
|
178
|
-
ctxNextSeq: 1,
|
|
179
178
|
commands: [
|
|
180
179
|
{
|
|
181
180
|
seq: 2,
|
|
@@ -189,7 +188,7 @@ describe("LocalStorageSession", () => {
|
|
|
189
188
|
root.getValue().save(record);
|
|
190
189
|
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
|
|
191
190
|
...record,
|
|
192
|
-
statewireStorageVersion:
|
|
191
|
+
statewireStorageVersion: 2,
|
|
193
192
|
savedAt: expect.any(Number),
|
|
194
193
|
});
|
|
195
194
|
expect(root.getValue().load()).toEqual(record);
|
|
@@ -203,26 +202,22 @@ describe("LocalStorageSession", () => {
|
|
|
203
202
|
JSON.stringify({
|
|
204
203
|
clientId: "c-1",
|
|
205
204
|
nextSeq: 1,
|
|
206
|
-
ctxNextSeq: 1,
|
|
207
205
|
commands: "invalid",
|
|
208
206
|
}),
|
|
209
207
|
JSON.stringify({
|
|
210
208
|
clientId: "c-1",
|
|
211
209
|
nextSeq: 2,
|
|
212
|
-
ctxNextSeq: 1,
|
|
213
210
|
commands: [{ seq: 1, method: "run", params: null, meta: {} }],
|
|
214
211
|
}),
|
|
215
212
|
JSON.stringify({
|
|
216
213
|
clientId: "c-1",
|
|
217
214
|
nextSeq: 1,
|
|
218
|
-
ctxNextSeq: 1,
|
|
219
215
|
commands: [],
|
|
220
216
|
verdicts: [{ seq: 1, type: "future" }],
|
|
221
217
|
}),
|
|
222
218
|
JSON.stringify({
|
|
223
219
|
clientId: "c-1",
|
|
224
220
|
nextSeq: 1,
|
|
225
|
-
ctxNextSeq: 1,
|
|
226
221
|
commands: [],
|
|
227
222
|
failed: [
|
|
228
223
|
{
|
|
@@ -247,7 +242,6 @@ describe("LocalStorageSession", () => {
|
|
|
247
242
|
root.getValue().save({
|
|
248
243
|
clientId: "c-1",
|
|
249
244
|
nextSeq: 1,
|
|
250
|
-
ctxNextSeq: 1,
|
|
251
245
|
commands: [],
|
|
252
246
|
});
|
|
253
247
|
expect(localStorage.getItem(`${SESSION_PREFIX}user-42:t1`)).not.toBeNull();
|
|
@@ -307,7 +301,6 @@ describe("LocalStorageSession", () => {
|
|
|
307
301
|
JSON.stringify({
|
|
308
302
|
clientId: key,
|
|
309
303
|
nextSeq: 1,
|
|
310
|
-
ctxNextSeq: 1,
|
|
311
304
|
commands: [],
|
|
312
305
|
savedAt: 1,
|
|
313
306
|
}),
|