@assistant-ui/react-statewire 0.0.5 → 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.
- package/dist/AssistantTransportThread.d.ts +1 -0
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +48 -7
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +25 -1
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +51 -15
- package/dist/StatewireThread.js.map +1 -1
- package/dist/host.d.ts +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/types.d.ts +26 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/AssistantTransportThread.ts +75 -7
- package/src/StatewireThread.test.tsx +279 -12
- package/src/StatewireThread.ts +91 -12
- package/src/index.ts +4 -0
- package/src/transport.test.tsx +145 -3
- package/src/types.ts +32 -0
package/src/StatewireThread.ts
CHANGED
|
@@ -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,
|
|
@@ -27,11 +28,6 @@ import type { AssistantTransportCommand } from "./types";
|
|
|
27
28
|
|
|
28
29
|
type AnyCommands = Record<string, (...args: any[]) => unknown>;
|
|
29
30
|
|
|
30
|
-
const EMPTY_CONVERTED: StatewireThread.State = {
|
|
31
|
-
messages: [],
|
|
32
|
-
isRunning: false,
|
|
33
|
-
};
|
|
34
|
-
|
|
35
31
|
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
36
32
|
...(context.system !== undefined && { system: context.system }),
|
|
37
33
|
...(context.tools !== undefined && {
|
|
@@ -61,13 +57,20 @@ const useStatewireThread = (
|
|
|
61
57
|
),
|
|
62
58
|
);
|
|
63
59
|
|
|
64
|
-
const {
|
|
60
|
+
const {
|
|
61
|
+
state: transportState,
|
|
62
|
+
commands,
|
|
63
|
+
connection,
|
|
64
|
+
setContext,
|
|
65
|
+
} = useStatewire<unknown, AnyCommands>({
|
|
65
66
|
transport: options.transport,
|
|
66
67
|
onCommandChange: (update) => {
|
|
67
68
|
if (update.status === "acked" || update.status === "settled")
|
|
68
69
|
retire(update.params[0]);
|
|
69
70
|
},
|
|
70
71
|
});
|
|
72
|
+
const attached = transportState !== undefined;
|
|
73
|
+
const state = attached ? transportState : options.initialState;
|
|
71
74
|
|
|
72
75
|
const clientRef = useAssistantClientRef();
|
|
73
76
|
const setContextRef = useRef(setContext);
|
|
@@ -111,21 +114,58 @@ const useStatewireThread = (
|
|
|
111
114
|
(): StatewireThread.ConnectionMetadata => ({
|
|
112
115
|
pendingCommands: [...pending],
|
|
113
116
|
isSending: pending.length > 0,
|
|
117
|
+
connection,
|
|
114
118
|
}),
|
|
115
|
-
[pending],
|
|
119
|
+
[pending, connection],
|
|
116
120
|
);
|
|
117
121
|
const converted = useMemo(
|
|
118
|
-
() =>
|
|
122
|
+
() => converter(state, metadata),
|
|
119
123
|
[converter, state, metadata],
|
|
120
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
|
+
);
|
|
121
160
|
|
|
122
161
|
const extras = useMemo(
|
|
123
162
|
(): AssistantTransportExtras => ({
|
|
124
163
|
[symbolAssistantTransportExtras]: true,
|
|
125
164
|
sendCommand: dispatch,
|
|
165
|
+
reconnect: connection.reconnect,
|
|
126
166
|
state,
|
|
127
167
|
}),
|
|
128
|
-
[dispatch, state],
|
|
168
|
+
[dispatch, connection.reconnect, state],
|
|
129
169
|
);
|
|
130
170
|
|
|
131
171
|
const handleAppend = (message: AppendMessage) => {
|
|
@@ -138,14 +178,27 @@ const useStatewireThread = (
|
|
|
138
178
|
ExternalThread({
|
|
139
179
|
messages: converted.messages as readonly ExternalThreadMessage[],
|
|
140
180
|
isRunning: converted.isRunning,
|
|
141
|
-
isLoading:
|
|
181
|
+
isLoading: !attached,
|
|
142
182
|
state: converted.state,
|
|
143
183
|
extras,
|
|
144
184
|
attachmentAdapter: options.adapters?.attachments,
|
|
145
185
|
onNew: handleAppend,
|
|
186
|
+
...(queue && { queue }),
|
|
146
187
|
...(options.capabilities?.edit && { onEdit: handleAppend }),
|
|
147
188
|
onCancel: () => {
|
|
148
|
-
|
|
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) => {
|
|
149
202
|
latest.current.onError?.(error);
|
|
150
203
|
});
|
|
151
204
|
},
|
|
@@ -161,15 +214,29 @@ export const StatewireThread = <T>(
|
|
|
161
214
|
export namespace StatewireThread {
|
|
162
215
|
export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
|
|
163
216
|
|
|
217
|
+
export type QueueItem = {
|
|
218
|
+
readonly id: string;
|
|
219
|
+
readonly prompt: string;
|
|
220
|
+
};
|
|
221
|
+
|
|
164
222
|
export type State = {
|
|
165
223
|
readonly messages: readonly ThreadMessage[];
|
|
166
224
|
readonly state?: ReadonlyJSONValue;
|
|
167
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[];
|
|
168
233
|
};
|
|
169
234
|
|
|
170
235
|
export type ConnectionMetadata = {
|
|
171
236
|
pendingCommands: AssistantTransportCommand[];
|
|
172
237
|
isSending: boolean;
|
|
238
|
+
/** Statewire connection status; local transports are always `live`. */
|
|
239
|
+
connection: StatewireClient.ConnectionState;
|
|
173
240
|
};
|
|
174
241
|
|
|
175
242
|
export type StateConverter<T> = (
|
|
@@ -177,8 +244,18 @@ export namespace StatewireThread {
|
|
|
177
244
|
connectionMetadata: ConnectionMetadata,
|
|
178
245
|
) => State;
|
|
179
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
|
+
|
|
180
256
|
export type Options<T> = {
|
|
181
257
|
transport: Transport<T>;
|
|
258
|
+
initialState: T;
|
|
182
259
|
converter: StateConverter<T>;
|
|
183
260
|
/**
|
|
184
261
|
* "command-send" mirrors the client's ambient model context (system,
|
|
@@ -186,6 +263,8 @@ export namespace StatewireThread {
|
|
|
186
263
|
* on connect and whenever it changes. Requires a remote transport.
|
|
187
264
|
*/
|
|
188
265
|
contextSync?: "command-send" | undefined;
|
|
266
|
+
/** Supplies the `cancel` command's payload; omitted, cancel sends no payload. */
|
|
267
|
+
cancelPayload?: (() => CancelPayload) | undefined;
|
|
189
268
|
onError?: ((error: Error) => void) | undefined;
|
|
190
269
|
capabilities?:
|
|
191
270
|
| {
|
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;
|
package/src/transport.test.tsx
CHANGED
|
@@ -1782,13 +1782,16 @@ describe("AssistantTransportThread", () => {
|
|
|
1782
1782
|
it("sends threadId null when the thread list item lookup throws", async () => {
|
|
1783
1783
|
const fetchMock = installFetch();
|
|
1784
1784
|
|
|
1785
|
+
const brokenItem = {
|
|
1786
|
+
getState: () => {
|
|
1787
|
+
throw new Error("no current item");
|
|
1788
|
+
},
|
|
1789
|
+
};
|
|
1785
1790
|
const BrokenThreads = resource(
|
|
1786
1791
|
() =>
|
|
1787
1792
|
({
|
|
1788
1793
|
getState: () => ({}),
|
|
1789
|
-
item: () =>
|
|
1790
|
-
throw new Error("no current item");
|
|
1791
|
-
},
|
|
1794
|
+
item: () => brokenItem,
|
|
1792
1795
|
}) as never,
|
|
1793
1796
|
);
|
|
1794
1797
|
|
|
@@ -1996,3 +1999,142 @@ describe("reload", () => {
|
|
|
1996
1999
|
expect(fetchMock.requests[2]!.body.parentId).toBe("m1");
|
|
1997
2000
|
});
|
|
1998
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?:
|