@assistant-ui/react-statewire 0.16.0 → 0.17.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.
@@ -1,7 +1,7 @@
1
1
  import { ResourceElement } from "@assistant-ui/tap";
2
2
  import { ClientOutput } from "@assistant-ui/store";
3
3
  import { Statewire, StatewireClient } from "statewire";
4
- import { Assistant, AttachmentAdapter, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
4
+ import { Assistant, AttachmentAdapter, CompleteAttachment, FeedbackAdapter, SpeechSynthesisAdapter, ThreadMessage } from "@assistant-ui/core";
5
5
  import { ReadonlyJSONValue } from "assistant-stream/utils";
6
6
  //#region src/StatewireThread.d.ts
7
7
  declare const symbolStatewireExtras: unique symbol;
@@ -10,6 +10,17 @@ declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => Resou
10
10
  declare namespace StatewireThread {
11
11
  type UserCommands = Assistant.Commands[keyof Assistant.Commands];
12
12
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
13
+ /** A composer draft as persisted: the text plus the completed attachments. */
14
+ export type ComposerDraft = {
15
+ readonly text: string;
16
+ readonly attachments: readonly CompleteAttachment[];
17
+ };
18
+ /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */
19
+ export type ComposerStorage = {
20
+ read(): ComposerDraft | undefined;
21
+ write(draft: ComposerDraft): void;
22
+ clear(): void;
23
+ };
13
24
  export type Extras = {
14
25
  [symbolStatewireExtras]: true;
15
26
  sendCommand: (command: Command) => void;
@@ -166,6 +177,8 @@ declare namespace StatewireThread {
166
177
  export type RunState = {
167
178
  /** 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. */
168
179
  readonly runId: string | null;
180
+ /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
181
+ readonly epoch?: number;
169
182
  readonly status: RunStatus;
170
183
  readonly queue: readonly RunsQueueEntry[];
171
184
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -197,6 +210,8 @@ declare namespace StatewireThread {
197
210
  export type Runs = {
198
211
  /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
199
212
  readonly runId: string | null;
213
+ /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
214
+ readonly epoch?: number;
200
215
  readonly queue: readonly RunsQueueEntry[];
201
216
  readonly steerQueue: readonly RunsQueueEntry[];
202
217
  /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
@@ -266,6 +281,10 @@ declare namespace StatewireThread {
266
281
  /** The host supports `run/reload` (regenerating an assistant message). */
267
282
  reload?: boolean | undefined;
268
283
  } | undefined;
284
+ /** Durable drafts: the mounted composer storage restores on mount, mirrors every change, and clears when the draft is consumed. */
285
+ storage?: {
286
+ composer?: ResourceElement<ComposerStorage> | undefined;
287
+ } | undefined;
269
288
  adapters?: {
270
289
  attachments?: AttachmentAdapter | undefined;
271
290
  speech?: SpeechSynthesisAdapter | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cAwCa;cAEA,oBAAqB,oBAAkB,gBAAgB;cA4RvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,eAAe,UAAU,eAAe,UAAU;cAE3C,UAAU,KAAK,gBAAgB,UAAU;cAEzC;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;;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,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;IAGN;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA8Ca;cAEA,oBAAqB,oBAAkB,gBAAgB;cA4VvD,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;aACr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AAgB;;IAEjC;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB"}
@@ -2,7 +2,7 @@ import { createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFi
2
2
  import { resolveToolApprovalInput, resolveToolResultInput } from "./inputRequests.js";
3
3
  import { runsOptimistic } from "./runsOptimistic.js";
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
5
- import { resource, useResource } from "@assistant-ui/tap";
5
+ import { resource, useResource, useResources, withKey } from "@assistant-ui/tap";
6
6
  import { ExternalThread } from "@assistant-ui/core/store";
7
7
  import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
8
8
  import { toToolsJSONSchema } from "assistant-stream";
@@ -93,6 +93,7 @@ const useStatewireThread = (options) => {
93
93
  status: entries === void 0 ? "loading" : entry?.status ?? "ready",
94
94
  runs: entry === void 0 ? RESTING_RUNS : {
95
95
  runId: entry.runId,
96
+ ...entry.epoch !== void 0 && { epoch: entry.epoch },
96
97
  queue: entry.queue,
97
98
  steerQueue: entry.steerQueue,
98
99
  ...entry.dispatching !== void 0 && { dispatching: entry.dispatching },
@@ -182,13 +183,57 @@ const useStatewireThread = (options) => {
182
183
  if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: stopPayload must return a plain object");
183
184
  commands["run/stop"]({
184
185
  ...payload,
185
- runId: runs.runId
186
+ runId: runs.runId,
187
+ ...runs.epoch !== void 0 && { epoch: runs.epoch }
186
188
  }).catch((error_0) => {
187
189
  latest.current.onError?.(error_0);
188
190
  });
189
191
  }
190
192
  }));
191
193
  threadRef.current = thread;
194
+ const composerStorage = useResources(options.storage?.composer !== void 0 ? [withKey("composer", options.storage.composer)] : [])[0];
195
+ const storageRef = useRef(composerStorage);
196
+ storageRef.current = composerStorage;
197
+ const storageHook = options.storage?.composer?.hook;
198
+ useEffect(() => {
199
+ const storage = storageRef.current;
200
+ if (storage === void 0) return;
201
+ const composer = threadRef.current.composer();
202
+ const draft_1 = storage.read();
203
+ if (draft_1 === void 0 || !composer.getState().isEmpty) return;
204
+ composer.setText(draft_1.text);
205
+ for (const attachment of draft_1.attachments) composer.addAttachment({
206
+ id: attachment.id,
207
+ type: attachment.type,
208
+ name: attachment.name,
209
+ ...attachment.contentType !== void 0 && { contentType: attachment.contentType },
210
+ content: attachment.content
211
+ }).catch((error_1) => {
212
+ latest.current.onError?.(error_1);
213
+ });
214
+ }, [storageHook]);
215
+ const { text: draftText, attachments: composerAttachments } = thread.getState().composer;
216
+ const draftAttachments = useMemo(() => composerAttachments.filter((attachment_0) => attachment_0.status.type === "complete").map(({ file: _file, ...record }) => record), [composerAttachments]);
217
+ const [draftSync] = useState(() => ({ writingFor: void 0 }));
218
+ useEffect(() => {
219
+ const storage_0 = storageRef.current;
220
+ if (storage_0 === void 0) return;
221
+ const isBaseline = draftSync.writingFor !== storageHook;
222
+ draftSync.writingFor = storageHook;
223
+ if (draftText === "" && draftAttachments.length === 0) {
224
+ if (!isBaseline) storage_0.clear();
225
+ return;
226
+ }
227
+ storage_0.write({
228
+ text: draftText,
229
+ attachments: draftAttachments
230
+ });
231
+ }, [
232
+ draftSync,
233
+ storageHook,
234
+ draftText,
235
+ draftAttachments
236
+ ]);
192
237
  return thread;
193
238
  };
194
239
  const StatewireThread = (options) => resource(useStatewireThread)(options);
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","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","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","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","T","UserCommands","Commands","Transport","TextPart","FilePart","mediaType","url","filename","UserMessage","id","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","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/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 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 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 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\"]!({ ...payload, runId: runs.runId }).catch(\n (error: Error) => {\n latest.current.onError?.(error);\n },\n );\n },\n }),\n );\n threadRef.current = thread;\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 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 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 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 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":";;;;;;;;;;AAwCA,MAAasC,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,k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kG,eAAeuC,UAAU7B,SAAS,CAAC;EACvE8B,gBAAgB;GACd,MAAMC,UAAU7G,OAAOC,QAAQ6G,cAAc;GAC7C,IACED,YAAYpH,KAAAA,MACX,OAAOoH,YAAY,YAClBA,YAAY,QACZE,MAAMC,QAAQH,OAAO,IAEvB,MAAM,IAAI/H,MAAM,mDAAmD;GACrE,SAAc,WAAW,CAAE;IAAE,GAAG+H;IAAS1H,OAAOyE,KAAKzE;GAAM,CAAC,CAAC,CAAC0D,OAC3DC,YAAiB;IAChB9C,OAAOC,QAAQ8C,UAAUD,OAAK;GAChC,CACF;EACF;CACF,CAAC,CACH;CACAE,UAAU/C,UAAUsF;CACpB,OAAOA;AACT;AAEA,MAAa3G,mBACXkB,YAEAvD,SAASsD,kBAAkB,CAAC,CAACC,OAAuC;AA0WtEjD,uBACEgD,oBACAnD,eAAe+C,KAAAA,CAAkB,CAAC,CAACgM,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","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","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","storage","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","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 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 /** Durable drafts: the mounted composer storage restores on mount, mirrors every change, and clears when the draft is consumed. */\n storage?:\n | { composer?: ResourceElement<ComposerStorage> | undefined }\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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,aAAaJ,WAAWI,YAC1B;GACAzE,SAASqE,WAAWrE;EACtB,CAAC,CAAC,CACDR,OAAOC,YAAiB;GACvB9C,OAAOC,QAAQ8C,UAAUD,OAAK;EAChC,CAAC;CAEP,GAAG,CAACuE,WAAW,CAAC;CAEhB,MAAM,EAAEjE,MAAM2E,WAAWnC,aAAaoC,wBACpCxC,OAAOgC,SAAS,CAAC,CAAC9D;CACpB,MAAMuE,mBAAmBhM,cAErB+L,oBACGvH,QACEiH,iBACCA,aAAWlG,OAAOoB,SAAS,UAC/B,CAAC,CACAsF,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAanM,gBAAgB,EAAEoM,YAAY9I,KAAAA,EAAqB,EAAE;CACzEzD,gBAAgB;EACd,MAAMmL,YAAUC,WAAWnH;EAC3B,IAAIkH,cAAY1H,KAAAA,GAAW;EAG3B,MAAM+I,aAAaF,UAAUC,eAAelB;EAC5CiB,UAAUC,aAAalB;EACvB,IAAIU,cAAc,MAAME,iBAAiBtD,WAAW,GAAG;GACrD,IAAI,CAAC6D,YAAYrB,UAAQsB,MAAM;GAC/B;EACF;EACAtB,UAAQuB,MAAM;GAAEtF,MAAM2E;GAAWnC,aAAaqC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWjB;EAAaU;EAAWE;CAAgB,CAAC;CAExD,OAAOzC;AACT;AAEA,MAAa5G,mBACXkB,YAEA1D,SAASyD,kBAAkB,CAAC,CAACC,OAAuC;AA+XtElD,uBACEiD,oBACApD,eAAegD,KAAAA,CAAkB,CAAC,CAAC6H,IACrC"}
@@ -0,0 +1,19 @@
1
+ import { StatewireThread } from "./StatewireThread.js";
2
+ //#region src/localStorage.d.ts
3
+ /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
4
+ declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
5
+ declare namespace LocalStorageComposerDrafts {
6
+ type Options = {
7
+ /** The thread whose draft this storage holds. */
8
+ threadId: string;
9
+ /** Derives the storage key from the thread id; defaults to the id itself. */
10
+ key?: ((threadId: string) => string) | undefined;
11
+ /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */
12
+ ttl?: number | undefined;
13
+ /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */
14
+ max?: number | undefined;
15
+ };
16
+ }
17
+ //#endregion
18
+ export { LocalStorageComposerDrafts };
19
+ //# sourceMappingURL=localStorage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA0Ea,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;kBAItB;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
@@ -0,0 +1,62 @@
1
+ import { useEffect, useMemo } from "@assistant-ui/tap/react-shim";
2
+ import { resource } from "@assistant-ui/tap";
3
+ //#region src/localStorage.ts
4
+ const PREFIX = "aui:composer-draft:";
5
+ const DAY = 864e5;
6
+ const sweep = (ttl, max) => {
7
+ const entries = [];
8
+ for (let i = 0; i < localStorage.length; i++) {
9
+ const key = localStorage.key(i);
10
+ if (!key.startsWith(PREFIX)) continue;
11
+ const { ts } = JSON.parse(localStorage.getItem(key));
12
+ entries.push({
13
+ key,
14
+ ts
15
+ });
16
+ }
17
+ const now = Date.now();
18
+ const fresh = entries.filter(({ key, ts }) => {
19
+ if (now - ts <= ttl) return true;
20
+ localStorage.removeItem(key);
21
+ return false;
22
+ });
23
+ fresh.sort((a, b) => b.ts - a.ts);
24
+ for (const { key } of fresh.slice(max)) localStorage.removeItem(key);
25
+ };
26
+ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * DAY, max = 50 }) => {
27
+ if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageComposerDrafts requires localStorage");
28
+ useEffect(() => {
29
+ sweep(ttl, max);
30
+ }, [ttl, max]);
31
+ const storageKey = PREFIX + key(threadId);
32
+ return useMemo(() => ({
33
+ read: () => {
34
+ const raw = localStorage.getItem(storageKey);
35
+ if (raw === null) return void 0;
36
+ const { text, attachments } = JSON.parse(raw);
37
+ return {
38
+ text,
39
+ attachments
40
+ };
41
+ },
42
+ write: (draft) => {
43
+ if (draft.text === "" && draft.attachments.length === 0) {
44
+ localStorage.removeItem(storageKey);
45
+ return;
46
+ }
47
+ localStorage.setItem(storageKey, JSON.stringify({
48
+ ...draft,
49
+ ts: Date.now()
50
+ }));
51
+ },
52
+ clear: () => {
53
+ localStorage.removeItem(storageKey);
54
+ }
55
+ }), [storageKey]);
56
+ };
57
+ /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
58
+ const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
59
+ //#endregion
60
+ export { LocalStorageComposerDrafts };
61
+
62
+ //# sourceMappingURL=localStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireThread","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"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\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\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":";;;AAIA,MAAMI,SAAS;AACf,MAAMC,MAAM;AAQZ,MAAMM,SAASC,KAAa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W,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,6BAA6BlC,SACxC+B,6BACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -16,6 +16,10 @@
16
16
  ".": {
17
17
  "types": "./dist/index.d.ts",
18
18
  "default": "./dist/index.js"
19
+ },
20
+ "./local-storage": {
21
+ "types": "./dist/localStorage.d.ts",
22
+ "default": "./dist/localStorage.js"
19
23
  }
20
24
  },
21
25
  "main": "./dist/index.js",
@@ -0,0 +1,352 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Contract tests for the composer draft storage seam: restore on mount,
4
+ // synchronous write-through on change, clear when the draft is consumed.
5
+
6
+ import { act, render, waitFor } from "@testing-library/react";
7
+ import type { FC } from "react";
8
+ import { useState } from "react";
9
+ import { describe, expect, it } from "vitest";
10
+ import { AuiProvider, useAui } from "@assistant-ui/store";
11
+ import { flushTapSync, resource } from "@assistant-ui/tap";
12
+ import {
13
+ StatewireReject,
14
+ useStatewireCommands,
15
+ useStatewireState,
16
+ } from "statewire/host";
17
+ import type { AttachmentAdapter } from "@assistant-ui/core";
18
+ import { StatewireThread } from "./StatewireThread";
19
+ import { LocalStorageComposerDrafts } from "./localStorage";
20
+ import { toThreadMessage } from "./__tests__/testHelpers";
21
+
22
+ type ServerState = {
23
+ messages: { id: string; role: "user" | "assistant"; text: string }[];
24
+ status: "ready";
25
+ runs: never[];
26
+ };
27
+
28
+ const converter: StatewireThread.StateConverter<ServerState> = (state) => ({
29
+ messages: state.messages.map(toThreadMessage),
30
+ });
31
+
32
+ const createServer = ({ rejectSends = false } = {}) => {
33
+ const received: unknown[] = [];
34
+ const transport = resource(() => {
35
+ const [state] = useStatewireState<ServerState>(() => ({
36
+ messages: [],
37
+ status: "ready",
38
+ runs: [],
39
+ }));
40
+ const submit = (command: unknown) => {
41
+ received.push(command);
42
+ if (rejectSends) throw new StatewireReject("unknown command");
43
+ };
44
+ const commands = useStatewireCommands({
45
+ "run/enqueue": submit,
46
+ "run/steer": submit,
47
+ });
48
+ return { state, commands };
49
+ })();
50
+ return { transport, received };
51
+ };
52
+
53
+ const createDraftStore = (initial?: StatewireThread.ComposerDraft) => {
54
+ const cell = { draft: initial, log: [] as string[] };
55
+ const storage: StatewireThread.ComposerStorage = {
56
+ read: () => cell.draft,
57
+ write: (draft) => {
58
+ cell.draft = draft;
59
+ cell.log.push(`write:${draft.text}`);
60
+ },
61
+ clear: () => {
62
+ cell.draft = undefined;
63
+ cell.log.push("clear");
64
+ },
65
+ };
66
+ return { cell, element: resource(() => storage)() };
67
+ };
68
+
69
+ const mountThread = (
70
+ options: Partial<StatewireThread.Options<ServerState>> &
71
+ Pick<StatewireThread.Options<ServerState>, "transport">,
72
+ ) => {
73
+ const captured: { aui?: ReturnType<typeof useAui> } = {};
74
+ const knobs: { setStorage?: (element: never) => void } = {};
75
+ const Capture: FC = () => {
76
+ captured.aui = useAui();
77
+ return null;
78
+ };
79
+ const App: FC = () => {
80
+ const [storage, setStorage] =
81
+ useState<StatewireThread.Options<ServerState>["storage"]>();
82
+ knobs.setStorage = (element) => setStorage({ composer: element });
83
+ const aui = useAui({
84
+ thread: StatewireThread({
85
+ initialState: { messages: [], status: "ready", runs: [] },
86
+ converter,
87
+ ...(storage !== undefined && { storage }),
88
+ ...options,
89
+ }),
90
+ });
91
+ return (
92
+ <AuiProvider value={aui}>
93
+ <Capture />
94
+ </AuiProvider>
95
+ );
96
+ };
97
+ const { unmount } = render(<App />);
98
+ return { aui: () => captured.aui!, knobs, unmount };
99
+ };
100
+
101
+ const composerOf = (aui: () => ReturnType<typeof useAui>) =>
102
+ aui().thread().composer();
103
+
104
+ describe("StatewireThread composer draft storage", () => {
105
+ it("restores the stored draft into an empty composer on mount", async () => {
106
+ const server = createServer();
107
+ const store = createDraftStore({ text: "draft text", attachments: [] });
108
+ const { aui } = mountThread({
109
+ transport: server.transport,
110
+ storage: { composer: store.element },
111
+ });
112
+
113
+ await waitFor(() =>
114
+ expect(composerOf(aui).getState().text).toBe("draft text"),
115
+ );
116
+ });
117
+
118
+ it("stays inert without a storage option", async () => {
119
+ const server = createServer();
120
+ const { aui } = mountThread({ transport: server.transport });
121
+
122
+ act(() => flushTapSync(() => composerOf(aui).setText("hello")));
123
+ await waitFor(() => expect(composerOf(aui).getState().text).toBe("hello"));
124
+ });
125
+
126
+ it("writes through synchronously on every text change", async () => {
127
+ const server = createServer();
128
+ const store = createDraftStore();
129
+ const { aui } = mountThread({
130
+ transport: server.transport,
131
+ storage: { composer: store.element },
132
+ });
133
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
134
+
135
+ act(() => {
136
+ flushTapSync(() => composerOf(aui).setText("hel"));
137
+ // the write landed inside the flush — no await, no timers
138
+ expect(store.cell.draft).toEqual({ text: "hel", attachments: [] });
139
+ flushTapSync(() => composerOf(aui).setText("hello"));
140
+ expect(store.cell.draft).toEqual({ text: "hello", attachments: [] });
141
+ });
142
+ expect(store.cell.log).toEqual(["write:hel", "write:hello"]);
143
+ });
144
+
145
+ it("clears the stored draft synchronously when the send consumes it", async () => {
146
+ const server = createServer();
147
+ const store = createDraftStore();
148
+ const { aui } = mountThread({
149
+ transport: server.transport,
150
+ storage: { composer: store.element },
151
+ });
152
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
153
+
154
+ act(() => {
155
+ flushTapSync(() => composerOf(aui).setText("hello"));
156
+ flushTapSync(() => composerOf(aui).send());
157
+ expect(store.cell.draft).toBeUndefined();
158
+ });
159
+ expect(store.cell.log).toEqual(["write:hello", "clear"]);
160
+ await waitFor(() => expect(server.received).toHaveLength(1));
161
+ });
162
+
163
+ it("re-persists the draft when a rejected send restores the text", async () => {
164
+ const server = createServer({ rejectSends: true });
165
+ const store = createDraftStore();
166
+ const errors: Error[] = [];
167
+ const { aui } = mountThread({
168
+ transport: server.transport,
169
+ storage: { composer: store.element },
170
+ onError: (error) => {
171
+ errors.push(error);
172
+ },
173
+ });
174
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
175
+
176
+ act(() => {
177
+ flushTapSync(() => composerOf(aui).setText("hello"));
178
+ flushTapSync(() => composerOf(aui).send());
179
+ });
180
+ expect(store.cell.draft).toBeUndefined();
181
+
182
+ await waitFor(() => expect(errors).toHaveLength(1));
183
+ await waitFor(() =>
184
+ expect(store.cell.draft).toEqual({ text: "hello", attachments: [] }),
185
+ );
186
+ });
187
+
188
+ it("persists complete attachments without their File handle", async () => {
189
+ const server = createServer();
190
+ const store = createDraftStore();
191
+ const { aui } = mountThread({
192
+ transport: server.transport,
193
+ storage: { composer: store.element },
194
+ });
195
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
196
+
197
+ const file = new File(["body"], "notes.txt", { type: "text/plain" });
198
+ await act(async () => {
199
+ await flushTapSync(() => composerOf(aui).addAttachment(file));
200
+ });
201
+
202
+ expect(store.cell.draft).toMatchObject({
203
+ text: "",
204
+ attachments: [
205
+ {
206
+ id: expect.any(String),
207
+ type: "file",
208
+ name: "notes.txt",
209
+ contentType: "text/plain",
210
+ content: [],
211
+ status: { type: "complete" },
212
+ },
213
+ ],
214
+ });
215
+ expect("file" in store.cell.draft!.attachments[0]!).toBe(false);
216
+ });
217
+
218
+ it("skips in-flight attachments, persisting the text alone", async () => {
219
+ const server = createServer();
220
+ const store = createDraftStore();
221
+ const adapter: AttachmentAdapter = {
222
+ accept: "*",
223
+ add: async ({ file }) => ({
224
+ id: "p1",
225
+ type: "document",
226
+ name: file.name,
227
+ contentType: file.type,
228
+ file,
229
+ status: { type: "running", reason: "uploading", progress: 0 },
230
+ }),
231
+ remove: async () => {},
232
+ send: async (attachment) => ({
233
+ ...attachment,
234
+ status: { type: "complete" },
235
+ content: [],
236
+ }),
237
+ };
238
+ const { aui } = mountThread({
239
+ transport: server.transport,
240
+ storage: { composer: store.element },
241
+ adapters: { attachments: adapter },
242
+ });
243
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
244
+
245
+ act(() => flushTapSync(() => composerOf(aui).setText("with upload")));
246
+ const file = new File(["body"], "notes.txt", { type: "text/plain" });
247
+ await act(async () => {
248
+ await composerOf(aui).addAttachment(file);
249
+ });
250
+
251
+ await waitFor(() =>
252
+ expect(composerOf(aui).getState().attachments).toHaveLength(1),
253
+ );
254
+ expect(store.cell.draft).toEqual({ text: "with upload", attachments: [] });
255
+ });
256
+
257
+ it("restores stored attachments into the composer alongside the text", async () => {
258
+ const server = createServer();
259
+ const store = createDraftStore({
260
+ text: "draft text",
261
+ attachments: [
262
+ {
263
+ id: "a1",
264
+ type: "document",
265
+ name: "notes.txt",
266
+ contentType: "text/plain",
267
+ content: [{ type: "text", text: "file body" }],
268
+ status: { type: "complete" },
269
+ },
270
+ ],
271
+ });
272
+ const { aui } = mountThread({
273
+ transport: server.transport,
274
+ storage: { composer: store.element },
275
+ });
276
+
277
+ await waitFor(() =>
278
+ expect(composerOf(aui).getState().text).toBe("draft text"),
279
+ );
280
+ await waitFor(() =>
281
+ expect(composerOf(aui).getState().attachments).toMatchObject([
282
+ {
283
+ id: "a1",
284
+ type: "document",
285
+ name: "notes.txt",
286
+ contentType: "text/plain",
287
+ content: [{ type: "text", text: "file body" }],
288
+ status: { type: "complete" },
289
+ },
290
+ ]),
291
+ );
292
+ });
293
+
294
+ it("round-trips text and attachments through localStorage across a remount", async () => {
295
+ localStorage.clear();
296
+ const threadId = "drafts-e2e";
297
+ const first = mountThread({
298
+ transport: createServer().transport,
299
+ storage: { composer: LocalStorageComposerDrafts({ threadId }) },
300
+ });
301
+ await waitFor(() =>
302
+ expect(composerOf(first.aui).getState().type).toBe("thread"),
303
+ );
304
+
305
+ act(() => flushTapSync(() => composerOf(first.aui).setText("carry me")));
306
+ await act(async () => {
307
+ await flushTapSync(() =>
308
+ composerOf(first.aui).addAttachment({
309
+ id: "a1",
310
+ type: "document",
311
+ name: "notes.txt",
312
+ contentType: "text/plain",
313
+ content: [{ type: "text", text: "file body" }],
314
+ }),
315
+ );
316
+ });
317
+ first.unmount();
318
+
319
+ const second = mountThread({
320
+ transport: createServer().transport,
321
+ storage: { composer: LocalStorageComposerDrafts({ threadId }) },
322
+ });
323
+ await waitFor(() =>
324
+ expect(composerOf(second.aui).getState().text).toBe("carry me"),
325
+ );
326
+ await waitFor(() =>
327
+ expect(composerOf(second.aui).getState().attachments).toMatchObject([
328
+ {
329
+ id: "a1",
330
+ name: "notes.txt",
331
+ content: [{ type: "text", text: "file body" }],
332
+ status: { type: "complete" },
333
+ },
334
+ ]),
335
+ );
336
+ });
337
+
338
+ it("leaves a non-empty composer alone when storage mounts, then persists it", async () => {
339
+ const server = createServer();
340
+ const store = createDraftStore({ text: "stored", attachments: [] });
341
+ const { aui, knobs } = mountThread({ transport: server.transport });
342
+ await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
343
+
344
+ act(() => flushTapSync(() => composerOf(aui).setText("typed")));
345
+ act(() => knobs.setStorage!(store.element as never));
346
+
347
+ await waitFor(() =>
348
+ expect(store.cell.draft).toEqual({ text: "typed", attachments: [] }),
349
+ );
350
+ expect(composerOf(aui).getState().text).toBe("typed");
351
+ });
352
+ });
@@ -1,5 +1,10 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
- import { resource, useResource } from "@assistant-ui/tap";
2
+ import {
3
+ resource,
4
+ useResource,
5
+ useResources,
6
+ withKey,
7
+ } from "@assistant-ui/tap";
3
8
  import type { ResourceElement } from "@assistant-ui/tap";
4
9
  import { ExternalThread } from "@assistant-ui/core/store";
5
10
  import type { ExternalThreadMessage } from "@assistant-ui/core/store";
@@ -13,6 +18,7 @@ import type {
13
18
  AddToolResultOptions,
14
19
  AppendMessage,
15
20
  AttachmentAdapter,
21
+ CompleteAttachment,
16
22
  FeedbackAdapter,
17
23
  ModelContext,
18
24
  RespondToToolApprovalOptions,
@@ -182,6 +188,7 @@ const useStatewireThread = (
182
188
  ? RESTING_RUNS
183
189
  : {
184
190
  runId: entry.runId,
191
+ ...(entry.epoch !== undefined && { epoch: entry.epoch }),
185
192
  queue: entry.queue,
186
193
  steerQueue: entry.steerQueue,
187
194
  ...(entry.dispatching !== undefined && {
@@ -312,15 +319,78 @@ const useStatewireThread = (
312
319
  Array.isArray(payload))
313
320
  )
314
321
  throw new Error("statewire: stopPayload must return a plain object");
315
- void commands["run/stop"]!({ ...payload, runId: runs.runId }).catch(
316
- (error: Error) => {
317
- latest.current.onError?.(error);
318
- },
319
- );
322
+ void commands["run/stop"]!({
323
+ ...payload,
324
+ runId: runs.runId,
325
+ ...(runs.epoch !== undefined && { epoch: runs.epoch }),
326
+ }).catch((error: Error) => {
327
+ latest.current.onError?.(error);
328
+ });
320
329
  },
321
330
  }),
322
331
  );
323
332
  threadRef.current = thread;
333
+
334
+ const composerStorage = useResources(
335
+ options.storage?.composer !== undefined
336
+ ? [withKey("composer", options.storage.composer)]
337
+ : [],
338
+ )[0];
339
+ const storageRef = useRef(composerStorage);
340
+ storageRef.current = composerStorage;
341
+ const storageHook = options.storage?.composer?.hook;
342
+
343
+ useEffect(() => {
344
+ const storage = storageRef.current;
345
+ if (storage === undefined) return;
346
+ const composer = threadRef.current!.composer();
347
+ const draft = storage.read();
348
+ if (draft === undefined || !composer.getState().isEmpty) return;
349
+ composer.setText(draft.text);
350
+ for (const attachment of draft.attachments) {
351
+ composer
352
+ .addAttachment({
353
+ id: attachment.id,
354
+ type: attachment.type,
355
+ name: attachment.name,
356
+ ...(attachment.contentType !== undefined && {
357
+ contentType: attachment.contentType,
358
+ }),
359
+ content: attachment.content,
360
+ })
361
+ .catch((error: Error) => {
362
+ latest.current.onError?.(error);
363
+ });
364
+ }
365
+ }, [storageHook]);
366
+
367
+ const { text: draftText, attachments: composerAttachments } =
368
+ thread.getState().composer;
369
+ const draftAttachments = useMemo(
370
+ () =>
371
+ composerAttachments
372
+ .filter(
373
+ (attachment): attachment is CompleteAttachment =>
374
+ attachment.status.type === "complete",
375
+ )
376
+ .map(({ file: _file, ...record }) => record),
377
+ [composerAttachments],
378
+ );
379
+ const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));
380
+ useEffect(() => {
381
+ const storage = storageRef.current;
382
+ if (storage === undefined) return;
383
+ // First run per storage is the baseline, not a change: never clear the
384
+ // stored draft the restore effect is about to load.
385
+ const isBaseline = draftSync.writingFor !== storageHook;
386
+ draftSync.writingFor = storageHook;
387
+ if (draftText === "" && draftAttachments.length === 0) {
388
+ if (!isBaseline) storage.clear();
389
+ return;
390
+ }
391
+ storage.write({ text: draftText, attachments: draftAttachments });
392
+ }, [draftSync, storageHook, draftText, draftAttachments]);
393
+
324
394
  return thread;
325
395
  };
