Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { join, resolve } from 'node:path'
3import { describe, expect, it } from 'vitest'
4import { createWorkspaceTools } from '../src/first-party/coding/workspace'
5import type { AnyTool } from '@tanstack/ai'
6import type { WorkspaceBackend } from '../src/first-party/coding/backend'
7
8/** A backend that keeps files in a map, by absolute path. */
9function memoryBackend() {
10 const files = new Map<string, Uint8Array>()
11 const backend: WorkspaceBackend = {
12 readFile: async (path) => {
13 const data = files.get(path)
14 if (!data) throw new Error(`No file ${path}`)
15 return data
16 },
17 writeFile: async (path, data) => {
18 files.set(
19 path,
20 typeof data === 'string' ? new TextEncoder().encode(data) : data,
21 )
22 },
23 stat: async () => undefined,
24 // No links: each path is its own real path.
25 realpath: async (path) => path,
26 readdir: async () => [],
27 exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
28 }
29 return backend
30}
31
32const root = resolve(tmpdir(), 'harness-edit')
33const backend = memoryBackend()
34const tools: Array<AnyTool> = createWorkspaceTools({ root, backend }).tools
35// Keep a byte order mark in the text, so the tests can see it.
36const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
37
38async function run(name: string, args: object) {
39 const tool = tools.find((item) => item.name === name)
40 if (!tool?.execute) throw new Error(`No tool ${name}`)
41 const result: string = await tool.execute(args)
42 return result
43}
44
45async function read(path: string) {
46 return decoder.decode(await backend.readFile(join(root, path)))
47}
48
49/** Write `text` to `path`, run `edit_file` on it, and read the file back. */
50async function edit(
51 path: string,
52 text: string,
53 change: { old: string; new: string; replaceAll?: boolean },
54) {
55 await backend.writeFile(join(root, path), text)
56 const result = await run('edit_file', { path, ...change })
57 return { result, text: await read(path) }
58}
59
60describe('edit_file', () => {
61 it('replaces the exact text', async () => {
62 expect(
63 await edit('exact.txt', 'let a = 1\nlet b = 2\n', {
64 old: 'a = 1',
65 new: 'a = 3',
66 }),
67 ).toEqual({
68 result: 'Edited exact.txt (1 change).',
69 text: 'let a = 3\nlet b = 2\n',
70 })
71 })
72
73 it('matches text in another Unicode form, and keeps the rest of the file', async () => {
74 // The file is in NFD form. The old text is in NFC form.
75 const { text } = await edit('nfd.txt', 'café and naïve\n', {
76 old: 'café',
77 new: 'tea',
78 })
79 expect(text).toBe('tea and naïve\n')
80 })
81
82 it('ignores spaces and tabs at the end of lines', async () => {
83 const { text } = await edit('trailing.txt', 'a \nb\t\nc \n', {
84 old: 'a\nb',
85 new: 'x',
86 })
87 expect(text).toBe('x\nc \n')
88 })
89
90 // Only the old text needs the change. The level must still run.
91 it.each([
92 ['another Unicode form', 'café\n', 'café', 'tea\n'],
93 ['spaces at the end of a line', 'a\nb\n', 'a \nb', 'tea\n'],
94 ])(
95 'matches old text in %s, in a file without it',
96 async (_, file, old, expected) => {
97 const { text } = await edit('reverse.txt', file, { old, new: 'tea' })
98 expect(text).toBe(expected)
99 },
100 )
101
102 it('prefers an exact match over a looser one', async () => {
103 // With trailing spaces ignored, `foo\n` is in the file twice.
104 const { text } = await edit('prefer.txt', 'foo\nfoo \n', {
105 old: 'foo\n',
106 new: 'bar\n',
107 })
108 expect(text).toBe('bar\nfoo \n')
109 })
110
111 it('refuses text that is not unique at the level that finds it, unless replaceAll', async () => {
112 const file = 'foo \nbar\nfoo\t\nbar\n'
113 await expect(
114 edit('twice.txt', file, { old: 'foo\nbar', new: 'x' }),
115 ).rejects.toThrow('The old text appears 2 times.')
116 expect(
117 await edit('twice.txt', file, {
118 old: 'foo\nbar',
119 new: 'x',
120 replaceAll: true,
121 }),
122 ).toEqual({ result: 'Edited twice.txt (2 changes).', text: 'x\nx\n' })
123 })
124
125 it('refuses text that is not in the file, and empty text', async () => {
126 await expect(
127 edit('missing.txt', 'abc\n', { old: 'zzz', new: 'q' }),
128 ).rejects.toThrow('The old text is not in the file.')
129 await expect(
130 edit('missing.txt', 'abc\n', { old: '', new: 'q' }),
131 ).rejects.toThrow('The old text is not in the file.')
132 })
133
134 it.each([
135 {
136 name: 'a CRLF file with LF text',
137 file: 'one\r\ntwo\r\nthree\r\n',
138 old: 'one\ntwo',
139 new: '1\n2',
140 expected: '1\r\n2\r\nthree\r\n',
141 },
142 {
143 name: 'an LF file with CRLF text',
144 file: 'one\ntwo\nthree\n',
145 old: 'one\r\ntwo',
146 new: '1\r\n2',
147 expected: '1\n2\nthree\n',
148 },
149 ])('edits $name, and keeps the line endings of the file', async (example) => {
150 const { text } = await edit('endings.txt', example.file, {
151 old: example.old,
152 new: example.new,
153 })
154 expect(text).toBe(example.expected)
155 })
156
157 it.each([
158 { name: 'without the mark', old: 'first' },
159 { name: 'that starts with the mark', old: 'first' },
160 ])('keeps the byte order mark, with old text $name', async ({ old }) => {
161 const { text } = await edit('bom.txt', 'first\nsecond\n', {
162 old,
163 new: '1st',
164 })
165 expect(text).toBe('1st\nsecond\n')
166 })
167})
168
169describe('write_file', () => {
170 it('writes the content as given', async () => {
171 expect(
172 await run('write_file', { path: 'new/w.txt', content: 'hi\r\n' }),
173 ).toBe('Wrote new/w.txt.')
174 expect(await read('new/w.txt')).toBe('hi\r\n')
175 })
176})