Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
import test from "ava";
import { Bash, BashTool } from "../wrapper.js";

test("BuiltinContext exposes AbortSignal and helpers", async (t) => {
let seen: any = {};
const bash = new Bash({
customBuiltins: {
probe: async (ctx: any) => {
seen.signal = ctx.signal;
seen.helpers = [
typeof ctx.throwIfCancelled,
typeof ctx.onCancel,
typeof ctx.fetch,
];
return "ok";
},
},
});
const result = await bash.execute("probe");
t.is(result.exitCode, 0);
t.true(seen.signal instanceof AbortSignal);
t.deepEqual(seen.helpers, ["function", "function", "function"]);
t.false(seen.signal.aborted);
});

test("cancel aborts hanging builtin, preserves state, next runs", async (t) => {
let aborted = false;
const bash = new Bash({
customBuiltins: {
hold: async (ctx: any) => {
await new Promise<void>((_, reject) => {
ctx.onCancel(() => {
aborted = true;
reject(new Error("cancelled"));
});
});
return "never";
},
},
});
await bash.execute(
"MARKER=kept; mkdir -p /tmp/cancel && echo data > /tmp/cancel/file.txt",
);
const pending = bash.execute("hold");
await new Promise((r) => setTimeout(r, 50));
bash.cancel();
const cancelled = await pending;
t.is(cancelled.exitCode, 130);
t.true(aborted);
const next = await bash.execute("echo next:$MARKER; cat /tmp/cancel/file.txt");
t.is(next.exitCode, 0);
t.true(next.stdout.includes("next:kept"));
t.true(next.stdout.includes("data"));
});

test("execution timeout aborts the builtin signal and reports exit 124", async (t) => {
let aborted = false;
const bash = new Bash({
timeoutMs: 300,
customBuiltins: {
hold: async (ctx: any) => {
// Records the signal but otherwise ignores it: the native deadline
// must still enforce exit 124 deterministically.
ctx.onCancel(() => {
aborted = true;
});
await new Promise((r) => setTimeout(r, 5000));
return "x";
},
},
});
const timedOut = await bash.execute("hold");
t.true(aborted);
t.is(timedOut.exitCode, 124);
const next = await bash.execute("echo alive");
t.is(next.exitCode, 0);
t.true(next.stdout.includes("alive"));
});

