@assistant-ui/react-statewire 0.10.0 → 0.11.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 -1
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +15 -9
- package/dist/StatewireThread.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.runs.test.tsx +148 -17
- package/src/StatewireThread.test.tsx +1 -1
- package/src/StatewireThread.ts +35 -21
|
@@ -232,7 +232,8 @@ declare namespace StatewireThread {
|
|
|
232
232
|
};
|
|
233
233
|
type Options<T> = {
|
|
234
234
|
transport: Transport<T>;
|
|
235
|
-
|
|
235
|
+
/** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */
|
|
236
|
+
initialState?: T | undefined;
|
|
236
237
|
converter: StateConverter<T>;
|
|
237
238
|
runs?: undefined;
|
|
238
239
|
/**
|
|
@@ -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":";;;;;;;cA6Xa;GACV,GACC,SAAS,gBAAgB,YAAY,KACpC,gBAAgB;GAClB,GACC,SAAS,gBAAgB,QAAQ,KAChC,gBAAgB;;kBAIJ;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;;aAGI,SAAS;;aAET;;aAEA;OAEb;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;aAEA;;OAGC;aACD;;OAGC;aACD;aACA;aACA;;OAGC;aACD;aACA;aACA;;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MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;OAMP,YAAY,KAAK,KAAK,QAAQ;;IAExC,eAAe,OAAO;IACtB,WAAW,mBAAmB;;IAE9B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;YAK9C;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -9,6 +9,10 @@ import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/sto
|
|
|
9
9
|
import { useStatewire } from "statewire";
|
|
10
10
|
import { toToolsJSONSchema } from "assistant-stream";
|
|
11
11
|
//#region src/StatewireThread.ts
|
|
12
|
+
const LOADING_STATE = {
|
|
13
|
+
messages: [],
|
|
14
|
+
isRunning: false
|
|
15
|
+
};
|
|
12
16
|
const READY_RUNS = {
|
|
13
17
|
status: "ready",
|
|
14
18
|
runId: null,
|
|
@@ -34,8 +38,9 @@ const useStatewireThread = (options) => {
|
|
|
34
38
|
const materializeOption = options.materialize;
|
|
35
39
|
const [materializeSeam] = useState(() => materializeOption !== void 0);
|
|
36
40
|
if (materializeSeam !== (materializeOption !== void 0)) throw new Error("statewire: the materialize option must be stable — it was " + (materializeSeam ? "set" : "unset") + " on first render and changed since");
|
|
37
|
-
const { state:
|
|
41
|
+
const { state: state_0, commands, connection: connection_0, setContext } = useStatewire({
|
|
38
42
|
transport: options.transport,
|
|
43
|
+
initialState: options.initialState,
|
|
39
44
|
...runsSeam && { optimistic: (draft, command_0, ctx) => {
|
|
40
45
|
const runsOpt = latest.current.runs;
|
|
41
46
|
runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command_0, ctx);
|
|
@@ -49,8 +54,6 @@ const useStatewireThread = (options) => {
|
|
|
49
54
|
onStateChange: (state, ctx_1) => latest.current.onStateChange?.(state, ctx_1),
|
|
50
55
|
onConnectionChange: (connection) => latest.current.onConnectionChange?.(connection)
|
|
51
56
|
});
|
|
52
|
-
const attached = transportState !== void 0;
|
|
53
|
-
const state_0 = attached ? transportState : options.initialState;
|
|
54
57
|
const clientRef = useAssistantClientRef();
|
|
55
58
|
const setContextRef = useRef(setContext);
|
|
56
59
|
setContextRef.current = setContext;
|
|
@@ -96,6 +99,7 @@ const useStatewireThread = (options) => {
|
|
|
96
99
|
}, [dispatch]);
|
|
97
100
|
const runs = useMemo(() => {
|
|
98
101
|
if (runsOption === void 0) return void 0;
|
|
102
|
+
if (state_0 === void 0) return READY_RUNS;
|
|
99
103
|
const entry = (runsOption === true ? state_0 : runsOption(state_0))?.runs?.[0];
|
|
100
104
|
return entry === void 0 ? READY_RUNS : {
|
|
101
105
|
status: entry.status,
|
|
@@ -118,7 +122,7 @@ const useStatewireThread = (options) => {
|
|
|
118
122
|
connection_0,
|
|
119
123
|
runs
|
|
120
124
|
]);
|
|
121
|
-
const converted = useMemo(() => converter(state_0, metadata), [
|
|
125
|
+
const converted = useMemo(() => state_0 === void 0 ? LOADING_STATE : converter(state_0, metadata), [
|
|
122
126
|
converter,
|
|
123
127
|
state_0,
|
|
124
128
|
metadata
|
|
@@ -127,8 +131,9 @@ const useStatewireThread = (options) => {
|
|
|
127
131
|
const queueItems = runs !== void 0 ? runs.queue : converted.queue;
|
|
128
132
|
const steerQueueItems = runs !== void 0 ? runs.steerQueue : converted.steerQueue;
|
|
129
133
|
if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
|
|
130
|
-
const [queueSeam] = useState(() => ({ present:
|
|
131
|
-
if (
|
|
134
|
+
const [queueSeam] = useState(() => ({ present: void 0 }));
|
|
135
|
+
if (state_0 !== void 0 && queueSeam.present === void 0) queueSeam.present = queueItems !== void 0;
|
|
136
|
+
if (queueSeam.present !== void 0 && queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
132
137
|
const queue = useMemo(() => queueItems ? createRunQueueAdapter(messages, queueItems, steerQueueItems, dispatch, dispatchSend) : void 0, [
|
|
133
138
|
messages,
|
|
134
139
|
queueItems,
|
|
@@ -137,8 +142,9 @@ const useStatewireThread = (options) => {
|
|
|
137
142
|
dispatchSend
|
|
138
143
|
]);
|
|
139
144
|
const inputRequests = runs !== void 0 ? runs.inputRequests ?? [] : converted.inputRequests;
|
|
140
|
-
const [inputSeam] = useState(() => ({ present:
|
|
141
|
-
if (
|
|
145
|
+
const [inputSeam] = useState(() => ({ present: void 0 }));
|
|
146
|
+
if (state_0 !== void 0 && inputSeam.present === void 0) inputSeam.present = inputRequests !== void 0;
|
|
147
|
+
if (inputSeam.present !== void 0 && inputSeam.present !== (inputRequests !== void 0)) throw new Error("statewire: the converter's inputRequests projection must be stable — it was " + (inputSeam.present ? "defined" : "undefined") + " on first convert and changed since");
|
|
142
148
|
const extras = useMemo(() => ({
|
|
143
149
|
[symbolAssistantTransportExtras]: true,
|
|
144
150
|
sendCommand: dispatch,
|
|
@@ -169,7 +175,7 @@ const useStatewireThread = (options) => {
|
|
|
169
175
|
const thread = useResource(ExternalThread({
|
|
170
176
|
messages,
|
|
171
177
|
isRunning: runs !== void 0 ? runs.status === "running" : converted.isRunning,
|
|
172
|
-
isLoading:
|
|
178
|
+
isLoading: state_0 === void 0,
|
|
173
179
|
state: converted.state,
|
|
174
180
|
extras,
|
|
175
181
|
attachmentAdapter: options.adapters?.attachments,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","transportState","commands","connection","setContext","transport","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","attached","initialState","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isRunning","isLoading","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","MaterializeEffects","append","rollback","to","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const {\n state: transportState,\n commands,\n connection,\n setContext,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n const attached = transportState !== undefined;\n const state = attached ? transportState : options.initialState;\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n () =>\n converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State,\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n const [queueSeam] = useState(() => ({\n present: queueItems !== undefined,\n }));\n if (queueSeam.present !== (queueItems !== undefined))\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: inputRequests !== undefined,\n }));\n if (inputSeam.present !== (inputRequests !== undefined))\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: !attached,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: 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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** 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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n initialState: T;\n converter: StateConverter<T>;\n runs?: undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** 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}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAiDA,MAAM6C,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOnC,kBAAkBgC,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS3D,OAAO0D,OAAO;CA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AAU1F;GAC1D,MAAMR,OACJQ,UAAUQ,KAAAA,IACN2H,YAAY3H,KAAAA,IACV,CAAA,IACA,CAAC2H,OAAO,IACV,CAAC;IAAE,GAAGA;IAASnI;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGR,IAAI,CAAC,CAACsE,OAAO1D,YAAiB;IAC1DU,OAAOC,QAAQgD,UAAU3D,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACAgE,UAAUrD,UAAU6F;CACpB,OAAOA;AACT;AAEA,MAAalH,mBAORmB,YACHxD,SAASuD,kBAAkB,CAAC,CAACC,OAAO;AAoXtCnD,uBACEkD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAAC+M,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","ExternalThreadQueueAdapter","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportThread","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","toWireMessage","viewedLeafId","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","AnyOptions","StatewireThread","Options","RunsOptions","LOADING_STATE","State","messages","isRunning","READY_RUNS","Runs","status","runId","queue","steerQueue","dispatching","error","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","runsOption","runs","runsSeam","Error","materializeOption","materialize","materializeSeam","state","commands","connection","setContext","transport","initialState","optimistic","draft","ctx","runsOpt","onCommandChange","update","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","onError","subscribe","dispatch","settled","type","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","mount","RunsState","entry","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","queueItems","steerQueueItems","queueSeam","present","inputSeam","extras","sendCommand","reconnect","handleAppend","crypto","randomUUID","anchorMessageId","handleReload","parentId","handleEdit","thread","isLoading","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","T","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","rollbackTo","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","ToolCallInputResponse","output","isError","artifact","ToolApprovalInputResponse","decision","editedArgs","InputResponse","RunInputCommand","requestId","response","InputRequestState","RunReloadCommand","RunCommand","QueueItem","RunStatus","RunsQueueEntry","meta","RunsInputOutcome","request","RunsDispatch","trigger","inputOutcomes","RunsError","RunState","Exclude","MaterializeEffects","append","rollback","to","ConnectionState","StateConverter","connectionMetadata","RunsConverterState","RunsStateConverter","StopPayload","reason","CommandUpdate","NonNullable","changes","Changes","Connection","Omit","Optimistic","Materialize","Assistant","Commands","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n ExternalThreadQueueAdapter,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport { symbolAssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type {\n AssistantTransportExtras,\n AssistantTransportThread,\n} from \"./AssistantTransportThread\";\nimport {\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n toWireMessage,\n viewedLeafId,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\ntype AnyOptions =\n | StatewireThread.Options<any>\n | StatewireThread.RunsOptions<any>;\n\nconst LOADING_STATE: StatewireThread.State = { messages: [], isRunning: false };\n\nconst READY_RUNS: StatewireThread.Runs = {\n status: \"ready\",\n runId: null,\n queue: [],\n steerQueue: [],\n dispatching: null,\n error: null,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (options: AnyOptions): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const runsOption = options.runs;\n const [runsSeam] = useState(() => runsOption !== undefined);\n if (runsSeam !== (runsOption !== undefined))\n throw new Error(\n \"statewire: the runs option must be stable — it was \" +\n (runsSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const materializeOption = (options as StatewireThread.RunsOptions<unknown>)\n .materialize;\n const [materializeSeam] = useState(() => materializeOption !== undefined);\n if (materializeSeam !== (materializeOption !== undefined))\n throw new Error(\n \"statewire: the materialize option must be stable — it was \" +\n (materializeSeam ? \"set\" : \"unset\") +\n \" on first render and changed since\",\n );\n\n const { state, commands, connection, setContext } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n initialState: options.initialState,\n ...(runsSeam && {\n optimistic: (draft, command, ctx) => {\n const runsOpt = latest.current.runs!;\n runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);\n (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(\n draft,\n command,\n ctx,\n );\n },\n }),\n ...(materializeSeam && {\n materialize: (draft: {}) =>\n (latest.current as StatewireThread.RunsOptions<unknown>).materialize!(\n draft,\n ),\n }),\n onCommandChange: (update, ctx) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const runs = useMemo((): StatewireThread.Runs | undefined => {\n if (runsOption === undefined) return undefined;\n if (state === undefined) return READY_RUNS;\n const mount = (runsOption === true ? state : runsOption(state)) as\n | StatewireThread.RunsState\n | undefined;\n const entry = mount?.runs?.[0];\n return entry === undefined\n ? READY_RUNS\n : {\n status: entry.status,\n runId: entry.runId,\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n dispatching: entry.dispatching,\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n error: entry.error,\n };\n }, [runsOption, state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n ...(runs !== undefined && { runs }),\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State =>\n state === undefined\n ? LOADING_STATE\n : (converter(\n state,\n metadata as StatewireThread.ConnectionMetadata & {\n runs: StatewireThread.Runs;\n },\n ) as StatewireThread.State),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const queueItems = runs !== undefined ? runs.queue : converted.queue;\n const steerQueueItems =\n runs !== undefined ? runs.steerQueue : converted.steerQueue;\n if (steerQueueItems !== undefined && queueItems === undefined)\n throw new Error(\n \"statewire: the converter's steerQueue projection requires the queue projection\",\n );\n // Seams anchor at the first real convert; the loading placeholder projects nothing.\n const [queueSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && queueSeam.present === undefined)\n queueSeam.present = queueItems !== undefined;\n if (\n queueSeam.present !== undefined &&\n queueSeam.present !== (queueItems !== undefined)\n )\n throw new Error(\n \"statewire: the converter's queue projection must be stable — it was \" +\n (queueSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const queue = useMemo(\n (): ExternalThreadQueueAdapter | undefined =>\n queueItems\n ? createRunQueueAdapter(\n messages,\n queueItems,\n steerQueueItems,\n dispatch,\n dispatchSend,\n )\n : undefined,\n [messages, queueItems, steerQueueItems, dispatch, dispatchSend],\n );\n\n const inputRequests =\n runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;\n const [inputSeam] = useState(() => ({\n present: undefined as boolean | undefined,\n }));\n if (state !== undefined && inputSeam.present === undefined)\n inputSeam.present = inputRequests !== undefined;\n if (\n inputSeam.present !== undefined &&\n inputSeam.present !== (inputRequests !== undefined)\n )\n throw new Error(\n \"statewire: the converter's inputRequests projection must be stable — it was \" +\n (inputSeam.present ? \"defined\" : \"undefined\") +\n \" on first convert and changed since\",\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n ...(inputRequests !== undefined && { inputRequests }),\n ...(runs !== undefined && { runs }),\n }),\n [dispatch, connection.reconnect, state, inputRequests, runs],\n );\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message)\n : {\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning:\n runs !== undefined ? runs.status === \"running\" : converted.isRunning,\n isLoading: state === undefined,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n ...(queue && { queue }),\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () => dispatch({ type: \"run/continue\" }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(inputRequests !== undefined && {\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval)),\n }),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs !== undefined ? runs.runId : converted.runId;\n const args =\n runId === undefined\n ? payload === undefined\n ? []\n : [payload]\n : [{ ...payload, runId }];\n void commands[\"run/stop\"]!(...args).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n return thread;\n};\n\nexport const StatewireThread: {\n <T>(\n options: StatewireThread.RunsOptions<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n <T>(\n options: StatewireThread.Options<T>,\n ): ResourceElement<ClientOutput<\"thread\">>;\n} = (options: AnyOptions): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunSteerCommand = {\n readonly type: \"run/steer\";\n } & (\n | {\n readonly message: UserMessage;\n /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */\n readonly anchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: string | null;\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 /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly rollbackTo: 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 = AssistantTransportThread.Command | RunCommand;\n\n /** A queued message projected out of the host state, wire shape. */\n export type QueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n /** The live run's id projected out of the host state; stamped onto `run/stop`. */\n readonly runId?: string | null;\n /**\n * The host's regular queue lane projected out of the state. Returning it\n * (even empty) turns on the queue capability: sends become `run/enqueue`\n * / `run/steer` commands and item controls send the `run/*` queue\n * commands. Presence must be stable across conversions.\n */\n readonly queue?: readonly QueueItem[];\n /** The host's steer lane; requires `queue`. Absent means empty. */\n readonly steerQueue?: readonly QueueItem[];\n /**\n * The host's parked input requests projected out of the state. Returning\n * it (even empty) routes tool results and approvals with a matching\n * pending request through `run/input`. Presence must be stable across\n * conversions.\n */\n readonly inputRequests?: readonly InputRequestState[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus =\n | \"ready\"\n | \"running\"\n | \"stopped\"\n | \"error\"\n | \"input-required\";\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unacked batch handed to the run; null between the ack and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** Present when input outcomes ride the dispatch; visible until the ack. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */\n readonly runId: string | null;\n readonly status: Exclude<RunStatus, \"ready\">;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n /** 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: RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */\n export type Runs = {\n readonly status: RunStatus;\n /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */\n readonly runId: string | null;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unacked batch handed to the run, cleared at the ack. */\n readonly dispatching: RunsDispatch | null;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n readonly error: RunsError | null;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read; present iff the `runs` option is set. */\n runs?: Runs;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */\n export type RunsConverterState = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type RunsStateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata & { runs: Runs },\n ) => RunsConverterState;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */\n initialState?: T | undefined;\n converter: StateConverter<T>;\n runs?: undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n\n /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */\n export type RunsOptions<T> = Omit<Options<T>, \"converter\" | \"runs\"> & {\n /** `true` reads the run mounts off the state root; a selector picks a nested mount. */\n runs: true | ((state: T) => unknown);\n converter: RunsStateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** 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}\n\ndeclare module \"@assistant-ui/react\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;;AAiDA,MAAM6C,gBAAuC;CAAEE,UAAU,CAAA;CAAIC,WAAW;AAAM;AAE9E,MAAMC,aAAmC;CACvCE,QAAQ;CACRC,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,aAAa;CACbC,OAAO;AACT;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOvC,kBAAkBoC,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBAAsBC,YAAgD;CAC1E,MAAMC,SAAS/D,OAAO8D,OAAO;CAC7BC,OAAOC,UAAUF;CAEjB,MAAM,CAACG,SAASC,cAAcjE,SAC5B,CAAA,CACF;CACA,MAAM,CAACmE,UAAUnE,gBACRoE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAMI,aAAaZ,QAAQa;CAC3B,MAAM,CAACC,YAAY3E,eAAeyE,eAAejB,KAAAA,CAAS;CAC1D,IAAImB,c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UQ,KAAAA,IACNsH,YAAYtH,KAAAA,IACV,CAAA,IACA,CAACsH,OAAO,IACV,CAAC;IAAE,GAAGA;IAAS9H;GAAM,CAAC;GAC5B,SAAc,WAAW,CAAE,GAAGZ,IAAI,CAAC,CAACwE,OAAOxD,YAAiB;IAC1DU,OAAOC,QAAQ8C,UAAUzD,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;CACA8D,UAAUnD,UAAUyF;CACpB,OAAOA;AACT;AAEA,MAAalH,mBAORuB,YACH5D,SAAS2D,kBAAkB,CAAC,CAACC,OAAO;AAqXtCvD,uBACEsD,oBACAxD,eAAeoD,KAAAA,CAAkB,CAAC,CAAC0M,IACrC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@assistant-ui/store": "^0.3.0",
|
|
35
35
|
"@assistant-ui/tap": "^0.9.7",
|
|
36
36
|
"assistant-stream": "^0.3.33",
|
|
37
|
-
"statewire": "^0.
|
|
37
|
+
"statewire": "^0.8.1"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"@assistant-ui/react": ">=0.15.6",
|
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
// run-dialect optimistic reducer.
|
|
6
6
|
|
|
7
7
|
import { act, render, waitFor } from "@testing-library/react";
|
|
8
|
+
import { useState } from "react";
|
|
8
9
|
import type { FC } from "react";
|
|
9
10
|
import { describe, expect, it } from "vitest";
|
|
10
11
|
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
|
-
import { resource } from "@assistant-ui/tap";
|
|
12
|
+
import { resource, withKey } from "@assistant-ui/tap";
|
|
12
13
|
import { StatewireSSE } from "statewire";
|
|
13
14
|
import { useStatewireCommands, useStatewireState } from "statewire/host";
|
|
14
15
|
import { StatewireThread } from "./StatewireThread";
|
|
@@ -118,12 +119,23 @@ const createServer = (init?: Partial<RunsServerState>) => {
|
|
|
118
119
|
};
|
|
119
120
|
|
|
120
121
|
// A remote SSE fake that delivers the snapshot and acks command posts but
|
|
121
|
-
// never settles them, so optimistic overlays stay visible.
|
|
122
|
-
|
|
122
|
+
// never settles them, so optimistic overlays stay visible. `hold` parks the
|
|
123
|
+
// snapshot until `release()` to expose the pre-attach window.
|
|
124
|
+
const createRemoteServer = (
|
|
125
|
+
init?: Partial<RunsServerState>,
|
|
126
|
+
opts?: { hold?: boolean },
|
|
127
|
+
) => {
|
|
123
128
|
const received: { method: string; params: unknown[] }[] = [];
|
|
124
129
|
const clients = new Map<string, number>();
|
|
125
130
|
const encoder = new TextEncoder();
|
|
126
131
|
const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
|
|
132
|
+
let released = !(opts?.hold ?? false);
|
|
133
|
+
let parkedSnapshot: (() => void) | undefined;
|
|
134
|
+
const release = () => {
|
|
135
|
+
released = true;
|
|
136
|
+
parkedSnapshot?.();
|
|
137
|
+
parkedSnapshot = undefined;
|
|
138
|
+
};
|
|
127
139
|
const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
|
|
128
140
|
const url = String(input);
|
|
129
141
|
const headers = new Headers(init2?.headers);
|
|
@@ -133,20 +145,23 @@ const createRemoteServer = (init?: Partial<RunsServerState>) => {
|
|
|
133
145
|
if (known === undefined) clients.set(clientId, 0);
|
|
134
146
|
const body = new ReadableStream<Uint8Array>({
|
|
135
147
|
start: (c) => {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
148
|
+
const sendSnapshot = () =>
|
|
149
|
+
c.enqueue(
|
|
150
|
+
encoder.encode(
|
|
151
|
+
frame({
|
|
152
|
+
ops: [
|
|
153
|
+
{
|
|
154
|
+
op: "replace",
|
|
155
|
+
path: [],
|
|
156
|
+
value: { ...INITIAL_STATE, ...init },
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
syn: { lastSeq: known ?? -1, lease: "lease-1" },
|
|
160
|
+
}),
|
|
161
|
+
),
|
|
162
|
+
);
|
|
163
|
+
if (released) sendSnapshot();
|
|
164
|
+
else parkedSnapshot = sendSnapshot;
|
|
150
165
|
},
|
|
151
166
|
});
|
|
152
167
|
return new Response(body, {
|
|
@@ -160,6 +175,7 @@ const createRemoteServer = (init?: Partial<RunsServerState>) => {
|
|
|
160
175
|
}) as typeof fetch;
|
|
161
176
|
return {
|
|
162
177
|
received,
|
|
178
|
+
release,
|
|
163
179
|
transport: StatewireSSE<RunsServerState>({
|
|
164
180
|
url: "http://fake/api",
|
|
165
181
|
fetch: fetchImpl,
|
|
@@ -570,6 +586,121 @@ describe("StatewireThread runs mode", () => {
|
|
|
570
586
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
571
587
|
});
|
|
572
588
|
|
|
589
|
+
it("preloads initialState: interactive before attach, sends fold in", async () => {
|
|
590
|
+
const server = createRemoteServer({}, { hold: true });
|
|
591
|
+
const { aui, runs } = mountThread({
|
|
592
|
+
transport: server.transport,
|
|
593
|
+
materialize: rollbackMaterialize,
|
|
594
|
+
});
|
|
595
|
+
|
|
596
|
+
expect(aui().thread().getState().isLoading).toBe(false);
|
|
597
|
+
act(() => {
|
|
598
|
+
aui().thread().append("hello");
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
// The pre-attach send renders through the same optimistic + materialize folds.
|
|
602
|
+
await waitFor(() => expect(runs().status).toBe("running"));
|
|
603
|
+
expect(runs().runId).toMatch(/^optimistic-/);
|
|
604
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
605
|
+
expect(server.received).toEqual([]);
|
|
606
|
+
|
|
607
|
+
server.release();
|
|
608
|
+
|
|
609
|
+
// Attach posts the queued command; the still-unacked overlay survives the snapshot.
|
|
610
|
+
await waitFor(() =>
|
|
611
|
+
expect(server.received.map((c) => c.method)).toEqual(["run/enqueue"]),
|
|
612
|
+
);
|
|
613
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
614
|
+
expect(runs().status).toBe("running");
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
it("preloads again after a transport swap on a persistent thread", async () => {
|
|
618
|
+
const serverA = createRemoteServer({
|
|
619
|
+
messages: [{ id: "a1", role: "user", text: "old thread" }],
|
|
620
|
+
});
|
|
621
|
+
const serverB = createRemoteServer({}, { hold: true });
|
|
622
|
+
const preload: RunsServerState = {
|
|
623
|
+
messages: [],
|
|
624
|
+
status: "ready",
|
|
625
|
+
runs: [],
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
629
|
+
const cell: { swap?: () => void } = {};
|
|
630
|
+
const Capture: FC = () => {
|
|
631
|
+
captured.aui = useAui();
|
|
632
|
+
return null;
|
|
633
|
+
};
|
|
634
|
+
const App: FC = () => {
|
|
635
|
+
const [transport, setTransport] = useState(() =>
|
|
636
|
+
withKey("a", serverA.transport),
|
|
637
|
+
);
|
|
638
|
+
cell.swap = () => setTransport(() => withKey("b", serverB.transport));
|
|
639
|
+
const aui = useAui({
|
|
640
|
+
thread: StatewireThread<RunsServerState>({
|
|
641
|
+
initialState: preload,
|
|
642
|
+
runs: true,
|
|
643
|
+
converter,
|
|
644
|
+
transport,
|
|
645
|
+
}),
|
|
646
|
+
});
|
|
647
|
+
return (
|
|
648
|
+
<AuiProvider value={aui}>
|
|
649
|
+
<Capture />
|
|
650
|
+
</AuiProvider>
|
|
651
|
+
);
|
|
652
|
+
};
|
|
653
|
+
render(<App />);
|
|
654
|
+
const aui = () => captured.aui!;
|
|
655
|
+
|
|
656
|
+
await waitFor(() =>
|
|
657
|
+
expect(
|
|
658
|
+
aui()
|
|
659
|
+
.thread()
|
|
660
|
+
.getState()
|
|
661
|
+
.messages.map((m) => m.id),
|
|
662
|
+
).toEqual(["a1"]),
|
|
663
|
+
);
|
|
664
|
+
|
|
665
|
+
act(() => cell.swap!());
|
|
666
|
+
|
|
667
|
+
// The new source's held snapshot leaves the swapped thread on the preload,
|
|
668
|
+
// interactive, with no bleed-through from the previous snapshot.
|
|
669
|
+
await waitFor(() => expect(aui().thread().getState().messages).toEqual([]));
|
|
670
|
+
expect(aui().thread().getState().isLoading).toBe(false);
|
|
671
|
+
|
|
672
|
+
serverB.release();
|
|
673
|
+
await waitFor(() =>
|
|
674
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
675
|
+
);
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
it("stays loading until the snapshot when initialState is omitted", async () => {
|
|
679
|
+
const server = createRemoteServer(
|
|
680
|
+
{ messages: [{ id: "m1", role: "user", text: "hi" }] },
|
|
681
|
+
{ hold: true },
|
|
682
|
+
);
|
|
683
|
+
const { aui } = mountThread({
|
|
684
|
+
transport: server.transport,
|
|
685
|
+
initialState: undefined,
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
expect(aui().thread().getState().isLoading).toBe(true);
|
|
689
|
+
expect(aui().thread().getState().messages).toEqual([]);
|
|
690
|
+
|
|
691
|
+
server.release();
|
|
692
|
+
|
|
693
|
+
await waitFor(() =>
|
|
694
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
695
|
+
);
|
|
696
|
+
expect(
|
|
697
|
+
aui()
|
|
698
|
+
.thread()
|
|
699
|
+
.getState()
|
|
700
|
+
.messages.map((m) => m.id),
|
|
701
|
+
).toEqual(["m1"]);
|
|
702
|
+
});
|
|
703
|
+
|
|
573
704
|
it("runs the app optimistic reducer after the lib's", async () => {
|
|
574
705
|
const server = createRemoteServer();
|
|
575
706
|
const observedStatus: string[] = [];
|
|
@@ -293,7 +293,7 @@ describe("StatewireThread", () => {
|
|
|
293
293
|
|
|
294
294
|
expect(observed[0]).toBe(initialState);
|
|
295
295
|
expect(threadTexts(aui)).toEqual(["local"]);
|
|
296
|
-
expect(aui().thread().getState().isLoading).toBe(
|
|
296
|
+
expect(aui().thread().getState().isLoading).toBe(false);
|
|
297
297
|
|
|
298
298
|
cell.attach!();
|
|
299
299
|
|
package/src/StatewireThread.ts
CHANGED
|
@@ -47,6 +47,8 @@ type AnyOptions =
|
|
|
47
47
|
| StatewireThread.Options<any>
|
|
48
48
|
| StatewireThread.RunsOptions<any>;
|
|
49
49
|
|
|
50
|
+
const LOADING_STATE: StatewireThread.State = { messages: [], isRunning: false };
|
|
51
|
+
|
|
50
52
|
const READY_RUNS: StatewireThread.Runs = {
|
|
51
53
|
status: "ready",
|
|
52
54
|
runId: null,
|
|
@@ -102,13 +104,12 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
102
104
|
" on first render and changed since",
|
|
103
105
|
);
|
|
104
106
|
|
|
105
|
-
const {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
setContext,
|
|
110
|
-
} = useStatewire<unknown, AnyCommands>({
|
|
107
|
+
const { state, commands, connection, setContext } = useStatewire<
|
|
108
|
+
unknown,
|
|
109
|
+
AnyCommands
|
|
110
|
+
>({
|
|
111
111
|
transport: options.transport,
|
|
112
|
+
initialState: options.initialState,
|
|
112
113
|
...(runsSeam && {
|
|
113
114
|
optimistic: (draft, command, ctx) => {
|
|
114
115
|
const runsOpt = latest.current.runs!;
|
|
@@ -135,8 +136,6 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
135
136
|
onConnectionChange: (connection) =>
|
|
136
137
|
latest.current.onConnectionChange?.(connection),
|
|
137
138
|
});
|
|
138
|
-
const attached = transportState !== undefined;
|
|
139
|
-
const state = attached ? transportState : options.initialState;
|
|
140
139
|
|
|
141
140
|
const clientRef = useAssistantClientRef();
|
|
142
141
|
const setContextRef = useRef(setContext);
|
|
@@ -198,6 +197,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
198
197
|
|
|
199
198
|
const runs = useMemo((): StatewireThread.Runs | undefined => {
|
|
200
199
|
if (runsOption === undefined) return undefined;
|
|
200
|
+
if (state === undefined) return READY_RUNS;
|
|
201
201
|
const mount = (runsOption === true ? state : runsOption(state)) as
|
|
202
202
|
| StatewireThread.RunsState
|
|
203
203
|
| undefined;
|
|
@@ -228,13 +228,15 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
228
228
|
[pending, connection, runs],
|
|
229
229
|
);
|
|
230
230
|
const converted = useMemo(
|
|
231
|
-
() =>
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
231
|
+
(): StatewireThread.State =>
|
|
232
|
+
state === undefined
|
|
233
|
+
? LOADING_STATE
|
|
234
|
+
: (converter(
|
|
235
|
+
state,
|
|
236
|
+
metadata as StatewireThread.ConnectionMetadata & {
|
|
237
|
+
runs: StatewireThread.Runs;
|
|
238
|
+
},
|
|
239
|
+
) as StatewireThread.State),
|
|
238
240
|
[converter, state, metadata],
|
|
239
241
|
);
|
|
240
242
|
// Dispatch limbo is a materialize concern: the fold makes the record
|
|
@@ -247,10 +249,16 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
247
249
|
throw new Error(
|
|
248
250
|
"statewire: the converter's steerQueue projection requires the queue projection",
|
|
249
251
|
);
|
|
252
|
+
// Seams anchor at the first real convert; the loading placeholder projects nothing.
|
|
250
253
|
const [queueSeam] = useState(() => ({
|
|
251
|
-
present:
|
|
254
|
+
present: undefined as boolean | undefined,
|
|
252
255
|
}));
|
|
253
|
-
if (queueSeam.present
|
|
256
|
+
if (state !== undefined && queueSeam.present === undefined)
|
|
257
|
+
queueSeam.present = queueItems !== undefined;
|
|
258
|
+
if (
|
|
259
|
+
queueSeam.present !== undefined &&
|
|
260
|
+
queueSeam.present !== (queueItems !== undefined)
|
|
261
|
+
)
|
|
254
262
|
throw new Error(
|
|
255
263
|
"statewire: the converter's queue projection must be stable — it was " +
|
|
256
264
|
(queueSeam.present ? "defined" : "undefined") +
|
|
@@ -274,9 +282,14 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
274
282
|
const inputRequests =
|
|
275
283
|
runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;
|
|
276
284
|
const [inputSeam] = useState(() => ({
|
|
277
|
-
present:
|
|
285
|
+
present: undefined as boolean | undefined,
|
|
278
286
|
}));
|
|
279
|
-
if (inputSeam.present
|
|
287
|
+
if (state !== undefined && inputSeam.present === undefined)
|
|
288
|
+
inputSeam.present = inputRequests !== undefined;
|
|
289
|
+
if (
|
|
290
|
+
inputSeam.present !== undefined &&
|
|
291
|
+
inputSeam.present !== (inputRequests !== undefined)
|
|
292
|
+
)
|
|
280
293
|
throw new Error(
|
|
281
294
|
"statewire: the converter's inputRequests projection must be stable — it was " +
|
|
282
295
|
(inputSeam.present ? "defined" : "undefined") +
|
|
@@ -321,7 +334,7 @@ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
|
|
|
321
334
|
messages: messages as readonly ExternalThreadMessage[],
|
|
322
335
|
isRunning:
|
|
323
336
|
runs !== undefined ? runs.status === "running" : converted.isRunning,
|
|
324
|
-
isLoading:
|
|
337
|
+
isLoading: state === undefined,
|
|
325
338
|
state: converted.state,
|
|
326
339
|
extras,
|
|
327
340
|
attachmentAdapter: options.adapters?.attachments,
|
|
@@ -667,7 +680,8 @@ export namespace StatewireThread {
|
|
|
667
680
|
|
|
668
681
|
export type Options<T> = {
|
|
669
682
|
transport: Transport<T>;
|
|
670
|
-
|
|
683
|
+
/** Preloads the thread: published and interactive from the first render, replaced by the attach snapshot. Omitted, the thread stays loading until attach. */
|
|
684
|
+
initialState?: T | undefined;
|
|
671
685
|
converter: StateConverter<T>;
|
|
672
686
|
runs?: undefined;
|
|
673
687
|
/**
|