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

chat-client-client-tool-status.test.ts

177 lines5.7 KB

1import { describe, expect, it, vi } from 'vitest'
2import { ChatClient } from '../src/chat-client'
3import {
4 createMockConnectionAdapter,
5 createTextChunks,
6 createToolCallChunks,
7} from './test-utils'
8import type { ConnectConnectionAdapter } from '../src/connection-adapters'
9import type { StreamChunk } from '@tanstack/ai/client'
10​
11/**
12 * Regression for https://github.com/TanStack/ai/issues/421
13 *
14 * After a client-side tool call runs, the client posts the tool result and
15 * auto-continues. A custom backend can answer that continuation run with a
16 * bare `RUN_FINISHED { finishReason: 'stop' }` and no assistant text/message.
17 * In that case the StreamProcessor's finalizeStream() has no
18 * `lastAssistantMessage` to emit `onStreamEnd` for, so `setStatus('ready')`
19 * never fires and status never settles. The issue reports this as stuck on
20 * `streaming`; the underlying stuck value is actually `submitted`, since
21 * `streaming` is only set by `onStreamStart` (which a bare `RUN_FINISHED`
22 * never triggers).
23 */
24describe('client tool call status (issue #421)', () => {
25 function createDeferred<T>() {
26 let resolve!: (value: T) => void
27 const promise = new Promise<T>((res) => {
28 resolve = res
29 })
30 return { promise, resolve }
31 }
32​
33 it('settles status to ready after a client tool when the continuation run emits only RUN_FINISHED', async () => {
34 // Round 1: the server asks for a CLIENT tool call (finishReason 'tool_calls').
35 const round1Chunks = createToolCallChunks([
36 { id: 'tc-1', name: 'get_weather', arguments: '{"city":"NYC"}' },
37 ])
38 // Round 2: the custom backend (as in the issue) closes the run with only a
39 // bare RUN_FINISHED — no assistant message, no text — after receiving the
40 // client tool result.
41 const round2Chunks: Array<StreamChunk> = [
42 {
43 type: 'RUN_FINISHED',
44 runId: 'run-2',
45 threadId: 'thread-2',
46 model: 'test',
47 timestamp: Date.now(),
48 metadata: { tanstack: { finishReason: 'stop' } },
49 } as StreamChunk,
50 ]
51​
52 let callIndex = 0
53 const adapter: ConnectConnectionAdapter = {
54 async *connect(_messages, _data, abortSignal) {
55 callIndex++
56 const chunks = callIndex === 1 ? round1Chunks : round2Chunks
57 for (const chunk of chunks) {
58 if (abortSignal?.aborted) return
59 yield chunk
60 }
61 },
62 }
63​
64 // Controlled promise so the client tool's resolution is deterministic and
65 // the test is not racy.
66 const toolGate = createDeferred<void>()
67​
68 const statuses: Array<string> = []
69 const client = new ChatClient({
70 threadId: 'thread-1',
71 connection: adapter,
72 onStatusChange: (s) => statuses.push(s),
73 tools: [
74 {
75 __toolSide: 'client' as const,
76 name: 'get_weather',
77 description: 'Get the weather',
78 execute: async () => {
79 await toolGate.promise
80 return { temp: 72 }
81 },
82 },
83 ],
84 })
85​
86 const sendPromise = client.sendMessage('What is the weather in NYC?')
87​
88 // Let round 1 stream through and the client tool begin executing.
89 await vi.waitFor(() => {
90 expect(callIndex).toBe(1)
91 })
92​
93 // Release the client tool; this posts the result and triggers the
94 // continuation (round 2).
95 toolGate.resolve()
96 await sendPromise
97​
98 await vi.waitFor(
99 () => {
100 expect(client.getIsLoading()).toBe(false)
101 expect(callIndex).toBeGreaterThanOrEqual(2)
102 },
103 { timeout: 2000 },
104 )
105​
106 // The run is fully complete (finishReason 'stop'); status must settle to
107 // 'ready', not stay stuck at 'submitted'.
108 expect(client.getStatus()).toBe('ready')
109 expect(statuses[statuses.length - 1]).toBe('ready')
110 })
111​
112 it("plain text run emits onStatusChange('ready') exactly once", async () => {
113 // A normal run with an assistant message: onStreamEnd fires and sets
114 // 'ready'. The terminal normalization added for #421 is guarded on
115 // `status !== 'ready'`, so it must NOT double-emit 'ready' here.
116 const adapter = createMockConnectionAdapter({
117 chunks: createTextChunks('Hello'),
118 })
119​
120 const statuses: Array<string> = []
121 const client = new ChatClient({
122 threadId: 'thread-1',
123 connection: adapter,
124 onStatusChange: (s) => statuses.push(s),
125 })
126​
127 await client.sendMessage('Hi')
128​
129 await vi.waitFor(() => {
130 expect(client.getIsLoading()).toBe(false)
131 })
132​
133 expect(client.getStatus()).toBe('ready')
134 expect(statuses.filter((s) => s === 'ready').length).toBe(1)
135 })
136​
137 it('sendMessage with a bare RUN_FINISHED{stop} first run (no assistant message) settles to ready', async () => {
138 // Sibling of the #421 repro on the FIRST run: the backend closes the run
139 // immediately with a bare RUN_FINISHED and no assistant message, so
140 // onStreamEnd never fires. Status must still settle to 'ready'.
141 const chunks: Array<StreamChunk> = [
142 {
143 type: 'RUN_FINISHED',
144 runId: 'run-1',
145 threadId: 'thread-1',
146 model: 'test',
147 timestamp: Date.now(),
148 metadata: { tanstack: { finishReason: 'stop' } },
149 } as StreamChunk,
150 ]
151​
152 const adapter: ConnectConnectionAdapter = {
153 async *connect(_messages, _data, abortSignal) {
154 for (const chunk of chunks) {
155 if (abortSignal?.aborted) return
156 yield chunk
157 }
158 },
159 }
160​
161 const statuses: Array<string> = []
162 const client = new ChatClient({
163 threadId: 'thread-1',
164 connection: adapter,
165 onStatusChange: (s) => statuses.push(s),
166 })
167​
168 await client.sendMessage('Hi')
169​
170 await vi.waitFor(() => {
171 expect(client.getIsLoading()).toBe(false)
172 })
173​
174 expect(client.getStatus()).toBe('ready')
175 expect(statuses[statuses.length - 1]).toBe('ready')
176 })
177})