test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) => {
const http = await import("node:http");
let serverAborted = false;
const server = http.createServer((req, _res) => {
// Hold the response indefinitely; detect the client going away.
req.on("close", () => {
serverAborted = true;
});
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
t.teardown(() => server.close());
const port = (server.address() as any).port;
try {
const bash = new Bash({
customBuiltins: {
fetchHold: async (ctx: any) => {
// ctx.fetch combines the execution signal: cancel aborts the request.
await ctx.fetch(`http://127.0.0.1:${port}/hold`);
return "unreachable";
},
},
});
await bash.execute("MARKER=kept");
const start = Date.now();
const pending = bash.execute("fetchHold");
await new Promise((r) => setTimeout(r, 200));
bash.cancel(); // programmatic Ctrl+C
const cancelled = await pending;
const elapsed = Date.now() - start;
t.is(cancelled.exitCode, 130);
t.true(elapsed < 10000, `cancellation took ${elapsed}ms`);
for (let i = 0; i < 100 && !serverAborted; i++) {
await new Promise((r) => setTimeout(r, 20));
}
t.true(serverAborted, "server saw the connection abort");
const next = await bash.execute("echo next:$MARKER");
t.is(next.exitCode, 0);
t.true(next.stdout.includes("next:kept"));
} finally {
server.close();
}
});

// The timeout-mirror coercion (graceful exit 0 -> 124) was open-coded in
// `Bash.execute`'s no-caller-signal branch only. Three of the four async
// `executeNative` call sites skipped it, so the same race reported 124 from
// `Bash` without a signal and 0 from `BashTool`, or from `Bash` whenever the
// caller also passed a signal. These pin the contract on every path: an
// execution that exceeded its deadline is never reported as success.

/** Ignores cancellation entirely; the native deadline enforces 124. */
const holdForever = {
hold: async (ctx: any) => {
ctx.onCancel(() => {});
await new Promise((r) => setTimeout(r, 5000));
return "x";
},
};

/**
* Treats cancellation as a graceful finish. This is the shape that lets the
* JS-side mirror beat native enforcement: the abort resolves the builtin
* *successfully*, so the script can reach exit 0 before the native deadline
* lands, and only the coercion turns that back into 124.
*/
const gracefulOnCancel = {
hold: async (ctx: any) => {
await new Promise<void>((resolve) => ctx.onCancel(() => resolve()));
return "finished";
},
};

test("execution timeout reports 124 from BashTool, not just Bash", async (t) => {
const viaBash = await new Bash({
timeoutMs: 300,
customBuiltins: holdForever,
}).execute("hold");
const viaTool = await new BashTool({
timeoutMs: 300,
customBuiltins: holdForever,
}).execute("hold");
t.is(viaBash.exitCode, 124);
t.is(viaTool.exitCode, viaBash.exitCode);
});

test("a builtin resolving on abort cannot mask the deadline", async (t) => {
const viaBash = await new Bash({
timeoutMs: 200,
customBuiltins: gracefulOnCancel,
}).execute("hold");
const viaTool = await new BashTool({
timeoutMs: 200,
customBuiltins: gracefulOnCancel,
}).execute("hold");
t.not(viaBash.exitCode, 0);
t.not(viaTool.exitCode, 0);
t.is(viaBash.exitCode, 124);
t.is(viaTool.exitCode, 124);
});

test("a caller signal does not disable the timeout mirror", async (t) => {
// A signal that never aborts: its only effect is taking the caller-signal
// branch, which used to return executeNative() straight through.
const never = new AbortController();
const viaBash = await new Bash({
timeoutMs: 200,
customBuiltins: gracefulOnCancel,
}).execute("hold", { signal: never.signal });
const viaTool = await new BashTool({
timeoutMs: 200,
customBuiltins: gracefulOnCancel,
}).execute("hold", { signal: never.signal });
t.is(viaBash.exitCode, 124);
t.is(viaTool.exitCode, 124);
});
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,8 @@ for (const [label, create] of [

shell.cancel();
const result = shell.executeSync("echo after-error");
assert.equal(result.exitCode, 1);
// Explicit cancel observed by the next command: standard exit 130.
assert.equal(result.exitCode, 130);
assert.equal(result.error, "execution cancelled");
assert.equal(result.stdout, "");
});
Expand Down Expand Up @@ -246,7 +247,8 @@ for (const [label, create] of [

shell.cancel();
const result = await shell.execute("echo after-error");
assert.equal(result.exitCode, 1);
// Explicit cancel observed by the next command: standard exit 130.
assert.equal(result.exitCode, 130);
assert.equal(result.error, "execution cancelled");
assert.equal(result.stdout, "");
});
Expand Down
3 changes: 2 additions & 1 deletion crates/bashkit-js/__test__/streaming-commands.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ for (const [label, create] of [
await new Promise<void>(() => {});
},
});
t.is(result.exitCode, 1);
// Caller-initiated abort mid-execution is programmatic Ctrl+C: exit 130.
t.is(result.exitCode, 130);
t.is(result.error, "execution cancelled");
t.is(
(await shell.execute("echo recovered", { capture: 64 })).stdout,
Expand Down
6 changes: 4 additions & 2 deletions crates/bashkit-js/__test__/streaming-output.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ for (const [label, create] of [

shell.cancel();
const result = shell.executeSync("echo after-error");
t.is(result.exitCode, 1);
// Explicit cancel observed by the next command: standard exit 130.
t.is(result.exitCode, 130);
t.is(result.error, "execution cancelled");
t.is(result.stdout, "");
});
Expand Down Expand Up @@ -339,7 +340,8 @@ for (const [label, create] of [

shell.cancel();
const result = await shell.execute("echo after-error");
t.is(result.exitCode, 1);
// Explicit cancel observed by the next command: standard exit 130.
t.is(result.exitCode, 130);
t.is(result.error, "execution cancelled");
t.is(result.stdout, "");
});
Expand Down
70 changes: 64 additions & 6 deletions crates/bashkit-js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,20 @@ fn js_exec_result_from_error(err: impl ToString) -> ExecResult {
fn js_exec_result_from_bash_result(result: bashkit::Result<RustExecResult>) -> ExecResult {
match result {
Ok(result) => js_exec_result_from_rust(result),
Err(bashkit::Error::Cancelled) => {
// Programmatic Ctrl+C (`bash.cancel()`): standard exit 130,
// matching the interactive SIGINT contract.
let mut result = js_exec_result_from_error(bashkit::Error::Cancelled);
result.exit_code = 130;
result
}
Err(err @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_))) => {
// Execution timeout, wherever enforced (adapter-level budget or
// outer exec enforcement): standard exit 124.
let mut result = js_exec_result_from_error(err);
result.exit_code = 124;
result
}
Err(err) => js_exec_result_from_error(err),
}
}
Expand Down Expand Up @@ -3476,6 +3490,22 @@ type BuiltinTsfn = napi::threadsafe_function::ThreadsafeFunction<
/// plus a native VFS handle (surfaced to user code as `ctx.fs`), and resolves
/// with the stdout to emit. Exceptions/rejections surface as
/// stderr + exit-code-1 (real-shell semantics).
/// Map an [`ExecutionBudget`] interruption to a builtin result.
///
/// Timeouts surface as exit 124, matching the embedded runtimes and the
/// documented `timeoutMs` contract. Cancellation propagates as an error so
/// the native cancelled flag (and its sticky-until-`clearCancel` contract
/// for executions without custom builtins) is preserved.
fn map_budget_error(err: bashkit::Error) -> bashkit::Result<RustExecResult> {
match err {
bashkit::Error::Cancelled => Err(bashkit::Error::Cancelled),
other @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_)) => {
Ok(RustExecResult::err(format!("{}\n", other), 124))
}
other => Err(other),
}
}

