Open History to see the last commit
1import { test, expect } from './fixtures'
2import type { APIRequestContext } from '@playwright/test'
3
4const ROUTE = '/api/harness-handoff'
5
6interface Started {
7 error?: string
8 runId: string
9 threadId: string
10}
11
12interface Debug {
13 error?: string
14 status: string
15 handoffs: Array<Record<string, unknown>>
16 transcript: Array<{
17 role: string
18 text: string
19 harness: { agent?: string; operator?: string } | null
20 }>
21 view: Array<{ role: string; agent: string | null; text: string }>
22 waits: Array<{ waitId: string; kind: string; message?: string }>
23 mainCalls: number
24 billingCalls: number
25 /** The messages of the first request of `billing`, as Anthropic gets them. */
26 billingMessages: Array<{ role: string; content: unknown }>
27}
28
29/** Open the thread of `scenario` for olga, shared with bea. */
30async function start(
31 request: APIRequestContext,
32 scenario: 'agent' | 'human' | 'code',
33) {
34 const res = await request.post(`${ROUTE}/start`, { data: { scenario } })
35 expect(res.ok()).toBe(true)
36 const started: Started = await res.json()
37 expect(started.error ?? null).toBeNull()
38 return started
39}
40
41/** Send one protocol input as `user`. Returns the receipt. */
42async function control(
43 request: APIRequestContext,
44 { runId, threadId }: Started,
45 input: Record<string, unknown>,
46 user = 'olga',
47) {
48 const res = await request.post(`${ROUTE}/control?runId=${runId}`, {
49 data: { threadId, input },
50 headers: { authorization: user },
51 })
52 expect(res.ok()).toBe(true)
53 const receipt: { status: string; reason?: string } = await res.json()
54 return receipt
55}
56
57/** Wait until the input `inputId` ends, and return how it ended. */
58async function outcomeOf(
59 request: APIRequestContext,
60 runId: string,
61 inputId: string,
62) {
63 let outcome: string | undefined
64 await expect
65 .poll(
66 async () => {
67 const res = await request.get(
68 `${ROUTE}/settled?runId=${runId}&inputId=${inputId}`,
69 )
70 const settled: { error?: string; outcome?: string } = await res.json()
71 outcome = settled.outcome
72 return settled.error ?? outcome !== undefined
73 },
74 { timeout: 20_000 },
75 )
76 .toBe(true)
77 return outcome
78}
79
80async function debug(request: APIRequestContext, runId: string) {
81 const res = await request.get(`${ROUTE}/debug?runId=${runId}`)
82 const read: Debug = await res.json()
83 return read
84}
85
86/** Read the run until `isDone` is true for it. */
87async function readUntil(
88 request: APIRequestContext,
89 runId: string,
90 isDone: (read: Debug) => boolean,
91) {
92 let read: Debug | undefined
93 await expect
94 .poll(
95 async () => {
96 read = await debug(request, runId)
97 return read.error ?? isDone(read)
98 },
99 { timeout: 20_000 },
100 )
101 .toBe(true)
102 return read!
103}
104
105/** The role and text of each message, and who wrote it. */
106const lines = (read: Debug) =>
107 read.transcript.map(({ role, text, harness }) => ({
108 role,
109 text,
110 by: harness?.agent ?? harness?.operator ?? null,
111 }))
112
113const stop = (request: APIRequestContext, runId: string) =>
114 request.post(`${ROUTE}/stop?runId=${runId}`)
115
116test.describe('harness: handoffs inside one session', () => {
117 test('the main model hands the turn to an agent, the agent answers in the same turn, and the next turn goes to it', async ({
118 request,
119 }) => {
120 const started = await start(request, 'agent')
121 try {
122 const sent = await control(request, started, {
123 op: 'prompt',
124 message: 'refund please',
125 inputId: 'in-1',
126 })
127 expect(sent.status).toBe('accepted')
128 expect(await outcomeOf(request, started.runId, 'in-1')).toBe('completed')
129
130 const first = await readUntil(request, started.runId, (read) =>
131 read.view.some((message) => message.agent === 'billing'),
132 )
133 // The session stream has one handoff event.
134 expect(first.handoffs).toEqual([
135 {
136 from: null,
137 to: 'billing',
138 note: 'Refund for order 42.',
139 by: 'tool',
140 runId: expect.any(String),
141 },
142 ])
143 // The answer of the turn comes from billing, and has its name.
144 expect(lines(first)).toEqual([
145 { role: 'user', text: 'refund please', by: null },
146 { role: 'assistant', text: '', by: null },
147 {
148 role: 'tool',
149 text: 'Handed off to billing. billing answers next.',
150 by: null,
151 },
152 {
153 role: 'assistant',
154 text: 'billing:\nYour refund is on its way.',
155 by: 'billing',
156 },
157 ])
158 expect(first.mainCalls).toBe(1)
159 expect(first.billingCalls).toBe(1)
160
161 // The router picks nothing, so the active agent answers.
162 await control(request, started, {
163 op: 'prompt',
164 message: 'and now?',
165 inputId: 'in-2',
166 })
167 expect(await outcomeOf(request, started.runId, 'in-2')).toBe('completed')
168 const second = await readUntil(
169 request,
170 started.runId,
171 (read) => read.transcript.length === 6,
172 )
173 expect(lines(second).slice(4)).toEqual([
174 { role: 'user', text: 'and now?', by: null },
175 { role: 'assistant', text: 'billing:\nBilling again.', by: 'billing' },
176 ])
177 expect(second.mainCalls).toBe(1)
178 expect(second.billingCalls).toBe(2)
179 expect(second.handoffs).toHaveLength(1)
180 // A client view names the agent on its messages.
181 expect(
182 second.view
183 .filter((message) => message.role === 'assistant')
184 .map((message) => message.agent),
185 ).toEqual([null, 'billing', 'billing'])
186 } finally {
187 await stop(request, started.runId)
188 }
189 })
190
191 test('a router and a code handoff put a handoff note in the request of the target model', async ({
192 request,
193 }) => {
194 const started = await start(request, 'code')
195 try {
196 await control(request, started, {
197 op: 'prompt',
198 message: 'refund please',
199 inputId: 'in-1',
200 })
201 expect(await outcomeOf(request, started.runId, 'in-1')).toBe('completed')
202
203 const read = await readUntil(request, started.runId, (done) =>
204 done.view.some((message) => message.agent === 'billing'),
205 )
206 expect(read.handoffs).toEqual([
207 expect.objectContaining({ from: null, to: 'triage', by: 'router' }),
208 expect.objectContaining({
209 from: 'triage',
210 to: 'billing',
211 note: 'Refund for order 42.',
212 by: 'code',
213 }),
214 ])
215 expect(read.mainCalls).toBe(0)
216 expect(read.billingCalls).toBe(1)
217 // The model of billing gets the note of its handoff last: a `handoff`
218 // tool call with the note, and its result.
219 const [noteCall, noteResult] = read.billingMessages.slice(-2)
220 expect(noteCall).toMatchObject({
221 role: 'assistant',
222 content: expect.arrayContaining([
223 expect.objectContaining({
224 type: 'tool_use',
225 name: 'handoff',
226 input: { to: 'billing', note: 'Refund for order 42.' },
227 }),
228 ]),
229 })
230 expect(noteResult).toMatchObject({ role: 'user' })
231 expect(JSON.stringify(noteResult)).toContain(
232 'Handed off to billing. billing answers next.',
233 )
234 expect(lines(read).at(-1)).toEqual({
235 role: 'assistant',
236 text: 'billing:\nYour refund is on its way.',
237 by: 'billing',
238 })
239 } finally {
240 await stop(request, started.runId)
241 }
242 })
243
244 test('a handoff to a person pauses the session until an operator gives it back', async ({
245 request,
246 }) => {
247 const started = await start(request, 'human')
248 try {
249 await control(request, started, {
250 op: 'prompt',
251 message: 'I want a person.',
252 inputId: 'in-1',
253 })
254 expect(await outcomeOf(request, started.runId, 'in-1')).toBe(
255 'interrupted',
256 )
257 // The operator bea sees the human wait over the protocol.
258 const res = await request.get(
259 `${ROUTE}/snapshot?runId=${started.runId}&threadId=${started.threadId}`,
260 { headers: { authorization: 'bea' } },
261 )
262 const snapshot: { pendingWaits: Debug['waits'] } = await res.json()
263 expect(snapshot.pendingWaits).toEqual([
264 expect.objectContaining({
265 kind: 'human',
266 message: 'The user asks for a person.',
267 }),
268 ])
269 const waitId = snapshot.pendingWaits[0]!.waitId
270
271 // A user message during the pause gets no model answer.
272 await control(request, started, {
273 op: 'prompt',
274 message: 'Hello? Anyone there?',
275 inputId: 'in-2',
276 })
277 expect(await outcomeOf(request, started.runId, 'in-2')).toBe(
278 'interrupted',
279 )
280
281 // The operator bea replies.
282 const reply = await control(
283 request,
284 started,
285 {
286 op: 'prompt',
287 message: 'Hi, I am Bea. I can help.',
288 as: 'operator',
289 inputId: 'op-1',
290 },
291 'bea',
292 )
293 expect(reply.status).toBe('accepted')
294 expect(await outcomeOf(request, started.runId, 'op-1')).toBe('completed')
295
296 const paused = await readUntil(request, started.runId, (read) =>
297 read.view.some(
298 (message) => message.text === 'Hi, I am Bea. I can help.',
299 ),
300 )
301 expect(paused.handoffs).toEqual([
302 {
303 from: null,
304 to: { human: true },
305 note: 'The user asks for a person.',
306 by: 'tool',
307 runId: expect.any(String),
308 waitId,
309 agents: ['billing'],
310 },
311 ])
312 expect(lines(paused).slice(3)).toEqual([
313 { role: 'user', text: 'Hello? Anyone there?', by: null },
314 { role: 'assistant', text: 'Hi, I am Bea. I can help.', by: 'bea' },
315 ])
316 expect(paused.mainCalls).toBe(1)
317 expect(paused.waits).toHaveLength(1)
318
319 // The operator gives the thread back to the main model.
320 const answered = await control(
321 request,
322 started,
323 { op: 'answer', questionId: waitId, value: { resume: true } },
324 'bea',
325 )
326 expect(answered.status).toBe('accepted')
327 await control(request, started, {
328 op: 'prompt',
329 message: 'Thanks.',
330 inputId: 'in-3',
331 })
332 expect(await outcomeOf(request, started.runId, 'in-3')).toBe('completed')
333
334 const back = await readUntil(
335 request,
336 started.runId,
337 (read) => read.transcript.length === 7,
338 )
339 expect(lines(back).slice(5)).toEqual([
340 { role: 'user', text: 'Thanks.', by: null },
341 { role: 'assistant', text: 'The main model is back.', by: null },
342 ])
343 expect(back.waits).toEqual([])
344 expect(back.mainCalls).toBe(2)
345 expect(back.handoffs.at(-1)).toEqual({
346 from: { human: true },
347 to: null,
348 by: 'operator',
349 runId: expect.any(String),
350 })
351 } finally {
352 await stop(request, started.runId)
353 }
354 })
355})