Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { join, posix, resolve, sep } from 'node:path'
3import { beforeAll, describe, expect, it } from 'vitest'
4import { createWorkspaceTools } from '../src/first-party/coding/workspace'
5import type { WorkspaceBackend } from '../src/first-party/coding/backend'
6import type { WorkspaceHooks } from '../src/first-party/workspace-hooks'
7
8/**
9 * A backend that keeps files in a map, by absolute path. It runs no
10 * commands. `shell: 'sh'` gives it POSIX paths, like a Linux sandbox.
11 */
12function memoryBackend(shell?: 'sh') {
13 const separator = shell === 'sh' ? posix.sep : sep
14 const files = new Map<string, Uint8Array>()
15 const backend: WorkspaceBackend = {
16 shell,
17 readFile: async (path) => {
18 const data = files.get(path)
19 if (!data) throw new Error(`No file ${path}`)
20 return data
21 },
22 writeFile: async (path, data) => {
23 files.set(
24 path,
25 typeof data === 'string' ? new TextEncoder().encode(data) : data,
26 )
27 },
28 stat: async (path) => {
29 const data = files.get(path)
30 if (!data) return undefined
31 return { type: 'file', size: data.length, mtimeMs: 0 }
32 },
33 // No links: each path is its own real path.
34 realpath: async (path) => path,
35 readdir: async (path) => {
36 const prefix = path + separator
37 const paths = [...files.keys()].filter((file) => file.startsWith(prefix))
38 // Like the host, a folder that is not there throws.
39 if (paths.length === 0) throw new Error(`No folder ${path}`)
40 return paths
41 .map((file) => file.slice(prefix.length))
42 .filter((name) => !name.includes(separator))
43 .sort()
44 .map((name) => ({ name, type: 'file' as const }))
45 },
46 exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
47 }
48 return backend
49}
50
51const root = resolve(tmpdir(), 'harness-read')
52const backend = memoryBackend()
53
54const ascii = (text: string) => new TextEncoder().encode(text)
55const put = (path: string, data: Uint8Array | string) =>
56 backend.writeFile(join(root, path), data)
57
58/**
59 * `read_file` with `hooks`, in `workspace`. Default: the memory backend at
60 * `root`.
61 */
62function reader(
63 options: {
64 hooks?: Array<WorkspaceHooks>
65 workspace?: { root: string; backend: WorkspaceBackend }
66 } = {},
67) {
68 const { hooks = [], workspace = { root, backend } } = options
69 const tool = createWorkspaceTools(workspace, {
70 hooks: () => hooks,
71 }).tools.find((item) => item.name === 'read_file')
72 return async (
73 path: string,
74 options: { offset?: number; limit?: number } = {},
75 ) => {
76 if (!tool?.execute) throw new Error('No read_file tool')
77 const result: unknown = await tool.execute({ path, ...options })
78 return result
79 }
80}
81
82const read = reader()
83
84/** The result of `read_file` for a text file. Throws for any other result. */
85async function readText(
86 path: string,
87 options: { offset?: number; limit?: number } = {},
88) {
89 const result = await read(path, options)
90 if (typeof result !== 'string') throw new Error('Not a text result')
91 return result
92}
93
94const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
95const pngPart = {
96 type: 'image',
97 source: { type: 'data', value: 'iVBORw0KGgo=', mimeType: 'image/png' },
98}
99const BINARY = new Uint8Array([0x49, 0x44, 0x00, 0x01])
100
101describe('read_file text', () => {
102 it('reads a file with a byte order mark without the mark', async () => {
103 await put('bom.txt', new Uint8Array([0xef, 0xbb, 0xbf, ...ascii('a\nb\n')]))
104 expect(await read('bom.txt')).toBe('1\ta\n2\tb')
105 })
106
107 it('cuts a line over 2000 characters, and says how much is cut', async () => {
108 await put('long.txt', `${'a'.repeat(2500)}\nshort`)
109 expect(await read('long.txt')).toBe(
110 `1\t${'a'.repeat(2000)}... [line cut: 500 more characters]\n2\tshort`,
111 )
112 })
113
114 it('reads a Git LFS pointer named .png as text', async () => {
115 await put('pointer.png', 'version https://git-lfs.github.com/spec/v1\n')
116 expect(await read('pointer.png')).toBe(
117 '1\tversion https://git-lfs.github.com/spec/v1',
118 )
119 })
120})
121
122describe('read_file pages', () => {
123 beforeAll(async () => {
124 const lines = Array.from({ length: 2500 }, (_, index) => `L${index + 1}`)
125 await put('many.txt', lines.join('\n'))
126 })
127
128 it.each([{}, { limit: 5000 }])(
129 'shows at most 2000 lines, then says where the next page starts (%o)',
130 async (options) => {
131 const lines = (await readText('many.txt', options)).split('\n')
132 expect(lines.slice(0, 2)).toEqual(['1\tL1', '2\tL2'])
133 expect(lines.slice(-3)).toEqual([
134 '2000\tL2000',
135 '',
136 '[Showing lines 1-2000 of 2500. Read more with offset 2001.]',
137 ])
138 },
139 )
140
141 it('reads the next page from its offset to the end, with no note', async () => {
142 const lines = (await readText('many.txt', { offset: 2001 })).split('\n')
143 expect(lines).toHaveLength(500)
144 expect(lines[0]).toBe('2001\tL2001')
145 expect(lines.at(-1)).toBe('2500\tL2500')
146 })
147
148 it('keeps a page under 50 KiB', async () => {
149 // Each line is about 1 KB, so 51 lines fit in 50 KiB.
150 await put(
151 'wide.txt',
152 Array.from({ length: 100 }, () => 'x'.repeat(1000)).join('\n'),
153 )
154 const lines = (await readText('wide.txt')).split('\n')
155 expect(lines.at(-3)).toBe(`51\t${'x'.repeat(1000)}`)
156 expect(lines.at(-1)).toBe(
157 '[Showing lines 1-51 of 100. Read more with offset 52.]',
158 )
159 })
160
161 it('says where the next page starts when the backend did not count the lines', async () => {
162 // `readLines` stopped after the page, so the number of lines is not known.
163 const paged: WorkspaceBackend = {
164 ...backend,
165 readLines: async () => ({
166 head: ascii('a\nb\n'),
167 size: 1000,
168 lines: ['a', 'b'],
169 total: undefined,
170 }),
171 }
172 const readPaged = reader({ workspace: { root, backend: paged } })
173 await put('paged.txt', 'a\nb\n')
174 expect(await readPaged('paged.txt')).toBe(
175 '1\ta\n2\tb\n\n[Showing lines 1-2. Read more with offset 3.]',
176 )
177 })
178
179 it('says how many lines there are when offset is past the end', async () => {
180 expect(await read('many.txt', { offset: 3000 })).toBe(
181 '[No lines from line 3000. many.txt has 2500 lines.]',
182 )
183 })
184})
185
186describe('read_file media and binary files', () => {
187 it.each([
188 { file: 'a.png', bytes: PNG, part: pngPart },
189 {
190 file: 'a.jpg',
191 bytes: new Uint8Array([0xff, 0xd8, 0xff, 0xe0]),
192 part: {
193 type: 'image',
194 source: { type: 'data', value: '/9j/4A==', mimeType: 'image/jpeg' },
195 },
196 },
197 {
198 file: 'a.gif',
199 bytes: ascii('GIF89a'),
200 part: {
201 type: 'image',
202 source: { type: 'data', value: 'R0lGODlh', mimeType: 'image/gif' },
203 },
204 },
205 {
206 file: 'a.webp',
207 bytes: new Uint8Array([
208 ...ascii('RIFF'),
209 0,
210 0,
211 0,
212 0,
213 ...ascii('WEBPVP8 '),
214 ]),
215 part: {
216 type: 'image',
217 source: {
218 type: 'data',
219 value: 'UklGRgAAAABXRUJQVlA4IA==',
220 mimeType: 'image/webp',
221 },
222 },
223 },
224 {
225 file: 'a.pdf',
226 bytes: ascii('%PDF-1.7'),
227 part: {
228 type: 'document',
229 source: {
230 type: 'data',
231 value: 'JVBERi0xLjc=',
232 mimeType: 'application/pdf',
233 },
234 },
235 },
236 ])('returns $file as a $part.type part', async ({ file, bytes, part }) => {
237 await put(file, bytes)
238 expect(await read(file)).toEqual([part])
239 })
240
241 it('refuses an image over 256 KB, and says how to read it', async () => {
242 const big = new Uint8Array(300 * 1024)
243 big.set(PNG)
244 await put('big.png', big)
245 await expect(read('big.png')).rejects.toThrow(
246 'big.png is 300 KB. read_file sends images and PDFs up to 256 KB. Make a smaller copy, for example with bash, and read that.',
247 )
248 })
249
250 it('sends an image of 256 KB', async () => {
251 const image = new Uint8Array(256 * 1024)
252 image.set(PNG)
253 await put('edge.png', image)
254 const result = await read('edge.png')
255 expect(result).toEqual([
256 {
257 type: 'image',
258 source: {
259 type: 'data',
260 value: Buffer.from(image).toString('base64'),
261 mimeType: 'image/png',
262 },
263 },
264 ])
265 })
266
267 it.each([
268 {
269 file: 'data.bin',
270 expected:
271 'data.bin is a binary file (4 bytes). read_file shows text, images, and PDFs only.',
272 },
273 {
274 file: 'clip.mp3',
275 expected:
276 'clip.mp3 is a binary file (4 bytes, audio/mpeg). read_file shows text, images, and PDFs only.',
277 },
278 ])('says $file is binary, with its size', async ({ file, expected }) => {
279 await put(file, BINARY)
280 expect(await read(file)).toBe(expected)
281 })
282})
283
284describe('read_file on a missing file', () => {
285 beforeAll(async () => {
286 const names = [
287 'src/Button.tsx',
288 'src/button.css',
289 'src/helpers.ts',
290 'src/index.ts',
291 'parts/a1.ts',
292 'parts/a2.ts',
293 'parts/a3.ts',
294 'parts/a4.ts',
295 ]
296 await Promise.all(names.map((name) => put(name, 'x')))
297 })
298
299 it.each([
300 {
301 path: 'src/button.ts',
302 message:
303 'File not found: src/button.ts. Did you mean src/Button.tsx, src/button.css?',
304 },
305 {
306 path: 'src/helpres.ts',
307 message: 'File not found: src/helpres.ts. Did you mean src/helpers.ts?',
308 },
309 {
310 path: 'parts/a.ts',
311 message:
312 'File not found: parts/a.ts. Did you mean parts/a1.ts, parts/a2.ts, parts/a3.ts?',
313 },
314 { path: 'nowhere/x.ts', message: 'File not found: nowhere/x.ts.' },
315 ])('names similar files for $path', async ({ path, message }) => {
316 await expect(read(path)).rejects.toThrow(message)
317 })
318
319 it('names them with POSIX paths in a sandbox, also on a Windows host', async () => {
320 const sandbox = memoryBackend('sh')
321 await sandbox.writeFile('/workspace/src/Button.tsx', 'x')
322 const readInSandbox = reader({
323 workspace: { root: '/workspace', backend: sandbox },
324 })
325 await expect(readInSandbox('src/button.tsx')).rejects.toThrow(
326 'File not found: src/button.tsx. Did you mean src/Button.tsx?',
327 )
328 })
329})
330
331describe('read_file hooks', () => {
332 it('adds afterRead text to a text file, not to media or binary files', async () => {
333 const readWithHook = reader({
334 hooks: [{ afterRead: async () => 'hook note' }],
335 })
336 await put('hooked.txt', 'hello')
337 await put('hooked.png', PNG)
338 await put('hooked.bin', BINARY)
339 expect(await readWithHook('hooked.txt')).toBe('1\thello\n\nhook note')
340 expect(await readWithHook('hooked.png')).toEqual([pngPart])
341 expect(await readWithHook('hooked.bin')).toBe(
342 'hooked.bin is a binary file (4 bytes). read_file shows text, images, and PDFs only.',
343 )
344 })
345})
346
347describe('the abort signal of a call', () => {
348 it('goes to each file call of the backend', async () => {
349 const files = memoryBackend()
350 // The signal of each file call, by the name of the method.
351 const seen: Array<[string, AbortSignal | undefined]> = []
352 const watched: WorkspaceBackend = {
353 ...files,
354 readFile: (path, options) => {
355 seen.push(['readFile', options?.signal])
356 return files.readFile(path)
357 },
358 writeFile: (path, data, options) => {
359 seen.push(['writeFile', options?.signal])
360 return files.writeFile(path, data)
361 },
362 stat: (path, options) => {
363 seen.push(['stat', options?.signal])
364 return files.stat(path)
365 },
366 realpath: (path, options) => {
367 seen.push(['realpath', options?.signal])
368 return files.realpath(path)
369 },
370 }
371 const { tools } = createWorkspaceTools({ root, backend: watched })
372 const tool = (name: string) => {
373 const found = tools.find((item) => item.name === name)?.execute
374 if (!found) throw new Error(`No ${name} tool`)
375 return found
376 }
377 const { signal } = new AbortController()
378 const context = { abortSignal: signal, emitCustomEvent: () => undefined }
379 await tool('write_file')({ path: 'signal.txt', content: 'hi' }, context)
380 await tool('read_file')({ path: 'signal.txt' }, context)
381 const names = new Set(seen.map(([name]) => name))
382 expect(names).toEqual(
383 new Set(['readFile', 'writeFile', 'stat', 'realpath']),
384 )
385 expect(seen.filter(([, each]) => each !== signal)).toEqual([])
386 })
387})