struct JsCustomBuiltinAdapter {
name: String,
callback: Arc<BuiltinTsfn>,
Expand Down Expand Up @@ -3520,14 +3550,42 @@ impl Builtin for JsCustomBuiltinAdapter {

// Two-step await: first call_async returns the `Promise<String>`
// handle from JS, then awaiting the Promise resolves to its value.
let promise = match self.callback.call_async((request_str, fs_handle)).await {
Ok(p) => p,
Err(e) => return Ok(RustExecResult::err(format!("{}\n", e), 1)),
// Both steps run under the execution budget so `bash.cancel()` and
// execution timeouts abort the wait instead of hanging: timeouts
// surface as exit 124, cancellation propagates as an error.
let callback = self.callback.clone();
let dispatch = callback.call_async((request_str, fs_handle));
let promise = match ctx.run_budgeted(dispatch).await {
Ok(Ok(p)) => p,
Ok(Err(e)) => {
// A callback that fails *because* the execution was
// cancelled or timed out (the natural `onCancel` reject
// pattern) reports the interruption, not a builtin failure.
if let Err(budget_err) = ctx.run_budgeted(async {}).await {
return map_budget_error(budget_err);
}
return Ok(RustExecResult::err(format!("{}\n", e), 1));
}
Err(e) => return map_budget_error(e),
};
let output = match ctx.run_budgeted(promise).await {
Ok(Ok(stdout)) => RustExecResult::ok(stdout),
Ok(Err(e)) => {
// Same interruption check as the dispatch arm above; falls
// through to a builtin failure only when the budget is clear.
if let Err(budget_err) = ctx.run_budgeted(async {}).await {
return map_budget_error(budget_err);
}
RustExecResult::err(format!("{}\n", e), 1)
}
Err(e) => return map_budget_error(e),
};
match promise.await {
Ok(stdout) => Ok(RustExecResult::ok(stdout)),
Err(e) => Ok(RustExecResult::err(format!("{}\n", e), 1)),
// Cancellation/timeout wins even when the JS callback resolves
// gracefully (e.g. it caught the AbortSignal and returned output).
if let Err(e) = ctx.run_budgeted(async {}).await {
return map_budget_error(e);
}
Ok(output)
}
}

Expand Down
Loading
Loading