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

harness-agent-tree.spec.ts

152 lines4.4 KB

1import { test, expect } from './fixtures'
2import type { APIRequestContext } from '@playwright/test'
3​
4const ROUTE = '/api/harness-agent-tree'
5​
6interface AgentRun {
7 runId: string
8 agent: string
9 status: string
10 parentRunId: string | null
11 error: { message: string; code?: string } | null
13​
14interface GroupResult {
15 results: Array<string>
16 leadRunId: string
17 runs: Array<AgentRun>
18 order: Array<string>
19 maxActive: number
21​
22interface BudgetResult {
23 leadResult: string
24 leadRunId: string
25 runs: Array<AgentRun>
27​
28interface StateResult {
29 count: number
30 runs: Array<AgentRun>
32​
33interface HarnessAgentResult {
34 text: string
35 turnId: string
36 childTextParentRunId: string | null
37 totalTokens: number
38 threadId: string
39 childThread: string | null
40 openError: string | null
42​
43interface Read<T> {
44 error?: string
45 done: boolean
46 result: T | null
48​
49/** Run `scenario` on the server, and return its result when it ends. */
50async function runScenario<T>(request: APIRequestContext, scenario: string) {
51 const res = await request.post(ROUTE, { data: { scenario } })
52 expect(res.ok()).toBe(true)
53 const started: { error?: string; runId: string } = await res.json()
54 expect(started.error ?? null).toBeNull()
55​
56 let read: Read<T> | undefined
57 await expect
58 .poll(
59 async () => {
60 const got = await request.get(`${ROUTE}?runId=${started.runId}`)
61 read = await got.json()
62 return read?.error ?? read?.done
63 },
64 { timeout: 20_000 },
65 )
66 .toBe(true)
67 return read!.result!
69​
70test.describe('harness: the agent tree of a session', () => {
71 test('a group runs its agents two at a time, returns the results in order, and keeps them as children of the lead run', async ({
72 request,
73 }) => {
74 const result = await runScenario<GroupResult>(request, 'group')
75​
76 expect(result.results).toEqual(['a: auth', 'b: billing', 'c: search'])
77 // `a` and `b` start first. `c` waits for a slot, and starts after one
78 // of them ends.
79 expect(result.maxActive).toBe(2)
80 expect([...result.order.slice(0, 2)].sort()).toEqual(['start a', 'start b'])
81 const firstEnd = result.order.findIndex((entry) => entry.startsWith('end '))
82 expect(result.order.indexOf('start c')).toBeGreaterThan(firstEnd)
83​
84 // The run tree: the lead is a root run, and a, b, and c are its children.
85 expect(result.runs).toEqual([
86 expect.objectContaining({
87 runId: result.leadRunId,
88 agent: 'lead',
89 status: 'completed',
90 parentRunId: null,
91 }),
92 ...['a', 'b', 'c'].map((agent) =>
93 expect.objectContaining({
94 agent,
95 status: 'completed',
96 parentRunId: result.leadRunId,
97 }),
98 ),
99 ])
100 })
101​
102 test('a run over its token budget fails with code budget, and its parent sees the code', async ({
103 request,
104 }) => {
105 const result = await runScenario<BudgetResult>(request, 'budget')
106​
107 // The lead caught the error of the worker and returned its code.
108 expect(result.leadResult).toBe('budget')
109 expect(result.runs).toEqual([
110 expect.objectContaining({ agent: 'lead', status: 'completed' }),
111 expect.objectContaining({
112 agent: 'worker',
113 status: 'failed',
114 parentRunId: result.leadRunId,
115 error: expect.objectContaining({ code: 'budget' }),
116 }),
117 ])
118 })
119​
120 test('two agents update one shared state, and the value has both updates', async ({
121 request,
122 }) => {
123 const result = await runScenario<StateResult>(request, 'state')
124​
125 // 0 + 1 + 10: neither update was lost.
126 expect(result.count).toBe(11)
127 expect(
128 result.runs.filter((run) => run.agent === 'adder').map((r) => r.status),
129 ).toEqual(['completed', 'completed'])
130 })
131​
132 test('harnessAgent runs a child harness in the session tree', async ({
133 request,
134 }) => {
135 const result = await runScenario<HarnessAgentResult>(
136 request,
137 'harness-agent',
138 )
139​
140 expect(result.text).toBe('Done.')
141 // The text of the child reaches the parent stream, marked with the run
142 // that called it.
143 expect(result.childTextParentRunId).toBe(result.turnId)
144 // Two lead calls of 6 tokens, and one child call of 41 tokens.
145 expect(result.totalTokens).toBe(53)
146 // The child has its own thread under the root, and nobody opens it alone.
147 expect(result.childThread).toMatch(
148 new RegExp(`^${result.threadId}/agent/.+`),
149 )
150 expect(result.openError).toContain('is the thread of a harnessAgent child')
151 })
152})