@assistant-ui/react-statewire 0.3.0 → 0.4.1

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.
@@ -42,7 +42,8 @@ const placementFields = (placement) => ({
42
42
  ...placement.insertAfter !== void 0 && { insertAfter: placement.insertAfter },
43
43
  ...placement.insertBefore !== void 0 && { insertBefore: placement.insertBefore }
44
44
  });
45
- const createRunQueueAdapter = (queueItems, steerQueueItems, dispatch) => {
45
+ const viewedLeafId = (messages) => messages.at(-1)?.id ?? null;
46
+ const createRunQueueAdapter = (messages, queueItems, steerQueueItems, dispatch) => {
46
47
  const laneOf = (queueItemId) => {
47
48
  if (steerQueueItems?.some((item) => item.id === queueItemId)) return "steer";
48
49
  if (queueItems.some((item) => item.id === queueItemId)) return "queue";
@@ -53,11 +54,13 @@ const createRunQueueAdapter = (queueItems, steerQueueItems, dispatch) => {
53
54
  steerItems: (steerQueueItems ?? []).map(toQueueItemState),
54
55
  enqueue: (message) => dispatch({
55
56
  type: "run/enqueue",
56
- message: toWireMessage(message, crypto.randomUUID())
57
+ message: toWireMessage(message, crypto.randomUUID()),
58
+ anchorMessageId: viewedLeafId(messages)
57
59
  }),
58
60
  steer: (message) => dispatch({
59
61
  type: "run/steer",
60
- message: toWireMessage(message, crypto.randomUUID())
62
+ message: toWireMessage(message, crypto.randomUUID()),
63
+ anchorMessageId: viewedLeafId(messages)
61
64
  }),
62
65
  move: (queueItemId, placement) => {
63
66
  const lane = placement.lane ?? laneOf(queueItemId);
@@ -96,10 +99,11 @@ const resolveReloadCommand = (messages, parentId) => {
96
99
  if (target === void 0 || target.role !== "assistant") throw new Error("statewire: run/reload requires an assistant message to regenerate");
97
100
  return {
98
101
  type: "run/reload",
99
- sourceId: target.id
102
+ sourceId: target.id,
103
+ messageId: crypto.randomUUID()
100
104
  };
101
105
  };
102
106
  //#endregion
103
- export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage };
107
+ export { createRunQueueAdapter, resolveReloadCommand, toQueueItemState, toWireMessage, viewedLeafId };
104
108
 
105
109
  //# sourceMappingURL=runCommands.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","FilePart","RunCommand","RunQueueItem","RunReloadCommand","RunUserMessage","TextPart","toWireMessage","message","id","role","Error","files","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","length","const","join","toQueueItemState","item","prompt","map","placementFields","placement","insertAfter","insertBefore","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","messages","parentId","index","findIndex","target","sourceId"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type {\n FilePart,\n RunCommand,\n RunQueueItem,\n RunReloadCommand,\n RunUserMessage,\n TextPart,\n} from \"./types\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: 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: (TextPart | 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\nexport const toQueueItemState = (item: 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\nexport const createRunQueueAdapter = (\n queueItems: readonly RunQueueItem[],\n steerQueueItems: readonly RunQueueItem[] | undefined,\n dispatch: (command: RunCommand) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\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\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): 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 { type: \"run/reload\", sourceId: target.id };\n};\n"],"mappings":"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"}
1
+ {"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadQueueAdapter","QueuePlacement","FilePart","RunCommand","RunQueueItem","RunReloadCommand","RunUserMessage","TextPart","toWireMessage","message","id","role","Error","files","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","length","const","join","toQueueItemState","item","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","at","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","command","laneOf","queueItemId","some","items","steerItems","enqueue","crypto","randomUUID","anchorMessageId","steer","move","lane","fields","messageId","edit","wireMessage","remove","resolveReloadCommand","parentId","index","findIndex","target","sourceId"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type {\n FilePart,\n RunCommand,\n RunQueueItem,\n RunReloadCommand,\n RunUserMessage,\n TextPart,\n} from \"./types\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): RunUserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: 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: (TextPart | 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\nexport const toQueueItemState = (item: 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\nexport const viewedLeafId = (\n messages: readonly { id: string }[],\n): string | null => messages.at(-1)?.id ?? null;\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n queueItems: readonly RunQueueItem[],\n steerQueueItems: readonly RunQueueItem[] | undefined,\n dispatch: (command: RunCommand) => void,\n): ExternalThreadQueueAdapter => {\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems?.some((item) => item.id === queueItemId))\n return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: (steerQueueItems ?? []).map(toQueueItemState),\n enqueue: (message) =>\n dispatch({\n type: \"run/enqueue\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n }),\n steer: (message) =>\n dispatch({\n type: \"run/steer\",\n message: toWireMessage(message, crypto.randomUUID()),\n anchorMessageId: viewedLeafId(messages),\n }),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\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\", message: wireMessage }\n : { type: \"run/enqueue\", message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({ type: \"run/dequeue\", messageId: queueItemId }),\n };\n};\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n): 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 sourceId: target.id,\n messageId: crypto.randomUUID(),\n };\n};\n"],"mappings":"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"}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { Assistant } from "@assistant-ui/react";
2
2
  import { AttachmentAdapter, LanguageModelConfig, LanguageModelV1CallSettings, ThreadMessage, ToolExecutionStatus } from "@assistant-ui/core";
3
- import { ToolModelContentPart } from "assistant-stream";
4
3
  import { ReadonlyJSONValue } from "assistant-stream/utils";
5
4
  //#region src/types.d.ts
6
5
  type UserCommands = Assistant.Commands[keyof Assistant.Commands];
@@ -9,40 +8,6 @@ type TextPart = {
9
8
  readonly type: "text";
10
9
  readonly text: string;
11
10
  };
12
- type ImagePart = {
13
- readonly type: "image";
14
- readonly image: string;
15
- };
16
- type UserMessagePart = TextPart | ImagePart;
17
- type UserMessage = {
18
- readonly role: "user";
19
- readonly parts: readonly UserMessagePart[];
20
- };
21
- type AssistantMessage = {
22
- readonly role: "assistant";
23
- readonly parts: readonly TextPart[];
24
- };
25
- type AddMessageCommand = {
26
- readonly type: "add-message";
27
- readonly message: UserMessage | AssistantMessage;
28
- readonly parentId: string | null;
29
- readonly sourceId: string | null;
30
- /**
31
- * How the host handles the message while a run is active: `"queue"`
32
- * appends to the queue, `"steer"` moves it to the front and interrupts
33
- * the run. Absent, the host decides. Ignored when the host is idle.
34
- */
35
- readonly behavior?: "queue" | "steer";
36
- };
37
- type AddToolResultCommand = {
38
- readonly type: "add-tool-result";
39
- readonly toolCallId: string;
40
- readonly toolName: string;
41
- readonly result: ReadonlyJSONValue;
42
- readonly isError: boolean;
43
- readonly artifact?: ReadonlyJSONValue;
44
- readonly modelContent?: readonly ToolModelContentPart[];
45
- };
46
11
  type FilePart = {
47
12
  readonly type: "file";
48
13
  readonly mediaType: string;
@@ -64,6 +29,8 @@ type RunEnqueueCommand = {
64
29
  readonly type: "run/enqueue";
65
30
  } & ({
66
31
  readonly message: RunUserMessage;
32
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
33
+ readonly anchorMessageId?: string | null;
67
34
  } | {
68
35
  readonly messageId: string;
69
36
  }) & RunPlacement;
@@ -71,6 +38,8 @@ type RunSteerCommand = {
71
38
  readonly type: "run/steer";
72
39
  } & ({
73
40
  readonly message: RunUserMessage;
41
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
42
+ readonly anchorMessageId?: string | null;
74
43
  } | {
75
44
  readonly messageId: string;
76
45
  }) & RunPlacement;
@@ -127,9 +96,11 @@ type InputRequestState = InputRequest & {
127
96
  type RunReloadCommand = {
128
97
  readonly type: "run/reload";
129
98
  readonly sourceId: string;
99
+ /** Client-generated id of the regenerated assistant message. */
100
+ readonly messageId: string;
130
101
  };
131
102
  type RunCommand = RunEnqueueCommand | RunSteerCommand | RunDequeueCommand | RunEditCommand | RunContinueCommand | RunReloadCommand | RunInputCommand;
132
- type AssistantTransportCommand = AddMessageCommand | AddToolResultCommand | RunCommand | UserCommands;
103
+ type AssistantTransportCommand = RunCommand | UserCommands;
133
104
  /** A queued message projected out of the host state, wire shape. */
134
105
  type RunQueueItem = {
135
106
  readonly id: string;
@@ -216,5 +187,5 @@ type AssistantTransportOptions<T> = {
216
187
  } | undefined;
217
188
  };
218
189
  //#endregion
219
- export { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, ImagePart, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse, UserCommands, UserExternalState, UserMessage, UserMessagePart };
190
+ export { AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, CustomInputRequest, FilePart, HeadersValue, InputRequest, InputRequestState, InputResponse, RunCommand, RunContinueCommand, RunDequeueCommand, RunEditCommand, RunEnqueueCommand, RunInputCommand, RunPlacement, RunQueueItem, RunReloadCommand, RunSteerCommand, RunUserMessage, SendCommandsRequestBody, TextPart, ToolApprovalInputRequest, ToolApprovalInputResponse, ToolCallInputRequest, ToolCallInputResponse, UserCommands, UserExternalState };
220
191
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;;;;;WAMA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD;WACA;WACA;WACA;;KAGC;WACD;WACA;WACA,iBAAiB,WAAW;WAC5B,WAAW;;;KAIV;WACD;WACA;;KAGC;WACD;;WACK,SAAS;;WAA8B;KACrD;KAEU;WACD;;WACK,SAAS;;WAA8B;KACrD;KAEU;WACD;WACA;;KAGC;WACD;WACA,SAAS;WACT;;KAGC;WACD;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;YACC,cAAc;;;KAId,eACR,uBACA,2BACA;KAEQ;WACD,QAAQ;;WAER;WACA,WAAW;;KAGV;WACD;WACA,aAAa;WACb;;KAGC,gBAAgB;KAEhB;WACD;WACA;WACA,UAAU;;;KAIT,oBAAoB;WACrB,UAAU;;KAGT;WACD;WACA;;KAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;KAEQ,4BACR,oBACA,uBACA,aACA;;KAGQ;WACD;WACA,iBAAiB,WAAW;;KAG3B;WACD,mBAAmB;WACnB,QAAQ;WACR;;;;;;;;WAQA,iBAAiB;;WAEjB,sBAAsB;;;;;;WAMtB,yBAAyB;;KAGxB;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;;IAMA;;IAEA;;EAGN;IAEM,cAAc"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;KAUY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;WACA;WACA;;KAGC;WACD;WACA;WACA,iBAAiB,WAAW;WAC5B,WAAW;;;KAIV;WACD;WACA;;KAGC;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;KAEU;WACD;;WAGI,SAAS;;WAET;;WAEA;KAEb;KAEU;WACD;WACA;;KAGC;WACD;WACA,SAAS;WACT;;KAGC;WACD;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;WACA;;KAGC;WACD;WACA;YACC,cAAc;;;KAId,eACR,uBACA,2BACA;KAEQ;WACD,QAAQ;;WAER;WACA,WAAW;;KAGV;WACD;WACA,aAAa;WACb;;KAGC,gBAAgB;KAEhB;WACD;WACA;WACA,UAAU;;;KAIT,oBAAoB;WACrB,UAAU;;KAGT;WACD;WACA;;WAEA;;KAGC,aACR,oBACA,kBACA,oBACA,iBACA,qBACA,mBACA;KAEQ,4BAA4B,aAAa;;KAGzC;WACD;WACA,iBAAiB,WAAW;;KAG3B;WACD,mBAAmB;WACnB,QAAQ;WACR;;;;;;;;WAQA,iBAAiB;;WAEjB,sBAAsB;;;;;;WAMtB,yBAAyB;;KAGxB;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;;IAMA;;IAEA;;EAGN;IAEM,cAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "@assistant-ui/store": "^0.3.0",
35
35
  "@assistant-ui/tap": "^0.9.7",
36
36
  "assistant-stream": "^0.3.33",
37
- "statewire": "^0.0.5"
37
+ "statewire": "^0.4.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@assistant-ui/react": ">=0.15.6",
@@ -27,7 +27,6 @@ import type {
27
27
  ToolExecutionStatus,
28
28
  } from "@assistant-ui/core";
29
29
  import { ToolInvocationTracker } from "@assistant-ui/core/internal";
30
- import type { ReadonlyJSONObject } from "assistant-stream/utils";
31
30
  import { useStatewire } from "statewire";
32
31
  import { AssistantTransportHost } from "./host";
33
32
  import type {
@@ -41,13 +40,13 @@ import {
41
40
  createRunQueueAdapter,
42
41
  resolveReloadCommand,
43
42
  toWireMessage,
43
+ viewedLeafId,
44
44
  } from "./runCommands";
45
45
  import {
46
46
  resolveToolApprovalInput,
47
47
  resolveToolResultInput,
48
48
  } from "./inputRequests";
49
49
  import type {
50
- AddToolResultCommand,
51
50
  AssistantTransportCommand,
52
51
  AssistantTransportOptions,
53
52
  InputRequestState,
@@ -163,10 +162,11 @@ const useAssistantTransportThread = (
163
162
  const messages = convertedRef.current
164
163
  .messages as readonly ThreadMessage[];
165
164
  if (!messagesContainToolCall(messages, command.toolCallId)) return;
166
- const requests = convertedRef.current.inputRequests;
167
165
  dispatch(
168
- (requests && resolveToolResultInput(requests, command)) ??
166
+ resolveToolResultInput(
167
+ convertedRef.current.inputRequests ?? [],
169
168
  command,
169
+ ),
170
170
  );
171
171
  },
172
172
  onStatusesChange: (statuses) => {
@@ -221,6 +221,7 @@ const useAssistantTransportThread = (
221
221
  const command: AssistantTransportCommand = {
222
222
  type: "run/steer",
223
223
  message: toWireMessage(message, crypto.randomUUID()),
224
+ anchorMessageId: viewedLeafId(convertedRef.current.messages),
224
225
  };
225
226
  void commands.setParentId(message.parentId).catch(() => {});
226
227
 
@@ -286,9 +287,14 @@ const useAssistantTransportThread = (
286
287
  const serverQueue = useMemo(
287
288
  () =>
288
289
  queueProjection
289
- ? createRunQueueAdapter(queueProjection, steerProjection, dispatch)
290
+ ? createRunQueueAdapter(
291
+ converted.messages,
292
+ queueProjection,
293
+ steerProjection,
294
+ dispatch,
295
+ )
290
296
  : undefined,
291
- [queueProjection, steerProjection, dispatch],
297
+ [converted.messages, queueProjection, steerProjection, dispatch],
292
298
  );
293
299
 
294
300
  const enableQueue = options.capabilities?.queue === true;
@@ -370,29 +376,14 @@ const useAssistantTransportThread = (
370
376
  throw new Error("Must pass resumeApi to options to resume runs");
371
377
  void commands.resume().catch(() => {});
372
378
  },
373
- onAddToolResult: (toolOptions: AddToolResultOptions) => {
374
- const requests = convertedRef.current.inputRequests;
375
- const inputCommand =
376
- requests && resolveToolResultInput(requests, toolOptions);
377
- if (inputCommand) {
378
- dispatch(inputCommand);
379
- return;
380
- }
381
- const command: AddToolResultCommand = {
382
- type: "add-tool-result",
383
- toolCallId: toolOptions.toolCallId,
384
- result: toolOptions.result as ReadonlyJSONObject,
385
- toolName: toolOptions.toolName,
386
- isError: toolOptions.isError,
387
- ...(toolOptions.artifact && { artifact: toolOptions.artifact }),
388
- ...(toolOptions.modelContent !== undefined && {
389
- modelContent: toolOptions.modelContent,
390
- }),
391
- };
392
-
393
- dispatch(command);
394
- },
395
379
  ...(inputRequests !== undefined && {
380
+ onAddToolResult: (toolOptions: AddToolResultOptions) =>
381
+ dispatch(
382
+ resolveToolResultInput(
383
+ convertedRef.current.inputRequests!,
384
+ toolOptions,
385
+ ),
386
+ ),
396
387
  onRespondToToolApproval: (options: RespondToToolApprovalOptions) =>
397
388
  dispatch(
398
389
  resolveToolApprovalInput(
@@ -18,7 +18,7 @@ import { createMockTransport } from "statewire/testing";
18
18
  import { StatewireThread } from "./StatewireThread";
19
19
  import { asAssistantTransportExtras } from "./AssistantTransportThread";
20
20
  import { useAssistantTransportState } from "./hooks";
21
- import type { AddMessageCommand, AssistantTransportCommand } from "./types";
21
+ import type { AssistantTransportCommand } from "./types";
22
22
  import {
23
23
  sendCommand,
24
24
  threadTexts,
@@ -38,10 +38,8 @@ type ServerState = {
38
38
  inputRequests: StatewireThread.InputRequestState[];
39
39
  };
40
40
 
41
- const textOf = (command: Pick<AddMessageCommand, "message">) =>
42
- command.message.parts
43
- .flatMap((p) => (p.type === "text" ? [p.text] : []))
44
- .join("");
41
+ const textOf = (message: { parts: StatewireThread.UserMessage["parts"] }) =>
42
+ message.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join("");
45
43
 
46
44
  const textEntry = (id: string, text: string): QueueEntry => ({
47
45
  id,
@@ -55,12 +53,12 @@ const converter: StatewireThread.StateConverter<ServerState> = (
55
53
  messages: [
56
54
  ...state.messages.map(toThreadMessage),
57
55
  ...meta.pendingCommands.flatMap((c, i) =>
58
- c.type === "add-message" && c.message.role === "user"
56
+ c.type === "run/steer" && "message" in c
59
57
  ? [
60
58
  toThreadMessage({
61
59
  id: `optimistic-${i}`,
62
60
  role: "user",
63
- text: textOf(c),
61
+ text: textOf(c.message),
64
62
  }),
65
63
  ]
66
64
  : [],
@@ -130,6 +128,11 @@ const createServer = (init?: {
130
128
  | StatewireThread.RunSteerCommand,
131
129
  ) => {
132
130
  received.push(command);
131
+ if (cell.hold) {
132
+ return new Promise<void>((resolve) => {
133
+ cell.resolvers = { resolve };
134
+ });
135
+ }
133
136
  if ("messageId" in command) {
134
137
  const entry = takeEntry(command.messageId);
135
138
  if (!entry) throw new StatewireReject("unknown-id");
@@ -157,6 +160,7 @@ const createServer = (init?: {
157
160
  return;
158
161
  }
159
162
  state[lane].push(entry);
163
+ return;
160
164
  };
161
165
 
162
166
  const commands = useStatewireCommands({
@@ -176,21 +180,6 @@ const createServer = (init?: {
176
180
  received.push(command);
177
181
  state.running = true;
178
182
  },
179
- "add-message": (command: AddMessageCommand) => {
180
- received.push(command);
181
- if (cell.hold) {
182
- return new Promise<void>((resolve) => {
183
- cell.resolvers = { resolve };
184
- });
185
- }
186
- state.messages.push({
187
- id: `u${state.messages.length}`,
188
- role: "user",
189
- text: textOf(command),
190
- });
191
- state.running = true;
192
- return undefined;
193
- },
194
183
  "run/stop": (payload?: unknown) => {
195
184
  received.push(
196
185
  payload === undefined
@@ -206,9 +195,6 @@ const createServer = (init?: {
206
195
  "run/input": (command: StatewireThread.RunInputCommand) => {
207
196
  received.push(command);
208
197
  },
209
- "add-tool-result": (command: AssistantTransportCommand) => {
210
- received.push(command);
211
- },
212
198
  "reject-me": () => {
213
199
  throw new StatewireReject("nope");
214
200
  },
@@ -312,7 +298,7 @@ describe("StatewireThread", () => {
312
298
  expect((observed.at(-1) as ServerState).messages[0]!.text).toBe("welcome");
313
299
  });
314
300
 
315
- it("round-trips an appended message through the add-message command", async () => {
301
+ it("round-trips an appended message through the run/steer command", async () => {
316
302
  const server = createServer();
317
303
  const { aui } = mountThread({ transport: server.transport, converter });
318
304
 
@@ -320,10 +306,12 @@ describe("StatewireThread", () => {
320
306
 
321
307
  await waitFor(() => expect(server.received).toHaveLength(1));
322
308
  expect(server.received[0]).toMatchObject({
323
- type: "add-message",
324
- message: { role: "user", parts: [{ type: "text", text: "hello" }] },
325
- parentId: null,
326
- sourceId: null,
309
+ type: "run/steer",
310
+ message: {
311
+ id: expect.any(String),
312
+ role: "user",
313
+ parts: [{ type: "text", text: "hello" }],
314
+ },
327
315
  });
328
316
 
329
317
  await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
@@ -360,7 +348,7 @@ describe("StatewireThread", () => {
360
348
  await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
361
349
  const meta = metas.at(-1)!;
362
350
  expect(meta.isSending).toBe(true);
363
- expect(meta.pendingCommands).toMatchObject([{ type: "add-message" }]);
351
+ expect(meta.pendingCommands).toMatchObject([{ type: "run/steer" }]);
364
352
 
365
353
  server.cell.resolvers!.resolve();
366
354
 
@@ -833,7 +821,7 @@ describe("StatewireThread", () => {
833
821
  );
834
822
  });
835
823
 
836
- it("falls back to add-tool-result without a matching pending request", async () => {
824
+ it("throws without a matching pending request", async () => {
837
825
  const server = createServer();
838
826
  const { aui } = mountThread({
839
827
  transport: server.transport,
@@ -843,17 +831,10 @@ describe("StatewireThread", () => {
843
831
  await waitFor(() =>
844
832
  expect(aui().thread().getState().isLoading).toBe(false),
845
833
  );
846
- toolCallPart(aui).addToolResult({ ok: true });
847
-
848
- await waitFor(() =>
849
- expect(server.received).toContainEqual({
850
- type: "add-tool-result",
851
- toolCallId: "tc1",
852
- toolName: "probe_tool",
853
- result: { ok: true },
854
- isError: false,
855
- }),
834
+ expect(() => toolCallPart(aui).addToolResult({ ok: true })).toThrow(
835
+ 'statewire: no tool-call input request for tool call "tc1"',
856
836
  );
837
+ expect(server.received).toEqual([]);
857
838
  });
858
839
 
859
840
  it("throws on answering a request that already carries a response", async () => {
@@ -1012,6 +993,7 @@ describe("StatewireThread", () => {
1012
993
  expect(server.received).toContainEqual({
1013
994
  type: "run/reload",
1014
995
  sourceId: "a1",
996
+ messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
1015
997
  }),
1016
998
  );
1017
999
  });
@@ -1034,6 +1016,7 @@ describe("StatewireThread", () => {
1034
1016
  expect(server.received).toContainEqual({
1035
1017
  type: "run/reload",
1036
1018
  sourceId: "a0",
1019
+ messageId: expect.stringMatching(/^[0-9a-f-]{36}$/),
1037
1020
  }),
1038
1021
  );
1039
1022
  });
@@ -27,16 +27,13 @@ import {
27
27
  createRunQueueAdapter,
28
28
  resolveReloadCommand,
29
29
  toWireMessage,
30
+ viewedLeafId,
30
31
  } from "./runCommands";
31
32
  import {
32
33
  resolveToolApprovalInput,
33
34
  resolveToolResultInput,
34
35
  } from "./inputRequests";
35
- import type {
36
- AddMessageCommand,
37
- AssistantTransportCommand,
38
- UserMessagePart,
39
- } from "./types";
36
+ import type { AssistantTransportCommand } from "./types";
40
37
 
41
38
  type AnyCommands = Record<string, (...args: any[]) => unknown>;
42
39
 
@@ -51,38 +48,6 @@ const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
51
48
  ...(context.config !== undefined && { config: context.config }),
52
49
  });
53
50
 
54
- const convertAppendMessageToCommand = (
55
- message: AppendMessage,
56
- ): AddMessageCommand | null => {
57
- if (message.role !== "user")
58
- throw new Error("Only user messages are supported");
59
-
60
- const parts: UserMessagePart[] = [];
61
- const content = [
62
- ...message.content,
63
- ...(message.attachments?.flatMap((a) => a.content) ?? []),
64
- ];
65
- for (const contentPart of content) {
66
- if (contentPart.type === "text") {
67
- parts.push({ type: "text", text: contentPart.text });
68
- } else if (contentPart.type === "image") {
69
- parts.push({ type: "image", image: contentPart.image });
70
- }
71
- }
72
-
73
- if (parts.length === 0) return null;
74
-
75
- return {
76
- type: "add-message",
77
- message: {
78
- role: "user",
79
- parts,
80
- },
81
- parentId: message.parentId,
82
- sourceId: message.sourceId,
83
- };
84
- };
85
-
86
51
  const withSessionLostFallback = (
87
52
  transport: StatewireThread.Transport<any>,
88
53
  latest: { current: StatewireThread.Options<any> },
@@ -223,9 +188,14 @@ const useStatewireThread = (
223
188
  const queue = useMemo(
224
189
  (): ExternalThreadQueueAdapter | undefined =>
225
190
  queueItems
226
- ? createRunQueueAdapter(queueItems, steerQueueItems, dispatch)
191
+ ? createRunQueueAdapter(
192
+ converted.messages,
193
+ queueItems,
194
+ steerQueueItems,
195
+ dispatch,
196
+ )
227
197
  : undefined,
228
- [queueItems, steerQueueItems, dispatch],
198
+ [converted.messages, queueItems, steerQueueItems, dispatch],
229
199
  );
230
200
 
231
201
  const inputRequests = converted.inputRequests;
@@ -251,9 +221,11 @@ const useStatewireThread = (
251
221
  );
252
222
 
253
223
  const handleAppend = (message: AppendMessage) => {
254
- const command = convertAppendMessageToCommand(message);
255
- if (!command) return;
256
- dispatch(command);
224
+ dispatch({
225
+ type: "run/steer",
226
+ message: toWireMessage(message, crypto.randomUUID()),
227
+ anchorMessageId: viewedLeafId(converted.messages),
228
+ });
257
229
  };
258
230
 
259
231
  const handleReload = (parentId: string | null) => {
@@ -261,7 +233,6 @@ const useStatewireThread = (
261
233
  };
262
234
 
263
235
  const handleEdit = (message: AppendMessage) => {
264
- if (!queueItems) return handleAppend(message);
265
236
  if (message.sourceId == null)
266
237
  throw new Error("statewire: run/edit requires a sourceId");
267
238
  dispatch({
@@ -287,27 +258,8 @@ const useStatewireThread = (
287
258
  }),
288
259
  ...(options.capabilities?.reload && { onReload: handleReload }),
289
260
  ...(inputRequests !== undefined && {
290
- onAddToolResult: (toolOptions: AddToolResultOptions) => {
291
- const inputCommand = resolveToolResultInput(
292
- inputRequests,
293
- toolOptions,
294
- );
295
- dispatch(
296
- inputCommand ?? {
297
- type: "add-tool-result",
298
- toolCallId: toolOptions.toolCallId,
299
- toolName: toolOptions.toolName,
300
- result: toolOptions.result,
301
- isError: toolOptions.isError,
302
- ...(toolOptions.artifact !== undefined && {
303
- artifact: toolOptions.artifact,
304
- }),
305
- ...(toolOptions.modelContent !== undefined && {
306
- modelContent: toolOptions.modelContent,
307
- }),
308
- },
309
- );
310
- },
261
+ onAddToolResult: (toolOptions: AddToolResultOptions) =>
262
+ dispatch(resolveToolResultInput(inputRequests, toolOptions)),
311
263
  onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>
312
264
  dispatch(resolveToolApprovalInput(inputRequests, approval)),
313
265
  }),
@@ -365,12 +317,26 @@ export namespace StatewireThread {
365
317
 
366
318
  export type RunEnqueueCommand = {
367
319
  readonly type: "run/enqueue";
368
- } & ({ readonly message: UserMessage } | { readonly messageId: string }) &
320
+ } & (
321
+ | {
322
+ readonly message: UserMessage;
323
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
324
+ readonly anchorMessageId?: string | null;
325
+ }
326
+ | { readonly messageId: string }
327
+ ) &
369
328
  Placement;
370
329
 
371
330
  export type RunSteerCommand = {
372
331
  readonly type: "run/steer";
373
- } & ({ readonly message: UserMessage } | { readonly messageId: string }) &
332
+ } & (
333
+ | {
334
+ readonly message: UserMessage;
335
+ /** Branch anchor: the newest message the client knows on its intended branch, null asserting an empty thread. Required on adds; optional on edits of queued items. */
336
+ readonly anchorMessageId?: string | null;
337
+ }
338
+ | { readonly messageId: string }
339
+ ) &
374
340
  Placement;
375
341
 
376
342
  export type RunDequeueCommand = {
@@ -441,6 +407,8 @@ export namespace StatewireThread {
441
407
  export type RunReloadCommand = {
442
408
  readonly type: "run/reload";
443
409
  readonly sourceId: string;
410
+ /** Client-generated id of the regenerated assistant message. */
411
+ readonly messageId: string;
444
412
  };
445
413
 
446
414
  export type RunCommand =
@@ -12,6 +12,7 @@ import type {
12
12
  AssistantTransportConnectionMetadata,
13
13
  AssistantTransportOptions,
14
14
  AssistantTransportStateConverter,
15
+ InputRequestState,
15
16
  } from "../types";
16
17
 
17
18
  export type TestState = {
@@ -193,10 +194,14 @@ export const toolCallConverter = (
193
194
  ): AssistantTransportStateConverter<TestState> => {
194
195
  type ToolCallState = TestState & {
195
196
  toolCall?: { id: string; name: string; argsText: string };
197
+ inputRequests?: InputRequestState[];
196
198
  };
197
199
  return (state, meta) => {
198
200
  metas.push(meta);
199
- const base = defaultConverter(state, meta);
201
+ const base = {
202
+ ...defaultConverter(state, meta),
203
+ inputRequests: (state as ToolCallState).inputRequests ?? [],
204
+ };
200
205
  const toolCall = (state as ToolCallState).toolCall;
201
206
  if (!toolCall) return base;
202
207
  return {
@@ -234,6 +239,18 @@ export const emitToolCall = (server: StreamResponse) => {
234
239
  path: ["toolCall"],
235
240
  value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
236
241
  },
242
+ {
243
+ type: "set",
244
+ path: ["inputRequests"],
245
+ value: [
246
+ {
247
+ type: "tool-call",
248
+ id: "req-tc1",
249
+ toolCallId: "tc1",
250
+ response: null,
251
+ },
252
+ ],
253
+ },
237
254
  ],
238
255
  });
239
256
  server.done();