@assistant-ui/react-statewire 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { AddMessageCommand, AssistantTransportCommand, AssistantTransportOptions } from "./types.js";
1
+ import { AssistantTransportCommand, AssistantTransportOptions, MessageAddCommand } from "./types.js";
2
2
  import { ResourceElement } from "@assistant-ui/tap";
3
3
  import { ClientOutput } from "@assistant-ui/store";
4
4
  import { AppendMessage } from "@assistant-ui/core";
@@ -7,10 +7,11 @@ declare const symbolAssistantTransportExtras: unique symbol;
7
7
  type AssistantTransportExtras = {
8
8
  [symbolAssistantTransportExtras]: true;
9
9
  sendCommand: (command: AssistantTransportCommand) => void;
10
+ reconnect: () => void;
10
11
  state: unknown;
11
12
  };
12
13
  declare const asAssistantTransportExtras: (extras: unknown) => AssistantTransportExtras;
13
- declare const convertAppendMessageToCommand: (message: AppendMessage) => AddMessageCommand | null;
14
+ declare const convertAppendMessageToCommand: (message: AppendMessage) => MessageAddCommand | null;
14
15
  declare const AssistantTransportThread: <T>(options: AssistantTransportOptions<T>) => ResourceElement<ClientOutput<"thread">>;
15
16
  //#endregion
16
17
  export { AssistantTransportExtras, AssistantTransportThread, asAssistantTransportExtras, convertAppendMessageToCommand, symbolAssistantTransportExtras };
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;cAsCa;KAID;GACT;EACD,cAAc,SAAS;EACvB;;cAGW,6BACX,oBACC;cAaU,gCACX,SAAS,kBACR;cA2NU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
1
+ {"version":3,"file":"AssistantTransportThread.d.ts","names":[],"sources":["../src/AssistantTransportThread.ts"],"mappings":";;;;;cAkDa;KAID;GACT;EACD,cAAc,SAAS;EACvB;EACA;;cAGW,6BACX,oBACC;cAaU,gCACX,SAAS,kBACR;cA+RU,2BAA4B,GACvC,SAAS,0BAA0B,OAClC,gBAAgB"}
@@ -1,12 +1,15 @@
1
1
  import { AssistantTransportHost } from "./host.js";
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
2
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "@assistant-ui/tap/react-shim";
3
3
  import { resource, useResource } from "@assistant-ui/tap";
4
4
  import { ExternalThread } from "@assistant-ui/react";
5
5
  import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
6
+ import { createMessageQueue } from "@assistant-ui/core";
6
7
  import { ToolInvocationTracker } from "@assistant-ui/core/internal";
7
8
  import { useStatewire } from "statewire";
8
9
  //#region src/AssistantTransportThread.ts
9
10
  const EMPTY_TOOL_STATUSES = {};
11
+ const EMPTY_QUEUE_ITEMS = [];
12
+ const subscribeNoop = () => () => {};
10
13
  const symbolAssistantTransportExtras = Symbol("assistant-transport-extras");
11
14
  const asAssistantTransportExtras = (extras) => {
12
15
  if (typeof extras !== "object" || extras == null || !(symbolAssistantTransportExtras in extras)) throw new Error("This method can only be called when you are using AssistantTransportThread or StatewireThread");
@@ -26,7 +29,7 @@ const convertAppendMessageToCommand = (message) => {
26
29
  });
27
30
  if (parts.length === 0) return null;
28
31
  return {
29
- type: "add-message",
32
+ type: "message/add",
30
33
  message: {
31
34
  role: "user",
32
35
  parts
@@ -53,7 +56,7 @@ const useAssistantTransportThread = (options) => {
53
56
  queued: [],
54
57
  inTransit: []
55
58
  } }));
