Open History to see the last commit
1/**
2 * Mock Text Adapter for deterministic testing
3 *
4 * This adapter returns predetermined responses based on a response sequence,
5 * allowing for fully deterministic testing of the snippets system.
6 */
7
8import type {
9 AdapterYieldChunk,
10 DefaultMessageMetadataByModality,
11} from '@tanstack/ai'
12
13/**
14 * A predetermined response that the mock adapter will return
15 */
16export interface MockResponse {
17 /**
18 * Text content to stream (optional)
19 */
20 content?: string
21
22 /**
23 * Tool calls to make (optional)
24 */
25 toolCalls?: Array<{
26 id: string
27 name: string
28 arguments: Record<string, unknown>
29 }>
30}
31
32/**
33 * Configuration for the mock adapter
34 */
35export interface MockAdapterConfig {
36 /**
37 * Sequence of responses to return.
38 * The adapter will return responses in order, cycling back to the start if needed.
39 */
40 responses: Array<MockResponse>
41
42 /**
43 * Optional callback when a response is used
44 */
45 onResponse?: (index: number, response: MockResponse) => void
46}
47
48/**
49 * Create a mock text adapter for testing
50 */
51export function createMockTextAdapter(config: MockAdapterConfig) {
52 let responseIndex = 0
53
54 const adapter = {
55 kind: 'text' as const,
56 name: 'mock',
57 model: 'mock-model',
58
59 // Type-only property for compatibility
60 '~types': {} as {
61 providerOptions: Record<string, unknown>
62 inputModalities: readonly ['text']
63 messageMetadataByModality: DefaultMessageMetadataByModality
64 },
65
66 async *chatStream(): AsyncIterable<AdapterYieldChunk> {
67 const response = config.responses[responseIndex % config.responses.length]
68 if (!response) {
69 throw new Error('No responses configured for mock adapter')
70 }
71
72 config.onResponse?.(responseIndex, response)
73 responseIndex++
74
75 const timestamp = Date.now()
76 const id = `mock-${timestamp}`
77
78 // Yield tool calls first if present
79 if (response.toolCalls && response.toolCalls.length > 0) {
80 for (let i = 0; i < response.toolCalls.length; i++) {
81 const toolCall = response.toolCalls[i]!
82 const toolCallChunk = {
83 type: 'tool_call',
84 id,
85 model: 'mock-model',
86 timestamp,
87 index: i,
88 toolCall: {
89 id: toolCall.id,
90 type: 'function',
91 function: {
92 name: toolCall.name,
93 arguments: JSON.stringify(toolCall.arguments),
94 },
95 },
96 }
97 yield toolCallChunk as AdapterYieldChunk
98 }
99
100 // Done with tool_calls finish reason
101 const doneChunk = {
102 type: 'done',
103 id,
104 model: 'mock-model',
105 timestamp,
106 finishReason: 'tool_calls',
107 usage: {
108 promptTokens: 10,
109 completionTokens: 10,
110 totalTokens: 20,
111 },
112 }
113 yield doneChunk as AdapterYieldChunk
114 return
115 }
116
117 // Stream content if present
118 if (response.content) {
119 // Stream content character by character for realistic simulation
120 let accumulated = ''
121 for (const char of response.content) {
122 accumulated += char
123 const contentChunk = {
124 type: 'content',
125 id,
126 model: 'mock-model',
127 timestamp,
128 delta: char,
129 content: accumulated,
130 role: 'assistant',
131 }
132 yield contentChunk as AdapterYieldChunk
133 }
134 }
135
136 // Done chunk
137 const doneChunk = {
138 type: 'done',
139 id,
140 model: 'mock-model',
141 timestamp,
142 finishReason: 'stop',
143 usage: {
144 promptTokens: 10,
145 completionTokens: response.content?.length || 0,
146 totalTokens: 10 + (response.content?.length || 0),
147 },
148 }
149 yield doneChunk as AdapterYieldChunk
150 },
151
152 async structuredOutput() {
153 throw new Error('Mock adapter does not support structured output')
154 },
155
156 /**
157 * Reset the response index to start from the beginning
158 */
159 reset() {
160 responseIndex = 0
161 },
162
163 /**
164 * Get the current response index
165 */
166 getResponseIndex() {
167 return responseIndex
168 },
169
170 /**
171 * Set the response index to a specific value
172 */
173 setResponseIndex(index: number) {
174 responseIndex = index
175 },
176 }
177
178 return adapter
179}
180
181/**
182 * Helper to create a text-only response
183 */
184export function textResponse(content: string): MockResponse {
185 return { content }
186}
187
188/**
189 * Helper to create a tool call response
190 */
191export function toolCallResponse(
192 toolCalls: Array<{
193 id: string
194 name: string
195 arguments: Record<string, unknown>
196 }>,
197): MockResponse {
198 return { toolCalls }
199}
200
201/**
202 * Helper to create a single tool call response
203 */
204export function singleToolCall(
205 name: string,
206 args: Record<string, unknown>,
207 id?: string,
208): MockResponse {
209 return {
210 toolCalls: [
211 {
212 id: id || `call_${name}_${Date.now()}`,
213 name,
214 arguments: args,
215 },
216 ],
217 }
218}