Open History to see the last commit
1import { test, expect } from './fixtures'
2import { openHarnessThread } from './helpers'
3import type { APIRequestContext } from '@playwright/test'
4import type { MediaRecord } from '@tanstack/ai-harness'
5
6/**
7 * The life of a thread on the harness protocol: `POST sessions` with
8 * `op: 'delete'` purges the thread (its messages, its index entry, and its
9 * media files), and a read of a thread whose session closed on idle still
10 * works. The `x-harness-idle: close` header picks a host in the route that
11 * closes an idle session at once.
12 */
13
14const BASE = '/api/harness-protocol'
15const ANSWER = 'Hello over the harness protocol.'
16const NOT_FOUND = { status: 404, body: { error: 'not found' } }
17// A 1x1 red PNG.
18const RED_DOT = Buffer.from(
19 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQD3A0FDAAAAAElFTkSuQmCC',
20 'base64',
21)
22
23/** The routes of the protocol handler, as the e2e user. */
24function harnessApi(
25 request: APIRequestContext,
26 {
27 testId,
28 aimockPort,
29 extraHeaders = {},
30 }: {
31 testId: string
32 aimockPort: number
33 extraHeaders?: Record<string, string>
34 },
35) {
36 const headers = {
37 authorization: 'Bearer e2e-token',
38 'x-test-id': testId,
39 'x-aimock-port': String(aimockPort),
40 ...extraHeaders,
41 }
42 const json = { ...headers, 'content-type': 'application/json' }
43 /** A GET of a thread route, as its status and its JSON body. */
44 const read = async (route: string, query: Record<string, string>) => {
45 const response = await request.get(
46 `${BASE}/${route}?${new URLSearchParams(query)}`,
47 { headers },
48 )
49 return { status: response.status(), body: await response.json() }
50 }
51 return {
52 headers,
53 read,
54 /** Send the hello prompt of the protocol fixture, and wait for its end. */
55 async send(threadId: string, runId: string) {
56 const response = await request.post(`${BASE}/run`, {
57 headers: json,
58 data: {
59 threadId,
60 // The run id is also the input id, so each run needs its own.
61 runId,
62 messages: [
63 { id: 'u1', role: 'user', content: '[harness-protocol] hello' },
64 ],
65 tools: [],
66 context: [],
67 state: {},
68 forwardedProps: {},
69 },
70 })
71 // The stream ends when the turn ends.
72 return response.text()
73 },
74 /** The role of each saved message, and the text of each answer. */
75 async transcript(threadId: string) {
76 const { status, body } = await read('transcript', { threadId })
77 const messages: Array<{ role: string; content: unknown }> = body
78 return {
79 status,
80 roles: messages.map((message) => message.role),
81 answers: messages
82 .filter((message) => message.role === 'assistant')
83 .map((message) => message.content),
84 }
85 },
86 /** Upload `bytes` as a PNG file of `threadId`. */
87 async upload(threadId: string, bytes: Buffer) {
88 const query = new URLSearchParams({ threadId, name: 'dot.png' })
89 const response = await request.post(`${BASE}/media?${query}`, {
90 headers: { ...headers, 'content-type': 'image/png' },
91 data: bytes,
92 })
93 const record: MediaRecord = await response.json()
94 return record
95 },
96 /** A GET of the file `id` of `threadId`, with the login of the user. */
97 media: (threadId: string, id: string) =>
98 request.get(`${BASE}/media?${new URLSearchParams({ threadId, id })}`, {
99 headers,
100 }),
101 /** The signed URL of a file, from the media-url route. */
102 async signedUrl(record: MediaRecord) {
103 const { body } = await read('media-url', {
104 threadId: record.threadId,
105 id: record.id,
106 })
107 const signed: { path: string } = body
108 return `${BASE}/${signed.path}`
109 },
110 /** Delete the thread with `POST sessions`. */
111 async remove(threadId: string) {
112 const response = await request.post(`${BASE}/sessions`, {
113 headers: json,
114 data: { op: 'delete', threadId },
115 })
116 return response.status()
117 },
118 }
119}
120
121test.describe('harness lifecycle', () => {
122 test('a delete removes the media files of the thread, also from a signed URL', async ({
123 request,
124 testId,
125 aimockPort,
126 }) => {
127 const api = harnessApi(request, { testId, aimockPort })
128 const threadId = `lifecycle-media-${testId}`
129 const record = await api.upload(threadId, RED_DOT)
130 const url = await api.signedUrl(record)
131
132 const before = await api.media(threadId, record.id)
133 expect(before.status()).toBe(200)
134 expect(await before.body()).toEqual(RED_DOT)
135
136 expect(await api.remove(threadId)).toBe(204)
137
138 const after = await api.media(threadId, record.id)
139 expect({ status: after.status(), body: await after.json() }).toEqual(
140 NOT_FOUND,
141 )
142 // The signature is still good, but the thread is gone.
143 const signed = await request.get(url, { headers: api.headers })
144 expect({ status: signed.status(), body: await signed.json() }).toEqual(
145 NOT_FOUND,
146 )
147
148 // The same thread id again: it has an entry, but not the old file.
149 await openHarnessThread(request, api.headers, threadId)
150 const reopened = await api.media(threadId, record.id)
151 expect({ status: reopened.status(), body: await reopened.json() }).toEqual(
152 NOT_FOUND,
153 )
154 })
155
156 test('a delete removes the messages, and a new prompt on the same id starts an empty transcript', async ({
157 request,
158 testId,
159 aimockPort,
160 }) => {
161 const api = harnessApi(request, { testId, aimockPort })
162 const threadId = `lifecycle-delete-${testId}`
163 await api.send(threadId, `lifecycle-first-${testId}`)
164 expect(await api.transcript(threadId)).toEqual({
165 status: 200,
166 roles: ['user', 'assistant'],
167 answers: [ANSWER],
168 })
169
170 expect(await api.remove(threadId)).toBe(204)
171
172 // With host access, a read of a thread with no entry is 404.
173 expect(await api.read('transcript', { threadId })).toEqual(NOT_FOUND)
174 expect(await api.read('snapshot', { threadId })).toEqual(NOT_FOUND)
175
176 await api.send(threadId, `lifecycle-again-${testId}`)
177 // Only the new turn: the first user message and answer are gone.
178 expect(await api.transcript(threadId)).toEqual({
179 status: 200,
180 roles: ['user', 'assistant'],
181 answers: [ANSWER],
182 })
183 })
184
185 test('a thread whose session closed on idle still answers its reads', async ({
186 request,
187 testId,
188 aimockPort,
189 }) => {
190 const api = harnessApi(request, {
191 testId,
192 aimockPort,
193 extraHeaders: { 'x-harness-idle': 'close' },
194 })
195 const threadId = `lifecycle-idle-${testId}`
196 await api.send(threadId, `lifecycle-idle-${testId}`)
197
198 // The turn ended, so the host closed the session. The reads load the
199 // thread from the store.
200 expect(await api.read('snapshot', { threadId })).toMatchObject({
201 status: 200,
202 body: {
203 threadId,
204 status: 'idle',
205 activeOperations: [],
206 pendingWaits: [],
207 },
208 })
209 expect(await api.transcript(threadId)).toEqual({
210 status: 200,
211 roles: ['user', 'assistant'],
212 answers: [ANSWER],
213 })
214 })
215})