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

chat-client-subagents.test.ts

324 lines9.5 KB

1import { describe, expect, it, vi } from 'vitest'
2import { EventType } from '@tanstack/ai/client'
3import { ChatClient } from '../src/chat-client'
4import { createMockConnectionAdapter } from './test-utils'
5import type { StreamChunk } from '@tanstack/ai/client'
6import type { ConnectConnectionAdapter } from '../src/connection-adapters'
7​
8const now = () => Date.now()
9​
10function runStarted(): StreamChunk {
11 return {
12 type: EventType.RUN_STARTED,
13 runId: 'run-1',
14 threadId: 'thread-1',
15 timestamp: now(),
16 }
18​
19function runFinished(): StreamChunk {
20 return {
21 type: EventType.RUN_FINISHED,
22 runId: 'run-1',
23 threadId: 'thread-1',
24 timestamp: now(),
25 }
27​
28function subagentStarted(): StreamChunk {
29 return {
30 type: EventType.SUBAGENT_STARTED,
31 subagentRunId: 'sub-1',
32 name: 'researcher',
33 timestamp: now(),
34 }
36​
37function subagentFinished(): StreamChunk {
38 return {
39 type: EventType.SUBAGENT_FINISHED,
40 subagentRunId: 'sub-1',
41 timestamp: now(),
42 }
44​
45function childTextStart(): StreamChunk {
46 return {
47 type: EventType.TEXT_MESSAGE_START,
48 messageId: 'child-msg',
49 role: 'assistant',
50 timestamp: now(),
51 subagentRunId: 'sub-1',
52 }
54​
55function childTextContent(delta: string): StreamChunk {
56 return {
57 type: EventType.TEXT_MESSAGE_CONTENT,
58 messageId: 'child-msg',
59 delta,
60 timestamp: now(),
61 subagentRunId: 'sub-1',
62 }
64​
65describe('ChatClient subagents', () => {
66 it('keeps useChat.subagents and part.subagent as the same object with stop', async () => {
67 const chunks: Array<StreamChunk> = [
68 runStarted(),
69 subagentStarted(),
70 childTextStart(),
71 childTextContent('Hello'),
72 subagentFinished(),
73 runFinished(),
74 ]
75​
76 const client = new ChatClient({
77 connection: createMockConnectionAdapter({ chunks }),
78 })
79 await client.sendMessage('hi')
80​
81 const assistant = client
82 .getMessages()
83 .find((message) => message.role === 'assistant')
84 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
85 const subagents = client.getSubagents()
86​
87 expect(part?.type).toBe('subagent')
88 if (part?.type !== 'subagent') throw new Error('expected subagent part')
89 expect(subagents).toHaveLength(1)
90 expect(subagents[0]).toBe(part.subagent)
91 expect(typeof part.subagent.stop).toBe('function')
92 expect(typeof subagents[0]?.stop).toBe('function')
93 expect(part.subagent.stop).toBe(subagents[0]?.stop)
94 })
95​
96 it('keeps status error after stop when SUBAGENT_FINISHED arrives later', async () => {
97 let release = () => {}
98 const gate = new Promise<void>((resolve) => {
99 release = resolve
100 })
101 const connection: ConnectConnectionAdapter = {
102 async *connect(_messages, _data, abortSignal) {
103 yield runStarted()
104 yield subagentStarted()
105 await gate
106 if (abortSignal?.aborted) return
107 yield childTextStart()
108 yield childTextContent('late')
109 yield subagentFinished()
110 yield runFinished()
111 },
112 }
113​
114 const client = new ChatClient({ connection })
115 const sendPromise = client.sendMessage('hi')
116 await vi.waitFor(() => {
117 expect(client.getSubagents()).toHaveLength(1)
118 })
119​
120 const handle = client.getSubagents()[0]
121 const assistant = client
122 .getMessages()
123 .find((message) => message.role === 'assistant')
124 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
125 expect(part?.type).toBe('subagent')
126 if (part?.type !== 'subagent') throw new Error('expected subagent part')
127 expect(handle).toBe(part.subagent)
128 handle?.stop?.()
129 expect(handle?.status).toBe('error')
130 expect(handle?.error).toEqual({ message: 'Stopped' })
131​
132 release()
133 await sendPromise
134​
135 expect(handle).toBe(part.subagent)
136 expect(handle?.status).toBe('error')
137 expect(handle?.error).toEqual({ message: 'Stopped' })
138 expect(part.subagent.status).toBe('error')
139 expect(handle?.messages).toEqual([])
140 })
141​
142 it('aborts a hanging child on stop so no later child text arrives', async () => {
143 let connectAbort: AbortSignal | undefined
144 const connection: ConnectConnectionAdapter = {
145 async *connect(_messages, _data, abortSignal) {
146 connectAbort = abortSignal
147 yield runStarted()
148 yield subagentStarted()
149 yield childTextStart()
150 yield childTextContent('partial')
151 await new Promise<void>((resolve) => {
152 if (abortSignal?.aborted) {
153 resolve()
154 return
155 }
156 abortSignal?.addEventListener('abort', () => resolve(), {
157 once: true,
158 })
159 })
160 if (!abortSignal?.aborted) {
161 yield childTextContent('late')
162 yield subagentFinished()
163 yield runFinished()
164 }
165 },
166 }
167​
168 const client = new ChatClient({ connection })
169 const sendPromise = client.sendMessage('hi')
170 await vi.waitFor(() => {
171 const nested = client.getSubagents()[0]?.messages[0]?.parts
172 expect(nested).toEqual([{ type: 'text', content: 'partial' }])
173 })
174​
175 const handle = client.getSubagents()[0]
176 const assistant = client
177 .getMessages()
178 .find((message) => message.role === 'assistant')
179 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
180 expect(part?.type).toBe('subagent')
181 if (part?.type !== 'subagent') throw new Error('expected subagent part')
182 expect(handle).toBe(part.subagent)
183 handle?.stop?.()
184​
185 expect(connectAbort?.aborted).toBe(true)
186 await sendPromise
187​
188 expect(handle?.status).toBe('error')
189 expect(handle?.error).toEqual({ message: 'Stopped' })
190 expect(handle?.messages[0]?.parts).toEqual([
191 { type: 'text', content: 'partial' },
192 ])
193 })
194​
195 it('lets a stopped child stream again when the server restarts it', async () => {
196 let call = 0
197 const connection: ConnectConnectionAdapter = {
198 async *connect(_messages, _data, abortSignal) {
199 call++
200 yield runStarted()
201 yield subagentStarted()
202 if (call === 1) {
203 yield childTextStart()
204 yield childTextContent('partial')
205 await new Promise<void>((resolve) => {
206 abortSignal?.addEventListener('abort', () => resolve(), {
207 once: true,
208 })
209 })
210 return
211 }
212 yield childTextStart()
213 yield childTextContent('again')
214 yield subagentFinished()
215 yield runFinished()
216 },
217 }
218​
219 const client = new ChatClient({ connection })
220 const first = client.sendMessage('hi')
221 await vi.waitFor(() => {
222 expect(client.getSubagents()[0]?.messages[0]?.parts).toEqual([
223 { type: 'text', content: 'partial' },
224 ])
225 })
226 client.getSubagents()[0]?.stop?.()
227 await first
228 expect(client.getSubagents()[0]?.status).toBe('error')
229​
230 // The same child id starts again, as a resume does. Its chunks count.
231 await client.sendMessage('go on')
232 const handle = client.getSubagents().find((entry) => entry.id === 'sub-1')
233 expect(handle?.status).toBe('finished')
234 expect(handle?.messages[0]?.parts).toEqual([
235 { type: 'text', content: 'again' },
236 ])
237 })
238})
239​
240describe('ChatClient subagent handles for restored messages', () => {
241 it('gives restored cards a handle, and drops it after clear()', () => {
242 const client = new ChatClient({
243 connection: createMockConnectionAdapter({ chunks: [] }),
244 initialMessages: [
245 {
246 id: 'a1',
247 role: 'assistant',
248 parts: [
249 {
250 type: 'subagent',
251 subagent: {
252 id: 'sub-restored',
253 name: 'researcher',
254 status: 'finished',
255 messages: [],
256 },
257 },
258 ],
259 },
260 ],
261 })
262​
263 const [handle] = client.getSubagents()
264 expect(handle).toMatchObject({ id: 'sub-restored', name: 'researcher' })
265 expect(typeof handle?.stop).toBe('function')
266 const part = client.getMessages()[0]?.parts[0]
267 expect(part?.type === 'subagent' ? part.subagent : undefined).toBe(handle)
268​
269 client.clear()
270 expect(client.getSubagents()).toEqual([])
271 })
272​
273 it('gives a nested card a handle with stop', () => {
274 const client = new ChatClient({
275 connection: createMockConnectionAdapter({ chunks: [] }),
276 initialMessages: [
277 {
278 id: 'a1',
279 role: 'assistant',
280 parts: [
281 {
282 type: 'subagent',
283 subagent: {
284 id: 'sub-outer',
285 name: 'researcher',
286 status: 'finished',
287 messages: [
288 {
289 id: 'c1',
290 role: 'assistant',
291 parts: [
292 {
293 type: 'subagent',
294 subagent: {
295 id: 'sub-inner',
296 name: 'fetcher',
297 status: 'finished',
298 messages: [],
299 },
300 },
301 ],
302 },
303 ],
304 },
305 },
306 ],
307 },
308 ],
309 })
310​
311 const ids = client.getSubagents().map((handle) => handle.id)
312 expect(ids).toEqual(['sub-outer', 'sub-inner'])
313 const inner = client.getSubagents().find((h) => h.id === 'sub-inner')
314 expect(typeof inner?.stop).toBe('function')
315 const outer = client.getMessages()[0]?.parts[0]
316 const nested =
317 outer?.type === 'subagent'
318 ? outer.subagent.messages[0]?.parts[0]
319 : undefined
320 expect(nested?.type === 'subagent' ? nested.subagent : undefined).toBe(
321 inner,
322 )
323 })
324})