@assistant-ui/react-statewire 0.18.0 → 0.20.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/dist/StatewireThread.d.ts +3 -3
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +3 -2
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +1 -1
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +13 -2
- package/dist/localStorage.js.map +1 -1
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.runs.test.tsx +90 -3
- package/src/StatewireThread.test.tsx +1 -1
- package/src/StatewireThread.ts +27 -5
- package/src/localStorage.test.ts +72 -0
- package/src/localStorage.ts +18 -2
- package/src/runsOptimistic.ts +1 -1
|
@@ -140,8 +140,8 @@ declare namespace StatewireThread {
|
|
|
140
140
|
};
|
|
141
141
|
/** Run subsystem status replicated by the host. */
|
|
142
142
|
export type RunStatus = "running" | "stopped" | "error" | "input-required";
|
|
143
|
-
/** The thread's status
|
|
144
|
-
export type ThreadStatus = "loading" | "ready" | RunStatus;
|
|
143
|
+
/** 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. */
|
|
144
|
+
export type ThreadStatus = "loading" | "ready" | "evicted" | "disconnected" | RunStatus;
|
|
145
145
|
/** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
|
|
146
146
|
export type RunsQueueEntry = UserMessage & {
|
|
147
147
|
/** Host-stamped opaque per-entry metadata. */
|
|
@@ -202,7 +202,7 @@ declare namespace StatewireThread {
|
|
|
202
202
|
/** The runs mount as replicated: the run entries plus the top-level status projection. */
|
|
203
203
|
export type RunsState = {
|
|
204
204
|
/** Projection of `runs[0]?.status ?? "ready"`. */
|
|
205
|
-
readonly status:
|
|
205
|
+
readonly status: "ready" | RunStatus;
|
|
206
206
|
/** At most one entry; empty while resting. */
|
|
207
207
|
readonly runs: readonly RunState[];
|
|
208
208
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA8Ca;cAEA,oBAAqB,oBAAkB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA8Ca;cAEA,oBAAqB,oBAAkB,gBAAgB;cA8WvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;;cAGzC;aACD;aACA,sBAAsB;;;cAIrB;IACV,QAAQ;IACR,MAAM,OAAO;IACb;;cAGU;KACT;IACD,cAAc,SAAS;IACvB;IACA;IACA,QAAQ;;IAER;IACA,wBAAwB;IACxB,MAAM;;cAGI;aACD;aACA;;cAGC;aACD;aACA;aACA;aACA;;cAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;cAIV;aACD;aACA;;cAGC;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;;aAEA;;aAGI,SAAS;;aAET;;aAEA;OAEb;cAEU;aACD;aACA;aACA;;cAGC;aACD;;aAEA;aACA,SAAS;aACT;;aAEA;;cAGC;aACD;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;aACA;;cAGC;aACD;aACA;cACC,cAAc;;;cAId,eACR,uBACA,2BACA;cAEQ,gBAAgB;cAEhB;aACD;aACA;aACA;aACA,UAAU;;;cAIT,oBAAoB;aACrB,WAAW;;aAEX,OAAO;;cAGN;aACD;;aAEA;aACA;;aAEA;;cAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;cAEQ,UAAU,aAAa;;cAGvB;aACD;aACA,iBAAiB,WAAW;;;cAI3B;;cAGA,kEAKR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;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -19,6 +19,7 @@ const RESTING_RUNS = {
|
|
|
19
19
|
queue: [],
|
|
20
20
|
steerQueue: []
|
|
21
21
|
};
|
|
22
|
+
const presentStatus = (status, connection) => status !== "running" || connection.status === "live" || connection.status === "idle" ? status : connection.status === "reconnecting" && connection.cause === "evicted" ? "evicted" : "disconnected";
|
|
22
23
|
const ambientContextOf = (context) => ({
|
|
23
24
|
...context.system !== void 0 && { system: context.system },
|
|
24
25
|
...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
|
|
@@ -91,7 +92,7 @@ const useStatewireThread = (options) => {
|
|
|
91
92
|
const entries = state_0?.runs;
|
|
92
93
|
const entry = entries?.[0];
|
|
93
94
|
return {
|
|
94
|
-
status: entries === void 0 ? "loading" : entry?.status ?? "ready",
|
|
95
|
+
status: presentStatus(entries === void 0 ? "loading" : entry?.status ?? "ready", connection_0),
|
|
95
96
|
runs: entry === void 0 ? RESTING_RUNS : {
|
|
96
97
|
runId: entry.runId,
|
|
97
98
|
...entry.epoch !== void 0 && { epoch: entry.epoch },
|
|
@@ -104,7 +105,7 @@ const useStatewireThread = (options) => {
|
|
|
104
105
|
...entry.error !== void 0 && { error: entry.error }
|
|
105
106
|
}
|
|
106
107
|
};
|
|
107
|
-
}, [state_0]);
|
|
108
|
+
}, [state_0, connection_0]);
|
|
108
109
|
const { converter } = options;
|
|
109
110
|
const metadata = useMemo(() => ({
|
|
110
111
|
pendingCommands: [...pending],
|
|
@@ -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","createRunQueueAdapter","resolveEditCommand","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","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","connection","setContext","isBusy","transport","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","status","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","ThreadStatus","entries","RunState","entry","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","storageRef","storageHook","hook","read","getState","isEmpty","attachment","addAttachment","id","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","Exclude","ConnectionState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput"],"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 createRunQueueAdapter,\n resolveEditCommand,\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};\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 { state, commands, connection, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\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 });\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 return {\n status: entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n runs:\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 && { stopping: entry.stopping }),\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 };\n }, [state]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n }),\n [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n ],\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 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 sendCommand: (command: Command) => void;\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 };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n /** 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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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, derived from the state: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status. */\n export type ThreadStatus = \"loading\" | \"ready\" | 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 /** 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: Exclude<ThreadStatus, \"loading\">;\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 };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\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 }\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 }\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":";;;;;;;;;;AA8CA,MAAayC,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;AACd;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOlC,kBAAkB+B,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS9D,OAAO4D,OAAO;CAC7BE,OAAOC,UAAUH;CAEjB,MAAM,CAACI,SAASC,cAAchE,SAC5B,CAAA,CACF;CACA,MAAM,CAACkE,UAAUlE,gBACRmE,YACLH,YAAYI,SACVA,KAAKC,SAASF,OAAkC,IAC5CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAM,EAAEI,OAAAA,SAAOC,UAAUC,YAAAA,cAAYC,YAAYC,WAAWrD,aAG1D;EACAsD,WAAWlB,QAAQkB;EACnBC,SAASnB,QAAQmB;EACjBC,cAAcpB,QAAQoB;EACtBC,aAAaC,OAAOd,WAASe,QAAQ;GACnCjD,eAAegD,OAAOd,WAASe,GAAG;GAClCrB,OAAOC,QAAQkB,aAAaC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B,UAAUC,aAAalB;EACvB,IAAIU,cAAc,MAAME,iBAAiBrD,WAAW,GAAG;GACrD,IAAI,CAAC4D,YAAYvH,UAAQwH,MAAM;GAC/B;EACF;EACAxH,UAAQyH,MAAM;GAAErF,MAAM0E;GAAWlC,aAAaoC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWjB;EAAaU;EAAWE;CAAgB,CAAC;CAExD,OAAOxC;AACT;AAEA,MAAa7G,mBACXkB,YAEA1D,SAASyD,kBAAkB,CAAC,CAACC,OAAuC;AAuYtElD,uBACEiD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAAC6H,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createRunQueueAdapter","resolveEditCommand","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","presentStatus","status","ThreadStatus","connection","ConnectionState","cause","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","setContext","isBusy","transport","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","entry","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","sendCommand","reconnect","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","storageRef","storageHook","hook","read","getState","isEmpty","attachment","addAttachment","id","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunEnqueueCommand","runAnchorMessageId","messageId","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","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"],"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 createRunQueueAdapter,\n resolveEditCommand,\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};\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 === \"live\" ||\n connection.status === \"idle\"\n ? status\n : connection.status === \"reconnecting\" && 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 { state, commands, connection, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\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 });\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 return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\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 && { stopping: entry.stopping }),\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 };\n }, [state, connection]);\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 inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo(\n (): StatewireThread.Extras => ({\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n }),\n [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n ],\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 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 sendCommand: (command: Command) => void;\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 };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n export type RunEnqueueCommand = {\n readonly type: \"run/enqueue\";\n /** 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 RunSteerCommand = {\n readonly type: \"run/steer\";\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 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 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 /** 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 };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\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 }\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 }\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":";;;;;;;;;;AA8CA,MAAayC,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,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UAAQsH,MAAM;GAC/B;EACF;EACAtH,UAAQuH,MAAM;GAAEpF,MAAMyE;GAAWlC,aAAaoC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWjB;EAAaU;EAAWE;CAAgB,CAAC;CAExD,OAAOxC;AACT;AAEA,MAAahH,mBACXwB,YAEAhE,SAAS+D,kBAAkB,CAAC,CAACC,OAAuC;AA4YtExD,uBACEuD,oBACA1D,eAAesD,KAAAA,CAAkB,CAAC,CAAC0H,IACrC"}
|
package/dist/localStorage.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { StatewireThread } from "./StatewireThread.js";
|
|
|
2
2
|
//#region src/localStorage.d.ts
|
|
3
3
|
/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
|
|
4
4
|
declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
|
|
5
|
-
/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
|
|
5
|
+
/** 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. */
|
|
6
6
|
declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
|
|
7
7
|
declare namespace LocalStorageSession {
|
|
8
8
|
type Options = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA4Ea,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;
|
|
1
|
+
{"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA4Ea,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA4C1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
|
package/dist/localStorage.js
CHANGED
|
@@ -57,9 +57,12 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
|
|
|
57
57
|
};
|
|
58
58
|
/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
|
|
59
59
|
const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
|
|
60
|
+
const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
|
|
60
61
|
const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
|
|
61
62
|
if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
|
|
63
|
+
if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
|
|
62
64
|
const storageKey = SESSION_PREFIX + key(threadId);
|
|
65
|
+
const lockName = SESSION_LOCK_PREFIX + key(threadId);
|
|
63
66
|
return useMemo(() => ({
|
|
64
67
|
load: () => {
|
|
65
68
|
const raw = localStorage.getItem(storageKey);
|
|
@@ -68,10 +71,18 @@ const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
|
|
|
68
71
|
},
|
|
69
72
|
save: (record) => {
|
|
70
73
|
localStorage.setItem(storageKey, JSON.stringify(record));
|
|
74
|
+
},
|
|
75
|
+
lock: (fn) => navigator.locks.request(lockName, async () => fn()),
|
|
76
|
+
subscribe: (listener) => {
|
|
77
|
+
const onStorage = (event) => {
|
|
78
|
+
if (event.key === storageKey) listener();
|
|
79
|
+
};
|
|
80
|
+
window.addEventListener("storage", onStorage);
|
|
81
|
+
return () => window.removeEventListener("storage", onStorage);
|
|
71
82
|
}
|
|
72
|
-
}), [storageKey]);
|
|
83
|
+
}), [storageKey, lockName]);
|
|
73
84
|
};
|
|
74
|
-
/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
|
|
85
|
+
/** 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. */
|
|
75
86
|
const LocalStorageSession = resource(useLocalStorageSession);
|
|
76
87
|
//#endregion
|
|
77
88
|
export { LocalStorageComposerDrafts, LocalStorageSession };
|
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","useLocalStorageSession","LocalStorageSession","SessionStorage","load","SessionRecord","save","record"],"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 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\n const storageKey = SESSION_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 }),\n [storageKey],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */\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,SAASC,KAAaC,QAAgB;CAC1C,MAAMC,UAAyC,CAAA;CAC/C,KAAK,IAAIE,IAAI,GAAGA,IAAIC,aAAaC,QAAQF,KAAK;EAC5C,MAAMD,MAAME,aAAaF,IAAIC,CAAC;EAC9B,IAAI,CAACD,IAAII,WAAWhB,MAAM,GAAG;EAC7B,MAAM,EAAEO,OAAOU,KAAKC,MAAMJ,aAAaK,QAAQP,GAAG,CAAE;EACpDD,QAAQS,KAAK;GAAER;GAAKL;EAAG,CAAC;CAC1B;CACA,MAAMc,MAAMC,KAAKD,IAAI;CACrB,MAAME,QAAQZ,QAAQa,QAAQ,EAAEZ,KAAKL,SAAS;EAC5C,IAAIc,MAAMd,MAAME,KAAK,OAAO;EAC5BK,aAAaW,WAAWb,GAAG;EAC3B,OAAO;CACT,CAAC;CACDW,MAAMG,MAAMC,GAAGC,MAAMA,EAAErB,KAAKoB,EAAEpB,EAAE;CAChC,KAAK,MAAM,EAAEK,SAASW,MAAMM,MAAMnB,GAAG,GAAGI,aAAaW,WAAWb,GAAG;AACrE;AAEA,MAAMkB,iCAAiC,EACrCC,UACAnB,OAAOoB,OAAOA,IACdvB,MAAM,IAAIP,KACVQ,MAAM,SACmE;CACzE,IAAI,OAAOI,iBAAiB,aAC1B,MAAM,IAAIsB,MACR,6DACF;CAEFzC,gBAAgB;EACda,MAAMC,KAAKC,GAAG;CAChB,GAAG,CAACD,KAAKC,GAAG,CAAC;CAEb,MAAM2B,aAAarC,SAASY,IAAImB,QAAQ;CACxC,OAAOnC,eACmC;EACtC0C,YAAY;GACV,MAAMC,MAAMzB,aAAaK,QAAQkB,UAAU;GAC3C,IAAIE,QAAQ,MAAM,OAAOC,KAAAA;GACzB,MAAM,EAAEpC,MAAMC,gBAAgBY,KAAKC,MAAMqB,GAAG;GAC5C,OAAO;IAAEnC;IAAMC;GAAY;EAC7B;EACAoC,QAAQC,UAAU;GAChB,IAAIA,MAAMtC,SAAS,MAAMsC,MAAMrC,YAAYU,WAAW,GAAG;IACvDD,aAAaW,WAAWY,UAAU;IAClC;GACF;GACAvB,aAAa6B,QACXN,YACApB,KAAK2B,UAAU;IAAE,GAAGF;IAAOnC,IAAIe,KAAKD,IAAI;GAAE,CAAC,CAC7C;EACF;EACAwB,aAAa;GACX/B,aAAaW,WAAWY,UAAU;EACpC;CACF,IACA,CAACA,UAAU,CACb;AACF;;AAGA,MAAaJ,6BAA6BpC,SACxCiC,6BACF;AAEA,MAAMgB,0BAA0B,
|
|
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,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,SAASC,KAAaC,QAAgB;CAC1C,MAAMC,UAAyC,CAAA;CAC/C,KAAK,IAAIE,IAAI,GAAGA,IAAIC,aAAaC,QAAQF,KAAK;EAC5C,MAAMD,M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E,CAAC,CAC7C;EACF;EACAwB,aAAa;GACX/B,aAAaW,WAAWY,UAAU;EACpC;CACF,IACA,CAACA,UAAU,CACb;AACF;;AAGA,MAAaJ,6BAA6BpC,SACxCiC,6BACF;AAEA,MAAMgB,sBAAsB;AAE5B,MAAMC,0BAA0B,EAC9BhB,UACAnB,OAAOoB,OAAOA,SACmD;CACjE,IAAI,OAAOlB,iBAAiB,aAC1B,MAAM,IAAIsB,MAAM,sDAAsD;CAExE,IAAI,OAAOc,cAAc,eAAeA,UAAUC,UAAUX,KAAAA,GAC1D,MAAM,IAAIJ,MACR,6EACF;CAEF,MAAMC,aAAapC,iBAAiBW,IAAImB,QAAQ;CAChD,MAAMqB,WAAWN,sBAAsBlC,IAAImB,QAAQ;CACnD,OAAOnC,eACkC;EACrCyD,YAAY;GACV,MAAMd,MAAMzB,aAAaK,QAAQkB,UAAU;GAC3C,IAAIE,QAAQ,MAAM,OAAO;GACzB,OAAOtB,KAAKC,MAAMqB,GAAG;EACvB;EACAgB,OAAOC,WAAW;GAChB1C,aAAa6B,QAAQN,YAAYpB,KAAK2B,UAAUY,MAAM,CAAC;EACzD;EACAC,OAAOC,OAAOR,UAAUC,MAAMQ,QAAQP,UAAU,YAAYM,GAAG,CAAC;EAChEE,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAMnD,QAAQyB,YAAYwB,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA,CAACzB,YAAYe,QAAQ,CACvB;AACF;;AAGA,MAAaJ,sBAAsBnD,SAASkD,sBAAsB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","Dispatch","trigger","messages","rollbackTo","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","stopping","reason","nextDispatch","inputRequests","response","error","RunsDraft","Exclude","ThreadStatus","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","steer","type","direct","target","push","continues","Error","hasPlacement","stageRewind","dispatch","runsOptimistic","mount","Command","args","ctx","OptimisticContext","commandRunId","params","seq","method","runAnchorMessageId","RunEditCommand","RunReloadCommand","RunDequeueCommand","requestId","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype Dispatch = {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching?: Dispatch;\n stopping?: { reason: \"stop\" | \"message-edit\" | \"message-reload\" };\n nextDispatch?: Dispatch;\n inputRequests?: { id: string; response?: unknown }[];\n error?: unknown;\n};\n\ntype RunsDraft = {\n status: Exclude<StatewireThread.ThreadStatus, \"loading\">;\n runs?: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const steer = command.type === \"run/steer\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"message-send\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n run.stopping = {\n reason: dispatch.trigger as \"message-edit\" | \"message-reload\",\n };\n run.nextDispatch = dispatch;\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"message-edit\",\n messages: [{ ...message }],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n run.stopping = { reason: \"stop\" };\n delete run.nextDispatch;\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests === undefined) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAkCA,MAAMiC,YAAYC,OAAkBjB,UAA4B;CAC9D,MAAMkB,QAAS,CAACD,MAAMF,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCf,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;CACd;CACAc,MAAMjB,SAAS;CAEf,IAAIiB,MAAMlB,UAAU,MAAMkB,MAAMlB,QAAQA;CACxC,OAAOkB,MAAMP;CACb,OAAOO,MAAMT;CACbQ,MAAMhB,SAAS;CACf,OAAOiB;AACT;AAEA,MAAMC,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAExC,OAAOkC,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKQ,SACLR,KAAKM,WAAWC,MAAMA,EAAExC,OAAOmC,YAAY;CACnDF,KAAKS,OAAOL,QAAQ,IAAIJ,KAAKQ,SAASJ,OAAO,GAAGN,KAAK;AACvD;AAEA,MAAMY,kBACJb,OACAc,SACA/B,UACS;CACT,MAAMkC,MAAMjB,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,GAAW;GAC1BoB,OAAOnC,WAAWA;GAClB,IAAI0D,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGrD,SAASC,OAAOjB,KAAK;GACjE;EACF;CAGF;AACF"}
|
|
1
|
+
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","Dispatch","trigger","messages","rollbackTo","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","stopping","reason","nextDispatch","inputRequests","response","error","RunsDraft","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","steer","type","direct","target","push","continues","Error","hasPlacement","stageRewind","dispatch","runsOptimistic","mount","Command","args","ctx","OptimisticContext","commandRunId","params","seq","method","runAnchorMessageId","RunEditCommand","RunReloadCommand","RunDequeueCommand","requestId","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype Dispatch = {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching?: Dispatch;\n stopping?: { reason: \"stop\" | \"message-edit\" | \"message-reload\" };\n nextDispatch?: Dispatch;\n inputRequests?: { id: string; response?: unknown }[];\n error?: unknown;\n};\n\ntype RunsDraft = {\n status: \"ready\" | StatewireThread.RunStatus;\n runs?: RunEntry[];\n};\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = command.message.parts;\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = { ...command.message };\n }\n\n const steer = command.type === \"run/steer\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"message-send\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n run.stopping = {\n reason: dispatch.trigger as \"message-edit\" | \"message-reload\",\n };\n run.nextDispatch = dispatch;\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"message-edit\",\n messages: [{ ...message }],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n run.stopping = { reason: \"stop\" };\n delete run.nextDispatch;\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests === undefined) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAkCA,MAAM+B,YAAYC,OAAkBf,UAA4B;CAC9D,MAAMgB,QAAS,CAACD,MAAMF,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCb,OAAO;EACPC,QAAQ;EACRE,OAAO,CAAA;EACPC,YAAY,CAAA;CACd;CACAY,MAAMf,SAAS;CAEf,IAAIe,MAAMhB,UAAU,MAAMgB,MAAMhB,QAAQA;CACxC,OAAOgB,MAAML;CACb,OAAOK,MAAMP;CACbM,MAAMd,SAAS;CACf,OAAOe;AACT;AAEA,MAAMC,UACJC,MACAF,OACA,EAAEG,aAAaC,mBACN;CACT,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAEtC,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;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE0C,WAAWtD,aAAamB,QAC7B4B,OAAO;GACV,MAAMS,WAAWnD,MAAMF,OAAO,EAAE,EAAEJ;GAClC,IAAIyD,aAAa3C,KAAAA,GAAW;GAC5B,MAAMoB,SAASuB,SAAS7B,MAAM8B,MAAMA,EAAEhF,OAAO6E,SAAS;GACtD,IAAIrB,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOjC,WAAWA;GAClB,IAAIwD,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGrD,SAASC,OAAOf,KAAK;GACjE;EACF;CAGF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.0",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"@assistant-ui/store": "^0.3.0",
|
|
38
38
|
"@assistant-ui/tap": "^0.9.7",
|
|
39
39
|
"assistant-stream": "^0.3.37",
|
|
40
|
-
"statewire": "^0.
|
|
40
|
+
"statewire": "^0.11.0"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
43
|
"@assistant-ui/core": ">=0.3.12",
|
|
@@ -45,7 +45,7 @@ type ServerRunEntry = {
|
|
|
45
45
|
|
|
46
46
|
type RunsServerState = {
|
|
47
47
|
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
48
|
-
status:
|
|
48
|
+
status: "ready" | StatewireThread.RunStatus;
|
|
49
49
|
runs?: ServerRunEntry[];
|
|
50
50
|
};
|
|
51
51
|
|
|
@@ -138,6 +138,13 @@ const createRemoteServer = (
|
|
|
138
138
|
parkedSnapshot?.();
|
|
139
139
|
parkedSnapshot = undefined;
|
|
140
140
|
};
|
|
141
|
+
let finSent = false;
|
|
142
|
+
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
143
|
+
const fin = (reason: string) => {
|
|
144
|
+
finSent = true;
|
|
145
|
+
stream!.enqueue(encoder.encode(frame({ fin: { reason } })));
|
|
146
|
+
stream!.close();
|
|
147
|
+
};
|
|
141
148
|
type Frame = {
|
|
142
149
|
ctx?: { seq: number }[];
|
|
143
150
|
cmd?: { method: string; params: unknown[]; seq: number }[];
|
|
@@ -163,6 +170,9 @@ const createRemoteServer = (
|
|
|
163
170
|
const attachFrame = JSON.parse(String(init2?.body)) as Frame;
|
|
164
171
|
const body = new ReadableStream<Uint8Array>({
|
|
165
172
|
start: (c) => {
|
|
173
|
+
stream = c;
|
|
174
|
+
// Reattach attempts after a fin park, so the episode status holds.
|
|
175
|
+
if (finSent) return;
|
|
166
176
|
const sendSnapshot = () => {
|
|
167
177
|
c.enqueue(
|
|
168
178
|
encoder.encode(
|
|
@@ -202,6 +212,7 @@ const createRemoteServer = (
|
|
|
202
212
|
return {
|
|
203
213
|
received,
|
|
204
214
|
release,
|
|
215
|
+
fin,
|
|
205
216
|
transport: StatewireSSE<RunsServerState>({
|
|
206
217
|
url: "http://fake/api",
|
|
207
218
|
fetch: fetchImpl,
|
|
@@ -713,8 +724,9 @@ describe("StatewireThread runs mode", () => {
|
|
|
713
724
|
aui().thread().append("hello");
|
|
714
725
|
});
|
|
715
726
|
|
|
716
|
-
// The pre-attach send renders through the same optimistic + materialize
|
|
717
|
-
|
|
727
|
+
// The pre-attach send renders through the same optimistic + materialize
|
|
728
|
+
// folds; while connecting, the run presents as disconnected.
|
|
729
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
718
730
|
expect(runs().runId).toEqual(expect.any(String));
|
|
719
731
|
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
720
732
|
expect(server.received).toEqual([]);
|
|
@@ -848,3 +860,78 @@ describe("StatewireThread runs mode", () => {
|
|
|
848
860
|
expect(observedStatus).toEqual(["running"]);
|
|
849
861
|
});
|
|
850
862
|
});
|
|
863
|
+
|
|
864
|
+
describe("StatewireThread connection presentation", () => {
|
|
865
|
+
it("presents a running run as evicted while reconnecting from eviction", async () => {
|
|
866
|
+
const server = createRemoteServer(
|
|
867
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
868
|
+
);
|
|
869
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
870
|
+
|
|
871
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
872
|
+
server.fin("evicted");
|
|
873
|
+
|
|
874
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("evicted"));
|
|
875
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
it("presents a running run as disconnected while reconnecting from a non-eviction", async () => {
|
|
879
|
+
const server = createRemoteServer(
|
|
880
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
881
|
+
);
|
|
882
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
883
|
+
|
|
884
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
885
|
+
server.fin("error");
|
|
886
|
+
|
|
887
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
888
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
it("presents a running run as disconnected when the session is gone", async () => {
|
|
892
|
+
const server = createRemoteServer(
|
|
893
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
894
|
+
);
|
|
895
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
896
|
+
|
|
897
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
898
|
+
server.fin("gone");
|
|
899
|
+
|
|
900
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
901
|
+
});
|
|
902
|
+
|
|
903
|
+
it("presents a preloaded running run as disconnected while connecting", async () => {
|
|
904
|
+
const running = withRun({ status: "running", runId: "run-1" });
|
|
905
|
+
const server = createRemoteServer(running, { hold: true });
|
|
906
|
+
const { aui } = mountThread({
|
|
907
|
+
transport: server.transport,
|
|
908
|
+
initialState: { ...INITIAL_STATE, ...running },
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
expect(threadStatus(aui())).toBe("disconnected");
|
|
912
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
913
|
+
|
|
914
|
+
server.release();
|
|
915
|
+
|
|
916
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
917
|
+
expect(aui().thread().getState().isRunning).toBe(true);
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
it.each(["input-required", "error", "stopped"] as const)(
|
|
921
|
+
"passes %s through the disconnected overlay",
|
|
922
|
+
async (status) => {
|
|
923
|
+
const server = createRemoteServer(withRun({ status, runId: "run-1" }));
|
|
924
|
+
const statuses: string[] = [];
|
|
925
|
+
const { aui } = mountThread({
|
|
926
|
+
transport: server.transport,
|
|
927
|
+
onConnectionChange: (connection) => statuses.push(connection.status),
|
|
928
|
+
});
|
|
929
|
+
|
|
930
|
+
await waitFor(() => expect(threadStatus(aui())).toBe(status));
|
|
931
|
+
server.fin("error");
|
|
932
|
+
|
|
933
|
+
await waitFor(() => expect(statuses).toContain("reconnecting"));
|
|
934
|
+
expect(threadStatus(aui())).toBe(status);
|
|
935
|
+
},
|
|
936
|
+
);
|
|
937
|
+
});
|
package/src/StatewireThread.ts
CHANGED
|
@@ -67,6 +67,20 @@ const RESTING_RUNS: StatewireThread.Runs = {
|
|
|
67
67
|
steerQueue: [],
|
|
68
68
|
};
|
|
69
69
|
|
|
70
|
+
// Derived presentation while the connection can't vouch for progress:
|
|
71
|
+
// live-claiming "running" reads as evicted/disconnected; facts pass through.
|
|
72
|
+
const presentStatus = (
|
|
73
|
+
status: StatewireThread.ThreadStatus,
|
|
74
|
+
connection: StatewireClient.ConnectionState,
|
|
75
|
+
): StatewireThread.ThreadStatus =>
|
|
76
|
+
status !== "running" ||
|
|
77
|
+
connection.status === "live" ||
|
|
78
|
+
connection.status === "idle"
|
|
79
|
+
? status
|
|
80
|
+
: connection.status === "reconnecting" && connection.cause === "evicted"
|
|
81
|
+
? "evicted"
|
|
82
|
+
: "disconnected";
|
|
83
|
+
|
|
70
84
|
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
71
85
|
...(context.system !== undefined && { system: context.system }),
|
|
72
86
|
...(context.tools !== undefined && {
|
|
@@ -183,7 +197,10 @@ const useStatewireThread = (
|
|
|
183
197
|
)?.runs;
|
|
184
198
|
const entry = entries?.[0];
|
|
185
199
|
return {
|
|
186
|
-
status:
|
|
200
|
+
status: presentStatus(
|
|
201
|
+
entries === undefined ? "loading" : (entry?.status ?? "ready"),
|
|
202
|
+
connection,
|
|
203
|
+
),
|
|
187
204
|
runs:
|
|
188
205
|
entry === undefined
|
|
189
206
|
? RESTING_RUNS
|
|
@@ -205,7 +222,7 @@ const useStatewireThread = (
|
|
|
205
222
|
...(entry.error !== undefined && { error: entry.error }),
|
|
206
223
|
},
|
|
207
224
|
};
|
|
208
|
-
}, [state]);
|
|
225
|
+
}, [state, connection]);
|
|
209
226
|
|
|
210
227
|
const { converter } = options;
|
|
211
228
|
const metadata = useMemo(
|
|
@@ -573,8 +590,13 @@ export namespace StatewireThread {
|
|
|
573
590
|
/** Run subsystem status replicated by the host. */
|
|
574
591
|
export type RunStatus = "running" | "stopped" | "error" | "input-required";
|
|
575
592
|
|
|
576
|
-
/** The thread's status
|
|
577
|
-
export type ThreadStatus =
|
|
593
|
+
/** 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. */
|
|
594
|
+
export type ThreadStatus =
|
|
595
|
+
| "loading"
|
|
596
|
+
| "ready"
|
|
597
|
+
| "evicted"
|
|
598
|
+
| "disconnected"
|
|
599
|
+
| RunStatus;
|
|
578
600
|
|
|
579
601
|
/** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
|
|
580
602
|
export type RunsQueueEntry = UserMessage & {
|
|
@@ -650,7 +672,7 @@ export namespace StatewireThread {
|
|
|
650
672
|
/** The runs mount as replicated: the run entries plus the top-level status projection. */
|
|
651
673
|
export type RunsState = {
|
|
652
674
|
/** Projection of `runs[0]?.status ?? "ready"`. */
|
|
653
|
-
readonly status:
|
|
675
|
+
readonly status: "ready" | RunStatus;
|
|
654
676
|
/** At most one entry; empty while resting. */
|
|
655
677
|
readonly runs: readonly RunState[];
|
|
656
678
|
};
|
package/src/localStorage.test.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
|
|
13
13
|
const PREFIX = "aui:composer-draft:";
|
|
14
14
|
const SESSION_PREFIX = "aui:statewire-session:";
|
|
15
|
+
const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
|
|
15
16
|
|
|
16
17
|
const mount = (options: LocalStorageComposerDrafts.Options) =>
|
|
17
18
|
createTapRoot(() => useResource(LocalStorageComposerDrafts(options)));
|
|
@@ -105,9 +106,30 @@ describe("LocalStorageSession", () => {
|
|
|
105
106
|
const mountSession = (options: LocalStorageSession.Options) =>
|
|
106
107
|
createTapRoot(() => useResource(LocalStorageSession(options)));
|
|
107
108
|
|
|
109
|
+
const requested: string[] = [];
|
|
110
|
+
const stubWebLocks = () => {
|
|
111
|
+
let chain: Promise<unknown> = Promise.resolve();
|
|
112
|
+
Object.defineProperty(navigator, "locks", {
|
|
113
|
+
configurable: true,
|
|
114
|
+
value: {
|
|
115
|
+
request: (name: string, cb: () => Promise<unknown>) => {
|
|
116
|
+
requested.push(name);
|
|
117
|
+
const run = chain.then(() => cb());
|
|
118
|
+
chain = run.then(
|
|
119
|
+
() => {},
|
|
120
|
+
() => {},
|
|
121
|
+
);
|
|
122
|
+
return run;
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
|
|
108
128
|
beforeEach(() => {
|
|
109
129
|
vi.unstubAllGlobals();
|
|
110
130
|
localStorage.clear();
|
|
131
|
+
requested.length = 0;
|
|
132
|
+
stubWebLocks();
|
|
111
133
|
});
|
|
112
134
|
|
|
113
135
|
it("round-trips the record with its un-durable commands", () => {
|
|
@@ -141,10 +163,60 @@ describe("LocalStorageSession", () => {
|
|
|
141
163
|
root.unmount();
|
|
142
164
|
});
|
|
143
165
|
|
|
166
|
+
it("serializes lock sections on a per-key Web Lock", async () => {
|
|
167
|
+
const root = mountSession({ threadId: "t1" });
|
|
168
|
+
const order: string[] = [];
|
|
169
|
+
let release!: () => void;
|
|
170
|
+
const held = new Promise<void>((r) => {
|
|
171
|
+
release = r;
|
|
172
|
+
});
|
|
173
|
+
const first = root.getValue().lock!(async () => {
|
|
174
|
+
order.push("first:enter");
|
|
175
|
+
await held;
|
|
176
|
+
order.push("first:exit");
|
|
177
|
+
});
|
|
178
|
+
const second = root.getValue().lock!(async () => {
|
|
179
|
+
order.push("second");
|
|
180
|
+
});
|
|
181
|
+
release();
|
|
182
|
+
await Promise.all([first, second]);
|
|
183
|
+
expect(order).toEqual(["first:enter", "first:exit", "second"]);
|
|
184
|
+
expect(requested).toEqual([
|
|
185
|
+
`${SESSION_LOCK_PREFIX}t1`,
|
|
186
|
+
`${SESSION_LOCK_PREFIX}t1`,
|
|
187
|
+
]);
|
|
188
|
+
root.unmount();
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
it("notifies subscribers on storage events for the session key only", () => {
|
|
192
|
+
const root = mountSession({ threadId: "t1" });
|
|
193
|
+
const seen: number[] = [];
|
|
194
|
+
const unsubscribe = root.getValue().subscribe!(() => seen.push(1));
|
|
195
|
+
|
|
196
|
+
const fire = (key: string) =>
|
|
197
|
+
window.dispatchEvent(new StorageEvent("storage", { key }));
|
|
198
|
+
fire(`${SESSION_PREFIX}t1`);
|
|
199
|
+
fire(`${SESSION_PREFIX}other`);
|
|
200
|
+
fire("unrelated");
|
|
201
|
+
expect(seen).toEqual([1]);
|
|
202
|
+
|
|
203
|
+
unsubscribe();
|
|
204
|
+
fire(`${SESSION_PREFIX}t1`);
|
|
205
|
+
expect(seen).toEqual([1]);
|
|
206
|
+
root.unmount();
|
|
207
|
+
});
|
|
208
|
+
|
|
144
209
|
it("throws without localStorage", () => {
|
|
145
210
|
vi.stubGlobal("localStorage", undefined);
|
|
146
211
|
expect(() => mountSession({ threadId: "t1" })).toThrow(
|
|
147
212
|
/requires localStorage/,
|
|
148
213
|
);
|
|
149
214
|
});
|
|
215
|
+
|
|
216
|
+
it("throws without the Web Locks API", () => {
|
|
217
|
+
delete (navigator as { locks?: unknown }).locks;
|
|
218
|
+
expect(() => mountSession({ threadId: "t1" })).toThrow(
|
|
219
|
+
/requires the Web Locks API/,
|
|
220
|
+
);
|
|
221
|
+
});
|
|
150
222
|
});
|
package/src/localStorage.ts
CHANGED
|
@@ -78,14 +78,22 @@ export const LocalStorageComposerDrafts = resource(
|
|
|
78
78
|
useLocalStorageComposerDrafts,
|
|
79
79
|
);
|
|
80
80
|
|
|
81
|
+
const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
|
|
82
|
+
|
|
81
83
|
const useLocalStorageSession = ({
|
|
82
84
|
threadId,
|
|
83
85
|
key = (id) => id,
|
|
84
86
|
}: LocalStorageSession.Options): StatewireClient.SessionStorage => {
|
|
85
87
|
if (typeof localStorage === "undefined")
|
|
86
88
|
throw new Error("statewire: LocalStorageSession requires localStorage");
|
|
89
|
+
// localStorage is shared across tabs: record mutations must serialize.
|
|
90
|
+
if (typeof navigator === "undefined" || navigator.locks === undefined)
|
|
91
|
+
throw new Error(
|
|
92
|
+
"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
|
|
93
|
+
);
|
|
87
94
|
|
|
88
95
|
const storageKey = SESSION_PREFIX + key(threadId);
|
|
96
|
+
const lockName = SESSION_LOCK_PREFIX + key(threadId);
|
|
89
97
|
return useMemo(
|
|
90
98
|
(): StatewireClient.SessionStorage => ({
|
|
91
99
|
load: () => {
|
|
@@ -96,12 +104,20 @@ const useLocalStorageSession = ({
|
|
|
96
104
|
save: (record) => {
|
|
97
105
|
localStorage.setItem(storageKey, JSON.stringify(record));
|
|
98
106
|
},
|
|
107
|
+
lock: (fn) => navigator.locks.request(lockName, async () => fn()),
|
|
108
|
+
subscribe: (listener) => {
|
|
109
|
+
const onStorage = (event: StorageEvent) => {
|
|
110
|
+
if (event.key === storageKey) listener();
|
|
111
|
+
};
|
|
112
|
+
window.addEventListener("storage", onStorage);
|
|
113
|
+
return () => window.removeEventListener("storage", onStorage);
|
|
114
|
+
},
|
|
99
115
|
}),
|
|
100
|
-
[storageKey],
|
|
116
|
+
[storageKey, lockName],
|
|
101
117
|
);
|
|
102
118
|
};
|
|
103
119
|
|
|
104
|
-
/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
|
|
120
|
+
/** 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. */
|
|
105
121
|
export const LocalStorageSession = resource(useLocalStorageSession);
|
|
106
122
|
|
|
107
123
|
export namespace LocalStorageSession {
|