Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { toolDefinition } from '@tanstack/ai'
3import { z } from 'zod'
4import { ChatClient } from '../src/chat-client'
5import { createTextChunks, createToolCallChunks } from './test-utils'
6import type { ConnectConnectionAdapter } from '../src/connection-adapters'
7
8const asyncCountSchema = z
9 .object({ count: z.number() })
10 .refine(async ({ count }) => count > 0, 'expected positive count')
11
12function findToolCallPart(client: ChatClient, toolCallId: string) {
13 for (const message of client.getMessages()) {
14 if (message.role !== 'assistant') {
15 continue
16 }
17
18 const part = message.parts.find(
19 (messagePart) =>
20 messagePart.type === 'tool-call' && messagePart.id === toolCallId,
21 )
22 if (part) {
23 return part
24 }
25 }
26
27 return undefined
28}
29
30function findToolResultPart(client: ChatClient, toolCallId: string) {
31 for (const message of client.getMessages()) {
32 if (message.role !== 'assistant') {
33 continue
34 }
35
36 const part = message.parts.find(
37 (messagePart) =>
38 messagePart.type === 'tool-result' &&
39 messagePart.toolCallId === toolCallId,
40 )
41 if (part) {
42 return part
43 }
44 }
45
46 return undefined
47}
48
49describe('ChatClient runtime context', () => {
50 it('passes client-local context to client tool execution without serializing it', async () => {
51 const firstChunks = createToolCallChunks([
52 { id: 'tc-client-context', name: 'read_client_context', arguments: '{}' },
53 ])
54 const secondChunks = createTextChunks('done', 'msg-2')
55 const outputs: Array<unknown> = []
56 const sentPayloads: Array<Record<string, unknown> | undefined> = []
57 const runContexts: Array<unknown> = []
58 let callIndex = 0
59
60 const adapter: ConnectConnectionAdapter = {
61 async *connect(_messages, data, abortSignal, runContext) {
62 sentPayloads.push(data)
63 runContexts.push(runContext)
64 const chunks = callIndex === 0 ? firstChunks : secondChunks
65 callIndex++
66 for (const chunk of chunks) {
67 if (abortSignal?.aborted) {
68 return
69 }
70 yield chunk
71 }
72 },
73 }
74
75 const tool = toolDefinition({
76 name: 'read_client_context',
77 description: 'Read client context',
78 }).client<{ localUserId: string; secretToken: string }>((_input, ctx) => {
79 outputs.push({
80 localUserId: ctx.context.localUserId,
81 tokenLength: ctx.context.secretToken.length,
82 })
83 return { ok: true }
84 })
85
86 const client = new ChatClient({
87 connection: adapter,
88 context: { localUserId: 'local-1', secretToken: 'secret-value' },
89 tools: [tool],
90 })
91
92 await client.sendMessage('use client context')
93
94 expect(outputs).toEqual([{ localUserId: 'local-1', tokenLength: 12 }])
95 expect(JSON.stringify(sentPayloads)).not.toContain('secret-value')
96 expect(JSON.stringify(runContexts)).not.toContain('secret-value')
97 expect(runContexts).toEqual([
98 expect.objectContaining({
99 forwardedProps: {},
100 }),
101 expect.objectContaining({
102 forwardedProps: {},
103 }),
104 ])
105 })
106
107 it('clears client-local context when updateOptions receives undefined', async () => {
108 type ClientContext = { localUserId: string }
109
110 const toolChunks = createToolCallChunks([
111 {
112 id: 'tc-update-context',
113 name: 'read_optional_context',
114 arguments: '{}',
115 },
116 ])
117 const textChunks = createTextChunks('done', 'msg-update-context')
118 const outputs: Array<string | null> = []
119 let callIndex = 0
120
121 const adapter: ConnectConnectionAdapter = {
122 async *connect(_messages, _data, abortSignal) {
123 const chunks = callIndex % 2 === 0 ? toolChunks : textChunks
124 callIndex++
125 for (const chunk of chunks) {
126 if (abortSignal?.aborted) {
127 return
128 }
129 yield chunk
130 }
131 },
132 }
133
134 const tool = toolDefinition({
135 name: 'read_optional_context',
136 description: 'Read optional client context',
137 }).client<ClientContext | undefined>((_input, ctx) => {
138 outputs.push(ctx?.context?.localUserId ?? null)
139 return { ok: true }
140 })
141
142 const client = new ChatClient({
143 connection: adapter,
144 context: { localUserId: 'local-1' },
145 tools: [tool],
146 })
147
148 await client.sendMessage('use initial context')
149 client.updateOptions({ context: undefined })
150 await client.sendMessage('use cleared context')
151
152 expect(outputs).toEqual(['local-1', null])
153 })
154
155 it('uses the per-run context snapshot for in-flight client tool execution', async () => {
156 const firstChunks = createToolCallChunks([
157 {
158 id: 'tc-context-snapshot',
159 name: 'read_snapshot_context',
160 arguments: '{}',
161 },
162 ])
163 const secondChunks = createTextChunks('done', 'msg-context-snapshot')
164 const outputs: Array<string> = []
165 let callIndex = 0
166 let client: ChatClient
167
168 const adapter: ConnectConnectionAdapter = {
169 async *connect(_messages, _data, abortSignal) {
170 const chunks = callIndex === 0 ? firstChunks : secondChunks
171 callIndex++
172 for (const chunk of chunks) {
173 if (abortSignal?.aborted) {
174 return
175 }
176 yield chunk
177 }
178 },
179 }
180
181 const tool = toolDefinition({
182 name: 'read_snapshot_context',
183 description: 'Read snapshot context',
184 }).client<{ localUserId: string }>((_input, ctx) => {
185 outputs.push(ctx.context.localUserId)
186 return { ok: true }
187 })
188
189 client = new ChatClient({
190 connection: adapter,
191 context: { localUserId: 'initial-user' },
192 tools: [tool],
193 onChunk: (chunk) => {
194 if (chunk.type === 'TOOL_CALL_START') {
195 client.updateOptions({ context: { localUserId: 'updated-user' } })
196 }
197 },
198 })
199
200 await client.sendMessage('use snapshot context')
201
202 expect(outputs).toEqual(['initial-user'])
203 })
204
205 it('uses the per-run client tool snapshot for automatic result validation', async () => {
206 type ClientContext = { localUserId: string }
207
208 const firstChunks = createToolCallChunks([
209 {
210 id: 'tc-tool-snapshot',
211 name: 'snapshot_schema_tool',
212 arguments: '{}',
213 },
214 ])
215 const secondChunks = createTextChunks('done', 'msg-tool-snapshot')
216 const outputs: Array<string> = []
217 let callIndex = 0
218
219 const adapter: ConnectConnectionAdapter = {
220 async *connect(_messages, _data, abortSignal) {
221 const chunks = callIndex === 0 ? firstChunks : secondChunks
222 callIndex++
223 for (const chunk of chunks) {
224 if (abortSignal?.aborted) {
225 return
226 }
227 yield chunk
228 }
229 },
230 }
231
232 const replacementTool = toolDefinition({
233 name: 'snapshot_schema_tool',
234 description: 'Replacement schema for later runs',
235 outputSchema: z.object({ updated: z.number() }),
236 }).client<ClientContext>(() => ({ updated: 1 }))
237
238 const initialTool = toolDefinition({
239 name: 'snapshot_schema_tool',
240 description: 'Initial schema for the active run',
241 outputSchema: z.object({ initial: z.string() }),
242 }).client<ClientContext>((_input, ctx) => {
243 outputs.push(ctx.context.localUserId)
244 client.updateOptions({ tools: replacementTools })
245 return { initial: 'from-original-tool' }
246 })
247
248 type SnapshotTools = ReadonlyArray<
249 typeof initialTool | typeof replacementTool
250 >
251
252 const initialTools: SnapshotTools = [initialTool]
253 const replacementTools: SnapshotTools = [replacementTool]
254
255 let client: ChatClient<SnapshotTools, ClientContext>
256
257 client = new ChatClient<SnapshotTools, ClientContext>({
258 connection: adapter,
259 context: { localUserId: 'snapshot-user' },
260 tools: initialTools,
261 })
262
263 await client.sendMessage('use snapshot tool')
264
265 expect(outputs).toEqual(['snapshot-user'])
266 expect(findToolCallPart(client, 'tc-tool-snapshot')).toMatchObject({
267 output: { initial: 'from-original-tool' },
268 state: 'complete',
269 })
270 expect(findToolResultPart(client, 'tc-tool-snapshot')).toMatchObject({
271 content: JSON.stringify({ initial: 'from-original-tool' }),
272 state: 'complete',
273 })
274 })
275
276 it('surfaces executable client tool outputSchema failures as output-error results', async () => {
277 const firstChunks = createToolCallChunks([
278 {
279 id: 'tc-invalid-executable-output',
280 name: 'invalid_output_tool',
281 arguments: '{}',
282 },
283 ])
284 const secondChunks = createTextChunks('done', 'msg-invalid-output')
285 let callIndex = 0
286
287 const adapter: ConnectConnectionAdapter = {
288 async *connect(_messages, _data, abortSignal) {
289 const chunks = callIndex === 0 ? firstChunks : secondChunks
290 callIndex++
291 for (const chunk of chunks) {
292 if (abortSignal?.aborted) {
293 return
294 }
295 yield chunk
296 }
297 },
298 }
299
300 const tool = toolDefinition({
301 name: 'invalid_output_tool',
302 description: 'Returns invalid output',
303 outputSchema: z.object({ count: z.number() }),
304 }).client(() => JSON.parse('null'))
305
306 const client = new ChatClient({
307 connection: adapter,
308 tools: [tool],
309 })
310
311 await client.sendMessage('call invalid output tool')
312
313 expect(
314 findToolCallPart(client, 'tc-invalid-executable-output'),
315 ).toMatchObject({
316 state: 'error',
317 output: {
318 error: expect.stringContaining('expected object'),
319 },
320 })
321 expect(
322 findToolResultPart(client, 'tc-invalid-executable-output'),
323 ).toMatchObject({
324 state: 'error',
325 })
326 })
327
328 it('awaits asynchronous outputSchema validation for executable client tools', async () => {
329 const firstChunks = createToolCallChunks([
330 {
331 id: 'tc-async-executable-output',
332 name: 'async_output_tool',
333 arguments: '{}',
334 },
335 ])
336 const secondChunks = createTextChunks('done', 'msg-async-output')
337 let callIndex = 0
338
339 const adapter: ConnectConnectionAdapter = {
340 async *connect(_messages, _data, abortSignal) {
341 const chunks = callIndex === 0 ? firstChunks : secondChunks
342 callIndex++
343 for (const chunk of chunks) {
344 if (abortSignal?.aborted) return
345 yield chunk
346 }
347 },
348 }
349
350 const tool = toolDefinition({
351 name: 'async_output_tool',
352 description: 'Returns asynchronously validated output',
353 outputSchema: asyncCountSchema,
354 }).client(() => ({ count: 1 }))
355
356 const client = new ChatClient({ connection: adapter, tools: [tool] })
357 await client.sendMessage('call async output tool')
358
359 expect(
360 findToolCallPart(client, 'tc-async-executable-output'),
361 ).toMatchObject({
362 state: 'complete',
363 output: { count: 1 },
364 })
365 expect(
366 findToolResultPart(client, 'tc-async-executable-output'),
367 ).toMatchObject({ state: 'complete' })
368 })
369
370 it('keeps non-JSON output of client tools that are not interrupts', async () => {
371 const firstChunks = createToolCallChunks([
372 { id: 'tc-legacy-plain', name: 'legacy_plain_tool', arguments: '{}' },
373 { id: 'tc-legacy-schema', name: 'legacy_schema_tool', arguments: '{}' },
374 ])
375 const secondChunks = createTextChunks('done', 'msg-legacy-output')
376 let callIndex = 0
377
378 const adapter: ConnectConnectionAdapter = {
379 async *connect(_messages, _data, abortSignal) {
380 const chunks = callIndex === 0 ? firstChunks : secondChunks
381 callIndex++
382 for (const chunk of chunks) {
383 if (abortSignal?.aborted) return
384 yield chunk
385 }
386 },
387 }
388
389 const plainTool = toolDefinition({
390 name: 'legacy_plain_tool',
391 description: 'Returns an object with an undefined field',
392 }).client(() => ({ ok: true, note: undefined }))
393 const schemaTool = toolDefinition({
394 name: 'legacy_schema_tool',
395 description: 'Returns an object with an undefined optional field',
396 outputSchema: z.object({ ok: z.boolean(), note: z.string().optional() }),
397 }).client(() => ({ ok: true, note: undefined }))
398
399 const client = new ChatClient({
400 connection: adapter,
401 tools: [plainTool, schemaTool],
402 })
403 await client.sendMessage('call legacy tools')
404
405 for (const toolCallId of ['tc-legacy-plain', 'tc-legacy-schema']) {
406 expect(findToolCallPart(client, toolCallId)).toMatchObject({
407 state: 'complete',
408 output: { ok: true },
409 })
410 expect(findToolResultPart(client, toolCallId)).toMatchObject({
411 state: 'complete',
412 })
413 }
414 })
415
416 it('renders a client tool that throws an empty-message error as terminal "error" (issue #718)', async () => {
417 const firstChunks = createToolCallChunks([
418 {
419 id: 'tc-empty-error',
420 name: 'throwing_tool',
421 arguments: '{}',
422 },
423 ])
424 const secondChunks = createTextChunks('done', 'msg-empty-error')
425 let callIndex = 0
426
427 const adapter: ConnectConnectionAdapter = {
428 async *connect(_messages, _data, abortSignal) {
429 const chunks = callIndex === 0 ? firstChunks : secondChunks
430 callIndex++
431 for (const chunk of chunks) {
432 if (abortSignal?.aborted) {
433 return
434 }
435 yield chunk
436 }
437 },
438 }
439
440 const tool = toolDefinition({
441 name: 'throwing_tool',
442 description: 'Throws an error with no message',
443 }).client(() => {
444 // Empty message — error-ness must come from the output-error state, not
445 // from the truthiness of the message string.
446 throw new Error()
447 })
448
449 const client = new ChatClient({
450 connection: adapter,
451 tools: [tool],
452 })
453
454 await client.sendMessage('call throwing tool')
455
456 expect(findToolCallPart(client, 'tc-empty-error')).toMatchObject({
457 state: 'error',
458 })
459 expect(findToolResultPart(client, 'tc-empty-error')).toMatchObject({
460 state: 'error',
461 })
462 })
463
464 it('awaits asynchronous outputSchema validation for manual client tool results', async () => {
465 const tool = toolDefinition({
466 name: 'manual_invalid_output_tool',
467 description: 'Validates manual output',
468 outputSchema: asyncCountSchema,
469 }).client(() => ({ count: 1 }))
470
471 const client = new ChatClient({
472 connection: {
473 async *connect() {},
474 },
475 tools: [tool],
476 })
477
478 client.setMessagesManually([
479 {
480 id: 'msg-manual-invalid-output',
481 role: 'assistant',
482 parts: [
483 {
484 type: 'tool-call',
485 id: 'tc-manual-invalid-output',
486 name: 'manual_invalid_output_tool',
487 arguments: '{}',
488 state: 'input-complete',
489 input: {},
490 },
491 ],
492 },
493 ])
494
495 await client.addToolResult({
496 toolCallId: 'tc-manual-invalid-output',
497 tool: 'manual_invalid_output_tool',
498 output: { count: 0 },
499 })
500
501 expect(findToolCallPart(client, 'tc-manual-invalid-output')).toMatchObject({
502 state: 'error',
503 output: {
504 error: 'expected positive count',
505 },
506 })
507 expect(
508 findToolResultPart(client, 'tc-manual-invalid-output'),
509 ).toMatchObject({
510 state: 'error',
511 })
512 })
513})