@assistant-ui/react-statewire 0.1.0 → 0.1.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.
@@ -11,13 +11,14 @@ import type { ClientOutput } from "@assistant-ui/store";
11
11
  import type {
12
12
  AppendMessage,
13
13
  AttachmentAdapter,
14
+ ExternalThreadQueueAdapter,
14
15
  ModelContext,
15
16
  ThreadMessage,
16
17
  } from "@assistant-ui/core";
17
18
  import { toToolsJSONSchema } from "assistant-stream";
18
19
  import type { ReadonlyJSONValue } from "assistant-stream/utils";
19
20
  import { useStatewire } from "statewire";
20
- import type { Statewire } from "statewire";
21
+ import type { Statewire, StatewireClient } from "statewire";
21
22
  import {
22
23
  convertAppendMessageToCommand,
23
24
  symbolAssistantTransportExtras,
@@ -30,10 +31,7 @@ type AnyCommands = Record<string, (...args: any[]) => unknown>;
30
31
  const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
31
32
  ...(context.system !== undefined && { system: context.system }),
32
33
  ...(context.tools !== undefined && {
33
- // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
34
- tools: toToolsJSONSchema(
35
- context.tools as unknown as Parameters<typeof toToolsJSONSchema>[0],
36
- ),
34
+ tools: toToolsJSONSchema(context.tools),
37
35
  }),
38
36
  ...(context.callSettings !== undefined && {
39
37
  callSettings: context.callSettings,
@@ -62,6 +60,7 @@ const useStatewireThread = (
62
60
  const {
63
61
  state: transportState,
64
62
  commands,
63
+ connection,
65
64
  setContext,
66
65
  } = useStatewire<unknown, AnyCommands>({
67
66
  transport: options.transport,
@@ -115,21 +114,58 @@ const useStatewireThread = (
115
114
  (): StatewireThread.ConnectionMetadata => ({
116
115
  pendingCommands: [...pending],
117
116
  isSending: pending.length > 0,
117
+ connection,
118
118
  }),
119
- [pending],
119
+ [pending, connection],
120
120
  );
121
121
  const converted = useMemo(
122
122
  () => converter(state, metadata),
123
123
  [converter, state, metadata],
124
124
  );
125
+ const convertedRef = useRef(converted);
126
+ convertedRef.current = converted;
127
+
128
+ const queueItems = converted.queue;
129
+ const [queueSeam] = useState(() => ({
130
+ present: queueItems !== undefined,
131
+ }));
132
+ if (queueSeam.present !== (queueItems !== undefined))
133
+ throw new Error(
134
+ "statewire: the converter's queue projection must be stable — it was " +
135
+ (queueSeam.present ? "defined" : "undefined") +
136
+ " on first convert and changed since",
137
+ );
138
+
139
+ const queue = useMemo(
140
+ (): ExternalThreadQueueAdapter | undefined =>
141
+ queueItems && {
142
+ items: queueItems,
143
+ enqueue: (message, { steer }) => {
144
+ const command = convertAppendMessageToCommand(message);
145
+ if (!command) return;
146
+ dispatch(
147
+ convertedRef.current.isRunning
148
+ ? { ...command, type: "enqueue-message", steer }
149
+ : command,
150
+ );
151
+ },
152
+ steer: (queueItemId) =>
153
+ dispatch({ type: "steer-queue-item", queueItemId }),
154
+ remove: (queueItemId) =>
155
+ dispatch({ type: "remove-queue-item", queueItemId }),
156
+ clear: (reason) => dispatch({ type: "clear-queue", reason }),
157
+ },
158
+ [queueItems, dispatch],
159
+ );
125
160
 
126
161
  const extras = useMemo(
127
162
  (): AssistantTransportExtras => ({
128
163
  [symbolAssistantTransportExtras]: true,
129
164
  sendCommand: dispatch,
165
+ reconnect: connection.reconnect,
130
166
  state,
131
167
  }),
132
- [dispatch, state],
168
+ [dispatch, connection.reconnect, state],
133
169
  );
134
170
 
135
171
  const handleAppend = (message: AppendMessage) => {
@@ -147,9 +183,22 @@ const useStatewireThread = (
147
183
  extras,
148
184
  attachmentAdapter: options.adapters?.attachments,
149
185
  onNew: handleAppend,
186
+ ...(queue && { queue }),
150
187
  ...(options.capabilities?.edit && { onEdit: handleAppend }),
151
188
  onCancel: () => {
152
- void commands["cancel"]!().catch((error: Error) => {
189
+ const payload = latest.current.cancelPayload?.();
190
+ if (
191
+ payload !== undefined &&
192
+ (typeof payload !== "object" ||
193
+ payload === null ||
194
+ Array.isArray(payload))
195
+ )
196
+ throw new Error(
197
+ "statewire: cancelPayload must return a plain object",
198
+ );
199
+ void commands["cancel"]!(
200
+ ...(payload === undefined ? [] : [payload]),
201
+ ).catch((error: Error) => {
153
202
  latest.current.onError?.(error);
154
203
  });
155
204
  },
@@ -165,15 +214,29 @@ export const StatewireThread = <T>(
165
214
  export namespace StatewireThread {
166
215
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
167
216
 
217
+ export type QueueItem = {
218
+ readonly id: string;
219
+ readonly prompt: string;
220
+ };
221
+
168
222
  export type State = {
169
223
  readonly messages: readonly ThreadMessage[];
170
224
  readonly state?: ReadonlyJSONValue;
171
225
  readonly isRunning: boolean;
226
+ /**
227
+ * Server-owned message queue projected out of the state. Returning it
228
+ * (even empty) turns on the queue capability: sends during a run become
229
+ * `enqueue-message` commands and item controls send the queue commands.
230
+ * Presence must be stable across conversions.
231
+ */
232
+ readonly queue?: readonly QueueItem[];
172
233
  };
173
234
 
174
235
  export type ConnectionMetadata = {
175
236
  pendingCommands: AssistantTransportCommand[];
176
237
  isSending: boolean;
238
+ /** Statewire connection status; local transports are always `live`. */
239
+ connection: StatewireClient.ConnectionState;
177
240
  };
178
241
 
179
242
  export type StateConverter<T> = (
@@ -181,6 +244,15 @@ export namespace StatewireThread {
181
244
  connectionMetadata: ConnectionMetadata,
182
245
  ) => State;
183
246
 
247
+ /**
248
+ * Payload of the built-in `cancel` command. `reason` is the one well-known
249
+ * field; apps extend it with their own JSON-serializable fields.
250
+ */
251
+ export type CancelPayload = {
252
+ readonly reason?: string | undefined;
253
+ readonly [key: string]: ReadonlyJSONValue | undefined;
254
+ };
255
+
184
256
  export type Options<T> = {
185
257
  transport: Transport<T>;
186
258
  initialState: T;
@@ -191,6 +263,8 @@ export namespace StatewireThread {
191
263
  * on connect and whenever it changes. Requires a remote transport.
192
264
  */
193
265
  contextSync?: "command-send" | undefined;
266
+ /** Supplies the `cancel` command's payload; omitted, cancel sends no payload. */
267
+ cancelPayload?: (() => CancelPayload) | undefined;
194
268
  onError?: ((error: Error) => void) | undefined;
195
269
  capabilities?:
196
270
  | {
package/src/host.ts CHANGED
@@ -183,12 +183,7 @@ const useHostLoop = (
183
183
  state: getAgent(),
184
184
  system: modelContext.system,
185
185
  tools: modelContext.tools
186
- ? // cast: core >=0.3.5 widens tool generics beyond assistant-stream's Tool
187
- toToolsJSONSchema(
188
- modelContext.tools as unknown as Parameters<
189
- typeof toToolsJSONSchema
190
- >[0],
191
- )
186
+ ? toToolsJSONSchema(modelContext.tools)
192
187
  : undefined,
193
188
  threadId,
194
189
  ...(runParentId !== undefined && { parentId: runParentId }),
package/src/index.ts CHANGED
@@ -17,6 +17,10 @@ export namespace AssistantTransportThread {
17
17
  export type StateConverter<T> = types.AssistantTransportStateConverter<T>;
18
18
  export type AddMessageCommand = types.AddMessageCommand;
19
19
  export type AddToolResultCommand = types.AddToolResultCommand;
20
+ export type EnqueueMessageCommand = types.EnqueueMessageCommand;
21
+ export type SteerQueueItemCommand = types.SteerQueueItemCommand;
22
+ export type RemoveQueueItemCommand = types.RemoveQueueItemCommand;
23
+ export type ClearQueueCommand = types.ClearQueueCommand;
20
24
  export type SendCommandsRequestBody = types.SendCommandsRequestBody;
21
25
  export type UserMessage = types.UserMessage;
22
26
  export type AssistantMessage = types.AssistantMessage;
@@ -1999,3 +1999,142 @@ describe("reload", () => {
1999
1999
  expect(fetchMock.requests[2]!.body.parentId).toBe("m1");
2000
2000
  });
2001
2001
  });
2002
+
2003
+ describe("message queue", () => {
2004
+ it("buffers a send during a run and dispatches it once the run settles", async () => {
2005
+ const fetchMock = installFetch();
2006
+ const servers: StreamResponse[] = [];
2007
+ fetchMock.setHandler(() => {
2008
+ const server = createStreamResponse();
2009
+ servers.push(server);
2010
+ return server.response;
2011
+ });
2012
+
2013
+ const { aui } = mountThread({ capabilities: { queue: true } });
2014
+ aui().thread().append("first");
2015
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2016
+ await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2017
+ expect(aui().thread().getState().capabilities.queue).toBe(true);
2018
+
2019
+ aui().thread().append("second");
2020
+ await waitFor(() =>
2021
+ expect(aui().thread().composer().getState().queue).toMatchObject([
2022
+ { prompt: "second" },
2023
+ ]),
2024
+ );
2025
+ expect(fetchMock.requests).toHaveLength(1);
2026
+
2027
+ servers[0]!.emit({
2028
+ type: "update-state",
2029
+ operations: [
2030
+ {
2031
+ type: "set",
2032
+ path: ["messages"],
2033
+ value: [
2034
+ { id: "m1", role: "user", text: "first" },
2035
+ { id: "m2", role: "assistant", text: "reply" },
2036
+ ],
2037
+ },
2038
+ ],
2039
+ });
2040
+ servers[0]!.done();
2041
+
2042
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2043
+ expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2044
+ {
2045
+ type: "add-message",
2046
+ message: { role: "user", parts: [{ type: "text", text: "second" }] },
2047
+ },
2048
+ ]);
2049
+ // restamped at dispatch time: parented under the finished run's head
2050
+ expect(fetchMock.requests[1]!.body.parentId).toBe("m2");
2051
+ await waitFor(() =>
2052
+ expect(aui().thread().composer().getState().queue).toHaveLength(0),
2053
+ );
2054
+ });
2055
+
2056
+ it("holds the queue through the stop-settling window until the transport releases", async () => {
2057
+ const fetchMock = installFetch();
2058
+ const servers: StreamResponse[] = [];
2059
+ fetchMock.setHandler(() => {
2060
+ const server = createStreamResponse();
2061
+ servers.push(server);
2062
+ return server.response;
2063
+ });
2064
+
2065
+ type RunningState = TestState & { running?: boolean };
2066
+ const { aui } = mountThread({
2067
+ capabilities: { queue: true },
2068
+ converter: (state, meta) => ({
2069
+ ...defaultConverter(state, meta),
2070
+ isRunning: (state as RunningState).running ?? false,
2071
+ }),
2072
+ });
2073
+
2074
+ aui().thread().append("first");
2075
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2076
+ servers[0]!.emit({
2077
+ type: "update-state",
2078
+ operations: [{ type: "set", path: ["running"], value: true }],
2079
+ });
2080
+ await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2081
+
2082
+ aui().thread().append("second");
2083
+ await waitFor(() =>
2084
+ expect(aui().thread().composer().getState().queue).toHaveLength(1),
2085
+ );
2086
+
2087
+ // state says the run stopped, but the stream has not settled yet: the
2088
+ // queued message must not dispatch into this window
2089
+ servers[0]!.emit({
2090
+ type: "update-state",
2091
+ operations: [{ type: "set", path: ["running"], value: false }],
2092
+ });
2093
+ await waitFor(() =>
2094
+ expect(aui().thread().getState().isRunning).toBe(false),
2095
+ );
2096
+ expect(fetchMock.requests).toHaveLength(1);
2097
+ expect(aui().thread().composer().getState().queue).toHaveLength(1);
2098
+
2099
+ servers[0]!.done();
2100
+
2101
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(2));
2102
+ expect(fetchMock.requests[1]!.body.commands).toMatchObject([
2103
+ {
2104
+ type: "add-message",
2105
+ message: { parts: [{ type: "text", text: "second" }] },
2106
+ },
2107
+ ]);
2108
+ });
2109
+
2110
+ it("drops queued messages when the run is cancelled", async () => {
2111
+ const fetchMock = installFetch();
2112
+ fetchMock.setHandler(({ init }) => abortableStream(init).response);
2113
+
2114
+ const { aui } = mountThread({ capabilities: { queue: true } });
2115
+ aui().thread().append("first");
2116
+ await waitFor(() => expect(fetchMock.requests).toHaveLength(1));
2117
+ await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
2118
+
2119
+ aui().thread().append("second");
2120
+ await waitFor(() =>
2121
+ expect(aui().thread().composer().getState().queue).toHaveLength(1),
2122
+ );
2123
+
2124
+ aui().thread().cancelRun();
2125
+
2126
+ await waitFor(() =>
2127
+ expect(aui().thread().getState().isRunning).toBe(false),
2128
+ );
2129
+ expect(aui().thread().composer().getState().queue).toHaveLength(0);
2130
+ expect(fetchMock.requests).toHaveLength(1);
2131
+ });
2132
+
2133
+ it("stays off without the capability", async () => {
2134
+ installFetch();
2135
+ const { aui } = mountThread();
2136
+ await waitFor(() =>
2137
+ expect(aui().thread().getState().capabilities.queue).toBe(false),
2138
+ );
2139
+ });
2140
+ });
package/src/types.ts CHANGED
@@ -53,9 +53,36 @@ export type AddToolResultCommand = {
53
53
  readonly modelContent?: readonly ToolModelContentPart[];
54
54
  };
55
55
 
56
+ export type EnqueueMessageCommand = {
57
+ readonly type: "enqueue-message";
58
+ readonly message: UserMessage | AssistantMessage;
59
+ readonly parentId: string | null;
60
+ readonly sourceId: string | null;
61
+ readonly steer: boolean;
62
+ };
63
+
64
+ export type SteerQueueItemCommand = {
65
+ readonly type: "steer-queue-item";
66
+ readonly queueItemId: string;
67
+ };
68
+
69
+ export type RemoveQueueItemCommand = {
70
+ readonly type: "remove-queue-item";
71
+ readonly queueItemId: string;
72
+ };
73
+
74
+ export type ClearQueueCommand = {
75
+ readonly type: "clear-queue";
76
+ readonly reason: "edit" | "reload" | "cancel-run";
77
+ };
78
+
56
79
  export type AssistantTransportCommand =
57
80
  | AddMessageCommand
58
81
  | AddToolResultCommand
82
+ | EnqueueMessageCommand
83
+ | SteerQueueItemCommand
84
+ | RemoveQueueItemCommand
85
+ | ClearQueueCommand
59
86
  | UserCommands;
60
87
 
61
88
  export type AssistantTransportState = {
@@ -130,6 +157,11 @@ export type AssistantTransportOptions<T> = {
130
157
  capabilities?:
131
158
  | {
132
159
  edit?: boolean | undefined;
160
+ /**
161
+ * Buffer messages sent during a run in an in-memory queue and dispatch
162
+ * them once the run settles. Steering interrupts the active run.
163
+ */
164
+ queue?: boolean | undefined;
133
165
  }
134
166
  | undefined;
135
167
  adapters?: