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

coding-tools.spec.ts

291 lines9.3 KB

1import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { test, expect } from '../fixtures'
5import type { APIRequestContext } from '@playwright/test'
6​
7/**
8 * The coding tools of `workspaceTools()` from
9 * `@tanstack/ai-harness/plugins/coding`. A `coding-*` scenario of
10 * `/api/coding-tools` runs one harness turn in a temp folder that the test
11 * makes. aimock gives one tool call, and the tool works on real files. Each
12 * test checks the `TOOL_CALL_RESULT` that the client gets, and the files
13 * after the turn. The `coding-diffs` tests check the `FileChanged` events
14 * of the turn and of an `/undo` instead. No `permissions()` is mounted, so no tool waits for approval.
15 * Only `coding-format-ask` mounts `permissions()`: there the write asks
16 * before it runs, and the route rejects the approval.
17 */
18​
19type Chunk = {
20 type: string
21 delta?: string
22 content?: string
23 name?: string
24 value?: unknown
25 outcome?: {
26 type: string
27 interrupts?: Array<{ reason?: string; message?: string }>
28 }
30​
31/** The chunks of an SSE body. */
32const sse = (body: string): Array<Chunk> =>
33 body
34 .split('\n')
35 .filter((line) => line.startsWith('data: '))
36 .map((line) => JSON.parse(line.slice('data: '.length)))
37​
38/** The workspace of the running test. */
39let root = ''
40const file = (path: string) => join(root, path)
41const read = (path: string) => readFile(file(path), 'utf8')
42​
43/** Run `scenario` in `root`. Gives the chunks the client got. */
44async function post(
45 request: APIRequestContext,
46 scenario: string,
47 testId: string,
48) {
49 const response = await request.post('/api/coding-tools', {
50 data: { scenario, testId, root },
51 })
52 const body = await response.text()
53 expect(response.ok(), body).toBe(true)
54 const chunks = sse(body)
55 expect(
56 chunks.filter((chunk) => chunk.type === 'RUN_ERROR'),
57 body,
58 ).toEqual([])
59 return chunks
61​
62/** Run `scenario` in `root`. Gives the tool results and the text the client got. */
63async function runScenario(
64 request: APIRequestContext,
65 scenario: string,
66 testId: string,
67) {
68 const chunks = await post(request, scenario, testId)
69 return {
70 results: chunks
71 .filter((chunk) => chunk.type === 'TOOL_CALL_RESULT')
72 .map((chunk) => chunk.content),
73 text: chunks
74 .filter((chunk) => chunk.type === 'TEXT_MESSAGE_CONTENT')
75 .map((chunk) => chunk.delta)
76 .join(''),
77 }
79​
80test.describe('Coding tools', () => {
81 test.beforeEach(async () => {
82 root = await mkdtemp(join(tmpdir(), 'e2e-coding-'))
83 })
84​
85 test.afterEach(async () => {
86 await rm(root, { recursive: true, force: true })
87 })
88​
89 test('read_file gives the lines with their numbers', async ({
90 request,
91 testId,
92 }) => {
93 await writeFile(file('notes.txt'), 'alpha\nbeta\n')
94​
95 expect(await runScenario(request, 'coding-read', testId)).toEqual({
96 results: ['1\talpha\n2\tbeta'],
97 text: 'notes.txt has two lines.',
98 })
99 expect(await read('notes.txt')).toBe('alpha\nbeta\n')
100 })
101​
102 test('edit_file finds the old text when the file has spaces at the end of a line', async ({
103 request,
104 testId,
105 }) => {
106 // The old text is `alpha\nbeta`. The exact text is not in the file.
107 await writeFile(file('notes.txt'), 'alpha \nbeta\n')
108​
109 expect(await runScenario(request, 'coding-edit', testId)).toEqual({
110 results: ['Edited notes.txt (1 change).'],
111 text: 'Edited notes.txt.',
112 })
113 // The match covers the trailing spaces, so they go too.
114 expect(await read('notes.txt')).toBe('gamma\nbeta\n')
115 })
116​
117 test('patch updates one file and adds another', async ({
118 request,
119 testId,
120 }) => {
121 await writeFile(file('notes.txt'), 'alpha\nbeta\n')
122​
123 expect(await runScenario(request, 'coding-patch', testId)).toEqual({
124 results: ['Applied the patch:\nupdated notes.txt\nadded added.txt'],
125 text: 'Patched notes.txt and added added.txt.',
126 })
127 expect(await read('notes.txt')).toBe('delta\nbeta\n')
128 expect(await read('added.txt')).toBe('added by patch\n')
129 })
130​
131 test('grep gives each match as file:line: text', async ({
132 request,
133 testId,
134 }) => {
135 await writeFile(file('notes.txt'), 'alpha\nbeta\n')
136 await writeFile(file('more.txt'), 'more beta\n')
137​
138 expect(await runScenario(request, 'coding-grep', testId)).toEqual({
139 results: ['more.txt:1: more beta\nnotes.txt:2: beta'],
140 text: 'beta is in two files.',
141 })
142 expect(await read('notes.txt')).toBe('alpha\nbeta\n')
143 })
144​
145 test('bash runs the command in the workspace with AGENT=1', async ({
146 request,
147 testId,
148 }) => {
149 // The command is `node -e "..."`: it writes bash.txt and prints `done`.
150 expect(await runScenario(request, 'coding-bash', testId)).toEqual({
151 results: ['exit code: 0\ndone\n'],
152 text: 'The command ran.',
153 })
154 expect(await read('bash.txt')).toBe('AGENT=1')
155 })
156​
157 test('edit_file works in a sandbox with sandboxWorkspaceBackend', async ({
158 request,
159 testId,
160 }) => {
161 await writeFile(file('notes.txt'), 'alpha\nbeta\n')
162​
163 // The sandbox maps its /workspace to the test folder.
164 expect(await runScenario(request, 'coding-sandbox', testId)).toEqual({
165 results: ['Edited notes.txt (1 change).'],
166 text: 'Edited notes.txt in the sandbox.',
167 })
168 expect(await read('notes.txt')).toBe('sandboxed\nbeta\n')
169 })
170​
171 test('revert puts back the files of the turns and keeps the edit of the user', async ({
172 request,
173 testId,
174 }) => {
175 await writeFile(file('notes.txt'), 'alpha\nbeta\n')
176 await writeFile(file('other.txt'), 'original\n')
177​
178 // Two turns edit notes.txt. Between them, the user edits other.txt.
179 // Then the route reverts to the first prompt.
180 expect(await runScenario(request, 'coding-revert', testId)).toEqual({
181 results: ['Edited notes.txt (1 change).', 'Edited notes.txt (1 change).'],
182 text: 'Edited notes.txt.Edited notes.txt again.',
183 })
184 expect(await read('notes.txt')).toBe('alpha\nbeta\n')
185 expect(await read('other.txt')).toBe('mine\n')
186 })
187​
188 test('write_file sends FileChanged with its patch, and snapshots() sends it for the file that bash wrote', async ({
189 request,
190 testId,
191 }) => {
192 await writeFile(file('a.txt'), 'one\n')
193​
194 // write_file changes a.txt and sends its event. Then bash writes b.txt.
195 // bash sends no event, so snapshots() sends one at the end of the step.
196 const chunks = await post(request, 'coding-diffs', testId)
197 const changes = chunks.find(
198 (chunk) => chunk.name === 'e2e.file-changes',
199 )?.value
200 expect(changes).toEqual([
201 {
202 path: file('a.txt'),
203 change: 'updated',
204 patch: expect.stringContaining('-one\n+two\n'),
205 additions: 1,
206 deletions: 1,
207 toolCallId: expect.any(String),
208 },
209 {
210 path: file('b.txt'),
211 change: 'created',
212 // Only `+hi`: on Windows, `echo` also writes a space and `\r`.
213 patch: expect.stringContaining('+hi'),
214 additions: 1,
215 deletions: 0,
216 toolCallId: expect.any(String),
217 },
218 ])
219 })
220​
221 test('/undo sends FileChanged for each file that it puts back', async ({
222 request,
223 testId,
224 }) => {
225 await writeFile(file('a.txt'), 'one\n')
226​
227 // The turn writes a.txt and b.txt. Then the route runs /undo.
228 const chunks = await post(request, 'coding-diffs', testId)
229 const changes = chunks.find(
230 (chunk) => chunk.name === 'e2e.undo-changes',
231 )?.value
232 // The events of a restore name no tool call.
233 expect(changes).toEqual([
234 {
235 path: file('a.txt'),
236 change: 'updated',
237 patch: expect.stringContaining('-two\n+one\n'),
238 additions: 1,
239 deletions: 1,
240 },
241 {
242 path: file('b.txt'),
243 change: 'deleted',
244 patch: expect.stringContaining('-hi'),
245 additions: 0,
246 deletions: 1,
247 },
248 ])
249 expect(await read('a.txt')).toBe('one\n')
250 await expect(read('b.txt')).rejects.toMatchObject({ code: 'ENOENT' })
251 })
252​
253 test('in acceptEdits mode, the write asks before it runs, with its formatter, and a reject keeps the file unwritten', async ({
254 request,
255 testId,
256 }) => {
257 // The config file makes prettier the formatter of a.ts.
258 await writeFile(file('.prettierrc'), '{}')
259​
260 const chunks = await post(request, 'coding-format-ask', testId)
261​
262 // acceptEdits allows a write. Only its formatter asks, so this one
263 // approval is for the write and prettier together, before the write runs.
264 const approvals = chunks.flatMap((chunk) =>
265 chunk.type === 'RUN_FINISHED' && chunk.outcome?.type === 'interrupt'
266 ? (chunk.outcome.interrupts ?? []).map(({ reason, message }) => ({
267 reason,
268 message,
269 }))
270 : [],
271 )
272 expect(approvals).toEqual([
273 {
274 reason: 'approval',
275 message:
276 'Allow write_file {"path":"a.ts","content":"let a=1\\n"}? Answer once, always, or reject.',
277 },
278 ])
279 // The formatter does not ask again in the middle of the run.
280 expect(chunks.filter((chunk) => chunk.name === 'harness.question')).toEqual(
281 [],
282 )
283 // The reject refuses the call, so nothing is written.
284 expect(
285 chunks
286 .filter((chunk) => chunk.type === 'TOOL_CALL_RESULT')
287 .map((chunk) => chunk.content),
288 ).toEqual(['{"error":"The user denied this tool call."}'])
289 await expect(read('a.ts')).rejects.toMatchObject({ code: 'ENOENT' })
290 })
291})