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