Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(js-sdk): run the full unit test suite in Cloudflare workerd (#1593)
Mish Ushakov1ae3f920903f
diff --git a/.changeset/cf-workers-connection-fixes.md b/.changeset/cf-workers-connection-fixes.mdnew file mode 100644index 000000000..9c6299d33--- /dev/null+++ b/.changeset/cf-workers-connection-fixes.md@@ -0,0 +1,5 @@+---+'e2b': patch+---++Recognize Cloudflare Workers' `Network connection lost` as a dropped sandbox connection so a sandbox killed mid-request surfaces as the health-checked `TimeoutError` (matching Node/Bun/Deno), and fix streaming downloads releasing their pooled connection twice when cancelled while a read was in flightdiff --git a/.github/workflows/js_sdk_tests.yml b/.github/workflows/js_sdk_tests.ymlindex b32ce4ab7..d5725246c 100644--- a/.github/workflows/js_sdk_tests.yml+++ b/.github/workflows/js_sdk_tests.yml@@ -86,8 +86,8 @@ jobs:path: ${{ matrix.os == 'windows-latest' && '~/AppData/Local/ms-playwright' || '~/.cache/ms-playwright' }}key: playwright-${{ runner.os }}-${{ steps.playwright-version.outputs.version }}- # Every suite needs dist/: the unit bundle test and both Cloudflare- # configs fail in CI when the build output is missing.+ # The unit bundle test and the Cloudflare deploy config fail in CI when+ # the build output is missing.- name: Test buildrun: pnpm build@@ -122,7 +122,8 @@ jobs:E2B_API_KEY: ${{ secrets.E2B_API_KEY }}E2B_DOMAIN: ${{ inputs.E2B_DOMAIN }}- - name: Run Cloudflare Workers tests+ # Full unit + connectionConfig suite inside workerd (vitest-pool-workers).+ - name: Run test suite under Cloudflare workerdif: matrix.runtime == 'cloudflare'run: pnpm test:cfenv:diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex d470c9213..8fc3393bf 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -295,8 +295,15 @@ export function wrapStreamWithConnectionCleanup(const reader = body.getReader()const idle = createIdleAbort(controller, idleTimeoutMs, 'Stream')- // Idempotent: safe to call from multiple stream callbacks.+ // Idempotent: safe to call from multiple stream callbacks — cancelling+ // while a pull is in flight settles both paths (the pending read resolves+ // `done` after `reader.cancel()`), which must not release twice.+ let released = falseconst release = () => {+ if (released) {+ return+ }+ released = trueidle.clear()cleanup()}diff --git a/packages/js-sdk/src/envd/rpc.ts b/packages/js-sdk/src/envd/rpc.tsindex 64234fa56..9c5b4ad1b 100644--- a/packages/js-sdk/src/envd/rpc.ts+++ b/packages/js-sdk/src/envd/rpc.ts@@ -25,14 +25,16 @@ export type SandboxHealthCheck = () => Promise<boolean | undefined>* is dropped mid-request. The transport surfaces a dropped connection (e.g. an* HTTP/2 stream reset) with runtime- and version-specific wording, so we match* every known variant:- * - Node (undici): `terminated`- * - Bun: `The socket connection was closed unexpectedly`- * - Deno: `error reading a body from connection`+ * - Node (undici): `terminated`+ * - Bun: `The socket connection was closed unexpectedly`+ * - Deno: `error reading a body from connection`+ * - Cloudflare Workers: `Network connection lost`*/const CONNECTION_TERMINATED_MESSAGES = ['terminated','The socket connection was closed unexpectedly','error reading a body from connection',+ 'Network connection lost',]/**diff --git a/packages/js-sdk/tests/envd/handleEnvdApiError.test.ts b/packages/js-sdk/tests/envd/handleEnvdApiError.test.tsindex d446cefa8..b886f3fe5 100644--- a/packages/js-sdk/tests/envd/handleEnvdApiError.test.ts+++ b/packages/js-sdk/tests/envd/handleEnvdApiError.test.ts@@ -125,6 +125,7 @@ describe('handleEnvdApiFetchError', () => {Node: new TypeError('terminated'),Bun: new Error('The socket connection was closed unexpectedly'),Deno: new TypeError('error reading a body from connection'),+ 'Cloudflare Workers': new Error('Network connection lost.'),}for (const [runtime, error] of Object.entries(runtimeTerminatedErrors)) {diff --git a/packages/js-sdk/tests/envd/handleRpcError.test.ts b/packages/js-sdk/tests/envd/handleRpcError.test.tsindex c3d0a3687..8df1a6d6a 100644--- a/packages/js-sdk/tests/envd/handleRpcError.test.ts+++ b/packages/js-sdk/tests/envd/handleRpcError.test.ts@@ -69,6 +69,7 @@ describe('handleRpcErrorWithHealthCheck', () => {Node: 'terminated',Bun: 'The socket connection was closed unexpectedly',Deno: 'error reading a body from connection',+ 'Cloudflare Workers': 'Network connection lost.',}test('returns a TimeoutError when the health check says the sandbox is not running', async () => {diff --git a/packages/js-sdk/tests/runtime.test.ts b/packages/js-sdk/tests/runtime.test.tsindex d78445d7c..af2919c7a 100644--- a/packages/js-sdk/tests/runtime.test.ts+++ b/packages/js-sdk/tests/runtime.test.ts@@ -1,11 +1,13 @@import { afterEach, expect, test, vi } from 'vitest'-// The unit project also runs under Bun (and prospectively Deno), where the-// host runtime's own unstubbable marker (globalThis.Bun / globalThis.Deno)-// correctly wins detection — these scenarios only exist on a Node host.+// The unit project also runs under Bun, Deno, and Cloudflare's workerd, where+// the host runtime's own unstubbable marker (globalThis.Bun / globalThis.Deno /+// the Cloudflare-Workers user agent) correctly wins detection — these+// scenarios only exist on a Node host.const isNodeHost =typeof (globalThis as any).Bun === 'undefined' &&- typeof (globalThis as any).Deno === 'undefined'+ typeof (globalThis as any).Deno === 'undefined' &&+ (globalThis as any).navigator?.userAgent !== 'Cloudflare-Workers'afterEach(() => {vi.unstubAllGlobals()diff --git a/packages/js-sdk/tests/runtimes/cloudflare/run.test.ts b/packages/js-sdk/tests/runtimes/cloudflare/run.test.tsdeleted file mode 100644index d8c4917db..000000000--- a/packages/js-sdk/tests/runtimes/cloudflare/run.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { env } from 'cloudflare:test'-import { expect, test } from 'vitest'--// Import the built ESM bundle — the artifact Workers users actually load.-// Importing src would bypass bundling regressions like #1579, where an-// eager createRequire shim emitted by tsdown crashed workerd at import.-import { Sandbox } from '../../../dist/index.mjs'-import { template } from '../../template'--const apiKey = (env as Record<string, string>).E2B_API_KEY-const domain = (env as Record<string, string>).E2B_DOMAIN || undefined--test('Cloudflare Workers test', async () => {- const sbx = await Sandbox.create(template, {- timeoutMs: 5_000,- apiKey,- domain,- })- try {- const isRunning = await sbx.isRunning()- expect(isRunning).toBeTruthy()-- const text = 'Hello, World!'-- const cmd = await sbx.commands.run(`echo "${text}"`)-- expect(cmd.exitCode).toBe(0)- expect(cmd.stdout).toEqual(`${text}\n`)-- await sbx.files.write('test.txt', text)- const content = await sbx.files.read('test.txt')-- expect(content).toEqual(text)- } finally {- await sbx.kill()- }-})diff --git a/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts b/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mtsindex 97fd7fe68..85cae1af5 100644--- a/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts+++ b/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts@@ -1,36 +1,43 @@-import { existsSync } from 'node:fs'-import path from 'node:path'-import { fileURLToPath } from 'node:url'-import { cloudflareTest } from '@cloudflare/vitest-pool-workers'import { config } from 'dotenv'import { defineConfig } from 'vitest/config'const env = config()-// The suite smoke-tests the built ESM bundle (what Workers users consume),-// so dist must exist. Skip locally to keep plain `vitest` runs green, but-// fail loudly in CI where the build step is expected to have run.-const distEntry = path.resolve(- path.dirname(fileURLToPath(import.meta.url)),- '../../../dist/index.mjs'-)-const hasDist = existsSync(distEntry)--if (!hasDist) {- const message =- 'dist/index.mjs not found — run `pnpm build` in packages/js-sdk before running the Cloudflare Workers tests'- if (process.env.CI) {- throw new Error(message)- }- console.warn(`Skipping Cloudflare Workers tests: ${message}`)-}+// Error names thrown by src/errors.ts (plus CommandExitError) — the shapes+// this suite's rejection tests expect. Kept as a literal list so an unknown+// error class still fails the run instead of being silently ignored.+const SDK_ERROR_NAMES = new Set([+ 'SandboxError',+ 'TimeoutError',+ 'InvalidArgumentError',+ 'NotEnoughSpaceError',+ 'NotFoundError',+ 'FileNotFoundError',+ 'SandboxNotFoundError',+ 'AuthenticationError',+ 'GitAuthError',+ 'GitUpstreamError',+ 'TemplateError',+ 'RateLimitError',+ 'BuildError',+ 'FileUploadError',+ 'VolumeError',+ 'CommandExitError',+])+// Runs the unit + connectionConfig projects (same coverage as test:bun /+// test:deno) inside Cloudflare's workerd via vitest-pool-workers, against src.+// The real-deploy suite (tests/runtimes/cloudflare-deploy) keeps covering the+// built bundle on actual Cloudflare infrastructure.export default defineConfig({plugins: [cloudflareTest({miniflare: {compatibilityDate: '2026-03-01',+ // nodejs_compat is a hard requirement for the SDK on Workers. It also+ // mirrors the bindings below into process.env (default since compat+ // date 2025-04-01), which is how tests and the SDK read E2B_*.compatibilityFlags: ['nodejs_compat'],bindings: {E2B_API_KEY: process.env.E2B_API_KEY ?? env.parsed?.E2B_API_KEY ?? '',@@ -41,8 +48,43 @@ export default defineConfig({],test: {name: 'cloudflare',- include: hasDist ? ['tests/runtimes/cloudflare/**/*.test.ts'] : [],- passWithNoTests: !hasDist,+ include: ['tests/**/*.test.ts'],+ exclude: [+ 'tests/runtimes/**',+ 'tests/template/**',+ // Inspects the host-built dist/index.mjs via node:fs, which workerd's+ // virtual filesystem can never see (and throws in CI when the file is+ // "missing"); the Node unit project keeps running it.+ 'tests/bundle/**',+ ],+ globals: false,testTimeout: 30_000,+ bail: 0,+ // workerd reports a rejection as unhandled unless a handler is attached+ // within the same microtask drain, and vitest never processes the+ // rejectionhandled retraction, so rejections the tests DO handle (the+ // `await expect(p).rejects` pattern, including inline ones — workerd also+ // flags intermediate promises of the async-function chain) false-positive+ // ~60 times per run. Instead of dangerouslyIgnoreUnhandledErrors, drop+ // only the rejection shapes these tests deliberately provoke; uncaught+ // exceptions and any unknown rejection shape still fail the run.+ onUnhandledError(error) {+ const message = String(error.message ?? '')+ const expectedRejection =+ error.type === 'Unhandled Rejection' &&+ // SDK public errors — what `expect(p).rejects` asserts on.+ (SDK_ERROR_NAMES.has(error.name) ||+ // The transport errors the SDK wraps: connect-rpc failures and+ // aborted requests surface on intermediate promises too.+ error.name === 'ConnectError' ||+ message.startsWith('ConnectError:') ||+ error.name === 'AbortError' ||+ // workerd's teardown error for in-flight streams when a test kills+ // the sandbox mid-request.+ message === 'Network connection lost.' ||+ // Stub rejection from tests/sandbox/git/validation.test.ts.+ message === 'commands.run should not be called')+ if (expectedRejection) return false+ },},})diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.tsindex 2f8628c84..28a1999b7 100644--- a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts@@ -79,9 +79,13 @@ test.skipIf(isDebug)(try {const marker = 'auto-pause-fs-only'await sandbox.files.write('/home/user/auto-pause-marker.txt', marker)+ // Read via a command, not files.read: envd's non-gzip download path+ // serves procfs files as an empty 200 (it sizes them by stat, which is+ // 0), so clients that don't negotiate gzip — like workerd's fetch —+ // silently get '' (infra#3363).const bootBefore = (- await sandbox.files.read('/proc/sys/kernel/random/boot_id')- ).trim()+ await sandbox.commands.run('cat /proc/sys/kernel/random/boot_id')+ ).stdout.trim()await wait(5_000)@@ -97,8 +101,8 @@ test.skipIf(isDebug)(assert.equal(persisted, marker)const bootAfter = (- await sandbox.files.read('/proc/sys/kernel/random/boot_id')- ).trim()+ await sandbox.commands.run('cat /proc/sys/kernel/random/boot_id')+ ).stdout.trim()assert.notEqual(bootAfter, bootBefore)} finally {await sandbox.kill().catch(() => {})diff --git a/packages/js-sdk/tests/sandbox/snapshot.test.ts b/packages/js-sdk/tests/sandbox/snapshot.test.tsindex 864cf8d39..ac0dead40 100644--- a/packages/js-sdk/tests/sandbox/snapshot.test.ts+++ b/packages/js-sdk/tests/sandbox/snapshot.test.ts@@ -173,10 +173,14 @@ sandboxTest.skipIf(isDebug)(await sandbox.files.write(filename, content)- // Kernel boot id before the pause; it changes only across a real (cold) boot.+ // Kernel boot id before the pause; it changes only across a real (cold)+ // boot. Read via a command, not files.read: envd's non-gzip download path+ // serves procfs files as an empty 200 (it sizes them by stat, which is 0),+ // so clients that don't negotiate gzip — like workerd's fetch — silently+ // get '' (infra#3363).const bootBefore = (- await sandbox.files.read('/proc/sys/kernel/random/boot_id')- ).trim()+ await sandbox.commands.run('cat /proc/sys/kernel/random/boot_id')+ ).stdout.trim()// Filesystem-only snapshot: no memory is captured, so resuming cold-boots.await sandbox.pause({ keepMemory: false })@@ -196,8 +200,8 @@ sandboxTest.skipIf(isDebug)(// A fresh boot id proves the guest rebooted rather than restoring memory.const bootAfter = (- await resumedSandbox.files.read('/proc/sys/kernel/random/boot_id')- ).trim()+ await resumedSandbox.commands.run('cat /proc/sys/kernel/random/boot_id')+ ).stdout.trim()assert.notEqual(bootAfter, bootBefore)})