Open History to see the last commit
1import {
2 mkdtemp,
3 readFile,
4 rm,
5 symlink,
6 unlink,
7 writeFile,
8} from 'node:fs/promises'
9import { tmpdir } from 'node:os'
10import { join } from 'node:path'
11import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
12import { hostBackend } from '../src/first-party/coding/backend'
13import { createWorkspaceTools } from '../src/first-party/coding/workspace'
14import { gate } from './helpers'
15import type { WorkspaceBackend } from '../src/first-party/coding/backend'
16
17// Coverage runs in CI are slow, so polled checks wait up to 5 s.
18const waitFor = <T>(
19 check: () => T | Promise<T>,
20 options?: { timeout?: number; interval?: number },
21) => vi.waitFor(check, { timeout: 5_000, ...options })
22
23let root = ''
24
25beforeEach(async () => {
26 root = await mkdtemp(join(tmpdir(), 'harness-locks-'))
27})
28
29afterEach(async () => {
30 await rm(root, { recursive: true, force: true })
31})
32
33const put = (path: string, text: string) => writeFile(join(root, path), text)
34const read = (path: string) => readFile(join(root, path), 'utf8')
35
36/**
37 * The workspace tools of one session on `at` (default: `root`). Runs a tool
38 * by its name. With `signal`, the call runs in the chat run of that signal.
39 */
40function openSession(backend: WorkspaceBackend = hostBackend, at = root) {
41 const { tools } = createWorkspaceTools({ root: at, backend, web: false })
42 return async (name: string, args: object, signal?: AbortSignal) => {
43 const tool = tools.find((each) => each.name === name)
44 if (!tool?.execute) throw new Error(`No tool ${name}.`)
45 const result: unknown = await tool.execute(
46 args,
47 signal && { emitCustomEvent: () => undefined, abortSignal: signal },
48 )
49 return result
50 }
51}
52
53/**
54 * The host backend, with a count of the `realpath` and `stat` calls. With
55 * `held`, each write waits for `release`, and `reached` resolves at the
56 * first write.
57 */
58function watchedBackend({ held = false } = {}) {
59 const reached = gate()
60 const released = gate()
61 const calls = { realpath: 0, stat: 0 }
62 const backend: WorkspaceBackend = {
63 ...hostBackend,
64 realpath: (path) => {
65 calls.realpath += 1
66 return hostBackend.realpath(path)
67 },
68 stat: (path) => {
69 calls.stat += 1
70 return hostBackend.stat(path)
71 },
72 writeFile: async (path, data) => {
73 if (held) {
74 reached.open()
75 await released.opened
76 }
77 return hostBackend.writeFile(path, data)
78 },
79 }
80 return { backend, calls, reached: reached.opened, release: released.open }
81}
82
83/** Long enough for a call that does not wait at the lock to go past it. */
84const settle = () => new Promise((resolve) => setTimeout(resolve, 50))
85
86/** A promise, and whether it settled. */
87function tracked<T>(promise: Promise<T>) {
88 const state = { settled: false }
89 const done = promise.finally(() => {
90 state.settled = true
91 })
92 return { done, state }
93}
94
95describe('file locks across sessions', () => {
96 it('makes the second edit wait, then fails it: the file changed since its read', async () => {
97 await put('a.txt', 'one\n')
98 const first = watchedBackend({ held: true })
99 const second = watchedBackend()
100 const firstCall = openSession(first.backend)
101 const secondCall = openSession(second.backend)
102 await firstCall('read_file', { path: 'a.txt' })
103 await secondCall('read_file', { path: 'a.txt' })
104
105 const firstEdit = firstCall('edit_file', {
106 path: 'a.txt',
107 old: 'one',
108 new: 'first',
109 })
110 await first.reached
111 const before = second.calls.realpath
112 const secondEdit = tracked(
113 secondCall('edit_file', { path: 'a.txt', old: 'one', new: 'second' }),
114 )
115 // `reach` resolves the path once. The lock resolves it again only when
116 // the first edit is done.
117 await waitFor(() => expect(second.calls.realpath).toBe(before + 1))
118 await settle()
119 expect(second.calls.realpath).toBe(before + 1)
120 expect(secondEdit.state.settled).toBe(false)
121
122 first.release()
123 await firstEdit
124 await expect(secondEdit.done).rejects.toThrow(
125 'a.txt changed since it was read. Read it again before you edit it.',
126 )
127 expect(await read('a.txt')).toBe('first\n')
128 })
129
130 it('makes an edit through another spelling of the root wait for the lock', async () => {
131 await put('a.txt', 'one\n')
132 const link = `${root}-link`
133 await symlink(root, link, 'junction')
134 try {
135 const first = watchedBackend({ held: true })
136 const firstCall = openSession(first.backend)
137 const secondCall = openSession(hostBackend, link)
138 await firstCall('read_file', { path: 'a.txt' })
139 await secondCall('read_file', { path: 'a.txt' })
140
141 const firstEdit = firstCall('edit_file', {
142 path: 'a.txt',
143 old: 'one',
144 new: 'first',
145 })
146 await first.reached
147 const secondEdit = tracked(
148 secondCall('edit_file', { path: 'a.txt', old: 'one', new: 'second' }),
149 )
150 // One folder, one lock: the second edit waits for the first.
151 await settle()
152 expect(secondEdit.state.settled).toBe(false)
153
154 first.release()
155 await firstEdit
156 await expect(secondEdit.done).rejects.toThrow(
157 'a.txt changed since it was read.',
158 )
159 expect(await read('a.txt')).toBe('first\n')
160 } finally {
161 await unlink(link)
162 }
163 })
164
165 it('lets the second session edit after it reads the file again', async () => {
166 await put('a.txt', 'one two\n')
167 const firstCall = openSession()
168 const secondCall = openSession()
169 await firstCall('read_file', { path: 'a.txt' })
170 await secondCall('read_file', { path: 'a.txt' })
171 await firstCall('edit_file', { path: 'a.txt', old: 'one', new: 'ONE' })
172 await expect(
173 secondCall('edit_file', { path: 'a.txt', old: 'two', new: 'TWO' }),
174 ).rejects.toThrow('a.txt changed since it was read.')
175
176 await secondCall('read_file', { path: 'a.txt' })
177 await secondCall('edit_file', { path: 'a.txt', old: 'two', new: 'TWO' })
178
179 expect(await read('a.txt')).toBe('ONE TWO\n')
180 })
181
182 it('fails write_file when another session created the file while it waited', async () => {
183 const first = watchedBackend({ held: true })
184 const second = watchedBackend()
185 const firstWrite = openSession(first.backend)('write_file', {
186 path: 'new.txt',
187 content: 'first',
188 })
189 await first.reached
190 const secondWrite = tracked(
191 openSession(second.backend)('write_file', {
192 path: 'new.txt',
193 content: 'second',
194 }),
195 )
196 // One `stat` before the lock sees no file. The check under the lock
197 // waits for the first write.
198 await waitFor(() => expect(second.calls.stat).toBe(1))
199 await settle()
200 expect(secondWrite.state.settled).toBe(false)
201
202 first.release()
203 await firstWrite
204 await expect(secondWrite.done).rejects.toThrow(
205 'new.txt was created while the tool waited. Read it before you edit it.',
206 )
207 expect(await read('new.txt')).toBe('first')
208 })
209})
210
211describe('the unchanged check of each chat run', () => {
212 it('fails a write of the lead after a subagent of the session changed the file', async () => {
213 await put('a.txt', 'one\n')
214 const call = openSession()
215 const lead = new AbortController().signal
216 const subagent = new AbortController().signal
217 await call('read_file', { path: 'a.txt' }, lead)
218 await call('read_file', { path: 'a.txt' }, subagent)
219 await call('write_file', { path: 'a.txt', content: 'the fix\n' }, subagent)
220
221 await expect(
222 call('write_file', { path: 'a.txt', content: 'one, again\n' }, lead),
223 ).rejects.toThrow('a.txt changed since it was read.')
224 expect(await read('a.txt')).toBe('the fix\n')
225 })
226})
227
228describe('the unchanged check', () => {
229 it.each([
230 ['edit_file', { path: 'a.txt', old: 'one', new: 'two' }],
231 ['write_file', { path: 'a.txt', content: 'two\n' }],
232 [
233 'patch',
234 {
235 patch: [
236 '*** Begin Patch',
237 '*** Update File: a.txt',
238 '@@',
239 '-one',
240 '+two',
241 '*** End Patch',
242 ].join('\n'),
243 },
244 ],
245 ])(
246 '%s fails for a file that changed on disk after the read',
247 async (name, args) => {
248 await put('a.txt', 'one\n')
249 const call = openSession()
250 await call('read_file', { path: 'a.txt' })
251 await put('a.txt', 'changed on disk\n')
252
253 await expect(call(name, args)).rejects.toThrow(
254 'a.txt changed since it was read. Read it again before you edit it.',
255 )
256 expect(await read('a.txt')).toBe('changed on disk\n')
257 },
258 )
259
260 it("keeps the session's own writes: a second edit after the first works", async () => {
261 await put('a.txt', 'one two\n')
262 const call = openSession()
263 await call('read_file', { path: 'a.txt' })
264
265 await call('edit_file', { path: 'a.txt', old: 'one', new: 'ONE' })
266 await call('edit_file', { path: 'a.txt', old: 'two', new: 'TWO' })
267
268 expect(await read('a.txt')).toBe('ONE TWO\n')
269 })
270
271 it('lets write_file replace a file that the session never read', async () => {
272 await put('a.txt', 'one\n')
273
274 await openSession()('write_file', { path: 'a.txt', content: 'two\n' })
275
276 expect(await read('a.txt')).toBe('two\n')
277 })
278})