Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import Dockerode from 'dockerode'
3import { defineSandbox, defineWorkspace } from '@tanstack/ai-sandbox'
4import { dockerSandbox } from '../src/index'
5import { dockerDaemonAvailable } from './docker-daemon'
6import type { SandboxHandle } from '@tanstack/ai-sandbox'
7
8// Auto-gate: only run when a Docker daemon is reachable. See `./docker-daemon.ts`
9// for what this matrix is the authority on.
10const dockerAvailable = await dockerDaemonAvailable('docker provider')
11
12/** For the image-inspection assertions below, which read the daemon directly. */
13const docker = new Dockerode()
14
15const IMAGE = 'alpine:3'
16
17/**
18 * A command line no other process on the machine will match, so a `ps` sweep
19 * inside the container attributes a survivor to THIS test and nothing else. The
20 * bracket in the grep pattern below keeps the grep from matching its own
21 * command line.
22 */
23const KILL_PROBE_SLEEP = '987654321'
24const KILL_PROBE_GREP = '98765[4]321'
25
26describe.skipIf(!dockerAvailable)(
27 'docker provider (gated on a reachable daemon)',
28 () => {
29 it('creates a container, runs exec, fs round-trip, snapshot + destroy', async () => {
30 const provider = dockerSandbox({ image: IMAGE })
31 let sbx: SandboxHandle | undefined
32 let snapshotTag: string | undefined
33 try {
34 sbx = await provider.create({})
35
36 const echo = await sbx.process.exec('echo hello-docker')
37 expect(echo.stdout.trim()).toBe('hello-docker')
38 expect(echo.exitCode).toBe(0)
39
40 await sbx.fs.write('/workspace/note.txt', 'inside the container')
41 expect(await sbx.fs.exists('/workspace/note.txt')).toBe(true)
42 expect(await sbx.fs.read('/workspace/note.txt')).toBe(
43 'inside the container',
44 )
45
46 const bytes = new Uint8Array([0, 1, 2, 250])
47 await sbx.fs.write('/workspace/bin', bytes)
48 expect(Array.from(await sbx.fs.readBytes('/workspace/bin'))).toEqual([
49 0, 1, 2, 250,
50 ])
51
52 // Larger than one `sh -c` argv (Linux MAX_ARG_STRLEN is 128 KiB).
53 const large = Buffer.alloc(180_000, 0x62)
54 await sbx.fs.write('/workspace/large.bin', large)
55 expect(await sbx.fs.readBytes('/workspace/large.bin')).toEqual(
56 new Uint8Array(large),
57 )
58
59 const snap = await sbx.snapshot?.('test')
60 expect(snap?.id).toMatch(/tanstack-ai-sandbox-snapshot/)
61 snapshotTag = snap?.id
62
63 // The returned id is a template string composed BEFORE the commit runs,
64 // so asserting its shape proves nothing about whether a snapshot exists
65 // — delete the `container.commit()` call and a shape assertion still
66 // passes. Inspect the image instead: this is the package's only snapshot
67 // coverage, so it has to fail when no image was actually committed.
68 const inspected = await docker.getImage(snapshotTag!).inspect()
69 expect(inspected.RepoTags).toContain(snapshotTag)
70 // ...and the snapshot really captured this container's filesystem.
71 expect(inspected.Id).not.toBe('')
72 } finally {
73 if (snapshotTag !== undefined) {
74 await docker
75 .getImage(snapshotTag)
76 .remove({ force: true })
77 .catch(() => {
78 // Best effort: never mask the real assertion failure.
79 })
80 }
81 await sbx?.destroy()
82 }
83 }, 120_000)
84
85 it('kill() actually terminates the container-side process, not just the client stream', async () => {
86 const provider = dockerSandbox({ image: IMAGE })
87 let sbx: SandboxHandle | undefined
88 try {
89 sbx = await provider.create({})
90 const handle = sbx
91
92 /** The probe process's rows in the container's own process table. */
93 const probeRows = async (): Promise<string> =>
94 (
95 await handle.process.exec(
96 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
97 )
98 ).stdout.trim()
99
100 const proc = await handle.process.spawn(
101 `echo up; sleep ${KILL_PROBE_SLEEP}`,
102 )
103 for await (const chunk of proc.stdout) {
104 if (chunk.includes('up')) break
105 }
106
107 // Guard the guard: if the probe were never visible here, its absence
108 // after kill() would prove nothing.
109 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
110
111 await proc.kill()
112
113 // `killableProcesses: true` claims the process is FORCIBLY terminated,
114 // so ask the container — do not take the handle's word for it. Reading
115 // `capabilities.killableProcesses` here would only re-read a module
116 // constant, and passed even when kill() was a no-op that left this
117 // `sleep` running until the container was removed.
118 let survivors = await probeRows()
119 for (let i = 0; i < 20 && survivors !== ''; i += 1) {
120 await new Promise((resolve) => setTimeout(resolve, 250))
121 survivors = await probeRows()
122 }
123 expect(survivors).toBe('')
124 } finally {
125 await sbx?.destroy()
126 }
127 }, 120_000)
128
129 // Three properties that together are what makes `killableProcesses: true`
130 // more than an assertion. Each fails on its own if the corresponding half of
131 // the fix is reverted.
132 it('kill() awaits the in-container kill instead of firing it and forgetting', async () => {
133 const provider = dockerSandbox({ image: IMAGE })
134 let sbx: SandboxHandle | undefined
135 try {
136 sbx = await provider.create({})
137 const handle = sbx
138 const probeRows = async (): Promise<string> =>
139 (
140 await handle.process.exec(
141 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
142 )
143 ).stdout.trim()
144
145 const proc = await handle.process.spawn(
146 `echo up; sleep ${KILL_PROBE_SLEEP}`,
147 )
148 for await (const chunk of proc.stdout) {
149 if (chunk.includes('up')) break
150 }
151 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
152
153 const started = Date.now()
154 await proc.kill()
155 const elapsed = Date.now() - started
156
157 // THE DISCRIMINATOR IS THE CLOCK, not the process table. The kill shell
158 // signals, then sleeps `KILL_ESCALATION_DELAY_MS` (200ms) before
159 // escalating to SIGKILL and verifying with `kill -0`, so a `kill()` that
160 // genuinely awaits it CANNOT resolve faster than that grace period. One
161 // that fires and forgets (`void this.exec(...)` then
162 // `Promise.resolve()`) resolves in ~1ms without a single round trip.
163 //
164 // Asserting on the process table instead does NOT distinguish the two:
165 // measured, a fire-and-forget kill still beats the `ps` probe, because
166 // the probe needs its own `container.exec()` + `exec.start()` round
167 // trips (~5ms each) and the kill was dispatched first. The sibling test
168 // above already covers "it dies"; this one covers "we waited for it".
169 expect(elapsed).toBeGreaterThanOrEqual(150)
170
171 // …and having waited, the ordering `await proc.kill(); <next step>`
172 // really does hold: no polling, no retry loop, gone right now.
173 expect(await probeRows()).toBe('')
174 } finally {
175 await sbx?.destroy()
176 }
177 }, 120_000)
178
179 it('treats a cleanly-exited process as nothing to kill: no wait, no warning', async () => {
180 const warnings: Array<string> = []
181 const provider = dockerSandbox({
182 image: IMAGE,
183 logger: {
184 warn: (message) => {
185 warnings.push(message)
186 },
187 },
188 })
189 let sbx: SandboxHandle | undefined
190 try {
191 sbx = await provider.create({})
192
193 // `journal-reader`'s `followJournal` calls `proc.kill()` from a `finally`
194 // on EVERY exit path, so this — a container-side command that ended on
195 // its own, then a kill — is the NORMAL teardown, not an edge case.
196 const proc = await sbx.process.spawn('echo done')
197 for await (const _chunk of proc.stdout) {
198 // drain to EOF, so the wrapper has exited and its pid file is gone
199 }
200 expect(await proc.wait()).toBe(0)
201 // Let the fire-and-forget `rm -f` land, so the kill below really does
202 // face an absent pid file.
203 await new Promise((resolve) => setTimeout(resolve, 500))
204
205 const started = Date.now()
206 await proc.kill()
207 const elapsed = Date.now() - started
208
209 // BOTH harms, because either one regresses on its own.
210 //
211 // THE CLOCK. The pid read is a bounded retry — `PID_WAIT_TIMEOUT_MS`
212 // (2s) at `PID_WAIT_INTERVAL_MS` — and it exists for the fast-abort race
213 // covered below, so it must stay. But "absent" also means "the owner
214 // exited and we removed it", and inferring the first from the second
215 // made every ordinary teardown block ~2s inside `await proc.kill()`.
216 // Measured at 2083ms before the `exited` state; a round trip that skips
217 // the loop is tens of milliseconds. 1s separates them with room to
218 // spare on a loaded machine.
219 expect(elapsed).toBeLessThan(1000)
220
221 // THE CHANNEL. That warning is the only in-band evidence for
222 // `killableProcesses: true` — the kill shell is built never to fail, so
223 // its exit code carries nothing. A channel that fires on every clean
224 // teardown cannot support the claim, so silence here is load-bearing,
225 // not cosmetic.
226 expect(warnings).toEqual([])
227 } finally {
228 await sbx?.destroy()
229 }
230 }, 120_000)
231
232 it('reports a kill it could not perform instead of resolving as if it worked', async () => {
233 const warnings: Array<{
234 message: string
235 meta?: Record<string, unknown>
236 }> = []
237 const provider = dockerSandbox({
238 image: IMAGE,
239 logger: {
240 warn: (message, meta) => {
241 warnings.push({ message, meta })
242 },
243 },
244 })
245 let sbx: SandboxHandle | undefined
246 try {
247 sbx = await provider.create({})
248 const handle = sbx
249 const probeRows = async (): Promise<string> =>
250 (
251 await handle.process.exec(
252 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
253 )
254 ).stdout.trim()
255 // Drive the unperformable case: delete the pid file out from under a
256 // STILL-RUNNING spawn, which is exactly the shape of "this process never
257 // recorded a pid" (its exec never started, or it died before its
258 // `echo $$`). The kill shell then waits, finds nothing, and sends NO
259 // signal — and the process really does survive, which is what makes this
260 // a genuine refusal rather than a modelled one.
261 //
262 // THAT "STILL-RUNNING" IS THE WHOLE DISTINCTION, and the reason this test
263 // keeps its shape after the `exited` fix. An absent pid file means two
264 // different things: "not written yet / never written" (here — nothing can
265 // be signalled, so warn) and "the owner exited and we cleaned up" (the
266 // sibling test above — nothing NEEDS signalling, so stay silent). The
267 // handle no longer infers either from the file alone; it tracks which
268 // happened. This case is the first, so the warning is earned. The
269 // assertions below prove that from the container's own process table
270 // rather than trusting the shape of the setup.
271 //
272 // Asserting only that `kill()` RESOLVED would pass against a kill that
273 // did nothing at all — the shell is built never to fail, so its exit
274 // code carries no information by design. The logger is the only channel
275 // that can carry it, which is why the assertion is on the logger.
276 const proc = await handle.process.spawn(
277 `echo up; sleep ${KILL_PROBE_SLEEP}`,
278 )
279 for await (const chunk of proc.stdout) {
280 if (chunk.includes('up')) break
281 }
282 // Guard the guard: there WAS a pid file, so its absence below is our
283 // doing and not a mechanism that never wrote one.
284 const listed = await handle.process.exec(
285 'ls -1 /tmp/.tanstack-sandbox-spawn-*.pid',
286 )
287 expect(listed.stdout.trim()).not.toBe('')
288 await handle.process.exec('rm -f /tmp/.tanstack-sandbox-spawn-*.pid')
289 // Guard the guard, part two: the probe is alive going in, so its presence
290 // afterwards is a survival and not a process that was never there.
291 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
292
293 await proc.kill()
294
295 // The kill could not be performed, and that fact is VISIBLE.
296 expect(
297 warnings.some((w) => /no pid was recorded/.test(w.message)),
298 ).toBe(true)
299
300 // …and the refusal it reports is REAL. Without this the test would pass
301 // against a handle that warned about a process it had in fact killed —
302 // i.e. against the cried-wolf channel the sibling test forbids. The
303 // container's own `ps` is the arbiter: the probe is still running,
304 // because no signal was ever sent to it.
305 expect(await probeRows()).toContain(KILL_PROBE_SLEEP)
306 } finally {
307 // The probe outlives the un-performable kill by construction; removing
308 // the container is what actually ends it.
309 await sbx?.destroy()
310 }
311 }, 120_000)
312
313 it('kills a process that is killed before its pid file can exist (the fast-abort race)', async () => {
314 const provider = dockerSandbox({ image: IMAGE })
315 let sbx: SandboxHandle | undefined
316 try {
317 sbx = await provider.create({})
318 const handle = sbx
319 const probeRows = async (): Promise<string> =>
320 (
321 await handle.process.exec(
322 `ps | grep ${KILL_PROBE_GREP} | grep -v grep || true`,
323 )
324 ).stdout.trim()
325
326 // NO waiting for output this time — that is the whole test.
327 // `container.exec()`/`exec.start()` resolve once the DAEMON accepts the
328 // exec; the container-side shell has not necessarily run its `echo $$`
329 // yet. `journal-reader` kills its follower this promptly on abort.
330 //
331 // With a bare `cat` on the pid file, `$pid` is empty here, `[ -n "$pid" ]`
332 // is false, NO signal is sent, and `stream.destroy()` only detaches the
333 // client — the exact pre-fix orphan. The bounded retry in
334 // `killRecordedPidCommand` is what closes it.
335 const proc = await handle.process.spawn(
336 `echo up; sleep ${KILL_PROBE_SLEEP}`,
337 )
338 await proc.kill()
339
340 // BusyBox `ps` prints argv, so a survivor is attributable to this test
341 // by its unique sleep duration. Poll until the probe is EMPTY, then
342 // assert once — do not assert inside the loop. `kill()` resolves when the
343 // daemon accepted the signal, not when the container-side process has
344 // finished dying, so a per-poll assertion turns a few milliseconds of
345 // teardown into a failure. The bound is the real assertion: the orphan
346 // this test exists to catch (`stream.destroy()` detaching only the
347 // client) leaves `sleep` running indefinitely, so it never empties and
348 // still fails here.
349 let rows = await probeRows()
350 for (let i = 0; i < 12 && rows !== ''; i += 1) {
351 await new Promise((resolve) => setTimeout(resolve, 250))
352 rows = await probeRows()
353 }
354 expect(rows).toBe('')
355 } finally {
356 await sbx?.destroy()
357 }
358 }, 120_000)
359
360 it('does not leak a pid file per spawn / per signal-bearing exec', async () => {
361 const provider = dockerSandbox({ image: IMAGE })
362 let sbx: SandboxHandle | undefined
363 try {
364 sbx = await provider.create({})
365 const handle = sbx
366 /** Every pid file the wrapper mechanism could have left in /tmp. */
367 const pidFiles = async (): Promise<string> =>
368 (
369 await handle.process.exec(
370 'ls -1 /tmp/.tanstack-sandbox-*.pid 2>/dev/null || true',
371 )
372 ).stdout.trim()
373
374 // `rm -f` used to run ONLY on the kill path, so a normally-exiting
375 // process left its file behind for the life of the container. The
376 // dot-prefix means `journalListCommand`'s `ls -1` never surfaced them,
377 // making the accumulation silent and unbounded.
378 const proc = await handle.process.spawn('echo done')
379 for await (const _chunk of proc.stdout) {
380 // drain to EOF — the cleanup hangs off the stream's `end`
381 }
382 expect(await proc.wait()).toBe(0)
383
384 // A signal-bearing exec writes one too (a plain fs-backing exec does
385 // not, and must not start paying for a kill path it never uses).
386 const ac = new AbortController()
387 const ran = await handle.process.exec('echo ok', { signal: ac.signal })
388 expect(ran.stdout.trim()).toBe('ok')
389
390 // The removals are dispatched fire-and-forget from stream completion,
391 // so allow them a beat to land before asserting.
392 let leftovers = await pidFiles()
393 for (let i = 0; i < 20 && leftovers !== ''; i += 1) {
394 await new Promise((resolve) => setTimeout(resolve, 250))
395 leftovers = await pidFiles()
396 }
397 expect(leftovers).toBe('')
398 } finally {
399 await sbx?.destroy()
400 }
401 }, 120_000)
402
403 it('resumes a running container by id and streams a spawned process', async () => {
404 const provider = dockerSandbox({ image: IMAGE })
405 let sbx: SandboxHandle | undefined
406 try {
407 sbx = await provider.create({})
408 await sbx.fs.write('/workspace/keep.txt', 'persisted')
409
410 const resumed = await provider.resume({ id: sbx.id })
411 expect(resumed?.id).toBe(sbx.id)
412 expect(await resumed!.fs.read('/workspace/keep.txt')).toBe('persisted')
413
414 const proc = await resumed!.process.spawn('echo streamed-line')
415 let out = ''
416 for await (const chunk of proc.stdout) out += chunk
417 expect(out).toContain('streamed-line')
418 expect(await proc.wait()).toBe(0)
419 } finally {
420 await sbx?.destroy()
421 }
422 }, 120_000)
423
424 it('ensure() bootstraps a workspace (setup command runs)', async () => {
425 const provider = dockerSandbox({ image: IMAGE })
426 const def = defineSandbox({
427 id: 'docker-ensure',
428 provider,
429 workspace: defineWorkspace({
430 source: { type: 'none' },
431 setup: ['echo bootstrapped > /workspace/setup-marker'],
432 }),
433 })
434 const ctx = { threadId: 'docker-t', runId: 'r1' }
435 try {
436 const sbx = await def.ensure(ctx)
437 expect((await sbx.fs.read('/workspace/setup-marker')).trim()).toBe(
438 'bootstrapped',
439 )
440 } finally {
441 await def.destroy(ctx)
442 }
443 }, 120_000)
444
445 it('reassembles a multi-byte character split across spawn stdout chunk boundaries', async () => {
446 const provider = dockerSandbox({ image: IMAGE })
447 let sbx: SandboxHandle | undefined
448 try {
449 sbx = await provider.create({})
450 // '€' = 0xE2 0x82 0xAC (octal \342 \202 \254). Emit the first byte,
451 // sleep, then the remaining bytes — forcing the container's exec
452 // stream to deliver them as separate chunks, reproducing a
453 // multi-byte character split across a chunk boundary.
454 const proc = await sbx.process.spawn(
455 `printf '\\342'; sleep 0.3; printf '\\202\\254lo'`,
456 )
457 let out = ''
458 for await (const chunk of proc.stdout) out += chunk
459 await proc.wait()
460 expect(out).toBe('€lo')
461 expect(out).not.toContain('�')
462 } finally {
463 await sbx?.destroy()
464 }
465 }, 120_000)
466
467 it('flushes a genuinely truncated trailing UTF-8 sequence at end of stream (as U+FFFD, not silently dropped)', async () => {
468 const provider = dockerSandbox({ image: IMAGE })
469 let sbx: SandboxHandle | undefined
470 try {
471 sbx = await provider.create({})
472 // Only the first byte of a 3-byte sequence is ever written.
473 const proc = await sbx.process.spawn(`printf '\\342'`)
474 let out = ''
475 for await (const chunk of proc.stdout) out += chunk
476 await proc.wait()
477 // Decision: flush at end-of-stream surfaces the truncated sequence
478 // as the replacement character, rather than silently dropping it.
479 expect(out).toBe('�')
480 } finally {
481 await sbx?.destroy()
482 }
483 }, 120_000)
484 },
485)