@assistant-ui/react-statewire 0.0.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/LICENSE +21 -0
- package/dist/AssistantTransportThread.d.ts +15 -0
- package/dist/AssistantTransportThread.d.ts.map +1 -0
- package/dist/AssistantTransportThread.js +172 -0
- package/dist/AssistantTransportThread.js.map +1 -0
- package/dist/hooks.d.ts +8 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +26 -0
- package/dist/hooks.js.map +1 -0
- package/dist/host.d.ts +41 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +294 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/replayBoundaryStream.d.ts +6 -0
- package/dist/replayBoundaryStream.d.ts.map +1 -0
- package/dist/replayBoundaryStream.js +47 -0
- package/dist/replayBoundaryStream.js.map +1 -0
- package/dist/stateOps.d.ts +10 -0
- package/dist/stateOps.d.ts.map +1 -0
- package/dist/stateOps.js +106 -0
- package/dist/stateOps.js.map +1 -0
- package/dist/types.d.ts +99 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/package.json +54 -0
- package/src/AssistantTransportThread.ts +295 -0
- package/src/__tests__/testHelpers.tsx +243 -0
- package/src/athena.e2e.test.tsx +628 -0
- package/src/hooks.ts +28 -0
- package/src/host.ts +413 -0
- package/src/index.ts +23 -0
- package/src/legacy-diff.test.tsx +581 -0
- package/src/replayBoundaryStream.ts +65 -0
- package/src/stateOps.test.ts +125 -0
- package/src/stateOps.ts +122 -0
- package/src/transport.test.tsx +1858 -0
- package/src/types.ts +140 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
|
+
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
|
+
import { ExternalThread } from "@assistant-ui/react";
|
|
5
|
+
import type { ExternalThreadMessage } from "@assistant-ui/react";
|
|
6
|
+
import {
|
|
7
|
+
forwardTransformScopes,
|
|
8
|
+
useAssistantClientRef,
|
|
9
|
+
} from "@assistant-ui/store";
|
|
10
|
+
import type { ClientOutput } from "@assistant-ui/store";
|
|
11
|
+
import type {
|
|
12
|
+
AddToolResultOptions,
|
|
13
|
+
AppendMessage,
|
|
14
|
+
ResumeToolCallOptions,
|
|
15
|
+
ThreadMessage,
|
|
16
|
+
ToolExecutionStatus,
|
|
17
|
+
} from "@assistant-ui/core";
|
|
18
|
+
import { ToolInvocationTracker } from "@assistant-ui/core/internal";
|
|
19
|
+
import type { ReadonlyJSONObject } from "assistant-stream/utils";
|
|
20
|
+
import { useStatewire } from "statewire";
|
|
21
|
+
import { AssistantTransportHost } from "./host";
|
|
22
|
+
import type {
|
|
23
|
+
AssistantTransportHostCommands,
|
|
24
|
+
AssistantTransportHostState,
|
|
25
|
+
HostQueueCell,
|
|
26
|
+
HostRunContext,
|
|
27
|
+
SendOptions,
|
|
28
|
+
} from "./host";
|
|
29
|
+
import type {
|
|
30
|
+
AddMessageCommand,
|
|
31
|
+
AddToolResultCommand,
|
|
32
|
+
AssistantTransportCommand,
|
|
33
|
+
AssistantTransportOptions,
|
|
34
|
+
UserMessagePart,
|
|
35
|
+
} from "./types";
|
|
36
|
+
|
|
37
|
+
const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
|
|
38
|
+
|
|
39
|
+
export const symbolAssistantTransportExtras = Symbol(
|
|
40
|
+
"assistant-transport-extras",
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
export type AssistantTransportExtras = {
|
|
44
|
+
[symbolAssistantTransportExtras]: true;
|
|
45
|
+
sendCommand: (command: AssistantTransportCommand) => void;
|
|
46
|
+
state: unknown;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const asAssistantTransportExtras = (
|
|
50
|
+
extras: unknown,
|
|
51
|
+
): AssistantTransportExtras => {
|
|
52
|
+
if (
|
|
53
|
+
typeof extras !== "object" ||
|
|
54
|
+
extras == null ||
|
|
55
|
+
!(symbolAssistantTransportExtras in extras)
|
|
56
|
+
)
|
|
57
|
+
throw new Error(
|
|
58
|
+
"This method can only be called when you are using AssistantTransportThread",
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
return extras as AssistantTransportExtras;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const convertAppendMessageToCommand = (
|
|
65
|
+
message: AppendMessage,
|
|
66
|
+
): AddMessageCommand | null => {
|
|
67
|
+
if (message.role !== "user")
|
|
68
|
+
throw new Error("Only user messages are supported");
|
|
69
|
+
|
|
70
|
+
const parts: UserMessagePart[] = [];
|
|
71
|
+
const content = [
|
|
72
|
+
...message.content,
|
|
73
|
+
...(message.attachments?.flatMap((a) => a.content) ?? []),
|
|
74
|
+
];
|
|
75
|
+
for (const contentPart of content) {
|
|
76
|
+
if (contentPart.type === "text") {
|
|
77
|
+
parts.push({ type: "text", text: contentPart.text });
|
|
78
|
+
} else if (contentPart.type === "image") {
|
|
79
|
+
parts.push({ type: "image", image: contentPart.image });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (parts.length === 0) return null;
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
type: "add-message",
|
|
87
|
+
message: {
|
|
88
|
+
role: "user",
|
|
89
|
+
parts,
|
|
90
|
+
},
|
|
91
|
+
parentId: message.parentId,
|
|
92
|
+
sourceId: message.sourceId,
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const messagesContainToolCall = (
|
|
97
|
+
messages: readonly ThreadMessage[],
|
|
98
|
+
toolCallId: string,
|
|
99
|
+
): boolean =>
|
|
100
|
+
messages.some((message) =>
|
|
101
|
+
message.content.some(
|
|
102
|
+
(part) =>
|
|
103
|
+
part.type === "tool-call" &&
|
|
104
|
+
(part.toolCallId === toolCallId ||
|
|
105
|
+
(part.messages !== undefined &&
|
|
106
|
+
messagesContainToolCall(part.messages, toolCallId))),
|
|
107
|
+
),
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
const useAssistantTransportThread = (
|
|
111
|
+
options: AssistantTransportOptions<any>,
|
|
112
|
+
): ClientOutput<"thread"> => {
|
|
113
|
+
const clientRef = useAssistantClientRef();
|
|
114
|
+
const [getRunContext] = useState(() => (): HostRunContext => {
|
|
115
|
+
const aui = clientRef.current ?? clientRef.parent;
|
|
116
|
+
// legacy parity: a threadListItem throw must not kill the run
|
|
117
|
+
let threadId: string | null = null;
|
|
118
|
+
try {
|
|
119
|
+
threadId = aui.threadListItem().getState().remoteId ?? null;
|
|
120
|
+
} catch {}
|
|
121
|
+
return {
|
|
122
|
+
modelContext: aui.modelContext().getModelContext(),
|
|
123
|
+
threadId,
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
const [queueCell] = useState(
|
|
128
|
+
(): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),
|
|
129
|
+
);
|
|
130
|
+
const { state, commands } = useStatewire<
|
|
131
|
+
AssistantTransportHostState,
|
|
132
|
+
AssistantTransportHostCommands
|
|
133
|
+
>({
|
|
134
|
+
transport: AssistantTransportHost({ ...options, getRunContext, queueCell }),
|
|
135
|
+
});
|
|
136
|
+
const { agent: agentState, isSending, isReplaying } = state;
|
|
137
|
+
const queue = queueCell.current;
|
|
138
|
+
|
|
139
|
+
// the commands proxy is identity-stable across renders
|
|
140
|
+
const dispatch = (command: AssistantTransportCommand, opts?: SendOptions) => {
|
|
141
|
+
void commands.send(command, opts).catch(() => {});
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const [toolStatuses, setToolStatuses] =
|
|
145
|
+
useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);
|
|
146
|
+
|
|
147
|
+
const converted = useMemo(
|
|
148
|
+
() =>
|
|
149
|
+
options.converter(agentState, {
|
|
150
|
+
pendingCommands: [...queue.inTransit, ...queue.queued],
|
|
151
|
+
isSending,
|
|
152
|
+
toolStatuses,
|
|
153
|
+
}),
|
|
154
|
+
[options.converter, agentState, queue, isSending, toolStatuses],
|
|
155
|
+
);
|
|
156
|
+
const convertedRef = useRef(converted);
|
|
157
|
+
convertedRef.current = converted;
|
|
158
|
+
|
|
159
|
+
const [toolInvocations] = useState(
|
|
160
|
+
() =>
|
|
161
|
+
new ToolInvocationTracker(
|
|
162
|
+
() => {
|
|
163
|
+
const aui = clientRef.current ?? clientRef.parent;
|
|
164
|
+
return aui.modelContext().getModelContext().tools;
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
onResult: (command) => {
|
|
168
|
+
const messages = convertedRef.current
|
|
169
|
+
.messages as readonly ThreadMessage[];
|
|
170
|
+
if (!messagesContainToolCall(messages, command.toolCallId)) return;
|
|
171
|
+
dispatch(command);
|
|
172
|
+
},
|
|
173
|
+
onStatusesChange: (statuses) => {
|
|
174
|
+
setToolStatuses(
|
|
175
|
+
statuses.size === 0
|
|
176
|
+
? EMPTY_TOOL_STATUSES
|
|
177
|
+
: Object.fromEntries(statuses),
|
|
178
|
+
);
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
),
|
|
182
|
+
);
|
|
183
|
+
// dep-less by design: setState dedups identical snapshots internally
|
|
184
|
+
useEffect(() => {
|
|
185
|
+
toolInvocations.setState({
|
|
186
|
+
messages: converted.messages as readonly ThreadMessage[],
|
|
187
|
+
isRunning: converted.isRunning,
|
|
188
|
+
isLoading: isReplaying,
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
useEffect(
|
|
192
|
+
() => () => {
|
|
193
|
+
toolInvocations.reset();
|
|
194
|
+
},
|
|
195
|
+
[toolInvocations],
|
|
196
|
+
);
|
|
197
|
+
|
|
198
|
+
const extras = useMemo(
|
|
199
|
+
(): AssistantTransportExtras => ({
|
|
200
|
+
[symbolAssistantTransportExtras]: true,
|
|
201
|
+
sendCommand: dispatch,
|
|
202
|
+
state: agentState,
|
|
203
|
+
}),
|
|
204
|
+
[commands, agentState],
|
|
205
|
+
);
|
|
206
|
+
|
|
207
|
+
const handleAppend = (message: AppendMessage) => {
|
|
208
|
+
const startRun = message.startRun ?? message.role === "user";
|
|
209
|
+
const command = convertAppendMessageToCommand(message);
|
|
210
|
+
void commands.setParentId(message.parentId).catch(() => {});
|
|
211
|
+
|
|
212
|
+
const send = () => {
|
|
213
|
+
if (!command) return;
|
|
214
|
+
dispatch(command, { schedule: startRun });
|
|
215
|
+
};
|
|
216
|
+
if (startRun) {
|
|
217
|
+
// abort in-flight tool executions so their late results cannot race the new turn
|
|
218
|
+
void toolInvocations.abort().then(send);
|
|
219
|
+
} else {
|
|
220
|
+
send();
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
return useResource(
|
|
225
|
+
ExternalThread({
|
|
226
|
+
messages: converted.messages as readonly ExternalThreadMessage[],
|
|
227
|
+
isRunning: converted.isRunning,
|
|
228
|
+
isLoading: isReplaying,
|
|
229
|
+
state: converted.state,
|
|
230
|
+
extras,
|
|
231
|
+
attachmentAdapter: options.adapters?.attachments,
|
|
232
|
+
onNew: handleAppend,
|
|
233
|
+
...(options.capabilities?.edit && { onEdit: handleAppend }),
|
|
234
|
+
...(queue.queued.length > 0 && {
|
|
235
|
+
onReload: (parentId: string | null) => {
|
|
236
|
+
void toolInvocations.abort().then(() => {
|
|
237
|
+
void commands.reload(parentId).catch(() => {});
|
|
238
|
+
});
|
|
239
|
+
},
|
|
240
|
+
}),
|
|
241
|
+
onCancel: () => {
|
|
242
|
+
void toolInvocations.abort();
|
|
243
|
+
void commands.cancel().catch(() => {});
|
|
244
|
+
},
|
|
245
|
+
onResume: () => {
|
|
246
|
+
if (!options.resumeApi)
|
|
247
|
+
throw new Error("Must pass resumeApi to options to resume runs");
|
|
248
|
+
void commands.resume().catch(() => {});
|
|
249
|
+
},
|
|
250
|
+
onAddToolResult: (toolOptions: AddToolResultOptions) => {
|
|
251
|
+
const command: AddToolResultCommand = {
|
|
252
|
+
type: "add-tool-result",
|
|
253
|
+
toolCallId: toolOptions.toolCallId,
|
|
254
|
+
result: toolOptions.result as ReadonlyJSONObject,
|
|
255
|
+
toolName: toolOptions.toolName,
|
|
256
|
+
isError: toolOptions.isError,
|
|
257
|
+
...(toolOptions.artifact && { artifact: toolOptions.artifact }),
|
|
258
|
+
...(toolOptions.modelContent !== undefined && {
|
|
259
|
+
modelContent: toolOptions.modelContent,
|
|
260
|
+
}),
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
dispatch(command);
|
|
264
|
+
},
|
|
265
|
+
onResumeToolCall: ({ toolCallId, payload }: ResumeToolCallOptions) => {
|
|
266
|
+
if (!toolInvocations.resume(toolCallId, payload))
|
|
267
|
+
throw new Error(`Tool call ${toolCallId} is not waiting for resume.`);
|
|
268
|
+
},
|
|
269
|
+
onLoadExternalState: (imported: unknown) => {
|
|
270
|
+
void commands.importState(imported).catch(() => {});
|
|
271
|
+
// reset() aborts tools before React re-renders — gate their late results against the imported state
|
|
272
|
+
convertedRef.current = options.converter(imported, {
|
|
273
|
+
pendingCommands: [...queue.inTransit, ...queue.queued],
|
|
274
|
+
isSending,
|
|
275
|
+
toolStatuses: EMPTY_TOOL_STATUSES,
|
|
276
|
+
});
|
|
277
|
+
toolInvocations.reset();
|
|
278
|
+
setToolStatuses(EMPTY_TOOL_STATUSES);
|
|
279
|
+
},
|
|
280
|
+
}),
|
|
281
|
+
);
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
export const AssistantTransportThread = <T>(
|
|
285
|
+
options: AssistantTransportOptions<T>,
|
|
286
|
+
): ResourceElement<ClientOutput<"thread">> =>
|
|
287
|
+
resource(useAssistantTransportThread)(
|
|
288
|
+
options as AssistantTransportOptions<any>,
|
|
289
|
+
);
|
|
290
|
+
|
|
291
|
+
// Scope transforms are keyed by the underlying hook, not the resource wrapper.
|
|
292
|
+
forwardTransformScopes(
|
|
293
|
+
useAssistantTransportThread,
|
|
294
|
+
ExternalThread(undefined as never).hook,
|
|
295
|
+
);
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { render } from "@testing-library/react";
|
|
2
|
+
import type { FC, ReactElement, ReactNode } from "react";
|
|
3
|
+
import { vi } from "vitest";
|
|
4
|
+
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
5
|
+
import type { ExternalThreadMessage } from "@assistant-ui/react";
|
|
6
|
+
import {
|
|
7
|
+
asAssistantTransportExtras,
|
|
8
|
+
AssistantTransportThread,
|
|
9
|
+
} from "../AssistantTransportThread";
|
|
10
|
+
import type {
|
|
11
|
+
AssistantTransportCommand,
|
|
12
|
+
AssistantTransportConnectionMetadata,
|
|
13
|
+
AssistantTransportOptions,
|
|
14
|
+
AssistantTransportStateConverter,
|
|
15
|
+
} from "../types";
|
|
16
|
+
|
|
17
|
+
export type TestState = {
|
|
18
|
+
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
19
|
+
todos?: string[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const INITIAL_STATE: TestState = { messages: [] };
|
|
23
|
+
|
|
24
|
+
export const toThreadMessage = (m: {
|
|
25
|
+
id: string;
|
|
26
|
+
role: "user" | "assistant";
|
|
27
|
+
text: string;
|
|
28
|
+
}): ExternalThreadMessage =>
|
|
29
|
+
({
|
|
30
|
+
id: m.id,
|
|
31
|
+
role: m.role,
|
|
32
|
+
createdAt: new Date(0),
|
|
33
|
+
content: [{ type: "text", text: m.text }],
|
|
34
|
+
attachments: [],
|
|
35
|
+
metadata: { custom: {} },
|
|
36
|
+
...(m.role === "assistant" && {
|
|
37
|
+
status: { type: "complete", reason: "stop" },
|
|
38
|
+
}),
|
|
39
|
+
}) as unknown as ExternalThreadMessage;
|
|
40
|
+
|
|
41
|
+
export const defaultConverter: AssistantTransportStateConverter<TestState> = (
|
|
42
|
+
state,
|
|
43
|
+
meta,
|
|
44
|
+
) => ({
|
|
45
|
+
messages: [
|
|
46
|
+
...state.messages.map(toThreadMessage),
|
|
47
|
+
...meta.pendingCommands.flatMap((c, i) =>
|
|
48
|
+
c.type === "add-message" && c.message.role === "user"
|
|
49
|
+
? [
|
|
50
|
+
toThreadMessage({
|
|
51
|
+
id: `optimistic-${i}`,
|
|
52
|
+
role: "user",
|
|
53
|
+
text: c.message.parts.find((p) => p.type === "text")?.text ?? "",
|
|
54
|
+
}),
|
|
55
|
+
]
|
|
56
|
+
: [],
|
|
57
|
+
),
|
|
58
|
+
],
|
|
59
|
+
isRunning: meta.isSending,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
export const sseEvent = (chunk: unknown) =>
|
|
63
|
+
`data: ${JSON.stringify(chunk)}\n\n`;
|
|
64
|
+
export const DONE = "data: [DONE]\n\n";
|
|
65
|
+
|
|
66
|
+
export const createStreamResponse = (init?: {
|
|
67
|
+
status?: number;
|
|
68
|
+
headers?: Record<string, string>;
|
|
69
|
+
}) => {
|
|
70
|
+
const encoder = new TextEncoder();
|
|
71
|
+
let controller!: ReadableStreamDefaultController<Uint8Array>;
|
|
72
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
73
|
+
start(c) {
|
|
74
|
+
controller = c;
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
return {
|
|
78
|
+
response: new Response(stream, {
|
|
79
|
+
status: init?.status ?? 200,
|
|
80
|
+
headers: init?.headers ?? {},
|
|
81
|
+
}),
|
|
82
|
+
push: (text: string) => controller.enqueue(encoder.encode(text)),
|
|
83
|
+
pushBytes: (bytes: Uint8Array) => controller.enqueue(bytes),
|
|
84
|
+
emit: (chunk: unknown) =>
|
|
85
|
+
controller.enqueue(encoder.encode(sseEvent(chunk))),
|
|
86
|
+
done: () => {
|
|
87
|
+
controller.enqueue(encoder.encode(DONE));
|
|
88
|
+
controller.close();
|
|
89
|
+
},
|
|
90
|
+
close: () => controller.close(),
|
|
91
|
+
error: (err: unknown) => controller.error(err),
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export type StreamResponse = ReturnType<typeof createStreamResponse>;
|
|
96
|
+
|
|
97
|
+
export type RecordedRequest = {
|
|
98
|
+
url: string;
|
|
99
|
+
init: RequestInit;
|
|
100
|
+
body: Record<string, any>;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export const installFetch = () => {
|
|
104
|
+
const requests: RecordedRequest[] = [];
|
|
105
|
+
let handler: (req: RecordedRequest) => Response | Promise<Response> = () => {
|
|
106
|
+
const server = createStreamResponse();
|
|
107
|
+
server.done();
|
|
108
|
+
return server.response;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
vi.stubGlobal(
|
|
112
|
+
"fetch",
|
|
113
|
+
async (url: RequestInfo | URL, init: RequestInit = {}) => {
|
|
114
|
+
const request: RecordedRequest = {
|
|
115
|
+
url: String(url),
|
|
116
|
+
init,
|
|
117
|
+
body: JSON.parse(init.body as string),
|
|
118
|
+
};
|
|
119
|
+
requests.push(request);
|
|
120
|
+
return handler(request);
|
|
121
|
+
},
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
requests,
|
|
126
|
+
setHandler: (h: typeof handler) => {
|
|
127
|
+
handler = h;
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
export const abortableStream = (init: RequestInit) => {
|
|
133
|
+
const server = createStreamResponse();
|
|
134
|
+
init.signal?.addEventListener("abort", () => {
|
|
135
|
+
server.error(new DOMException("The operation was aborted.", "AbortError"));
|
|
136
|
+
});
|
|
137
|
+
return server;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export const mountThread = (
|
|
141
|
+
options?: Partial<AssistantTransportOptions<TestState>>,
|
|
142
|
+
mountOpts?: {
|
|
143
|
+
wrap?: (node: ReactElement) => ReactElement;
|
|
144
|
+
children?: ReactNode;
|
|
145
|
+
},
|
|
146
|
+
) => {
|
|
147
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
148
|
+
const Capture: FC = () => {
|
|
149
|
+
captured.aui = useAui();
|
|
150
|
+
return null;
|
|
151
|
+
};
|
|
152
|
+
const App: FC = () => {
|
|
153
|
+
const aui = useAui({
|
|
154
|
+
thread: AssistantTransportThread<TestState>({
|
|
155
|
+
initialState: INITIAL_STATE,
|
|
156
|
+
api: "https://example.com/api",
|
|
157
|
+
headers: {},
|
|
158
|
+
converter: defaultConverter,
|
|
159
|
+
protocol: "assistant-transport",
|
|
160
|
+
...options,
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
return (
|
|
164
|
+
<AuiProvider value={aui}>
|
|
165
|
+
<Capture />
|
|
166
|
+
{mountOpts?.children}
|
|
167
|
+
</AuiProvider>
|
|
168
|
+
);
|
|
169
|
+
};
|
|
170
|
+
const node = <App />;
|
|
171
|
+
const utils = render(mountOpts?.wrap ? mountOpts.wrap(node) : node);
|
|
172
|
+
return { aui: () => captured.aui!, ...utils };
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
export const sendCommand = (
|
|
176
|
+
aui: () => ReturnType<typeof useAui>,
|
|
177
|
+
command: AssistantTransportCommand,
|
|
178
|
+
) =>
|
|
179
|
+
asAssistantTransportExtras(aui().thread().getState().extras).sendCommand(
|
|
180
|
+
command,
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
export const threadTexts = (aui: () => ReturnType<typeof useAui>) =>
|
|
184
|
+
aui()
|
|
185
|
+
.thread()
|
|
186
|
+
.getState()
|
|
187
|
+
.messages.map((m) =>
|
|
188
|
+
m.parts.flatMap((p) => (p.type === "text" ? [p.text] : [])).join(""),
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
export const toolCallConverter = (
|
|
192
|
+
metas: AssistantTransportConnectionMetadata[],
|
|
193
|
+
): AssistantTransportStateConverter<TestState> => {
|
|
194
|
+
type ToolCallState = TestState & {
|
|
195
|
+
toolCall?: { id: string; name: string; argsText: string };
|
|
196
|
+
};
|
|
197
|
+
return (state, meta) => {
|
|
198
|
+
metas.push(meta);
|
|
199
|
+
const base = defaultConverter(state, meta);
|
|
200
|
+
const toolCall = (state as ToolCallState).toolCall;
|
|
201
|
+
if (!toolCall) return base;
|
|
202
|
+
return {
|
|
203
|
+
...base,
|
|
204
|
+
messages: [
|
|
205
|
+
...base.messages,
|
|
206
|
+
{
|
|
207
|
+
id: "a-tool",
|
|
208
|
+
role: "assistant",
|
|
209
|
+
createdAt: new Date(0),
|
|
210
|
+
content: [
|
|
211
|
+
{
|
|
212
|
+
type: "tool-call",
|
|
213
|
+
toolCallId: toolCall.id,
|
|
214
|
+
toolName: toolCall.name,
|
|
215
|
+
args: JSON.parse(toolCall.argsText),
|
|
216
|
+
argsText: toolCall.argsText,
|
|
217
|
+
},
|
|
218
|
+
],
|
|
219
|
+
attachments: [],
|
|
220
|
+
metadata: { custom: {} },
|
|
221
|
+
status: { type: "requires-action", reason: "tool-call" },
|
|
222
|
+
} as unknown as ExternalThreadMessage,
|
|
223
|
+
],
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
export const emitToolCall = (server: StreamResponse) => {
|
|
229
|
+
server.emit({
|
|
230
|
+
type: "update-state",
|
|
231
|
+
operations: [
|
|
232
|
+
{
|
|
233
|
+
type: "set",
|
|
234
|
+
path: ["toolCall"],
|
|
235
|
+
value: { id: "tc1", name: "probe_tool", argsText: '{"x":1}' },
|
|
236
|
+
},
|
|
237
|
+
],
|
|
238
|
+
});
|
|
239
|
+
server.done();
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export const allCommands = (requests: RecordedRequest[]) =>
|
|
243
|
+
requests.flatMap((r) => r.body.commands as AssistantTransportCommand[]);
|