Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { createBootstrapShell } from '../src/shell'
3import type { ExecResult, ProcessOptions, SpawnHandle } from '../src/contracts'
4
5/**
6 * A push-based async-iterable for driving fake stdout chunks in tests.
7 *
8 * Call `push(chunk)` to enqueue a chunk that will be yielded to the consumer.
9 * Call `close()` to signal end-of-stream.
10 */
11function createPushIterable(): {
12 iterable: AsyncIterable<string>
13 push: (chunk: string) => void
14 close: () => void
15} {
16 const queue: Array<string> = []
17 const waiters: Array<(result: IteratorResult<string>) => void> = []
18 let done = false
19
20 function push(chunk: string): void {
21 const waiter = waiters.shift()
22 if (waiter !== undefined) {
23 waiter({ value: chunk, done: false })
24 } else {
25 queue.push(chunk)
26 }
27 }
28
29 function close(): void {
30 done = true
31 for (const waiter of waiters) {
32 waiter({ value: undefined as unknown as string, done: true })
33 }
34 waiters.length = 0
35 }
36
37 const iterable: AsyncIterable<string> = {
38 [Symbol.asyncIterator](): AsyncIterator<string> {
39 return {
40 next(): Promise<IteratorResult<string>> {
41 const queued = queue.shift()
42 if (queued !== undefined) {
43 return Promise.resolve({ value: queued, done: false })
44 }
45 if (done) {
46 return Promise.resolve({
47 value: undefined as unknown as string,
48 done: true,
49 })
50 }
51 return new Promise<IteratorResult<string>>((resolve) => {
52 waiters.push(resolve)
53 })
54 },
55 }
56 },
57 }
58
59 return { iterable, push, close }
60}
61
62/**
63 * Build a fake {@link SpawnHandle} that:
64 * - records stdin writes
65 * - exposes a `push` helper to inject stdout chunks
66 * - records `kill` calls
67 * - counts how many times `spawn` was invoked (via the outer counter)
68 */
69interface FakeHandle {
70 /** Mutable counters — read them after the fact to observe what happened. */
71 counts: { spawn: number; kill: number; end: number }
72 handle: Parameters<typeof createBootstrapShell>[0]
73 stdinWrites: Array<string>
74 pushStdout: (chunk: string) => void
75 closeStdout: () => void
76}
77
78function makeFakeHandle(
79 options: { closeStdoutOnKill?: boolean; stdoutError?: Error } = {},
80): FakeHandle {
81 const counts = { spawn: 0, kill: 0, end: 0 }
82 const stdinWrites: Array<string> = []
83
84 const {
85 iterable,
86 push: pushStdout,
87 close: closeStdout,
88 } = createPushIterable()
89
90 // A stdout async-iterable that throws instead of yielding — a transport reset
91 // or provider stream error mid-drain.
92 const stdoutError = options.stdoutError
93 const stdout: AsyncIterable<string> =
94 stdoutError === undefined
95 ? iterable
96 : {
97 [Symbol.asyncIterator](): AsyncIterator<string> {
98 return { next: () => Promise.reject(stdoutError) }
99 },
100 }
101
102 const spawnHandle: SpawnHandle = {
103 pid: 1,
104 stdout,
105 stderr: (async function* empty() {})(),
106 stdin: {
107 write: (data: string) => {
108 stdinWrites.push(data)
109 return Promise.resolve()
110 },
111 end: () => {
112 counts.end += 1
113 return Promise.resolve()
114 },
115 },
116 wait: () => Promise.resolve(0),
117 kill: () => {
118 counts.kill += 1
119 // Mirror real providers (e.g. docker exec): the stdout async-iterable
120 // only terminates when the underlying stream is destroyed by kill().
121 // Nothing else closes it. The bootstrap shell's dispose() must rely on
122 // this to unblock its stdout drain loop, or it hangs forever.
123 if (options.closeStdoutOnKill === true) closeStdout()
124 return Promise.resolve()
125 },
126 }
127
128 const handle: Parameters<typeof createBootstrapShell>[0] = {
129 id: 'fake',
130 provider: 'fake',
131 capabilities: {
132 fs: true,
133 exec: true,
134 env: true,
135 ports: false,
136 backgroundProcesses: true,
137 writableStdin: true,
138 killableProcesses: true,
139 snapshots: false,
140 networkPolicy: false,
141 durableFilesystem: false,
142 fork: false,
143 },
144 fs: {} as Parameters<typeof createBootstrapShell>[0]['fs'],
145 git: {} as Parameters<typeof createBootstrapShell>[0]['git'],
146 process: {
147 exec: () => Promise.reject(new Error('exec not used in shell tests')),
148 spawn: (_cmd, _opts) => {
149 counts.spawn += 1
150 return Promise.resolve(spawnHandle)
151 },
152 },
153 ports: {
154 connect: () => Promise.reject(new Error('ports not used in shell tests')),
155 },
156 env: { set: () => Promise.resolve() },
157 destroy: () => Promise.resolve(),
158 }
159
160 return { counts, handle, stdinWrites, pushStdout, closeStdout }
161}
162
163/** A scripted exec response for one `run()` of the exec-backed shell. */
164interface ExecResponse {
165 cmdOut: string
166 rc: number
167 newCwd: string
168 exports: Array<string>
169}
170
171interface ExecFakeHandle {
172 handle: Parameters<typeof createBootstrapShell>[0]
173 calls: Array<{
174 cwd: string | undefined
175 env: Record<string, string> | undefined
176 }>
177 spawnCount: number
178}
179
180/**
181 * Build a fake handle with `writableStdin: false`, so `createBootstrapShell`
182 * takes the exec-backed path. Its `process.exec` returns crafted stdout matching
183 * the exec shell's marker protocol; `process.spawn` MUST never be called.
184 */
185function makeExecFakeHandle(responses: Array<ExecResponse>): ExecFakeHandle {
186 const calls: ExecFakeHandle['calls'] = []
187 let spawnCount = 0
188 let i = 0
189
190 const handle: Parameters<typeof createBootstrapShell>[0] = {
191 id: 'fake-exec',
192 provider: 'fake',
193 capabilities: {
194 fs: true,
195 exec: true,
196 env: true,
197 ports: false,
198 backgroundProcesses: true,
199 writableStdin: false,
200 killableProcesses: false,
201 snapshots: false,
202 networkPolicy: false,
203 durableFilesystem: false,
204 fork: false,
205 },
206 fs: {} as Parameters<typeof createBootstrapShell>[0]['fs'],
207 git: {} as Parameters<typeof createBootstrapShell>[0]['git'],
208 process: {
209 exec: (script: string, opts?: ProcessOptions): Promise<ExecResult> => {
210 calls.push({ cwd: opts?.cwd, env: opts?.env })
211 // The shell embeds its sentinel id in the script; echo it back.
212 const sentinel = /__BSSH_\d+__/.exec(script)?.[0] ?? '__BSSH_?__'
213 const resp = responses[i] ?? {
214 cmdOut: '',
215 rc: 0,
216 newCwd: opts?.cwd ?? '/',
217 exports: [],
218 }
219 i += 1
220 const stdout =
221 [
222 resp.cmdOut,
223 '', // the leading \n the shell prints before the sentinel
224 `${sentinel} ${resp.rc}`,
225 `${sentinel}_CWD`,
226 resp.newCwd,
227 `${sentinel}_ENV`,
228 ...resp.exports,
229 ].join('\n') + '\n'
230 return Promise.resolve({ stdout, stderr: '', exitCode: 0 })
231 },
232 spawn: () => {
233 spawnCount += 1
234 return Promise.reject(
235 new Error('spawn must not run for writableStdin:false'),
236 )
237 },
238 },
239 ports: {
240 connect: () => Promise.reject(new Error('ports not used in shell tests')),
241 },
242 env: { set: () => Promise.resolve() },
243 destroy: () => Promise.resolve(),
244 }
245
246 return {
247 handle,
248 calls,
249 get spawnCount() {
250 return spawnCount
251 },
252 }
253}
254
255describe('createBootstrapShell', () => {
256 it('reuses a single spawn for multiple run() calls', async () => {
257 const fake = makeFakeHandle()
258
259 const shellPromise = createBootstrapShell(fake.handle)
260
261 // The shell spawns `sh` synchronously as part of createBootstrapShell.
262 // Push the responses for two run() calls in sequence.
263
264 // We use an orchestrating async function so we can interleave push/resolve.
265 const result = await new Promise<{
266 r1: { exitCode: number; stdout: string }
267 r2: { exitCode: number; stdout: string }
268 }>(async (resolve) => {
269 const shell = await shellPromise
270
271 // Queue both run() calls but don't await them yet.
272 const p1 = shell.run('echo hello')
273 // Simulate stdout response for the first command.
274 // The shell writes: `echo hello; printf "\n__BSSH_0__ $?\n"\n`
275 // We emit: "hello\n__BSSH_0__ 0\n"
276 fake.pushStdout('hello\n')
277 fake.pushStdout('__BSSH_0__ 0\n')
278
279 const r1 = await p1
280
281 const p2 = shell.run('false')
282 // `false` exits with code 1.
283 fake.pushStdout('__BSSH_1__ 1\n')
284
285 const r2 = await p2
286
287 fake.closeStdout()
288 await shell.dispose()
289
290 resolve({ r1, r2 })
291 })
292
293 // Only ONE spawn call for both run() invocations.
294 expect(fake.counts.spawn).toBe(1)
295 expect(result.r1.exitCode).toBe(0)
296 expect(result.r1.stdout).toBe('hello')
297 expect(result.r2.exitCode).toBe(1)
298 })
299
300 it('returns the correct exit code from the sentinel', async () => {
301 const fake = makeFakeHandle()
302
303 const shellPromise = createBootstrapShell(fake.handle)
304
305 const r = await new Promise<{ exitCode: number; stdout: string }>(
306 async (resolve) => {
307 const shell = await shellPromise
308 const p = shell.run('exit 42 || true; echo done')
309 // Emit multi-line output, then sentinel with code 42.
310 fake.pushStdout('line1\n')
311 fake.pushStdout('done\n')
312 fake.pushStdout('__BSSH_0__ 42\n')
313 const r = await p
314 fake.closeStdout()
315 await shell.dispose()
316 resolve(r)
317 },
318 )
319
320 expect(r.exitCode).toBe(42)
321 expect(r.stdout).toBe('line1\ndone')
322 })
323
324 it('dispose() calls stdin.end() and kill()', async () => {
325 const fake = makeFakeHandle()
326 const shellPromise = createBootstrapShell(fake.handle)
327
328 await new Promise<void>(async (resolve) => {
329 const shell = await shellPromise
330
331 // Run one command so the shell is active.
332 const p = shell.run('echo hi')
333 fake.pushStdout('hi\n')
334 fake.pushStdout('__BSSH_0__ 0\n')
335 await p
336
337 fake.closeStdout()
338 await shell.dispose()
339 resolve()
340 })
341
342 expect(fake.counts.end).toBe(1)
343 expect(fake.counts.kill).toBe(1)
344 })
345
346 it('dispose() completes when stdout only closes as a result of kill()', async () => {
347 /*
348 * Regression for the docker-exec hang: the spawned stdout async-iterable
349 * never ends on its own — only when the process is killed (its underlying
350 * stream destroyed). dispose() must drive that close itself and not block
351 * forever on the stdout drain loop. The test deliberately never calls
352 * closeStdout(); the only thing that ends the stream is dispose()'s kill().
353 */
354 const fake = makeFakeHandle({ closeStdoutOnKill: true })
355 const shell = await createBootstrapShell(fake.handle)
356
357 const p = shell.run('echo hi')
358 fake.pushStdout('hi\n')
359 fake.pushStdout('__BSSH_0__ 0\n')
360 await p
361
362 // If dispose() blocks on the never-self-closing stdout iterator, this race
363 // rejects; the fix lets kill() close stdout so the drain loop completes.
364 await Promise.race([
365 shell.dispose(),
366 new Promise<never>((_, reject) =>
367 setTimeout(() => reject(new Error('dispose() hung')), 2000),
368 ),
369 ])
370
371 expect(fake.counts.kill).toBe(1)
372 expect(fake.counts.end).toBe(1)
373 })
374
375 it('rejects promptly — without spinning — when stdout ends before the sentinel', async () => {
376 /*
377 * Regression for the bootstrap OOM. `sh` can exit before it ever prints the
378 * sentinel (a missing binary, an OOM kill, the provider reaping the sandbox
379 * mid-bootstrap). The old loop's only exit was the sentinel, and `nextLine()`
380 * answered `''` forever once the stream was done, so `run()` became a hot
381 * microtask loop pushing empty strings into its output buffer until the host
382 * process died of memory exhaustion.
383 *
384 * BOTH assertions matter. "It rejects" alone would also pass an
385 * implementation that spins for a while first, so the reject is raced
386 * against a REAL timer (a microtask hot loop starves the macrotask queue, so
387 * the watchdog can only fire if the loop actually yields), and the heap is
388 * checked to prove the output buffer did not grow.
389 */
390 const fake = makeFakeHandle()
391 const shell = await createBootstrapShell(fake.handle)
392 // The shell is dead: stdout ends with nothing on it.
393 fake.closeStdout()
394
395 const heapBefore = process.memoryUsage().heapUsed
396 let watchdog: ReturnType<typeof setTimeout> | undefined
397 const timedOut = new Promise<never>((_, reject) => {
398 watchdog = setTimeout(
399 () => reject(new Error('run() did not settle within 1s')),
400 1000,
401 )
402 })
403 try {
404 await expect(
405 Promise.race([shell.run('echo hi'), timedOut]),
406 ).rejects.toThrow(/exited before the sentinel/)
407 } finally {
408 clearTimeout(watchdog)
409 }
410
411 const grownMb = (process.memoryUsage().heapUsed - heapBefore) / 1024 / 1024
412 expect(grownMb).toBeLessThan(50)
413 })
414
415 it('rejects when the stdout iterator throws mid-drain instead of parking waiters', async () => {
416 /*
417 * `drainStdout()` is started but not awaited. A throw while iterating stdout
418 * used to skip the `streamDone = true` / waiter-flush entirely, so every
419 * `run()` parked on a promise nobody would ever resolve (and the rejection
420 * was unhandled). The drain must record the error and unblock waiters.
421 */
422 const boom = new Error('stdout transport reset')
423 const fake = makeFakeHandle({ stdoutError: boom })
424 const shell = await createBootstrapShell(fake.handle)
425
426 let watchdog: ReturnType<typeof setTimeout> | undefined
427 const timedOut = new Promise<never>((_, reject) => {
428 watchdog = setTimeout(
429 () => reject(new Error('run() never settled — waiter parked forever')),
430 1000,
431 )
432 })
433 try {
434 const settled = await Promise.race([
435 shell.run('echo hi').then(
436 () => undefined,
437 (error: unknown) => error,
438 ),
439 timedOut,
440 ])
441 expect(settled).toBeInstanceOf(Error)
442 expect(String(settled)).toMatch(/exited before the sentinel/)
443 // The original stream failure is preserved as the cause, so the operator
444 // can tell a transport reset from a clean early exit.
445 expect(settled instanceof Error ? settled.cause : undefined).toBe(boom)
446 } finally {
447 clearTimeout(watchdog)
448 }
449 })
450
451 it('rejects with a deadline when the shell stays alive but never answers', async () => {
452 // Belt-and-braces: stdout neither ends nor produces a sentinel.
453 const fake = makeFakeHandle()
454 const shell = await createBootstrapShell(fake.handle, {
455 commandTimeoutMs: 25,
456 })
457 await expect(shell.run('sleep forever')).rejects.toThrow(/timed out/)
458 })
459
460 it('forkState() returns the current cwd and parsed exported env vars', async () => {
461 const fake = makeFakeHandle()
462 const shellPromise = createBootstrapShell(fake.handle)
463
464 const result = await new Promise<{
465 cwd: string
466 env: Record<string, string>
467 }>(async (resolve) => {
468 const shell = await shellPromise
469
470 const p = shell.forkState()
471
472 // forkState runs `pwd` first, then `export -p`.
473 // Sentinel for pwd (counter 0): __BSSH_0__ 0
474 fake.pushStdout('/home/sandbox\n')
475 fake.pushStdout('__BSSH_0__ 0\n')
476
477 // Sentinel for export -p (counter 1): __BSSH_1__ 0
478 // Include declare -x form, export form, and one unparseable junk line.
479 fake.pushStdout('declare -x FOO="bar"\n')
480 fake.pushStdout('export BAZ="qux"\n')
481 fake.pushStdout('THIS LINE IS JUNK\n')
482 fake.pushStdout('__BSSH_1__ 0\n')
483
484 const r = await p
485 fake.closeStdout()
486 await shell.dispose()
487 resolve(r)
488 })
489
490 expect(result.cwd).toBe('/home/sandbox')
491 expect(result.env['FOO']).toBe('bar')
492 expect(result.env['BAZ']).toBe('qux')
493 // The junk line must be silently skipped — no extra keys.
494 expect(Object.keys(result.env)).toHaveLength(2)
495 })
496
497 it('uses the exec-backed shell (no spawn) when writableStdin is false', async () => {
498 const fake = makeExecFakeHandle([
499 { cmdOut: 'installed', rc: 0, newCwd: '/work', exports: [] },
500 ])
501 const shell = await createBootstrapShell(fake.handle)
502 const r = await shell.run('npm i -g claude')
503
504 expect(fake.spawnCount).toBe(0) // never spawns a persistent shell
505 expect(fake.calls).toHaveLength(1)
506 expect(r.exitCode).toBe(0)
507 expect(r.stdout).toContain('installed')
508 })
509
510 it('exec-backed run() reports the command exit code (not the wrapper exit)', async () => {
511 const fake = makeExecFakeHandle([
512 { cmdOut: '', rc: 7, newCwd: '/', exports: [] },
513 ])
514 const shell = await createBootstrapShell(fake.handle)
515 const r = await shell.run('exit 7')
516 expect(r.exitCode).toBe(7)
517 })
518
519 it('exec-backed shell threads cwd + env across run() calls', async () => {
520 const fake = makeExecFakeHandle([
521 { cmdOut: '', rc: 0, newCwd: '/app', exports: ['export FOO="bar"'] },
522 { cmdOut: '', rc: 0, newCwd: '/app', exports: ['export FOO="bar"'] },
523 ])
524 const shell = await createBootstrapShell(fake.handle, { cwd: '/workspace' })
525
526 await shell.run('cd /app && export FOO=bar')
527 await shell.run('echo "$FOO"')
528
529 // First exec starts in the provided cwd with no accumulated env…
530 expect(fake.calls[0]?.cwd).toBe('/workspace')
531 expect(fake.calls[0]?.env).toEqual({})
532 // …the second inherits the cwd + exported var captured from the first.
533 expect(fake.calls[1]?.cwd).toBe('/app')
534 expect(fake.calls[1]?.env).toEqual({ FOO: 'bar' })
535 })
536
537 it('exec-backed forkState() returns the threaded cwd + env', async () => {
538 const fake = makeExecFakeHandle([
539 { cmdOut: '', rc: 0, newCwd: '/app', exports: ['export TOKEN="abc"'] },
540 ])
541 const shell = await createBootstrapShell(fake.handle, { cwd: '/workspace' })
542 await shell.run('cd /app && export TOKEN=abc')
543
544 const state = await shell.forkState()
545 expect(state.cwd).toBe('/app')
546 expect(state.env).toEqual({ TOKEN: 'abc' })
547 })
548
549 it('captures stdout lines from run() correctly across chunk boundaries', async () => {
550 const fake = makeFakeHandle()
551
552 const shellPromise = createBootstrapShell(fake.handle)
553
554 const r = await new Promise<{ exitCode: number; stdout: string }>(
555 async (resolve) => {
556 const shell = await shellPromise
557 const p = shell.run('printf "a\\nb\\nc"')
558 // Push chunks that split across line boundaries.
559 fake.pushStdout('a\nb')
560 fake.pushStdout('\nc\n')
561 fake.pushStdout('__BSSH_0__ 0\n')
562 const r = await p
563 fake.closeStdout()
564 await shell.dispose()
565 resolve(r)
566 },
567 )
568
569 expect(r.exitCode).toBe(0)
570 // Lines before the sentinel: 'a', 'b', 'c', '' -> joined with \n.
571 // The empty string comes from the trailing newline before the sentinel.
572 // What matters is that 'a', 'b', 'c' are present.
573 expect(r.stdout).toContain('a')
574 expect(r.stdout).toContain('b')
575 expect(r.stdout).toContain('c')
576 })
577})