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

tool-call-lifecycle.spec.ts

56 lines2.0 KB

1import { test, expect } from './fixtures'
2​
3/**
4 * Issue #519 regression — `chat()` must not emit a duplicate `TOOL_CALL_END`
5 * for server-executed tools.
6 *
7 * The adapter streams its own START/ARGS/END; pre-fix the post-execution phase
8 * pushed a second END with no matching START, which `@ag-ui/client`'s
9 * `verifyEvents` rejects. `/api/tool-call-lifecycle-wire` runs the real
10 * `chat()` engine with a server tool and returns the emitted chunks.
11 */
12test.describe('chat() tool-call lifecycle (#519)', () => {
13 test('emits exactly one TOOL_CALL_END per server-executed tool', async ({
14 request,
15 }) => {
16 const res = await request.post('/api/tool-call-lifecycle-wire')
17 expect(res.ok()).toBe(true)
18 const { chunks, error } = (await res.json()) as {
19 chunks: Array<Record<string, unknown>>
20 error: string | null
21 }
22​
23 expect(error).toBeNull()
24​
25 const idOf = (c: Record<string, unknown>) => c.toolCallId as string
26 const starts = chunks.filter(
27 (c) => c.type === 'TOOL_CALL_START' && idOf(c) === 'call_weather',
28 )
29 const ends = chunks.filter(
30 (c) => c.type === 'TOOL_CALL_END' && idOf(c) === 'call_weather',
31 )
32 const results = chunks.filter(
33 (c) => c.type === 'TOOL_CALL_RESULT' && idOf(c) === 'call_weather',
34 )
35​
36 // Pre-fix `ends` was 2 (adapter + duplicate from buildToolResultChunks).
37 expect(starts).toHaveLength(1)
38 expect(ends).toHaveLength(1)
39 expect(results).toHaveLength(1)
40​
41 // The server tool actually ran — its result reached the stream.
42 expect(results[0]).toMatchObject({ content: expect.stringContaining('22') })
43​
44 // verifyEvents invariant: every END consumes a matching open START, so a
45 // duplicate END for the same toolCallId finds none and fails here.
46 const open = new Set<string>()
47 for (const c of chunks) {
48 if (c.type === 'TOOL_CALL_START') open.add(idOf(c))
49 if (c.type === 'TOOL_CALL_END') {
50 const id = idOf(c)
51 expect(open.has(id)).toBe(true)
52 open.delete(id)
53 }
54 }
55 })
56})