Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { CommandExitError } from 'e2b'
3import {
4 E2BHandle,
5 E2B_CAPS,
6 TRAFFIC_TOKEN_HEADER,
7 groupLeaderCommand,
8 snapshotName,
9} from '../src/handle'
10import type { CommandHandle, Sandbox } from 'e2b'
11
12/** A fake background command whose output and exit are driven by the test. */
13interface FakeCommand {
14 handle: CommandHandle
15 kill: ReturnType<typeof vi.fn>
16 sendStdin: ReturnType<typeof vi.fn>
17 closeStdin: ReturnType<typeof vi.fn>
18 emitStdout: (text: string) => void
19 emitStderr: (text: string) => void
20 exit: (code: number) => void
21}
22
23function fakeCommand(
24 opts: {
25 pid?: number
26 onStdout?: (d: string) => void
27 onStderr?: (d: string) => void
28 } = {},
29): FakeCommand {
30 let stdout = ''
31 let stderr = ''
32 let settle!: (code: number) => void
33 const exited = new Promise<number>((r) => (settle = r))
34 const kill = vi.fn(async () => {
35 settle(-1)
36 return true
37 })
38 const sendStdin = vi.fn(async () => {})
39 const closeStdin = vi.fn(async () => {})
40 const handle = {
41 pid: opts.pid ?? 4242,
42 get stdout() {
43 return stdout
44 },
45 get stderr() {
46 return stderr
47 },
48 wait: async () => {
49 const exitCode = await exited
50 const result = { exitCode, stdout, stderr, error: undefined }
51 if (exitCode !== 0) {
52 throw new CommandExitError({
53 ...result,
54 error: `exit status ${exitCode}`,
55 })
56 }
57 return result
58 },
59 kill,
60 sendStdin,
61 closeStdin,
62 } as unknown as CommandHandle
63 return {
64 handle,
65 kill,
66 sendStdin,
67 closeStdin,
68 emitStdout: (text) => {
69 stdout += text
70 opts.onStdout?.(text)
71 },
72 emitStderr: (text) => {
73 stderr += text
74 opts.onStderr?.(text)
75 },
76 exit: (code) => settle(code),
77 }
78}
79
80function fakeSandbox(
81 overrides: {
82 /** Decide what each started command does; default exits 0 immediately. */
83 onRun?: (cmd: string, fake: FakeCommand) => void
84 files?: Partial<Sandbox['files']>
85 trafficAccessToken?: string
86 createSnapshot?: Sandbox['createSnapshot']
87 fork?: Sandbox['fork']
88 } = {},
89) {
90 const runs: Array<{ cmd: string; opts: Record<string, unknown> }> = []
91 /** Group kills issued as their own command (`kill -KILL -- -<pid>`). */
92 const kills: Array<string> = []
93 const sandbox = {
94 sandboxId: 'sbx_123',
95 trafficAccessToken: overrides.trafficAccessToken,
96 getHost: (port: number) => `${port}-sbx_123.e2b.app`,
97 commands: {
98 run: vi.fn(async (cmd: string, opts?: Record<string, unknown>) => {
99 if (cmd.startsWith('kill -KILL -- -')) {
100 kills.push(cmd)
101 const killer = fakeCommand()
102 killer.exit(0)
103 return killer.handle
104 }
105 if (!opts) throw new Error(`unexpected foreground command: ${cmd}`)
106 runs.push({ cmd, opts })
107 const fake = fakeCommand({
108 onStdout: opts.onStdout as (d: string) => void,
109 onStderr: opts.onStderr as (d: string) => void,
110 })
111 if (overrides.onRun) overrides.onRun(cmd, fake)
112 else fake.exit(0)
113 return fake.handle
114 }),
115 },
116 files: {
117 read: vi.fn(async () => ''),
118 write: vi.fn(async () => ({})),
119 list: vi.fn(async () => []),
120 makeDir: vi.fn(async () => true),
121 remove: vi.fn(async () => {}),
122 rename: vi.fn(async () => ({})),
123 exists: vi.fn(async () => true),
124 ...overrides.files,
125 },
126 createSnapshot: overrides.createSnapshot ?? vi.fn(),
127 fork: overrides.fork ?? vi.fn(),
128 kill: vi.fn(async () => true),
129 }
130 return { sandbox: sandbox as unknown as Sandbox, runs, kills }
131}
132
133const WORKDIR = '/home/user/workspace'
134
135function createHandle(fake = fakeSandbox()) {
136 return {
137 ...fake,
138 handle: new E2BHandle({
139 sandbox: fake.sandbox,
140 workdir: WORKDIR,
141 timeoutMs: 60_000,
142 }),
143 }
144}
145
146async function collect(stream: AsyncIterable<string>): Promise<string> {
147 let out = ''
148 for await (const chunk of stream) out += chunk
149 return out
150}
151
152describe('E2BHandle', () => {
153 it('exposes the expected capabilities and identity', () => {
154 const { handle } = createHandle()
155 expect(handle.provider).toBe('e2b')
156 expect(handle.id).toBe('sbx_123')
157 expect(handle.workspaceRoot).toBe(WORKDIR)
158 expect(handle.capabilities).toBe(E2B_CAPS)
159 expect(handle.capabilities.writableStdin).toBe(true)
160 expect(handle.capabilities.killableProcesses).toBe(true)
161 })
162
163 it('exec runs in the workdir with native cwd/env and splits stdout from stderr', async () => {
164 const { handle, runs } = createHandle(
165 fakeSandbox({
166 onRun: (_cmd, fake) => {
167 fake.emitStdout('to-out\n')
168 fake.emitStderr('to-err\n')
169 fake.exit(0)
170 },
171 }),
172 )
173 await handle.env.set({ BASE: '1' })
174 const result = await handle.process.exec('echo hi', {
175 cwd: '/workspace/sub',
176 env: { EXTRA: '2' },
177 })
178 expect(result).toEqual({
179 stdout: 'to-out\n',
180 stderr: 'to-err\n',
181 exitCode: 0,
182 })
183 // The command runs as a setsid group leader so kill can reach children.
184 expect(runs[0]?.cmd).toBe("exec setsid bash -c 'echo hi'")
185 expect(runs[0]?.opts).toMatchObject({
186 background: true,
187 cwd: `${WORKDIR}/sub`,
188 envs: { BASE: '1', EXTRA: '2' },
189 stdin: false,
190 timeoutMs: 0,
191 })
192 // Env never lands in the command string.
193 expect(runs[0]?.cmd).not.toContain('export')
194 })
195
196 it('exec reports a non-zero exit as a result, not an error', async () => {
197 const { handle } = createHandle(
198 fakeSandbox({
199 onRun: (_cmd, fake) => {
200 fake.emitStderr('boom\n')
201 fake.exit(3)
202 },
203 }),
204 )
205 const result = await handle.process.exec('exit 3')
206 expect(result.exitCode).toBe(3)
207 expect(result.stderr).toBe('boom\n')
208 })
209
210 it('exec defaults cwd to the workdir and omits envs when none are set', async () => {
211 const { handle, runs } = createHandle()
212 await handle.process.exec('pwd')
213 expect(runs[0]?.opts).toMatchObject({ cwd: WORKDIR })
214 expect(runs[0]?.opts).not.toHaveProperty('envs')
215 })
216
217 it('exec kills the sandbox-side process group when the signal aborts', async () => {
218 let fake!: FakeCommand
219 const { handle, kills } = createHandle(
220 fakeSandbox({
221 onRun: (_cmd, f) => {
222 fake = f
223 },
224 }),
225 )
226 const controller = new AbortController()
227 const pending = handle.process.exec('sleep 60', {
228 signal: controller.signal,
229 })
230 await new Promise((r) => setTimeout(r, 0))
231 controller.abort()
232 const result = await pending
233 expect(kills).toEqual(['kill -KILL -- -4242'])
234 expect(fake.kill).toHaveBeenCalledOnce()
235 expect(result.exitCode).not.toBe(0)
236 })
237
238 it('spawn streams stdout and stderr separately and resolves wait() with the exit code', async () => {
239 const { handle } = createHandle(
240 fakeSandbox({
241 onRun: (_cmd, fake) => {
242 setTimeout(() => {
243 fake.emitStdout('line-1\n')
244 fake.emitStderr('warn\n')
245 fake.emitStdout('line-2\n')
246 fake.exit(0)
247 }, 0)
248 },
249 }),
250 )
251 const proc = await handle.process.spawn('run')
252 expect(proc.pid).toBe(4242)
253 const [out, err, code] = await Promise.all([
254 collect(proc.stdout),
255 collect(proc.stderr),
256 proc.wait(),
257 ])
258 expect(out).toBe('line-1\nline-2\n')
259 expect(err).toBe('warn\n')
260 expect(code).toBe(0)
261 })
262
263 it('spawn requests stdin and forwards write/end to the command', async () => {
264 let fake!: FakeCommand
265 const { handle, runs } = createHandle(
266 fakeSandbox({
267 onRun: (_cmd, f) => {
268 fake = f
269 },
270 }),
271 )
272 const proc = await handle.process.spawn('cat')
273 expect(runs[0]?.opts).toMatchObject({ stdin: true })
274 await proc.stdin.write('hello\n')
275 await proc.stdin.end()
276 expect(fake.sendStdin).toHaveBeenCalledWith('hello\n')
277 expect(fake.closeStdin).toHaveBeenCalledOnce()
278 fake.exit(0)
279 expect(await proc.wait()).toBe(0)
280 })
281
282 // A dropped event stream says nothing about the process; the SDK's wait()
283 // rejects while the process may still run. It must not outlive the error.
284 it('kills the process group when wait() fails with a non-exit error', async () => {
285 let started: FakeCommand | undefined
286 const { handle, kills } = createHandle(
287 fakeSandbox({
288 onRun: (_cmd, fake) => {
289 started = fake
290 fake.handle.wait = async () => {
291 throw new Error('stream dropped')
292 }
293 },
294 }),
295 )
296 const proc = await handle.process.spawn('sleep 60')
297 await expect(proc.wait()).rejects.toThrow('stream dropped')
298 expect(kills).toEqual(['kill -KILL -- -4242'])
299 expect(started?.kill).toHaveBeenCalledOnce()
300 // The same path serves exec.
301 kills.length = 0
302 await expect(handle.process.exec('sleep 60')).rejects.toThrow(
303 'stream dropped',
304 )
305 expect(kills).toEqual(['kill -KILL -- -4242'])
306 })
307
308 it('spawn kill() signals the process group, then the pid, and wait() reports a signal exit', async () => {
309 let fake!: FakeCommand
310 const { handle, kills } = createHandle(
311 fakeSandbox({
312 onRun: (_cmd, f) => {
313 fake = f
314 },
315 }),
316 )
317 const proc = await handle.process.spawn('sleep 60')
318 await proc.kill('SIGTERM')
319 expect(kills).toEqual(['kill -KILL -- -4242'])
320 expect(fake.kill).toHaveBeenCalledOnce()
321 expect(await proc.wait()).toBe(-1)
322 })
323
324 it('aborting the spawn signal kills the process group', async () => {
325 let fake!: FakeCommand
326 const { handle, kills } = createHandle(
327 fakeSandbox({
328 onRun: (_cmd, f) => {
329 fake = f
330 },
331 }),
332 )
333 const controller = new AbortController()
334 const proc = await handle.process.spawn('sleep 60', {
335 signal: controller.signal,
336 })
337 controller.abort()
338 await proc.wait()
339 expect(kills).toEqual(['kill -KILL -- -4242'])
340 expect(fake.kill).toHaveBeenCalledOnce()
341 })
342
343 it('rejects spawn when the signal is already aborted', async () => {
344 const { handle, runs } = createHandle()
345 const controller = new AbortController()
346 controller.abort()
347 await expect(
348 handle.process.spawn('true', { signal: controller.signal }),
349 ).rejects.toThrow()
350 expect(runs).toHaveLength(0)
351 })
352
353 it('caps a spawned stream and kills the process on overflow', async () => {
354 let fake!: FakeCommand
355 const { handle } = createHandle(
356 fakeSandbox({
357 onRun: (_cmd, f) => {
358 fake = f
359 },
360 }),
361 )
362 const proc = await handle.process.spawn('yes')
363 const chunk = 'x'.repeat(1024 * 1024)
364 for (let i = 0; i < 9; i++) fake.emitStdout(chunk)
365 const out = await collect(proc.stdout)
366 expect(out).toContain('output truncated')
367 expect(out.length).toBeLessThan(9 * 1024 * 1024)
368 // The kill settles the exit; awaiting it proves the overflow triggered it.
369 expect(await proc.wait()).toBe(-1)
370 expect(fake.kill).toHaveBeenCalled()
371 })
372
373 it('write sends strings as-is and binary data as a Blob', async () => {
374 const { handle, sandbox } = createHandle()
375 await handle.fs.write('/workspace/a.txt', 'hello')
376 expect(sandbox.files.write).toHaveBeenCalledWith(
377 `${WORKDIR}/a.txt`,
378 'hello',
379 )
380 await handle.fs.write('/workspace/b.bin', new Uint8Array([0, 1, 250]))
381 const [path, blob] = (sandbox.files.write as ReturnType<typeof vi.fn>).mock
382 .calls[1] as [string, Blob]
383 expect(path).toBe(`${WORKDIR}/b.bin`)
384 expect(blob).toBeInstanceOf(Blob)
385 expect(Array.from(new Uint8Array(await blob.arrayBuffer()))).toEqual([
386 0, 1, 250,
387 ])
388 })
389
390 it('read and readBytes pick the text and bytes formats', async () => {
391 const { handle, sandbox } = createHandle()
392 await handle.fs.read('/workspace/a.txt')
393 expect(sandbox.files.read).toHaveBeenCalledWith(`${WORKDIR}/a.txt`, {
394 format: 'text',
395 })
396 await handle.fs.readBytes('/workspace/b.bin')
397 expect(sandbox.files.read).toHaveBeenCalledWith(`${WORKDIR}/b.bin`, {
398 format: 'bytes',
399 })
400 })
401
402 it('maps list entries to { name, path, type } on the virtual path', async () => {
403 const { handle } = createHandle(
404 fakeSandbox({
405 files: {
406 list: vi.fn(async () => [
407 { name: 'src', type: 'dir', path: `${WORKDIR}/src` },
408 { name: 'a.txt', type: 'file', path: `${WORKDIR}/a.txt` },
409 { name: 'link', type: undefined, path: `${WORKDIR}/link` },
410 ]) as unknown as Sandbox['files']['list'],
411 },
412 }),
413 )
414 expect(await handle.fs.list('/workspace/')).toEqual([
415 { name: 'src', path: '/workspace/src', type: 'dir' },
416 { name: 'a.txt', path: '/workspace/a.txt', type: 'file' },
417 { name: 'link', path: '/workspace/link', type: 'file' },
418 ])
419 })
420
421 it('mkdir/remove/rename/exists go through the native file API', async () => {
422 const { handle, sandbox } = createHandle()
423 await handle.fs.mkdir('/workspace/d')
424 expect(sandbox.files.makeDir).toHaveBeenCalledWith(`${WORKDIR}/d`)
425 await handle.fs.remove('/workspace/d')
426 expect(sandbox.files.remove).toHaveBeenCalledWith(`${WORKDIR}/d`)
427 await handle.fs.rename('/workspace/a', '/workspace/b')
428 expect(sandbox.files.rename).toHaveBeenCalledWith(
429 `${WORKDIR}/a`,
430 `${WORKDIR}/b`,
431 )
432 expect(await handle.fs.exists('/workspace/a')).toBe(true)
433 expect(sandbox.files.exists).toHaveBeenCalledWith(`${WORKDIR}/a`)
434 })
435
436 it('leaves paths outside /workspace untouched', async () => {
437 const { handle, sandbox } = createHandle()
438 await handle.fs.read('/etc/hostname')
439 expect(sandbox.files.read).toHaveBeenCalledWith('/etc/hostname', {
440 format: 'text',
441 })
442 })
443
444 it('maps a public port to a plain https channel', async () => {
445 const { handle } = createHandle()
446 expect(await handle.ports.connect(3000)).toEqual({
447 url: 'https://3000-sbx_123.e2b.app',
448 })
449 })
450
451 it('attaches the traffic access token when the sandbox restricts public traffic', async () => {
452 const { handle } = createHandle(
453 fakeSandbox({ trafficAccessToken: 'tok_1' }),
454 )
455 expect(await handle.ports.connect(3000)).toEqual({
456 url: 'https://3000-sbx_123.e2b.app',
457 token: 'tok_1',
458 headers: { [TRAFFIC_TOKEN_HEADER]: 'tok_1' },
459 })
460 })
461
462 it('snapshot names the template per sandbox and returns a SnapshotRef', async () => {
463 const createSnapshot = vi.fn(async () => ({
464 snapshotId: 'team/tanstack-ai-sbx-123-after-setup:default',
465 names: [],
466 }))
467 const { handle } = createHandle(
468 fakeSandbox({
469 createSnapshot: createSnapshot as unknown as Sandbox['createSnapshot'],
470 }),
471 )
472 const ref = await handle.snapshot!('after-setup')
473 expect(createSnapshot).toHaveBeenCalledWith({
474 name: 'tanstack-ai-sbx-123-after-setup',
475 })
476 expect(ref).toEqual({
477 id: 'team/tanstack-ai-sbx-123-after-setup:default',
478 label: 'after-setup',
479 })
480 })
481
482 it('fork returns a handle on the forked sandbox with the parent env overlay', async () => {
483 const child = fakeSandbox().sandbox
484 Object.assign(child, { sandboxId: 'sbx_child' })
485 const fork = vi.fn(async () => [child])
486 const { handle } = createHandle(
487 fakeSandbox({ fork: fork as unknown as Sandbox['fork'] }),
488 )
489 await handle.env.set({ A: '1' })
490 const forked = await handle.fork!()
491 expect(fork).toHaveBeenCalledWith({ timeoutMs: 60_000 })
492 expect(forked.id).toBe('sbx_child')
493 expect(forked.workspaceRoot).toBe(WORKDIR)
494 await forked.process.exec('env')
495 expect(
496 (child.commands.run as ReturnType<typeof vi.fn>).mock.calls[0]?.[1],
497 ).toMatchObject({ envs: { A: '1' } })
498 })
499
500 it('fork surfaces a per-fork error', async () => {
501 const fork = vi.fn(async () => [new Error('429: rate limited')])
502 const { handle } = createHandle(
503 fakeSandbox({ fork: fork as unknown as Sandbox['fork'] }),
504 )
505 await expect(handle.fork!()).rejects.toThrow('rate limited')
506 })
507
508 it('destroy kills the sandbox', async () => {
509 const { handle, sandbox } = createHandle()
510 await handle.destroy()
511 expect(sandbox.kill).toHaveBeenCalledOnce()
512 })
513})
514
515describe('groupLeaderCommand', () => {
516 it('single-quotes the command for the inner shell', () => {
517 expect(groupLeaderCommand(`echo 'it''s' && cd "$HOME"`)).toBe(
518 `exec setsid bash -c 'echo '\\''it'\\'''\\''s'\\'' && cd "$HOME"'`,
519 )
520 })
521})
522
523describe('snapshotName', () => {
524 it('lower-cases, strips unsafe characters and bounds the length', () => {
525 expect(snapshotName('SbX_1', 'after-run-Run:9')).toBe(
526 'tanstack-ai-sbx-1-after-run-run-9',
527 )
528 expect(snapshotName('sbx', undefined)).toBe('tanstack-ai-sbx-snap')
529 expect(snapshotName('sbx', '///')).toBe('tanstack-ai-sbx-snap')
530 // A long id is truncated; the label survives so two snapshots stay apart.
531 const long = snapshotName('x'.repeat(80), 'after-run-9')
532 expect(long.length).toBeLessThanOrEqual(63)
533 expect(long.endsWith('-after-run-9')).toBe(true)
534 })
535})