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

harness-thread-controls.spec.ts

329 lines10.9 KB

1import { test, expect } from './fixtures'
2import type { APIRequestContext } from '@playwright/test'
3​
4/**
5 * Per-thread controls of a harness session over HTTP: usage totals, stored
6 * settings (`configure`), `reset` with a handoff note, and `host.fork`
7 * (through a test-only route). The model is the OpenAI adapter against
8 * aimock, and aimock's journal shows what each model call sent.
9 */
10​
11type JournalEntry = {
12 headers?: Record<string, string>
13 body: {
14 model?: string
15 messages?: Array<{ role: string; content: unknown }>
16 } | null
18​
19type Message = {
20 id?: string
21 role: string
22 content: unknown
23 metadata?: { harness?: { reset?: unknown } }
25​
26// Each event has an `id:` line (its log cursor) before its `data:` line.
27const textOf = (sse: string) =>
28 sse
29 .split('\n')
30 .filter((line) => line.startsWith('data: '))
31 .map((line) => JSON.parse(line.slice('data: '.length)))
32 .filter((chunk) => chunk.type === 'TEXT_MESSAGE_CONTENT')
33 .map((chunk) => chunk.delta)
34 .join('')
35​
36/** The text of a message's content, for a string or a list of parts. */
37const contentText = (content: unknown) =>
38 typeof content === 'string'
39 ? content
40 : Array.isArray(content)
41 ? content
42 .map((part) =>
43 typeof part === 'object' && part !== null && 'text' in part
44 ? String(part.text)
45 : '',
46 )
47 .join('')
48 : ''
49​
50function client(
51 request: APIRequestContext,
52 testId: string,
53 aimockPort: number,
54) {
55 const headers = {
56 authorization: 'Bearer e2e-token',
57 'x-test-id': testId,
58 'x-aimock-port': String(aimockPort),
59 }
60 const json = { ...headers, 'content-type': 'application/json' }
61 let runs = 0
62 const prompt = async (threadId: string, content: string) => {
63 runs += 1
64 const response = await request.post('/api/harness-protocol/run', {
65 headers: json,
66 data: {
67 threadId,
68 runId: `run-${testId}-${runs}`,
69 messages: [{ id: `u-${runs}`, role: 'user', content }],
70 tools: [],
71 context: [],
72 state: {},
73 forwardedProps: {},
74 },
75 })
76 expect(response.status()).toBe(200)
77 return textOf(await response.text())
78 }
79 const control = async (threadId: string, input: unknown) =>
80 (
81 await request.post('/api/harness-protocol/control', {
82 headers: json,
83 data: { threadId, input },
84 })
85 ).json()
86 const read = async (route: string, threadId: string) =>
87 (
88 await request.get(`/api/harness-protocol/${route}?threadId=${threadId}`, {
89 headers,
90 })
91 ).json()
92 /** This test's model calls, in order, from aimock's journal. */
93 const modelCalls = async () => {
94 const journal = await request.get(
95 `http://127.0.0.1:${aimockPort}/v1/_requests`,
96 )
97 const entries = (await journal.json()) as Array<JournalEntry>
98 return entries.filter((entry) => entry.headers?.['x-test-id'] === testId)
99 }
100 return { headers, json, prompt, control, read, modelCalls }
102​
103test.describe('harness thread controls', () => {
104 test('counts the usage of a turn per model and per sender', async ({
105 request,
106 testId,
107 aimockPort,
108 baseURL,
109 }) => {
110 const user = client(request, testId, aimockPort)
111 const threadId = `usage-${testId}`
112 expect(await user.prompt(threadId, '[harness-usage] hello')).toBe(
113 'Counted.',
114 )
115​
116 const { usage } = await user.read('snapshot', threadId)
117 // aimock reports no token counts for this adapter, so the call count is
118 // what this test can check.
119 expect(usage.total.calls).toBeGreaterThanOrEqual(1)
120 expect(usage.bySender.e2e.calls).toBe(usage.total.calls)
121 expect(Object.keys(usage.byModel).join(' ')).toContain('gpt-4o')
122​
123 // The session stream has a `harness.usage` event for a live total.
124 const events = await fetch(
125 `${baseURL}/api/harness-protocol/events?threadId=${threadId}&from=0`,
126 { headers: user.headers },
127 )
128 const reader = events.body!.pipeThrough(new TextDecoderStream()).getReader()
129 let feed = ''
130 while (!feed.includes('"harness.usage"')) {
131 const { value, done } = await reader.read()
132 if (done) break
133 feed += value
134 }
135 await reader.cancel()
136 expect(feed).toContain('"harness.usage"')
137 })
138​
139 test('runs the next turn with the stored model and instructions', async ({
140 request,
141 testId,
142 aimockPort,
143 }) => {
144 const user = client(request, testId, aimockPort)
145 const threadId = `settings-${testId}`
146 expect(
147 await user.control(threadId, {
148 op: 'configure',
149 settings: { model: 'strong', instructions: 'Answer in one word.' },
150 }),
151 ).toMatchObject({ status: 'accepted' })
152 expect(
153 await user.control(threadId, {
154 op: 'configure',
155 settings: { model: 'missing' },
156 }),
157 ).toMatchObject({ status: 'rejected' })
158 // The harness does not expose `plugins` to clients.
159 expect(
160 await user.control(threadId, {
161 op: 'configure',
162 settings: { plugins: { remove: ['e2e/settings'] } },
163 }),
164 ).toMatchObject({ status: 'rejected', reason: 'not_exposed' })
165​
166 expect(await user.prompt(threadId, '[harness-settings] hi')).toBe('Strong.')
167 const [call] = await user.modelCalls()
168 expect(call?.body?.model).toBe('gpt-4.1')
169 const system = (call?.body?.messages ?? [])
170 .filter((message) => message.role === 'system')
171 .map((message) => contentText(message.content))
172 .join('\n')
173 expect(system).toContain('Answer in one word.')
174​
175 const described = await user.read('describe', threadId)
176 expect(described.settings).toMatchObject({
177 model: 'strong',
178 instructions: 'Answer in one word.',
179 })
180 expect(described.models).toEqual(expect.arrayContaining(['fast', 'strong']))
181 })
182​
183 test('tells the next model call that the working folder changed', async ({
184 request,
185 testId,
186 aimockPort,
187 }) => {
188 const user = client(request, testId, aimockPort)
189 const threadId = `cwd-${testId}`
190 // A new thread gets no note, so the note needs a first turn.
191 expect(await user.prompt(threadId, '[harness-cwd] start')).toBe('Started.')
192 expect(
193 await user.control(threadId, {
194 op: 'configure',
195 settings: { cwd: '/repo/app' },
196 }),
197 ).toMatchObject({ status: 'accepted' })
198 expect(await user.prompt(threadId, '[harness-cwd] where')).toBe('Moved.')
199​
200 const [, call] = await user.modelCalls()
201 const seen = (call?.body?.messages ?? [])
202 .filter((message) => message.role !== 'system')
203 .map((message) => contentText(message.content))
204 expect(seen).toEqual([
205 '[harness-cwd] start',
206 'Started.',
207 'The working folder is now /repo/app. Paths are relative to it.',
208 '[harness-cwd] where',
209 ])
210 })
211​
212 test('starts a fresh context with the handoff note after a reset', async ({
213 request,
214 testId,
215 aimockPort,
216 }) => {
217 const user = client(request, testId, aimockPort)
218 const threadId = `reset-${testId}`
219 const note = 'Summary: the user asked a first question.'
220 expect(await user.prompt(threadId, '[harness-reset] first')).toBe(
221 'First answer.',
222 )
223 expect(await user.control(threadId, { op: 'reset', note })).toMatchObject({
224 status: 'accepted',
225 })
226 expect(await user.prompt(threadId, '[harness-reset] second')).toBe(
227 'Second answer.',
228 )
229​
230 // The model got only the note and the new message.
231 const calls = await user.modelCalls()
232 const last = calls.at(-1)?.body?.messages ?? []
233 const seen = last
234 .filter((message) => message.role !== 'system')
235 .map((message) => contentText(message.content))
236 expect(seen).toEqual([note, '[harness-reset] second'])
237​
238 // The transcript keeps every message, with the reset marker.
239 const transcript: Array<Message> = await user.read('transcript', threadId)
240 const texts = transcript.map((message) => contentText(message.content))
241 expect(texts).toContain('[harness-reset] first')
242 expect(texts).toContain('[harness-reset] second')
243 expect(transcript.some((message) => message.metadata?.harness?.reset)).toBe(
244 true,
245 )
246 })
247​
248 test('keeps the metadata an app writes when the next turn writes its usage', async ({
249 request,
250 testId,
251 aimockPort,
252 }) => {
253 const user = client(request, testId, aimockPort)
254 const threadId = `chips-${testId}`
255 const update = (data: Record<string, unknown>) =>
256 request.post('/api/harness-protocol/sessions', {
257 headers: user.json,
258 data: { op: 'update', threadId, ...data },
259 })
260 expect(await user.prompt(threadId, '[harness-chips] one')).toBe(
261 'Chips one.',
262 )
263​
264 const updated = await update({
265 pinned: true,
266 metadata: { chips: ['a.ts'] },
267 })
268 expect(updated.status()).toBe(200)
269 expect(await user.prompt(threadId, '[harness-chips] two')).toBe(
270 'Chips two.',
271 )
272​
273 const entry = async () => {
274 const list = await request.get('/api/harness-protocol/sessions', {
275 headers: user.headers,
276 })
277 const { entries } = (await list.json()) as {
278 entries: Array<{ threadId: string }>
279 }
280 return entries.find((item) => item.threadId === threadId)
281 }
282 // The host writes the usage of the turn after the answer streams.
283 await expect.poll(entry).toMatchObject({
284 pinned: true,
285 metadata: { chips: ['a.ts'] },
286 usage: { turns: 2 },
287 })
288 // The harness `metadataSchema` refuses metadata of another shape.
289 const refused = await update({ metadata: { chips: 'a.ts' } })
290 expect(refused.status()).toBe(400)
291 expect(await refused.json()).toMatchObject({ error: 'invalid_metadata' })
292 })
293​
294 test('forks a thread at a message and leaves the source as it was', async ({
295 request,
296 testId,
297 aimockPort,
298 }) => {
299 const user = client(request, testId, aimockPort)
300 const threadId = `fork-${testId}`
301 expect(await user.prompt(threadId, '[harness-fork] one')).toBe('One.')
302 expect(await user.prompt(threadId, '[harness-fork] two')).toBe('Two.')
303 const source: Array<Message> = await user.read('transcript', threadId)
304 const at = source.find((message) => message.role === 'assistant')?.id
305 if (!at) throw new Error('The first answer has no message id.')
306​
307 const response = await request.post('/api/harness-protocol/fork', {
308 headers: user.json,
309 data: { threadId, newThreadId: `${threadId}-copy`, at },
310 })
311 expect(response.status()).toBe(200)
312 const { transcript } = (await response.json()) as {
313 transcript: Array<Message>
314 }
315 expect(transcript.map((message) => contentText(message.content))).toEqual([
316 '[harness-fork] one',
317 'One.',
318 ])
319​
320 const after: Array<Message> = await user.read('transcript', threadId)
321 expect(after).toHaveLength(source.length)
322 // A fork onto a thread that has messages is refused.
323 const again = await request.post('/api/harness-protocol/fork', {
324 headers: user.json,
325 data: { threadId, newThreadId: `${threadId}-copy`, at },
326 })
327 expect(again.status()).toBe(400)
328 })
329})