Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

test-utils.ts

454 lines10.4 KB

1import { vi } from 'vitest'
2import { withTanstackMetadata } from '@tanstack/ai/client'
3import type {
4 ConnectConnectionAdapter,
5 SubscribeConnectionAdapter,
6} from '../src/connection-adapters'
7import type { ModelMessage, StreamChunk } from '@tanstack/ai/client'
8import type { ChatClientPersistence, UIMessage } from '../src/types'
9​
10function runFinishedChunk(options: {
11 runId: string
12 threadId: string
13 finishReason: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null
14 model?: string
15}): StreamChunk {
16 return withTanstackMetadata(
17 {
18 type: 'RUN_FINISHED',
19 runId: options.runId,
20 threadId: options.threadId,
21 timestamp: Date.now(),
22 },
23 {
24 finishReason: options.finishReason,
25 ...(options.model !== undefined ? { model: options.model } : {}),
26 },
27 ) as StreamChunk
29​
30/**
31 * Build a minimal text {@link UIMessage} for tests.
32 */
33export function createUIMessage(
34 id: string,
35 text: string = 'hello',
36 role: UIMessage['role'] = 'user',
37): UIMessage {
38 return { id, role, parts: [{ type: 'text', content: text }] }
40​
41/** Mock message persistence adapter for ChatPersistor / ChatClient tests. */
42export function createMockPersistence(
43 initial?: Array<UIMessage> | null,
44): ChatClientPersistence {
45 return {
46 getItem: vi.fn(() => initial),
47 setItem: vi.fn(),
48 removeItem: vi.fn(),
49 }
51​
52/**
53 * Options for creating a mock connection adapter
54 */
55export interface MockConnectionAdapterOptions {
56 /**
57 * Chunks to yield from the stream
58 */
59 chunks?: Array<StreamChunk>
60​
61 /**
62 * Delay between chunks (in ms)
63 */
64 chunkDelay?: number
65​
66 /**
67 * Whether to throw an error
68 */
69 shouldError?: boolean
70​
71 /**
72 * Error to throw
73 */
74 error?: Error
75​
76 /**
77 * Callback when connect is called
78 */
79 onConnect?: (
80 messages: Array<ModelMessage> | Array<UIMessage>,
81 data?: Record<string, any>,
82 abortSignal?: AbortSignal,
83 ) => void
84​
85 /**
86 * Callback to check abort signal during streaming
87 */
88 onAbort?: (abortSignal: AbortSignal) => void
90​
91/**
92 * Create a mock connection adapter for testing
93 *
94 * @example
95 * ```typescript
96 * const adapter = createMockConnectionAdapter({
97 * chunks: [
98 * { type: "TEXT_MESSAGE_CONTENT", messageId: "1", timestamp: Date.now(), delta: "Hello" },
99 * { type: "RUN_FINISHED", runId: "run-1", timestamp: Date.now(), metadata: { tanstack: { finishReason: "stop" } } }
100 * ]
101 * });
102 * ```
103 */
104export function createMockConnectionAdapter(
105 options: MockConnectionAdapterOptions = {},
106): ConnectConnectionAdapter {
107 const {
108 chunks = [],
109 chunkDelay = 0,
110 shouldError = false,
111 error = new Error('Mock adapter error'),
112 onConnect,
113 onAbort,
114 } = options
115​
116 return {
117 async *connect(messages, data, abortSignal) {
118 if (onConnect) {
119 // Type assertion: messages can be ModelMessage[] or UIMessage[]
120 // Filter out system messages if present
121 const filteredMessages = (messages as any[]).filter(
122 (m: any) => !('role' in m) || m.role !== 'system',
123 )
124 onConnect(filteredMessages as any, data, abortSignal)
125 }
126​
127 if (shouldError) {
128 throw error
129 }
130​
131 for (const chunk of chunks) {
132 // Check abort signal before yielding
133 if (abortSignal?.aborted) {
134 if (onAbort) {
135 onAbort(abortSignal)
136 }
137 return
138 }
139​
140 if (chunkDelay > 0) {
141 await new Promise((resolve) => setTimeout(resolve, chunkDelay))
142 }
143​
144 // Check again after delay
145 if (abortSignal?.aborted) {
146 if (onAbort) {
147 onAbort(abortSignal)
148 }
149 return
150 }
151​
152 yield chunk
153 }
154 },
155 }
157​
158/**
159 * Subscribe/send adapter that tests can push chunks into at any time.
160 *
161 * A push between reading the queue and parking the waiter would lose the wake
162 * on a naive mock. This helper:
163 * - rechecks the queue after every yielded batch
164 * - rechecks again after parking the waiter, so a push in that window still
165 * wakes
166 */
167export function createPushableSubscribeConnection(): {
168 connection: SubscribeConnectionAdapter
169 push: (...chunks: Array<StreamChunk>) => void
170} {
171 let wake: (() => void) | null = null
172 const queue: Array<StreamChunk> = []
173​
174 const wakeWaiter = () => {
175 const resolve = wake
176 wake = null
177 resolve?.()
178 }
179​
180 const connection: SubscribeConnectionAdapter = {
181 subscribe: (signal?: AbortSignal) => {
182 return (async function* () {
183 while (!signal?.aborted) {
184 if (queue.length > 0) {
185 const batch = queue.splice(0)
186 for (const chunk of batch) {
187 yield chunk
188 }
189 continue
190 }
191 await new Promise<void>((resolve) => {
192 if (signal?.aborted) {
193 resolve()
194 return
195 }
196 wake = resolve
197 const onAbort = () => {
198 if (wake === resolve) {
199 wake = null
200 }
201 resolve()
202 }
203 signal?.addEventListener('abort', onAbort, { once: true })
204 if (queue.length > 0 || signal?.aborted) {
205 wakeWaiter()
206 }
207 })
208 }
209 })()
210 },
211 send: async () => {
212 wakeWaiter()
213 },
214 }
215​
216 const push = (...chunks: Array<StreamChunk>) => {
217 queue.push(...chunks)
218 wakeWaiter()
219 }
220​
221 return { connection, push }
223​
224/**
225 * Helper to create simple text content chunks (AG-UI format)
226 */
227export function createTextChunks(
228 text: string,
229 messageId: string = 'msg-1',
230 model: string = 'test',
231): Array<StreamChunk> {
232 const chunks: Array<StreamChunk> = []
233 const runId = `run-${messageId}`
234 const threadId = `thread-${messageId}`
235​
236 for (const delta of text) {
237 chunks.push({
238 type: 'TEXT_MESSAGE_CONTENT',
239 messageId,
240 timestamp: Date.now(),
241 delta,
242 } as StreamChunk)
243 }
244​
245 chunks.push(
246 runFinishedChunk({ runId, threadId, finishReason: 'stop', model }),
247 )
248​
249 return chunks
251​
252/**
253 * Helper to create custom event chunks
254 */
255export function createCustomEventChunks(
256 events: Array<{ name: string; value?: unknown }>,
257 model: string = 'test',
258): Array<StreamChunk> {
259 const chunks: Array<StreamChunk> = []
260​
261 for (const event of events) {
262 chunks.push({
263 type: 'CUSTOM',
264 timestamp: Date.now(),
265 name: event.name,
266 value: event.value,
267 } as StreamChunk)
268 }
269​
270 chunks.push(
271 runFinishedChunk({
272 runId: 'run-1',
273 threadId: 'thread-1',
274 finishReason: 'stop',
275 model,
276 }),
277 )
278​
279 return chunks
281​
282/**
283 * Helper to create tool call chunks (AG-UI format)
284 * Optionally includes tool-input-available chunks to trigger onToolCall
285 */
286export function createToolCallChunks(
287 toolCalls: Array<{ id: string; name: string; arguments: string }>,
288 messageId: string = 'msg-1',
289 model: string = 'test',
290 includeToolInputAvailable: boolean = true,
291): Array<StreamChunk> {
292 const chunks: Array<StreamChunk> = []
293 const runId = `run-${messageId}`
294​
295 for (let i = 0; i < toolCalls.length; i++) {
296 const toolCall = toolCalls[i]!
297​
298 chunks.push({
299 type: 'TOOL_CALL_START',
300 toolCallId: toolCall.id,
301 toolCallName: toolCall.name,
302 timestamp: Date.now(),
303 } as StreamChunk)
304​
305 chunks.push({
306 type: 'TOOL_CALL_ARGS',
307 toolCallId: toolCall.id,
308 timestamp: Date.now(),
309 delta: toolCall.arguments,
310 } as StreamChunk)
311​
312 // Add tool-input-available CUSTOM chunk if requested
313 if (includeToolInputAvailable) {
314 let parsedInput: any
315 try {
316 parsedInput = JSON.parse(toolCall.arguments)
317 } catch {
318 parsedInput = toolCall.arguments
319 }
320​
321 chunks.push({
322 type: 'CUSTOM',
323 timestamp: Date.now(),
324 name: 'tool-input-available',
325 value: {
326 toolCallId: toolCall.id,
327 toolName: toolCall.name,
328 input: parsedInput,
329 },
330 } as StreamChunk)
331 }
332 }
333​
334 chunks.push(
335 runFinishedChunk({
336 runId,
337 threadId: `thread-${messageId}`,
338 finishReason: 'tool_calls',
339 model,
340 }),
341 )
342​
343 return chunks
345​
346/**
347 * Helper to create tool call chunks with approval requests (AG-UI format)
348 * Tools will be in 'input-complete' state with pending approval
349 */
350export function createApprovalToolCallChunks(
351 toolCalls: Array<{
352 id: string
353 name: string
354 arguments: string
355 approvalId: string
356 }>,
357 messageId: string = 'msg-1',
358 model: string = 'test',
359): Array<StreamChunk> {
360 const chunks: Array<StreamChunk> = []
361 const runId = `run-${messageId}`
362​
363 for (let i = 0; i < toolCalls.length; i++) {
364 const toolCall = toolCalls[i]!
365​
366 chunks.push({
367 type: 'TOOL_CALL_START',
368 toolCallId: toolCall.id,
369 toolCallName: toolCall.name,
370 timestamp: Date.now(),
371 } as StreamChunk)
372​
373 chunks.push({
374 type: 'TOOL_CALL_ARGS',
375 toolCallId: toolCall.id,
376 timestamp: Date.now(),
377 delta: toolCall.arguments,
378 } as StreamChunk)
379​
380 chunks.push({
381 type: 'TOOL_CALL_END',
382 toolCallId: toolCall.id,
383 timestamp: Date.now(),
384 } as StreamChunk)
385​
386 chunks.push({
387 type: 'CUSTOM',
388 timestamp: Date.now(),
389 name: 'approval-requested',
390 value: {
391 toolCallId: toolCall.id,
392 toolName: toolCall.name,
393 input: JSON.parse(toolCall.arguments),
394 approval: { id: toolCall.approvalId, needsApproval: true },
395 },
396 } as StreamChunk)
397 }
398​
399 chunks.push(
400 runFinishedChunk({
401 runId,
402 threadId: `thread-${messageId}`,
403 finishReason: 'tool_calls',
404 model,
405 }),
406 )
407​
408 return chunks
410​
411/**
412 * Helper to create thinking chunks (AG-UI reasoning events)
413 */
414export function createThinkingChunks(
415 thinkingContent: string,
416 textContent: string = '',
417 messageId: string = 'msg-1',
418 model: string = 'test',
419): Array<StreamChunk> {
420 const chunks: Array<StreamChunk> = []
421 const runId = `run-${messageId}`
422 const reasoningId = `reasoning-${messageId}`
423​
424 for (const delta of thinkingContent) {
425 chunks.push({
426 type: 'REASONING_MESSAGE_CONTENT',
427 messageId: reasoningId,
428 timestamp: Date.now(),
429 delta,
430 } as StreamChunk)
431 }
432​
433 if (textContent) {
434 for (const delta of textContent) {
435 chunks.push({
436 type: 'TEXT_MESSAGE_CONTENT',
437 messageId,
438 timestamp: Date.now(),
439 delta,
440 } as StreamChunk)
441 }
442 }
443​
444 chunks.push(
445 runFinishedChunk({
446 runId,
447 threadId: `thread-${messageId}`,
448 finishReason: 'stop',
449 model,
450 }),
451 )
452​
453 return chunks