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

chat-client-foreign-client-tool.test.ts

94 lines3.0 KB

1import { describe, expect, it, vi } from 'vitest'
2import { toolDefinition } from '@tanstack/ai/client'
3import { z } from 'zod'
4import { ChatClient } from '../src/chat-client'
5import type { ConnectConnectionAdapter } from '../src/connection-adapters'
6import type { StreamChunk } from '@tanstack/ai/client'
7​
8/**
9 * An AG-UI server outside TanStack AI ends a run that calls a frontend tool
10 * with a success outcome and no TOOL_CALL_RESULT (issue #1464).
11 */
12function foreignServer() {
13 const requests: Array<unknown> = []
14 const connection: ConnectConnectionAdapter = {
15 async *connect(messages) {
16 requests.push(messages)
17 const runId = `run-${requests.length}`
18 const chunks =
19 requests.length === 1
20 ? [
21 { type: 'RUN_STARTED', threadId: 't', runId },
22 {
23 type: 'TOOL_CALL_START',
24 toolCallId: 'tc-1',
25 toolCallName: 'ping',
26 },
27 { type: 'TOOL_CALL_ARGS', toolCallId: 'tc-1', delta: '{}' },
28 { type: 'TOOL_CALL_END', toolCallId: 'tc-1' },
29 {
30 type: 'RUN_FINISHED',
31 threadId: 't',
32 runId,
33 outcome: { type: 'success' },
34 },
35 ]
36 : [
37 { type: 'RUN_STARTED', threadId: 't', runId },
38 { type: 'RUN_FINISHED', threadId: 't', runId },
39 ]
40 for (const chunk of chunks) {
41 yield { ...chunk, timestamp: Date.now() } as StreamChunk
42 }
43 },
44 }
45 return { connection, requests }
47​
48describe('client tools from a foreign AG-UI server', () => {
49 it('runs the tool and continues with its result', async () => {
50 const execute = vi.fn(() => ({ reply: 'pong' }))
51 const ping = toolDefinition({
52 name: 'ping',
53 description: 'Reply with pong',
54 inputSchema: z.object({}),
55 }).client(execute)
56 const { connection, requests } = foreignServer()
57 const client = new ChatClient({
58 threadId: 'thread-1',
59 connection,
60 tools: [ping],
61 })
62​
63 await client.sendMessage('ping me')
64​
65 await vi.waitFor(() => expect(requests).toHaveLength(2))
66 expect(execute).toHaveBeenCalledTimes(1)
67 expect(JSON.stringify(requests[1])).toContain('{\\"reply\\":\\"pong\\"}')
68 })
69​
70 it('does not run a tool that needs approval', async () => {
71 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
72 const execute = vi.fn(() => ({ reply: 'pong' }))
73 const ping = toolDefinition({
74 name: 'ping',
75 description: 'Reply with pong',
76 inputSchema: z.object({}),
77 needsApproval: true,
78 }).client(execute)
79 const { connection, requests } = foreignServer()
80 const client = new ChatClient({
81 threadId: 'thread-1',
82 connection,
83 tools: [ping],
84 })
85​
86 await client.sendMessage('ping me')
87 await new Promise((resolve) => setTimeout(resolve, 20))
88​
89 expect(execute).not.toHaveBeenCalled()
90 expect(requests).toHaveLength(1)
91 expect(warn).toHaveBeenCalledOnce()
92 warn.mockRestore()
93 })
94})