@assistant-ui/react-statewire 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -163,6 +163,10 @@ declare namespace StatewireThread {
|
|
|
163
163
|
* runs for commands it declined.
|
|
164
164
|
*/
|
|
165
165
|
onCommandSessionLost?: ((command: StatewireClient.SessionLostCommand) => "replay" | void) | undefined;
|
|
166
|
+
/** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
|
|
167
|
+
onCommandChange?: ((update: Statewire.CommandUpdate<Record<string, (...args: any[]) => unknown>>, ctx: {
|
|
168
|
+
state: NonNullable<T>;
|
|
169
|
+
}) => void) | undefined;
|
|
166
170
|
onError?: ((error: Error) => void) | undefined;
|
|
167
171
|
capabilities?: {
|
|
168
172
|
edit?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA6Ra,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;cACC,cAAc;;;OAId,eACR,uBACA,2BACA;OAEQ;aACD,QAAQ;;aAER;aACA,WAAW;;OAGV;aACD;aACA,aAAa;aACb;;OAGC,gBAAgB;OAEhB;aACD;aACA;aACA,UAAU;;;OAIT,oBAAoB;aACrB,UAAU;;OAGT;aACD;aACA;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;;;;;;aAOtB,yBAAyB;;OAGxB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;OAGlB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;;IAEA,qBAAqB;;;;;;;IAOrB,yBACM,SAAS,gBAAgB;;IAG/B,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;IAGhC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -33,8 +33,9 @@ const useStatewireThread = (options) => {
|
|
|
33
33
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
34
34
|
const { state: transportState, commands, connection, setContext } = useStatewire({
|
|
35
35
|
transport: options.onCommandSessionLost === void 0 ? options.transport : withSessionLostFallback(options.transport, latest),
|
|
36
|
-
onCommandChange: (update) => {
|
|
36
|
+
onCommandChange: (update, ctx) => {
|
|
37
37
|
if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
|
|
38
|
+
latest.current.onCommandChange?.(update, ctx);
|
|
38
39
|
}
|
|
39
40
|
});
|
|
40
41
|
const attached = transportState !== void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","length","Error","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","messages","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","message","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","sourceId","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\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 withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\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: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, queueItems, steerQueueItems, dispatch],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n });\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\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 export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\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 initialState: T;\n converter: StateConverter<T>;\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 /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\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":";;;;;;;;;;AAuCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrB,kBAAkBkB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAUT;CAI9C,IACEgB,KAAKC,SAAS,KACd,OAAOF,qBAAqB,YAC5BA,qBAAqB,MAErB,MAAM,IAAIG,MACR,iGACF;CAEF,MAAMC,iBAAiBJ,iBAAiBK;CAGxC,OAAO;EACL,GAAGX;EACHT,MAAM,CACJ;GACE,GAAGe;GACHK,uBACEC,YAEAF,iBAAiBE,O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,CAAC,EACnD;EACA,GAAItC,QAAQwE,cAAcK,UAAU,EAAEC,UAAUhB,aAAa;EAC7D,GAAIV,kBAAkBxE,KAAAA,KAAa;GACjCmG,kBAAkBC,gBAChB3C,SAASjE,uBAAuBgF,eAAe4B,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7C,SAASlE,yBAAyBiF,eAAe8B,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUhG,OAAOC,QAAQgG,cAAc;GAC7C,IACED,YAAYxG,KAAAA,MACX,OAAOwG,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI1F,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAI0F,YAAYxG,KAAAA,IAAY,CAAA,IAAK,CAACwG,OAAO,CAC3C,CAAC,CAACnD,OAAOC,YAAiB;IACxB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAahD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAgOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC0J,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","ModelContext","RespondToToolApprovalOptions","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","createRunQueueAdapter","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","AssistantTransportCommand","AnyCommands","Record","args","ambientContextOf","context","system","undefined","tools","callSettings","config","withSessionLostFallback","transport","StatewireThread","Transport","latest","current","Options","transportOptions","rest","length","Error","transportLevel","onCommandSessionLost","command","SessionLostCommand","useStatewireThread","options","pending","setPending","Command","retire","prev","includes","filter","c","state","transportState","commands","connection","setContext","onCommandChange","update","ctx","status","params","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","queueItems","queue","steerQueueItems","steerQueue","queueSeam","present","messages","inputRequests","inputSeam","extras","sendCommand","reconnect","handleAppend","message","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","sourceId","isRunning","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","TextPart","text","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","State","ConnectionState","StateConverter","connectionMetadata","StopPayload","reason","CommandUpdate","NonNullable","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\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 withSessionLostFallback = (\n transport: StatewireThread.Transport<any>,\n latest: { current: StatewireThread.Options<any> },\n): StatewireThread.Transport<any> => {\n const [transportOptions, ...rest] = transport.args as [\n Record<string, unknown>,\n ...unknown[],\n ];\n if (\n rest.length > 0 ||\n typeof transportOptions !== \"object\" ||\n transportOptions === null\n ) {\n throw new Error(\n \"statewire: onCommandSessionLost requires a transport element that takes a single options object\",\n );\n }\n const transportLevel = transportOptions.onCommandSessionLost as\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n return {\n ...transport,\n args: [\n {\n ...transportOptions,\n onCommandSessionLost: (\n command: StatewireClient.SessionLostCommand,\n ): \"replay\" | void =>\n transportLevel?.(command) ??\n latest.current.onCommandSessionLost?.(command),\n },\n ],\n };\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: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport:\n options.onCommandSessionLost === undefined\n ? options.transport\n : withSessionLostFallback(options.transport, latest),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n }),\n [pending, connection],\n );\n const converted = useMemo(\n () => converter(state, metadata),\n [converter, state, metadata],\n );\n const queueItems = converted.queue;\n const steerQueueItems = converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n converted.messages,\n queueItems,\n steerQueueItems,\n dispatch,\n )\n : undefined,\n [converted.messages, queueItems, steerQueueItems, dispatch],\n );\n\n const inputRequests = converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n }),\n [dispatch, connection.reconnect, state, inputRequests],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(converted.messages),\n });\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(converted.messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n dispatch({\n type: \"run/edit\",\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n });\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!(\n ...(payload === undefined ? [] : [payload]),\n ).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\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 export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type ToolCallInputResponse = {\n readonly output: ReadonlyJSONValue;\n /** Default false; when true, `output` carries the error payload. */\n readonly isError?: boolean;\n readonly artifact?: ReadonlyJSONValue;\n };\n\n export type ToolApprovalInputResponse = {\n readonly decision: \"approve\" | \"reject\" | \"edit\" | \"respond\";\n readonly editedArgs?: ReadonlyJSONValue;\n readonly message?: string;\n };\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state with its response echo. */\n export type InputRequestState = InputRequest & {\n readonly response: InputResponse | null;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n readonly sourceId: string;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = AssistantTransportCommand | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\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 initialState: T;\n converter: StateConverter<T>;\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 /**\n * Offered each pending command when a remote transport's session is\n * evicted; return \"replay\" to re-enqueue it under the rotated client id.\n * A callback set on the transport options is consulted first; this one\n * runs for commands it declined.\n */\n onCommandSessionLost?:\n | ((command: StatewireClient.SessionLostCommand) => \"replay\" | void)\n | undefined;\n /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\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":";;;;;;;;;;AAuCA,MAAMqC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOrB,kBAAkBkB,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,2BACJC,WACAG,WACmC;CACnC,MAAM,CAACG,kBAAkB,GAAGC,QAAQP,UAAUT;CAI9C,IACEgB,KAAKC,SAAS,KACd,OAAOF,qBAAqB,YAC5BA,qBAAqB,MAErB,MAAM,IAAIG,MACR,iGACF;CAEF,MAAMC,iBAAiBJ,iBAAiBK;CAGxC,OAAO;EACL,GAAGX;EACHT,MAAM,CACJ;GACE,GAAGe;GACHK,uBACEC,YAEAF,iBAAiBE,OAAO,KACxBT,OAAOC,QAAQO,uBAAuBC,OAAO;EACjD,CAAC;CAEL;AACF;AAEA,MAAME,sBACJC,YAC2B;CAC3B,MAAMZ,SAAS7C,OAAOyD,OAAO;CAC7BZ,OAAOC,UAAUW;CAEjB,MAAM,CAACC,SAASC,cAAc1D,SAC5B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SAASlE,uBAAuBiF,eAAe4B,WAAW,CAAC;GAC7DC,0BAA0BC,aACxB7C,SAASnE,yBAAyBkF,eAAe8B,QAAQ,CAAC;EAC9D;EACAC,gBAAgB;GACd,MAAMC,UAAUjG,OAAOC,QAAQiG,cAAc;GAC7C,IACED,YAAYzG,KAAAA,MACX,OAAOyG,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI3F,MAAM,mDAAmD;GACrE,SAAc,WAAW,CACvB,GAAI2F,YAAYzG,KAAAA,IAAY,CAAA,IAAK,CAACyG,OAAO,CAC3C,CAAC,CAACnD,OAAOC,YAAiB;IACxB/C,OAAOC,QAAQ+C,UAAUD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAajD,mBACXc,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AAyOtElD,uBACEiD,oBACAnD,eAAegC,KAAAA,CAAkB,CAAC,CAAC6J,IACrC"}
|
package/package.json
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
useStatewireState,
|
|
16
16
|
} from "statewire/host";
|
|
17
17
|
import { createMockTransport } from "statewire/testing";
|
|
18
|
+
import type { Statewire } from "statewire";
|
|
18
19
|
import { StatewireThread } from "./StatewireThread";
|
|
19
20
|
import { asAssistantTransportExtras } from "./AssistantTransportThread";
|
|
20
21
|
import { useAssistantTransportState } from "./hooks";
|
|
@@ -401,6 +402,43 @@ describe("StatewireThread", () => {
|
|
|
401
402
|
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
402
403
|
});
|
|
403
404
|
|
|
405
|
+
it("reports the command lifecycle through onCommandChange after retiring the pending command", async () => {
|
|
406
|
+
const server = createServer();
|
|
407
|
+
const updates: Statewire.CommandUpdate<
|
|
408
|
+
Record<string, (...args: any[]) => unknown>
|
|
409
|
+
>[] = [];
|
|
410
|
+
const states: ServerState[] = [];
|
|
411
|
+
const metas: StatewireThread.ConnectionMetadata[] = [];
|
|
412
|
+
const { aui } = mountThread({
|
|
413
|
+
transport: server.transport,
|
|
414
|
+
converter: (state, meta) => {
|
|
415
|
+
metas.push(meta);
|
|
416
|
+
return converter(state, meta);
|
|
417
|
+
},
|
|
418
|
+
onCommandChange: (update, ctx) => {
|
|
419
|
+
updates.push(update);
|
|
420
|
+
states.push(ctx.state);
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
aui().thread().append("hello");
|
|
425
|
+
|
|
426
|
+
await waitFor(() =>
|
|
427
|
+
expect(updates.map((u) => u.status)).toEqual([
|
|
428
|
+
"queued",
|
|
429
|
+
"posted",
|
|
430
|
+
"acked",
|
|
431
|
+
"settled",
|
|
432
|
+
]),
|
|
433
|
+
);
|
|
434
|
+
expect(updates.at(-1)).toMatchObject({
|
|
435
|
+
method: "run/steer",
|
|
436
|
+
params: [{ type: "run/steer" }],
|
|
437
|
+
});
|
|
438
|
+
expect(states.at(-1)!.messages.map((m) => m.text)).toEqual(["hello"]);
|
|
439
|
+
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
440
|
+
});
|
|
441
|
+
|
|
404
442
|
describe("contextSync: command-send", () => {
|
|
405
443
|
const contextValueOf = (command: { context?: unknown }) => {
|
|
406
444
|
const ops = command.context as [
|
package/src/StatewireThread.ts
CHANGED
|
@@ -111,9 +111,10 @@ const useStatewireThread = (
|
|
|
111
111
|
options.onCommandSessionLost === undefined
|
|
112
112
|
? options.transport
|
|
113
113
|
: withSessionLostFallback(options.transport, latest),
|
|
114
|
-
onCommandChange: (update) => {
|
|
114
|
+
onCommandChange: (update, ctx) => {
|
|
115
115
|
if (update.status === "acked" || update.status === "settled")
|
|
116
116
|
retire(update.params[0]);
|
|
117
|
+
latest.current.onCommandChange?.(update, ctx);
|
|
117
118
|
},
|
|
118
119
|
});
|
|
119
120
|
const attached = transportState !== undefined;
|
|
@@ -490,6 +491,15 @@ export namespace StatewireThread {
|
|
|
490
491
|
onCommandSessionLost?:
|
|
491
492
|
| ((command: StatewireClient.SessionLostCommand) => "replay" | void)
|
|
492
493
|
| undefined;
|
|
494
|
+
/** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
|
|
495
|
+
onCommandChange?:
|
|
496
|
+
| ((
|
|
497
|
+
update: Statewire.CommandUpdate<
|
|
498
|
+
Record<string, (...args: any[]) => unknown>
|
|
499
|
+
>,
|
|
500
|
+
ctx: { state: NonNullable<T> },
|
|
501
|
+
) => void)
|
|
502
|
+
| undefined;
|
|
493
503
|
onError?: ((error: Error) => void) | undefined;
|
|
494
504
|
capabilities?:
|
|
495
505
|
| {
|