@assistant-ui/react-statewire 0.21.0 → 0.22.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.
@@ -31,6 +31,12 @@ declare namespace StatewireThread {
31
31
  isBusy: boolean;
32
32
  inputRequests: readonly InputRequestState[];
33
33
  runs: Runs;
34
+ /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
35
+ retryFailed: (messageId: string) => void;
36
+ /** Removes the failed entry; keyed by the entry's message id. */
37
+ discardFailed: (messageId: string) => void;
38
+ /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
39
+ popFailed: (messageId: string) => string;
34
40
  };
35
41
  export type TextPart = {
36
42
  readonly type: "text";
@@ -147,6 +153,10 @@ declare namespace StatewireThread {
147
153
  /** Host-stamped opaque per-entry metadata. */
148
154
  readonly meta?: ReadonlyJSONValue;
149
155
  };
156
+ /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
157
+ export type RunsFailedEntry = RunsQueueEntry & {
158
+ readonly sendFailure: StatewireClient.SendFailure;
159
+ };
150
160
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
151
161
  export type RunsInputOutcome = {
152
162
  readonly request: InputRequest;
@@ -223,6 +233,8 @@ declare namespace StatewireThread {
223
233
  readonly inputRequests?: readonly InputRequestState[];
224
234
  /** Set only by an unhandled throw; cleared by the next user-initiated run. */
225
235
  readonly error?: RunsError;
236
+ /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
237
+ readonly failed: readonly RunsFailedEntry[];
226
238
  };
227
239
  export type ConnectionMetadata = {
228
240
  pendingCommands: Command[];
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;cA+Ca;cAEA,oBAAqB,oBAAkB,gBAAgB;cAoXvD,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACV,e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kB;;aAElB,eAAe;;;cAId;;aAED;;aAEA;aACA,gBAAgB;aAChB,qBAAqB;;aAErB,cAAc;aACd,WAAW;;aAEX,eAAe;;aAEf,yBAAyB;;aAEzB,QAAQ;;aAER,iBAAiB;;cAGhB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;IAE5B,MAAM;;;cAII;aACD,mBAAmB;aACnB,QAAQ;;cAGP,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;cAMO;aACD;cACC,cAAc;;cAGd,QAAQ;IAClB,WAAW,UAAU;;IAErB,cAAc;IACd,WAAW,eAAe;;IAE1B,aACI,gBAAgB,WACd,GACA,mBAAmB;;IAIzB,cAAc,gBAAgB,YAAY,YAAY;;;;;;IAMtD;;IAEA,qBAAqB;;IAErB,oBAEM,QAAQ,UAAU,cAChB,mBAAmB,2BAErB;MAAO,OAAO,YAAY;;;IAIhC,kBACM,OAAO,YAAY,IAAI;MAAO,SAAS,UAAU;;;IAGvD,uBACM,YAAY,gBAAgB;IAElC,YAAY,OAAO;IACnB;MAEM;;MAEA;;MAEA;;MAEA;;;;;;;;IASN;MAEM,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB,gBAAgB;;IAGhD;MAEM,cAAc;MACd,SAAS;MACT,WAAW;;;;;;YAOT;cACE;MACR,YAAY,gBAAgB;MAC5B,UAAU,gBAAgB;MAC1B,YAAY,gBAAgB;MAC5B,SAAS,gBAAgB;MACzB,aAAa,gBAAgB;MAC7B,WAAW,gBAAgB;MAC3B,UAAU,gBAAgB;MAC1B,qBAAqB,gBAAgB"}
@@ -1,4 +1,4 @@
1
- import { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage } from "./runCommands.js";
1
+ import { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, retryCommand, sendFields, toWireMessage } from "./runCommands.js";
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";
@@ -17,7 +17,15 @@ const NO_INPUT_REQUESTS = [];
17
17
  const RESTING_RUNS = {
18
18
  runId: null,
19
19
  queue: [],
20
- steerQueue: []
20
+ steerQueue: [],
21
+ failed: []
22
+ };
23
+ /** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */
24
+ const failedRunCommand = (entry) => {
25
+ if (entry.command !== "run/enqueue" && entry.command !== "run/steer" && entry.command !== "run/edit") return void 0;
26
+ const command = entry.params[0];
27
+ if (command?.message === void 0) return void 0;
28
+ return command;
21
29
  };
22
30
  const presentStatus = (status, connection) => status !== "running" || connection.status === "live" || connection.status === "idle" ? status : connection.status === "reconnecting" && connection.cause === "evicted" ? "evicted" : "disconnected";
23
31
  const ambientContextOf = (context) => ({
@@ -31,7 +39,7 @@ const useStatewireThread = (options) => {
31
39
  latest.current = options;
32
40
  const [pending, setPending] = useState([]);
33
41
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
34
- const { state: state_0, commands, connection: connection_0, setContext, isBusy } = useStatewire({
42
+ const { state: state_1, commands, connection: connection_0, setContext, isBusy, failed, discardFailed } = useStatewire({
35
43
  transport: options.transport,
36
44
  storage: options.storage,
37
45
  initialState: options.initialState,
@@ -45,8 +53,16 @@ const useStatewireThread = (options) => {
45
53
  latest.current.onCommandChange?.(update, ctx_0);
46
54
  },
47
55
  onStateChange: (state, ctx_1) => latest.current.onStateChange?.(state, ctx_1),
48
- onConnectionChange: (connection) => latest.current.onConnectionChange?.(connection)
56
+ onConnectionChange: (connection) => latest.current.onConnectionChange?.(connection),
57
+ failureCovered: (state_0, entry) => {
58
+ const command_1 = failedRunCommand(entry);
59
+ if (command_1 === void 0) return false;
60
+ return state_0.messages?.some((m) => m.id === command_1.message.id) ?? false;
61
+ }
49
62
  });
63
+ useEffect(() => {
64
+ for (const entry_0 of failed) if (failedRunCommand(entry_0) === void 0) discardFailed(entry_0);
65
+ }, [failed, discardFailed]);
50
66
  const clientRef = useAssistantClientRef();
51
67
  const setContextRef = useRef(setContext);
52
68
  setContextRef.current = setContext;
@@ -70,42 +86,56 @@ const useStatewireThread = (options) => {
70
86
  clientRef,
71
87
  syncState
72
88
  ]);
73
- const dispatch = useCallback((command_1) => {
74
- setPending((prev_0) => [...prev_0, command_1]);
75
- const settled = commands[command_1.type](command_1);
89
+ const dispatch = useCallback((command_2) => {
90
+ setPending((prev_0) => [...prev_0, command_2]);
91
+ const settled = commands[command_2.type](command_2);
76
92
  settled.catch((error) => {
77
- retire(command_1);
93
+ retire(command_2);
78
94
  latest.current.onError?.(error);
79
95
  });
80
96
  return settled;
81
97
  }, [commands, retire]);
82
98
  const threadRef = useRef(null);
83
- const dispatchSend = useCallback((command_2, message) => {
84
- if (message.sourceId != null) return void dispatch(command_2);
99
+ const dispatchSend = useCallback((command_3, message) => {
100
+ if (message.sourceId != null) return void dispatch(command_3);
85
101
  const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n");
86
- dispatch(command_2).catch(() => {
102
+ dispatch(command_3).catch(() => {
87
103
  const setText = threadRef.current.composer().setText;
88
104
  setText((prev_1) => prev_1 === "" ? text : prev_1);
89
105
  });
90
106
  }, [dispatch]);
91
107
  const { status, runs } = useMemo(() => {
92
- const entries = state_0?.runs;
93
- const entry = entries?.[0];
108
+ const entries = state_1?.runs;
109
+ const entry_1 = entries?.[0];
110
+ const failedEntries = failed.flatMap((failure) => {
111
+ const command_4 = failedRunCommand(failure);
112
+ return command_4 === void 0 ? [] : [{
113
+ ...command_4.message,
114
+ sendFailure: failure.failure
115
+ }];
116
+ });
94
117
  return {
95
- status: presentStatus(entries === void 0 ? "loading" : entry?.status ?? "ready", connection_0),
96
- runs: entry === void 0 ? RESTING_RUNS : {
97
- runId: entry.runId,
98
- ...entry.epoch !== void 0 && { epoch: entry.epoch },
99
- queue: entry.queue,
100
- steerQueue: entry.steerQueue,
101
- ...entry.dispatching !== void 0 && { dispatching: entry.dispatching },
102
- ...entry.stopping !== void 0 && { stopping: entry.stopping },
103
- ...entry.nextDispatch !== void 0 && { nextDispatch: entry.nextDispatch },
104
- ...entry.inputRequests !== void 0 && { inputRequests: entry.inputRequests },
105
- ...entry.error !== void 0 && { error: entry.error }
118
+ status: presentStatus(entries === void 0 ? "loading" : entry_1?.status ?? "ready", connection_0),
119
+ runs: entry_1 === void 0 && failedEntries.length === 0 ? RESTING_RUNS : {
120
+ ...entry_1 === void 0 ? RESTING_RUNS : {
121
+ runId: entry_1.runId,
122
+ ...entry_1.epoch !== void 0 && { epoch: entry_1.epoch },
123
+ queue: entry_1.queue,
124
+ steerQueue: entry_1.steerQueue,
125
+ ...entry_1.dispatching !== void 0 && { dispatching: entry_1.dispatching },
126
+ ...entry_1.stopping !== void 0 && { stopping: entry_1.stopping },
127
+ ...entry_1.nextDispatch !== void 0 && { nextDispatch: entry_1.nextDispatch },
128
+ ...entry_1.inputRequests !== void 0 && { inputRequests: entry_1.inputRequests },
129
+ ...entry_1.error !== void 0 && { error: entry_1.error }
130
+ },
131
+ failed: failedEntries
106
132
  }
107
133
  };
108
- }, [state_0, connection_0]);
134
+ }, [
135
+ state_1,
136
+ connection_0,
137
+ failed
138
+ ]);
109
139
  const { converter } = options;
110
140
  const metadata = useMemo(() => ({
111
141
  pendingCommands: [...pending],
@@ -117,54 +147,77 @@ const useStatewireThread = (options) => {
117
147
  connection_0,
118
148
  runs
119
149
  ]);
120
- const converted = useMemo(() => converter(state_0, metadata), [
150
+ const converted = useMemo(() => converter(state_1, metadata), [
121
151
  converter,
122
- state_0,
152
+ state_1,
123
153
  metadata
124
154
  ]);
125
- const messages = converted.messages;
155
+ const messages_0 = converted.messages;
126
156
  const liveRunId = runs.runId;
127
- const queue = useMemo(() => createRunQueueAdapter(messages, liveRunId, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
128
- messages,
157
+ const queue = useMemo(() => createRunQueueAdapter(messages_0, liveRunId, runs.queue, runs.steerQueue, dispatch, dispatchSend), [
158
+ messages_0,
129
159
  liveRunId,
130
160
  runs,
131
161
  dispatch,
132
162
  dispatchSend
133
163
  ]);
134
- const branches = useMemo(() => createBranchCommandAdapter(messages, dispatch), [messages, dispatch]);
164
+ const branches = useMemo(() => createBranchCommandAdapter(messages_0, dispatch), [messages_0, dispatch]);
135
165
  const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
136
- const extras = useMemo(() => ({
137
- [symbolStatewireExtras]: true,
138
- sendCommand: dispatch,
139
- reconnect: connection_0.reconnect,
140
- state: state_0,
141
- status,
142
- isBusy,
143
- inputRequests,
144
- runs
145
- }), [
166
+ const extras = useMemo(() => {
167
+ const takeFailed = (messageId) => {
168
+ const entry_2 = failed.find((f) => failedRunCommand(f)?.message.id === messageId);
169
+ if (entry_2 === void 0) throw new Error(`statewire: unknown failed entry "${messageId}"`);
170
+ return entry_2;
171
+ };
172
+ return {
173
+ [symbolStatewireExtras]: true,
174
+ sendCommand: dispatch,
175
+ reconnect: connection_0.reconnect,
176
+ state: state_1,
177
+ status,
178
+ isBusy,
179
+ inputRequests,
180
+ runs,
181
+ retryFailed: (messageId_0) => {
182
+ const entry_3 = takeFailed(messageId_0);
183
+ const command_5 = retryCommand(messages_0, liveRunId, failedRunCommand(entry_3));
184
+ discardFailed(entry_3);
185
+ dispatch(command_5);
186
+ },
187
+ discardFailed: (messageId_1) => discardFailed(takeFailed(messageId_1)),
188
+ popFailed: (messageId_2) => {
189
+ const entry_4 = takeFailed(messageId_2);
190
+ discardFailed(entry_4);
191
+ return failedRunCommand(entry_4).message.parts.flatMap((p) => p.type === "text" ? [p.text] : []).join("\n\n");
192
+ }
193
+ };
194
+ }, [
146
195
  dispatch,
147
196
  connection_0.reconnect,
148
- state_0,
197
+ state_1,
149
198
  status,
150
199
  isBusy,
151
200
  inputRequests,
152
- runs
201
+ runs,
202
+ failed,
203
+ discardFailed,
204
+ messages_0,
205
+ liveRunId
153
206
  ]);
154
207
  const handleAppend = (message_0) => {
155
- dispatchSend(message_0.sourceId != null ? resolveEditCommand(messages, message_0, liveRunId) : {
208
+ dispatchSend(message_0.sourceId != null ? resolveEditCommand(messages_0, message_0, liveRunId) : {
156
209
  type: "run/steer",
157
- ...sendFields(messages, liveRunId, toWireMessage(message_0, crypto.randomUUID()))
210
+ ...sendFields(messages_0, liveRunId, toWireMessage(message_0, crypto.randomUUID()))
158
211
  }, message_0);
159
212
  };
160
213
  const handleReload = (parentId) => {
161
- dispatch(resolveReloadCommand(messages, parentId, liveRunId));
214
+ dispatch(resolveReloadCommand(messages_0, parentId, liveRunId));
162
215
  };
163
216
  const handleEdit = (message_1) => {
164
- dispatch(resolveEditCommand(messages, message_1, liveRunId));
217
+ dispatch(resolveEditCommand(messages_0, message_1, liveRunId));
165
218
  };
166
219
  const thread = useResource(ExternalThread({
167
- messages,
220
+ messages: messages_0,
168
221
  isRunning: status === "running",
169
222
  state: converted.state,
170
223
  extras,
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","presentStatus","status","ThreadStatus","connection","ConnectionState","cause","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","command","prev","includes","filter","c","state","commands","setContext","isBusy","transport","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","params","onStateChange","onConnectionChange","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","message","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","entry","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","State","messages","liveRunId","branches","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","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","storageRef","storageHook","hook","read","getState","isEmpty","attachment","addAttachment","id","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","UserMessage","role","parts","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","messageId","RunEnqueueCommand","RunSteerCommand","RunDequeueCommand","RunEditCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"live\" ||\n connection.status === \"idle\"\n ? status\n : connection.status === \"reconnecting\" && connection.cause === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const { state, commands, connection, setContext, isBusy } = useStatewire<\n unknown,\n AnyCommands\n >({\n transport: options.transport,\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && { stopping: entry.stopping }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n },\n };\n }, [state, connection]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\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 ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n const storageRef = useRef(composerStorage);\n storageRef.current = composerStorage;\n const storageHook = options.storage?.composer?.hook;\n\n useEffect(() => {\n const storage = storageRef.current;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [storageHook]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = storageRef.current;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storageHook;\n draftSync.writingFor = storageHook;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, storageHook, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n 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 type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `live`. */\n connection: StatewireClient.ConnectionState;\n /** The typed runs read. */\n runs: Runs;\n };\n\n /** Converter output: app-owned keys only — the lib projects the run mounts itself. */\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n /**\n * Payload of the built-in `run/stop` command. `reason` is the one well-known\n * field; apps extend it with their own JSON-serializable fields.\n */\n export type StopPayload = {\n readonly reason?: string | undefined;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n export type Options<T> = {\n transport: Transport<T>;\n /** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */\n initialState: T;\n converter: StateConverter<T>;\n /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */\n optimistic?:\n | StatewireClient.Optimistic<\n T,\n Record<string, (...args: any[]) => unknown>\n >\n | undefined;\n /** Makes dispatch records concrete in the draft (runs after the optimistic folds); without it, dispatch limbo stays out of `messages`. */\n materialize?: StatewireClient.Materialize<NonNullable<T>> | undefined;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */\n stopPayload?: (() => StopPayload) | undefined;\n /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */\n onCommandChange?:\n | ((\n update: Statewire.CommandUpdate<\n Record<string, (...args: any[]) => unknown>\n >,\n ctx: { state: NonNullable<T> },\n ) => void)\n | undefined;\n /** Observes the transport state: fires with the attach snapshot, then once per change. */\n onStateChange?:\n | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)\n | undefined;\n /** Observes connection status transitions, starting with the initial status. */\n onConnectionChange?:\n | ((connection: StatewireClient.Connection) => void)\n | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n /** The host supports `run/continue` (a continue affordance on aborted runs). */\n continue?: boolean | undefined;\n /** The host supports `run/reload` (regenerating an assistant message). */\n reload?: boolean | undefined;\n /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AA+CA,MAAa0C,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;AAIA,MAAMC,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,UACtBE,WAAWF,WAAW,SAClBA,SACAE,WAAWF,WAAW,kBAAkBE,WAAWE,UAAU,YAC3D,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,EACjCC,OAAOzC,kBAAkBsC,QAAQG,KAAK,EACxC;CACA,GAAIH,QAAQI,iBAAiBF,KAAAA,KAAa,EACxCE,cAAcJ,QAAQI,aACxB;CACA,GAAIJ,QAAQK,WAAWH,KAAAA,KAAa,EAAEG,QAAQL,QAAQK,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAASrE,OAAOmE,OA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AAa,EAC1CoI,aAAaJ,WAAWI,YAC1B;GACAzE,SAASqE,WAAWrE;EACtB,CAAC,CAAC,CACDR,OAAOC,YAAiB;GACvB7C,OAAOC,QAAQ6C,UAAUD,OAAK;EAChC,CAAC;CAEP,GAAG,CAACuE,WAAW,CAAC;CAEhB,MAAM,EAAEjE,MAAM2E,WAAWnC,aAAaoC,wBACpCxC,OAAOgC,SAAS,CAAC,CAAC9D;CACpB,MAAMuE,mBAAmBtM,cAErBqM,oBACGtH,QACEgH,iBACCA,aAAWxI,OAAO0D,SAAS,UAC/B,CAAC,CACAsF,KAAK,EAAEC,MAAMC,OAAO,GAAGC,aAAaA,MAAM,GAC/C,CAACL,mBAAmB,CACtB;CACA,MAAM,CAACM,aAAazM,gBAAgB,EAAE0M,YAAY7I,KAAAA,EAAqB,EAAE;CACzEhE,gBAAgB;EACd,MAAMuF,YAAUmG,WAAWlH;EAC3B,IAAIe,cAAYvB,KAAAA,GAAW;EAG3B,MAAM8I,aAAaF,UAAUC,eAAelB;EAC5CiB,UAAUC,aAAalB;EACvB,IAAIU,cAAc,MAAME,iBAAiBvD,WAAW,GAAG;GACrD,IAAI,CAAC8D,YAAYvH,UAAQwH,MAAM;GAC/B;EACF;EACAxH,UAAQyH,MAAM;GAAEtF,MAAM2E;GAAWnC,aAAaqC;EAAiB,CAAC;CAClE,GAAG;EAACK;EAAWjB;EAAaU;EAAWE;CAAgB,CAAC;CAExD,OAAOzC;AACT;AAEA,MAAajH,mBACXwB,YAEAjE,SAASgE,kBAAkB,CAAC,CAACC,OAAuC;AAgZtEzD,uBACEwD,oBACA3D,eAAeuD,KAAAA,CAAkB,CAAC,CAAC4H,IACrC"}
1
+ {"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","useResources","withKey","ResourceElement","ExternalThread","ExternalThreadMessage","Assistant","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","AttachmentAdapter","CompleteAttachment","FeedbackAdapter","ModelContext","RespondToToolApprovalOptions","SpeechSynthesisAdapter","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","StatewireClient","createBranchCommandAdapter","createRunQueueAdapter","resolveEditCommand","retryCommand","resolveReloadCommand","sendFields","toWireMessage","resolveToolApprovalInput","resolveToolResultInput","runsOptimistic","AnyCommands","Record","args","symbolStatewireExtras","Symbol","asStatewireExtras","extras","StatewireThread","Extras","Error","NO_INPUT_REQUESTS","InputRequestState","RESTING_RUNS","Runs","runId","queue","steerQueue","failed","failedRunCommand","entry","FailedCommand","RunEnqueueCommand","RunSteerCommand","RunEditCommand","message","UserMessage","command","undefined","params","ReturnType","presentStatus","status","ThreadStatus","connection","ConnectionState","cause","ambientContextOf","context","system","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","Command","retire","prev","includes","filter","c","state","commands","setContext","isBusy","discardFailed","transport","storage","initialState","optimistic","draft","ctx","materialize","onCommandChange","update","onStateChange","onConnectionChange","failureCovered","messages","id","some","m","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","subscribe","dispatch","settled","type","catch","error","onError","threadRef","dispatchSend","sourceId","text","content","flatMap","part","join","setText","composer","next","runs","entries","RunState","failedEntries","failure","RunsFailedEntry","sendFailure","length","epoch","dispatching","stopping","nextDispatch","inputRequests","converter","metadata","ConnectionMetadata","pendingCommands","isSending","converted","State","liveRunId","branches","takeFailed","messageId","find","f","sendCommand","reconnect","retryFailed","popFailed","parts","p","handleAppend","crypto","randomUUID","handleReload","parentId","handleEdit","thread","isRunning","attachmentAdapter","adapters","attachments","speechAdapter","speech","feedbackAdapter","feedback","onNew","capabilities","edit","onEdit","continue","onResume","reload","onReload","unstable_switchBranch","onAddToolResult","toolOptions","onRespondToToolApproval","approval","onCancel","payload","stopPayload","Array","isArray","composerStorage","storageRef","storageHook","hook","read","getState","isEmpty","attachment","addAttachment","name","contentType","draftText","composerAttachments","draftAttachments","map","file","_file","record","draftSync","writingFor","isBaseline","clear","write","T","UserCommands","Commands","Transport","ComposerDraft","ComposerStorage","TextPart","FilePart","mediaType","url","filename","role","Placement","insertAfter","insertBefore","RunSendCommand","TType","runAnchorMessageId","RunDequeueCommand","RunContinueCommand","ToolCallInputRequest","toolCallId","ToolApprovalInputRequest","CustomInputRequest","InputRequest","InputResponse","RunInputCommand","requestId","response","meta","BranchMetadata","siblings","SwitchBranchCommand","branchId","RunReloadCommand","RunCommand","RunQueueItem","RunStatus","RunsQueueEntry","SendFailure","RunsInputOutcome","request","RunsDispatch","trigger","rollbackTo","rootMeta","inputOutcomes","RunsStopping","reason","RunsError","MaterializeEffects","append","rollback","to","RunsState","StateConverter","connectionMetadata","StopPayload","Optimistic","Materialize","NonNullable","CommandUpdate","changes","Changes","Connection","session","SessionStorage","runEnqueue","runSteer","runDequeue","runEdit","runContinue","runReload","runInput","messageSwitchBranch"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n resource,\n useResource,\n useResources,\n withKey,\n} from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/core/store\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/core/store\";\nimport type { Assistant } from \"@assistant-ui/core\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n AttachmentAdapter,\n CompleteAttachment,\n FeedbackAdapter,\n ModelContext,\n RespondToToolApprovalOptions,\n SpeechSynthesisAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport {\n createBranchCommandAdapter,\n createRunQueueAdapter,\n resolveEditCommand,\n retryCommand,\n resolveReloadCommand,\n sendFields,\n toWireMessage,\n} from \"./runCommands\";\nimport {\n resolveToolApprovalInput,\n resolveToolResultInput,\n} from \"./inputRequests\";\nimport { runsOptimistic } from \"./runsOptimistic\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nexport const symbolStatewireExtras = Symbol(\"statewire-extras\");\n\nexport const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolStatewireExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using StatewireThread\",\n );\n\n return extras as StatewireThread.Extras;\n};\n\nconst NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];\n\nconst RESTING_RUNS: StatewireThread.Runs = {\n runId: null,\n queue: [],\n steerQueue: [],\n failed: [],\n};\n\n/** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */\nconst failedRunCommand = (\n entry: StatewireClient.FailedCommand,\n):\n | ((\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand\n | StatewireThread.RunEditCommand\n ) & { message: StatewireThread.UserMessage })\n | undefined => {\n if (\n entry.command !== \"run/enqueue\" &&\n entry.command !== \"run/steer\" &&\n entry.command !== \"run/edit\"\n )\n return undefined;\n const command = entry.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (command?.message === undefined) return undefined;\n return command as ReturnType<typeof failedRunCommand>;\n};\n\n// Derived presentation while the connection can't vouch for progress:\n// live-claiming \"running\" reads as evicted/disconnected; facts pass through.\nconst presentStatus = (\n status: StatewireThread.ThreadStatus,\n connection: StatewireClient.ConnectionState,\n): StatewireThread.ThreadStatus =>\n status !== \"running\" ||\n connection.status === \"live\" ||\n connection.status === \"idle\"\n ? status\n : connection.status === \"reconnecting\" && connection.cause === \"evicted\"\n ? \"evicted\"\n : \"disconnected\";\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly StatewireThread.Command[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as StatewireThread.Command)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const {\n state,\n commands,\n connection,\n setContext,\n isBusy,\n failed,\n discardFailed,\n } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n storage: options.storage,\n initialState: options.initialState,\n optimistic: (draft, command, ctx) => {\n runsOptimistic(draft, command, ctx);\n latest.current.optimistic?.(draft, command, ctx);\n },\n materialize: (draft: {}) => latest.current.materialize?.(draft),\n onCommandChange: (update, ctx) => {\n if (update.status === \"applied\" || update.status === \"settled\")\n retire(update.params[0]);\n latest.current.onCommandChange?.(update, ctx);\n },\n onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),\n onConnectionChange: (connection) =>\n latest.current.onConnectionChange?.(connection),\n failureCovered: (state, entry) => {\n const command = failedRunCommand(entry);\n if (command === undefined) return false;\n const messages = (state as { messages?: readonly { id: string }[] })\n .messages;\n return messages?.some((m) => m.id === command.message.id) ?? false;\n },\n });\n\n // Failures the thread cannot project stay onError-only, as before the lane.\n useEffect(() => {\n for (const entry of failed) {\n if (failedRunCommand(entry) === undefined) discardFailed(entry);\n }\n }, [failed, discardFailed]);\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n setContextRef.current(value);\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: StatewireThread.Command) => {\n setPending((prev) => [...prev, command]);\n const settled = commands[command.type]!(command);\n settled.catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n return settled;\n },\n [commands, retire],\n );\n\n const threadRef = useRef<ClientOutput<\"thread\"> | null>(null);\n const dispatchSend = useCallback(\n (command: StatewireThread.Command, message: AppendMessage) => {\n if (message.sourceId != null) return void dispatch(command);\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\");\n void dispatch(command).catch(() => {\n // Rejected send: put the text back unless the user typed since.\n // ExternalThread's setText is live-ref-backed and takes an updater.\n const setText = threadRef.current!.composer().setText as (\n next: string | ((prev: string) => string),\n ) => void;\n setText((prev) => (prev === \"\" ? text : prev));\n });\n },\n [dispatch],\n );\n\n const { status, runs } = useMemo((): {\n status: StatewireThread.ThreadStatus;\n runs: StatewireThread.Runs;\n } => {\n const entries = (\n state as { runs?: readonly StatewireThread.RunState[] } | undefined\n )?.runs;\n const entry = entries?.[0];\n const failedEntries = failed.flatMap(\n (failure): StatewireThread.RunsFailedEntry[] => {\n const command = failedRunCommand(failure);\n return command === undefined\n ? []\n : [{ ...command.message, sendFailure: failure.failure }];\n },\n );\n return {\n status: presentStatus(\n entries === undefined ? \"loading\" : (entry?.status ?? \"ready\"),\n connection,\n ),\n runs:\n entry === undefined && failedEntries.length === 0\n ? RESTING_RUNS\n : {\n ...(entry === undefined\n ? RESTING_RUNS\n : {\n runId: entry.runId,\n ...(entry.epoch !== undefined && { epoch: entry.epoch }),\n queue: entry.queue,\n steerQueue: entry.steerQueue,\n ...(entry.dispatching !== undefined && {\n dispatching: entry.dispatching,\n }),\n ...(entry.stopping !== undefined && {\n stopping: entry.stopping,\n }),\n ...(entry.nextDispatch !== undefined && {\n nextDispatch: entry.nextDispatch,\n }),\n ...(entry.inputRequests !== undefined && {\n inputRequests: entry.inputRequests,\n }),\n ...(entry.error !== undefined && { error: entry.error }),\n }),\n failed: failedEntries,\n },\n };\n }, [state, connection, failed]);\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n connection,\n runs,\n }),\n [pending, connection, runs],\n );\n const converted = useMemo(\n (): StatewireThread.State => converter(state, metadata),\n [converter, state, metadata],\n );\n // Dispatch limbo is a materialize concern: the fold makes the record\n // concrete in state before conversion.\n const messages = converted.messages;\n const liveRunId = runs.runId;\n\n const queue = useMemo(\n () =>\n createRunQueueAdapter(\n messages,\n liveRunId,\n runs.queue,\n runs.steerQueue,\n dispatch,\n dispatchSend,\n ),\n [messages, liveRunId, runs, dispatch, dispatchSend],\n );\n\n const branches = useMemo(\n () => createBranchCommandAdapter(messages, dispatch),\n [messages, dispatch],\n );\n\n const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;\n\n const extras = useMemo((): StatewireThread.Extras => {\n const takeFailed = (messageId: string): StatewireClient.FailedCommand => {\n const entry = failed.find(\n (f) => failedRunCommand(f)?.message.id === messageId,\n );\n if (entry === undefined)\n throw new Error(`statewire: unknown failed entry \"${messageId}\"`);\n return entry;\n };\n return {\n [symbolStatewireExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n retryFailed: (messageId) => {\n const entry = takeFailed(messageId);\n const command = retryCommand(\n messages,\n liveRunId,\n failedRunCommand(entry)!,\n );\n discardFailed(entry);\n void dispatch(command);\n },\n discardFailed: (messageId) => discardFailed(takeFailed(messageId)),\n popFailed: (messageId) => {\n const entry = takeFailed(messageId);\n discardFailed(entry);\n return failedRunCommand(entry)!\n .message.parts.flatMap((p) => (p.type === \"text\" ? [p.text] : []))\n .join(\"\\n\\n\");\n },\n };\n }, [\n dispatch,\n connection.reconnect,\n state,\n status,\n isBusy,\n inputRequests,\n runs,\n failed,\n discardFailed,\n messages,\n liveRunId,\n ]);\n\n const handleAppend = (message: AppendMessage) => {\n dispatchSend(\n message.sourceId != null\n ? resolveEditCommand(messages, message, liveRunId)\n : {\n type: \"run/steer\",\n ...sendFields(\n messages,\n liveRunId,\n toWireMessage(message, crypto.randomUUID()),\n ),\n },\n message,\n );\n };\n\n const handleReload = (parentId: string | null) => {\n dispatch(resolveReloadCommand(messages, parentId, liveRunId));\n };\n\n const handleEdit = (message: AppendMessage) => {\n dispatch(resolveEditCommand(messages, message, liveRunId));\n };\n\n const thread = useResource(\n ExternalThread({\n messages: messages as readonly ExternalThreadMessage[],\n isRunning: status === \"running\",\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n speechAdapter: options.adapters?.speech,\n feedbackAdapter: options.adapters?.feedback,\n onNew: handleAppend,\n queue,\n ...(options.capabilities?.edit && { onEdit: handleEdit }),\n ...(options.capabilities?.continue && {\n onResume: () =>\n dispatch({\n type: \"run/continue\",\n ...(liveRunId !== null && { runId: liveRunId }),\n }),\n }),\n ...(options.capabilities?.reload && { onReload: handleReload }),\n ...(options.capabilities?.unstable_switchBranch && { branches }),\n onAddToolResult: (toolOptions: AddToolResultOptions) =>\n dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),\n onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>\n dispatch(resolveToolApprovalInput(inputRequests, approval, liveRunId)),\n onCancel: () => {\n const payload = latest.current.stopPayload?.();\n if (\n payload !== undefined &&\n (typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload))\n )\n throw new Error(\"statewire: stopPayload must return a plain object\");\n void commands[\"run/stop\"]!({\n ...payload,\n runId: runs.runId,\n ...(runs.epoch !== undefined && { epoch: runs.epoch }),\n }).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n threadRef.current = thread;\n\n const composerStorage = useResources(\n options.storage?.composer !== undefined\n ? [withKey(\"composer\", options.storage.composer)]\n : [],\n )[0];\n const storageRef = useRef(composerStorage);\n storageRef.current = composerStorage;\n const storageHook = options.storage?.composer?.hook;\n\n useEffect(() => {\n const storage = storageRef.current;\n if (storage === undefined) return;\n const composer = threadRef.current!.composer();\n const draft = storage.read();\n if (draft === undefined || !composer.getState().isEmpty) return;\n composer.setText(draft.text);\n for (const attachment of draft.attachments) {\n composer\n .addAttachment({\n id: attachment.id,\n type: attachment.type,\n name: attachment.name,\n ...(attachment.contentType !== undefined && {\n contentType: attachment.contentType,\n }),\n content: attachment.content,\n })\n .catch((error: Error) => {\n latest.current.onError?.(error);\n });\n }\n }, [storageHook]);\n\n const { text: draftText, attachments: composerAttachments } =\n thread.getState().composer;\n const draftAttachments = useMemo(\n () =>\n composerAttachments\n .filter(\n (attachment): attachment is CompleteAttachment =>\n attachment.status.type === \"complete\",\n )\n .map(({ file: _file, ...record }) => record),\n [composerAttachments],\n );\n const [draftSync] = useState(() => ({ writingFor: undefined as unknown }));\n useEffect(() => {\n const storage = storageRef.current;\n if (storage === undefined) return;\n // First run per storage is the baseline, not a change: never clear the\n // stored draft the restore effect is about to load.\n const isBaseline = draftSync.writingFor !== storageHook;\n draftSync.writingFor = storageHook;\n if (draftText === \"\" && draftAttachments.length === 0) {\n if (!isBaseline) storage.clear();\n return;\n }\n storage.write({ text: draftText, attachments: draftAttachments });\n }, [draftSync, storageHook, draftText, draftAttachments]);\n\n return thread;\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n type UserCommands = Assistant.Commands[keyof Assistant.Commands];\n\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n /** A composer draft as persisted: the text plus the completed attachments. */\n export type ComposerDraft = {\n readonly text: string;\n readonly attachments: readonly CompleteAttachment[];\n };\n\n /** Composer draft storage seam; `write` must persist synchronously in the caller's flow. */\n export type ComposerStorage = {\n read(): ComposerDraft | undefined;\n write(draft: ComposerDraft): void;\n clear(): void;\n };\n\n export type Extras = {\n [symbolStatewireExtras]: true;\n 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 /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */\n retryFailed: (messageId: string) => void;\n /** Removes the failed entry; keyed by the entry's message id. */\n discardFailed: (messageId: string) => void;\n /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */\n popFailed: (messageId: string) => string;\n };\n\n export type TextPart = {\n readonly type: \"text\";\n readonly text: string;\n };\n\n export type FilePart = {\n readonly type: \"file\";\n readonly mediaType: string;\n readonly url: string;\n readonly filename?: string;\n };\n\n export type UserMessage = {\n readonly id: string;\n readonly role: \"user\";\n readonly parts: readonly (TextPart | FilePart)[];\n readonly metadata?: Record<string, unknown>;\n };\n\n /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */\n export type Placement = {\n readonly insertAfter?: string | null;\n readonly insertBefore?: string | null;\n };\n\n type RunSendCommand<TType extends \"run/enqueue\" | \"run/steer\"> = {\n readonly type: TType;\n /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */\n readonly runId: string;\n } & (\n | {\n readonly message: UserMessage;\n /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */\n readonly runAnchorMessageId?: string | null;\n }\n | { readonly messageId: string }\n ) &\n Placement;\n\n export type RunEnqueueCommand = RunSendCommand<\"run/enqueue\">;\n\n export type RunSteerCommand = RunSendCommand<\"run/steer\">;\n\n export type RunDequeueCommand = {\n readonly type: \"run/dequeue\";\n readonly runId: string;\n readonly messageId: string;\n };\n\n export type RunEditCommand = {\n readonly type: \"run/edit\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly message: UserMessage;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunContinueCommand = {\n readonly type: \"run/continue\";\n readonly runId?: string;\n };\n\n export type ToolCallInputRequest = {\n readonly type: \"tool-call\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type ToolApprovalInputRequest = {\n readonly type: \"tool-approval\";\n readonly id: string;\n readonly toolCallId: string;\n };\n\n export type CustomInputRequest = {\n readonly type: string;\n readonly id: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A host request parking the run until answered; open union for custom types. */\n export type InputRequest =\n | ToolCallInputRequest\n | ToolApprovalInputRequest\n | CustomInputRequest;\n\n export type InputResponse = ReadonlyJSONValue;\n\n export type RunInputCommand = {\n readonly type: \"run/input\";\n readonly runId?: string;\n readonly requestId: string;\n readonly response: InputResponse;\n };\n\n /** An input request projected out of the host state; a present `response` key marks the entry answered. */\n export type InputRequestState = InputRequest & {\n readonly response?: InputResponse;\n /** The answer's `run/input` meta; absent when the answer carried none. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */\n export type BranchMetadata = {\n readonly id: number;\n readonly siblings: readonly number[];\n };\n\n export type SwitchBranchCommand = {\n readonly type: \"message/switch-branch\";\n readonly branchId: number;\n };\n\n export type RunReloadCommand = {\n readonly type: \"run/reload\";\n /** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */\n readonly runId: string;\n readonly sourceId: string;\n /** Asserts `sourceId`'s parent — the rewind target; null names the root. */\n readonly runAnchorMessageId: string | null;\n };\n\n export type RunCommand =\n | RunEnqueueCommand\n | RunSteerCommand\n | RunDequeueCommand\n | RunEditCommand\n | RunContinueCommand\n | RunReloadCommand\n | RunInputCommand;\n\n export type Command = RunCommand | UserCommands;\n\n /** A queued message projected out of the host state, wire shape. */\n export type RunQueueItem = {\n readonly id: string;\n readonly parts: readonly (TextPart | FilePart)[];\n };\n\n /** Run subsystem status replicated by the host. */\n export type RunStatus = \"running\" | \"stopped\" | \"error\" | \"input-required\";\n\n /** The thread's status: `\"loading\"` while the runs mount is absent, `\"ready\"` while resting, otherwise the run's status; `\"evicted\"` and `\"disconnected\"` are client-derived from the connection, never replicated. */\n export type ThreadStatus =\n | \"loading\"\n | \"ready\"\n | \"evicted\"\n | \"disconnected\"\n | RunStatus;\n\n /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */\n export type RunsQueueEntry = UserMessage & {\n /** Host-stamped opaque per-entry metadata. */\n readonly meta?: ReadonlyJSONValue;\n };\n\n /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */\n export type RunsFailedEntry = RunsQueueEntry & {\n readonly sendFailure: StatewireClient.SendFailure;\n };\n\n /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */\n export type RunsInputOutcome = {\n readonly request: InputRequest;\n readonly response: InputResponse | null;\n readonly meta: ReadonlyJSONValue | null;\n };\n\n /** The dispatch record — the unapplied batch handed to the run; absent between applied and the next dispatch or take. */\n export type RunsDispatch = {\n readonly trigger:\n | \"message-send\"\n | \"message-edit\"\n | \"message-reload\"\n | \"input-resume\"\n | \"error-continue\"\n | \"stop-continue\"\n | \"steer\";\n readonly messages: readonly RunsQueueEntry[];\n /** Present on rewind dispatches: truncate the thread at this id first; null names the root. */\n readonly rollbackTo?: string | null;\n /** The run-starting op's meta; present only when carried. */\n readonly rootMeta?: ReadonlyJSONValue;\n /** Present when input outcomes ride the dispatch; visible until applied. */\n readonly inputOutcomes?: readonly RunsInputOutcome[];\n };\n\n /** The stopping window: present while a stop of the live run is underway; `\"message-edit\"` / `\"message-reload\"` pair with `nextDispatch`. */\n export type RunsStopping = {\n readonly reason: \"stop\" | \"message-edit\" | \"message-reload\";\n };\n\n /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */\n export type RunsError = {\n readonly message: string;\n readonly [key: string]: ReadonlyJSONValue | undefined;\n };\n\n /** A replicated run entry — one element of the mount's `runs` array. */\n export type RunState = {\n /** The run's identity — client-minted, adopted by the host at run creation; persists through steers, input-required, and error/stop, retiring only when the queue drains and the run completes. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */\n readonly epoch?: number;\n readonly status: RunStatus;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n };\n\n /** App-shaped effects `runsMaterialize` applies for the dispatch record. */\n export type MaterializeEffects = {\n /** Append one dispatched message to the app's committed message state. */\n append: (message: RunsQueueEntry) => void;\n /** Truncate to the rolled-back view first (null names the root); required for hosts that dispatch edits/reloads. */\n rollback?: (to: string | null) => void;\n };\n\n /** The runs mount as replicated: the run entries plus the top-level status projection. */\n export type RunsState = {\n /** Projection of `runs[0]?.status ?? \"ready\"`. */\n readonly status: \"ready\" | RunStatus;\n /** At most one entry; empty while resting. */\n readonly runs: readonly RunState[];\n };\n\n /** The run subsystem's typed read — `runs[0]` of the state with unsettled commands folded in, resting defaults while no entry is live. */\n export type Runs = {\n /** The live run's id — non-null whenever a run entry is live (running, input-required, error/stop); the target for `run/*` sends. */\n readonly runId: string | null;\n /** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */\n readonly epoch?: number;\n readonly queue: readonly RunsQueueEntry[];\n readonly steerQueue: readonly RunsQueueEntry[];\n /** The dispatch record — the unapplied batch handed to the run, cleared at applied. */\n readonly dispatching?: RunsDispatch;\n readonly stopping?: RunsStopping;\n /** The complete dispatch staged behind a stopping rewind; promotes under the entry's `runId`. */\n readonly nextDispatch?: RunsDispatch;\n /** The parked pending set; present only in input-required. */\n readonly inputRequests?: readonly InputRequestState[];\n /** Set only by an unhandled throw; cleared by the next user-initiated run. */\n readonly error?: RunsError;\n /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */\n readonly failed: readonly RunsFailedEntry[];\n };\n\n export type ConnectionMetadata = {\n pendingCommands: Command[];\n isSending: boolean;\n /** Statewire connection status; local transports are always `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 /** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */\n unstable_switchBranch?: boolean | undefined;\n }\n | undefined;\n /**\n * Durable drafts: the mounted composer storage restores on mount, mirrors\n * every change, and clears when the draft is consumed. The session storage\n * holds this thread's lane identity and its un-durable commands, which\n * resend under their original seqs on the next mount.\n */\n storage?:\n | {\n composer?: ResourceElement<ComposerStorage> | undefined;\n session?: ResourceElement<StatewireClient.SessionStorage> | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n speech?: SpeechSynthesisAdapter | undefined;\n feedback?: FeedbackAdapter | undefined;\n }\n | undefined;\n };\n}\n\ndeclare module \"@assistant-ui/core\" {\n namespace Assistant {\n interface Commands {\n runEnqueue: StatewireThread.RunEnqueueCommand;\n runSteer: StatewireThread.RunSteerCommand;\n runDequeue: StatewireThread.RunDequeueCommand;\n runEdit: StatewireThread.RunEditCommand;\n runContinue: StatewireThread.RunContinueCommand;\n runReload: StatewireThread.RunReloadCommand;\n runInput: StatewireThread.RunInputCommand;\n messageSwitchBranch: StatewireThread.SwitchBranchCommand;\n }\n }\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;;AAgDA,MAAa2C,wBAAwBC,OAAO,kBAAkB;AAE9D,MAAaC,qBAAqBC,WAA4C;CAC5E,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEH,yBAAyBG,SAE3B,MAAM,IAAIG,MACR,mEACF;CAEF,OAAOH;AACT;AAEA,MAAMI,oBAAkE,CAAA;AAExE,MAAME,eAAqC;CACzCE,OAAO;CACPC,OAAO,CAAA;CACPC,YAAY,CAAA;CACZC,QAAQ,CAAA;AACV;;AAGA,MAAMC,oBACJC,UAOe;CACf,IACEA,MAAMO,YAAY,iBAClBP,MAAMO,YAAY,eAClBP,MAAMO,YAAY,YAElB,OAAOC,KAAAA;CACT,MAAMD,UAAUP,MAAMS,OAAO;CAG7B,IAAIF,SAASF,YAAYG,KAAAA,GAAW,OAAOA,KAAAA;CAC3C,OAAOD;AACT;AAIA,MAAMI,iBACJC,QACAE,eAEAF,WAAW,aACXE,WAAWF,WAAW,UACtBE,WAAWF,WAAW,SAClBA,SACAE,WAAWF,WAAW,kBAAkBE,WAAWE,UAAU,YAC3D,YACA;AAER,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWX,KAAAA,KAAa,EAAEW,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,UAAUZ,KAAAA,KAAa,EACjCY,OAAOtD,kBAAkBoD,QAAQE,KAAK,EACxC;CACA,GAAIF,QAAQG,iBAAiBb,KAAAA,KAAa,EACxCa,cAAcH,QAAQG,aACxB;CACA,GAAIH,QAAQI,WAAWd,KAAAA,KAAa,EAAEc,QAAQJ,QAAQI,OAAO;AAC/D;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAASlF,OAAOgF,OAAO;CAC7BE,OAAOC,UAAUH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B,CAAC,CAACoJ,IACrC"}
@@ -16,6 +16,17 @@ declare const sendFields: (messages: readonly {
16
16
  message: StatewireThread.UserMessage;
17
17
  runAnchorMessageId?: string | null;
18
18
  };
19
+ /** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */
20
+ declare const retryCommand: (messages: readonly {
21
+ id: string;
22
+ status?: {
23
+ type: string;
24
+ };
25
+ }[], runId: string | null, command: (StatewireThread.RunEnqueueCommand & {
26
+ message: StatewireThread.UserMessage;
27
+ }) | (StatewireThread.RunSteerCommand & {
28
+ message: StatewireThread.UserMessage;
29
+ }) | StatewireThread.RunEditCommand) => StatewireThread.RunCommand;
19
30
  declare const createRunQueueAdapter: (messages: readonly {
20
31
  id: string;
21
32
  }[], runId: string | null, queueItems: readonly StatewireThread.RunQueueItem[], steerQueueItems: readonly StatewireThread.RunQueueItem[], dispatch: (command: StatewireThread.RunCommand) => void, dispatchSend: (command: StatewireThread.RunCommand, message: AppendMessage) => void) => ExternalThreadQueueAdapter;
@@ -31,5 +42,5 @@ declare const resolveReloadCommand: (messages: readonly {
31
42
  role: string;
32
43
  }[], parentId: string | null, runId: string | null) => StatewireThread.RunReloadCommand;
33
44
  //#endregion
34
- export { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage };
45
+ export { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, retryCommand, sendFields, toWireMessage };
35
46
  //# sourceMappingURL=runCommands.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;cAyEN,qBACX;EAAqB;KACrB,SAAS,eACT,yBACC,gBAAgB;;cAkBN,aACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,SAAS,gBAAgB;EAEzB;EACA,SAAS,gBAAgB;EACzB;;cAUW,wBACX;EAAqB;KACrB,sBACA,qBAAqB,gBAAgB,gBACrC,0BAA0B,gBAAgB,gBAC1C,WAAW,SAAS,gBAAgB,qBACpC,eACE,SAAS,gBAAgB,YACzB,SAAS,2BAEV;;cA8EU,6BACX;EACE;EACA;IAAY,QAAQ;;KAEtB,WAAW,SAAS,gBAAgB,iCACnC;cAiBU,uBACX;EAAqB;EAAY;KACjC,yBACA,yBACC,gBAAgB"}
1
+ {"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;cAyEN,qBACX;EAAqB;KACrB,SAAS,eACT,yBACC,gBAAgB;;cAkBN,aACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,SAAS,gBAAgB;EAEzB;EACA,SAAS,gBAAgB;EACzB;;;cAWW,eACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,UACK,gBAAgB;EACf,SAAS,gBAAgB;MAE1B,gBAAgB;EACf,SAAS,gBAAgB;KAE3B,gBAAgB,mBACnB,gBAAgB;cAoBN,wBACX;EAAqB;KACrB,sBACA,qBAAqB,gBAAgB,gBACrC,0BAA0B,gBAAgB,gBAC1C,WAAW,SAAS,gBAAgB,qBACpC,eACE,SAAS,gBAAgB,YACzB,SAAS,2BAEV;;cA8EU,6BACX;EACE;EACA;IAAY,QAAQ;;KAEtB,WAAW,SAAS,gBAAgB,iCACnC;cAiBU,uBACX;EAAqB;EAAY;KACjC,yBACA,yBACC,gBAAgB"}
@@ -67,6 +67,23 @@ const sendFields = (messages, runId, message) => runId !== null ? {
67
67
  message,
68
68
  runAnchorMessageId: viewedLeafId(messages)
69
69
  };
70
+ /** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */
71
+ const retryCommand = (messages, runId, command) => {
72
+ if (command.type === "run/edit") {
73
+ const index = messages.findIndex((m) => m.id === command.sourceId);
74
+ if (index === -1) throw new Error(`statewire: run/edit source "${command.sourceId}" is unknown`);
75
+ return {
76
+ ...command,
77
+ runId: runId ?? crypto.randomUUID(),
78
+ runAnchorMessageId: messages[index - 1]?.id ?? null
79
+ };
80
+ }
81
+ if (runId !== null && command.runId === runId) return command;
82
+ return {
83
+ type: "run/enqueue",
84
+ ...sendFields(messages, runId, command.message)
85
+ };
86
+ };
70
87
  const createRunQueueAdapter = (messages, runId, queueItems, steerQueueItems, dispatch, dispatchSend) => {
71
88
  const liveRunId = () => {
72
89
  if (runId === null) throw new Error("statewire: no live run to target");
@@ -166,6 +183,6 @@ const resolveReloadCommand = (messages, parentId, runId) => {
166
183
  };
167
184
  };
168
185
  //#endregion
169
- export { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, sendFields, toWireMessage };
186
+ export { createBranchCommandAdapter, createRunQueueAdapter, resolveEditCommand, resolveReloadCommand, retryCommand, sendFields, toWireMessage };
170
187
 
171
188
  //# sourceMappingURL=runCommands.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","RunCommand","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG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;CAAS;AACxB;;AAGA,MAAaO,8BACXlD,UAIAiB,cACiC;CACjCmC,cAAcnB,cAAc;EAC1B,MAAMS,SAASL,SAASrC,SAASqD,MAAM5C,MAAMA,EAAE/C,OAAOuE,SAAS,CAAC;EAChE,IAAIS,WAAW1D,KAAAA,GAAW,OAAO,CAAA;EAEjC,OAAO0D,OAAOC,SAASjD,KAAK4D,YAC1BA,YAAYZ,OAAOhF,KAAKuE,YAAYsB,OAAOD,OAAO,CACpD;CACF;CACAE,iBAAiBC,aAAa;EAC5B,MAAMC,SAASd,OAAOa,QAAQ;EAC9B,IAAI,CAACb,OAAOC,UAAUa,MAAM,GAC1B,MAAM,IAAI7F,MAAM,8BAA8B4F,SAAQ,EAAG;EAC3DxC,SAAS;GAAE1C,MAAM;GAAyBkF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX3D,UACA4D,UACAxD,UACqC;CACrC,MAAMG,QACJqD,aAAa,OACT,IACA5D,SAASQ,WAAW/C,YAAYA,QAAQC,OAAOkG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQrD,UAAU,GACjC,MAAM,IAAI1C,MAAM,iCAAiC+F,SAAQ,aAAc;CACzE,MAAMF,SAAS1D,SAASO;CACxB,IAAImD,WAAW1E,KAAAA,KAAa0E,OAAO9F,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACN6B,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUoD,OAAOhG;EACjBkD,oBAAoBgD;CACtB;AACF"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiE,CACrE,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,MAA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
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  "@assistant-ui/store": "^0.3.0",
38
38
  "@assistant-ui/tap": "^0.9.7",
39
39
  "assistant-stream": "^0.3.37",
40
- "statewire": "^0.11.0"
40
+ "statewire": "^0.13.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@assistant-ui/core": ">=0.3.12",
@@ -0,0 +1,279 @@
1
+ // @vitest-environment jsdom
2
+
3
+ // Contract tests for StatewireThread's failed lane at its public seam: run
4
+ // sends that settle non-accepted project into the runs read as failed
5
+ // entries, with retry/discard/pop on the thread extras.
6
+
7
+ import { act, render, waitFor } from "@testing-library/react";
8
+ import type { FC } from "react";
9
+ import { describe, expect, it } from "vitest";
10
+ import { AuiProvider, useAui } from "@assistant-ui/store";
11
+ import { StatewireSSE } from "statewire";
12
+ import { asStatewireExtras, StatewireThread } from "./StatewireThread";
13
+ import { useStatewireRuns } from "./hooks";
14
+ import { sendCommand, toThreadMessage } from "./__tests__/testHelpers";
15
+
16
+ type ServerState = {
17
+ messages: { id: string; role: "user" | "assistant"; text: string }[];
18
+ status: "ready";
19
+ runs: never[];
20
+ };
21
+
22
+ const INITIAL_STATE: ServerState = { messages: [], status: "ready", runs: [] };
23
+
24
+ const converter: StatewireThread.StateConverter<ServerState> = (state) => ({
25
+ messages: state.messages.map(toThreadMessage),
26
+ });
27
+
28
+ const wireMessage = (
29
+ id: string,
30
+ text: string,
31
+ ): StatewireThread.UserMessage => ({
32
+ id,
33
+ role: "user",
34
+ parts: [{ type: "text", text }],
35
+ });
36
+
37
+ const extras = (aui: () => ReturnType<typeof useAui>) =>
38
+ asStatewireExtras(aui().thread().getState().extras);
39
+
40
+ // A remote SSE fake that settles every admitted command with a verdict on the
41
+ // stream: rejected by default, accepted after `accept()`. `sendOps` pushes
42
+ // canonical state, for the covered contract.
43
+ const createSettlingServer = (init?: Partial<ServerState>) => {
44
+ const received: { method: string; params: unknown[]; seq: number }[] = [];
45
+ const clients = new Map<string, { seq: number; ctxSeq: number }>();
46
+ const encoder = new TextEncoder();
47
+ const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
48
+ let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
49
+ let verdict = (): Record<string, unknown> => ({
50
+ type: "rejected",
51
+ message: "nope",
52
+ });
53
+ const push = (chunk: unknown) =>
54
+ stream!.enqueue(encoder.encode(frame(chunk)));
55
+ type Frame = {
56
+ ctx?: { seq: number }[];
57
+ cmd?: { method: string; params: unknown[]; seq: number }[];
58
+ };
59
+ const admit = (clientId: string, body: Frame) => {
60
+ const rec = clients.get(clientId)!;
61
+ for (const statement of body.ctx ?? []) {
62
+ rec.ctxSeq = Math.max(rec.ctxSeq, statement.seq);
63
+ }
64
+ for (const statement of body.cmd ?? []) {
65
+ rec.seq = Math.max(rec.seq, statement.seq);
66
+ received.push({
67
+ method: statement.method,
68
+ params: statement.params,
69
+ seq: statement.seq,
70
+ });
71
+ push({ cmd: [{ seq: statement.seq, dur: true }] });
72
+ push({ cmd: [{ seq: statement.seq, ...verdict() }] });
73
+ }
74
+ };
75
+ const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
76
+ const url = String(input);
77
+ const headers = new Headers(init2?.headers);
78
+ const clientId = headers.get("Statewire-Client-Id")!;
79
+ if (url.endsWith("/stream")) {
80
+ if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
81
+ const rec = clients.get(clientId)!;
82
+ const attachFrame = JSON.parse(String(init2?.body)) as Frame;
83
+ const body = new ReadableStream<Uint8Array>({
84
+ start: (c) => {
85
+ stream = c;
86
+ c.enqueue(
87
+ encoder.encode(
88
+ frame({
89
+ ops: [
90
+ {
91
+ op: "replace",
92
+ path: [],
93
+ value: { ...INITIAL_STATE, ...init },
94
+ },
95
+ ],
96
+ syn: { seq: rec.seq, ctxSeq: rec.ctxSeq },
97
+ }),
98
+ ),
99
+ );
100
+ admit(clientId, attachFrame);
101
+ },
102
+ });
103
+ return new Response(body, {
104
+ status: 200,
105
+ headers: {
106
+ "content-type": "text/event-stream",
107
+ "Statewire-Lease": "lease-1",
108
+ },
109
+ });
110
+ }
111
+ admit(clientId, JSON.parse(String(init2?.body)) as Frame);
112
+ return Response.json({});
113
+ }) as typeof fetch;
114
+ return {
115
+ received,
116
+ accept: () => {
117
+ verdict = () => ({ type: "result" });
118
+ },
119
+ sendOps: (ops: unknown[]) => push({ ops }),
120
+ transport: StatewireSSE<ServerState>({
121
+ url: "http://fake/api",
122
+ fetch: fetchImpl,
123
+ }),
124
+ };
125
+ };
126
+
127
+ const mountThread = (
128
+ options: Omit<
129
+ StatewireThread.Options<ServerState>,
130
+ "initialState" | "converter"
131
+ >,
132
+ ) => {
133
+ const captured: {
134
+ aui?: ReturnType<typeof useAui>;
135
+ runs?: StatewireThread.Runs;
136
+ } = {};
137
+ const Capture: FC = () => {
138
+ captured.aui = useAui();
139
+ captured.runs = useStatewireRuns();
140
+ return null;
141
+ };
142
+ const App: FC = () => {
143
+ const aui = useAui({
144
+ thread: StatewireThread<ServerState>({
145
+ initialState: INITIAL_STATE,
146
+ converter,
147
+ ...options,
148
+ }),
149
+ });
150
+ return (
151
+ <AuiProvider value={aui}>
152
+ <Capture />
153
+ </AuiProvider>
154
+ );
155
+ };
156
+ render(<App />);
157
+ return { aui: () => captured.aui!, runs: () => captured.runs! };
158
+ };
159
+
160
+ const mountFailed = async (
161
+ command: StatewireThread.RunCommand,
162
+ init?: Partial<ServerState>,
163
+ ) => {
164
+ const server = createSettlingServer(init);
165
+ const mounted = mountThread({ transport: server.transport });
166
+ await waitFor(() => expect(extras(mounted.aui).status).toBe("ready"));
167
+ act(() => {
168
+ sendCommand(mounted.aui, command);
169
+ });
170
+ await waitFor(() => expect(mounted.runs().failed).toHaveLength(1));
171
+ return { server, ...mounted };
172
+ };
173
+
174
+ describe("StatewireThread failed lane", () => {
175
+ it("projects a rejected enqueue as a failed entry", async () => {
176
+ const { runs } = await mountFailed({
177
+ type: "run/enqueue",
178
+ runId: "run-1",
179
+ message: wireMessage("m1", "hello"),
180
+ runAnchorMessageId: null,
181
+ });
182
+ expect(runs().failed[0]).toMatchObject({
183
+ id: "m1",
184
+ role: "user",
185
+ parts: [{ type: "text", text: "hello" }],
186
+ sendFailure: { fate: "rejected", cause: "server", message: "nope" },
187
+ });
188
+ expect(runs().runId).toBeNull();
189
+ });
190
+
191
+ it("retry re-dispatches the send and removes the entry", async () => {
192
+ const { server, aui, runs } = await mountFailed({
193
+ type: "run/enqueue",
194
+ runId: "run-1",
195
+ message: wireMessage("m1", "hello"),
196
+ runAnchorMessageId: null,
197
+ });
198
+ server.accept();
199
+ act(() => {
200
+ extras(aui).retryFailed("m1");
201
+ });
202
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
203
+ const sends = server.received.filter((r) => r.method === "run/enqueue");
204
+ expect(sends).toHaveLength(2);
205
+ expect(sends[1]!.params[0]).toMatchObject({
206
+ message: { id: "m1" },
207
+ runAnchorMessageId: null,
208
+ });
209
+ expect((sends[1]!.params[0] as { runId: string }).runId).not.toBe("run-1");
210
+ });
211
+
212
+ it("a failed steer whose run is gone retries as a plain enqueue", async () => {
213
+ const { server, aui, runs } = await mountFailed({
214
+ type: "run/steer",
215
+ runId: "run-9",
216
+ message: wireMessage("s1", "now"),
217
+ runAnchorMessageId: null,
218
+ });
219
+ server.accept();
220
+ act(() => {
221
+ extras(aui).retryFailed("s1");
222
+ });
223
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
224
+ expect(server.received.at(-1)).toMatchObject({
225
+ method: "run/enqueue",
226
+ params: [{ message: { id: "s1" } }],
227
+ });
228
+ });
229
+
230
+ it("discard removes the entry and refuses an unknown one", async () => {
231
+ const { aui, runs } = await mountFailed({
232
+ type: "run/enqueue",
233
+ runId: "run-1",
234
+ message: wireMessage("m1", "hello"),
235
+ runAnchorMessageId: null,
236
+ });
237
+ act(() => {
238
+ extras(aui).discardFailed("m1");
239
+ });
240
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
241
+ expect(() => extras(aui).discardFailed("m1")).toThrow(
242
+ /unknown failed entry/,
243
+ );
244
+ });
245
+
246
+ it("pop returns the entry's text and removes it", async () => {
247
+ const { aui, runs } = await mountFailed({
248
+ type: "run/enqueue",
249
+ runId: "run-1",
250
+ message: wireMessage("m1", "hello"),
251
+ runAnchorMessageId: null,
252
+ });
253
+ let text = "";
254
+ act(() => {
255
+ text = extras(aui).popFailed("m1");
256
+ });
257
+ expect(text).toBe("hello");
258
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
259
+ });
260
+
261
+ it("drops the entry once the canonical state carries its message", async () => {
262
+ const { server, runs } = await mountFailed({
263
+ type: "run/enqueue",
264
+ runId: "run-1",
265
+ message: wireMessage("m1", "hello"),
266
+ runAnchorMessageId: null,
267
+ });
268
+ act(() => {
269
+ server.sendOps([
270
+ {
271
+ op: "replace",
272
+ path: ["messages"],
273
+ value: [{ id: "m1", role: "user", text: "hello" }],
274
+ },
275
+ ]);
276
+ });
277
+ await waitFor(() => expect(runs().failed).toHaveLength(0));
278
+ });
279
+ });
@@ -563,7 +563,7 @@ describe("StatewireThread", () => {
563
563
  });
564
564
 
565
565
  await waitFor(() => expect(statuses).toEqual(["live"]));
566
- await mock.finish("superseded");
566
+ await mock.finish("gone");
567
567
  await waitFor(() => expect(statuses).toEqual(["live", "gone"]));
568
568
  await new Promise((r) => setTimeout(r, 20));
569
569
  expect(statuses).toEqual(["live", "gone"]);
@@ -1293,7 +1293,7 @@ describe("StatewireThread", () => {
1293
1293
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1294
1294
  expect(seen).toEqual(["connecting", "live"]);
1295
1295
 
1296
- await mock.finish("superseded", "taken over");
1296
+ await mock.finish("gone", "taken over");
1297
1297
  await waitFor(() => expect(seen.at(-1)).toBe("gone"));
1298
1298
  });
1299
1299
 
@@ -1317,7 +1317,7 @@ describe("StatewireThread", () => {
1317
1317
  });
1318
1318
 
1319
1319
  await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
1320
- await mock.finish("superseded");
1320
+ await mock.finish("gone");
1321
1321
  await waitFor(() => expect(seen.at(-1)).toBe("gone"));
1322
1322
 
1323
1323
  asStatewireExtras(aui().thread().getState().extras).reconnect();
@@ -33,6 +33,7 @@ import {
33
33
  createBranchCommandAdapter,
34
34
  createRunQueueAdapter,
35
35
  resolveEditCommand,
36
+ retryCommand,
36
37
  resolveReloadCommand,
37
38
  sendFields,
38
39
  toWireMessage,
@@ -66,6 +67,30 @@ const RESTING_RUNS: StatewireThread.Runs = {
66
67
  runId: null,
67
68
  queue: [],
68
69
  steerQueue: [],
70
+ failed: [],
71
+ };
72
+
73
+ /** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */
74
+ const failedRunCommand = (
75
+ entry: StatewireClient.FailedCommand,
76
+ ):
77
+ | ((
78
+ | StatewireThread.RunEnqueueCommand
79
+ | StatewireThread.RunSteerCommand
80
+ | StatewireThread.RunEditCommand
81
+ ) & { message: StatewireThread.UserMessage })
82
+ | undefined => {
83
+ if (
84
+ entry.command !== "run/enqueue" &&
85
+ entry.command !== "run/steer" &&
86
+ entry.command !== "run/edit"
87
+ )
88
+ return undefined;
89
+ const command = entry.params[0] as
90
+ | { message?: StatewireThread.UserMessage }
91
+ | undefined;
92
+ if (command?.message === undefined) return undefined;
93
+ return command as ReturnType<typeof failedRunCommand>;
69
94
  };
70
95
 
71
96
  // Derived presentation while the connection can't vouch for progress:
@@ -111,10 +136,15 @@ const useStatewireThread = (
111
136
  ),
112
137
  );
113
138
 
114
- const { state, commands, connection, setContext, isBusy } = useStatewire<
115
- unknown,
116
- AnyCommands
117
- >({
139
+ const {
140
+ state,
141
+ commands,
142
+ connection,
143
+ setContext,
144
+ isBusy,
145
+ failed,
146
+ discardFailed,
147
+ } = useStatewire<unknown, AnyCommands>({
118
148
  transport: options.transport,
119
149
  storage: options.storage,
120
150
  initialState: options.initialState,
@@ -131,8 +161,22 @@ const useStatewireThread = (
131
161
  onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
132
162
  onConnectionChange: (connection) =>
133
163
  latest.current.onConnectionChange?.(connection),
164
+ failureCovered: (state, entry) => {
165
+ const command = failedRunCommand(entry);
166
+ if (command === undefined) return false;
167
+ const messages = (state as { messages?: readonly { id: string }[] })
168
+ .messages;
169
+ return messages?.some((m) => m.id === command.message.id) ?? false;
170
+ },
134
171
  });
135
172
 
173
+ // Failures the thread cannot project stay onError-only, as before the lane.
174
+ useEffect(() => {
175
+ for (const entry of failed) {
176
+ if (failedRunCommand(entry) === undefined) discardFailed(entry);
177
+ }
178
+ }, [failed, discardFailed]);
179
+
136
180
  const clientRef = useAssistantClientRef();
137
181
  const setContextRef = useRef(setContext);
138
182
  setContextRef.current = setContext;
@@ -197,33 +241,48 @@ const useStatewireThread = (
197
241
  state as { runs?: readonly StatewireThread.RunState[] } | undefined
198
242
  )?.runs;
199
243
  const entry = entries?.[0];
244
+ const failedEntries = failed.flatMap(
245
+ (failure): StatewireThread.RunsFailedEntry[] => {
246
+ const command = failedRunCommand(failure);
247
+ return command === undefined
248
+ ? []
249
+ : [{ ...command.message, sendFailure: failure.failure }];
250
+ },
251
+ );
200
252
  return {
201
253
  status: presentStatus(
202
254
  entries === undefined ? "loading" : (entry?.status ?? "ready"),
203
255
  connection,
204
256
  ),
205
257
  runs:
206
- entry === undefined
258
+ entry === undefined && failedEntries.length === 0
207
259
  ? RESTING_RUNS
208
260
  : {
209
- runId: entry.runId,
210
- ...(entry.epoch !== undefined && { epoch: entry.epoch }),
211
- queue: entry.queue,
212
- steerQueue: entry.steerQueue,
213
- ...(entry.dispatching !== undefined && {
214
- dispatching: entry.dispatching,
215
- }),
216
- ...(entry.stopping !== undefined && { stopping: entry.stopping }),
217
- ...(entry.nextDispatch !== undefined && {
218
- nextDispatch: entry.nextDispatch,
219
- }),
220
- ...(entry.inputRequests !== undefined && {
221
- inputRequests: entry.inputRequests,
222
- }),
223
- ...(entry.error !== undefined && { error: entry.error }),
261
+ ...(entry === undefined
262
+ ? RESTING_RUNS
263
+ : {
264
+ runId: entry.runId,
265
+ ...(entry.epoch !== undefined && { epoch: entry.epoch }),
266
+ queue: entry.queue,
267
+ steerQueue: entry.steerQueue,
268
+ ...(entry.dispatching !== undefined && {
269
+ dispatching: entry.dispatching,
270
+ }),
271
+ ...(entry.stopping !== undefined && {
272
+ stopping: entry.stopping,
273
+ }),
274
+ ...(entry.nextDispatch !== undefined && {
275
+ nextDispatch: entry.nextDispatch,
276
+ }),
277
+ ...(entry.inputRequests !== undefined && {
278
+ inputRequests: entry.inputRequests,
279
+ }),
280
+ ...(entry.error !== undefined && { error: entry.error }),
281
+ }),
282
+ failed: failedEntries,
224
283
  },
225
284
  };
226
- }, [state, connection]);
285
+ }, [state, connection, failed]);
227
286
 
228
287
  const { converter } = options;
229
288
  const metadata = useMemo(
@@ -264,8 +323,16 @@ const useStatewireThread = (
264
323
 
265
324
  const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
266
325
 
267
- const extras = useMemo(
268
- (): StatewireThread.Extras => ({
326
+ const extras = useMemo((): StatewireThread.Extras => {
327
+ const takeFailed = (messageId: string): StatewireClient.FailedCommand => {
328
+ const entry = failed.find(
329
+ (f) => failedRunCommand(f)?.message.id === messageId,
330
+ );
331
+ if (entry === undefined)
332
+ throw new Error(`statewire: unknown failed entry "${messageId}"`);
333
+ return entry;
334
+ };
335
+ return {
269
336
  [symbolStatewireExtras]: true,
270
337
  sendCommand: dispatch,
271
338
  reconnect: connection.reconnect,
@@ -274,17 +341,38 @@ const useStatewireThread = (
274
341
  isBusy,
275
342
  inputRequests,
276
343
  runs,
277
- }),
278
- [
279
- dispatch,
280
- connection.reconnect,
281
- state,
282
- status,
283
- isBusy,
284
- inputRequests,
285
- runs,
286
- ],
287
- );
344
+ retryFailed: (messageId) => {
345
+ const entry = takeFailed(messageId);
346
+ const command = retryCommand(
347
+ messages,
348
+ liveRunId,
349
+ failedRunCommand(entry)!,
350
+ );
351
+ discardFailed(entry);
352
+ void dispatch(command);
353
+ },
354
+ discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
355
+ popFailed: (messageId) => {
356
+ const entry = takeFailed(messageId);
357
+ discardFailed(entry);
358
+ return failedRunCommand(entry)!
359
+ .message.parts.flatMap((p) => (p.type === "text" ? [p.text] : []))
360
+ .join("\n\n");
361
+ },
362
+ };
363
+ }, [
364
+ dispatch,
365
+ connection.reconnect,
366
+ state,
367
+ status,
368
+ isBusy,
369
+ inputRequests,
370
+ runs,
371
+ failed,
372
+ discardFailed,
373
+ messages,
374
+ liveRunId,
375
+ ]);
288
376
 
289
377
  const handleAppend = (message: AppendMessage) => {
290
378
  dispatchSend(
@@ -452,6 +540,12 @@ export namespace StatewireThread {
452
540
  isBusy: boolean;
453
541
  inputRequests: readonly InputRequestState[];
454
542
  runs: Runs;
543
+ /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
544
+ retryFailed: (messageId: string) => void;
545
+ /** Removes the failed entry; keyed by the entry's message id. */
546
+ discardFailed: (messageId: string) => void;
547
+ /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
548
+ popFailed: (messageId: string) => string;
455
549
  };
456
550
 
457
551
  export type TextPart = {
@@ -612,6 +706,11 @@ export namespace StatewireThread {
612
706
  readonly meta?: ReadonlyJSONValue;
613
707
  };
614
708
 
709
+ /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
710
+ export type RunsFailedEntry = RunsQueueEntry & {
711
+ readonly sendFailure: StatewireClient.SendFailure;
712
+ };
713
+
615
714
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
616
715
  export type RunsInputOutcome = {
617
716
  readonly request: InputRequest;
@@ -702,6 +801,8 @@ export namespace StatewireThread {
702
801
  readonly inputRequests?: readonly InputRequestState[];
703
802
  /** Set only by an unhandled throw; cleared by the next user-initiated run. */
704
803
  readonly error?: RunsError;
804
+ /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
805
+ readonly failed: readonly RunsFailedEntry[];
705
806
  };
706
807
 
707
808
  export type ConnectionMetadata = {
@@ -121,6 +121,38 @@ export const sendFields = (
121
121
  runAnchorMessageId: viewedLeafId(messages),
122
122
  };
123
123
 
124
+ /** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */
125
+ export const retryCommand = (
126
+ messages: readonly { id: string; status?: { type: string } }[],
127
+ runId: string | null,
128
+ command:
129
+ | (StatewireThread.RunEnqueueCommand & {
130
+ message: StatewireThread.UserMessage;
131
+ })
132
+ | (StatewireThread.RunSteerCommand & {
133
+ message: StatewireThread.UserMessage;
134
+ })
135
+ | StatewireThread.RunEditCommand,
136
+ ): StatewireThread.RunCommand => {
137
+ if (command.type === "run/edit") {
138
+ const index = messages.findIndex((m) => m.id === command.sourceId);
139
+ if (index === -1)
140
+ throw new Error(
141
+ `statewire: run/edit source "${command.sourceId}" is unknown`,
142
+ );
143
+ return {
144
+ ...command,
145
+ runId: runId ?? crypto.randomUUID(),
146
+ runAnchorMessageId: messages[index - 1]?.id ?? null,
147
+ };
148
+ }
149
+ if (runId !== null && command.runId === runId) return command;
150
+ return {
151
+ type: "run/enqueue",
152
+ ...sendFields(messages, runId, command.message),
153
+ };
154
+ };
155
+
124
156
  export const createRunQueueAdapter = (
125
157
  messages: readonly { id: string }[],
126
158
  runId: string | null,