56
- const { state, commands } = useStatewire({ transport: AssistantTransportHost({
59
+ const { state, commands, connection } = useStatewire({ transport: AssistantTransportHost({
57
60
  ...options,
58
61
  getRunContext,
59
62
  queueCell
@@ -84,7 +87,10 @@ const useAssistantTransportThread = (options) => {
84
87
  onResult: (command_0) => {
85
88
  const messages = convertedRef.current.messages;
86
89
  if (!messagesContainToolCall(messages, command_0.toolCallId)) return;
87
- dispatch(command_0);
90
+ dispatch({
91
+ ...command_0,
92
+ type: "tool-result/add"
93
+ });
88
94
  },
89
95
  onStatusesChange: (statuses) => {
90
96
  setToolStatuses(statuses.size === 0 ? EMPTY_TOOL_STATUSES : Object.fromEntries(statuses));
@@ -103,8 +109,13 @@ const useAssistantTransportThread = (options) => {
103
109
  const extras = useMemo(() => ({
104
110
  [symbolAssistantTransportExtras]: true,
105
111
  sendCommand: dispatch,
112
+ reconnect: connection.reconnect,
106
113
  state: agentState
107
- }), [dispatch, agentState]);
114
+ }), [
115
+ dispatch,
116
+ connection.reconnect,
117
+ agentState
118
+ ]);
108
119
  const handleAppend = (message) => {
109
120
  const startRun = message.startRun ?? message.role === "user";
110
121
  const command_1 = convertAppendMessageToCommand(message);
@@ -116,6 +127,39 @@ const useAssistantTransportThread = (options) => {
116
127
  if (startRun) toolInvocations.abort().then(send);
117
128
  else send();
118
129
  };
130
+ const handleCancel = () => {
131
+ toolInvocations.abort();
132
+ commands.cancel().catch(() => {});
133
+ };
134
+ const driverRef = useRef(void 0);
135
+ driverRef.current = {
136
+ run: (message_0) => handleAppend({
137
+ ...message_0,
138
+ parentId: convertedRef.current.messages.at(-1)?.id ?? null
139
+ }),
140
+ cancel: handleCancel
141
+ };
142
+ const enableQueue = options.capabilities?.queue === true;
143
+ const queueRef = useRef(null);
144
+ if (enableQueue && !queueRef.current) queueRef.current = createMessageQueue({
145
+ run: (message_1, opts_0) => driverRef.current.run(message_1, opts_0),
146
+ cancel: () => driverRef.current.cancel()
147
+ });
148
+ else if (!enableQueue && queueRef.current) {
149
+ queueRef.current.clear();
150
+ queueRef.current = null;
151
+ }
152
+ const messageQueue = queueRef.current;
153
+ const queueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
154
+ const steerQueueItems = useSyncExternalStore(messageQueue?.subscribe ?? subscribeNoop, () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS, () => EMPTY_QUEUE_ITEMS);
155
+ const busy = isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
156
+ const wasBusyRef = useRef(false);
157
+ useEffect(() => {
158
+ if (wasBusyRef.current === busy) return;
159
+ wasBusyRef.current = busy;
160
+ if (busy) messageQueue?.notifyBusy();
161
+ else messageQueue?.notifyIdle();
162
+ });
119
163
  return useResource(ExternalThread({
120
164
  messages: converted.messages,
121
165
  isRunning: converted.isRunning,
@@ -124,6 +168,11 @@ const useAssistantTransportThread = (options) => {
124
168
  extras,
125
169
  attachmentAdapter: options.adapters?.attachments,
126
170
  onNew: handleAppend,
171
+ ...messageQueue && { queue: {
172
+ ...messageQueue.adapter,
173
+ items: queueItems,
174
+ steerItems: steerQueueItems
175
+ } },
127
176
  ...options.capabilities?.edit && { onEdit: handleAppend },
128
177
  onReload: (parentId) => {
129
178
  toolInvocations.abort().then(() => {
@@ -131,8 +180,8 @@ const useAssistantTransportThread = (options) => {
131
180
  });
132
181
  },
133
182
  onCancel: () => {
134
- toolInvocations.abort();
135
- commands.cancel().catch(() => {});
183
+ messageQueue?.clear();
184
+ handleCancel();
136
185
  },
137
186
  onResume: () => {
138
187
  if (!options.resumeApi) throw new Error("Must pass resumeApi to options to resume runs");
@@ -140,7 +189,7 @@ const useAssistantTransportThread = (options) => {
140
189
  },
141
190
  onAddToolResult: (toolOptions) => {
142
191
  const command_2 = {
143
- type: "add-tool-result",
192
+ type: "tool-result/add",
144
193
  toolCallId: toolOptions.toolCallId,
145
194
  result: toolOptions.result,
146
195
  toolName: toolOptions.toolName,
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AddToolResultOptions","AppendMessage","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","AddMessageCommand","AddToolResultCommand","AssistantTransportCommand","AssistantTransportOptions","UserMessagePart","EMPTY_TOOL_STATUSES","Record","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","state","asAssistantTransportExtras","extras","Error","convertAppendMessageToCommand","message","role","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","messagesContainToolCall","messages","toolCallId","some","part","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","handleAppend","startRun","setParentId","schedule","abort","then","attachmentAdapter","adapters","onNew","capabilities","edit","onEdit","onReload","reload","onCancel","cancel","onResume","resumeApi","resume","onAddToolResult","toolOptions","result","toolName","isError","artifact","modelContent","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport type {\n AddMessageCommand,\n AddToolResultCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n UserMessagePart,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n state: unknown;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch(command);\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state: agentState,\n }),\n [dispatch, agentState],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command = convertAppendMessageToCommand(message);\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => {\n if (!command) return;\n dispatch(command, { schedule: startRun });\n };\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onReload: (parentId: string | null) => {\n void toolInvocations.abort().then(() => {\n void commands.reload(parentId).catch(() => {});\n });\n },\n onCancel: () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n },\n onResume: () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n dispatch(command);\n },\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AAoCA,MAAMgC,sBAA2D,CAAC;AAElE,MAAaE,iCAAiCC,OAC5C,4BACF;AAQA,MAAaK,8BACXC,WAC6B;CAC7B,IACE,OAAOA,WAAW,YAClBA,UAAU,QACV,EAAEP,kCAAkCO,SAEpC,MAAM,IAAIC,MACR,+FACF;CAEF,OAAOD;AACT;AAEA,MAAaE,iCACXC,YAC6B;CAC7B,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIH,MAAM,kCAAkC;CAEpD,MAAMI,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGH,QAAQG,SACX,GAAIH,QAAQI,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,eAAeJ,SACxB,IAAII,YAAYC,SAAS,QACvBN,MAAMO,KAAK;EAAED,MAAM;EAAQE,MAAMH,YAAYG;CAAK,CAAC;MAC9C,IAAIH,YAAYC,SAAS,SAC9BN,MAAMO,KAAK;EAAED,MAAM;EAASG,OAAOJ,YAAYI;CAAM,CAAC;CAI1D,IAAIT,MAAMU,WAAW,GAAG,OAAO;CAE/B,OAAO;EACLJ,MAAM;EACNR,SAAS;GACPC,MAAM;GACNC;EACF;EACAW,UAAUb,QAAQa;EAClBC,UAAUd,QAAQc;CACpB;AACF;AAEA,MAAMC,2BACJC,UACAC,eAEAD,SAASE,MAAMlB,YACbA,QAAQG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,MAAa6G,4BACX3E,YAEA7D,SAAS4D,2BAA2B,CAAC,CACnCC,OACF;AAGFxD,uBACEuD,6BACAzD,eAAewD,KAAAA,CAAkB,CAAC,CAAC+E,IACrC"}
1
+ {"version":3,"file":"AssistantTransportThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","useSyncExternalStore","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","createMessageQueue","AddToolResultOptions","AppendMessage","MessageQueueController","MessageQueueDriver","ResumeToolCallOptions","ThreadMessage","ToolExecutionStatus","ToolInvocationTracker","ReadonlyJSONObject","useStatewire","AssistantTransportHost","AssistantTransportHostCommands","AssistantTransportHostState","HostQueueCell","HostRunContext","SendOptions","MessageAddCommand","ToolResultAddCommand","AssistantTransportCommand","AssistantTransportOptions","UserMessagePart","EMPTY_TOOL_STATUSES","Record","EMPTY_QUEUE_ITEMS","subscribeNoop","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","reconnect","state","asAssistantTransportExtras","extras","Error","convertAppendMessageToCommand","message","role","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","length","parentId","sourceId","messagesContainToolCall","messages","toolCallId","some","part","undefined","useAssistantTransportThread","options","clientRef","getRunContext","aui","current","parent","threadId","threadListItem","getState","remoteId","modelContext","getModelContext","queueCell","queued","inTransit","commands","connection","transport","agent","agentState","isSending","isReplaying","queue","dispatch","opts","send","catch","toolStatuses","setToolStatuses","converter","converted","pendingCommands","convertedRef","toolInvocations","tools","onResult","onStatusesChange","statuses","size","Object","fromEntries","setState","isRunning","isLoading","reset","handleAppend","startRun","setParentId","schedule","abort","then","handleCancel","cancel","driverRef","run","at","id","enableQueue","capabilities","queueRef","clear","messageQueue","queueItems","subscribe","adapter","items","steerQueueItems","steerItems","busy","keys","wasBusyRef","notifyBusy","notifyIdle","attachmentAdapter","adapters","onNew","edit","onEdit","onReload","reload","onCancel","onResume","resumeApi","resume","onAddToolResult","toolOptions","result","toolName","isError","artifact","modelContent","onResumeToolCall","payload","onLoadExternalState","imported","importState","AssistantTransportThread","T","hook"],"sources":["../src/AssistantTransportThread.ts"],"sourcesContent":["import {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n AddToolResultOptions,\n AppendMessage,\n MessageQueueController,\n MessageQueueDriver,\n ResumeToolCallOptions,\n ThreadMessage,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport { ToolInvocationTracker } from \"@assistant-ui/core/internal\";\nimport type { ReadonlyJSONObject } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport { AssistantTransportHost } from \"./host\";\nimport type {\n AssistantTransportHostCommands,\n AssistantTransportHostState,\n HostQueueCell,\n HostRunContext,\n SendOptions,\n} from \"./host\";\nimport type {\n MessageAddCommand,\n ToolResultAddCommand,\n AssistantTransportCommand,\n AssistantTransportOptions,\n UserMessagePart,\n} from \"./types\";\n\nconst EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};\nconst EMPTY_QUEUE_ITEMS: MessageQueueController[\"adapter\"][\"items\"] = [];\nconst subscribeNoop = () => () => {};\n\nexport const symbolAssistantTransportExtras = Symbol(\n \"assistant-transport-extras\",\n);\n\nexport type AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n reconnect: () => void;\n state: unknown;\n};\n\nexport const asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using AssistantTransportThread or StatewireThread\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const convertAppendMessageToCommand = (\n message: AppendMessage,\n): MessageAddCommand | null => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n if (parts.length === 0) return null;\n\n return {\n type: \"message/add\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst messagesContainToolCall = (\n messages: readonly ThreadMessage[],\n toolCallId: string,\n): boolean =>\n messages.some((message) =>\n message.content.some(\n (part) =>\n part.type === \"tool-call\" &&\n (part.toolCallId === toolCallId ||\n (part.messages !== undefined &&\n messagesContainToolCall(part.messages, toolCallId))),\n ),\n );\n\nconst useAssistantTransportThread = (\n options: AssistantTransportOptions<any>,\n): ClientOutput<\"thread\"> => {\n const clientRef = useAssistantClientRef();\n const [getRunContext] = useState(() => (): HostRunContext => {\n const aui = clientRef.current ?? clientRef.parent;\n // legacy parity: a threadListItem throw must not kill the run\n let threadId: string | null = null;\n try {\n threadId = aui.threadListItem().getState().remoteId ?? null;\n } catch {}\n return {\n modelContext: aui.modelContext().getModelContext(),\n threadId,\n };\n });\n\n const [queueCell] = useState(\n (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),\n );\n const { state, commands, connection } = useStatewire<\n AssistantTransportHostState,\n AssistantTransportHostCommands\n >({\n transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),\n });\n const { agent: agentState, isSending, isReplaying } = state;\n const queue = queueCell.current;\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand, opts?: SendOptions) => {\n void commands.send(command, opts).catch(() => {});\n },\n [commands],\n );\n\n const [toolStatuses, setToolStatuses] =\n useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);\n\n const { converter } = options;\n const converted = useMemo(\n () =>\n converter(agentState, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses,\n }),\n [converter, agentState, queue, isSending, toolStatuses],\n );\n const convertedRef = useRef(converted);\n convertedRef.current = converted;\n\n const [toolInvocations] = useState(\n () =>\n new ToolInvocationTracker(\n () => {\n const aui = clientRef.current ?? clientRef.parent;\n return aui.modelContext().getModelContext().tools;\n },\n {\n onResult: (command) => {\n const messages = convertedRef.current\n .messages as readonly ThreadMessage[];\n if (!messagesContainToolCall(messages, command.toolCallId)) return;\n dispatch({ ...command, type: \"tool-result/add\" });\n },\n onStatusesChange: (statuses) => {\n setToolStatuses(\n statuses.size === 0\n ? EMPTY_TOOL_STATUSES\n : Object.fromEntries(statuses),\n );\n },\n },\n ),\n );\n // dep-less by design: setState dedups identical snapshots internally\n useEffect(() => {\n toolInvocations.setState({\n messages: converted.messages as readonly ThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n });\n });\n useEffect(\n () => () => {\n toolInvocations.reset();\n },\n [toolInvocations],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n reconnect: connection.reconnect,\n state: agentState,\n }),\n [dispatch, connection.reconnect, agentState],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const startRun = message.startRun ?? message.role === \"user\";\n const command = convertAppendMessageToCommand(message);\n void commands.setParentId(message.parentId).catch(() => {});\n\n const send = () => {\n if (!command) return;\n dispatch(command, { schedule: startRun });\n };\n if (startRun) {\n // abort in-flight tool executions so their late results cannot race the new turn\n void toolInvocations.abort().then(send);\n } else {\n send();\n }\n };\n\n const handleCancel = () => {\n void toolInvocations.abort();\n void commands.cancel().catch(() => {});\n };\n\n const driverRef = useRef<{\n run: MessageQueueDriver[\"run\"];\n cancel: () => void;\n }>(undefined as never);\n driverRef.current = {\n // the queued message was stamped with the head at enqueue time; restamp so\n // it appends to the thread the finished run left behind\n run: (message) =>\n handleAppend({\n ...message,\n parentId: convertedRef.current.messages.at(-1)?.id ?? null,\n }),\n cancel: handleCancel,\n };\n\n const enableQueue = options.capabilities?.queue === true;\n const queueRef = useRef<MessageQueueController | null>(null);\n if (enableQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message, opts) => driverRef.current.run(message, opts),\n cancel: () => driverRef.current.cancel(),\n });\n } else if (!enableQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const messageQueue = queueRef.current;\n\n // fresh view per snapshot: the controller mutates adapter.items in place,\n // which a stable prop identity would hide from the thread resource\n const queueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n messageQueue?.subscribe ?? subscribeNoop,\n () => messageQueue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // settled edge: the queue only advances once the host run loop has fully\n // released (isSending), the converted state agrees, and no client tool from\n // the finished run is still executing\n const busy =\n isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;\n const wasBusyRef = useRef(false);\n useEffect(() => {\n if (wasBusyRef.current === busy) return;\n wasBusyRef.current = busy;\n if (busy) messageQueue?.notifyBusy();\n else messageQueue?.notifyIdle();\n });\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(messageQueue && {\n queue: {\n ...messageQueue.adapter,\n items: queueItems,\n steerItems: steerQueueItems,\n },\n }),\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onReload: (parentId: string | null) => {\n void toolInvocations.abort().then(() => {\n void commands.reload(parentId).catch(() => {});\n });\n },\n onCancel: () => {\n // user cancel drops pending lanes; a steer interrupt (driver.cancel) keeps them\n messageQueue?.clear();\n handleCancel();\n },\n onResume: () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n void commands.resume().catch(() => {});\n },\n onAddToolResult: (toolOptions: AddToolResultOptions) => {\n const command: ToolResultAddCommand = {\n type: \"tool-result/add\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n dispatch(command);\n },\n onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {\n if (!toolInvocations.resume(toolCallId, payload))\n throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);\n },\n onLoadExternalState: (imported: unknown) => {\n void commands.importState(imported).catch(() => {});\n // reset() aborts tools before React re-renders — gate their late results against the imported state\n convertedRef.current = options.converter(imported, {\n pendingCommands: [...queue.inTransit, ...queue.queued],\n isSending,\n toolStatuses: EMPTY_TOOL_STATUSES,\n });\n toolInvocations.reset();\n setToolStatuses(EMPTY_TOOL_STATUSES);\n },\n }),\n );\n};\n\nexport const AssistantTransportThread = <T>(\n options: AssistantTransportOptions<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useAssistantTransportThread)(\n options as AssistantTransportOptions<any>,\n );\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useAssistantTransportThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;;AA8CA,MAAMoC,sBAA2D,CAAC;AAClE,MAAME,oBAAgE,CAAA;AACtE,MAAMC,4BAA4B,CAAC;AAEnC,MA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BAAgB;GACd,IAAI,CAACjF,QAAQkF,WACX,MAAM,IAAI1G,MAAM,+CAA+C;GACjE,SAAc2G,OAAO,CAAC,CAACzD,YAAY,CAAC,CAAC;EACvC;EACA0D,kBAAkBC,gBAAsC;GACtD,MAAMlH,YAAgC;IACpCe,MAAM;IACNS,YAAY0F,YAAY1F;IACxB2F,QAAQD,YAAYC;IACpBC,UAAUF,YAAYE;IACtBC,SAASH,YAAYG;IACrB,GAAIH,YAAYI,YAAY,EAAEA,UAAUJ,YAAYI,SAAS;IAC7D,GAAIJ,YAAYK,iBAAiB5F,KAAAA,KAAa,EAC5C4F,cAAcL,YAAYK,aAC5B;GACF;GAEAnE,SAASpD,SAAO;EAClB;EACAwH,mBAAmB,EAAEhG,YAAYiG,cAAqC;GACpE,IAAI,CAAC3D,gBAAgBkD,OAAOxF,YAAYiG,OAAO,GAC7C,MAAM,IAAIpH,MAAM,aAAamB,WAAU,4BAA6B;EACxE;EACAkG,sBAAsBC,aAAsB;GAC1C,SAAcC,YAAYD,QAAQ,CAAC,CAACpE,YAAY,CAAC,CAAC;GAElDM,aAAa5B,UAAUJ,QAAQ6B,UAAUiE,UAAU;IACjD/D,iBAAiB,CAAC,GAAGT,MAAMR,WAAW,GAAGQ,MAAMT,MAAM;IACrDO;IACAO,cAAchE;GAChB,CAAC;GACDsE,gBAAgBW,MAAM;GACtBhB,gBAAgBjE,mBAAmB;EACrC;CACF,CAAC,CACH;AACF;AAEA,MAAaqI,4BACXhG,YAEAnE,SAASkE,2BAA2B,CAAC,CACnCC,OACF;AAGF9D,uBACE6D,6BACA/D,eAAe8D,KAAAA,CAAkB,CAAC,CAACoG,IACrC"}
@@ -1,23 +1,96 @@
1
1
  import { AssistantTransportCommand } from "./types.js";
2
2
  import { ResourceElement } from "@assistant-ui/tap";
3
3
  import { ClientOutput } from "@assistant-ui/store";
4
- import { Statewire } from "statewire";
5
4
  import { AttachmentAdapter, ThreadMessage } from "@assistant-ui/core";
5
+ import { Statewire, StatewireClient } from "statewire";
6
6
  import { ReadonlyJSONValue } from "assistant-stream/utils";
7
7
  //#region src/StatewireThread.d.ts
8
8
  declare const StatewireThread: <T>(options: StatewireThread.Options<T>) => ResourceElement<ClientOutput<"thread">>;
9
9
  declare namespace StatewireThread {
10
10
  type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
11
+ type TextPart = {
12
+ readonly type: "text";
13
+ readonly text: string;
14
+ };
15
+ type FilePart = {
16
+ readonly type: "file";
17
+ readonly mediaType: string;
18
+ readonly url: string;
19
+ readonly filename?: string;
20
+ };
21
+ type UserMessage = {
22
+ readonly id: string;
23
+ readonly role: "user";
24
+ readonly parts: readonly (TextPart | FilePart)[];
25
+ readonly metadata?: Record<string, unknown>;
26
+ };
27
+ /** Queue placement fields, flat on the command. Absent is load-bearing: it means default placement; `null` names a queue boundary. */
28
+ type Placement = {
29
+ readonly insertAfter?: string | null;
30
+ readonly insertBefore?: string | null;
31
+ };
32
+ type RunEnqueueCommand = {
33
+ readonly type: "run/enqueue";
34
+ } & ({
35
+ readonly message: UserMessage;
36
+ } | {
37
+ readonly messageId: string;
38
+ }) & Placement;
39
+ type RunSteerCommand = {
40
+ readonly type: "run/steer";
41
+ } & ({
42
+ readonly message: UserMessage;
43
+ } | {
44
+ readonly messageId: string;
45
+ }) & Placement;
46
+ type RunDequeueCommand = {
47
+ readonly type: "run/dequeue";
48
+ readonly messageId: string;
49
+ };
50
+ type RunEditCommand = {
51
+ readonly type: "run/edit";
52
+ readonly message: UserMessage;
53
+ readonly sourceId: string;
54
+ };
55
+ type RunContinueCommand = {
56
+ readonly type: "run/continue";
57
+ };
58
+ type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand;
59
+ type Command = AssistantTransportCommand | RunCommand;
60
+ /** A queued message projected out of the host state, wire shape. */
61
+ type QueueItem = {
62
+ readonly id: string;
63
+ readonly parts: readonly (TextPart | FilePart)[];
64
+ };
11
65
  type State = {
12
66
  readonly messages: readonly ThreadMessage[];
13
67
  readonly state?: ReadonlyJSONValue;
14
68
  readonly isRunning: boolean;
69
+ /**
70
+ * The host's regular queue lane projected out of the state. Returning it
71
+ * (even empty) turns on the queue capability: sends become `run/enqueue`
72
+ * / `run/steer` commands and item controls send the `run/*` queue
73
+ * commands. Presence must be stable across conversions.
74
+ */
75
+ readonly queue?: readonly QueueItem[];
76
+ /** The host's steer lane; requires `queue`. Absent means empty. */
77
+ readonly steerQueue?: readonly QueueItem[];
15
78
  };
16
79
  type ConnectionMetadata = {
17
- pendingCommands: AssistantTransportCommand[];
80
+ pendingCommands: Command[];
18
81
  isSending: boolean;
82
+ /** Statewire connection status; local transports are always `live`. */
83
+ connection: StatewireClient.ConnectionState;
19
84
  };
20
85
  type StateConverter<T> = (state: T, connectionMetadata: ConnectionMetadata) => State;
86
+ /**
87
+ * Payload of the built-in `run/cancel` command. `reason` is the one well-known
88
+ * field; apps extend it with their own JSON-serializable fields.
89
+ */
90
+ type CancelPayload = {
91
+ readonly reason?: string | undefined;
92
+ readonly [key: string]: ReadonlyJSONValue | undefined;
93
+ };
21
94
  type Options<T> = {
22
95
  transport: Transport<T>;
23
96
  initialState: T;
@@ -28,9 +101,20 @@ declare namespace StatewireThread {
28
101
  * on connect and whenever it changes. Requires a remote transport.
29
102
  */
30
103
  contextSync?: "command-send" | undefined;
104
+ /** Supplies the `run/cancel` command's payload; omitted, cancel sends no payload. */
105
+ cancelPayload?: (() => CancelPayload) | undefined;
106
+ /**
107
+ * Offered each pending command when a remote transport's session is
108
+ * evicted; return "replay" to re-enqueue it under the rotated client id.
109
+ * A callback set on the transport options is consulted first; this one
110
+ * runs for commands it declined.
111
+ */
112
+ onCommandSessionLost?: ((command: StatewireClient.SessionLostCommand) => "replay" | void) | undefined;
31
113
  onError?: ((error: Error) => void) | undefined;
32
114
  capabilities?: {
33
115
  edit?: boolean | undefined;
116
+ /** The host supports `run/continue` (a continue affordance on aborted runs). */
117
+ continue?: boolean | undefined;
34
118
  } | undefined;
35
119
  adapters?: {
36
120
  attachments?: AttachmentAdapter | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA+Ja,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD,mBAAmB;aACnB,QAAQ;aACR;;OAGC;IACV,iBAAiB;IACjB;;OAGU,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;OAEO,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;IACA,YAAY,OAAO;IACnB;MAEM;;IAGN;MAEM,cAAc"}
1
+ {"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cAiWa,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD;aACA;;OAGC;aACD;aACA;aACA;aACA;;OAGC;aACD;aACA;aACA,iBAAiB,WAAW;aAC5B,WAAW;;;OAIV;aACD;aACA;;OAGC;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;;aACK,SAAS;;aAA2B;OAClD;OAEU;aACD;aACA;;OAGC;aACD;aACA,SAAS;aACT;;OAGC;aACD;;OAGC,aACR,oBACA,kBACA,oBACA,iBACA;OAEQ,UAAU,4BAA4B;;OAGtC;aACD;aACA,iBAAiB,WAAW;;OAG3B;aACD,mBAAmB;aACnB,QAAQ;aACR;;;;;;;aAOA,iBAAiB;;aAEjB,sBAAsB;;OAGrB;IACV,iBAAiB;IACjB;;IAEA,YAAY,gBAAgB;;OAGlB,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;;;;;OAMO;aACD;cACC,cAAc;;OAGd,QAAQ;IAClB,WAAW,UAAU;IACrB,cAAc;IACd,WAAW,eAAe;;;;;;IAM1B;;IAEA,uBAAuB;;;;;;;IAOvB,yBACM,SAAS,gBAAgB;IAE/B,YAAY,OAAO;IACnB;MAEM;;MAEA;;IAGN;MAEM,cAAc"}
@@ -12,13 +12,68 @@ const ambientContextOf = (context) => ({
12
12
  ...context.callSettings !== void 0 && { callSettings: context.callSettings },
13
13
  ...context.config !== void 0 && { config: context.config }
14
14
  });
15
+ const toWireMessage = (message, id) => {
16
+ if (message.role !== "user") throw new Error("statewire: only user messages are supported");
17
+ const files = [];
18
+ const texts = [];
19
+ const source = [...message.content, ...message.attachments?.flatMap((a) => a.content) ?? []];
20
+ for (const part of source) if (part.type === "text") texts.push(part.text);
21
+ else if (part.type === "image") files.push({
22
+ type: "file",
23
+ mediaType: "image/*",
24
+ url: part.image
25
+ });
26
+ else if (part.type === "file") files.push({
27
+ type: "file",
28
+ mediaType: part.mimeType,
29
+ url: part.data,
30
+ ...part.filename !== void 0 && { filename: part.filename }
31
+ });
32
+ else throw new Error(`statewire: unsupported message part "${part.type}"`);
33
+ const parts = [...files, ...texts.length > 0 ? [{
34
+ type: "text",
35
+ text: texts.join("\n\n")
36
+ }] : []];
37
+ if (parts.length === 0) throw new Error("statewire: cannot send an empty message");
38
+ return {
39
+ id,
40
+ role: "user",
41
+ parts
42
+ };
43
+ };
44
+ const toQueueItemState = (item) => ({
45
+ id: item.id,
46
+ prompt: item.parts.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n\n"),
47
+ parts: item.parts.map((part) => part.type === "text" ? part : {
48
+ type: "file",
49
+ data: part.url,
50
+ mimeType: part.mediaType,
51
+ ...part.filename !== void 0 && { filename: part.filename }
52
+ })
53
+ });
54
+ const placementFields = (placement) => ({
55
+ ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
56
+ ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
57
+ });
58
+ const withSessionLostFallback = (transport, latest) => {
59
+ const [transportOptions, ...rest] = transport.args;
60
+ if (rest.length > 0 || typeof transportOptions !== "object" || transportOptions === null) throw new Error("statewire: onCommandSessionLost requires a transport element that takes a single options object");
61
+ const transportLevel = transportOptions.onCommandSessionLost;
62
+ return {
63
+ ...transport,
64
+ args: [{
65
+ ...transportOptions,
66
+ onCommandSessionLost: (command) => transportLevel?.(command) ?? latest.current.onCommandSessionLost?.(command)
67
+ }]
68
+ };
69
+ };
15
70
  const useStatewireThread = (options) => {
16
71
  const latest = useRef(options);
17
72
  latest.current = options;
18
73
  const [pending, setPending] = useState([]);
19
74
  const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
20
- const { state: transportState, commands, setContext } = useStatewire({
21
- transport: options.transport,
75
+ const { state: transportState, commands, connection, setContext } = useStatewire({
76
+ transport: options.onCommandSessionLost === void 0 ? options.transport : withSessionLostFallback(options.transport, latest),
22
77
  onCommandChange: (update) => {
23
78
  if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
24
79
  }
@@ -60,23 +115,95 @@ const useStatewireThread = (options) => {
60
115
  const { converter } = options;
61
116
  const metadata = useMemo(() => ({
62
117
  pendingCommands: [...pending],
63
- isSending: pending.length > 0
64
- }), [pending]);
118
+ isSending: pending.length > 0,
119
+ connection
120
+ }), [pending, connection]);
65
121
  const converted = useMemo(() => converter(state, metadata), [
66
122
  converter,
67
123
  state,
68
124
  metadata
69
125
  ]);
126
+ const queueItems = converted.queue;
127
+ const steerQueueItems = converted.steerQueue;
128
+ if (steerQueueItems !== void 0 && queueItems === void 0) throw new Error("statewire: the converter's steerQueue projection requires the queue projection");
129
+ const [queueSeam] = useState(() => ({ present: queueItems !== void 0 }));
130
+ if (queueSeam.present !== (queueItems !== void 0)) throw new Error("statewire: the converter's queue projection must be stable — it was " + (queueSeam.present ? "defined" : "undefined") + " on first convert and changed since");
131
+ const queue = useMemo(() => {
132
+ if (!queueItems) return void 0;
133
+ const laneOf = (queueItemId) => {
134
+ if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
135
+ if (queueItems.some((item_0) => item_0.id === queueItemId)) return "queue";
136
+ throw new Error(`statewire: unknown queue item "${queueItemId}"`);
137
+ };
138
+ return {
139
+ items: queueItems.map(toQueueItemState),
140
+ steerItems: (steerQueueItems ?? []).map(toQueueItemState),
141
+ enqueue: (message) => dispatch({
142
+ type: "run/enqueue",
143
+ message: toWireMessage(message, crypto.randomUUID())
144
+ }),
145
+ steer: (message_0) => dispatch({
146
+ type: "run/steer",
147
+ message: toWireMessage(message_0, crypto.randomUUID())
148
+ }),
149
+ move: (queueItemId_0, placement) => {
150
+ const lane = placement.lane ?? laneOf(queueItemId_0);
151
+ const fields = {
152
+ messageId: queueItemId_0,
153
+ ...placementFields(placement)
154
+ };
155
+ dispatch(lane === "steer" ? {
156
+ type: "run/steer",
157
+ ...fields
158
+ } : {
159
+ type: "run/enqueue",
160
+ ...fields
161
+ });
162
+ },
163
+ edit: (queueItemId_1, message_1) => {
164
+ const wireMessage = toWireMessage(message_1, queueItemId_1);
165
+ dispatch(laneOf(queueItemId_1) === "steer" ? {
166
+ type: "run/steer",
167
+ message: wireMessage
168
+ } : {
169
+ type: "run/enqueue",
170
+ message: wireMessage
171
+ });
172
+ },
173
+ remove: (queueItemId_2) => dispatch({
174
+ type: "run/dequeue",
175
+ messageId: queueItemId_2
176
+ })
177
+ };
178
+ }, [
179
+ queueItems,
180
+ steerQueueItems,
181
+ dispatch
182
+ ]);
70
183
  const extras = useMemo(() => ({
71
184
  [symbolAssistantTransportExtras]: true,
72
185
  sendCommand: dispatch,
186
+ reconnect: connection.reconnect,
73
187
  state
74
- }), [dispatch, state]);
75
- const handleAppend = (message) => {
76
- const command_1 = convertAppendMessageToCommand(message);
188
+ }), [
189
+ dispatch,
190
+ connection.reconnect,
191
+ state
192
+ ]);
193
+ const handleAppend = (message_2) => {
194
+ const command_1 = convertAppendMessageToCommand(message_2);
77
195
  if (!command_1) return;
78
196
  dispatch(command_1);
79
197
  };
198
+ const handleEdit = (message_3) => {
199
+ if (!queueItems) return handleAppend(message_3);
200
+ if (message_3.sourceId == null) throw new Error("statewire: run/edit requires a sourceId");
201
+ dispatch({
202
+ type: "run/edit",
203
+ message: toWireMessage(message_3, crypto.randomUUID()),
204
+ sourceId: message_3.sourceId
205
+ });
206
+ };
80
207
  return useResource(ExternalThread({
81
208
  messages: converted.messages,
82
209
  isRunning: converted.isRunning,
@@ -85,9 +212,13 @@ const useStatewireThread = (options) => {
85
212
  extras,
86
213
  attachmentAdapter: options.adapters?.attachments,
87
214
  onNew: handleAppend,
88
- ...options.capabilities?.edit && { onEdit: handleAppend },
215
+ ...queue && { queue },
216
+ ...options.capabilities?.edit && { onEdit: handleEdit },
217
+ ...options.capabilities?.continue && { onResume: () => dispatch({ type: "run/continue" }) },
89
218
  onCancel: () => {
90
- commands["cancel"]().catch((error_1) => {
219
+ const payload = latest.current.cancelPayload?.();
220
+ if (payload !== void 0 && (typeof payload !== "object" || payload === null || Array.isArray(payload))) throw new Error("statewire: cancelPayload must return a plain object");
221
+ commands["run/cancel"](...payload === void 0 ? [] : [payload]).catch((error_1) => {
91
222
  latest.current.onError?.(error_1);
92
223
  });
93
224
  }