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

subagent-reconstruct.test.ts

448 lines12.6 KB

1import { describe, expect, it } from 'vitest'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 defineAgent,
7 uiMessagesToWire,
8} from '@tanstack/ai'
9import type {
10 AnyTextAdapter,
11 ModelMessage,
12 StreamChunk,
13 SubagentStatus,
14 UIMessage,
15} from '@tanstack/ai'
16import { memoryPersistence, reconstructChat, withPersistence } from '../src'
17​
18// AnyTextAdapter brands private adapter fields. A partial object cannot
19// satisfy that type, and this test must not call the parent model.
20function parentAdapter(): AnyTextAdapter {
21 return {
22 kind: 'text',
23 name: 'mock',
24 model: 'test-model',
25 '~types': {},
26 chatStream() {
27 throw new Error('parent model should not run')
28 },
29 } as unknown as AnyTextAdapter
31​
32function textChunk(messageId: string, delta: string): StreamChunk {
33 return {
34 type: EventType.TEXT_MESSAGE_CONTENT,
35 messageId,
36 delta,
37 timestamp: 1,
38 }
40​
41function noteAgent(name: string, description: string, delta: string) {
42 return defineAgent({
43 name,
44 description,
45 run: async function* () {
46 yield textChunk(`${name}-note`, delta)
47 },
48 })
50​
51type Card = {
52 type: string
53 content?: string
54 subagent?: {
55 id?: string
56 name: string
57 status?: string
58 parentRunId?: string
59 messages: Array<{ parts: Array<{ content?: string }> }>
60 }
62​
63type DeskMessage = {
64 id: string
65 role: string
66 metadata?: { tanstack?: { runId?: string } }
67 parts: Array<Card>
69​
70type Desk = {
71 activeRun: { runId: string } | null
72 messages: Array<DeskMessage>
74​
75function isDesk(value: unknown): value is Desk {
76 if (value == null || typeof value !== 'object') return false
77 if (!('messages' in value) || !Array.isArray(value.messages)) return false
78 return 'activeRun' in value
80​
81async function loadDesk(
82 persistence: ReturnType<typeof memoryPersistence>,
83): Promise<Desk> {
84 const response = await reconstructChat(
85 persistence,
86 new Request('http://local/api/chat?threadId=blog-desk'),
87 )
88 const body: unknown = await response.json()
89 if (!isDesk(body)) {
90 throw new Error('reconstructChat returned an unexpected body')
91 }
92 return body
94​
95function cardsOf(message: DeskMessage | undefined) {
96 return message?.parts.filter((part) => part.type === 'subagent') ?? []
98​
99function cardText(message: DeskMessage | undefined, name: string) {
100 const card = cardsOf(message).find((part) => part.subagent?.name === name)
101 return card?.subagent?.messages[0]?.parts[0]?.content
103​
104function statusOf(value: string | undefined): SubagentStatus {
105 if (value === 'running' || value === 'error' || value === 'suspended') {
106 return value
107 }
108 return 'finished'
110​
111function toUi(messages: Array<DeskMessage>): Array<UIMessage> {
112 return messages.map((message) => {
113 const parts: UIMessage['parts'] = []
114 for (const part of message.parts) {
115 if (part.type === 'text' && part.content !== undefined) {
116 parts.push({ type: 'text', content: part.content })
117 continue
118 }
119 const subagent = part.subagent
120 if (part.type !== 'subagent' || subagent === undefined) continue
121 parts.push({
122 type: 'subagent',
123 subagent: {
124 id: subagent.id ?? subagent.name,
125 name: subagent.name,
126 status: statusOf(subagent.status),
127 ...(subagent.parentRunId !== undefined
128 ? { parentRunId: subagent.parentRunId }
129 : {}),
130 messages: subagent.messages.map((child, index) => ({
131 id: `child-${subagent.name}-${index}`,
132 role: 'assistant' as const,
133 parts: child.parts.flatMap((piece) =>
134 piece.content === undefined
135 ? []
136 : [{ type: 'text' as const, content: piece.content }],
137 ),
138 })),
139 },
140 })
141 }
142 const role = message.role === 'assistant' ? 'assistant' : 'user'
143 return {
144 id: message.id,
145 role,
146 parts,
147 ...(message.metadata !== undefined ? { metadata: message.metadata } : {}),
148 }
149 })
151​
152function visibleText(messages: ReadonlyArray<UIMessage | ModelMessage>) {
153 return messages
154 .map((message) => {
155 if ('parts' in message) {
156 return message.parts
157 .map((part) => {
158 if (part.type === 'text') return part.content
159 if (part.type !== 'subagent') return ''
160 return part.subagent.messages
161 .map((child) =>
162 'parts' in child
163 ? child.parts
164 .map((piece) =>
165 piece.type === 'text' ? piece.content : '',
166 )
167 .join('\n')
168 : '',
169 )
170 .join('\n')
171 })
172 .join('\n')
173 }
174 return typeof message.content === 'string' ? message.content : ''
175 })
176 .join('\n')
178​
179async function runChat(input: {
180 persistence: ReturnType<typeof memoryPersistence>
181 runId: string
182 messages: Array<UIMessage | ModelMessage>
183 agents: ReturnType<typeof noteAgent>[]
184 router: () => Array<string>
185}) {
186 const chunks: Array<StreamChunk> = []
187 for await (const chunk of chat({
188 adapter: parentAdapter(),
189 threadId: 'blog-desk',
190 runId: input.runId,
191 messages: input.messages,
192 middleware: [withPersistence(input.persistence)],
193 subagents: {
194 agents: input.agents,
195 strategy: 'exclusive',
196 router: input.router,
197 },
198 })) {
199 chunks.push(chunk)
200 }
201 return chunks
203​
204async function sendFollowUp(input: {
205 persistence: ReturnType<typeof memoryPersistence>
206 messages: Array<UIMessage>
207 seen: { text: string }
208}) {
209 const wire = uiMessagesToWire(input.messages)
210 const params = await chatParamsFromRequestBody({
211 threadId: 'blog-desk',
212 runId: 'run-2',
213 messages: wire,
214 tools: [],
215 context: [],
216 })
217 const writer = defineAgent({
218 name: 'writer',
219 description: 'Writes the article',
220 run: async function* (ctx) {
221 input.seen.text = visibleText(ctx.messages)
222 yield textChunk('article', 'Draft article')
223 },
224 })
225 await runChat({
226 persistence: input.persistence,
227 runId: 'run-2',
228 messages: params.messages,
229 agents: [
230 noteAgent('researcher', 'Looks up facts', 'unused'),
231 noteAgent('seo', 'Suggests titles', 'unused'),
232 writer,
233 ],
234 router: () => ['writer'],
235 })
237​
238describe('reconstruct subagent cards', () => {
239 it('puts both child texts back on the parent message', async () => {
240 const persistence = memoryPersistence()
241 await runChat({
242 persistence,
243 runId: 'run-1',
244 messages: [
245 {
246 id: 'user-1',
247 role: 'user',
248 parts: [{ type: 'text', content: 'research and seo' }],
249 },
250 ],
251 agents: [
252 noteAgent('researcher', 'Looks up facts', 'Octopus notes'),
253 noteAgent('seo', 'Suggests titles', 'Title ideas'),
254 ],
255 router: () => ['researcher', 'seo'],
256 })
257​
258 const body = await loadDesk(persistence)
259 expect(body.activeRun).toBeNull()
260 const assistant = body.messages.find(
261 (message) => message.role === 'assistant',
262 )
263 expect(cardText(assistant, 'researcher')).toBe('Octopus notes')
264 expect(cardText(assistant, 'seo')).toBe('Title ideas')
265 expect(
266 cardsOf(assistant).every(
267 (part) => part.subagent?.parentRunId === 'run-1',
268 ),
269 ).toBe(true)
270 const runs = await persistence.stores.runs.listByParentRun?.('run-1')
271 expect(runs?.map((run) => run.name).sort()).toEqual(['researcher', 'seo'])
272 expect(runs?.every((run) => run.subagentRunId === run.runId)).toBe(true)
273 expect(runs?.every((run) => run.threadId !== 'blog-desk')).toBe(true)
274 })
275​
276 it('keeps the cards when a later message is sent after a reload', async () => {
277 const persistence = memoryPersistence()
278 await runChat({
279 persistence,
280 runId: 'run-1',
281 messages: [
282 {
283 id: 'user-1',
284 role: 'user',
285 parts: [{ type: 'text', content: 'research and seo' }],
286 },
287 ],
288 agents: [
289 noteAgent('researcher', 'Looks up facts', 'Octopus notes'),
290 noteAgent('seo', 'Suggests titles', 'Title ideas'),
291 ],
292 router: () => ['researcher', 'seo'],
293 })
294 const first = await loadDesk(persistence)
295 const seen = { text: '' }
296 await sendFollowUp({
297 persistence,
298 messages: [
299 ...toUi(first.messages),
300 {
301 id: 'user-2',
302 role: 'user',
303 parts: [{ type: 'text', content: 'Now write the article' }],
304 },
305 ],
306 seen,
307 })
308​
309 expect(seen.text).toContain('Octopus notes')
310 expect(seen.text).toContain('Title ideas')
311 const body = await loadDesk(persistence)
312 const assistants = body.messages.filter(
313 (message) => message.role === 'assistant',
314 )
315 expect(cardText(assistants[0], 'researcher')).toBe('Octopus notes')
316 expect(cardText(assistants[0], 'seo')).toBe('Title ideas')
317 expect(cardText(assistants[1], 'writer')).toBe('Draft article')
318 })
319​
320 it('keeps the cards when the live client uses its own assistant id', async () => {
321 const persistence = memoryPersistence()
322 await runChat({
323 persistence,
324 runId: 'run-1',
325 messages: [
326 {
327 id: 'user-1',
328 role: 'user',
329 parts: [{ type: 'text', content: 'research and seo' }],
330 },
331 ],
332 agents: [
333 noteAgent('researcher', 'Looks up facts', 'Octopus notes'),
334 noteAgent('seo', 'Suggests titles', 'Title ideas'),
335 ],
336 router: () => ['researcher', 'seo'],
337 })
338 const first = await loadDesk(persistence)
339 const live = toUi(first.messages).map((message) =>
340 message.role === 'assistant'
341 ? {
342 id: 'live-assistant',
343 role: 'assistant' as const,
344 parts: message.parts,
345 }
346 : message,
347 )
348 const seen = { text: '' }
349 await sendFollowUp({
350 persistence,
351 messages: [
352 ...live,
353 {
354 id: 'user-2',
355 role: 'user',
356 parts: [{ type: 'text', content: 'Now write the article' }],
357 },
358 ],
359 seen,
360 })
361​
362 expect(seen.text).toContain('Octopus notes')
363 const body = await loadDesk(persistence)
364 const research = body.messages.find((message) =>
365 cardsOf(message).some((part) => part.subagent?.name === 'researcher'),
366 )
367 expect(cardText(research, 'researcher')).toBe('Octopus notes')
368 expect(cardText(research, 'seo')).toBe('Title ideas')
369 })
370​
371 it('shows partial cards while both children are still running', async () => {
372 const persistence = memoryPersistence()
373 let release: () => void = () => {}
374 const gate = new Promise<void>((resolve) => {
375 release = () => {
376 resolve()
377 }
378 })
379 const waiting = (name: string, delta: string) =>
380 defineAgent({
381 name,
382 description: name,
383 run: async function* () {
384 yield textChunk(`${name}-note`, delta)
385 await gate
386 },
387 })
388​
389 const stream = chat({
390 adapter: parentAdapter(),
391 threadId: 'blog-desk',
392 runId: 'run-1',
393 messages: [
394 {
395 id: 'user-1',
396 role: 'user',
397 parts: [{ type: 'text', content: 'research and seo' }],
398 },
399 ],
400 // Write every delta, so the reload below sees both first notes.
401 middleware: [withPersistence(persistence, { snapshotIntervalMs: 0 })],
402 subagents: {
403 agents: [
404 waiting('researcher', 'Octopus notes'),
405 waiting('seo', 'Title ideas'),
406 ],
407 strategy: 'exclusive',
408 router: () => ['researcher', 'seo'],
409 },
410 })
411 const iterator = stream[Symbol.asyncIterator]()
412 try {
413 const seen: Array<StreamChunk> = []
414 while (
415 seen.filter((chunk) => chunk.type === 'TEXT_MESSAGE_CONTENT').length < 2
416 ) {
417 const next = await iterator.next()
418 if (next.done) break
419 seen.push(next.value)
420 }
421 const mid = await loadDesk(persistence)
422 expect(mid.activeRun?.runId).toBe('run-1')
423 const assistant = mid.messages.find(
424 (message) => message.role === 'assistant',
425 )
426 expect(cardText(assistant, 'researcher')).toBe('Octopus notes')
427 expect(cardText(assistant, 'seo')).toBe('Title ideas')
428 expect(
429 cardsOf(assistant).every((part) => part.subagent?.status === 'running'),
430 ).toBe(true)
431 } finally {
432 release()
433 while (true) {
434 const next = await iterator.next()
435 if (next.done) break
436 }
437 }
438​
439 const done = await loadDesk(persistence)
440 expect(done.activeRun).toBeNull()
441 const assistant = done.messages.find(
442 (message) => message.role === 'assistant',
443 )
444 expect(
445 cardsOf(assistant).every((part) => part.subagent?.status === 'finished'),
446 ).toBe(true)
447 })
448})