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

harness-protocol-inputs.spec.ts

827 lines26.6 KB

1import { ChatClient, fetchServerSentEvents } from '@tanstack/ai-client'
2import { deploy } from '../src/lib/harness-protocol-tools'
3import { test, expect } from './fixtures'
4import { openHarnessThread } from './helpers'
5import type { APIRequestContext } from '@playwright/test'
6​
7type Chunk = {
8 type: string
9 runId?: string
10 name?: string
11 delta?: string
12 content?: string
13 outcome?: {
14 type: string
15 interrupts?: Array<{ id: string; metadata?: Record<string, any> }>
16 }
18​
19// Each event has an `id:` line (its log cursor) before its `data:` line.
20const sse = (text: string): Array<Chunk> =>
21 text
22 .split('\n')
23 .filter((line) => line.startsWith('data: '))
24 .map((line) => JSON.parse(line.slice('data: '.length)))
25​
26const textOf = (chunks: Array<Chunk>) =>
27 chunks
28 .filter((chunk) => chunk.type === 'TEXT_MESSAGE_CONTENT')
29 .map((chunk) => chunk.delta)
30 .join('')
31​
32const toolResults = (chunks: Array<Chunk>) =>
33 chunks
34 .filter((chunk) => chunk.type === 'TOOL_CALL_RESULT')
35 .map((chunk) => chunk.content)
36​
37/** The interrupt that `RUN_FINISHED` stops the turn for. */
38const interruptOf = (chunks: Array<Chunk>) => {
39 const finished = chunks.find((chunk) => chunk.type === 'RUN_FINISHED')
40 const interrupt = finished?.outcome?.interrupts?.[0]
41 if (!interrupt) throw new Error('The turn did not stop for an approval.')
42 return interrupt
44​
45type Snapshot = {
46 pendingWaits: Array<{ waitId: string; message?: string }>
47 waitingInputs: Array<{ inputId: string; delivery: string }>
49​
50type JournalEntry = {
51 headers?: Record<string, string>
52 body: { messages?: Array<{ role: string; content: unknown }> } | null
54​
55/**
56 * The custom events of a session stream, from its start. It reads until
57 * `isDone` is true for the events so far.
58 */
59async function customEvents(
60 url: string,
61 headers: Record<string, string>,
62 isDone: (events: Array<{ name?: string; value?: unknown }>) => boolean,
63) {
64 const response = await fetch(url, { headers })
65 if (!response.body) throw new Error('The session stream has no body.')
66 const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
67 const events: Array<{ name?: string; value?: unknown }> = []
68 let buffer = ''
69 while (!isDone(events)) {
70 const read = await reader.read()
71 if (read.done) break
72 buffer += read.value
73 const blocks = buffer.split('\n\n')
74 buffer = blocks.pop() ?? ''
75 for (const block of blocks) {
76 // Each event has an `id:` line before its `data:` line.
77 const data = block.split('\n').find((line) => line.startsWith('data: '))
78 if (!data) continue
79 const frame: {
80 event?: { type: string; name?: string; value?: unknown }
81 } = JSON.parse(data.slice('data: '.length))
82 if (frame.event?.type === 'CUSTOM') {
83 events.push({ name: frame.event.name, value: frame.event.value })
84 }
85 }
86 }
87 await reader.cancel()
88 return events
90​
91/** One user of the harness protocol route: its headers and its requests. */
92function asUser(
93 request: APIRequestContext,
94 testId: string,
95 aimockPort: number,
96 token = 'e2e-token',
97 extraHeaders: Record<string, string> = {},
98) {
99 const headers = {
100 authorization: `Bearer ${token}`,
101 'x-test-id': testId,
102 'x-aimock-port': String(aimockPort),
103 ...extraHeaders,
104 }
105 const json = { ...headers, 'content-type': 'application/json' }
106 const run = (body: object) =>
107 request.post('/api/harness-protocol/run', {
108 headers: json,
109 data: { messages: [], tools: [], context: [], state: {}, ...body },
110 })
111 const control = async (threadId: string, input: unknown) =>
112 (
113 await request.post('/api/harness-protocol/control', {
114 headers: json,
115 data: { threadId, input },
116 })
117 ).json()
118 const read = async (route: string, threadId: string) =>
119 (
120 await request.get(`/api/harness-protocol/${route}?threadId=${threadId}`, {
121 headers,
122 })
123 ).json()
124 const transcript = (
125 threadId: string,
126 ): Promise<Array<{ id?: string; role: string; content: unknown }>> =>
127 read('transcript', threadId)
128 const answers = async (threadId: string) =>
129 (await transcript(threadId))
130 .filter((message) => message.role === 'assistant')
131 .map((message) => message.content)
132 const snapshot = (threadId: string): Promise<Snapshot> =>
133 read('snapshot', threadId)
134 /** The question that the thread waits for, or `undefined`. */
135 const question = async (threadId: string) =>
136 (await snapshot(threadId)).pendingWaits[0]
137 return {
138 headers,
139 json,
140 run,
141 control,
142 transcript,
143 answers,
144 snapshot,
145 question,
146 }
148​
149const userMessage = (content: string) => [{ id: 'u1', role: 'user', content }]
150​
151test.describe('harness protocol inputs', () => {
152 test('answers an approval on POST run with the run id the client sent', async ({
153 request,
154 testId,
155 aimockPort,
156 }) => {
157 const user = asUser(request, testId, aimockPort)
158 const threadId = `runid-${testId}`
159 const runId = `client-run-${testId}`
160 const body = {
161 threadId,
162 runId,
163 messages: userMessage('[harness-runid] deploy prod'),
164 forwardedProps: {},
165 }
166​
167 const first = sse(await (await user.run(body)).text())
168 expect(first.find((chunk) => chunk.type === 'RUN_STARTED')?.runId).toBe(
169 runId,
170 )
171 const interrupt = interruptOf(first)
172 // A client matches the interrupt against the run id it sent.
173 expect(
174 interrupt.metadata?.['tanstack:interruptBinding']?.interruptedRunId,
175 ).toBe(runId)
176​
177 // The same request again runs nothing: the model is not called again.
178 const retry = await user.run(body)
179 expect(retry.status()).toBe(200)
180 expect(await retry.text()).not.toContain('Deployed to prod.')
181​
182 // A ChatClient with `persistence` reads this when the page loads.
183 const hydrate = await (
184 await request.get(`/api/harness-protocol/run?threadId=${threadId}`, {
185 headers: user.headers,
186 })
187 ).json()
188 expect(
189 hydrate.messages.map((message: { role: string }) => message.role),
190 ).toEqual(['user', 'assistant'])
191 expect(hydrate.interrupts).toMatchObject({
192 runId,
193 pending: [{ id: interrupt.id }],
194 })
195​
196 const resumed = sse(
197 await (
198 await user.run({
199 threadId,
200 runId: `${runId}-resume`,
201 parentRunId: runId,
202 forwardedProps: {},
203 resume: [
204 {
205 interruptId: interrupt.id,
206 status: 'resolved',
207 payload: { approved: true },
208 },
209 ],
210 })
211 ).text(),
212 )
213 expect(resumed.find((chunk) => chunk.type === 'RUN_STARTED')?.runId).toBe(
214 `${runId}-resume`,
215 )
216 expect(toolResults(resumed).join('')).toContain('prod')
217 expect(textOf(resumed)).toBe('Deployed to prod.')
218 })
219​
220 test('accepts a resolve sent as soon as RUN_FINISHED arrives', async ({
221 request,
222 baseURL,
223 testId,
224 aimockPort,
225 }) => {
226 const user = asUser(request, testId, aimockPort)
227 const threadId = `fast-resolve-${testId}`
228 // Read the stream as it arrives, and answer on RUN_FINISHED.
229 const response = await fetch(`${baseURL}/api/harness-protocol/run`, {
230 method: 'POST',
231 headers: user.json,
232 body: JSON.stringify({
233 threadId,
234 runId: `fast-${testId}`,
235 messages: userMessage('[harness-fast-resolve] deploy stage'),
236 tools: [],
237 context: [],
238 state: {},
239 forwardedProps: {},
240 }),
241 })
242 if (!response.body) throw new Error('POST run has no stream.')
243 const reader = response.body
244 .pipeThrough(new TextDecoderStream())
245 .getReader()
246 let buffer = ''
247 let receipt: unknown
248 while (receipt === undefined) {
249 const read = await reader.read()
250 if (read.done) break
251 buffer += read.value
252 let end = buffer.indexOf('\n\n')
253 while (end !== -1 && receipt === undefined) {
254 const block = buffer.slice(0, end)
255 buffer = buffer.slice(end + 2)
256 end = buffer.indexOf('\n\n')
257 const data = block.split('\n').find((line) => line.startsWith('data: '))
258 if (!data) continue
259 const chunk: Chunk = JSON.parse(data.slice('data: '.length))
260 if (chunk.type !== 'RUN_FINISHED') continue
261 receipt = await user.control(threadId, {
262 op: 'resolve',
263 resume: [
264 {
265 interruptId: interruptOf([chunk]).id,
266 status: 'resolved',
267 payload: { approved: true },
268 },
269 ],
270 })
271 }
272 }
273 await reader.cancel()
274​
275 expect(receipt).toMatchObject({ status: 'accepted' })
276 await expect
277 .poll(() => user.answers(threadId))
278 .toContain('Deployed to stage.')
279 })
280​
281 test('gives forwardedProps to the tools as the input context', async ({
282 request,
283 testId,
284 aimockPort,
285 }) => {
286 const user = asUser(request, testId, aimockPort)
287 const chunks = sse(
288 await (
289 await user.run({
290 threadId: `context-${testId}`,
291 runId: `context-run-${testId}`,
292 messages: userMessage('[harness-context] probe'),
293 forwardedProps: { screen: 'settings' },
294 })
295 ).text(),
296 )
297 expect(toolResults(chunks).join('')).toContain('"screen":"settings"')
298 expect(textOf(chunks)).toBe('Probed the context.')
299 })
300​
301 test('runs an exposed tool with no model call, and refuses another tool', async ({
302 request,
303 testId,
304 aimockPort,
305 }) => {
306 const threadId = `tool-op-${testId}`
307 const user = asUser(request, testId, aimockPort)
308​
309 const receipt = await user.control(threadId, {
310 op: 'tool',
311 name: 'probe',
312 args: {},
313 inputId: `tool-op-input-${testId}`,
314 })
315 expect(receipt).toMatchObject({
316 inputId: `tool-op-input-${testId}`,
317 status: 'accepted',
318 })
319 // The tool gets its thread in its context. No model call happened, so
320 // no aimock fixture answers this thread.
321 await expect
322 .poll(async () => JSON.stringify(await user.transcript(threadId)))
323 .toMatch(new RegExp(`threadId[\\\\":]+${threadId}`))
324​
325 expect(
326 await user.control(threadId, { op: 'tool', name: 'deploy', args: {} }),
327 ).toMatchObject({ status: 'rejected', reason: 'not_exposed' })
328 })
329​
330 test('adds an exposed record that the next turn reads', async ({
331 request,
332 testId,
333 aimockPort,
334 }) => {
335 const threadId = `append-${testId}`
336 const user = asUser(request, testId, aimockPort, 'e2e-token', {
337 'x-harness-durable': '1',
338 })
339​
340 expect(
341 await user.control(threadId, {
342 op: 'append',
343 records: [
344 { type: 'app.signal', text: '[harness-append] the build failed' },
345 ],
346 }),
347 ).toMatchObject({ status: 'accepted' })
348 expect(
349 await user.control(threadId, {
350 op: 'append',
351 records: [{ type: 'app.secret', text: 'no' }],
352 }),
353 ).toMatchObject({ status: 'rejected', reason: 'not_exposed' })
354​
355 await user.control(threadId, { op: 'continue' })
356 await expect
357 .poll(() => user.answers(threadId))
358 .toContain('I will look at the build.')
359 })
360​
361 test('runs each input as the user who sent it', async ({
362 request,
363 testId,
364 aimockPort,
365 }) => {
366 const threadId = `sender-${testId}`
367 const opener = asUser(request, testId, aimockPort)
368 const bob = asUser(request, testId, aimockPort, 'e2e-token-bob')
369 // The first user opens the session of the thread.
370 await openHarnessThread(request, opener.headers, threadId)
371​
372 const chunks = sse(
373 await (
374 await bob.run({
375 threadId,
376 runId: `sender-run-${testId}`,
377 messages: userMessage('[harness-sender] who am i'),
378 forwardedProps: {},
379 })
380 ).text(),
381 )
382 expect(toolResults(chunks).join('')).toContain('"id":"bob"')
383 expect(textOf(chunks)).toBe('You are the sender.')
384 })
385​
386 test('lets a ChatClient answer an approval on POST run', async ({
387 baseURL,
388 testId,
389 aimockPort,
390 }) => {
391 const client = new ChatClient({
392 connection: fetchServerSentEvents(`${baseURL}/api/harness-protocol/run`, {
393 headers: {
394 authorization: 'Bearer e2e-token',
395 'x-test-id': testId,
396 'x-aimock-port': String(aimockPort),
397 },
398 }),
399 threadId: `chatclient-${testId}`,
400 tools: [deploy.client()],
401 })
402 const assistantText = () =>
403 client
404 .getMessages()
405 .filter((message) => message.role === 'assistant')
406 .flatMap((message) => message.parts)
407 .flatMap((part) => (part.type === 'text' ? [part.content] : []))
408 .join('')
409​
410 await client.sendMessage('[harness-chatclient] deploy dev')
411 const [interrupt] = client.getInterrupts()
412 expect(interrupt).toMatchObject({ canResolve: true })
413​
414 client.resolveInterrupts(true)
415 await expect.poll(assistantText).toContain('Deployed to dev.')
416 client.dispose()
417 })
418​
419 test('lets a reloaded ChatClient join the turn that still runs', async ({
420 request,
421 baseURL,
422 testId,
423 aimockPort,
424 }) => {
425 const user = asUser(request, testId, aimockPort)
426 const threadId = `rejoin-${testId}`
427 const connection = () =>
428 fetchServerSentEvents(`${baseURL}/api/harness-protocol/run`, {
429 headers: user.headers,
430 })
431 /** Each message as its role and its text, to compare two clients. */
432 const shape = (client: ChatClient) =>
433 client.getMessages().map((message) => ({
434 role: message.role,
435 text: message.parts
436 .flatMap((part) => (part.type === 'text' ? [part.content] : []))
437 .join(''),
438 }))
439 const pendingQuestion = async () => {
440 const response = await request.get(
441 `/api/harness-protocol/snapshot?threadId=${threadId}`,
442 { headers: user.headers },
443 )
444 // 404 until the turn of the first tab opens the thread.
445 if (response.status() === 404) return undefined
446 const snapshot: { pendingWaits: Array<{ waitId: string }> } =
447 await response.json()
448 return snapshot.pendingWaits[0]?.waitId
449 }
450​
451 // The first tab starts a turn. Its tool waits for an answer.
452 const first = new ChatClient({ connection: connection(), threadId })
453 const sent = first.sendMessage('[harness-rejoin] ask my name')
454 await expect.poll(pendingQuestion).toBeTruthy()
455​
456 // The page reloads: a new client loads the thread from the server and
457 // joins the turn that still runs.
458 const reloaded = new ChatClient({
459 connection: connection(),
460 threadId,
461 persistence: true,
462 })
463 reloaded.attach()
464 await expect
465 .poll(() => reloaded.getMessages().map((message) => message.role))
466 .toEqual(['user', 'assistant'])
467​
468 expect(
469 await user.control(threadId, {
470 op: 'answer',
471 questionId: await pendingQuestion(),
472 value: 'Otto',
473 }),
474 ).toMatchObject({ status: 'accepted' })
475 await sent
476 await expect.poll(() => shape(reloaded).at(-1)?.text).toBe('Hello, Otto.')
477 // The joined client shows the same messages as the tab that sent it.
478 expect(shape(reloaded)).toEqual(shape(first))
479 first.dispose()
480 reloaded.dispose()
481 })
482​
483 test('cancels one waiting input and moves another into the running turn', async ({
484 request,
485 baseURL,
486 testId,
487 aimockPort,
488 }) => {
489 const user = asUser(request, testId, aimockPort)
490 const threadId = `waiting-${testId}`
491 const dropped = `drop-${testId}`
492 const moved = `move-${testId}`
493 // The turn waits for an answer, so the next inputs wait too.
494 expect(
495 await user.control(threadId, {
496 op: 'prompt',
497 message: '[harness-queue] ask my name',
498 }),
499 ).toMatchObject({ status: 'accepted' })
500 await expect.poll(() => user.question(threadId)).toBeTruthy()
501 for (const [inputId, message] of [
502 [dropped, '[harness-queue-dropped] never runs'],
503 [moved, '[harness-queue-moved] say it now'],
504 ]) {
505 expect(
506 await user.control(threadId, { op: 'followUp', message, inputId }),
507 ).toMatchObject({ status: 'queued' })
508 }
509 expect((await user.snapshot(threadId)).waitingInputs).toMatchObject([
510 { inputId: dropped, delivery: 'queue' },
511 { inputId: moved, delivery: 'queue' },
512 ])
513​
514 expect(
515 await user.control(threadId, { op: 'cancelInput', inputId: dropped }),
516 ).toMatchObject({ status: 'accepted' })
517 // A cancelled input does not wait any more.
518 expect(
519 await user.control(threadId, { op: 'cancelInput', inputId: dropped }),
520 ).toMatchObject({ status: 'rejected', reason: 'not_waiting' })
521 expect(
522 await user.control(threadId, {
523 op: 'setDelivery',
524 inputId: moved,
525 delivery: 'steer',
526 }),
527 ).toMatchObject({ status: 'accepted' })
528 expect((await user.snapshot(threadId)).waitingInputs).toMatchObject([
529 { inputId: moved, delivery: 'steer' },
530 ])
531​
532 // The session stream tells every client about both changes.
533 const events = await customEvents(
534 `${baseURL}/api/harness-protocol/events?threadId=${threadId}&from=0`,
535 user.headers,
536 (seen) => seen.some((event) => event.name === 'harness.input.delivery'),
537 )
538 expect(events).toContainEqual({
539 name: 'harness.input.settled',
540 value: expect.objectContaining({ inputId: dropped, outcome: 'aborted' }),
541 })
542 expect(events).toContainEqual({
543 name: 'harness.input.delivery',
544 value: { inputId: moved, delivery: 'steer' },
545 })
546​
547 // After the answer, the moved input joins the next model call.
548 const asked = await user.question(threadId)
549 expect(
550 await user.control(threadId, {
551 op: 'answer',
552 questionId: asked?.waitId,
553 value: 'Otto',
554 }),
555 ).toMatchObject({ status: 'accepted' })
556 await expect
557 .poll(() => user.answers(threadId))
558 .toContain('Hello, Otto. I got the moved message.')
559 const sent = (await user.transcript(threadId))
560 .filter((message) => message.role === 'user')
561 .map((message) => message.content)
562 expect(sent).toEqual([
563 '[harness-queue] ask my name',
564 '[harness-queue-moved] say it now',
565 ])
566 })
567​
568 test('moves a running tool call to the background', async ({
569 request,
570 testId,
571 aimockPort,
572 }) => {
573 const user = asUser(request, testId, aimockPort)
574 const threadId = `background-${testId}`
575 // Before the tool runs, there is nothing to move.
576 expect(await user.control(threadId, { op: 'background' })).toMatchObject({
577 status: 'rejected',
578 reason: 'not_running',
579 })
580 expect(
581 await user.control(threadId, {
582 op: 'prompt',
583 message: '[harness-background] build it',
584 }),
585 ).toMatchObject({ status: 'accepted' })
586 // `slowBuild` waits for `release`. A client needs no `expose` entry.
587 await expect
588 .poll(
589 async () => (await user.control(threadId, { op: 'background' })).status,
590 )
591 .toBe('accepted')
592​
593 // The tool call answers at once, and the turn ends.
594 await expect
595 .poll(() => user.answers(threadId))
596 .toContain('The build runs in the background.')
597 const results = (await user.transcript(threadId))
598 .filter((message) => message.role === 'tool')
599 .map((message) => message.content)
600 expect(String(results[0])).toContain('The job moved to the background.')
601​
602 // When the job ends, a note wakes the session.
603 expect(
604 await user.control(threadId, { op: 'command', name: 'release' }),
605 ).toMatchObject({ status: 'accepted' })
606 await expect
607 .poll(() => user.answers(threadId))
608 .toContain('The build is done.')
609 })
610​
611 test('asks an MCP elicitation as a question and sends the answer to the server', async ({
612 request,
613 testId,
614 aimockPort,
615 }) => {
616 const user = asUser(request, testId, aimockPort, 'e2e-token', {
617 'x-harness-mcp': '1',
618 })
619 const threadId = `elicit-${testId}`
620 expect(
621 await user.control(threadId, {
622 op: 'prompt',
623 message: '[harness-elicit] what is the forecast',
624 }),
625 ).toMatchObject({ status: 'accepted' })
626 await expect.poll(() => user.question(threadId)).toBeTruthy()
627 const asked = await user.question(threadId)
628 expect(asked).toMatchObject({
629 message: 'Which city?',
630 schema: { type: 'object', properties: { value: { type: 'string' } } },
631 })
632​
633 expect(
634 await user.control(threadId, {
635 op: 'answer',
636 questionId: asked?.waitId,
637 value: { value: 'Paris' },
638 }),
639 ).toMatchObject({ status: 'accepted' })
640 await expect
641 .poll(() => user.answers(threadId))
642 .toContain('The forecast for Paris is sunny.')
643​
644 // The server got the answer: the tool result has the city.
645 const result = (await user.transcript(threadId)).find(
646 (message) => message.role === 'tool',
647 )
648 expect(JSON.stringify(result?.content)).toContain('Forecast for Paris')
649 })
650​
651 test('asks each elicitation/create request of a spec 2025 server, two in one tool call', async ({
652 request,
653 testId,
654 aimockPort,
655 }) => {
656 const user = asUser(request, testId, aimockPort, 'e2e-token', {
657 'x-harness-mcp': '2025',
658 })
659 const threadId = `elicit-2025-${testId}`
660 expect(
661 await user.control(threadId, {
662 op: 'prompt',
663 message: '[harness-elicit-2025] book a trip',
664 }),
665 ).toMatchObject({ status: 'accepted' })
666 for (const [message, value] of [
667 ['Which city?', 'Paris'],
668 ['Which seat?', '12A'],
669 ]) {
670 await expect
671 .poll(async () => (await user.question(threadId))?.message)
672 .toBe(message)
673 const asked = await user.question(threadId)
674 expect(
675 await user.control(threadId, {
676 op: 'answer',
677 questionId: asked?.waitId,
678 value: { value },
679 }),
680 ).toMatchObject({ status: 'accepted' })
681 }
682 await expect
683 .poll(() => user.answers(threadId))
684 .toContain('Your trip to Paris is booked, seat 12A.')
685​
686 // The server got both answers in the same tool call.
687 const result = (await user.transcript(threadId)).find(
688 (message) => message.role === 'tool',
689 )
690 expect(JSON.stringify(result?.content)).toContain('Booked Paris, seat 12A')
691 })
692​
693 test('answers the stored user message on continue, with no new message', async ({
694 request,
695 testId,
696 aimockPort,
697 }) => {
698 const user = asUser(request, testId, aimockPort)
699 const threadId = `continue-${testId}`
700 expect(
701 await user.control(threadId, {
702 op: 'prompt',
703 message: '[harness-continue] name a color',
704 }),
705 ).toMatchObject({ status: 'accepted' })
706 await expect.poll(() => user.answers(threadId)).toEqual(['Red.'])
707 // A fork through the prompt ends with the user message.
708 const at = (await user.transcript(threadId))[0]?.id
709 if (!at) throw new Error('The prompt has no message id.')
710 const forked = await request.post('/api/harness-protocol/sessions', {
711 headers: user.json,
712 data: { op: 'fork', threadId, through: at },
713 })
714 const fork: { threadId: string } = await forked.json()
715​
716 expect(await user.control(fork.threadId, { op: 'continue' })).toMatchObject(
717 { status: 'accepted' },
718 )
719 await expect
720 .poll(async () =>
721 (await user.transcript(fork.threadId)).map(
722 (message) => `${message.role}: ${String(message.content)}`,
723 ),
724 )
725 .toEqual(['user: [harness-continue] name a color', 'assistant: Blue.'])
726 })
727​
728 test('gives the model the ephemeral messages of a prompt, and never stores them', async ({
729 request,
730 testId,
731 aimockPort,
732 }) => {
733 const user = asUser(request, testId, aimockPort)
734 const threadId = `ephemeral-prompt-${testId}`
735 const message = '[harness-ephemeral-prompt] name a fruit'
736 const note = '[harness-ephemeral-prompt] note: answer in one word'
737 expect(
738 await user.control(threadId, {
739 op: 'prompt',
740 message,
741 ephemeral: [{ role: 'user', content: note }],
742 }),
743 ).toMatchObject({ status: 'accepted' })
744​
745 // The fixture answers only when the note is the last user message.
746 await expect.poll(() => user.answers(threadId)).toEqual(['Apple.'])
747 expect(JSON.stringify(await user.transcript(threadId))).not.toContain(note)
748 const journal = await request.get(
749 `http://127.0.0.1:${aimockPort}/v1/_requests`,
750 )
751 const entries: Array<JournalEntry> = await journal.json()
752 const sent = entries
753 .filter((entry) => entry.headers?.['x-test-id'] === testId)
754 .at(-1)
755 ?.body?.messages?.slice(-2)
756 .map((sentMessage) => sentMessage.content)
757 expect(sent).toEqual([message, note])
758 })
759​
760 test('gives the model the ephemeral messages of continue, and never stores them', async ({
761 request,
762 testId,
763 aimockPort,
764 }) => {
765 const user = asUser(request, testId, aimockPort)
766 const threadId = `ephemeral-continue-${testId}`
767 const note = '[harness-ephemeral-continue] note: pick another color'
768 expect(
769 await user.control(threadId, {
770 op: 'prompt',
771 message: '[harness-ephemeral-continue] name a color',
772 }),
773 ).toMatchObject({ status: 'accepted' })
774 await expect.poll(() => user.answers(threadId)).toEqual(['Red.'])
775 // A fork through the prompt ends with the user message.
776 const at = (await user.transcript(threadId))[0]?.id
777 if (!at) throw new Error('The prompt has no message id.')
778 const forked = await request.post('/api/harness-protocol/sessions', {
779 headers: user.json,
780 data: { op: 'fork', threadId, through: at },
781 })
782 const fork: { threadId: string } = await forked.json()
783​
784 expect(
785 await user.control(fork.threadId, {
786 op: 'continue',
787 ephemeral: [{ role: 'user', content: note }],
788 }),
789 ).toMatchObject({ status: 'accepted' })
790 // The fixture answers only when the note is the last user message.
791 await expect
792 .poll(async () =>
793 (await user.transcript(fork.threadId)).map(
794 (message) => `${message.role}: ${String(message.content)}`,
795 ),
796 )
797 .toEqual([
798 'user: [harness-ephemeral-continue] name a color',
799 'assistant: Green.',
800 ])
801 })
802​
803 test('rejects continue on an empty thread with nothing_to_continue', async ({
804 request,
805 baseURL,
806 testId,
807 aimockPort,
808 }) => {
809 const user = asUser(request, testId, aimockPort)
810 const threadId = `continue-empty-${testId}`
811 const inputId = `empty-${testId}`
812 await user.control(threadId, { op: 'continue', inputId })
813​
814 // The session checks the transcript when the turn starts, and tells
815 // every client.
816 const events = await customEvents(
817 `${baseURL}/api/harness-protocol/events?threadId=${threadId}&from=0`,
818 user.headers,
819 (seen) => seen.some((event) => event.name === 'harness.input.rejected'),
820 )
821 expect(events).toContainEqual({
822 name: 'harness.input.rejected',
823 value: { inputId, reason: 'nothing_to_continue' },
824 })
825 expect(await user.transcript(threadId)).toEqual([])
826 })
827})