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

harness-protocol.spec.ts

617 lines20.4 KB

1import { test, expect } from './fixtures'
2import { openHarnessThread } from './helpers'
3​
4test.describe('harness protocol', () => {
5 const headers = (testId: string, aimockPort: number) => ({
6 authorization: 'Bearer e2e-token',
7 'x-test-id': testId,
8 'x-aimock-port': String(aimockPort),
9 })
10​
11 test('refuses a request without the token', async ({ request }) => {
12 const response = await request.get('/api/harness-protocol/capabilities')
13 expect(response.status()).toBe(401)
14 })
15​
16 test('lists exposed agents in the capabilities', async ({
17 request,
18 testId,
19 aimockPort,
20 }) => {
21 const response = await request.get('/api/harness-protocol/capabilities', {
22 headers: headers(testId, aimockPort),
23 })
24 const body = await response.json()
25 expect(body.identity.name).toBe('e2e/protocol')
26 expect(body.custom.tanstack.agents[0].name).toBe('echo')
27 })
28​
29 test('streams a standard AG-UI run through a session', async ({
30 request,
31 testId,
32 aimockPort,
33 }) => {
34 const response = await request.post('/api/harness-protocol/run', {
35 headers: {
36 ...headers(testId, aimockPort),
37 'content-type': 'application/json',
38 },
39 data: {
40 threadId: `protocol-${testId}`,
41 // The run id is also the input id, so each test needs its own.
42 runId: `client-run-${testId}`,
43 messages: [
44 { id: 'u1', role: 'user', content: '[harness-protocol] hello' },
45 ],
46 tools: [],
47 context: [],
48 state: {},
49 forwardedProps: {},
50 },
51 })
52 expect(response.headers()['content-type']).toContain('text/event-stream')
53 const text = await response.text()
54 const events = text
55 .split('\n')
56 .filter((line) => line.startsWith('data: '))
57 .map((line) => JSON.parse(line.slice(6)))
58 const answer = events
59 .filter((event) => event.type === 'TEXT_MESSAGE_CONTENT')
60 .map((event) => event.delta)
61 .join('')
62 expect(answer).toBe('Hello over the harness protocol.')
63 // The turn runs as the run id the client sent.
64 expect(events.find((event) => event.type === 'RUN_STARTED').runId).toBe(
65 `client-run-${testId}`,
66 )
67 expect(events.at(-1).name).toBe('harness.operation.finished')
68 })
69​
70 test('changes a plugin setting and runs a plugin command', async ({
71 request,
72 testId,
73 aimockPort,
74 }) => {
75 const control = async (input: unknown) =>
76 (
77 await request.post('/api/harness-protocol/control', {
78 headers: {
79 ...headers(testId, aimockPort),
80 'content-type': 'application/json',
81 },
82 data: { threadId: `plugins-${testId}`, input },
83 })
84 ).json()
85​
86 expect(
87 await control({ op: 'config', key: 'tone', value: 'warm' }),
88 ).toMatchObject({
89 status: 'accepted',
90 })
91 const rejected = await control({ op: 'config', key: 'tone', value: 'loud' })
92 expect(rejected.status).toBe('rejected')
93 expect(rejected.reason).toContain('plain, warm')
94 const command = await control({ op: 'command', name: 'greet' })
95 expect(command.status).toBe('accepted')
96 expect(command.operationId).toMatch(/^op-command-/)
97 })
98​
99 test('refuses a command and a config key that the harness does not expose', async ({
100 request,
101 testId,
102 aimockPort,
103 }) => {
104 const control = async (input: unknown) =>
105 (
106 await request.post('/api/harness-protocol/control', {
107 headers: {
108 ...headers(testId, aimockPort),
109 'content-type': 'application/json',
110 },
111 data: { threadId: `expose-${testId}`, input },
112 })
113 ).json()
114​
115 expect(
116 await control({ op: 'command', name: 'mode', input: 'bypass' }),
117 ).toMatchObject({ status: 'rejected', reason: 'not_exposed' })
118 expect(
119 await control({ op: 'config', key: 'mode', value: 'bypass' }),
120 ).toMatchObject({ status: 'rejected', reason: 'not_exposed' })
121 })
122​
123 test('runs a retried prompt with the same inputId once on a durable host', async ({
124 request,
125 testId,
126 aimockPort,
127 }) => {
128 const threadId = `durable-${testId}`
129 const durable = { ...headers(testId, aimockPort), 'x-harness-durable': '1' }
130 const control = async (input: unknown) =>
131 (
132 await request.post('/api/harness-protocol/control', {
133 headers: { ...durable, 'content-type': 'application/json' },
134 data: { threadId, input },
135 })
136 ).json()
137 const prompt = {
138 op: 'prompt',
139 message: '[harness-durable] run once',
140 inputId: `once-${testId}`,
141 }
142​
143 const first = await control(prompt)
144 const retry = await control(prompt)
145​
146 expect(first.status).toBe('accepted')
147 expect(retry).toEqual(first)
148 const answers = async () => {
149 const response = await request.get(
150 `/api/harness-protocol/transcript?threadId=${threadId}`,
151 { headers: durable },
152 )
153 const transcript: Array<{ role: string; content: unknown }> =
154 await response.json()
155 return transcript
156 .filter((message) => message.role === 'assistant')
157 .map((message) => message.content)
158 }
159 await expect.poll(answers).toEqual(['Stored once.'])
160 expect(
161 await control({ ...prompt, message: '[harness-durable] other text' }),
162 ).toMatchObject({ status: 'rejected', reason: 'conflict' })
163 })
164​
165 test('retries a 503 from the model in the same turn', async ({
166 request,
167 testId,
168 aimockPort,
169 }) => {
170 const threadId = `retry-${testId}`
171 const turnHeaders = {
172 ...headers(testId, aimockPort),
173 'x-harness-turn': 'retry',
174 }
175 const receipt = await (
176 await request.post('/api/harness-protocol/control', {
177 headers: { ...turnHeaders, 'content-type': 'application/json' },
178 data: {
179 threadId,
180 input: { op: 'prompt', message: '[harness-retry] try twice' },
181 },
182 })
183 ).json()
184 expect(receipt.status).toBe('accepted')
185​
186 const answers = async () => {
187 const response = await request.get(
188 `/api/harness-protocol/transcript?threadId=${threadId}`,
189 { headers: turnHeaders },
190 )
191 const transcript: Array<{ role: string; content: unknown }> =
192 await response.json()
193 return transcript
194 .filter((message) => message.role === 'assistant')
195 .map((message) => message.content)
196 }
197 await expect.poll(answers).toEqual(['Back after a retry.'])
198 })
199​
200 test('sends the model back to work with beforeFinish', async ({
201 request,
202 testId,
203 aimockPort,
204 }) => {
205 const threadId = `finish-${testId}`
206 const turnHeaders = {
207 ...headers(testId, aimockPort),
208 'x-harness-turn': 'finish',
209 }
210 await request.post('/api/harness-protocol/control', {
211 headers: { ...turnHeaders, 'content-type': 'application/json' },
212 data: {
213 threadId,
214 input: { op: 'prompt', message: '[harness-finish] post it' },
215 },
216 })
217​
218 const transcript = async () => {
219 const response = await request.get(
220 `/api/harness-protocol/transcript?threadId=${threadId}`,
221 { headers: turnHeaders },
222 )
223 const messages: Array<{ role: string; content: unknown }> =
224 await response.json()
225 return messages.map(
226 (message) => `${message.role}: ${String(message.content)}`,
227 )
228 }
229 await expect
230 .poll(transcript)
231 .toEqual([
232 'user: [harness-finish] post it',
233 'assistant: Draft answer.',
234 'user: [harness-finish] reminder: post the answer',
235 'assistant: Posted answer.',
236 ])
237 })
238​
239 test('reverts to an earlier message, then unreverts', async ({
240 request,
241 testId,
242 aimockPort,
243 }) => {
244 const threadId = `revert-${testId}`
245 const json = {
246 ...headers(testId, aimockPort),
247 'content-type': 'application/json',
248 }
249 const control = async (input: unknown) =>
250 (
251 await request.post('/api/harness-protocol/control', {
252 headers: json,
253 data: { threadId, input },
254 })
255 ).json()
256 const transcript = async () => {
257 const response = await request.get(
258 `/api/harness-protocol/transcript?threadId=${threadId}`,
259 { headers: json },
260 )
261 const messages: Array<{ id: string; role: string; content: unknown }> =
262 await response.json()
263 return messages
264 }
265 const lines = async () =>
266 (await transcript()).map(
267 (message) => `${message.role}: ${String(message.content)}`,
268 )
269 await control({ op: 'prompt', message: '[harness-revert] first' })
270 await expect.poll(lines).toHaveLength(2)
271 await control({ op: 'prompt', message: '[harness-revert] second' })
272 const all = [
273 'user: [harness-revert] first',
274 'assistant: First answer.',
275 'user: [harness-revert] second',
276 'assistant: Second answer.',
277 ]
278 await expect.poll(lines).toEqual(all)
279 const [, firstAnswer] = await transcript()
280​
281 // A refused revert changes nothing, so the test can ask again until the
282 // last turn has ended.
283 await expect
284 .poll(
285 async () =>
286 (await control({ op: 'revert', messageId: firstAnswer?.id })).status,
287 )
288 .toBe('accepted')
289 expect(await lines()).toEqual(all.slice(0, 2))
290​
291 expect(await control({ op: 'unrevert' })).toMatchObject({
292 status: 'accepted',
293 })
294 expect(await lines()).toEqual(all)
295 })
296​
297 test('gives an ephemeral reminder from beforeFinish to the next model call only', async ({
298 request,
299 testId,
300 aimockPort,
301 }) => {
302 const threadId = `ephemeral-${testId}`
303 const turnHeaders = {
304 ...headers(testId, aimockPort),
305 'x-harness-turn': 'ephemeral',
306 }
307 await request.post('/api/harness-protocol/control', {
308 headers: { ...turnHeaders, 'content-type': 'application/json' },
309 data: {
310 threadId,
311 input: { op: 'prompt', message: '[harness-finish] post it' },
312 },
313 })
314​
315 const transcript = async () => {
316 const response = await request.get(
317 `/api/harness-protocol/transcript?threadId=${threadId}`,
318 { headers: turnHeaders },
319 )
320 const messages: Array<{ role: string; content: unknown }> =
321 await response.json()
322 return messages.map(
323 (message) => `${message.role}: ${String(message.content)}`,
324 )
325 }
326 // The transcript does not keep the reminder.
327 await expect
328 .poll(transcript)
329 .toEqual([
330 'user: [harness-finish] post it',
331 'assistant: Draft answer.',
332 'assistant: Posted answer.',
333 ])
334​
335 // The second model call got the reminder as its last message.
336 const journal = await request.get(
337 `http://127.0.0.1:${aimockPort}/v1/_requests`,
338 )
339 const entries: Array<{
340 headers?: Record<string, string>
341 body: { messages?: Array<{ role: string; content: unknown }> } | null
342 }> = await journal.json()
343 const lastSent = entries
344 .filter((entry) => entry.headers?.['x-test-id'] === testId)
345 .map((entry) => entry.body?.messages?.at(-1)?.content)
346 expect(lastSent).toEqual([
347 '[harness-finish] post it',
348 '[harness-finish] reminder: post the answer',
349 ])
350 })
351​
352 test('takes a control input and returns a receipt', async ({
353 request,
354 testId,
355 aimockPort,
356 }) => {
357 const response = await request.post('/api/harness-protocol/control', {
358 headers: {
359 ...headers(testId, aimockPort),
360 'content-type': 'application/json',
361 },
362 data: {
363 threadId: `control-${testId}`,
364 input: { op: 'agent', agent: 'echo', input: { text: 'hi' } },
365 },
366 })
367 const receipt = await response.json()
368 expect(receipt.status).toBe('accepted')
369 expect(receipt.operationId).toMatch(/^op-agent-/)
370 })
371​
372 test('lists, renames, and forks sessions with their settings', async ({
373 request,
374 testId,
375 aimockPort,
376 }) => {
377 const auth = headers(testId, aimockPort)
378 const json = { ...auth, 'content-type': 'application/json' }
379 const first = `sessions-a-${testId}`
380 const second = `sessions-b-${testId}`
381 const settings = { model: 'strong', instructions: 'Answer in one word.' }
382 const configured = await request.post('/api/harness-protocol/control', {
383 headers: json,
384 data: { threadId: first, input: { op: 'configure', settings } },
385 })
386 expect(await configured.json()).toMatchObject({ status: 'accepted' })
387 const run = await request.post('/api/harness-protocol/run', {
388 headers: json,
389 data: {
390 threadId: first,
391 runId: `sessions-run-${testId}`,
392 messages: [
393 { id: 'u1', role: 'user', content: '[harness-protocol] hello' },
394 ],
395 tools: [],
396 context: [],
397 state: {},
398 forwardedProps: {},
399 },
400 })
401 // The stream ends with the turn.
402 await run.text()
403 // The second thread only opens.
404 await openHarnessThread(request, auth, second)
405​
406 const sessions = (body: object) =>
407 request.post('/api/harness-protocol/sessions', {
408 headers: json,
409 data: body,
410 })
411 const title = 'Trip plan'
412 const renamed = await sessions({ op: 'rename', threadId: first, title })
413 expect(await renamed.json()).toMatchObject({ threadId: first, title })
414​
415 const transcript = async (threadId: string) => {
416 const response = await request.get(
417 `/api/harness-protocol/transcript?threadId=${threadId}`,
418 { headers: auth },
419 )
420 const messages: Array<{ id?: string; role: string; content: unknown }> =
421 await response.json()
422 return messages
423 }
424 const source = await transcript(first)
425 expect(source.map((message) => message.role)).toEqual(['user', 'assistant'])
426 const at = source[0]?.id
427 if (!at) throw new Error('The prompt has no message id.')
428 const forked = await sessions({ op: 'fork', threadId: first, through: at })
429 expect(forked.status()).toBe(200)
430 const fork: { threadId: string; title?: string } = await forked.json()
431 expect(fork.title).toBe(`${title} (fork)`)
432 // The fork has the messages through the prompt, and the stored settings.
433 const copied = await transcript(fork.threadId)
434 expect(copied.map((message) => message.content)).toEqual([
435 '[harness-protocol] hello',
436 ])
437 const described = await request.get(
438 `/api/harness-protocol/describe?threadId=${fork.threadId}`,
439 { headers: auth },
440 )
441 expect((await described.json()).settings).toMatchObject(settings)
442​
443 // The host is shared, so the list has the threads of other tests too.
444 const response = await request.get('/api/harness-protocol/sessions', {
445 headers: auth,
446 })
447 const listed: { entries: Array<{ threadId: string; title?: string }> } =
448 await response.json()
449 const titles = Object.fromEntries(
450 listed.entries.map((entry) => [entry.threadId, entry.title ?? null]),
451 )
452 expect(titles).toMatchObject({
453 [first]: title,
454 [second]: null,
455 [fork.threadId]: `${title} (fork)`,
456 })
457 })
458​
459 test('lists the child of a thread with parentThreadId', async ({
460 request,
461 testId,
462 aimockPort,
463 }) => {
464 const auth = headers(testId, aimockPort)
465 const threadId = `children-${testId}`
466 const response = await request.post('/api/harness-protocol/control', {
467 headers: { ...auth, 'content-type': 'application/json' },
468 data: {
469 threadId,
470 input: { op: 'agent', agent: 'echo', input: { text: 'hi' } },
471 },
472 })
473 expect(await response.json()).toMatchObject({ status: 'accepted' })
474​
475 // The agent run is a child session `subagent:<id>` of the thread.
476 const query = new URLSearchParams({ parentThreadId: threadId })
477 await expect
478 .poll(async () => {
479 const listed = await request.get(
480 `/api/harness-protocol/sessions?${query}`,
481 { headers: auth },
482 )
483 const body: {
484 entries: Array<{ threadId: string; parentThreadId?: string }>
485 } = await listed.json()
486 return body.entries
487 })
488 .toEqual([
489 expect.objectContaining({
490 threadId: expect.stringMatching(/^subagent:/),
491 parentThreadId: threadId,
492 }),
493 ])
494 })
495​
496 test('searches the session list by title, without case', async ({
497 request,
498 testId,
499 aimockPort,
500 }) => {
501 const auth = headers(testId, aimockPort)
502 const json = { ...auth, 'content-type': 'application/json' }
503 const titles = {
504 [`search-a-${testId}`]: `Plan the trip ${testId}`,
505 [`search-b-${testId}`]: `Write the docs ${testId}`,
506 [`search-c-${testId}`]: `Trip budget ${testId}`,
507 }
508 for (const [threadId, title] of Object.entries(titles)) {
509 await openHarnessThread(request, auth, threadId)
510 const renamed = await request.post('/api/harness-protocol/sessions', {
511 headers: json,
512 data: { op: 'rename', threadId, title },
513 })
514 expect(renamed.status()).toBe(200)
515 }
516​
517 // The test id keeps out the threads of other tests on the shared host.
518 const query = new URLSearchParams({ search: `TRIP ${testId}` })
519 const response = await request.get(
520 `/api/harness-protocol/sessions?${query}`,
521 { headers: auth },
522 )
523 const listed: { entries: Array<{ threadId: string }> } =
524 await response.json()
525 expect(listed.entries.map((entry) => entry.threadId)).toEqual([
526 `search-a-${testId}`,
527 ])
528 const budget = await request.get(
529 `/api/harness-protocol/sessions?${new URLSearchParams({ search: 'trip' })}`,
530 { headers: auth },
531 )
532 const found: { entries: Array<{ threadId: string }> } = await budget.json()
533 expect(found.entries.map((entry) => entry.threadId)).toEqual(
534 expect.arrayContaining([`search-a-${testId}`, `search-c-${testId}`]),
535 )
536 expect(found.entries.map((entry) => entry.threadId)).not.toContain(
537 `search-b-${testId}`,
538 )
539 })
540​
541 test('shows running, then idle, on the host status feed', async ({
542 request,
543 baseURL,
544 testId,
545 aimockPort,
546 }) => {
547 const auth = headers(testId, aimockPort)
548 const threadId = `status-${testId}`
549 // Open the session first, so the feed starts with its status.
550 await openHarnessThread(request, auth, threadId)
551 const feed = await fetch(`${baseURL}/api/harness-protocol/host-events`, {
552 headers: auth,
553 })
554 if (!feed.body) throw new Error('The status feed has no stream.')
555 const reader = feed.body.pipeThrough(new TextDecoderStream()).getReader()
556 // The feed has every session of this user. This test reads its own.
557 const statuses: Array<string> = []
558 let buffer = ''
559 while (statuses.length < 3) {
560 const read = await reader.read()
561 if (read.done) break
562 buffer += read.value
563 const blocks = buffer.split('\n\n')
564 buffer = blocks.pop() ?? ''
565 for (const block of blocks) {
566 if (!block.startsWith('data: ')) continue
567 const event: { type: string; threadId?: string; status?: string } =
568 JSON.parse(block.slice('data: '.length))
569 const isOurs = event.type === 'status' && event.threadId === threadId
570 if (!isOurs || !event.status) continue
571 statuses.push(event.status)
572 if (statuses.length > 1) continue
573 // The first status shows that the feed reads, so start a turn now.
574 const receipt = await request.post('/api/harness-protocol/control', {
575 headers: { ...auth, 'content-type': 'application/json' },
576 data: {
577 threadId,
578 input: { op: 'prompt', message: '[harness-protocol] hello' },
579 },
580 })
581 expect(await receipt.json()).toMatchObject({ status: 'accepted' })
582 }
583 }
584 await reader.cancel()
585 expect(statuses).toEqual(['idle', 'running', 'idle'])
586 })
587​
588 test('an unsupported v gets an error frame with a requestId', async ({
589 request,
590 testId,
591 aimockPort,
592 }) => {
593 const auth = headers(testId, aimockPort)
594 const threadId = `version-${testId}`
595 await openHarnessThread(request, auth, threadId)
596​
597 // The host sends one error frame, then closes the stream.
598 const response = await request.get(
599 `/api/harness-protocol/events?threadId=${threadId}&v=9`,
600 { headers: { ...auth, 'x-request-id': 'e2e-version-9' } },
601 )
602 expect(response.headers()['x-request-id']).toBe('e2e-version-9')
603 const frames = (await response.text())
604 .split('\n')
605 .filter((line) => line.startsWith('data: '))
606 .map((line) => JSON.parse(line.slice('data: '.length)))
607 expect(frames).toEqual([
608 {
609 type: 'harness.error',
610 message:
611 'Protocol version 9 is not supported. This host speaks version 2.',
612 code: 'unsupported_version',
613 requestId: 'e2e-version-9',
614 },
615 ])
616 })
617})