Open History to see the last commit
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
28}
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 }] }
39}
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 ? { messages: initial } : initial)),
47 setItem: vi.fn(),
48 removeItem: vi.fn(),
49 }
50}
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
89}
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 }
156}
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 }
222}
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
250}
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
280}
281
282/**
283 * Helper to create tool call chunks (AG-UI format). The RUN_FINISHED leaves
284 * the calls unanswered, so the client runs them (onToolCall).
285 */
286export function createToolCallChunks(
287 toolCalls: Array<{ id: string; name: string; arguments: string }>,
288 messageId: string = 'msg-1',
289 model: string = 'test',
290): Array<StreamChunk> {
291 const chunks: Array<StreamChunk> = []
292 const runId = `run-${messageId}`
293
294 for (let i = 0; i < toolCalls.length; i++) {
295 const toolCall = toolCalls[i]!
296
297 chunks.push({
298 type: 'TOOL_CALL_START',
299 toolCallId: toolCall.id,
300 toolCallName: toolCall.name,
301 timestamp: Date.now(),
302 } as StreamChunk)
303
304 chunks.push({
305 type: 'TOOL_CALL_ARGS',
306 toolCallId: toolCall.id,
307 timestamp: Date.now(),
308 delta: toolCall.arguments,
309 } as StreamChunk)
310 }
311
312 chunks.push(
313 runFinishedChunk({
314 runId,
315 threadId: `thread-${messageId}`,
316 finishReason: 'stop',
317 model,
318 }),
319 )
320
321 return chunks
322}
323
324/**
325 * Helper to create thinking chunks (AG-UI reasoning events)
326 */
327export function createThinkingChunks(
328 thinkingContent: string,
329 textContent: string = '',
330 messageId: string = 'msg-1',
331 model: string = 'test',
332): Array<StreamChunk> {
333 const chunks: Array<StreamChunk> = []
334 const runId = `run-${messageId}`
335 const reasoningId = `reasoning-${messageId}`
336
337 for (const delta of thinkingContent) {
338 chunks.push({
339 type: 'REASONING_MESSAGE_CONTENT',
340 messageId: reasoningId,
341 timestamp: Date.now(),
342 delta,
343 } as StreamChunk)
344 }
345
346 if (textContent) {
347 for (const delta of textContent) {
348 chunks.push({
349 type: 'TEXT_MESSAGE_CONTENT',
350 messageId,
351 timestamp: Date.now(),
352 delta,
353 } as StreamChunk)
354 }
355 }
356
357 chunks.push(
358 runFinishedChunk({
359 runId,
360 threadId: `thread-${messageId}`,
361 finishReason: 'stop',
362 model,
363 }),
364 )
365
366 return chunks
367}