fix(opencode): keep child process options when the args slot is null or undefined (#4748)

## Description

Part of #4744

The OpenCode transport wraps `spawn`, `fork`, `exec` and `execFile` to
inject an `env`. It guessed the options index with
`Array.isArray(args[1]) ? 2 : 1` and spliced the injected object in
whenever that slot was not an object. For `spawn(cmd, undefined, { cwd
})` and `fork(mod, null, opts)` the injected object landed in Node's
args slot, Node read it as the options, and the caller's `cwd`, `stdio`
and `shell` were lost. For `exec(cmd, undefined, cb)` and
`execFile(file, args, null, cb)` the callback ended up past the last
parameter Node reads and was never called. Both shapes are valid Node
signatures.

This PR finds the options slot after an omitted, undefined or null
`args`, and replaces an undefined or null options slot instead of
inserting beside it. Plain argument shapes are unchanged.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `plugins/opencode/src/transport.ts`: new `optionsIndexAfterArgs` used
by the `spawn`, `execFile` and `fork` wrappers (`exec` has no args slot
and keeps index 1). `injectOptionsEnv` replaces an undefined or null
slot that is inside the argument list instead of inserting next to it.
- `plugins/opencode/src/transport.test.ts`: a `describe` block that
starts real children (a small script that prints its `cwd` and the
injected proxy variable): `spawn`/`fork` with `undefined` and `null`
args and a `cwd`, `exec`/`execFile` with `undefined` and `null` options
and a callback, `execFile(file, null, cb)`, and eight plain shapes that
must keep working. The block restores the real `child_process` functions
before each test, because an earlier test in the file ("skips the shim
preload...") restores `spawn` before it calls
`uninstallHeadroomTransport()`, which puts its mock back; that left
`child_process.spawn` mocked for the rest of the file. I did not change
that test.

## Testing

- [ ] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

This is a TypeScript change in `plugins/opencode`, so the Python checks
above do not apply. The package's own checks were run instead: `vitest
run` and `tsc --noEmit` (`node node_modules/@typescript/native/bin/tsc
--noEmit`, no output). The package has no lint or format script and the
root ruff config covers Python only, so none was run.

### Test Output

Fail before (`transport.ts`, `plugin.ts`, `retrieve.ts` from
`origin/main` `1da8930a`, new tests kept; `npx vitest run` in
`plugins/opencode`, Ubuntu on WSL2, Node v24.22.2):

```text
FAIL spawn(cmd, undefined, { cwd }) keeps cwd and still injects the env     Error: spawn "<node>" "<probe.cjs>" ENOENT
FAIL spawn(cmd, null, { cwd }) keeps cwd and still injects the env          Error: spawn "<node>" "<probe.cjs>" ENOENT
FAIL fork(module, undefined, { cwd }) keeps cwd and still injects the env   Error: child printed ""
FAIL fork(module, null, { cwd }) keeps cwd and still injects the env        Error: child printed ""
FAIL exec(cmd, undefined, callback) still calls the callback                Error: callback was never called
FAIL exec(cmd, null, callback) still calls the callback                     Error: callback was never called
FAIL execFile(file, args, undefined, callback) still calls the callback     Error: callback was never called
FAIL execFile(file, args, null, callback) still calls the callback          Error: callback was never called
FAIL execFile(file, null, callback) and execFile(file, callback) ...        Error: callback was never called
 Test Files  1 failed | 3 passed (4)
      Tests  9 failed | 74 passed (83)
```

Pass after (this branch):

```text
 Test Files  4 passed (4)
      Tests  83 passed (83)
```

## Real Behavior Proof

- Environment: Ubuntu on WSL2 (Windows 11 host), Node v24.22.2, vitest
and TypeScript from `plugins/opencode/package-lock.json` (`npm ci
--ignore-scripts`), real child processes, no network.
- Exact command / steps: `npx vitest run` in `plugins/opencode`. Each
new test installs the transport (shim preload off, as a checkout has no
`dist/`), makes the call in its title with a probe script that prints
`process.cwd()` and `HEADROOM_OPENCODE_TRANSPORT_PROXY_URL`, and checks
the cwd and the env or that the callback fires.
- Observed result: see Test Output; the nine tests fail on `origin/main`
and the 83 tests of the package pass here.
- Not tested: the real OpenCode host; Windows (the `shell: true` and
quoting path of the test commands was only run on Linux); `fork` with an
`execArgv`/IPC channel in use.

## Runtime Rollout Safety

- Rollout-managed feature(s): none changed.
- Minimum rollout channel: n/a (no new feature)
- Stable/default behavior changed: yes, narrowly: calls with an explicit
`undefined`/`null` args or options now keep their own options (and
`exec`/`execFile` callbacks fire) while the env is still injected. Plain
shapes behave as before.
- Kill switch / disable path: none added.
- Unsafe override required: no
- Qualification impact: none expected.
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes (see
Testing)
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

- Not in this PR (one topic): the wrapped `exec` and `execFile` lose
`util.promisify.custom`, so `promisify(child_process.exec)(cmd)`
resolves to a string instead of `{ stdout, stderr }`. It is described in
the linked issue.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
tests and proof above were run on my machine against a clone of the
repository.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4748"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
HetCreep
2026-11-12 22:47:09 -06:00
committed by GitHub
co-authored by Claude Sonnet 5.5 JD Davis
parent e602e4cfb5
commit 9f2cc01786
4 changed files with 169 additions and 14 deletions
+8 -4
View File
@@ -19882,7 +19882,7 @@ function injectOptionsEnv(args, optionIndex, state) {
if (process.platform === "win32" && existing.windowsHide === void 0) {
existing.windowsHide = true;
}
if (isOptions(nextArgs[optionIndex])) {
if (isOptions(nextArgs[optionIndex]) || nextArgs[optionIndex] == null && optionIndex < nextArgs.length) {
nextArgs[optionIndex] = existing;
} else {
nextArgs.splice(optionIndex, 0, existing);
@@ -19892,13 +19892,17 @@ function injectOptionsEnv(args, optionIndex, state) {
}
return nextArgs;
}
function optionsIndexAfterArgs(args) {
const params = typeof args.at(-1) === "function" ? args.slice(0, -1) : args;
return Array.isArray(params[1]) || params.length > 2 && params[1] == null ? 2 : 1;
}
function wrapSpawn(originalSpawn) {
return function headroomSpawn(...args) {
const state = getState();
if (!state) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
@@ -19917,7 +19921,7 @@ function wrapExecFile(originalExecFile) {
if (!state) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
@@ -19927,7 +19931,7 @@ function wrapFork(originalFork) {
if (!state) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
@@ -97,7 +97,7 @@ function injectOptionsEnv(args, optionIndex, state) {
if (process.platform === "win32" && existing.windowsHide === void 0) {
existing.windowsHide = true;
}
if (isOptions(nextArgs[optionIndex])) {
if (isOptions(nextArgs[optionIndex]) || nextArgs[optionIndex] == null && optionIndex < nextArgs.length) {
nextArgs[optionIndex] = existing;
} else {
nextArgs.splice(optionIndex, 0, existing);
@@ -107,13 +107,17 @@ function injectOptionsEnv(args, optionIndex, state) {
}
return nextArgs;
}
function optionsIndexAfterArgs(args) {
const params = typeof args.at(-1) === "function" ? args.slice(0, -1) : args;
return Array.isArray(params[1]) || params.length > 2 && params[1] == null ? 2 : 1;
}
function wrapSpawn(originalSpawn) {
return function headroomSpawn(...args) {
const state = getState();
if (!state) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
};
}
@@ -132,7 +136,7 @@ function wrapExecFile(originalExecFile) {
if (!state) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
};
}
@@ -142,7 +146,7 @@ function wrapFork(originalFork) {
if (!state) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
};
}
+139 -2
View File
@@ -1,9 +1,11 @@
import childProcess from "node:child_process";
import childProcess, { type ChildProcess } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import http2 from "node:http2";
import https from "node:https";
import { afterEach, describe, expect, it, vi } from "vitest";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { installHeadroomTransport, uninstallHeadroomTransport } from "./transport.js";
@@ -1309,6 +1311,141 @@ describe("Headroom OpenCode transport", () => {
globalThis.fetch = originalFetch;
});
describe("child_process wrappers with omitted or null args/options slots", () => {
// Real children, not mocks: the bug is that Node reads the injected env
// object from the wrong parameter, so only a real call shows it. The shim
// preload is switched off because the checkout has no dist/ for it to load.
function probeScript(): { dir: string; script: string; run: string } {
const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "headroom-cp-")));
const script = path.join(dir, "probe.cjs");
fs.writeFileSync(
script,
"process.stdout.write(JSON.stringify({cwd: process.cwd(), proxy: process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL}));",
);
return { dir, script, run: `"${process.execPath}" "${script}"` };
}
function collect(child: ChildProcess): Promise<{ cwd: string; proxy?: string }> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("child did not finish")), 5000);
let out = "";
child.stdout?.on("data", (chunk) => {
out += chunk;
});
child.on("error", (err) => {
clearTimeout(timer);
reject(err);
});
child.on("close", () => {
clearTimeout(timer);
try {
resolve(JSON.parse(out));
} catch {
reject(new Error(`child printed ${JSON.stringify(out)}`));
}
});
});
}
function viaCallback(
call: (cb: (err: Error | null, stdout: string | Buffer) => void) => unknown,
): Promise<{ cwd: string; proxy?: string }> {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("callback was never called")), 3000);
call((err, stdout) => {
clearTimeout(timer);
if (err) reject(err);
else resolve(JSON.parse(String(stdout)));
});
});
}
const cp = childProcess as unknown as Record<string, (...args: unknown[]) => any>;
// Earlier tests in this file can leave a mock behind in child_process, so
// start from the functions Node loaded.
const real = {
spawn: childProcess.spawn,
exec: childProcess.exec,
execFile: childProcess.execFile,
fork: childProcess.fork,
};
beforeEach(() => {
Object.assign(childProcess, real);
});
function install(): void {
vi.spyOn(fs, "existsSync").mockReturnValue(false);
installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1" });
}
const plainShapes: Array<[string, (p: { dir: string; script: string; run: string }) => Promise<{ cwd: string }>]> = [
["spawn(file, [args], { cwd })", (p) => collect(cp.spawn(process.execPath, [p.script], { cwd: p.dir }))],
["spawn(cmd, { cwd, shell })", (p) => collect(cp.spawn(p.run, { cwd: p.dir, shell: true }))],
["exec(cmd, { cwd }, cb)", (p) => viaCallback((cb) => cp.exec(p.run, { cwd: p.dir }, cb))],
["exec(cmd, cb)", (p) => viaCallback((cb) => cp.exec(p.run, cb)).then((r) => ({ ...r, cwd: p.dir }))],
["execFile(file, [args], { cwd }, cb)", (p) => viaCallback((cb) => cp.execFile(process.execPath, [p.script], { cwd: p.dir }, cb))],
["execFile(file, [args], cb)", (p) => viaCallback((cb) => cp.execFile(process.execPath, [p.script], cb)).then((r) => ({ ...r, cwd: p.dir }))],
["fork(module, [args], { cwd })", (p) => collect(cp.fork(p.script, [], { cwd: p.dir, silent: true }))],
["fork(module, { cwd })", (p) => collect(cp.fork(p.script, { cwd: p.dir, silent: true }))],
];
it.each(plainShapes)("plain shape %s is unchanged", async (_name, call) => {
const probe = probeScript();
install();
const seen = await call(probe);
expect(seen.cwd).toBe(probe.dir);
});
it.each([undefined, null])("spawn(cmd, %s, { cwd }) keeps cwd and still injects the env", async (args) => {
const { dir, run } = probeScript();
install();
const seen = await collect(cp.spawn(run, args, { cwd: dir, shell: true }));
expect(seen.cwd).toBe(dir);
expect(seen.proxy).toBe("http://127.0.0.1:8787/v1");
});
it.each([undefined, null])("fork(module, %s, { cwd }) keeps cwd and still injects the env", async (args) => {
const { dir, script } = probeScript();
install();
const seen = await collect(cp.fork(script, args, { cwd: dir, silent: true }));
expect(seen.cwd).toBe(dir);
expect(seen.proxy).toBe("http://127.0.0.1:8787/v1");
});
it.each([undefined, null])("exec(cmd, %s, callback) still calls the callback", async (options) => {
const { run } = probeScript();
install();
const seen = await viaCallback((cb) => cp.exec(run, options, cb));
expect(seen.proxy).toBe("http://127.0.0.1:8787/v1");
});
it.each([undefined, null])("execFile(file, args, %s, callback) still calls the callback", async (options) => {
const { script } = probeScript();
install();
const seen = await viaCallback((cb) => cp.execFile(process.execPath, [script], options, cb));
expect(seen.proxy).toBe("http://127.0.0.1:8787/v1");
});
it("execFile(file, null, callback) and execFile(file, callback) still call the callback", async () => {
install();
for (const call of [
(cb: any) => cp.execFile(process.execPath, null, cb),
(cb: any) => cp.execFile(process.execPath, cb),
]) {
// no script: node starts, reads the closed stdin and exits; only the callback matters
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("callback was never called")), 3000);
const child = call(() => {
clearTimeout(timer);
resolve();
});
child.stdin?.end();
});
}
});
});
it.each(["", "127.0.0.1:8787"])("leaves all traffic alone when the proxy URL is unusable (%j)", async (proxyUrl) => {
const originalFetch = globalThis.fetch;
const fetchMock = vi.fn(async (..._args: FetchCall) => new Response("ok"));
+14 -4
View File
@@ -181,7 +181,9 @@ function injectOptionsEnv(args: unknown[], optionIndex: number, state: Transport
existing.windowsHide = true;
}
if (isOptions(nextArgs[optionIndex])) {
// An explicit undefined/null in the options slot is replaced, not pushed
// right: inserting would move the callback past Node's last parameter.
if (isOptions(nextArgs[optionIndex]) || (nextArgs[optionIndex] == null && optionIndex < nextArgs.length)) {
nextArgs[optionIndex] = existing;
} else {
nextArgs.splice(optionIndex, 0, existing);
@@ -193,13 +195,21 @@ function injectOptionsEnv(args: unknown[], optionIndex: number, state: Transport
return nextArgs;
}
// Node takes (file, args?, options?, callback?) where args and options may each
// be omitted, undefined or null, so `spawn(cmd, undefined, opts)` keeps its
// options in the third slot.
function optionsIndexAfterArgs(args: unknown[]): number {
const params = typeof args.at(-1) === "function" ? args.slice(0, -1) : args;
return Array.isArray(params[1]) || (params.length > 2 && params[1] == null) ? 2 : 1;
}
function wrapSpawn(originalSpawn: ChildSpawn): ChildSpawn {
return function headroomSpawn(this: unknown, ...args: unknown[]) {
const state = getState();
if (!state) {
return Reflect.apply(originalSpawn, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalSpawn, this, injectOptionsEnv(args, optionIndex, state));
} as ChildSpawn;
}
@@ -220,7 +230,7 @@ function wrapExecFile(originalExecFile: ChildExecFile): ChildExecFile {
if (!state) {
return Reflect.apply(originalExecFile, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalExecFile, this, injectOptionsEnv(args, optionIndex, state));
} as ChildExecFile;
}
@@ -231,7 +241,7 @@ function wrapFork(originalFork: ChildFork): ChildFork {
if (!state) {
return Reflect.apply(originalFork, this, args);
}
const optionIndex = Array.isArray(args[1]) ? 2 : 1;
const optionIndex = optionsIndexAfterArgs(args);
return Reflect.apply(originalFork, this, injectOptionsEnv(args, optionIndex, state));
} as ChildFork;
}