Open History to see the last commit
1/**
2 * Provider tests against a mocked `e2b`. The cases that matter most: a killed
3 * or expired sandbox resumes as `null` (so `ensure()` re-creates), anything
4 * else from `connect` surfaces (so `ensure()` does not duplicate a live
5 * sandbox), and an abort that lands mid-create kills what was just made.
6 */
7import { beforeEach, describe, expect, it, vi } from 'vitest'
8import { INSTANCE_KEY_METADATA, e2bSandbox } from '../src/index'
9
10const { createMock, connectMock, killMock, MockNotFound } = vi.hoisted(() => {
11 class MockNotFound extends Error {}
12 return {
13 createMock: vi.fn(),
14 connectMock: vi.fn(),
15 killMock: vi.fn(),
16 MockNotFound,
17 }
18})
19
20vi.mock('e2b', () => ({
21 Sandbox: { create: createMock, connect: connectMock, kill: killMock },
22 SandboxNotFoundError: MockNotFound,
23 CommandExitError: class extends Error {},
24}))
25
26/** A sandbox stub covering only what the provider touches. */
27function sandboxStub(id = 'sbx_123') {
28 return {
29 sandboxId: id,
30 trafficAccessToken: undefined,
31 files: { makeDir: vi.fn(async () => true) },
32 kill: vi.fn(async () => true),
33 }
34}
35
36beforeEach(() => {
37 createMock.mockReset()
38 connectMock.mockReset()
39 killMock.mockReset()
40})
41
42describe('e2bSandbox create', () => {
43 it('creates with the 30 minute default timeout, kill-on-timeout, and the key as metadata', async () => {
44 const stub = sandboxStub()
45 createMock.mockResolvedValue(stub)
46 const handle = await e2bSandbox({ apiKey: 'k' }).create({
47 id: 'thread-1',
48 env: { A: 'b' },
49 })
50 expect(handle.id).toBe('sbx_123')
51 expect(handle.workspaceRoot).toBe('/home/user/workspace')
52 expect(createMock).toHaveBeenCalledWith(
53 expect.objectContaining({
54 apiKey: 'k',
55 timeoutMs: 30 * 60_000,
56 envs: { A: 'b' },
57 metadata: { [INSTANCE_KEY_METADATA]: 'thread-1' },
58 lifecycle: { onTimeout: 'kill' },
59 }),
60 )
61 // The workdir is created natively before any cwd-bound command runs.
62 expect(stub.files.makeDir).toHaveBeenCalledWith('/home/user/workspace')
63 })
64
65 it('forwards the configured template', async () => {
66 createMock.mockResolvedValue(sandboxStub())
67 await e2bSandbox({ apiKey: 'k', template: 'my-template' }).create({})
68 expect(createMock).toHaveBeenCalledWith(
69 expect.objectContaining({ apiKey: 'k', template: 'my-template' }),
70 )
71 })
72
73 it('forwards timeoutMs, onTimeout, metadata, workdir and allowPublicTraffic', async () => {
74 const stub = sandboxStub()
75 createMock.mockResolvedValue(stub)
76 const handle = await e2bSandbox({
77 timeoutMs: 60_000,
78 onTimeout: 'pause',
79 metadata: { team: 'x' },
80 workdir: '/home/user/app',
81 allowPublicTraffic: false,
82 }).create({ id: 'k1' })
83 expect(createMock).toHaveBeenCalledWith(
84 expect.objectContaining({
85 timeoutMs: 60_000,
86 lifecycle: { onTimeout: 'pause' },
87 metadata: { team: 'x', [INSTANCE_KEY_METADATA]: 'k1' },
88 network: { allowPublicTraffic: false },
89 }),
90 )
91 expect(stub.files.makeDir).toHaveBeenCalledWith('/home/user/app')
92 expect(handle.workspaceRoot).toBe('/home/user/app')
93 })
94
95 it('does not send an empty envs object', async () => {
96 createMock.mockResolvedValue(sandboxStub())
97 await e2bSandbox().create({ env: {} })
98 expect(createMock.mock.calls[0]?.[0]).not.toHaveProperty('envs')
99 })
100
101 it('maps a deny network policy onto allowInternetAccess: false', async () => {
102 createMock.mockResolvedValue(sandboxStub())
103 await e2bSandbox().create({
104 policy: { capabilities: { network: 'deny' } },
105 })
106 expect(createMock).toHaveBeenCalledWith(
107 expect.objectContaining({ allowInternetAccess: false }),
108 )
109 })
110
111 it('leaves internet access at the E2B default for allow/ask', async () => {
112 createMock.mockResolvedValue(sandboxStub())
113 await e2bSandbox().create({
114 policy: { capabilities: { network: 'allow' } },
115 })
116 expect(createMock.mock.calls[0]?.[0]).not.toHaveProperty(
117 'allowInternetAccess',
118 )
119 })
120
121 // The SDK's signal only cancels the HTTP request, so an abort that lands
122 // after the sandbox exists must kill it rather than leave a billed sandbox
123 // with no owner.
124 it('kills the sandbox when the signal aborts during create', async () => {
125 const stub = sandboxStub()
126 const controller = new AbortController()
127 createMock.mockImplementation(async () => {
128 controller.abort()
129 return stub
130 })
131 await expect(
132 e2bSandbox().create({ signal: controller.signal }),
133 ).rejects.toThrow()
134 expect(stub.kill).toHaveBeenCalledOnce()
135 })
136
137 it('kills the sandbox when preparing the workdir fails', async () => {
138 const stub = sandboxStub()
139 stub.files.makeDir.mockRejectedValue(new Error('disk full'))
140 createMock.mockResolvedValue(stub)
141 await expect(e2bSandbox().create({})).rejects.toThrow('disk full')
142 expect(stub.kill).toHaveBeenCalledOnce()
143 })
144
145 // The SDK cannot cancel a pending create, so the caller is released at once
146 // and the sandbox is killed when the create eventually settles.
147 it('rejects promptly while create is pending and kills the late sandbox', async () => {
148 const stub = sandboxStub()
149 let settle!: (s: typeof stub) => void
150 createMock.mockReturnValue(new Promise((r) => (settle = r)))
151 const controller = new AbortController()
152 const pending = e2bSandbox().create({ signal: controller.signal })
153 controller.abort(new Error('caller gave up'))
154 await expect(pending).rejects.toThrow('caller gave up')
155 expect(stub.kill).not.toHaveBeenCalled()
156 settle(stub)
157 await new Promise((r) => setTimeout(r, 0))
158 expect(stub.kill).toHaveBeenCalledOnce()
159 })
160
161 it('applies the same abort handling to restoreSnapshot', async () => {
162 createMock.mockReturnValue(new Promise(() => {}))
163 const controller = new AbortController()
164 const pending = e2bSandbox().restoreSnapshot!({
165 snapshotId: 'snap',
166 signal: controller.signal,
167 })
168 controller.abort()
169 await expect(pending).rejects.toThrow()
170 })
171
172 it('rejects a plain-http apiUrl at construction, but allows loopback', () => {
173 expect(() => e2bSandbox({ apiUrl: 'http://api.example.com' })).toThrow(
174 /apiUrl must use https/,
175 )
176 expect(() => e2bSandbox({ apiUrl: 'http://localhost:3000' })).not.toThrow()
177 expect(() => e2bSandbox({ apiUrl: 'https://api.e2b.app' })).not.toThrow()
178 })
179
180 it('rejects before creating when the signal is already aborted', async () => {
181 const controller = new AbortController()
182 controller.abort()
183 await expect(
184 e2bSandbox().create({ signal: controller.signal }),
185 ).rejects.toThrow()
186 expect(createMock).not.toHaveBeenCalled()
187 })
188})
189
190describe('e2bSandbox restoreSnapshot', () => {
191 it('creates a sandbox from the snapshot id and carries env + policy', async () => {
192 createMock.mockResolvedValue(sandboxStub('sbx_restored'))
193 const provider = e2bSandbox({ apiKey: 'k' })
194 // restoreSnapshot is optional on the contract; this provider implements it.
195 const handle = await provider.restoreSnapshot!({
196 snapshotId: 'team/tanstack-ai-sbx-after-setup:default',
197 env: { SECRET: 's' },
198 policy: { capabilities: { network: 'deny' } },
199 })
200 expect(handle.id).toBe('sbx_restored')
201 expect(createMock).toHaveBeenCalledWith(
202 expect.objectContaining({
203 template: 'team/tanstack-ai-sbx-after-setup:default',
204 envs: { SECRET: 's' },
205 allowInternetAccess: false,
206 }),
207 )
208 })
209
210 it('kills the sandbox when the signal aborts while the workdir is being prepared', async () => {
211 const stub = sandboxStub()
212 const controller = new AbortController()
213 stub.files.makeDir.mockImplementation(async () => {
214 controller.abort()
215 throw new Error('request aborted')
216 })
217 createMock.mockResolvedValue(stub)
218 await expect(
219 e2bSandbox().create({ signal: controller.signal }),
220 ).rejects.toThrow()
221 expect(stub.kill).toHaveBeenCalledOnce()
222 })
223})
224
225describe('e2bSandbox resume', () => {
226 it('connects by id and extends the timeout', async () => {
227 connectMock.mockResolvedValue(sandboxStub('sbx_live'))
228 const handle = await e2bSandbox({ apiKey: 'k' }).resume({ id: 'sbx_live' })
229 expect(handle?.id).toBe('sbx_live')
230 expect(connectMock).toHaveBeenCalledWith(
231 'sbx_live',
232 expect.objectContaining({ apiKey: 'k', timeoutMs: 30 * 60_000 }),
233 )
234 })
235
236 it('returns null for a killed or expired sandbox', async () => {
237 connectMock.mockRejectedValue(new MockNotFound('Sandbox not found'))
238 expect(await e2bSandbox().resume({ id: 'gone' })).toBeNull()
239 })
240
241 // A 401 or a transport error is NOT "gone". Reporting it as null sends
242 // `ensure()` down the create path and silently duplicates a live sandbox.
243 it('rethrows anything that is not a not-found error', async () => {
244 connectMock.mockRejectedValue(new Error('401: Invalid API key'))
245 await expect(e2bSandbox().resume({ id: 'sbx_live' })).rejects.toThrow(
246 'Invalid API key',
247 )
248 })
249})
250
251describe('e2bSandbox destroy', () => {
252 it('kills by id and treats an already-gone sandbox as success', async () => {
253 killMock.mockResolvedValue(false)
254 await expect(
255 e2bSandbox({ apiKey: 'k' }).destroy({ id: 'sbx_gone' }),
256 ).resolves.toBeUndefined()
257 expect(killMock).toHaveBeenCalledWith(
258 'sbx_gone',
259 expect.objectContaining({ apiKey: 'k' }),
260 )
261 })
262
263 it('rethrows a failed kill instead of reporting success', async () => {
264 killMock.mockRejectedValue(new Error('401: Invalid API key'))
265 await expect(e2bSandbox().destroy({ id: 'sbx_live' })).rejects.toThrow(
266 'Invalid API key',
267 )
268 })
269})
270
271describe('e2bSandbox identity', () => {
272 it('reports the provider name and capabilities', () => {
273 const provider = e2bSandbox()
274 expect(provider.name).toBe('e2b')
275 expect(provider.capabilities().snapshots).toBe(true)
276 expect(typeof provider.restoreSnapshot).toBe('function')
277 })
278})