Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { diffSnapshots, watchWorkspace } from '../src/watch'
3import { captureLogger } from './fakes'
4import type { SandboxHandle } from '../src/contracts'
5import type { SandboxFileEvent } from '../src/watch'
6
7/** Let queued microtasks (the native watcher's async classify) settle. */
8function flush(): Promise<void> {
9 return new Promise((resolve) => setTimeout(resolve, 5))
10}
11
12/** Minimal handle exposing only the fs/process bits a watcher touches. */
13function fakeHandle(fs: Partial<SandboxHandle['fs']>): SandboxHandle {
14 return {
15 id: 'fake',
16 provider: 'fake',
17 capabilities: {
18 fs: true,
19 exec: true,
20 env: true,
21 ports: false,
22 backgroundProcesses: false,
23 writableStdin: true,
24 killableProcesses: true,
25 snapshots: false,
26 networkPolicy: false,
27 durableFilesystem: false,
28 fork: false,
29 },
30 fs: {
31 read: () => Promise.reject(new Error('unused')),
32 readBytes: () => Promise.reject(new Error('unused')),
33 write: () => Promise.resolve(),
34 list: () => Promise.resolve([]),
35 mkdir: () => Promise.resolve(),
36 remove: () => Promise.resolve(),
37 rename: () => Promise.resolve(),
38 exists: () => Promise.resolve(false),
39 ...fs,
40 },
41 git: {} as SandboxHandle['git'],
42 process: {
43 exec: () => Promise.reject(new Error('unused')),
44 spawn: () => Promise.reject(new Error('unused')),
45 },
46 ports: { connect: () => Promise.reject(new Error('unused')) },
47 env: { set: () => Promise.resolve() },
48 destroy: () => Promise.resolve(),
49 }
50}
51
52describe('diffSnapshots', () => {
53 it('detects create, change, and delete', () => {
54 const prev = new Map([
55 ['/workspace/a.js', '1\t10'],
56 ['/workspace/b.js', '2\t20'],
57 ])
58 const next = new Map([
59 ['/workspace/b.js', '2.5\t25'], // changed signature
60 ['/workspace/c.js', '3\t30'], // new
61 ])
62 const events = diffSnapshots(prev, next, 123)
63 expect(events).toEqual(
64 expect.arrayContaining([
65 { type: 'change', path: '/workspace/b.js', timestamp: 123 },
66 { type: 'create', path: '/workspace/c.js', timestamp: 123 },
67 { type: 'delete', path: '/workspace/a.js', timestamp: 123 },
68 ]),
69 )
70 expect(events).toHaveLength(3)
71 })
72
73 it('emits nothing for identical snapshots', () => {
74 const snap = new Map([['/workspace/a.js', '1\t10']])
75 expect(diffSnapshots(snap, new Map(snap), 1)).toEqual([])
76 })
77})
78
79describe('watchWorkspace (exec-poll)', () => {
80 afterEach(() => vi.useRealTimers())
81
82 it('diffs successive `find` snapshots into file events', async () => {
83 vi.useFakeTimers()
84 const snapshots = [
85 // initial — `find .` prints cwd-relative paths (normalized back under root)
86 '1.0\t10\t./a.js\n2.0\t20\t./b.js\n',
87 // after the agent edits b, adds c, removes a
88 '2.5\t25\t./b.js\n3.0\t30\t./c.js\n',
89 ]
90 let call = 0
91 const handle = fakeHandle({})
92 handle.process.exec = () =>
93 Promise.resolve({
94 stdout: snapshots[Math.min(call++, snapshots.length - 1)] ?? '',
95 stderr: '',
96 exitCode: 0,
97 })
98
99 const events: Array<SandboxFileEvent> = []
100 const watcher = await watchWorkspace(handle, {
101 onEvent: (e) => events.push(e),
102 intervalMs: 100,
103 })
104
105 await vi.advanceTimersByTimeAsync(120)
106 await watcher.stop()
107
108 expect(events.map((e) => `${e.type} ${e.path}`).sort()).toEqual([
109 'change /workspace/b.js',
110 'create /workspace/c.js',
111 'delete /workspace/a.js',
112 ])
113 })
114
115 it('preserves the previous snapshot when a `find` poll fails (no phantom delete/create storm)', async () => {
116 vi.useFakeTimers()
117 // initial (a, b present) → transient non-zero poll → recovery (unchanged).
118 const results = [
119 { stdout: '1.0\t10\t./a.js\n2.0\t20\t./b.js\n', stderr: '', exitCode: 0 },
120 { stdout: '', stderr: 'find: not found', exitCode: 127 },
121 { stdout: '1.0\t10\t./a.js\n2.0\t20\t./b.js\n', stderr: '', exitCode: 0 },
122 ]
123 let call = 0
124 const handle = fakeHandle({})
125 handle.process.exec = () =>
126 Promise.resolve(results[Math.min(call++, results.length - 1)]!)
127
128 const events: Array<SandboxFileEvent> = []
129 const { logger, calls } = captureLogger()
130 const watcher = await watchWorkspace(handle, {
131 onEvent: (e) => events.push(e),
132 intervalMs: 100,
133 logger,
134 })
135
136 // Tick 1 = the failed poll (preserve a,b), tick 2 = recovery (unchanged).
137 await vi.advanceTimersByTimeAsync(250)
138 await watcher.stop()
139
140 // Collapsing the failed poll to {} would emit delete a/b then re-create
141 // a/b on recovery. The preserved snapshot emits nothing.
142 expect(events).toEqual([])
143 expect(
144 calls.some((c) => c.level === 'warn' && c.msg.includes('non-zero')),
145 ).toBe(true)
146 })
147
148 it('seeds (does not diff) after a failed INITIAL poll, so recovery emits no phantom creates', async () => {
149 vi.useFakeTimers()
150 // The very first poll fails (container warming up) → then recovers with two
151 // pre-existing files. They must be adopted as the baseline, NOT reported as
152 // freshly created.
153 const results = [
154 { stdout: '', stderr: 'find: not ready', exitCode: 127 }, // initial fails
155 { stdout: '1.0\t10\t./a.js\n2.0\t20\t./b.js\n', stderr: '', exitCode: 0 },
156 { stdout: '1.0\t10\t./a.js\n2.0\t20\t./b.js\n', stderr: '', exitCode: 0 },
157 ]
158 let call = 0
159 const handle = fakeHandle({})
160 handle.process.exec = () =>
161 Promise.resolve(results[Math.min(call++, results.length - 1)]!)
162
163 const events: Array<SandboxFileEvent> = []
164 const watcher = await watchWorkspace(handle, {
165 onEvent: (e) => events.push(e),
166 intervalMs: 100,
167 })
168 await vi.advanceTimersByTimeAsync(250)
169 await watcher.stop()
170
171 // Seeding an empty baseline would fabricate a `create` for a.js and b.js.
172 expect(events).toEqual([])
173 })
174
175 it('does not crash when the INITIAL find exec rejects; recovers on the next poll', async () => {
176 vi.useFakeTimers()
177 let call = 0
178 const handle = fakeHandle({})
179 handle.process.exec = () => {
180 call++
181 if (call === 1) return Promise.reject(new Error('container not ready'))
182 return Promise.resolve({
183 stdout: '1.0\t10\t./a.js\n',
184 stderr: '',
185 exitCode: 0,
186 })
187 }
188 const events: Array<SandboxFileEvent> = []
189 // Must resolve (not reject) despite the initial exec throwing — otherwise
190 // middleware setup crashes and leaks the sandbox.
191 const watcher = await watchWorkspace(handle, {
192 onEvent: (e) => events.push(e),
193 intervalMs: 100,
194 })
195 await vi.advanceTimersByTimeAsync(250)
196 await watcher.stop()
197 // a.js is seeded on recovery, not fabricated as a `create`.
198 expect(events).toEqual([])
199 })
200
201 it('a partial (non-zero) poll does not fabricate deletes for transiently-missing files', async () => {
202 vi.useFakeTimers()
203 // full → partial (c transiently unreadable, exit 1) → full without c (real delete).
204 const results = [
205 {
206 stdout: '1\t1\t./a.js\n2\t2\t./b.js\n3\t3\t./c.js\n',
207 stderr: '',
208 exitCode: 0,
209 },
210 { stdout: '1\t1\t./a.js\n2\t2\t./b.js\n', stderr: 'denied', exitCode: 1 },
211 { stdout: '1\t1\t./a.js\n2\t2\t./b.js\n', stderr: '', exitCode: 0 },
212 ]
213 let call = 0
214 const handle = fakeHandle({})
215 handle.process.exec = () =>
216 Promise.resolve(results[Math.min(call++, results.length - 1)]!)
217
218 const events: Array<SandboxFileEvent> = []
219 const watcher = await watchWorkspace(handle, {
220 onEvent: (e) => events.push(e),
221 intervalMs: 100,
222 })
223 await vi.advanceTimersByTimeAsync(120) // tick 1: the partial poll
224 expect(events).toEqual([]) // c NOT reported deleted despite being absent
225
226 await vi.advanceTimersByTimeAsync(100) // tick 2: complete poll, c really gone
227 await watcher.stop()
228 expect(events).toEqual([
229 {
230 type: 'delete',
231 path: '/workspace/c.js',
232 timestamp: expect.any(Number),
233 },
234 ])
235 })
236
237 it('uses partial `find` output when it exits non-zero but still printed files', async () => {
238 vi.useFakeTimers()
239 // `find` hits a permission-denied dir (exit 1) but still prints readable
240 // files. The watcher must parse that output, not blind itself for the run.
241 const results = [
242 { stdout: '1.0\t10\t./a.js\n', stderr: 'permission denied', exitCode: 1 },
243 {
244 stdout: '1.0\t10\t./a.js\n2.0\t20\t./b.js\n',
245 stderr: 'permission denied',
246 exitCode: 1,
247 },
248 ]
249 let call = 0
250 const handle = fakeHandle({})
251 handle.process.exec = () =>
252 Promise.resolve(results[Math.min(call++, results.length - 1)]!)
253
254 const events: Array<SandboxFileEvent> = []
255 const watcher = await watchWorkspace(handle, {
256 onEvent: (e) => events.push(e),
257 intervalMs: 100,
258 })
259 await vi.advanceTimersByTimeAsync(120)
260 await watcher.stop()
261
262 // Baseline (a.js) parsed from the non-zero poll; b.js then seen as created.
263 expect(events).toEqual([
264 {
265 type: 'create',
266 path: '/workspace/b.js',
267 timestamp: expect.any(Number),
268 },
269 ])
270 })
271
272 it('re-baselines on the first complete poll after a PARTIAL seed, so recovered files are not fabricated as creates', async () => {
273 vi.useFakeTimers()
274 // Partial initial seed (b transiently unreadable) → first complete poll
275 // sees b → it must be adopted as baseline, NOT reported as a create.
276 const results = [
277 { stdout: '1\t1\t./a.js\n', stderr: 'denied', exitCode: 1 }, // partial seed
278 { stdout: '1\t1\t./a.js\n2\t2\t./b.js\n', stderr: '', exitCode: 0 }, // complete
279 { stdout: '1\t1\t./a.js\n2\t2\t./b.js\n', stderr: '', exitCode: 0 },
280 ]
281 let call = 0
282 const handle = fakeHandle({})
283 handle.process.exec = () =>
284 Promise.resolve(results[Math.min(call++, results.length - 1)]!)
285
286 const events: Array<SandboxFileEvent> = []
287 const watcher = await watchWorkspace(handle, {
288 onEvent: (e) => events.push(e),
289 intervalMs: 100,
290 })
291 await vi.advanceTimersByTimeAsync(250)
292 await watcher.stop()
293
294 // b was merely unreadable at seed time; the first complete poll re-baselines
295 // rather than diffing, so no phantom `create` for b.
296 expect(events).toEqual([])
297 })
298
299 it('logs a warning when the INITIAL find exec throws', async () => {
300 let call = 0
301 const handle = fakeHandle({})
302 handle.process.exec = () => {
303 call++
304 return call === 1
305 ? Promise.reject(new Error('boom'))
306 : Promise.resolve({ stdout: '', stderr: '', exitCode: 0 })
307 }
308 const { logger, calls } = captureLogger()
309 // Large interval so no tick fires before we stop — isolates the seed throw.
310 const watcher = await watchWorkspace(handle, {
311 onEvent: () => undefined,
312 intervalMs: 10000,
313 logger,
314 })
315 await watcher.stop()
316 expect(
317 calls.some((c) => c.level === 'warn' && c.msg.includes('initial')),
318 ).toBe(true)
319 })
320
321 it('logs (sandbox) and preserves previous when a steady-state tick exec throws', async () => {
322 vi.useFakeTimers()
323 let call = 0
324 const handle = fakeHandle({})
325 handle.process.exec = () => {
326 call++
327 // initial + tick1 + tick3 succeed with {a}; tick2 (call 3) throws.
328 return call === 3
329 ? Promise.reject(new Error('tick boom'))
330 : Promise.resolve({
331 stdout: '1\t1\t./a.js\n',
332 stderr: '',
333 exitCode: 0,
334 })
335 }
336 const events: Array<SandboxFileEvent> = []
337 const { logger, calls } = captureLogger()
338 const watcher = await watchWorkspace(handle, {
339 onEvent: (e) => events.push(e),
340 intervalMs: 100,
341 logger,
342 })
343 await vi.advanceTimersByTimeAsync(350)
344 await watcher.stop()
345 // The throw preserved `previous`; no fabricated delete/create for a.js.
346 expect(events).toEqual([])
347 expect(
348 calls.some((c) => c.level === 'debug' && c.msg.includes('poll threw')),
349 ).toBe(true)
350 // A single transient throw must NOT escalate to warn.
351 expect(calls.some((c) => c.level === 'warn')).toBe(false)
352 })
353
354 it('escalates to a warning when `find` polls throw persistently (watcher wedged)', async () => {
355 vi.useFakeTimers()
356 let call = 0
357 const handle = fakeHandle({})
358 handle.process.exec = () => {
359 call++
360 // Initial poll seeds {a}; every steady-state tick then throws (seam wedged).
361 return call === 1
362 ? Promise.resolve({ stdout: '1\t1\t./a.js\n', stderr: '', exitCode: 0 })
363 : Promise.reject(new Error('exec wedged'))
364 }
365 const events: Array<SandboxFileEvent> = []
366 const { logger, calls } = captureLogger()
367 const watcher = await watchWorkspace(handle, {
368 onEvent: (e) => events.push(e),
369 intervalMs: 100,
370 logger,
371 })
372 // 4 ticks all throw → crosses the 3-in-a-row escalation threshold.
373 await vi.advanceTimersByTimeAsync(450)
374 await watcher.stop()
375 // Still no fabricated events (previous preserved), but now surfaced at warn.
376 expect(events).toEqual([])
377 expect(
378 calls.some(
379 (c) => c.level === 'warn' && c.msg.includes('poll threw repeatedly'),
380 ),
381 ).toBe(true)
382 })
383
384 it('does not start polling when the signal is already aborted', async () => {
385 const controller = new AbortController()
386 controller.abort()
387 let execCalls = 0
388 const handle = fakeHandle({})
389 handle.process.exec = () => {
390 execCalls++
391 return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 })
392 }
393 const events: Array<SandboxFileEvent> = []
394 const watcher = await watchWorkspace(handle, {
395 onEvent: (e) => events.push(e),
396 intervalMs: 10,
397 signal: controller.signal,
398 })
399 await new Promise((resolve) => setTimeout(resolve, 30))
400 await watcher.stop()
401 expect(execCalls).toBe(0)
402 expect(events).toEqual([])
403 })
404})
405
406describe('watchWorkspace (native fs.watch)', () => {
407 it('classifies raw events as create/change/delete via a known-path set', async () => {
408 const present = new Set<string>()
409 let onRaw: (e: { type: string; path: string }) => void = () => undefined
410 const handle = fakeHandle({
411 list: () => Promise.resolve([]),
412 exists: (p) => Promise.resolve(present.has(p)),
413 watch: (_path, cb) => {
414 onRaw = cb
415 return Promise.resolve({ stop: () => Promise.resolve() })
416 },
417 })
418
419 const events: Array<SandboxFileEvent> = []
420 const watcher = await watchWorkspace(handle, {
421 onEvent: (e) => events.push(e),
422 })
423
424 present.add('/workspace/x.js')
425 onRaw({ type: 'rename', path: '/workspace/x.js' })
426 await flush()
427 onRaw({ type: 'change', path: '/workspace/x.js' })
428 await flush()
429 present.delete('/workspace/x.js')
430 onRaw({ type: 'rename', path: '/workspace/x.js' })
431 await flush()
432
433 await watcher.stop()
434 expect(events.map((e) => e.type)).toEqual(['create', 'change', 'delete'])
435 })
436
437 it('ignores .git / node_modules paths', async () => {
438 let onRaw: (e: { type: string; path: string }) => void = () => undefined
439 const handle = fakeHandle({
440 list: () => Promise.resolve([]),
441 exists: () => Promise.resolve(true),
442 watch: (_path, cb) => {
443 onRaw = cb
444 return Promise.resolve({ stop: () => Promise.resolve() })
445 },
446 })
447 const events: Array<SandboxFileEvent> = []
448 const watcher = await watchWorkspace(handle, {
449 onEvent: (e) => events.push(e),
450 })
451
452 onRaw({ type: 'change', path: '/workspace/.git/index' })
453 onRaw({ type: 'change', path: '/workspace/node_modules/x/index.js' })
454 await flush()
455
456 await watcher.stop()
457 expect(events).toEqual([])
458 })
459
460 it('logs a warning when native event classification fails (no silent drop)', async () => {
461 let onRaw: (e: { type: string; path: string }) => void = () => undefined
462 const handle = fakeHandle({
463 list: () => Promise.resolve([]),
464 exists: () => Promise.reject(new Error('exists boom')),
465 watch: (_p, cb) => {
466 onRaw = cb
467 return Promise.resolve({ stop: () => Promise.resolve() })
468 },
469 })
470 const { logger, calls } = captureLogger()
471 const events: Array<SandboxFileEvent> = []
472 const watcher = await watchWorkspace(handle, {
473 onEvent: (e) => events.push(e),
474 logger,
475 })
476
477 onRaw({ type: 'change', path: '/workspace/x.js' })
478 await flush()
479 await watcher.stop()
480
481 expect(events).toEqual([]) // classify failed → no event
482 expect(
483 calls.some((c) => c.level === 'warn' && c.msg.includes('classify')),
484 ).toBe(true)
485 })
486
487 it('re-seeds after a failed initial root list, so a pre-existing file is a change (not a create)', async () => {
488 let onRaw: (e: { type: string; path: string }) => void = () => undefined
489 let listCalls = 0
490 const handle = fakeHandle({
491 // First seed (during watchWorkspace) throws; the lazy re-seed on the
492 // first event succeeds and lists the pre-existing file.
493 list: () => {
494 listCalls++
495 return listCalls === 1
496 ? Promise.reject(new Error('list not ready'))
497 : Promise.resolve([
498 { name: 'a.ts', path: '/workspace/a.ts', type: 'file' as const },
499 ])
500 },
501 exists: () => Promise.resolve(true),
502 watch: (_p, cb) => {
503 onRaw = cb
504 return Promise.resolve({ stop: () => Promise.resolve() })
505 },
506 })
507 const events: Array<SandboxFileEvent> = []
508 const watcher = await watchWorkspace(handle, {
509 onEvent: (e) => events.push(e),
510 })
511
512 onRaw({ type: 'change', path: '/workspace/a.ts' })
513 await flush()
514 await watcher.stop()
515
516 // Empty seed would classify the edit as `create`; the re-seed makes a.ts
517 // known, so it's correctly a `change`.
518 expect(events.map((e) => e.type)).toEqual(['change'])
519 })
520
521 it('honors a custom root when classifying native events', async () => {
522 const present = new Set<string>()
523 let onRaw: (e: { type: string; path: string }) => void = () => undefined
524 const handle = fakeHandle({
525 list: () => Promise.resolve([]),
526 exists: (p) => Promise.resolve(present.has(p)),
527 watch: (_path, cb) => {
528 onRaw = cb
529 return Promise.resolve({ stop: () => Promise.resolve() })
530 },
531 })
532 const events: Array<SandboxFileEvent> = []
533 const watcher = await watchWorkspace(handle, {
534 onEvent: (e) => events.push(e),
535 root: '/workspace/sub',
536 })
537
538 present.add('/workspace/sub/a.ts')
539 onRaw({ type: 'rename', path: '/workspace/sub/a.ts' })
540 await flush()
541 present.delete('/workspace/sub/a.ts')
542 onRaw({ type: 'rename', path: '/workspace/sub/a.ts' })
543 await flush()
544
545 await watcher.stop()
546 expect(events.map((e) => e.type)).toEqual(['create', 'delete'])
547 })
548})