Open History to see the last commit
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 }
46}
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({ connection, tools: [ping] })
58
59 await client.sendMessage('ping me')
60
61 await vi.waitFor(() => expect(requests).toHaveLength(2))
62 expect(execute).toHaveBeenCalledTimes(1)
63 expect(JSON.stringify(requests[1])).toContain('{\\"reply\\":\\"pong\\"}')
64 })
65
66 it('does not run a tool that needs approval', async () => {
67 const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
68 const execute = vi.fn(() => ({ reply: 'pong' }))
69 const ping = toolDefinition({
70 name: 'ping',
71 description: 'Reply with pong',
72 inputSchema: z.object({}),
73 needsApproval: true,
74 }).client(execute)
75 const { connection, requests } = foreignServer()
76 const client = new ChatClient({ connection, tools: [ping] })
77
78 await client.sendMessage('ping me')
79 await new Promise((resolve) => setTimeout(resolve, 20))
80
81 expect(execute).not.toHaveBeenCalled()
82 expect(requests).toHaveLength(1)
83 expect(warn).toHaveBeenCalledOnce()
84 warn.mockRestore()
85 })
86})