Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { join, relative, resolve, sep } from 'node:path'
3import { describe, expect, it } from 'vitest'
4import { fileVersions } from '../src/first-party/coding/edit'
5import { FileChanged } from '../src/first-party/coding/events'
6import {
7 parsePatch,
8 patchPaths,
9 patchTools,
10} from '../src/first-party/coding/patch'
11import type { AnyTool } from '@tanstack/ai'
12import type {
13 ToolEnv,
14 WorkspaceBackend,
15} from '../src/first-party/coding/backend'
16
17const root = resolve(tmpdir(), 'harness-patch')
18const encoder = new TextEncoder()
19// Keep a byte order mark in the text, so the tests can see it.
20const decoder = new TextDecoder('utf-8', { ignoreBOM: true })
21
22/** A workspace path, with `/` between the parts. */
23const shown = (full: string) => relative(root, full).split(sep).join('/')
24
25/** A patch with `lines` between the begin and end lines. */
26function patch(...lines: Array<string>) {
27 return ['*** Begin Patch', ...lines, '*** End Patch'].join('\n')
28}
29
30/** A unified diff of `rows`, each with a line ending. */
31const diff = (...rows: Array<string>) => rows.map((row) => `${row}\n`).join('')
32
33/**
34 * The patch tool on files in memory that start as `files`. `written` lists
35 * the files that the `afterWrite` hook saw, in order, and `changes` the
36 * `FileChanged` values that the tool sent. With `canRemove: false`, the
37 * backend has no `remove`. `dirs` are folders. The `beforeWrite` hook
38 * refuses the files in `protect`, and `checked` lists the files it saw.
39 */
40function workspace(
41 files: Record<string, string>,
42 {
43 canRemove = true,
44 dirs = [] as Array<string>,
45 protect = [] as Array<string>,
46 } = {},
47) {
48 const store = new Map<string, Uint8Array>()
49 for (const [path, text] of Object.entries(files)) {
50 store.set(join(root, path), encoder.encode(text))
51 }
52 const backend: WorkspaceBackend = {
53 readFile: async (path) => {
54 const data = store.get(path)
55 if (!data) throw new Error(`No file ${path}`)
56 return data
57 },
58 writeFile: async (path, data) => {
59 store.set(path, typeof data === 'string' ? encoder.encode(data) : data)
60 },
61 remove: canRemove
62 ? async (path) => {
63 if (!store.delete(path)) throw new Error(`No file ${path}`)
64 }
65 : undefined,
66 stat: async (path) => {
67 if (dirs.some((dir) => join(root, dir) === path)) {
68 return { type: 'dir', size: 0, mtimeMs: 0 }
69 }
70 const data = store.get(path)
71 return data && { type: 'file', size: data.length, mtimeMs: 0 }
72 },
73 // No links: each path is its own real path.
74 realpath: async (path) => path,
75 readdir: async () => [],
76 exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
77 }
78 const written: Array<string> = []
79 const checked: Array<string> = []
80 const changes: Array<unknown> = []
81 const env: ToolEnv = {
82 backend,
83 root,
84 hooks: () => [
85 {
86 beforeWrite: async (path) => {
87 checked.push(shown(path))
88 if (protect.includes(shown(path))) {
89 return { refuse: `${shown(path)} is protected.` }
90 }
91 return undefined
92 },
93 afterWrite: async (path) => {
94 written.push(shown(path))
95 },
96 },
97 ],
98 lock: (_path, fn) => fn(),
99 reach: async (path) => resolve(root, path),
100 shown,
101 emit: (event, value) => {
102 if (event === FileChanged) changes.push(value)
103 },
104 }
105 const tools: Array<AnyTool> = patchTools(env, fileVersions(env))
106 const [tool] = tools
107 return {
108 written,
109 checked,
110 changes,
111 run: async (text: string) => {
112 if (!tool?.execute) throw new Error('No patch tool')
113 const result: string = await tool.execute({ patch: text })
114 return result
115 },
116 /** Every file, by workspace path. */
117 files: () =>
118 Object.fromEntries(
119 [...store].map(
120 ([full, data]) => [shown(full), decoder.decode(data)] as const,
121 ),
122 ),
123 }
124}
125
126/** Apply `text` to a workspace with one file, `a.txt`, and read it back. */
127async function patchFile(content: string, text: string) {
128 const files = workspace({ 'a.txt': content })
129 await files.run(text)
130 return files.files()['a.txt']
131}
132
133describe('parsePatch', () => {
134 it('reads added, deleted, and updated files, and a move', () => {
135 const text = patch(
136 '*** Add File: src/new.ts',
137 '+export const a = 1',
138 '+',
139 '*** Delete File: old.txt',
140 '*** Update File: src/app.ts',
141 '*** Move to: src/main.ts',
142 '@@ function main() {',
143 ' const x = 1',
144 '-const y = 2',
145 '+const y = 3',
146 )
147 expect(parsePatch(text)).toEqual([
148 { type: 'add', path: 'src/new.ts', content: 'export const a = 1\n\n' },
149 { type: 'delete', path: 'old.txt' },
150 {
151 type: 'update',
152 path: 'src/app.ts',
153 movePath: 'src/main.ts',
154 chunks: [
155 {
156 context: 'function main() {',
157 oldLines: ['const x = 1', 'const y = 2'],
158 newLines: ['const x = 1', 'const y = 3'],
159 endOfFile: false,
160 },
161 ],
162 },
163 ])
164 })
165
166 it('reads several chunks, a first chunk without @@, End of File, and CRLF text', () => {
167 const text = patch(
168 '*** Update File: a.txt',
169 '-one',
170 '+1',
171 '@@',
172 ' two',
173 '',
174 '-three',
175 '*** End of File',
176 ).replaceAll('\n', '\r\n')
177 expect(parsePatch(text)).toEqual([
178 {
179 type: 'update',
180 path: 'a.txt',
181 chunks: [
182 {
183 oldLines: ['one'],
184 newLines: ['1'],
185 endOfFile: false,
186 },
187 {
188 oldLines: ['two', '', 'three'],
189 newLines: ['two', ''],
190 endOfFile: true,
191 },
192 ],
193 },
194 ])
195 })
196
197 it.each([
198 {
199 name: 'a missing begin line',
200 text: '\n*** Update File: a.txt\n*** End Patch',
201 error: 'Patch line 2: the patch must start with "*** Begin Patch".',
202 },
203 {
204 name: 'a missing end line',
205 text: '*** Begin Patch\n*** Delete File: a.txt\n',
206 error: 'Patch line 2: the patch must end with "*** End Patch".',
207 },
208 {
209 name: 'an unknown header',
210 text: patch('*** Rename File: a.txt'),
211 error:
212 'Patch line 2: expected "*** Add File:", "*** Delete File:", or "*** Update File:".',
213 },
214 {
215 name: 'an added line without +',
216 text: patch('*** Add File: a.txt', '+one', 'two'),
217 error: 'Patch line 4: each line of an added file must start with "+".',
218 },
219 {
220 name: 'a chunk line without a prefix',
221 text: patch('*** Update File: a.txt', '@@', ' one', 'two'),
222 error: 'Patch line 5: each chunk line must start with " ", "-", or "+".',
223 },
224 {
225 name: 'an update without changes',
226 text: patch('*** Update File: a.txt', '@@', '*** Delete File: b.txt'),
227 error: 'Patch line 2: "*** Update File: a.txt" has no changes.',
228 },
229 {
230 name: 'a header without a path',
231 text: patch('*** Add File: '),
232 error: 'Patch line 2: the path is missing.',
233 },
234 ])('refuses $name', ({ text, error }) => {
235 expect(() => parsePatch(text)).toThrow(error)
236 })
237})
238
239describe('patchPaths', () => {
240 it('lists every path, with the move targets', () => {
241 const text = patch(
242 '*** Add File: new.txt',
243 '+x',
244 '*** Delete File: old.txt',
245 '*** Update File: src/a.ts',
246 '*** Move to: src/b.ts',
247 '-x',
248 )
249 expect(patchPaths(text)).toEqual([
250 'new.txt',
251 'old.txt',
252 'src/a.ts',
253 'src/b.ts',
254 ])
255 })
256
257 it('throws when the patch does not parse', () => {
258 expect(() => patchPaths('*** Delete File: a.txt')).toThrow(
259 'Patch line 1: the patch must start with "*** Begin Patch".',
260 )
261 })
262})
263
264describe('patch tool', () => {
265 it('adds and updates files, and lists them', async () => {
266 const files = workspace({ 'src/a.ts': 'const a = 1\nconst b = 2\n' })
267 const result = await files.run(
268 patch(
269 '*** Add File: src/new.ts',
270 '+hello',
271 '*** Update File: src/a.ts',
272 '@@',
273 '-const b = 2',
274 '+const b = 3',
275 ),
276 )
277 expect(result).toBe(
278 'Applied the patch:\nadded src/new.ts\nupdated src/a.ts',
279 )
280 expect(files.files()).toEqual({
281 'src/a.ts': 'const a = 1\nconst b = 3\n',
282 'src/new.ts': 'hello\n',
283 })
284 })
285
286 it('searches from the @@ line', async () => {
287 const file =
288 'function a() {\n return 1\n}\nfunction b() {\n return 1\n}\n'
289 const text = patch(
290 '*** Update File: a.txt',
291 '@@ function b() {',
292 '- return 1',
293 '+ return 2',
294 )
295 expect(await patchFile(file, text)).toBe(
296 'function a() {\n return 1\n}\nfunction b() {\n return 2\n}\n',
297 )
298 })
299
300 it('puts only added lines below the @@ line', async () => {
301 const text = patch('*** Update File: a.txt', '@@ two', '+two and a half')
302 expect(await patchFile('one\ntwo\nthree\n', text)).toBe(
303 'one\ntwo\ntwo and a half\nthree\n',
304 )
305 })
306
307 it('searches each chunk after the chunk before it', async () => {
308 // `x` is in the file twice, but once after the first chunk.
309 const text = patch(
310 '*** Update File: a.txt',
311 '@@',
312 '-a',
313 '+A',
314 '@@',
315 '-x',
316 '+X',
317 )
318 expect(await patchFile('x\na\nx\n', text)).toBe('x\nA\nX\n')
319 })
320
321 it('matches the end of the file after End of File', async () => {
322 const text = patch(
323 '*** Update File: a.txt',
324 '@@',
325 '-end',
326 '+END',
327 '*** End of File',
328 )
329 expect(await patchFile('end\nmiddle\nend\n', text)).toBe(
330 'end\nmiddle\nEND\n',
331 )
332 })
333
334 it('sees the changes of an earlier section on the same file', async () => {
335 const text = patch(
336 '*** Update File: a.txt',
337 '-one',
338 '+1',
339 '*** Update File: a.txt',
340 '-1',
341 '+uno',
342 )
343 expect(await patchFile('one\n', text)).toBe('uno\n')
344 })
345
346 it.each([
347 {
348 name: 'a CRLF file stays CRLF',
349 file: 'one\r\ntwo\r\nthree\r\n',
350 expected: 'one\r\n2\r\nthree\r\n',
351 },
352 {
353 name: 'a byte order mark stays',
354 file: 'one\ntwo\nthree\n',
355 expected: 'one\n2\nthree\n',
356 },
357 {
358 name: 'a file without a last line ending stays without it',
359 file: 'one\ntwo',
360 expected: 'one\n2',
361 },
362 ])('$name', async ({ file, expected }) => {
363 const text = patch('*** Update File: a.txt', '@@', ' one', '-two', '+2')
364 expect(await patchFile(file, text)).toBe(expected)
365 })
366
367 it('matches lines in another Unicode form', async () => {
368 // The file is in NFD form. The patch is in NFC form.
369 const file = 'café\nnaïve\n'
370 const text = patch('*** Update File: a.txt', '@@', '-café', '+tea')
371 expect(await patchFile(file, text)).toBe('tea\nnaïve\n')
372 })
373
374 it.each([
375 {
376 name: 'old lines that are not in the file',
377 file: 'x\nmid\nx\n',
378 lines: ['@@', '-zzz', '+q'],
379 error: 'Chunk 1 of a.txt: the old lines are not in the file.',
380 },
381 {
382 name: 'old lines that are in the file twice',
383 file: 'x\nmid\nx\n',
384 lines: ['@@', '-x', '+y'],
385 error:
386 'Chunk 1 of a.txt: the old lines appear 2 times. Add context lines.',
387 },
388 {
389 name: 'an @@ line that is not in the file',
390 file: 'x\nmid\nx\n',
391 lines: ['@@ function nope() {', '-x', '+y'],
392 error: 'Chunk 1 of a.txt: "@@ function nope() {" is not in the file.',
393 },
394 {
395 // The file has `x` only at the end of the line `ax`.
396 name: 'old lines that start inside a line',
397 file: 'ax\nb\n',
398 lines: ['@@', '-x', '+y'],
399 error: 'Chunk 1 of a.txt: the old lines are not in the file.',
400 },
401 ])('refuses $name, and changes nothing', async ({ file, lines, error }) => {
402 const files = workspace({ 'a.txt': file })
403 await expect(
404 files.run(patch('*** Update File: a.txt', ...lines)),
405 ).rejects.toThrow(error)
406 expect(files.files()).toEqual({ 'a.txt': file })
407 })
408
409 it('changes no file, and sends no event, when a later file does not fit', async () => {
410 const files = workspace({ 'a.txt': 'a\n', 'b.txt': 'b\n' })
411 const text = patch(
412 '*** Update File: a.txt',
413 '-a',
414 '+A',
415 '*** Add File: c.txt',
416 '+c',
417 '*** Update File: b.txt',
418 '-zzz',
419 '+Z',
420 )
421 await expect(files.run(text)).rejects.toThrow(
422 'Chunk 1 of b.txt: the old lines are not in the file.',
423 )
424 expect(files.files()).toEqual({ 'a.txt': 'a\n', 'b.txt': 'b\n' })
425 expect(files.written).toEqual([])
426 expect(files.changes).toEqual([])
427 })
428
429 it('changes no file when an added file is a folder', async () => {
430 const files = workspace({ 'a.txt': 'a\n' }, { dirs: ['src'] })
431 const text = patch(
432 '*** Update File: a.txt',
433 '-a',
434 '+A',
435 '*** Add File: src',
436 '+c',
437 )
438 await expect(files.run(text)).rejects.toThrow(
439 'Cannot add src: it is a folder.',
440 )
441 expect(files.files()).toEqual({ 'a.txt': 'a\n' })
442 })
443
444 it('checks every file with beforeWrite, and a refusal writes nothing', async () => {
445 const files = workspace(
446 { 'a.txt': 'a\n', 'b.txt': 'b\n', 'c.txt': 'c\n' },
447 { protect: ['c.txt'] },
448 )
449 await expect(
450 files.run(
451 patch(
452 '*** Update File: a.txt',
453 '-a',
454 '+A',
455 '*** Delete File: b.txt',
456 '*** Update File: c.txt',
457 '-c',
458 '+C',
459 ),
460 ),
461 ).rejects.toThrow('c.txt is protected.')
462 expect(files.checked).toEqual(['a.txt', 'b.txt', 'c.txt'])
463 expect(files.written).toEqual([])
464 expect(files.files()).toEqual({
465 'a.txt': 'a\n',
466 'b.txt': 'b\n',
467 'c.txt': 'c\n',
468 })
469 })
470
471 it('runs the afterWrite hook once for each written file', async () => {
472 const files = workspace({ 'a.txt': 'a\n', 'b.txt': 'b\n' })
473 await files.run(
474 patch(
475 '*** Update File: a.txt',
476 '-a',
477 '+A',
478 '*** Update File: b.txt',
479 '-b',
480 '+B',
481 '*** Update File: a.txt',
482 '-A',
483 '+AA',
484 ),
485 )
486 expect(files.written).toEqual(['a.txt', 'b.txt'])
487 })
488
489 it('deletes a file, and runs no hook for it', async () => {
490 const files = workspace({ 'a.txt': 'a\n', 'b.txt': 'b\n' })
491 const result = await files.run(
492 patch('*** Add File: c.txt', '+c', '*** Delete File: a.txt'),
493 )
494 expect(result).toBe('Applied the patch:\nadded c.txt\ndeleted a.txt')
495 expect(files.files()).toEqual({ 'b.txt': 'b\n', 'c.txt': 'c\n' })
496 expect(files.written).toEqual(['c.txt'])
497 })
498
499 it('moves a file, and applies its chunks', async () => {
500 const files = workspace({ 'a.txt': 'one\ntwo\n' })
501 const result = await files.run(
502 patch(
503 '*** Update File: a.txt',
504 '*** Move to: src/b.txt',
505 '@@',
506 ' one',
507 '-two',
508 '+2',
509 ),
510 )
511 expect(result).toBe('Applied the patch:\nmoved a.txt to src/b.txt')
512 expect(files.files()).toEqual({ 'src/b.txt': 'one\n2\n' })
513 expect(files.written).toEqual(['src/b.txt'])
514 })
515
516 it.each([
517 {
518 name: 'a delete of a missing file',
519 lines: ['*** Delete File: missing.txt'],
520 error: 'Cannot delete missing.txt: no such file.',
521 },
522 {
523 name: 'a move onto a file that is there',
524 lines: ['*** Update File: a.txt', '*** Move to: b.txt'],
525 error: 'Cannot move a.txt to b.txt: b.txt already exists.',
526 },
527 ])('refuses $name, and changes nothing', async ({ lines, error }) => {
528 const before = { 'a.txt': 'a\n', 'b.txt': 'b\n', 'd.txt': 'd\n' }
529 const files = workspace(before)
530 await expect(
531 files.run(
532 patch('*** Add File: c.txt', '+c', '*** Delete File: d.txt', ...lines),
533 ),
534 ).rejects.toThrow(error)
535 expect(files.files()).toEqual(before)
536 })
537
538 it.each([
539 {
540 name: 'a delete',
541 lines: ['*** Delete File: a.txt'],
542 error: 'Cannot delete a.txt: the workspace cannot remove files.',
543 },
544 {
545 name: 'a move',
546 lines: ['*** Update File: a.txt', '*** Move to: b.txt'],
547 error: 'Cannot move a.txt: the workspace cannot remove files.',
548 },
549 ])(
550 'refuses $name when the backend cannot remove files, and changes nothing',
551 async ({ lines, error }) => {
552 const files = workspace({ 'a.txt': 'a\n' }, { canRemove: false })
553 await expect(
554 files.run(patch('*** Add File: c.txt', '+c', ...lines)),
555 ).rejects.toThrow(error)
556 expect(files.files()).toEqual({ 'a.txt': 'a\n' })
557 },
558 )
559})
560
561describe('FileChanged of the patch tool', () => {
562 it('sends one event for each added, updated, and deleted file', async () => {
563 const files = workspace({ 'a.txt': 'a\n', 'b.txt': 'b\n' })
564 await files.run(
565 patch(
566 '*** Add File: c.txt',
567 '+c',
568 '*** Update File: a.txt',
569 '-a',
570 '+A',
571 '*** Delete File: b.txt',
572 ),
573 )
574 // No tool call id: a call from code mode sends the events too.
575 expect(files.changes).toEqual([
576 {
577 path: join(root, 'c.txt'),
578 change: 'created',
579 patch: diff(
580 'diff --git a/c.txt b/c.txt',
581 'new file mode 100644',
582 '--- /dev/null',
583 '+++ b/c.txt',
584 '@@ -0,0 +1 @@',
585 '+c',
586 ),
587 additions: 1,
588 deletions: 0,
589 },
590 {
591 path: join(root, 'a.txt'),
592 change: 'updated',
593 patch: diff(
594 'diff --git a/a.txt b/a.txt',
595 '--- a/a.txt',
596 '+++ b/a.txt',
597 '@@ -1 +1 @@',
598 '-a',
599 '+A',
600 ),
601 additions: 1,
602 deletions: 1,
603 },
604 {
605 path: join(root, 'b.txt'),
606 change: 'deleted',
607 patch: diff(
608 'diff --git a/b.txt b/b.txt',
609 'deleted file mode 100644',
610 '--- a/b.txt',
611 '+++ /dev/null',
612 '@@ -1 +0,0 @@',
613 '-b',
614 ),
615 additions: 0,
616 deletions: 1,
617 },
618 ])
619 })
620
621 it('sends one moved event for a move, with the old path', async () => {
622 const files = workspace({ 'a.txt': 'one\ntwo\n' })
623 await files.run(
624 patch(
625 '*** Update File: a.txt',
626 '*** Move to: src/b.txt',
627 '@@',
628 ' one',
629 '-two',
630 '+2',
631 ),
632 )
633 expect(files.changes).toEqual([
634 {
635 path: join(root, 'src', 'b.txt'),
636 change: 'moved',
637 from: join(root, 'a.txt'),
638 patch: diff(
639 'diff --git a/a.txt b/src/b.txt',
640 'rename from a.txt',
641 'rename to src/b.txt',
642 '--- a/a.txt',
643 '+++ b/src/b.txt',
644 '@@ -1,2 +1,2 @@',
645 ' one',
646 '-two',
647 '+2',
648 ),
649 additions: 1,
650 deletions: 1,
651 },
652 ])
653 })
654
655 it.each([
656 {
657 name: 'an add that replaces a file, against the old text',
658 lines: ['*** Add File: a.txt', '+new'],
659 },
660 {
661 name: 'a file that two sections change, against its text before the patch',
662 lines: [
663 '*** Update File: a.txt',
664 '-old',
665 '+between',
666 '*** Update File: a.txt',
667 '-between',
668 '+new',
669 ],
670 },
671 ])('sends updated for $name', async ({ lines }) => {
672 const files = workspace({ 'a.txt': 'old\n' })
673 await files.run(patch(...lines))
674 expect(files.changes).toEqual([
675 {
676 path: join(root, 'a.txt'),
677 change: 'updated',
678 patch: diff(
679 'diff --git a/a.txt b/a.txt',
680 '--- a/a.txt',
681 '+++ b/a.txt',
682 '@@ -1 +1 @@',
683 '-old',
684 '+new',
685 ),
686 additions: 1,
687 deletions: 1,
688 },
689 ])
690 })
691
692 it('sends no patch for a binary file', async () => {
693 const files = workspace({ 'a.bin': 'x\0y' })
694 await files.run(patch('*** Delete File: a.bin'))
695 expect(files.changes).toEqual([
696 {
697 path: join(root, 'a.bin'),
698 change: 'deleted',
699 additions: 0,
700 deletions: 0,
701 },
702 ])
703 })
704})