@assistant-ui/react-statewire 0.27.1 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/StatewireThread.d.ts +2 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +42 -8
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +4 -0
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +37 -28
- package/dist/localStorage.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.failed.test.tsx +28 -2
- package/src/StatewireThread.retract.test.tsx +175 -0
- package/src/StatewireThread.runs.test.tsx +39 -29
- package/src/StatewireThread.test.tsx +4 -6
- package/src/StatewireThread.ts +55 -8
- package/src/localStorage.test.ts +69 -13
- package/src/localStorage.ts +62 -96
|
@@ -263,6 +263,8 @@ declare namespace StatewireThread {
|
|
|
263
263
|
transport: Transport<T>;
|
|
264
264
|
/** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
|
|
265
265
|
initialState: T;
|
|
266
|
+
/** Application protocol for optimistic commands; must match the transport's protocol. */
|
|
267
|
+
protocol?: string | undefined;
|
|
266
268
|
converter: StateConverter<T>;
|
|
267
269
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
268
270
|
optimistic?: StatewireClient.Optimistic<T, Record<string, (...args: any[]) => unknown>> | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAgDa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA+fvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OACh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d,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;;cAIP;;IAEV,SAAS,SAAS;;IAElB,YAAY;;;cAIF;;aAED,kBAAkB;;aAElB,eAAe;;;cAId;;aAED;;aAEA;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;aAER,iBAAiB;;cAGhB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;;;cAII;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;;IAEd;IACA,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;MAEA;;;;;;;;IASN;MAEM,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB,gBAAgB;;IAGhD;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -27,7 +27,7 @@ const failedRunCommand = (entry) => {
|
|
|
27
27
|
if (command?.message === void 0) return void 0;
|
|
28
28
|
return command;
|
|
29
29
|
};
|
|
30
|
-
const presentStatus = (status, connection) => status !== "running" || connection.status === "connected" || connection.status === "
|
|
30
|
+
const presentStatus = (status, connection) => status !== "running" || connection.status === "connected" || connection.status === "standby" && connection.reason === "idle" ? status : connection.status === "retrying" && connection.cause === "reconnect" && connection.code === "evicted" ? "evicted" : "disconnected";
|
|
31
31
|
const ambientContextOf = (context) => ({
|
|
32
32
|
...context.system !== void 0 && { system: context.system },
|
|
33
33
|
...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
|
|
@@ -37,6 +37,7 @@ const ambientContextOf = (context) => ({
|
|
|
37
37
|
const useStatewireThread = (options) => {
|
|
38
38
|
const latest = useRef(options);
|
|
39
39
|
latest.current = options;
|
|
40
|
+
const retrying = useRef(/* @__PURE__ */ new Set());
|
|
40
41
|
const [pending, setPending] = useState([]);
|
|
41
42
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
42
43
|
const { state: state_1, commands, connection: connection_0, setContext, isBusy, failed, discardFailed } = useStatewire({
|
|
@@ -44,6 +45,7 @@ const useStatewireThread = (options) => {
|
|
|
44
45
|
onError: (error) => latest.current.onError?.(error),
|
|
45
46
|
storage: options.storage,
|
|
46
47
|
initialState: options.initialState,
|
|
48
|
+
...options.protocol !== void 0 && { protocol: options.protocol },
|
|
47
49
|
optimistic: (draft, command_0, ctx) => {
|
|
48
50
|
runsOptimistic(draft, command_0, ctx);
|
|
49
51
|
latest.current.optimistic?.(draft, command_0, ctx);
|
|
@@ -109,6 +111,27 @@ const useStatewireThread = (options) => {
|
|
|
109
111
|
setText((prev_1) => prev_1 === "" ? text : prev_1);
|
|
110
112
|
});
|
|
111
113
|
}, [dispatch]);
|
|
114
|
+
const popRetracted = async (retracted, runId) => {
|
|
115
|
+
if (!Array.isArray(retracted) || retracted.length === 0 || runId === null) return;
|
|
116
|
+
const composerApi = threadRef.current.composer();
|
|
117
|
+
if (composerApi.getState().text !== "") return;
|
|
118
|
+
const texts = [];
|
|
119
|
+
for (const item of retracted) {
|
|
120
|
+
try {
|
|
121
|
+
await dispatch({
|
|
122
|
+
type: "run/dequeue",
|
|
123
|
+
runId,
|
|
124
|
+
messageId: item.id
|
|
125
|
+
});
|
|
126
|
+
} catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
texts.push(item.parts.flatMap((part_0) => part_0.type === "text" ? [part_0.text] : []).join("\n\n"));
|
|
130
|
+
}
|
|
131
|
+
if (texts.length === 0) return;
|
|
132
|
+
const setText_0 = composerApi.setText;
|
|
133
|
+
setText_0((prev_2) => [prev_2, ...texts].filter(Boolean).join("\n\n"));
|
|
134
|
+
};
|
|
112
135
|
const { status, runs } = useMemo(() => {
|
|
113
136
|
const entries = state_1?.runs;
|
|
114
137
|
const entry_1 = entries?.[0];
|
|
@@ -184,10 +207,20 @@ const useStatewireThread = (options) => {
|
|
|
184
207
|
inputRequests,
|
|
185
208
|
runs,
|
|
186
209
|
retryFailed: (messageId_0) => {
|
|
210
|
+
if (retrying.current.has(messageId_0)) return;
|
|
187
211
|
const entry_3 = takeFailed(messageId_0);
|
|
188
212
|
const command_5 = retryCommand(messages_0, liveRunId, failedRunCommand(entry_3));
|
|
189
|
-
|
|
190
|
-
|
|
213
|
+
retrying.current.add(messageId_0);
|
|
214
|
+
const release = () => {
|
|
215
|
+
retrying.current.delete(messageId_0);
|
|
216
|
+
};
|
|
217
|
+
try {
|
|
218
|
+
discardFailed(entry_3);
|
|
219
|
+
dispatch(command_5).then(release, release);
|
|
220
|
+
} catch (error_1) {
|
|
221
|
+
release();
|
|
222
|
+
throw error_1;
|
|
223
|
+
}
|
|
191
224
|
},
|
|
192
225
|
discardFailed: (messageId_1) => discardFailed(takeFailed(messageId_1)),
|
|
193
226
|
popFailed: (messageId_2) => {
|
|
@@ -243,12 +276,13 @@ const useStatewireThread = (options) => {
|
|
|
243
276
|
onCancel: () => {
|
|
244
277
|
const payload = latest.current.stopPayload?.();
|
|
245
278
|
if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
|
|
279
|
+
const runId_0 = runs.runId;
|
|
246
280
|
commands["run/stop"]({
|
|
247
281
|
...payload,
|
|
248
|
-
runId:
|
|
282
|
+
runId: runId_0,
|
|
249
283
|
...runs.epoch !== void 0 && { epoch: runs.epoch }
|
|
250
|
-
}).catch((
|
|
251
|
-
latest.current.onError?.(
|
|
284
|
+
}).then((retracted_0) => popRetracted(retracted_0, runId_0)).catch((error_2) => {
|
|
285
|
+
latest.current.onError?.(error_2);
|
|
252
286
|
});
|
|
253
287
|
}
|
|
254
288
|
}));
|
|
@@ -267,8 +301,8 @@ const useStatewireThread = (options) => {
|
|
|
267
301
|
name: attachment.name,
|
|
268
302
|
...attachment.contentType !== void 0 && { contentType: attachment.contentType },
|
|
269
303
|
content: attachment.content
|
|
270
|
-
}).catch((
|
|
271
|
-
latest.current.onError?.(
|
|
304
|
+
}).catch((error_3) => {
|
|
305
|
+
latest.current.onError?.(error_3);
|
|
272
306
|
});
|
|
273
307
|
}, [composerStorage]);
|
|
274
308
|
const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","length","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","messageId","find","f","sendCommand","reconnect","retryFailed","popFailed","parts","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","read","getState","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","Promise","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"disconnected\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"connecting\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined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,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACsP,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","reason","cause","code","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","retrying","Set","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","onError","error","storage","initialState","protocol","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","discarded","WeakSet","has","add","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","popRetracted","retracted","Promise","Array","isArray","length","composerApi","getState","texts","item","RunsQueueEntry","messageId","push","parts","Boolean","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","find","f","sendCommand","reconnect","retryFailed","release","delete","then","popFailed","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","composerStorage","read","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"connected\" ||\n (connection.status === \"standby\" && connection.reason === \"idle\")\n ? status\n : connection.status === \"retrying\" &&\n connection.cause === \"reconnect\" &&\n connection.code === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n const retrying = useRef(new Set<string>());\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onError: (error) => latest.current.onError?.(error),\n storage: options.storage,\n initialState: options.initialState,\n ...(options.protocol !== undefined && { protocol: options.protocol }),\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());\n // Effects can replay before the updated failed lane reaches the binding.\n useEffect(() => {\n for (const entry of failed) {\n if (\n failedRunCommand(entry) === undefined &&\n !discarded.current.has(entry)\n ) {\n discarded.current.add(entry);\n discardFailed(entry);\n }\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n // The stop verdict carries the run's retracted items; the stopping client\n // dequeues them into an empty composer. Other clients see them queued.\n const popRetracted = async (\n retracted: unknown,\n runId: string | null,\n ): Promise<void> => {\n if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)\n return;\n const composerApi = threadRef.current!.composer();\n if (composerApi.getState().text !== \"\") return;\n const texts: string[] = [];\n for (const item of retracted as StatewireThread.RunsQueueEntry[]) {\n try {\n await dispatch({ type: \"run/dequeue\", runId, messageId: item.id });\n } catch {\n continue; // rejected dequeue: the item stays queued\n }\n texts.push(\n item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n );\n }\n if (texts.length === 0) return;\n const setText = composerApi.setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => [prev, ...texts].filter(Boolean).join(\"\\n\\n\"));\n };\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n if (retrying.current.has(messageId)) return;\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n retrying.current.add(messageId);\n const release = () => {\n retrying.current.delete(messageId);\n };\n try {\n discardFailed(entry);\n void dispatch(command).then(release, release);\n } catch (error) {\n release();\n throw error;\n }\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n const runId = runs.runId;\n void commands[\"run/stop\"]!({\n ...payload,\n runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n })\n .then((retracted) => popRetracted(retracted, runId))\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n /** Application protocol for optimistic commands; must match the transport's protocol. */\n protocol?: string | undefined;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,aAAaE,WAAWE,WAAW,SACtDJ,SACAE,WAAWF,WAAW,cACpBE,WAAWG,UAAU,eACrBH,WAAWI,SAAS,YACpB,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWb,KAAAA,KAAa,EAAEa,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUd,KAAAA,KAAa,EACjCc,OAAOxD,kBAAkBsD,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBf,KAAAA,KAAa,EACxCe,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWhB,KAAAA,KAAa,EAAEgB,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC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C,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AAgatExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACmQ,IACrC"}
|
package/dist/localStorage.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { StatewireThread } from "./StatewireThread.js";
|
|
2
2
|
import { StatewireClient } from "statewire";
|
|
3
|
+
import { KeyValueSessionStorage } from "statewire/storage";
|
|
3
4
|
//#region src/localStorage.d.ts
|
|
4
5
|
/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
|
|
5
6
|
declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
|
|
@@ -7,6 +8,9 @@ declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<S
|
|
|
7
8
|
declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
|
|
8
9
|
declare namespace LocalStorageSession {
|
|
9
10
|
type Options = {
|
|
11
|
+
legacyProtocol?: KeyValueSessionStorage.Options["legacyProtocol"];
|
|
12
|
+
retention?: KeyValueSessionStorage.Options["retention"];
|
|
13
|
+
onError?: KeyValueSessionStorage.Options["onError"];
|
|
10
14
|
/** Upgrade incompatible queued commands, or return null to discard the saved session. */
|
|
11
15
|
migrate?: StatewireClient.SessionStorage["migrate"];
|
|
12
16
|
/** The thread whose session this storage holds. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;;;cA2Ja,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA2F1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;IACV,iBAAiB,uBAAuB;IACxC,YAAY,uBAAuB;IACnC,UAAU,uBAAuB;;IAEjC,UAAU,gBAAgB;;IAE1B;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
|
package/dist/localStorage.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useEffect, useMemo } from "@assistant-ui/tap/react-shim";
|
|
2
|
-
import { resource } from "@assistant-ui/tap";
|
|
2
|
+
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
|
+
import { KeyValueSessionStorage } from "statewire/storage";
|
|
3
4
|
//#region src/localStorage.ts
|
|
4
5
|
const PREFIX = "aui:composer-draft:";
|
|
5
6
|
const SESSION_PREFIX = "aui:statewire-session:";
|
|
@@ -26,23 +27,6 @@ const isStoredAttachment = (value) => {
|
|
|
26
27
|
return typeof value["id"] === "string" && typeof value["type"] === "string" && typeof value["name"] === "string" && isOptionalString(value["contentType"]) && value["file"] === void 0 && isRecord(status) && status["type"] === "complete" && Array.isArray(value["content"]) && value["content"].every(isUserMessagePart);
|
|
27
28
|
};
|
|
28
29
|
const isStoredDraft = (value) => isRecord(value) && typeof value["text"] === "string" && Array.isArray(value["attachments"]) && value["attachments"].every(isStoredAttachment) && typeof value["ts"] === "number" && Number.isFinite(value["ts"]);
|
|
29
|
-
const isPositiveSafeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
30
|
-
const isSessionCommand = (value) => isRecord(value) && isPositiveSafeInteger(value["seq"]) && typeof value["method"] === "string" && Array.isArray(value["params"]);
|
|
31
|
-
const isSessionVerdict = (value) => isRecord(value) && isPositiveSafeInteger(value["seq"]) && (value["type"] === "result" || value["type"] === "rejected" || value["type"] === "failed" || value["type"] === "crashed" || value["type"] === "expired") && isOptionalString(value["code"]) && isOptionalString(value["message"]);
|
|
32
|
-
const isSendFailure = (value) => {
|
|
33
|
-
if (!isRecord(value)) return false;
|
|
34
|
-
switch (value["fate"]) {
|
|
35
|
-
case "rejected": return value["cause"] === "server" && isOptionalString(value["code"]) && isOptionalString(value["message"]);
|
|
36
|
-
case "failed": return value["cause"] === "server" && isOptionalString(value["message"]);
|
|
37
|
-
case "crashed":
|
|
38
|
-
case "expired": return value["cause"] === "server";
|
|
39
|
-
case "aborted": return (value["cause"] === "unmount" || value["cause"] === "stream-gone" || value["cause"] === "session-lost") && (value["predecessorLost"] === void 0 || value["predecessorLost"] === true);
|
|
40
|
-
case "lost": return value["cause"] === "unmount" || value["cause"] === "stream-gone" || value["cause"] === "session-lost";
|
|
41
|
-
default: return false;
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
|
-
const isFailedCommand = (value) => isRecord(value) && typeof value["command"] === "string" && Array.isArray(value["params"]) && isSendFailure(value["failure"]) && typeof value["ts"] === "number" && Number.isFinite(value["ts"]) && isPositiveSafeInteger(value["seq"]);
|
|
45
|
-
const isSessionRecord = (value) => isRecord(value) && typeof value["clientId"] === "string" && isPositiveSafeInteger(value["nextSeq"]) && isPositiveSafeInteger(value["ctxNextSeq"]) && Array.isArray(value["commands"]) && value["commands"].every(isSessionCommand) && (value["verdicts"] === void 0 || Array.isArray(value["verdicts"]) && value["verdicts"].every(isSessionVerdict)) && (value["failed"] === void 0 || Array.isArray(value["failed"]) && value["failed"].every(isFailedCommand));
|
|
46
30
|
const loadStored = (key, validate) => {
|
|
47
31
|
const raw = localStorage.getItem(key);
|
|
48
32
|
if (raw === null) return null;
|
|
@@ -106,19 +90,44 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
|
|
|
106
90
|
/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
|
|
107
91
|
const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
|
|
108
92
|
const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
|
|
109
|
-
const
|
|
93
|
+
const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
|
|
94
|
+
const sessionBackend = {
|
|
95
|
+
getItem: (key) => localStorage.getItem(key),
|
|
96
|
+
setItem: (key, value) => localStorage.setItem(key, value),
|
|
97
|
+
removeItem: (key) => localStorage.removeItem(key),
|
|
98
|
+
getAllKeys: () => Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)).filter((key) => key !== null),
|
|
99
|
+
withUnused: (key, action) => navigator.locks.request(SESSION_ACTIVE_PREFIX + key, { ifAvailable: true }, (lock) => lock === null ? void 0 : navigator.locks.request(SESSION_LOCK_PREFIX + key.slice(22), { ifAvailable: true }, (lock) => lock === null ? void 0 : action()))
|
|
100
|
+
};
|
|
101
|
+
const useLocalStorageSession = ({ threadId, migrate, key = (id) => id, legacyProtocol, retention, onError }) => {
|
|
110
102
|
if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
|
|
111
103
|
if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
|
|
112
104
|
const storageKey = SESSION_PREFIX + key(threadId);
|
|
113
105
|
const lockName = SESSION_LOCK_PREFIX + key(threadId);
|
|
106
|
+
useEffect(() => {
|
|
107
|
+
let release;
|
|
108
|
+
let disposed = false;
|
|
109
|
+
navigator.locks.request(SESSION_ACTIVE_PREFIX + storageKey, { mode: "shared" }, () => {
|
|
110
|
+
if (disposed) return;
|
|
111
|
+
return new Promise((resolve) => {
|
|
112
|
+
release = resolve;
|
|
113
|
+
});
|
|
114
|
+
}).catch((error) => onError?.(error));
|
|
115
|
+
return () => {
|
|
116
|
+
disposed = true;
|
|
117
|
+
release?.();
|
|
118
|
+
};
|
|
119
|
+
}, [storageKey, onError]);
|
|
120
|
+
const storage = useResource(KeyValueSessionStorage({
|
|
121
|
+
backend: sessionBackend,
|
|
122
|
+
key: key(threadId),
|
|
123
|
+
namespace: SESSION_PREFIX,
|
|
124
|
+
...migrate === void 0 ? {} : { migrate },
|
|
125
|
+
...legacyProtocol === void 0 ? {} : { legacyProtocol },
|
|
126
|
+
...retention === void 0 ? {} : { retention },
|
|
127
|
+
...onError === void 0 ? {} : { onError }
|
|
128
|
+
}));
|
|
114
129
|
return useMemo(() => ({
|
|
115
|
-
|
|
116
|
-
return loadStored(storageKey, isSessionRecord);
|
|
117
|
-
},
|
|
118
|
-
save: (record) => {
|
|
119
|
-
localStorage.setItem(storageKey, JSON.stringify(record));
|
|
120
|
-
},
|
|
121
|
-
...migrate !== void 0 && { migrate },
|
|
130
|
+
...storage,
|
|
122
131
|
lock: (fn) => navigator.locks.request(lockName, async () => fn()),
|
|
123
132
|
subscribe: (listener) => {
|
|
124
133
|
const onStorage = (event) => {
|
|
@@ -128,9 +137,9 @@ const useLocalStorageSession = ({ threadId, migrate, key = (id) => id }) => {
|
|
|
128
137
|
return () => window.removeEventListener("storage", onStorage);
|
|
129
138
|
}
|
|
130
139
|
}), [
|
|
140
|
+
storage,
|
|
131
141
|
storageKey,
|
|
132
|
-
lockName
|
|
133
|
-
migrate
|
|
142
|
+
lockName
|
|
134
143
|
]);
|
|
135
144
|
};
|
|
136
145
|
/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */
|
package/dist/localStorage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","isPositiveSafeInteger","isSafeInteger","isSessionCommand","SessionCommand","isSessionVerdict","SessionVerdict","isSendFailure","SendFailure","isFailedCommand","FailedCommand","isSessionRecord","SessionRecord","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","useLocalStorageSession","migrate","LocalStorageSession","SessionStorage","navigator","locks","lockName","load","save","record","lock","fn","request","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst isPositiveSafeInteger = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0;\n\nconst isSessionCommand = (\n value: unknown,\n): value is StatewireClient.SessionCommand =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n typeof value[\"method\"] === \"string\" &&\n Array.isArray(value[\"params\"]);\n\nconst isSessionVerdict = (\n value: unknown,\n): value is StatewireClient.SessionVerdict =>\n isRecord(value) &&\n isPositiveSafeInteger(value[\"seq\"]) &&\n (value[\"type\"] === \"result\" ||\n value[\"type\"] === \"rejected\" ||\n value[\"type\"] === \"failed\" ||\n value[\"type\"] === \"crashed\" ||\n value[\"type\"] === \"expired\") &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"]);\n\nconst isSendFailure = (\n value: unknown,\n): value is StatewireClient.SendFailure => {\n if (!isRecord(value)) return false;\n switch (value[\"fate\"]) {\n case \"rejected\":\n return (\n value[\"cause\"] === \"server\" &&\n isOptionalString(value[\"code\"]) &&\n isOptionalString(value[\"message\"])\n );\n case \"failed\":\n return value[\"cause\"] === \"server\" && isOptionalString(value[\"message\"]);\n case \"crashed\":\n case \"expired\":\n return value[\"cause\"] === \"server\";\n case \"aborted\":\n return (\n (value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\") &&\n (value[\"predecessorLost\"] === undefined ||\n value[\"predecessorLost\"] === true)\n );\n case \"lost\":\n return (\n value[\"cause\"] === \"unmount\" ||\n value[\"cause\"] === \"stream-gone\" ||\n value[\"cause\"] === \"session-lost\"\n );\n default:\n return false;\n }\n};\n\nconst isFailedCommand = (\n value: unknown,\n): value is StatewireClient.FailedCommand =>\n isRecord(value) &&\n typeof value[\"command\"] === \"string\" &&\n Array.isArray(value[\"params\"]) &&\n isSendFailure(value[\"failure\"]) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]) &&\n isPositiveSafeInteger(value[\"seq\"]);\n\nconst isSessionRecord = (\n value: unknown,\n): value is StatewireClient.SessionRecord =>\n isRecord(value) &&\n typeof value[\"clientId\"] === \"string\" &&\n isPositiveSafeInteger(value[\"nextSeq\"]) &&\n isPositiveSafeInteger(value[\"ctxNextSeq\"]) &&\n Array.isArray(value[\"commands\"]) &&\n value[\"commands\"].every(isSessionCommand) &&\n (value[\"verdicts\"] === undefined ||\n (Array.isArray(value[\"verdicts\"]) &&\n value[\"verdicts\"].every(isSessionVerdict))) &&\n (value[\"failed\"] === undefined ||\n (Array.isArray(value[\"failed\"]) && value[\"failed\"].every(isFailedCommand)));\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(PREFIX)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n key = (id) => id,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n // localStorage is shared across tabs: record mutations must serialize.\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n load: () => {\n return loadStored(storageKey, isSessionRecord);\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\n ...(migrate !== undefined && { migrate }),\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storageKey, lockName, migrate],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n /** Upgrade incompatible queued commands, or return null to discard the saved session. */\n migrate?: StatewireClient.SessionStorage[\"migrate\"];\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;AAKA,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,YAAYC,UAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACE,MAAMC,QAAQH,KAAK;AAErE,MAAMI,oBAAoBJ,UACxBA,UAAUK,KAAAA,KAAa,OAAOL,UAAU;AAE1C,MAAMM,qBAAqBN,UAA4B;CACrD,IAAI,CAACD,SAASC,KAAK,GAAG,OAAO;CAC7B,QAAQA,MAAM,SAAd;EACE,KAAK,QACH,OAAO,OAAOA,MAAM,YAAY;EAClC,KAAK,SACH,OACE,OAAOA,MAAM,aAAa,YAC1BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OACE,OAAOA,MAAM,YAAY,YACzB,OAAOA,MAAM,gBAAgB,YAC7BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OAAO,OAAOA,MAAM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BAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAACvB;EAAYc;EAAUL;CAAO,CAChC;AACF;;AAGA,MAAaC,sBAAsBtF,SAASoF,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","useResource","KeyValueSessionStorage","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","isRecord","value","Record","Array","isArray","isOptionalString","undefined","isUserMessagePart","audio","StoredAttachment","isStoredAttachment","status","every","isStoredDraft","Number","isFinite","loadStored","key","validate","T","raw","localStorage","getItem","JSON","parse","removeItem","sweep","ttl","max","entries","keys","from","length","_","index","startsWith","stored","push","now","Date","fresh","filter","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","SESSION_ACTIVE_PREFIX","sessionBackend","Backend","getAllKeys","withUnused","action","navigator","locks","request","ifAvailable","lock","useLocalStorageSession","migrate","legacyProtocol","retention","onError","LocalStorageSession","SessionStorage","lockName","release","disposed","mode","Promise","resolve","catch","error","storage","backend","namespace","fn","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport { KeyValueSessionStorage } from \"statewire/storage\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isOptionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\nconst isUserMessagePart = (value: unknown): boolean => {\n if (!isRecord(value)) return false;\n switch (value[\"type\"]) {\n case \"text\":\n return typeof value[\"text\"] === \"string\";\n case \"image\":\n return (\n typeof value[\"image\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"file\":\n return (\n typeof value[\"data\"] === \"string\" &&\n typeof value[\"mimeType\"] === \"string\" &&\n isOptionalString(value[\"filename\"])\n );\n case \"data\":\n return typeof value[\"name\"] === \"string\";\n case \"audio\": {\n const audio = value[\"audio\"];\n return (\n isRecord(audio) &&\n typeof audio[\"data\"] === \"string\" &&\n (audio[\"format\"] === \"mp3\" || audio[\"format\"] === \"wav\")\n );\n }\n default:\n return false;\n }\n};\n\ntype StoredAttachment = StoredDraft[\"attachments\"][number];\n\nconst isStoredAttachment = (value: unknown): value is StoredAttachment => {\n if (!isRecord(value)) return false;\n const status = value[\"status\"];\n return (\n typeof value[\"id\"] === \"string\" &&\n typeof value[\"type\"] === \"string\" &&\n typeof value[\"name\"] === \"string\" &&\n isOptionalString(value[\"contentType\"]) &&\n value[\"file\"] === undefined &&\n isRecord(status) &&\n status[\"type\"] === \"complete\" &&\n Array.isArray(value[\"content\"]) &&\n value[\"content\"].every(isUserMessagePart)\n );\n};\n\nconst isStoredDraft = (value: unknown): value is StoredDraft =>\n isRecord(value) &&\n typeof value[\"text\"] === \"string\" &&\n Array.isArray(value[\"attachments\"]) &&\n value[\"attachments\"].every(isStoredAttachment) &&\n typeof value[\"ts\"] === \"number\" &&\n Number.isFinite(value[\"ts\"]);\n\nconst loadStored = <T>(\n key: string,\n validate: (value: unknown) => value is T,\n): T | null => {\n const raw = localStorage.getItem(key);\n if (raw === null) return null;\n try {\n const value: unknown = JSON.parse(raw);\n if (validate(value)) return value;\n } catch {}\n localStorage.removeItem(key);\n return null;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n const keys = Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n );\n for (const key of keys) {\n if (key === null || !key.startsWith(PREFIX)) continue;\n const stored = loadStored(key, isStoredDraft);\n if (stored !== null) entries.push({ key, ts: stored.ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const stored = loadStored(storageKey, isStoredDraft);\n if (stored === null) return undefined;\n return { text: stored.text, attachments: stored.attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst SESSION_ACTIVE_PREFIX = \"aui:statewire-session-active:\";\n\nconst sessionBackend: KeyValueSessionStorage.Backend = {\n getItem: (key) => localStorage.getItem(key),\n setItem: (key, value) => localStorage.setItem(key, value),\n removeItem: (key) => localStorage.removeItem(key),\n getAllKeys: () =>\n Array.from({ length: localStorage.length }, (_, index) =>\n localStorage.key(index),\n ).filter((key): key is string => key !== null),\n withUnused: (key, action) =>\n navigator.locks.request(\n SESSION_ACTIVE_PREFIX + key,\n { ifAvailable: true },\n (lock) =>\n lock === null\n ? undefined\n : navigator.locks.request(\n SESSION_LOCK_PREFIX + key.slice(SESSION_PREFIX.length),\n { ifAvailable: true },\n (lock) => (lock === null ? undefined : action()),\n ),\n ),\n};\n\nconst useLocalStorageSession = ({\n threadId,\n migrate,\n key = (id) => id,\n legacyProtocol,\n retention,\n onError,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n useEffect(() => {\n let release: (() => void) | undefined;\n let disposed = false;\n void navigator.locks\n .request(SESSION_ACTIVE_PREFIX + storageKey, { mode: \"shared\" }, () => {\n if (disposed) return;\n return new Promise<void>((resolve) => {\n release = resolve;\n });\n })\n .catch((error: unknown) => onError?.(error));\n return () => {\n disposed = true;\n release?.();\n };\n }, [storageKey, onError]);\n const storage = useResource(\n KeyValueSessionStorage({\n backend: sessionBackend,\n key: key(threadId),\n namespace: SESSION_PREFIX,\n ...(migrate === undefined ? {} : { migrate }),\n ...(legacyProtocol === undefined ? {} : { legacyProtocol }),\n ...(retention === undefined ? {} : { retention }),\n ...(onError === undefined ? {} : { onError }),\n }),\n );\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n ...storage,\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storage, storageKey, lockName],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n legacyProtocol?: KeyValueSessionStorage.Options[\"legacyProtocol\"];\n retention?: KeyValueSessionStorage.Options[\"retention\"];\n onError?: KeyValueSessionStorage.Options[\"onError\"];\n /** Upgrade incompatible queued commands, or return null to discard the saved session. */\n migrate?: StatewireClient.SessionStorage[\"migrate\"];\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;;AAMA,MAAMO,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,YAAYC,UAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACE,MAAMC,QAAQH,KAAK;AAErE,MAAMI,oBAAoBJ,UACxBA,UAAUK,KAAAA,KAAa,OAAOL,UAAU;AAE1C,MAAMM,qBAAqBN,UAA4B;CACrD,IAAI,CAACD,SAASC,KAAK,GAAG,OAAO;CAC7B,QAAQA,MAAM,SAAd;EACE,KAAK,QACH,OAAO,OAAOA,MAAM,YAAY;EAClC,KAAK,SACH,OACE,OAAOA,MAAM,aAAa,YAC1BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OACE,OAAOA,MAAM,YAAY,YACzB,OAAOA,MAAM,gBAAgB,YAC7BI,iBAAiBJ,MAAM,WAAW;EAEtC,KAAK,QACH,OAAO,OAAOA,MAAM,YAA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U;GACd,OAAO,IAAIE,SAAeC,YAAY;IACpCJ,UAAUI;GACZ,CAAC;EACH,CAAC,CAAC,CACDC,OAAOC,UAAmBV,UAAUU,KAAK,CAAC;EAC7C,aAAa;GACXL,WAAW;GACXD,UAAU;EACZ;CACF,GAAG,CAAC3B,YAAYuB,OAAO,CAAC;CACxB,MAAMW,UAAUnG,YACdC,uBAAuB;EACrBmG,SAAS1B;EACT7C,KAAKA,IAAI8B,QAAQ;EACjB0C,WAAWhG;EACX,GAAIgF,YAAYnE,KAAAA,IAAY,CAAC,IAAI,EAAEmE,QAAQ;EAC3C,GAAIC,mBAAmBpE,KAAAA,IAAY,CAAC,IAAI,EAAEoE,eAAe;EACzD,GAAIC,cAAcrE,KAAAA,IAAY,CAAC,IAAI,EAAEqE,UAAU;EAC/C,GAAIC,YAAYtE,KAAAA,IAAY,CAAC,IAAI,EAAEsE,QAAQ;CAC7C,CAAC,CACH;CACA,OAAO1F,eACkC;EACrC,GAAGqG;EACHhB,OAAOmB,OAAOvB,UAAUC,MAAMC,QAAQU,UAAU,YAAYW,GAAG,CAAC;EAChEC,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAM7E,QAAQoC,YAAYuC,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA;EAACN;EAASlC;EAAY0B;CAAQ,CAChC;AACF;;AAGA,MAAaF,sBAAsB1F,SAASqF,sBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.1",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"@assistant-ui/store": "^0.3.0",
|
|
39
39
|
"@assistant-ui/tap": "^0.9.7",
|
|
40
40
|
"assistant-stream": "^0.3.37",
|
|
41
|
-
"statewire": "^0.
|
|
41
|
+
"statewire": "^0.18.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@assistant-ui/core": ">=0.3.12",
|