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

chat-client-subagents.test.ts

450 lines13.3 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(metadata?: Record<string, unknown>): StreamChunk {
29 return {
30 type: EventType.SUBAGENT_STARTED,
31 subagentRunId: 'sub-1',
32 name: 'researcher',
33 timestamp: now(),
34 ...(metadata && { metadata }),
35 }
37​
38function subagentFinished(): StreamChunk {
39 return {
40 type: EventType.SUBAGENT_FINISHED,
41 subagentRunId: 'sub-1',
42 timestamp: now(),
43 }
45​
46function childTextStart(): StreamChunk {
47 return {
48 type: EventType.TEXT_MESSAGE_START,
49 messageId: 'child-msg',
50 role: 'assistant',
51 timestamp: now(),
52 subagentRunId: 'sub-1',
53 }
55​
56function childTextContent(delta: string): StreamChunk {
57 return {
58 type: EventType.TEXT_MESSAGE_CONTENT,
59 messageId: 'child-msg',
60 delta,
61 timestamp: now(),
62 subagentRunId: 'sub-1',
63 }
65​
66describe('ChatClient subagents', () => {
67 it('keeps useChat.subagents and part.subagent as the same object with stop', async () => {
68 const chunks: Array<StreamChunk> = [
69 runStarted(),
70 subagentStarted(),
71 childTextStart(),
72 childTextContent('Hello'),
73 subagentFinished(),
74 runFinished(),
75 ]
76​
77 const client = new ChatClient({
78 threadId: 'thread-1',
79 connection: createMockConnectionAdapter({ chunks }),
80 })
81 await client.sendMessage('hi')
82​
83 const assistant = client
84 .getMessages()
85 .find((message) => message.role === 'assistant')
86 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
87 const subagents = client.getSubagents()
88​
89 expect(part?.type).toBe('subagent')
90 if (part?.type !== 'subagent') throw new Error('expected subagent part')
91 expect(subagents).toHaveLength(1)
92 expect(subagents[0]).toBe(part.subagent)
93 expect(typeof part.subagent.stop).toBe('function')
94 expect(typeof subagents[0]?.stop).toBe('function')
95 expect(part.subagent.stop).toBe(subagents[0]?.stop)
96 })
97​
98 it('gives the handle the checked input from the card metadata', async () => {
99 const chunks: Array<StreamChunk> = [
100 runStarted(),
101 subagentStarted({
102 tanstack: { subagentInput: { task: 'Find squids' } },
103 }),
104 childTextStart(),
105 childTextContent('Hello'),
106 subagentFinished(),
107 runFinished(),
108 ]
109​
110 const client = new ChatClient({
111 threadId: 'thread-1',
112 connection: createMockConnectionAdapter({ chunks }),
113 })
114 await client.sendMessage('hi')
115​
116 // The handle keeps the input after later chunks update the card.
117 expect(client.getSubagents()[0]?.input).toEqual({ task: 'Find squids' })
118 })
119​
120 it('keeps status error after stop when SUBAGENT_FINISHED arrives later', async () => {
121 let release = () => {}
122 const gate = new Promise<void>((resolve) => {
123 release = resolve
124 })
125 const connection: ConnectConnectionAdapter = {
126 async *connect(_messages, _data, abortSignal) {
127 yield runStarted()
128 yield subagentStarted()
129 await gate
130 if (abortSignal?.aborted) return
131 yield childTextStart()
132 yield childTextContent('late')
133 yield subagentFinished()
134 yield runFinished()
135 },
136 }
137​
138 const client = new ChatClient({ threadId: 'thread-1', connection })
139 const sendPromise = client.sendMessage('hi')
140 await vi.waitFor(() => {
141 expect(client.getSubagents()).toHaveLength(1)
142 })
143​
144 const handle = client.getSubagents()[0]
145 const assistant = client
146 .getMessages()
147 .find((message) => message.role === 'assistant')
148 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
149 expect(part?.type).toBe('subagent')
150 if (part?.type !== 'subagent') throw new Error('expected subagent part')
151 expect(handle).toBe(part.subagent)
152 handle?.stop?.()
153 expect(handle?.status).toBe('error')
154 expect(handle?.error).toEqual({ message: 'Stopped' })
155​
156 release()
157 await sendPromise
158​
159 expect(handle).toBe(part.subagent)
160 expect(handle?.status).toBe('error')
161 expect(handle?.error).toEqual({ message: 'Stopped' })
162 expect(part.subagent.status).toBe('error')
163 expect(handle?.messages).toEqual([])
164 })
165​
166 it('aborts a hanging child on stop so no later child text arrives', async () => {
167 let connectAbort: AbortSignal | undefined
168 const connection: ConnectConnectionAdapter = {
169 async *connect(_messages, _data, abortSignal) {
170 connectAbort = abortSignal
171 yield runStarted()
172 yield subagentStarted()
173 yield childTextStart()
174 yield childTextContent('partial')
175 await new Promise<void>((resolve) => {
176 if (abortSignal?.aborted) {
177 resolve()
178 return
179 }
180 abortSignal?.addEventListener('abort', () => resolve(), {
181 once: true,
182 })
183 })
184 if (!abortSignal?.aborted) {
185 yield childTextContent('late')
186 yield subagentFinished()
187 yield runFinished()
188 }
189 },
190 }
191​
192 const client = new ChatClient({ threadId: 'thread-1', connection })
193 const sendPromise = client.sendMessage('hi')
194 await vi.waitFor(() => {
195 const nested = client.getSubagents()[0]?.messages[0]?.parts
196 expect(nested).toEqual([{ type: 'text', content: 'partial' }])
197 })
198​
199 const handle = client.getSubagents()[0]
200 const assistant = client
201 .getMessages()
202 .find((message) => message.role === 'assistant')
203 const part = assistant?.parts.find((entry) => entry.type === 'subagent')
204 expect(part?.type).toBe('subagent')
205 if (part?.type !== 'subagent') throw new Error('expected subagent part')
206 expect(handle).toBe(part.subagent)
207 handle?.stop?.()
208​
209 expect(connectAbort?.aborted).toBe(true)
210 await sendPromise
211​
212 expect(handle?.status).toBe('error')
213 expect(handle?.error).toEqual({ message: 'Stopped' })
214 expect(handle?.messages[0]?.parts).toEqual([
215 { type: 'text', content: 'partial' },
216 ])
217 })
218​
219 it('lets a stopped child stream again when the server restarts it', async () => {
220 let call = 0
221 const connection: ConnectConnectionAdapter = {
222 async *connect(_messages, _data, abortSignal) {
223 call++
224 yield runStarted()
225 yield subagentStarted()
226 if (call === 1) {
227 yield childTextStart()
228 yield childTextContent('partial')
229 await new Promise<void>((resolve) => {
230 abortSignal?.addEventListener('abort', () => resolve(), {
231 once: true,
232 })
233 })
234 return
235 }
236 yield childTextStart()
237 yield childTextContent('again')
238 yield subagentFinished()
239 yield runFinished()
240 },
241 }
242​
243 const client = new ChatClient({ threadId: 'thread-1', connection })
244 const first = client.sendMessage('hi')
245 await vi.waitFor(() => {
246 expect(client.getSubagents()[0]?.messages[0]?.parts).toEqual([
247 { type: 'text', content: 'partial' },
248 ])
249 })
250 client.getSubagents()[0]?.stop?.()
251 await first
252 expect(client.getSubagents()[0]?.status).toBe('error')
253​
254 // The same child id starts again, as a resume does. Its chunks count.
255 await client.sendMessage('go on')
256 const handle = client.getSubagents().find((entry) => entry.id === 'sub-1')
257 expect(handle?.status).toBe('finished')
258 expect(handle?.messages[0]?.parts).toEqual([
259 { type: 'text', content: 'again' },
260 ])
261 })
262})
263​
264describe('ChatClient subagent handles for restored messages', () => {
265 it('gives restored cards a handle, and drops it after clear()', () => {
266 const client = new ChatClient({
267 threadId: 'thread-1',
268 connection: createMockConnectionAdapter({ chunks: [] }),
269 initialMessages: [
270 {
271 id: 'a1',
272 role: 'assistant',
273 parts: [
274 {
275 type: 'subagent',
276 subagent: {
277 id: 'sub-restored',
278 name: 'researcher',
279 status: 'finished',
280 messages: [],
281 metadata: { tanstack: { subagentInput: { task: 'Saved' } } },
282 },
283 },
284 ],
285 },
286 ],
287 })
288​
289 const [handle] = client.getSubagents()
290 expect(handle).toMatchObject({
291 id: 'sub-restored',
292 name: 'researcher',
293 input: { task: 'Saved' },
294 })
295 expect(typeof handle?.stop).toBe('function')
296 const part = client.getMessages()[0]?.parts[0]
297 expect(part?.type === 'subagent' ? part.subagent : undefined).toBe(handle)
298​
299 client.clear()
300 expect(client.getSubagents()).toEqual([])
301 })
302​
303 it('accepts frozen snapshot messages back without throwing', () => {
304 const client = new ChatClient({
305 threadId: 'thread-1',
306 connection: createMockConnectionAdapter({ chunks: [] }),
307 initialMessages: [
308 {
309 id: 'a1',
310 role: 'assistant',
311 parts: [
312 {
313 type: 'subagent',
314 subagent: {
315 id: 'sub-restored',
316 name: 'researcher',
317 status: 'finished',
318 messages: [],
319 },
320 },
321 ],
322 },
323 ],
324 })
325 const saved = client.getSnapshot().messages
326 expect(Object.isFrozen(saved[0]?.parts[0])).toBe(true)
327​
328 client.clear()
329 expect(() => client.setMessagesManually([...saved])).not.toThrow()
330 expect(typeof client.getSubagents()[0]?.stop).toBe('function')
331​
332 const fork = new ChatClient({
333 threadId: 'thread-1',
334 connection: createMockConnectionAdapter({ chunks: [] }),
335 initialMessages: [...saved],
336 })
337 expect(typeof fork.getSubagents()[0]?.stop).toBe('function')
338 // Each client owns its handle, so `stop()` reaches the right client.
339 expect(fork.getSubagents()[0]).not.toBe(client.getSubagents()[0])
340 })
341​
342 it('accepts a frozen nested subagent card back without throwing', () => {
343 const client = new ChatClient({
344 threadId: 'thread-1',
345 connection: createMockConnectionAdapter({ chunks: [] }),
346 initialMessages: [
347 {
348 id: 'a1',
349 role: 'assistant',
350 parts: [
351 {
352 type: 'subagent',
353 subagent: {
354 id: 'sub-outer',
355 name: 'planner',
356 status: 'finished',
357 messages: [
358 {
359 id: 'child-1',
360 role: 'assistant',
361 parts: [
362 {
363 type: 'subagent',
364 subagent: {
365 id: 'sub-inner',
366 name: 'researcher',
367 status: 'finished',
368 messages: [],
369 },
370 },
371 ],
372 },
373 ],
374 },
375 },
376 ],
377 },
378 ],
379 })
380 const saved = client.getSnapshot().messages
381 const outer = saved[0]?.parts[0]
382 expect(
383 outer?.type === 'subagent' &&
384 Object.isFrozen(outer.subagent.messages[0]?.parts[0]),
385 ).toBe(true)
386​
387 client.clear()
388 expect(() => client.setMessagesManually(saved)).not.toThrow()
389 expect(client.getSubagents().map((handle) => handle.id)).toEqual([
390 'sub-outer',
391 'sub-inner',
392 ])
393 for (const handle of client.getSubagents()) {
394 expect(typeof handle.stop).toBe('function')
395 }
396 })
397​
398 it('gives a nested card a handle with stop', () => {
399 const client = new ChatClient({
400 threadId: 'thread-1',
401 connection: createMockConnectionAdapter({ chunks: [] }),
402 initialMessages: [
403 {
404 id: 'a1',
405 role: 'assistant',
406 parts: [
407 {
408 type: 'subagent',
409 subagent: {
410 id: 'sub-outer',
411 name: 'researcher',
412 status: 'finished',
413 messages: [
414 {
415 id: 'c1',
416 role: 'assistant',
417 parts: [
418 {
419 type: 'subagent',
420 subagent: {
421 id: 'sub-inner',
422 name: 'fetcher',
423 status: 'finished',
424 messages: [],
425 },
426 },
427 ],
428 },
429 ],
430 },
431 },
432 ],
433 },
434 ],
435 })
436​
437 const ids = client.getSubagents().map((handle) => handle.id)
438 expect(ids).toEqual(['sub-outer', 'sub-inner'])
439 const inner = client.getSubagents().find((h) => h.id === 'sub-inner')
440 expect(typeof inner?.stop).toBe('function')
441 const outer = client.getMessages()[0]?.parts[0]
442 const nested =
443 outer?.type === 'subagent'
444 ? outer.subagent.messages[0]?.parts[0]
445 : undefined
446 expect(nested?.type === 'subagent' ? nested.subagent : undefined).toBe(
447 inner,
448 )
449 })
450})