Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 buildSubagentSteps,
4 collectServerSteps,
5 collectSubagents,
6 groupTimeline,
7 snapshotTurns,
8 subagentIdForRunId,
9} from '../src/store/subagent-steps'
10import type { Iteration, Message } from '../src/store/ai-context'
11
12const researcherMessages = [
13 {
14 id: 'child-1',
15 role: 'assistant',
16 parts: [
17 { type: 'thinking', content: 'Look up the facts first.' },
18 {
19 type: 'tool-call',
20 id: 'call_1',
21 name: 'lookupFacts',
22 arguments: '{"topic":"squids"}',
23 state: 'complete',
24 output: { facts: ['three hearts'] },
25 },
26 {
27 type: 'tool-result',
28 toolCallId: 'call_1',
29 content: '{"facts":["three hearts"]}',
30 state: 'complete',
31 },
32 { type: 'text', content: 'Squids have three hearts.' },
33 ],
34 },
35]
36
37const snapshot = [
38 { id: 'u1', role: 'user', parts: [{ type: 'text', content: 'hi' }] },
39 { id: 'a1', role: 'assistant', parts: [{ type: 'text', content: 'hello' }] },
40 { id: 'u2', role: 'user', parts: [{ type: 'text', content: 'research' }] },
41 {
42 id: 'a2',
43 role: 'assistant',
44 parts: [
45 {
46 type: 'subagent',
47 subagent: {
48 id: 'sub-1',
49 name: 'researcher',
50 status: 'finished',
51 messages: [
52 ...researcherMessages,
53 {
54 id: 'child-2',
55 role: 'assistant',
56 parts: [
57 {
58 type: 'subagent',
59 subagent: {
60 id: 'sub-2',
61 name: 'checker',
62 status: 'error',
63 error: { message: 'boom' },
64 messages: [],
65 },
66 },
67 ],
68 },
69 ],
70 },
71 },
72 ],
73 },
74]
75
76describe('collectSubagents', () => {
77 it('lists every child with its path and turn', () => {
78 const agents = collectSubagents(snapshot)
79 expect(agents.map((a) => [a.id, a.path, a.status, a.turn])).toEqual([
80 ['sub-1', 'researcher', 'finished', 1],
81 ['sub-2', 'researcher > checker', 'error', 1],
82 ])
83 expect(agents[1]?.error).toBe('boom')
84 })
85})
86
87describe('subagentIdForRunId', () => {
88 const ids = new Set(['sub-1', 'sub-2'])
89 it('matches the child run id suffix', () => {
90 expect(subagentIdForRunId('run-9:sub-1', ids)).toBe('sub-1')
91 expect(subagentIdForRunId('run-9:sub-1:sub-2', ids)).toBe('sub-2')
92 expect(subagentIdForRunId('sub-2', ids)).toBe('sub-2')
93 })
94 it('ignores the parent run and unknown runs', () => {
95 expect(subagentIdForRunId('run-9', ids)).toBeUndefined()
96 expect(subagentIdForRunId('run-9:other', ids)).toBeUndefined()
97 expect(subagentIdForRunId(undefined, ids)).toBeUndefined()
98 })
99})
100
101function iteration(
102 requestId: string,
103 runId: string,
104 index: number,
105 startedAt: number,
106): Iteration {
107 return {
108 requestId,
109 runId,
110 index,
111 messageId: `${requestId}-${index}`,
112 startedAt,
113 completedAt: startedAt + 1,
114 middlewareEvents: [],
115 messageIds: [`${requestId}-${index}`],
116 }
117}
118
119function user(id: string, timestamp: number, requestId: string): Message {
120 return { id, role: 'user', content: id, timestamp, requestId }
121}
122
123describe('groupTimeline', () => {
124 const agents = collectSubagents(snapshot)
125
126 it('moves child server steps under their agent and drops child user copies', () => {
127 const iterations = [
128 iteration('root-1', 'run-1', 0, 10),
129 iteration('root-2', 'run-2', 0, 30),
130 iteration('child-a', 'run-2:sub-1', 0, 31),
131 iteration('child-a', 'run-2:sub-1', 1, 32),
132 ]
133 const messages = [
134 user('u1', 5, 'root-1'),
135 user('u2', 25, 'root-2'),
136 // The child request re-sends the history. These are not new turns.
137 user('u1-copy', 31, 'child-a'),
138 user('u2-copy', 31, 'child-a'),
139 ]
140 const groups = groupTimeline(iterations, messages, agents)
141
142 expect(groups.map((g) => g.userMessage?.id)).toEqual(['u1', 'u2'])
143 expect(groups[0]?.agents).toEqual([])
144 expect(groups[1]?.iterations.map((i) => i.requestId)).toEqual(['root-2'])
145
146 const [researcher, checker] = groups[1]?.agents ?? []
147 expect(researcher?.agent.path).toBe('researcher')
148 expect(researcher?.source).toBe('server')
149 expect(researcher?.iterations.map((i) => i.index)).toEqual([0, 1])
150 // No server steps for this child, so they come from the snapshot.
151 expect(checker?.agent.path).toBe('researcher > checker')
152 expect(checker?.source).toBe('snapshot')
153 })
154
155 it('keeps a turn that only has child steps', () => {
156 const groups = groupTimeline(
157 [iteration('child-a', 'run-2:sub-1', 0, 31)],
158 [user('u1', 5, 'root-1'), user('u2', 25, 'root-2')],
159 agents,
160 )
161 expect(groups.map((g) => g.userMessage?.id)).toEqual(['u2'])
162 expect(groups[0]?.iterations).toEqual([])
163 expect(groups[0]?.agents.map((g) => g.agent.id)).toEqual(['sub-1', 'sub-2'])
164 })
165})
166
167describe('turns from the snapshot', () => {
168 const agents = collectSubagents(snapshot)
169
170 it('keeps a routed turn that has no parent server steps', () => {
171 // Turn 1 went to the researcher. Only turn 2 ran the parent model.
172 const turns = snapshotTurns([
173 {
174 id: 'u1',
175 role: 'user',
176 createdAt: new Date(10),
177 parts: [{ type: 'text', content: 'research' }],
178 },
179 { id: 'a1', role: 'assistant', parts: [] },
180 {
181 id: 'u2',
182 role: 'user',
183 createdAt: '1970-01-01T00:00:00.030Z',
184 parts: [{ type: 'text', content: 'what is 2 + 2' }],
185 },
186 ])
187 expect(turns.map((t) => [t.id, t.content, t.timestamp])).toEqual([
188 ['u1', 'research', 10],
189 ['u2', 'what is 2 + 2', 30],
190 ])
191 const researcher = agents.filter((agent) => agent.id === 'sub-1')
192 const groups = groupTimeline(
193 [iteration('root-2', 'run-2', 0, 31)],
194 // The server conversation only knows turn 2.
195 [user('u2-server', 31, 'root-2')],
196 researcher.map((agent) => ({ ...agent, turn: 0 })),
197 turns,
198 )
199 expect(groups.map((g) => g.userMessage?.id)).toEqual(['u1', 'u2'])
200 expect(groups[0]?.agents.map((g) => g.agent.id)).toEqual(['sub-1'])
201 expect(groups[1]?.iterations.map((i) => i.requestId)).toEqual(['root-2'])
202 })
203
204 it('returns no turns when a user message has no createdAt', () => {
205 expect(snapshotTurns([{ id: 'u1', role: 'user', parts: [] }])).toEqual([])
206 })
207})
208
209describe('collectServerSteps', () => {
210 it('pulls child steps from the child thread conversation', () => {
211 const agents = collectSubagents(snapshot)
212 const root = {
213 iterations: [iteration('root-2', 'run-2', 0, 30)],
214 messages: [user('u2', 29, 'root-2')],
215 }
216 const childThread = {
217 iterations: [iteration('child-a', 'run-1:sub-1', 0, 11)],
218 messages: [
219 {
220 id: 'child-msg',
221 role: 'assistant' as const,
222 content: 'notes',
223 timestamp: 11,
224 },
225 ],
226 }
227 const other = {
228 iterations: [iteration('x', 'run-9', 0, 5)],
229 messages: [user('other', 5, 'x')],
230 }
231 const steps = collectServerSteps(root, [root, childThread, other], agents)
232 expect(steps.iterations.map((i) => i.requestId)).toEqual([
233 'root-2',
234 'child-a',
235 ])
236 expect(steps.messages.map((m) => m.id)).toEqual(['u2', 'child-msg'])
237 })
238})
239
240describe('buildSubagentSteps', () => {
241 it('ends a step after its tool results', () => {
242 const agent = collectSubagents(snapshot)[0]
243 if (!agent) throw new Error('no agent')
244 const { iterations, messages } = buildSubagentSteps(agent)
245
246 expect(iterations).toHaveLength(2)
247 expect(iterations[0]?.finishReason).toBe('tool_calls')
248 expect(iterations[1]?.finishReason).toBe('stop')
249
250 const first = messages.find((m) => m.id === iterations[0]?.messageId)
251 expect(first?.thinkingContent).toBe('Look up the facts first.')
252 expect(first?.toolCalls?.[0]).toMatchObject({
253 name: 'lookupFacts',
254 result: { facts: ['three hearts'] },
255 })
256 const result = messages.find(
257 (m) => m.role === 'tool' && iterations[0]?.messageIds.includes(m.id),
258 )
259 expect(result?.content).toBe('{"facts":["three hearts"]}')
260
261 const second = messages.find((m) => m.id === iterations[1]?.messageId)
262 expect(second?.content).toBe('Squids have three hearts.')
263 })
264
265 it('keeps parallel tool results in one step', () => {
266 const { iterations } = buildSubagentSteps({
267 id: 'sub-3',
268 name: 'x',
269 path: 'x',
270 turn: 0,
271 status: 'running',
272 messages: [
273 {
274 role: 'assistant',
275 parts: [
276 { type: 'tool-call', id: 'a', name: 'one', arguments: '{}' },
277 { type: 'tool-call', id: 'b', name: 'two', arguments: '{}' },
278 { type: 'tool-result', toolCallId: 'a', content: '1' },
279 { type: 'tool-result', toolCallId: 'b', content: '2' },
280 ],
281 },
282 ],
283 })
284 expect(iterations).toHaveLength(1)
285 expect(iterations[0]?.messageIds).toHaveLength(3)
286 // A running child's last step is still open.
287 expect(iterations[0]?.completedAt).toBeUndefined()
288 })
289})