326
396
 
@@ -334,6 +404,19 @@ export namespace StatewireThread {
334
404
 
335
405
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
336
406
 
407
+ /** A composer draft as persisted: the text plus the completed attachments. */
408
+ export type ComposerDraft = {
409
+ readonly text: string;
410
+ readonly attachments: readonly CompleteAttachment[];
411
+ };
412
+
413
+ /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */
414
+ export type ComposerStorage = {
415
+ read(): ComposerDraft | undefined;
416
+ write(draft: ComposerDraft): void;
417
+ clear(): void;
418
+ };
419
+
337
420
  export type Extras = {
338
421
  [symbolStatewireExtras]: true;
339
422
  sendCommand: (command: Command) => void;
@@ -539,6 +622,8 @@ export namespace StatewireThread {
539
622
  export type RunState = {
540
623
  /** 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. */
541
624
  readonly runId: string | null;
625
+ /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
626
+ readonly epoch?: number;
542
627
  readonly status: RunStatus;
543
628
  readonly queue: readonly RunsQueueEntry[];
544
629
  readonly steerQueue: readonly RunsQueueEntry[];
@@ -573,6 +658,8 @@ export namespace StatewireThread {
573
658
  export type Runs = {
574
659
  /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */
575
660
  readonly runId: string | null;
661
+ /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
662
+ readonly epoch?: number;
576
663
  readonly queue: readonly RunsQueueEntry[];
577
664
  readonly steerQueue: readonly RunsQueueEntry[];
578
665
  /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
@@ -664,6 +751,10 @@ export namespace StatewireThread {
664
751
  reload?: boolean | undefined;
665
752
  }
666
753
  | undefined;
754
+ /** Durable drafts: the mounted composer storage restores on mount, mirrors every change, and clears when the draft is consumed. */
755
+ storage?:
756
+ | { composer?: ResourceElement<ComposerStorage> | undefined }
757
+ | undefined;
667
758
  adapters?:
668
759
  | {
669
760
  attachments?: AttachmentAdapter | undefined;
@@ -0,0 +1,98 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Contract tests for LocalStorageComposerDrafts: persisted record shape,
4
+ // empty-draft removal, and the mount sweep (ttl + max).
5
+
6
+ import { beforeEach, describe, expect, it, vi } from "vitest";
7
+ import { createTapRoot, useResource } from "@assistant-ui/tap";
8
+ import { LocalStorageComposerDrafts } from "./localStorage";
9
+
10
+ const PREFIX = "aui:composer-draft:";
11
+
12
+ const mount = (options: LocalStorageComposerDrafts.Options) =>
13
+ createTapRoot(() => useResource(LocalStorageComposerDrafts(options)));
14
+
15
+ const seed = (key: string, ts: number, text = "seeded") =>
16
+ localStorage.setItem(
17
+ PREFIX + key,
18
+ JSON.stringify({ text, attachments: [], ts }),
19
+ );
20
+
21
+ describe("LocalStorageComposerDrafts", () => {
22
+ beforeEach(() => {
23
+ localStorage.clear();
24
+ vi.unstubAllGlobals();
25
+ });
26
+
27
+ it("round-trips a draft through a timestamped record", () => {
28
+ const root = mount({ threadId: "t1" });
29
+ root.getValue().write({ text: "hello", attachments: [] });
30
+
31
+ const record = JSON.parse(localStorage.getItem(`${PREFIX}t1`)!);
32
+ expect(record).toEqual({
33
+ text: "hello",
34
+ attachments: [],
35
+ ts: expect.any(Number),
36
+ });
37
+ expect(root.getValue().read()).toEqual({ text: "hello", attachments: [] });
38
+ root.unmount();
39
+ });
40
+
41
+ it("derives the storage key through the key callback", () => {
42
+ const root = mount({ threadId: "t1", key: (id) => `user-42:${id}` });
43
+ root.getValue().write({ text: "hello", attachments: [] });
44
+ expect(localStorage.getItem(`${PREFIX}user-42:t1`)).not.toBeNull();
45
+ expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
46
+ root.unmount();
47
+ });
48
+
49
+ it("reads undefined without a stored draft and removes the record on clear", () => {
50
+ const root = mount({ threadId: "t1" });
51
+ expect(root.getValue().read()).toBeUndefined();
52
+
53
+ root.getValue().write({ text: "hello", attachments: [] });
54
+ root.getValue().clear();
55
+ expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
56
+ expect(root.getValue().read()).toBeUndefined();
57
+ root.unmount();
58
+ });
59
+
60
+ it("removes the record on an empty write instead of storing it", () => {
61
+ const root = mount({ threadId: "t1" });
62
+ root.getValue().write({ text: "hello", attachments: [] });
63
+ root.getValue().write({ text: "", attachments: [] });
64
+ expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
65
+ root.unmount();
66
+ });
67
+
68
+ it("sweeps drafts older than ttl on mount, leaving foreign keys alone", () => {
69
+ const now = Date.now();
70
+ seed("old", now - 100_000);
71
+ seed("live", now - 1_000);
72
+ localStorage.setItem("unrelated", "kept");
73
+
74
+ const root = mount({ threadId: "t1", ttl: 10_000 });
75
+ expect(localStorage.getItem(`${PREFIX}old`)).toBeNull();
76
+ expect(localStorage.getItem(`${PREFIX}live`)).not.toBeNull();
77
+ expect(localStorage.getItem("unrelated")).toBe("kept");
78
+ root.unmount();
79
+ });
80
+
81
+ it("sweeps the oldest drafts beyond max on mount", () => {
82
+ const now = Date.now();
83
+ seed("a", now - 3_000);
84
+ seed("b", now - 2_000);
85
+ seed("c", now - 1_000);
86
+
87
+ const root = mount({ threadId: "t1", max: 2 });
88
+ expect(localStorage.getItem(`${PREFIX}a`)).toBeNull();
89
+ expect(localStorage.getItem(`${PREFIX}b`)).not.toBeNull();
90
+ expect(localStorage.getItem(`${PREFIX}c`)).not.toBeNull();
91
+ root.unmount();
92
+ });
93
+
94
+ it("throws without localStorage", () => {
95
+ vi.stubGlobal("localStorage", undefined);
96
+ expect(() => mount({ threadId: "t1" })).toThrow(/requires localStorage/);
97
+ });
98
+ });
@@ -0,0 +1,90 @@
1
+ import { useEffect, useMemo } from "react";
2
+ import { resource } from "@assistant-ui/tap";
3
+ import type { StatewireThread } from "./StatewireThread";
4
+
5
+ const PREFIX = "aui:composer-draft:";
6
+ const DAY = 86_400_000;
7
+
8
+ type StoredDraft = {
9
+ text: string;
10
+ attachments: StatewireThread.ComposerDraft["attachments"];
11
+ ts: number;
12
+ };
13
+
14
+ const sweep = (ttl: number, max: number) => {
15
+ const entries: { key: string; ts: number }[] = [];
16
+ for (let i = 0; i < localStorage.length; i++) {
17
+ const key = localStorage.key(i)!;
18
+ if (!key.startsWith(PREFIX)) continue;
19
+ const { ts } = JSON.parse(localStorage.getItem(key)!) as StoredDraft;
20
+ entries.push({ key, ts });
21
+ }
22
+ const now = Date.now();
23
+ const fresh = entries.filter(({ key, ts }) => {
24
+ if (now - ts <= ttl) return true;
25
+ localStorage.removeItem(key);
26
+ return false;
27
+ });
28
+ fresh.sort((a, b) => b.ts - a.ts);
29
+ for (const { key } of fresh.slice(max)) localStorage.removeItem(key);
30
+ };
31
+
32
+ const useLocalStorageComposerDrafts = ({
33
+ threadId,
34
+ key = (id) => id,
35
+ ttl = 7 * DAY,
36
+ max = 50,
37
+ }: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {
38
+ if (typeof localStorage === "undefined")
39
+ throw new Error(
40
+ "statewire: LocalStorageComposerDrafts requires localStorage",
41
+ );
42
+
43
+ useEffect(() => {
44
+ sweep(ttl, max);
45
+ }, [ttl, max]);
46
+
47
+ const storageKey = PREFIX + key(threadId);
48
+ return useMemo(
49
+ (): StatewireThread.ComposerStorage => ({
50
+ read: () => {
51
+ const raw = localStorage.getItem(storageKey);
52
+ if (raw === null) return undefined;
53
+ const { text, attachments } = JSON.parse(raw) as StoredDraft;
54
+ return { text, attachments };
55
+ },
56
+ write: (draft) => {
57
+ if (draft.text === "" && draft.attachments.length === 0) {
58
+ localStorage.removeItem(storageKey);
59
+ return;
60
+ }
61
+ localStorage.setItem(
62
+ storageKey,
63
+ JSON.stringify({ ...draft, ts: Date.now() }),
64
+ );
65
+ },
66
+ clear: () => {
67
+ localStorage.removeItem(storageKey);
68
+ },
69
+ }),
70
+ [storageKey],
71
+ );
72
+ };
73
+
74
+ /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
75
+ export const LocalStorageComposerDrafts = resource(
76
+ useLocalStorageComposerDrafts,
77
+ );
78
+
79
+ export namespace LocalStorageComposerDrafts {
80
+ export type Options = {
81
+ /** The thread whose draft this storage holds. */
82
+ threadId: string;
83
+ /** Derives the storage key from the thread id; defaults to the id itself. */
84
+ key?: ((threadId: string) => string) | undefined;
85
+ /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */
86
+ ttl?: number | undefined;
87
+ /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */
88
+ max?: number | undefined;
89
+ };
90
+ }