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