Open History to see the last commit
1import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import { basename, join } from 'node:path'
4import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5import { memoryPersistence } from '@tanstack/ai-persistence'
6import { createHarnessHost, defineHarness, definePlugin } from '../src'
7import {
8 WorkspaceHooks,
9 hostBackend,
10 workspaceRoot,
11 workspaceTools,
12} from '../src/first-party/coding'
13import { mockAdapter, text, toolCall } from './helpers'
14
15let dir = ''
16beforeEach(async () => {
17 dir = await mkdtemp(join(tmpdir(), 'harness-backend-'))
18})
19afterEach(async () => {
20 await rm(dir, { recursive: true, force: true })
21})
22
23const decoder = new TextDecoder()
24
25/** Run `fn` with `vars` set in the env of this process, then put it back. */
26async function withEnv(vars: Record<string, string>, fn: () => Promise<void>) {
27 const before = Object.keys(vars).map(
28 (name) => [name, process.env[name]] as const,
29 )
30 Object.assign(process.env, vars)
31 try {
32 await fn()
33 } finally {
34 for (const [name, value] of before) {
35 if (value === undefined) delete process.env[name]
36 else process.env[name] = value
37 }
38 }
39}
40
41describe('hostBackend', () => {
42 it('writes into new folders, then reads, stats, and lists them', async () => {
43 const file = join(dir, 'a', 'b.txt')
44 await hostBackend.writeFile(file, 'hi')
45 expect(decoder.decode(await hostBackend.readFile(file))).toBe('hi')
46 expect(await hostBackend.stat(file)).toMatchObject({
47 type: 'file',
48 size: 2,
49 })
50 expect(await hostBackend.stat(join(dir, 'a'))).toMatchObject({
51 type: 'dir',
52 })
53 expect(await hostBackend.readdir(dir)).toEqual([{ name: 'a', type: 'dir' }])
54 })
55
56 it('stops a file read, a write, and a page read when the signal aborts', async () => {
57 const file = join(dir, 'a.txt')
58 await writeFile(file, 'hi')
59 const signal = AbortSignal.abort()
60 await expect(hostBackend.readFile(file, { signal })).rejects.toThrow(
61 'aborted',
62 )
63 await expect(
64 hostBackend.writeFile(join(dir, 'b.txt'), 'b', { signal }),
65 ).rejects.toThrow('aborted')
66 await expect(
67 hostBackend.readLines(file, { offset: 1, limit: 1, signal }),
68 ).rejects.toThrow('aborted')
69 expect(await hostBackend.stat(join(dir, 'b.txt'))).toBeUndefined()
70 })
71
72 it('stats a missing path as undefined', async () => {
73 expect(await hostBackend.stat(join(dir, 'missing'))).toBeUndefined()
74 })
75
76 it('removes a file, and refuses a folder', async () => {
77 const file = join(dir, 'a', 'b.txt')
78 await hostBackend.writeFile(file, 'hi')
79 await expect(hostBackend.remove(join(dir, 'a'))).rejects.toThrow()
80 await hostBackend.remove(file)
81 expect(await hostBackend.stat(file)).toBeUndefined()
82 expect(await hostBackend.stat(join(dir, 'a'))).toMatchObject({
83 type: 'dir',
84 })
85 })
86
87 it('runs a command with added env, and resolves with its exit code', async () => {
88 expect(
89 await hostBackend.exec(
90 `node -e "console.log(process.env.HARNESS_VALUE); process.exit(2)"`,
91 { cwd: dir, env: { HARNESS_VALUE: 'set' } },
92 ),
93 ).toEqual({ exitCode: 2, stdout: 'set\n', stderr: '' })
94 })
95
96 // The command sleeps for one second. On Windows, `exec` waits for it even
97 // after the timeout kills the shell, so keep it short. It runs outside
98 // `dir`: on Windows, a running command keeps its folder from removal.
99 const sleep = `node -e "setTimeout(function () {}, 1000)"`
100
101 it('gives exit code 124 when the timeout kills a command', async () => {
102 const result = await hostBackend.exec(sleep, { timeoutMs: 100 })
103 expect(result.exitCode).toBe(124)
104 })
105
106 it('gives exit code 1 when the signal stops a command', async () => {
107 const controller = new AbortController()
108 const running = hostBackend.exec(sleep, { signal: controller.signal })
109 controller.abort()
110 expect((await running).exitCode).toBe(1)
111 })
112
113 it('starts a background command, then gives its exit code and output', async () => {
114 // --no-warnings: a runner that sets NO_COLOR and FORCE_COLOR makes node
115 // print a warning to the output.
116 const job = hostBackend.spawn(
117 `node --no-warnings -e "console.log('done')"`,
118 {
119 cwd: dir,
120 },
121 )
122 expect(await job.wait()).toEqual({ exitCode: 0 })
123 expect(job.output()).toBe('done\n')
124 })
125
126 it('kills a background command', async () => {
127 const job = hostBackend.spawn(`node -e "setTimeout(function () {}, 60000)"`)
128 job.kill()
129 expect((await job.wait()).exitCode).not.toBe(0)
130 })
131
132 it('keeps the newest 1 MiB of the output of a background command', async () => {
133 // 1 MiB of x, then `end`: 3 bytes too many.
134 const job = hostBackend.spawn(
135 `node --no-warnings -e "process.stdout.write('x'.repeat(1048576) + 'end')"`,
136 )
137 await job.wait()
138 const marker = '[3 earlier bytes were dropped.]\n'
139 const output = job.output()
140 expect(output.length).toBe(marker.length + 1024 * 1024)
141 expect(output.startsWith(marker)).toBe(true)
142 expect(output.endsWith('xxend')).toBe(true)
143 })
144
145 // `start /b` runs node, and `cmd.exe` ends at once. Node keeps the output
146 // pipes open, so the job does not end. `taskkill /T` cannot find node from
147 // the shell that ended.
148 it.runIf(process.platform === 'win32')(
149 'kills a command that its shell left running',
150 async () => {
151 const job = hostBackend.spawn(
152 `start /b node --no-warnings -e "console.log(process.pid); setTimeout(function () {}, 60000)"`,
153 )
154 let pid = Number.NaN
155 for (let tries = 0; tries < 100 && Number.isNaN(pid); tries++) {
156 await new Promise((done) => setTimeout(done, 100))
157 pid = Number.parseInt(job.output(), 10)
158 }
159 job.kill()
160 await job.wait()
161 expect(() => process.kill(pid, 0)).toThrow()
162 },
163 20_000,
164 )
165
166 // cmd.exe looks in the current folder before the PATH. A cloned repo can
167 // put an `rg.cmd` there, and grep runs `rg` with no question.
168 it.runIf(process.platform === 'win32')(
169 'does not run a program from the working folder by its name',
170 async () => {
171 // A host can set the variable already. Test the host that does not.
172 const before = process.env.NoDefaultCurrentDirectoryInExePath
173 delete process.env.NoDefaultCurrentDirectoryInExePath
174 try {
175 await writeFile(join(dir, 'rg.cmd'), '@echo ran> "%~dp0ran.txt"\r\n')
176 await hostBackend.exec('rg --version', { cwd: dir })
177 await hostBackend.spawn('rg --version', { cwd: dir }).wait()
178 expect(await hostBackend.stat(join(dir, 'ran.txt'))).toBeUndefined()
179 } finally {
180 if (before !== undefined) {
181 process.env.NoDefaultCurrentDirectoryInExePath = before
182 }
183 }
184 },
185 )
186
187 it('does not give a variable of the server to a command', async () => {
188 const print = `node -e "console.log(process.env.SECRET_TOKEN || 'unset')"`
189 await withEnv({ SECRET_TOKEN: 'hunter2' }, async () => {
190 const run = await hostBackend.exec(print, { cwd: dir })
191 expect(run.stdout).toBe('unset\n')
192 const job = hostBackend.spawn(print, { cwd: dir })
193 await job.wait()
194 expect(job.output()).toBe('unset\n')
195 })
196 })
197})
198
199describe('workspaceRoot', () => {
200 it('keeps each thread id from a client in its own folder in base', () => {
201 expect(workspaceRoot('/srv/work', 'acme', '../other-tenant/t-1')).toBe(
202 '/srv/work/acme/..%2Fother-tenant%2Ft-1',
203 )
204 // A child thread id has `/agent/` in it.
205 expect(workspaceRoot('/srv/work', 'acme', 't-1/agent/c-2')).toBe(
206 '/srv/work/acme/t-1%2Fagent%2Fc-2',
207 )
208 expect(() => workspaceRoot('/srv/work', 'acme', '..')).toThrow(
209 'cannot name a workspace folder',
210 )
211 })
212})
213
214describe('hostBackend.readLines', () => {
215 /**
216 * The page of a whole-file read, as `read_file` makes it, and the line
217 * count when the page gets to the end of the file.
218 */
219 const expected = (text: string, offset: number, limit: number) => {
220 const all = text.replace(/^/, '').split('\n')
221 if (text.endsWith('\n')) all.pop()
222 const isLast = offset - 1 + limit >= all.length
223 return {
224 lines: all.slice(offset - 1, offset - 1 + limit),
225 total: isLast ? all.length : undefined,
226 }
227 }
228 // 1 MiB is the read size: `é` is split over the edge of the first read.
229 const edge = `${'x'.repeat(1024 * 1024 - 1)}é\nlast`
230
231 it.each([
232 ['an empty file', '', 1, 5],
233 ['no final newline', 'a\nb', 1, 5],
234 ['a final newline', 'a\nb\n', 2, 5],
235 ['CRLF lines', 'a\r\nb\r\n', 1, 5],
236 ['a byte order mark', 'a\nb\n', 1, 1],
237 ['an offset after the end', 'a\nb\n', 9, 5],
238 ['a character over the read edge', edge, 1, 1],
239 ['a page after the read edge', edge, 2, 1],
240 ])('reads %s like a whole-file read', async (_, text, offset, limit) => {
241 const file = join(dir, 'f.txt')
242 await writeFile(file, text)
243 const read = await hostBackend.readLines(file, { offset, limit })
244 expect({ lines: read.lines, total: read.total }).toEqual(
245 expected(text, offset, limit),
246 )
247 expect(read.size).toBe(Buffer.byteLength(text))
248 expect(read.head).toEqual(Buffer.from(text).subarray(0, 8 * 1024))
249 })
250
251 it('stops after 64 KiB of lines, and does not count the lines after it', async () => {
252 const file = join(dir, 'long.txt')
253 await writeFile(file, `${'y'.repeat(40 * 1024)}\n`.repeat(4))
254 const read = await hostBackend.readLines(file, { offset: 1, limit: 10 })
255 expect(read.lines).toHaveLength(2)
256 expect(read.total).toBeUndefined()
257 })
258
259 /** A file of 300,000 lines of 10 bytes: 3 MB, more than one read. */
260 async function manyLines() {
261 const file = join(dir, 'many.txt')
262 const lines = Array.from(
263 { length: 300_000 },
264 (_, index) => `line${String(index + 1).padStart(6, '0')}`,
265 )
266 await writeFile(file, `${lines.join('\n')}\n`)
267 return file
268 }
269
270 it('stops after the first page of a big file, so the line count is not known', async () => {
271 const read = await hostBackend.readLines(await manyLines(), {
272 offset: 1,
273 limit: 3,
274 })
275 expect(read).toMatchObject({
276 size: 3_300_000,
277 lines: ['line000001', 'line000002', 'line000003'],
278 })
279 expect(read.total).toBeUndefined()
280 })
281
282 it('counts the lines when the page gets to the end of a big file', async () => {
283 const read = await hostBackend.readLines(await manyLines(), {
284 offset: 299_999,
285 limit: 5,
286 })
287 expect(read.lines).toEqual(['line299999', 'line300000'])
288 expect(read.total).toBe(300_000)
289 })
290})
291
292describe('workspace hooks', () => {
293 it('runs afterWrite after each write, and adds afterRead text to read_file', async () => {
294 const written: Array<string> = []
295 const hooks = definePlugin({
296 name: 'test/hooks',
297 setup: () => ({
298 contribute: [
299 WorkspaceHooks.item({
300 afterWrite: async (path) => {
301 written.push(decoder.decode(await hostBackend.readFile(path)))
302 },
303 afterRead: async (path) => `read ${basename(path)}`,
304 }),
305 ],
306 }),
307 })
308 const { adapter, calls } = mockAdapter([
309 () => toolCall('write_file', { path: 'a.txt', content: 'one' }, 'c1'),
310 () =>
311 toolCall('edit_file', { path: 'a.txt', old: 'one', new: 'two' }, 'c2'),
312 () => toolCall('read_file', { path: 'a.txt' }, 'c3'),
313 () => text('done'),
314 ])
315 const host = createHarnessHost({ persistence: memoryPersistence() })
316 const session = await host.open(
317 defineHarness({
318 name: 'test/hooks',
319 adapter,
320 // The hooks plugin comes after the tools: the tools read hooks
321 // when they run.
322 plugins: () => [workspaceTools({ root: dir }), hooks],
323 }),
324 {
325 threadId: 't',
326 },
327 )
328
329 await session.send('work')
330
331 expect(written).toEqual(['one', 'two'])
332 expect(JSON.stringify(calls[3].messages)).toContain(
333 '1\\ttwo\\n\\nread a.txt',
334 )
335 await host.close()
336 })
337})