Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk-js): preserve caller cancellation after response headers
Claire-ovoea547d10fa8e
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.mdindex 58b8d196a..6aeccea4b 100644--- a/docs/sdks/javascript.md+++ b/docs/sdks/javascript.md@@ -477,6 +477,7 @@ The `ConnectionConfig` class manages API server connection settings.::: info Runtime Notes- In browsers, the SDK uses the global `fetch` implementation.+- A caller-provided `AbortSignal` remains active while reading the response body, including SSE streams and download responses. Signal composition uses the standard `AbortSignal.any` API, which must be available in the runtime.- `requestTimeoutSeconds` bounds the wait for a response: it stops applying once the response headers arrive (streaming responses are not cut off). It never caps a healthy file upload body, which can legitimately take longer than the timeout; on Node.js a stalled upload, or an upload that gets no response headers within the timeout once the body has been sent, is aborted instead of hanging (the Go SDK's `ResponseHeaderTimeout` contract).- In Node.js, every `Sandbox` and `SandboxManager` clones the base `ConnectionConfig` via `withTransportIfMissing()`, so each instance gets an isolated `undici` keep-alive pool. Call `sandbox.close()` or `manager.close()` when you are done so the SDK can release the associated agent.:::diff --git a/sdks/sandbox/javascript/src/config/connection.ts b/sdks/sandbox/javascript/src/config/connection.tsindex d4be97ad3..88ace59f7 100644--- a/sdks/sandbox/javascript/src/config/connection.ts+++ b/sdks/sandbox/javascript/src/config/connection.ts@@ -296,13 +296,11 @@ function createTimedFetch(opts: {): undefined;- const onAbort = () =>- ac.abort((requestSignal as any)?.reason ?? new Error("Aborted"));- if (requestSignal) {- if (requestSignal.aborted) onAbort();- else- requestSignal.addEventListener("abort", onAbort, { once: true } as any);- }+ // Caller cancellation covers the response body too; only the SDK's+ // response-header deadline is cleared when fetch resolves.+ const signal = requestSignal+ ? AbortSignal.any([requestSignal, ac.signal])+ : ac.signal;// Best-effort: attach the SDK host's own IP so the server can see the// client's self-reported address. Applied per request (never overriding a@@ -314,7 +312,7 @@ function createTimedFetch(opts: {const reqInput = withIp.input;const mergedInit: RequestInit = {...(withIp.init ?? {}),- signal: ac.signal,+ signal,};if (debug) {@@ -349,8 +347,6 @@ function createTimedFetch(opts: {return res;} finally {if (t) clearTimeout(t);- if (requestSignal)- requestSignal.removeEventListener("abort", onAbort as any);}};}diff --git a/sdks/sandbox/javascript/tests/connection.body-abort.test.mjs b/sdks/sandbox/javascript/tests/connection.body-abort.test.mjsnew file mode 100644index 000000000..5592ccf3c--- /dev/null+++ b/sdks/sandbox/javascript/tests/connection.body-abort.test.mjs@@ -0,0 +1,82 @@+// Copyright 2026 The OpenSandbox Authors+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++import assert from "node:assert/strict";+import { once } from "node:events";+import { createServer } from "node:http";+import { setTimeout as sleep } from "node:timers/promises";+import test from "node:test";+import { ConnectionConfig } from "../dist/index.js";+import { _setClientIpForTest } from "../dist/internal.js";++async function streamingServer(t) {+ const server = createServer((_req, res) => {+ res.writeHead(200, { "Content-Type": "text/event-stream" });+ res.write('data: {"type":"stdout","text":"first"}\n\n');+ });+ server.listen(0, "127.0.0.1");+ await once(server, "listening");+ t.after(async () => {+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ });+ return `http://127.0.0.1:${server.address().port}`;+}++for (const transport of ["fetch", "sseFetch", "uploadFetch"]) {+ for (const signalOnRequest of [false, true]) {+ test(`${transport}: abort after headers cancels body (${signalOnRequest ? "Request" : "init"} signal)`, { timeout: 5000 }, async (t) => {+ _setClientIpForTest("127.0.0.1");+ const url = await streamingServer(t);+ const config = new ConnectionConfig({ wakeRetryEnabled: false }).withTransportIfMissing();+ t.after(() => config.closeTransport());+ const controller = new AbortController();+ const response = signalOnRequest+ ? await config[transport](new Request(url, { signal: controller.signal }))+ : await config[transport](url, { signal: controller.signal });+ const reader = response.body.getReader();+ t.after(() => reader.cancel().catch(() => {}));+ assert.equal((await reader.read()).done, false);+ const pendingRead = reader.read().then(+ () => "resolved",+ (error) => error.name,+ );+ controller.abort();+ let timer;+ try {+ const result = await Promise.race([+ pendingRead,+ new Promise((resolve) => { timer = setTimeout(() => resolve("not cancelled"), 500); }),+ ]);+ assert.equal(result, "AbortError");+ } finally {+ clearTimeout(timer);+ }+ });+ }+}++test("response-header timeout does not become a response-body timeout", { timeout: 5000 }, async (t) => {+ _setClientIpForTest("127.0.0.1");+ const url = await streamingServer(t);+ const config = new ConnectionConfig({ requestTimeoutSeconds: 0.1, wakeRetryEnabled: false }).withTransportIfMissing();+ t.after(() => config.closeTransport());+ const response = await config.fetch(url);+ const reader = response.body.getReader();+ t.after(() => reader.cancel().catch(() => {}));+ await reader.read();+ let settled = false;+ const pendingRead = reader.read().finally(() => { settled = true; });+ await sleep(200);+ assert.equal(settled, false, "the response must remain open beyond the header deadline");+ await reader.cancel();+ await pendingRead;+});