@assistant-ui/react-statewire 0.24.0 → 0.25.0
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/README.md +39 -0
- package/dist/StatewireThread.js +14 -16
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +60 -14
- package/dist/localStorage.js.map +1 -1
- package/package.json +4 -3
- package/src/StatewireThread.drafts.test.tsx +31 -1
- package/src/StatewireThread.failed.test.tsx +4 -3
- package/src/StatewireThread.runs.test.tsx +11 -6
- package/src/StatewireThread.ts +10 -10
- package/src/localStorage.test.ts +83 -1
- package/src/localStorage.ts +173 -12
package/README.md
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# @assistant-ui/react-statewire
|
|
2
|
+
|
|
3
|
+
Binds a statewire to an assistant-ui thread: a converter projects the replicated state into messages, and the run-dialect commands drive the composer and message actions. Part of [harness-sdk](https://github.com/assistant-ui/harness-sdk), with `harness-sdk` and `pinned`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @assistant-ui/react-statewire statewire @assistant-ui/core @assistant-ui/store react
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Use
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
15
|
+
import { StatewireThread } from "@assistant-ui/react-statewire";
|
|
16
|
+
import { LocalStorageComposerDrafts } from "@assistant-ui/react-statewire/local-storage";
|
|
17
|
+
import { StatewireSSE } from "statewire";
|
|
18
|
+
|
|
19
|
+
const thread = StatewireThread<ServerState>({
|
|
20
|
+
transport: StatewireSSE({ url }),
|
|
21
|
+
initialState: { messages: [], status: "ready", runs: [] },
|
|
22
|
+
converter,
|
|
23
|
+
capabilities: { edit: true, reload: true },
|
|
24
|
+
storage: { composer: LocalStorageComposerDrafts({ threadId }) },
|
|
25
|
+
});
|
|
26
|
+
const aui = useAui({ thread });
|
|
27
|
+
return (
|
|
28
|
+
<AuiProvider value={aui}>
|
|
29
|
+
<Thread />
|
|
30
|
+
</AuiProvider>
|
|
31
|
+
);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Docs
|
|
35
|
+
|
|
36
|
+
- Get started: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/get-started/statewire/page.mdx
|
|
37
|
+
- Guide: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/guides/statewire/bindings/page.mdx
|
|
38
|
+
- Reference: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/reference/statewire-bindings/page.mdx
|
|
39
|
+
- Spec: https://github.com/assistant-ui/harness-sdk/blob/main/apps/docs/app/docs/spec/statewire-protocol/page.mdx
|
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 === "disconnected" && connection.reason === "idle" ? status : connection.status === "connecting" && connection.cause === "evicted" ? "evicted" : "disconnected";
|
|
30
|
+
const presentStatus = (status, connection) => status !== "running" || connection.status === "connected" || connection.status === "disconnected" && connection.reason === "idle" ? status : connection.status === "connecting" && 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) },
|
|
@@ -41,6 +41,7 @@ const useStatewireThread = (options) => {
|
|
|
41
41
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
42
42
|
const { state: state_1, commands, connection: connection_0, setContext, isBusy, failed, discardFailed } = useStatewire({
|
|
43
43
|
transport: options.transport,
|
|
44
|
+
onError: (error) => latest.current.onError?.(error),
|
|
44
45
|
storage: options.storage,
|
|
45
46
|
initialState: options.initialState,
|
|
46
47
|
optimistic: (draft, command_0, ctx) => {
|
|
@@ -89,9 +90,9 @@ const useStatewireThread = (options) => {
|
|
|
89
90
|
const dispatch = useCallback((command_2) => {
|
|
90
91
|
setPending((prev_0) => [...prev_0, command_2]);
|
|
91
92
|
const settled = commands[command_2.type](command_2);
|
|
92
|
-
settled.catch((
|
|
93
|
+
settled.catch((error_0) => {
|
|
93
94
|
retire(command_2);
|
|
94
|
-
latest.current.onError?.(
|
|
95
|
+
latest.current.onError?.(error_0);
|
|
95
96
|
});
|
|
96
97
|
return settled;
|
|
97
98
|
}, [commands, retire]);
|
|
@@ -242,18 +243,15 @@ const useStatewireThread = (options) => {
|
|
|
242
243
|
...payload,
|
|
243
244
|
runId: runs.runId,
|
|
244
245
|
...runs.epoch !== void 0 && { epoch: runs.epoch }
|
|
245
|
-
}).catch((
|
|
246
|
-
latest.current.onError?.(
|
|
246
|
+
}).catch((error_1) => {
|
|
247
|
+
latest.current.onError?.(error_1);
|
|
247
248
|
});
|
|
248
249
|
}
|
|
249
250
|
}));
|
|
250
251
|
threadRef.current = thread;
|
|
251
252
|
const composerStorage = useResources(options.storage?.composer !== void 0 ? [withKey("composer", options.storage.composer)] : [])[0];
|
|
252
|
-
const storageRef = useRef(composerStorage);
|
|
253
|
-
storageRef.current = composerStorage;
|
|
254
|
-
const storageHook = options.storage?.composer?.hook;
|
|
255
253
|
useEffect(() => {
|
|
256
|
-
const storage =
|
|
254
|
+
const storage = composerStorage;
|
|
257
255
|
if (storage === void 0) return;
|
|
258
256
|
const composer = threadRef.current.composer();
|
|
259
257
|
const draft_1 = storage.read();
|
|
@@ -265,18 +263,18 @@ const useStatewireThread = (options) => {
|
|
|
265
263
|
name: attachment.name,
|
|
266
264
|
...attachment.contentType !== void 0 && { contentType: attachment.contentType },
|
|
267
265
|
content: attachment.content
|
|
268
|
-
}).catch((
|
|
269
|
-
latest.current.onError?.(
|
|
266
|
+
}).catch((error_2) => {
|
|
267
|
+
latest.current.onError?.(error_2);
|
|
270
268
|
});
|
|
271
|
-
}, [
|
|
269
|
+
}, [composerStorage]);
|
|
272
270
|
const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
|
|
273
271
|
const draftAttachments = useMemo(() => composerAttachments.filter((attachment_0) => attachment_0.status.type === "complete").map(({ file: _file, ...record }) => record), [composerAttachments]);
|
|
274
272
|
const [draftSync] = useState(() => ({ writingFor: void 0 }));
|
|
275
273
|
useEffect(() => {
|
|
276
|
-
const storage_0 =
|
|
274
|
+
const storage_0 = composerStorage;
|
|
277
275
|
if (storage_0 === void 0) return;
|
|
278
|
-
const isBaseline = draftSync.writingFor !==
|
|
279
|
-
draftSync.writingFor =
|
|
276
|
+
const isBaseline = draftSync.writingFor !== storage_0;
|
|
277
|
+
draftSync.writingFor = storage_0;
|
|
280
278
|
if (draftText === "" && draftAttachments.length === 0) {
|
|
281
279
|
if (!isBaseline) storage_0.clear();
|
|
282
280
|
return;
|
|
@@ -287,7 +285,7 @@ const useStatewireThread = (options) => {
|
|
|
287
285
|
});
|
|
288
286
|
}, [
|
|
289
287
|
draftSync,
|
|
290
|
-
|
|
288
|
+
composerStorage,
|
|
291
289
|
draftText,
|
|
292
290
|
draftAttachments
|
|
293
291
|
]);
|
|
@@ -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","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","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","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","storageRef","storageHook","hook","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"],"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\" && connection.cause === \"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 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 // Failures the thread cannot project stay onError-only, as before the lane.\n useEffect(() => {\n for (const entry of failed) {\n if (failedRunCommand(entry) === undefined) discardFailed(entry);\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 const storageRef = useRef(composerStorage);\n storageRef.current = composerStorage;\n const storageHook = options.storage?.composer?.hook;\n\n useEffect(() => {\n const storage = storageRef.current;\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 }, [storageHook]);\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 = storageRef.current;\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 !== storageHook;\n draftSync.writingFor = storageHook;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, storageHook, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,kBAAkBE,WAAWE,WAAW,SAC3DJ,SACAE,WAAWF,WAAW,gBAAgBE,WAAWG,UAAU,YACzD,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWZ,KAAAA,KAAa,EAAEY,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUb,KAAAA,KAAa,EACjCa,OAAOvD,kBAAkBqD,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBd,KAAAA,KAAa,EACxCc,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWf,KAAAA,KAAa,EAAEe,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAASnF,OAAOiF,OAAO;CAC7BE,OAAOC,UAAUH;CAEjB,MAAM,CAACI,SAASC,cAAcrF,SAC5B,C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,"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","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 // Failures the thread cannot project stay onError-only, as before the lane.\n useEffect(() => {\n for (const entry of failed) {\n if (failedRunCommand(entry) === undefined) discardFailed(entry);\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [composerStorage]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = composerStorage;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storage;\n draftSync.writingFor = storage;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, composerStorage, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n /** Dispatches the command; the promise settles with the accepted command's result payload, rejecting with `StatewireSendError` otherwise. */\n sendCommand: (command: Command) => Promise<unknown>;\n reconnect: () => void;\n state: unknown;\n status: ThreadStatus;\n /** Negation of the server's broadcast idle level (a transport without idle is always busy). */\n isBusy: boolean;\n inputRequests: readonly InputRequestState[];\n runs: Runs;\n /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `connected`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,eACrBE,WAAWF,WAAW,kBAAkBE,WAAWE,WAAW,SAC3DJ,SACAE,WAAWF,WAAW,gBACpBE,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,KAA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E5F,MAAMiF;GAAW/B,aAAaiC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWf;EAAiBQ;EAAWE;CAAgB,CAAC;CAE5D,OAAOrC;AACT;AAEA,MAAa5I,mBACXsC,YAEAhF,SAAS+E,kBAAkB,CAAC,CAACC,OAAuC;AA8ZtExE,uBACEuE,oBACA1E,eAAeyD,KAAAA,CAAkB,CAAC,CAACkP,IACrC"}
|
|
@@ -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":";;;cA+Oa,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA0C1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
|
package/dist/localStorage.js
CHANGED
|
@@ -4,15 +4,64 @@ import { resource } from "@assistant-ui/tap";
|
|
|
4
4
|
const PREFIX = "aui:composer-draft:";
|
|
5
5
|
const SESSION_PREFIX = "aui:statewire-session:";
|
|
6
6
|
const DAY = 864e5;
|
|
7
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
const isOptionalString = (value) => value === void 0 || typeof value === "string";
|
|
9
|
+
const isUserMessagePart = (value) => {
|
|
10
|
+
if (!isRecord(value)) return false;
|
|
11
|
+
switch (value["type"]) {
|
|
12
|
+
case "text": return typeof value["text"] === "string";
|
|
13
|
+
case "image": return typeof value["image"] === "string" && isOptionalString(value["filename"]);
|
|
14
|
+
case "file": return typeof value["data"] === "string" && typeof value["mimeType"] === "string" && isOptionalString(value["filename"]);
|
|
15
|
+
case "data": return typeof value["name"] === "string";
|
|
16
|
+
case "audio": {
|
|
17
|
+
const audio = value["audio"];
|
|
18
|
+
return isRecord(audio) && typeof audio["data"] === "string" && (audio["format"] === "mp3" || audio["format"] === "wav");
|
|
19
|
+
}
|
|
20
|
+
default: return false;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const isStoredAttachment = (value) => {
|
|
24
|
+
if (!isRecord(value)) return false;
|
|
25
|
+
const status = value["status"];
|
|
26
|
+
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
|
+
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
|
+
const loadStored = (key, validate) => {
|
|
47
|
+
const raw = localStorage.getItem(key);
|
|
48
|
+
if (raw === null) return null;
|
|
49
|
+
try {
|
|
50
|
+
const value = JSON.parse(raw);
|
|
51
|
+
if (validate(value)) return value;
|
|
52
|
+
} catch {}
|
|
53
|
+
localStorage.removeItem(key);
|
|
54
|
+
return null;
|
|
55
|
+
};
|
|
7
56
|
const sweep = (ttl, max) => {
|
|
8
57
|
const entries = [];
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
if (!key.startsWith(PREFIX)) continue;
|
|
12
|
-
const
|
|
13
|
-
entries.push({
|
|
58
|
+
const keys = Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index));
|
|
59
|
+
for (const key of keys) {
|
|
60
|
+
if (key === null || !key.startsWith(PREFIX)) continue;
|
|
61
|
+
const stored = loadStored(key, isStoredDraft);
|
|
62
|
+
if (stored !== null) entries.push({
|
|
14
63
|
key,
|
|
15
|
-
ts
|
|
64
|
+
ts: stored.ts
|
|
16
65
|
});
|
|
17
66
|
}
|
|
18
67
|
const now = Date.now();
|
|
@@ -32,12 +81,11 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
|
|
|
32
81
|
const storageKey = PREFIX + key(threadId);
|
|
33
82
|
return useMemo(() => ({
|
|
34
83
|
read: () => {
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
37
|
-
const { text, attachments } = JSON.parse(raw);
|
|
84
|
+
const stored = loadStored(storageKey, isStoredDraft);
|
|
85
|
+
if (stored === null) return void 0;
|
|
38
86
|
return {
|
|
39
|
-
text,
|
|
40
|
-
attachments
|
|
87
|
+
text: stored.text,
|
|
88
|
+
attachments: stored.attachments
|
|
41
89
|
};
|
|
42
90
|
},
|
|
43
91
|
write: (draft) => {
|
|
@@ -65,9 +113,7 @@ const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
|
|
|
65
113
|
const lockName = SESSION_LOCK_PREFIX + key(threadId);
|
|
66
114
|
return useMemo(() => ({
|
|
67
115
|
load: () => {
|
|
68
|
-
|
|
69
|
-
if (raw === null) return null;
|
|
70
|
-
return JSON.parse(raw);
|
|
116
|
+
return loadStored(storageKey, isSessionRecord);
|
|
71
117
|
},
|
|
72
118
|
save: (record) => {
|
|
73
119
|
localStorage.setItem(storageKey, JSON.stringify(record));
|
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","sweep","ttl","max","entries","key","i","localStorage","length","startsWith","JSON","parse","getItem","push","now","Date","fresh","filter","removeItem","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","raw","undefined","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","useLocalStorageSession","LocalStorageSession","SessionStorage","navigator","locks","lockName","load","SessionRecord","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 sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)!;\n if (!key.startsWith(PREFIX)) continue;\n const { ts } = JSON.parse(localStorage.getItem(key)!) as StoredDraft;\n entries.push({ key, 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 raw = localStorage.getItem(storageKey);\n if (raw === null) return undefined;\n const { text, attachments } = JSON.parse(raw) as StoredDraft;\n return { text, 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 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 const raw = localStorage.getItem(storageKey);\n if (raw === null) return null;\n return JSON.parse(raw) as StatewireClient.SessionRecord;\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\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],\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 /** 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,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AsB"}
|
|
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","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 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 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],\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 /** 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,MA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Q;CACnD,OAAOvE,eACkC;EACrC2F,YAAY;GACV,OAAOnD,WAAWqC,YAAYvC,eAAe;EAC/C;EACAsD,OAAOC,WAAW;GAChBhD,aAAaoC,QAAQJ,YAAY9B,KAAKmC,UAAUW,MAAM,CAAC;EACzD;EACAC,OAAOC,OAAOP,UAAUC,MAAMO,QAAQN,UAAU,YAAYK,GAAG,CAAC;EAChEE,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAM3D,QAAQoC,YAAYqB,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA,CAACtB,YAAYa,QAAQ,CACvB;AACF;;AAGA,MAAaJ,sBAAsBrF,SAASoF,sBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
"types": "./dist/index.d.ts",
|
|
27
27
|
"files": [
|
|
28
28
|
"dist",
|
|
29
|
-
"src"
|
|
29
|
+
"src",
|
|
30
|
+
"README.md"
|
|
30
31
|
],
|
|
31
32
|
"scripts": {
|
|
32
33
|
"build": "aui-build",
|
|
@@ -37,7 +38,7 @@
|
|
|
37
38
|
"@assistant-ui/store": "^0.3.0",
|
|
38
39
|
"@assistant-ui/tap": "^0.9.7",
|
|
39
40
|
"assistant-stream": "^0.3.37",
|
|
40
|
-
"statewire": "^0.
|
|
41
|
+
"statewire": "^0.15.0"
|
|
41
42
|
},
|
|
42
43
|
"peerDependencies": {
|
|
43
44
|
"@assistant-ui/core": ">=0.3.12",
|
|
@@ -50,6 +50,10 @@ const createServer = ({ rejectSends = false } = {}) => {
|
|
|
50
50
|
return { transport, received };
|
|
51
51
|
};
|
|
52
52
|
|
|
53
|
+
const draftStore = resource(
|
|
54
|
+
(storage: StatewireThread.ComposerStorage) => storage,
|
|
55
|
+
);
|
|
56
|
+
|
|
53
57
|
const createDraftStore = (initial?: StatewireThread.ComposerDraft) => {
|
|
54
58
|
const cell = { draft: initial, log: [] as string[] };
|
|
55
59
|
const storage: StatewireThread.ComposerStorage = {
|
|
@@ -63,7 +67,7 @@ const createDraftStore = (initial?: StatewireThread.ComposerDraft) => {
|
|
|
63
67
|
cell.log.push("clear");
|
|
64
68
|
},
|
|
65
69
|
};
|
|
66
|
-
return { cell, element:
|
|
70
|
+
return { cell, element: draftStore(storage) };
|
|
67
71
|
};
|
|
68
72
|
|
|
69
73
|
const mountThread = (
|
|
@@ -349,4 +353,30 @@ describe("StatewireThread composer draft storage", () => {
|
|
|
349
353
|
);
|
|
350
354
|
expect(composerOf(aui).getState().text).toBe("typed");
|
|
351
355
|
});
|
|
356
|
+
|
|
357
|
+
it("restores from and persists to the new storage when the element switches", async () => {
|
|
358
|
+
const server = createServer();
|
|
359
|
+
const first = createDraftStore();
|
|
360
|
+
const second = createDraftStore({ text: "second draft", attachments: [] });
|
|
361
|
+
const { aui, knobs } = mountThread({ transport: server.transport });
|
|
362
|
+
await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
|
|
363
|
+
|
|
364
|
+
act(() => knobs.setStorage!(first.element as never));
|
|
365
|
+
act(() => flushTapSync(() => composerOf(aui).setText("first draft")));
|
|
366
|
+
await waitFor(() => expect(first.cell.draft?.text).toBe("first draft"));
|
|
367
|
+
act(() => flushTapSync(() => composerOf(aui).setText("")));
|
|
368
|
+
await waitFor(() => expect(first.cell.draft).toBeUndefined());
|
|
369
|
+
|
|
370
|
+
act(() => knobs.setStorage!(second.element as never));
|
|
371
|
+
await waitFor(() =>
|
|
372
|
+
expect(composerOf(aui).getState().text).toBe("second draft"),
|
|
373
|
+
);
|
|
374
|
+
act(() => flushTapSync(() => composerOf(aui).setText("second edited")));
|
|
375
|
+
await waitFor(() => expect(second.cell.draft?.text).toBe("second edited"));
|
|
376
|
+
expect(second.cell.log).toEqual([
|
|
377
|
+
"write:second draft",
|
|
378
|
+
"write:second edited",
|
|
379
|
+
]);
|
|
380
|
+
expect(first.cell.log).toEqual(["write:first draft", "clear"]);
|
|
381
|
+
});
|
|
352
382
|
});
|
|
@@ -75,11 +75,12 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
75
75
|
const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
|
|
76
76
|
const url = String(input);
|
|
77
77
|
const headers = new Headers(init2?.headers);
|
|
78
|
-
const clientId =
|
|
78
|
+
const clientId =
|
|
79
|
+
headers.get("Statewire-Client-Id") ?? [...clients.keys()].at(-1)!;
|
|
79
80
|
if (url.endsWith("/stream")) {
|
|
80
81
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
81
82
|
const rec = clients.get(clientId)!;
|
|
82
|
-
const attachFrame = JSON.parse(String(init2?.body)) as Frame;
|
|
83
|
+
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
83
84
|
const body = new ReadableStream<Uint8Array>({
|
|
84
85
|
start: (c) => {
|
|
85
86
|
stream = c;
|
|
@@ -108,7 +109,7 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
108
109
|
},
|
|
109
110
|
});
|
|
110
111
|
}
|
|
111
|
-
admit(clientId, JSON.parse(String(init2?.body)) as Frame);
|
|
112
|
+
admit(clientId, JSON.parse(String(init2?.body ?? "{}")) as Frame);
|
|
112
113
|
return Response.json({});
|
|
113
114
|
}) as typeof fetch;
|
|
114
115
|
return {
|
|
@@ -140,9 +140,13 @@ const createRemoteServer = (
|
|
|
140
140
|
};
|
|
141
141
|
let finSent = false;
|
|
142
142
|
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
143
|
-
const fin = (reason: string) => {
|
|
143
|
+
const fin = (reason: string, code?: string) => {
|
|
144
144
|
finSent = true;
|
|
145
|
-
stream!.enqueue(
|
|
145
|
+
stream!.enqueue(
|
|
146
|
+
encoder.encode(
|
|
147
|
+
frame({ fin: { reason, ...(code === undefined ? {} : { code }) } }),
|
|
148
|
+
),
|
|
149
|
+
);
|
|
146
150
|
stream!.close();
|
|
147
151
|
};
|
|
148
152
|
type Frame = {
|
|
@@ -162,11 +166,12 @@ const createRemoteServer = (
|
|
|
162
166
|
const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
|
|
163
167
|
const url = String(input);
|
|
164
168
|
const headers = new Headers(init2?.headers);
|
|
165
|
-
const clientId =
|
|
169
|
+
const clientId =
|
|
170
|
+
headers.get("Statewire-Client-Id") ?? [...clients.keys()].at(-1)!;
|
|
166
171
|
if (url.endsWith("/stream")) {
|
|
167
172
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
168
173
|
const rec = clients.get(clientId)!;
|
|
169
|
-
const attachFrame = JSON.parse(String(init2?.body)) as Frame;
|
|
174
|
+
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
170
175
|
const body = new ReadableStream<Uint8Array>({
|
|
171
176
|
start: (c) => {
|
|
172
177
|
stream = c;
|
|
@@ -201,7 +206,7 @@ const createRemoteServer = (
|
|
|
201
206
|
},
|
|
202
207
|
});
|
|
203
208
|
}
|
|
204
|
-
admit(clientId, JSON.parse(String(init2?.body)) as Frame);
|
|
209
|
+
admit(clientId, JSON.parse(String(init2?.body ?? "{}")) as Frame);
|
|
205
210
|
return Response.json({});
|
|
206
211
|
}) as typeof fetch;
|
|
207
212
|
return {
|
|
@@ -864,7 +869,7 @@ describe("StatewireThread connection presentation", () => {
|
|
|
864
869
|
const { aui } = mountThread({ transport: server.transport });
|
|
865
870
|
|
|
866
871
|
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
867
|
-
server.fin("evicted");
|
|
872
|
+
server.fin("reconnect", "evicted");
|
|
868
873
|
|
|
869
874
|
await waitFor(() => expect(threadStatus(aui())).toBe("evicted"));
|
|
870
875
|
expect(aui().thread().getState().isRunning).toBe(false);
|
package/src/StatewireThread.ts
CHANGED
|
@@ -103,7 +103,9 @@ const presentStatus = (
|
|
|
103
103
|
connection.status === "connected" ||
|
|
104
104
|
(connection.status === "disconnected" && connection.reason === "idle")
|
|
105
105
|
? status
|
|
106
|
-
: connection.status === "connecting" &&
|
|
106
|
+
: connection.status === "connecting" &&
|
|
107
|
+
connection.cause === "reconnect" &&
|
|
108
|
+
connection.code === "evicted"
|
|
107
109
|
? "evicted"
|
|
108
110
|
: "disconnected";
|
|
109
111
|
|
|
@@ -146,6 +148,7 @@ const useStatewireThread = (
|
|
|
146
148
|
discardFailed,
|
|
147
149
|
} = useStatewire<unknown, AnyCommands>({
|
|
148
150
|
transport: options.transport,
|
|
151
|
+
onError: (error) => latest.current.onError?.(error),
|
|
149
152
|
storage: options.storage,
|
|
150
153
|
initialState: options.initialState,
|
|
151
154
|
optimistic: (draft, command, ctx) => {
|
|
@@ -449,12 +452,9 @@ const useStatewireThread = (
|
|
|
449
452
|
? [withKey("composer", options.storage.composer)]
|
|
450
453
|
: [],
|
|
451
454
|
)[0];
|
|
452
|
-
const storageRef = useRef(composerStorage);
|
|
453
|
-
storageRef.current = composerStorage;
|
|
454
|
-
const storageHook = options.storage?.composer?.hook;
|
|
455
455
|
|
|
456
456
|
useEffect(() => {
|
|
457
|
-
const storage =
|
|
457
|
+
const storage = composerStorage;
|
|
458
458
|
if (storage === undefined) return;
|
|
459
459
|
const composer = threadRef.current!.composer();
|
|
460
460
|
const draft = storage.read();
|
|
@@ -475,7 +475,7 @@ const useStatewireThread = (
|
|
|
475
475
|
latest.current.onError?.(error);
|
|
476
476
|
});
|
|
477
477
|
}
|
|
478
|
-
}, [
|
|
478
|
+
}, [composerStorage]);
|
|
479
479
|
|
|
480
480
|
const { text: draftText, attachments: composerAttachments } =
|
|
481
481
|
thread.getState().composer;
|
|
@@ -491,18 +491,18 @@ const useStatewireThread = (
|
|
|
491
491
|
);
|
|
492
492
|
const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));
|
|
493
493
|
useEffect(() => {
|
|
494
|
-
const storage =
|
|
494
|
+
const storage = composerStorage;
|
|
495
495
|
if (storage === undefined) return;
|
|
496
496
|
// First run per storage is the baseline, not a change: never clear the
|
|
497
497
|
// stored draft the restore effect is about to load.
|
|
498
|
-
const isBaseline = draftSync.writingFor !==
|
|
499
|
-
draftSync.writingFor =
|
|
498
|
+
const isBaseline = draftSync.writingFor !== storage;
|
|
499
|
+
draftSync.writingFor = storage;
|
|
500
500
|
if (draftText === "" && draftAttachments.length === 0) {
|
|
501
501
|
if (!isBaseline) storage.clear();
|
|
502
502
|
return;
|
|
503
503
|
}
|
|
504
504
|
storage.write({ text: draftText, attachments: draftAttachments });
|
|
505
|
-
}, [draftSync,
|
|
505
|
+
}, [draftSync, composerStorage, draftText, draftAttachments]);
|
|
506
506
|
|
|
507
507
|
return thread;
|
|
508
508
|
};
|
package/src/localStorage.test.ts
CHANGED
|
@@ -96,6 +96,35 @@ describe("LocalStorageComposerDrafts", () => {
|
|
|
96
96
|
root.unmount();
|
|
97
97
|
});
|
|
98
98
|
|
|
99
|
+
it("discards malformed draft records without breaking the mount sweep", () => {
|
|
100
|
+
localStorage.setItem(`${PREFIX}broken-json`, "{");
|
|
101
|
+
localStorage.setItem(
|
|
102
|
+
`${PREFIX}broken-shape`,
|
|
103
|
+
JSON.stringify({ text: 42, attachments: [], ts: Date.now() }),
|
|
104
|
+
);
|
|
105
|
+
localStorage.setItem(
|
|
106
|
+
`${PREFIX}broken-attachment`,
|
|
107
|
+
JSON.stringify({ text: "draft", attachments: [null], ts: Date.now() }),
|
|
108
|
+
);
|
|
109
|
+
seed("live", Date.now());
|
|
110
|
+
|
|
111
|
+
const root = mount({ threadId: "t1" });
|
|
112
|
+
expect(localStorage.getItem(`${PREFIX}broken-json`)).toBeNull();
|
|
113
|
+
expect(localStorage.getItem(`${PREFIX}broken-shape`)).toBeNull();
|
|
114
|
+
expect(localStorage.getItem(`${PREFIX}broken-attachment`)).toBeNull();
|
|
115
|
+
expect(localStorage.getItem(`${PREFIX}live`)).not.toBeNull();
|
|
116
|
+
root.unmount();
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("discards a malformed draft encountered during read", () => {
|
|
120
|
+
const root = mount({ threadId: "t1" });
|
|
121
|
+
localStorage.setItem(`${PREFIX}t1`, "null");
|
|
122
|
+
|
|
123
|
+
expect(root.getValue().read()).toBeUndefined();
|
|
124
|
+
expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
|
|
125
|
+
root.unmount();
|
|
126
|
+
});
|
|
127
|
+
|
|
99
128
|
it("throws without localStorage", () => {
|
|
100
129
|
vi.stubGlobal("localStorage", undefined);
|
|
101
130
|
expect(() => mount({ threadId: "t1" })).toThrow(/requires localStorage/);
|
|
@@ -140,7 +169,14 @@ describe("LocalStorageSession", () => {
|
|
|
140
169
|
clientId: "c-1",
|
|
141
170
|
nextSeq: 3,
|
|
142
171
|
ctxNextSeq: 1,
|
|
143
|
-
commands: [
|
|
172
|
+
commands: [
|
|
173
|
+
{
|
|
174
|
+
seq: 2,
|
|
175
|
+
method: "run/steer",
|
|
176
|
+
params: [{ text: "hi" }],
|
|
177
|
+
meta: { requestId: "r-2" },
|
|
178
|
+
},
|
|
179
|
+
],
|
|
144
180
|
};
|
|
145
181
|
root.getValue().save(record);
|
|
146
182
|
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual(
|
|
@@ -150,6 +186,52 @@ describe("LocalStorageSession", () => {
|
|
|
150
186
|
root.unmount();
|
|
151
187
|
});
|
|
152
188
|
|
|
189
|
+
it("discards malformed session records during load", () => {
|
|
190
|
+
const root = mountSession({ threadId: "t1" });
|
|
191
|
+
for (const raw of [
|
|
192
|
+
"{",
|
|
193
|
+
JSON.stringify({
|
|
194
|
+
clientId: "c-1",
|
|
195
|
+
nextSeq: 1,
|
|
196
|
+
ctxNextSeq: 1,
|
|
197
|
+
commands: "invalid",
|
|
198
|
+
}),
|
|
199
|
+
JSON.stringify({
|
|
200
|
+
clientId: "c-1",
|
|
201
|
+
nextSeq: 2,
|
|
202
|
+
ctxNextSeq: 1,
|
|
203
|
+
commands: [{ seq: 1, method: "run", params: null, meta: {} }],
|
|
204
|
+
}),
|
|
205
|
+
JSON.stringify({
|
|
206
|
+
clientId: "c-1",
|
|
207
|
+
nextSeq: 1,
|
|
208
|
+
ctxNextSeq: 1,
|
|
209
|
+
commands: [],
|
|
210
|
+
verdicts: [{ seq: 1, type: "future" }],
|
|
211
|
+
}),
|
|
212
|
+
JSON.stringify({
|
|
213
|
+
clientId: "c-1",
|
|
214
|
+
nextSeq: 1,
|
|
215
|
+
ctxNextSeq: 1,
|
|
216
|
+
commands: [],
|
|
217
|
+
failed: [
|
|
218
|
+
{
|
|
219
|
+
command: "run",
|
|
220
|
+
params: [],
|
|
221
|
+
failure: { fate: "lost", cause: "server" },
|
|
222
|
+
ts: Date.now(),
|
|
223
|
+
seq: 1,
|
|
224
|
+
},
|
|
225
|
+
],
|
|
226
|
+
}),
|
|
227
|
+
]) {
|
|
228
|
+
localStorage.setItem(`${SESSION_PREFIX}t1`, raw);
|
|
229
|
+
expect(root.getValue().load()).toBeNull();
|
|
230
|
+
expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBeNull();
|
|
231
|
+
}
|
|
232
|
+
root.unmount();
|
|
233
|
+
});
|
|
234
|
+
|
|
153
235
|
it("derives the storage key through the key callback", () => {
|
|
154
236
|
const root = mountSession({ threadId: "t1", key: (id) => `user-42:${id}` });
|
|
155
237
|
root.getValue().save({
|
package/src/localStorage.ts
CHANGED
|
@@ -13,13 +13,177 @@ type StoredDraft = {
|
|
|
13
13
|
ts: number;
|
|
14
14
|
};
|
|
15
15
|
|
|
16
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
17
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
+
|
|
19
|
+
const isOptionalString = (value: unknown): boolean =>
|
|
20
|
+
value === undefined || typeof value === "string";
|
|
21
|
+
|
|
22
|
+
const isUserMessagePart = (value: unknown): boolean => {
|
|
23
|
+
if (!isRecord(value)) return false;
|
|
24
|
+
switch (value["type"]) {
|
|
25
|
+
case "text":
|
|
26
|
+
return typeof value["text"] === "string";
|
|
27
|
+
case "image":
|
|
28
|
+
return (
|
|
29
|
+
typeof value["image"] === "string" &&
|
|
30
|
+
isOptionalString(value["filename"])
|
|
31
|
+
);
|
|
32
|
+
case "file":
|
|
33
|
+
return (
|
|
34
|
+
typeof value["data"] === "string" &&
|
|
35
|
+
typeof value["mimeType"] === "string" &&
|
|
36
|
+
isOptionalString(value["filename"])
|
|
37
|
+
);
|
|
38
|
+
case "data":
|
|
39
|
+
return typeof value["name"] === "string";
|
|
40
|
+
case "audio": {
|
|
41
|
+
const audio = value["audio"];
|
|
42
|
+
return (
|
|
43
|
+
isRecord(audio) &&
|
|
44
|
+
typeof audio["data"] === "string" &&
|
|
45
|
+
(audio["format"] === "mp3" || audio["format"] === "wav")
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
default:
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
type StoredAttachment = StoredDraft["attachments"][number];
|
|
54
|
+
|
|
55
|
+
const isStoredAttachment = (value: unknown): value is StoredAttachment => {
|
|
56
|
+
if (!isRecord(value)) return false;
|
|
57
|
+
const status = value["status"];
|
|
58
|
+
return (
|
|
59
|
+
typeof value["id"] === "string" &&
|
|
60
|
+
typeof value["type"] === "string" &&
|
|
61
|
+
typeof value["name"] === "string" &&
|
|
62
|
+
isOptionalString(value["contentType"]) &&
|
|
63
|
+
value["file"] === undefined &&
|
|
64
|
+
isRecord(status) &&
|
|
65
|
+
status["type"] === "complete" &&
|
|
66
|
+
Array.isArray(value["content"]) &&
|
|
67
|
+
value["content"].every(isUserMessagePart)
|
|
68
|
+
);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const isStoredDraft = (value: unknown): value is StoredDraft =>
|
|
72
|
+
isRecord(value) &&
|
|
73
|
+
typeof value["text"] === "string" &&
|
|
74
|
+
Array.isArray(value["attachments"]) &&
|
|
75
|
+
value["attachments"].every(isStoredAttachment) &&
|
|
76
|
+
typeof value["ts"] === "number" &&
|
|
77
|
+
Number.isFinite(value["ts"]);
|
|
78
|
+
|
|
79
|
+
const isPositiveSafeInteger = (value: unknown): value is number =>
|
|
80
|
+
typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
81
|
+
|
|
82
|
+
const isSessionCommand = (
|
|
83
|
+
value: unknown,
|
|
84
|
+
): value is StatewireClient.SessionCommand =>
|
|
85
|
+
isRecord(value) &&
|
|
86
|
+
isPositiveSafeInteger(value["seq"]) &&
|
|
87
|
+
typeof value["method"] === "string" &&
|
|
88
|
+
Array.isArray(value["params"]);
|
|
89
|
+
|
|
90
|
+
const isSessionVerdict = (
|
|
91
|
+
value: unknown,
|
|
92
|
+
): value is StatewireClient.SessionVerdict =>
|
|
93
|
+
isRecord(value) &&
|
|
94
|
+
isPositiveSafeInteger(value["seq"]) &&
|
|
95
|
+
(value["type"] === "result" ||
|
|
96
|
+
value["type"] === "rejected" ||
|
|
97
|
+
value["type"] === "failed" ||
|
|
98
|
+
value["type"] === "crashed" ||
|
|
99
|
+
value["type"] === "expired") &&
|
|
100
|
+
isOptionalString(value["code"]) &&
|
|
101
|
+
isOptionalString(value["message"]);
|
|
102
|
+
|
|
103
|
+
const isSendFailure = (
|
|
104
|
+
value: unknown,
|
|
105
|
+
): value is StatewireClient.SendFailure => {
|
|
106
|
+
if (!isRecord(value)) return false;
|
|
107
|
+
switch (value["fate"]) {
|
|
108
|
+
case "rejected":
|
|
109
|
+
return (
|
|
110
|
+
value["cause"] === "server" &&
|
|
111
|
+
isOptionalString(value["code"]) &&
|
|
112
|
+
isOptionalString(value["message"])
|
|
113
|
+
);
|
|
114
|
+
case "failed":
|
|
115
|
+
return value["cause"] === "server" && isOptionalString(value["message"]);
|
|
116
|
+
case "crashed":
|
|
117
|
+
case "expired":
|
|
118
|
+
return value["cause"] === "server";
|
|
119
|
+
case "aborted":
|
|
120
|
+
return (
|
|
121
|
+
(value["cause"] === "unmount" ||
|
|
122
|
+
value["cause"] === "stream-gone" ||
|
|
123
|
+
value["cause"] === "session-lost") &&
|
|
124
|
+
(value["predecessorLost"] === undefined ||
|
|
125
|
+
value["predecessorLost"] === true)
|
|
126
|
+
);
|
|
127
|
+
case "lost":
|
|
128
|
+
return (
|
|
129
|
+
value["cause"] === "unmount" ||
|
|
130
|
+
value["cause"] === "stream-gone" ||
|
|
131
|
+
value["cause"] === "session-lost"
|
|
132
|
+
);
|
|
133
|
+
default:
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const isFailedCommand = (
|
|
139
|
+
value: unknown,
|
|
140
|
+
): value is StatewireClient.FailedCommand =>
|
|
141
|
+
isRecord(value) &&
|
|
142
|
+
typeof value["command"] === "string" &&
|
|
143
|
+
Array.isArray(value["params"]) &&
|
|
144
|
+
isSendFailure(value["failure"]) &&
|
|
145
|
+
typeof value["ts"] === "number" &&
|
|
146
|
+
Number.isFinite(value["ts"]) &&
|
|
147
|
+
isPositiveSafeInteger(value["seq"]);
|
|
148
|
+
|
|
149
|
+
const isSessionRecord = (
|
|
150
|
+
value: unknown,
|
|
151
|
+
): value is StatewireClient.SessionRecord =>
|
|
152
|
+
isRecord(value) &&
|
|
153
|
+
typeof value["clientId"] === "string" &&
|
|
154
|
+
isPositiveSafeInteger(value["nextSeq"]) &&
|
|
155
|
+
isPositiveSafeInteger(value["ctxNextSeq"]) &&
|
|
156
|
+
Array.isArray(value["commands"]) &&
|
|
157
|
+
value["commands"].every(isSessionCommand) &&
|
|
158
|
+
(value["verdicts"] === undefined ||
|
|
159
|
+
(Array.isArray(value["verdicts"]) &&
|
|
160
|
+
value["verdicts"].every(isSessionVerdict))) &&
|
|
161
|
+
(value["failed"] === undefined ||
|
|
162
|
+
(Array.isArray(value["failed"]) && value["failed"].every(isFailedCommand)));
|
|
163
|
+
|
|
164
|
+
const loadStored = <T>(
|
|
165
|
+
key: string,
|
|
166
|
+
validate: (value: unknown) => value is T,
|
|
167
|
+
): T | null => {
|
|
168
|
+
const raw = localStorage.getItem(key);
|
|
169
|
+
if (raw === null) return null;
|
|
170
|
+
try {
|
|
171
|
+
const value: unknown = JSON.parse(raw);
|
|
172
|
+
if (validate(value)) return value;
|
|
173
|
+
} catch {}
|
|
174
|
+
localStorage.removeItem(key);
|
|
175
|
+
return null;
|
|
176
|
+
};
|
|
177
|
+
|
|
16
178
|
const sweep = (ttl: number, max: number) => {
|
|
17
179
|
const entries: { key: string; ts: number }[] = [];
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
180
|
+
const keys = Array.from({ length: localStorage.length }, (_, index) =>
|
|
181
|
+
localStorage.key(index),
|
|
182
|
+
);
|
|
183
|
+
for (const key of keys) {
|
|
184
|
+
if (key === null || !key.startsWith(PREFIX)) continue;
|
|
185
|
+
const stored = loadStored(key, isStoredDraft);
|
|
186
|
+
if (stored !== null) entries.push({ key, ts: stored.ts });
|
|
23
187
|
}
|
|
24
188
|
const now = Date.now();
|
|
25
189
|
const fresh = entries.filter(({ key, ts }) => {
|
|
@@ -50,10 +214,9 @@ const useLocalStorageComposerDrafts = ({
|
|
|
50
214
|
return useMemo(
|
|
51
215
|
(): StatewireThread.ComposerStorage => ({
|
|
52
216
|
read: () => {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
55
|
-
|
|
56
|
-
return { text, attachments };
|
|
217
|
+
const stored = loadStored(storageKey, isStoredDraft);
|
|
218
|
+
if (stored === null) return undefined;
|
|
219
|
+
return { text: stored.text, attachments: stored.attachments };
|
|
57
220
|
},
|
|
58
221
|
write: (draft) => {
|
|
59
222
|
if (draft.text === "" && draft.attachments.length === 0) {
|
|
@@ -97,9 +260,7 @@ const useLocalStorageSession = ({
|
|
|
97
260
|
return useMemo(
|
|
98
261
|
(): StatewireClient.SessionStorage => ({
|
|
99
262
|
load: () => {
|
|
100
|
-
|
|
101
|
-
if (raw === null) return null;
|
|
102
|
-
return JSON.parse(raw) as StatewireClient.SessionRecord;
|
|
263
|
+
return loadStored(storageKey, isSessionRecord);
|
|
103
264
|
},
|
|
104
265
|
save: (record) => {
|
|
105
266
|
localStorage.setItem(storageKey, JSON.stringify(record));
|