mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(opencode): restore process env keys on transport dispose (#4430)
## Description
`installHeadroomTransport` sets `NODE_OPTIONS` (hook-shim `--import`),
`HEADROOM_OPENCODE_TRANSPORT_PROXY_URL` and
`HEADROOM_OPENCODE_EXCLUDE_HOSTS` in `process.env`, but its dispose only
restored `fetch`/`http`/`https`/`http2`/`child_process`. After dispose,
the parent and every child it spawned kept the shim preload and proxy
URL. The transport now snapshots those three keys on the first install
and restores them when the last install is disposed.
Fixes #4428
## 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`: `TransportState.originalEnv`
snapshot taken at first install (before `installProcessEnv`);
`restoreProcessEnv` runs in `uninstallHeadroomTransport` when `refs`
reaches 0. A nested dispose (refs still above 0) leaves the env alone.
- `plugins/opencode/src/transport.test.ts`: new test for the restore,
including the nested-dispose case and a pre-existing
`NODE_OPTIONS`/exclude-hosts value. Two existing tests (`prefers the
excludeHosts option over ...`, `clears a pre-existing ... when
excludeHosts is explicitly empty`) restored the env before disposing in
`finally`; they now dispose first, otherwise the new restore put the
earlier value back after their own cleanup and three later session-token
tests failed.
- `headroom/providers/opencode/_dist/index.js`,
`headroom/providers/opencode/hook-shim/handler.js`: rebuilt with `npm
run build:standalone` (the CI `cmp` check requires the committed bundles
to match the source).
## Testing
- [x] Unit tests pass (`pytest`)
- [ ] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
(The unit tests are `vitest` in `plugins/opencode`; `npm run typecheck`
also passes. No Python file changed, so ruff and mypy were not run.)
### Test Output
```text
# plugins/opencode, new test with the transport.ts change reverted
FAIL src/transport.test.ts > Headroom OpenCode transport > restores the process env keys it set once the last install is disposed
AssertionError: expected '--trace-warnings --import=file:///var…' to be '--trace-warnings'
Tests 1 failed | 57 passed (58)
# with the fix
Test Files 3 passed (3)
Tests 58 passed (58)
$ npm run typecheck # tsc --noEmit, no output
```
## Real Behavior Proof
- Environment: Ubuntu on WSL2, Node v24.22.1, upstream/main e995eb9f
plus this commit. The committed bundle
(`headroom/providers/opencode/_dist/index.js`) imported in Node, a local
stub HTTP server on 127.0.0.1:18930 as the proxy.
- Exact command / steps: `NODE_OPTIONS` set to `--trace-warnings`; `node
proof18.mjs <_dist/index.js>` imports the bundle, calls
`default.server(...)` with `proxyUrl=http://127.0.0.1:18930`, spawns a
child Node process that prints its env, sends one `fetch` to
`https://api.anthropic.com/v1/messages` (the stub log shows it arrived),
calls `hooks.dispose()`, then spawns a child again.
- Observed result: before (upstream/main bundle), after dispose the
child still has `NODE_OPTIONS` with `--import=.../hook-shim/handler.js`,
the proxy URL and `EXCLUDE=example.invalid`. After (this commit), the
child and the parent have `NODE_OPTIONS=--trace-warnings` and the other
two unset. Full output below.
- Not tested: a real OpenCode 1.x or 2.x host; Windows or macOS; a host
that changes one of the three variables itself between install and
dispose (the restore would overwrite that value with the pre-install
one).
Before (upstream/main `_dist`):
```text
while installed child env: {"NODE_OPTIONS":"--trace-warnings --import=file://<before>/headroom/providers/opencode/hook-shim/handler.js","PROXY":"http://127.0.0.1:18930","EXCLUDE":"example.invalid"}
stub saw: ["POST /v1/messages x-headroom-base-url=https://api.anthropic.com"]
fetch restored: true
after dispose child env: {"NODE_OPTIONS":"--trace-warnings --import=file://<before>/headroom/providers/opencode/hook-shim/handler.js","PROXY":"http://127.0.0.1:18930","EXCLUDE":"example.invalid"}
parent env after dispose: {"NODE_OPTIONS":"--trace-warnings --import=file://<before>/headroom/providers/opencode/hook-shim/handler.js","PROXY":"http://127.0.0.1:18930","EXCLUDE":"example.invalid"}
```
After (this commit):
```text
while installed child env: {"NODE_OPTIONS":"--trace-warnings --import=file://<after>/headroom/providers/opencode/hook-shim/handler.js","PROXY":"http://127.0.0.1:18930","EXCLUDE":"example.invalid"}
stub saw: ["POST /v1/messages x-headroom-base-url=https://api.anthropic.com"]
fetch restored: true
after dispose child env: {"NODE_OPTIONS":"--trace-warnings","PROXY":null,"EXCLUDE":null}
parent env after dispose: {"NODE_OPTIONS":"--trace-warnings","PROXY":null,"EXCLUDE":null}
```
## Runtime Rollout Safety
- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: yes, narrowly: after the OpenCode
plugin is disposed, `process.env` no longer carries the shim `--import`
and proxy variables, so children started afterwards are no longer routed
through the proxy
- Kill switch / disable path: none needed; the variables are only
touched while the transport is installed
- 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
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Screenshots (if applicable)
N/A
## Additional Notes
N/A items: documentation (no doc describes the leaked variables),
ruff/mypy (no Python changed). Design choice to review: the snapshot is
taken once, at the first install, and restored only when the last nested
install is disposed, matching how the other patches are restored.
Produced with AI assistance (Claude Code) operated by me (HetCreep); the
reproduction was run on my machine on 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/4430"
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 Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
JerrettDavis
parent
760c05e1b0
commit
d17bac8d64
@@ -19835,6 +19835,19 @@ function withShimEnv(env, proxyUrl, excludeHosts) {
|
||||
}
|
||||
return nextEnv;
|
||||
}
|
||||
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"];
|
||||
function snapshotProcessEnv() {
|
||||
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
|
||||
}
|
||||
function restoreProcessEnv(saved) {
|
||||
for (const key of PROCESS_ENV_KEYS) {
|
||||
if (saved[key] === void 0) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = saved[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
function installProcessEnv(proxyUrl, excludeHosts) {
|
||||
process.env[PROXY_ENV] = proxyUrl;
|
||||
withExcludeHostsEnv(process.env, excludeHosts);
|
||||
@@ -20171,7 +20184,8 @@ function installHeadroomTransport(options) {
|
||||
originalChildSpawn: childProcess.spawn,
|
||||
originalChildExec: childProcess.exec,
|
||||
originalChildExecFile: childProcess.execFile,
|
||||
originalChildFork: childProcess.fork
|
||||
originalChildFork: childProcess.fork,
|
||||
originalEnv: snapshotProcessEnv()
|
||||
};
|
||||
setState(state);
|
||||
installProcessEnv(options.proxyUrl, excludeHosts);
|
||||
@@ -20215,6 +20229,7 @@ function uninstallHeadroomTransport() {
|
||||
childProcess.exec = state.originalChildExec;
|
||||
childProcess.execFile = state.originalChildExecFile;
|
||||
childProcess.fork = state.originalChildFork;
|
||||
restoreProcessEnv(state.originalEnv);
|
||||
syncBuiltinESMExports();
|
||||
setState(void 0);
|
||||
}
|
||||
|
||||
@@ -50,6 +50,19 @@ function withShimEnv(env, proxyUrl2, excludeHosts) {
|
||||
}
|
||||
return nextEnv;
|
||||
}
|
||||
var PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"];
|
||||
function snapshotProcessEnv() {
|
||||
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
|
||||
}
|
||||
function restoreProcessEnv(saved) {
|
||||
for (const key of PROCESS_ENV_KEYS) {
|
||||
if (saved[key] === void 0) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = saved[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
function installProcessEnv(proxyUrl2, excludeHosts) {
|
||||
process.env[PROXY_ENV] = proxyUrl2;
|
||||
withExcludeHostsEnv(process.env, excludeHosts);
|
||||
@@ -379,7 +392,8 @@ function installHeadroomTransport(options) {
|
||||
originalChildSpawn: childProcess.spawn,
|
||||
originalChildExec: childProcess.exec,
|
||||
originalChildExecFile: childProcess.execFile,
|
||||
originalChildFork: childProcess.fork
|
||||
originalChildFork: childProcess.fork,
|
||||
originalEnv: snapshotProcessEnv()
|
||||
};
|
||||
setState(state);
|
||||
installProcessEnv(options.proxyUrl, excludeHosts);
|
||||
@@ -423,6 +437,7 @@ function uninstallHeadroomTransport() {
|
||||
childProcess.exec = state.originalChildExec;
|
||||
childProcess.execFile = state.originalChildExecFile;
|
||||
childProcess.fork = state.originalChildFork;
|
||||
restoreProcessEnv(state.originalEnv);
|
||||
syncBuiltinESMExports();
|
||||
setState(void 0);
|
||||
}
|
||||
|
||||
@@ -476,6 +476,39 @@ describe("Headroom OpenCode transport", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("restores the process env keys it set once the last install is disposed", () => {
|
||||
const keys = ["NODE_OPTIONS", "HEADROOM_OPENCODE_TRANSPORT_PROXY_URL", "HEADROOM_OPENCODE_EXCLUDE_HOSTS"] as const;
|
||||
const saved = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
|
||||
|
||||
try {
|
||||
process.env.NODE_OPTIONS = "--trace-warnings";
|
||||
delete process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL;
|
||||
process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS = "keep.example.com";
|
||||
|
||||
const first = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["a.example.com"] });
|
||||
const second = installHeadroomTransport({ proxyUrl: "http://127.0.0.1:8787/v1", excludeHosts: ["a.example.com"] });
|
||||
expect(process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
|
||||
// A nested dispose keeps the env: the transport is still installed.
|
||||
first();
|
||||
expect(process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
|
||||
second();
|
||||
expect(process.env.NODE_OPTIONS).toBe("--trace-warnings");
|
||||
expect(process.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBeUndefined();
|
||||
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("keep.example.com");
|
||||
} finally {
|
||||
for (const key of keys) {
|
||||
if (saved[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = saved[key];
|
||||
}
|
||||
}
|
||||
uninstallHeadroomTransport();
|
||||
}
|
||||
});
|
||||
|
||||
it("skips the shim preload when the bundle ships without it (#2798)", () => {
|
||||
const originalNodeOptions = process.env.NODE_OPTIONS;
|
||||
const originalSpawn = childProcess.spawn;
|
||||
@@ -772,6 +805,7 @@ describe("Headroom OpenCode transport", () => {
|
||||
expect(fetchMock.mock.calls[1][0]).toEqual(new URL("http://127.0.0.1:8787/v1/messages"));
|
||||
expect(process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS).toBe("opencode.ai");
|
||||
} finally {
|
||||
uninstallHeadroomTransport();
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalExclude === undefined) {
|
||||
delete process.env.HEADROOM_OPENCODE_EXCLUDE_HOSTS;
|
||||
@@ -871,6 +905,8 @@ describe("Headroom OpenCode transport", () => {
|
||||
expect(options.env.HEADROOM_OPENCODE_TRANSPORT_PROXY_URL).toBe("http://127.0.0.1:8787/v1");
|
||||
}
|
||||
} finally {
|
||||
// Dispose first: uninstall now restores the env it saved at install time.
|
||||
uninstallHeadroomTransport();
|
||||
globalThis.fetch = originalFetch;
|
||||
childProcess.spawn = originalSpawn;
|
||||
if (originalExclude === undefined) {
|
||||
|
||||
@@ -51,6 +51,7 @@ interface TransportState {
|
||||
originalChildExec: ChildExec;
|
||||
originalChildExecFile: ChildExecFile;
|
||||
originalChildFork: ChildFork;
|
||||
originalEnv: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
interface GlobalWithHeadroomTransport {
|
||||
@@ -120,6 +121,23 @@ function withShimEnv(
|
||||
return nextEnv;
|
||||
}
|
||||
|
||||
// installProcessEnv writes these process-wide keys; uninstall puts them back.
|
||||
const PROCESS_ENV_KEYS = [PROXY_ENV, EXCLUDE_HOSTS_ENV, "NODE_OPTIONS"] as const;
|
||||
|
||||
function snapshotProcessEnv(): Record<string, string | undefined> {
|
||||
return Object.fromEntries(PROCESS_ENV_KEYS.map((key) => [key, process.env[key]]));
|
||||
}
|
||||
|
||||
function restoreProcessEnv(saved: Record<string, string | undefined>): void {
|
||||
for (const key of PROCESS_ENV_KEYS) {
|
||||
if (saved[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = saved[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function installProcessEnv(proxyUrl: string, excludeHosts: string[]): void {
|
||||
process.env[PROXY_ENV] = proxyUrl;
|
||||
withExcludeHostsEnv(process.env, excludeHosts);
|
||||
@@ -562,6 +580,7 @@ export function installHeadroomTransport(options: InstallOptions): () => void {
|
||||
originalChildExec: childProcess.exec,
|
||||
originalChildExecFile: childProcess.execFile,
|
||||
originalChildFork: childProcess.fork,
|
||||
originalEnv: snapshotProcessEnv(),
|
||||
};
|
||||
|
||||
setState(state);
|
||||
@@ -611,6 +630,7 @@ export function uninstallHeadroomTransport(): void {
|
||||
childProcess.exec = state.originalChildExec;
|
||||
childProcess.execFile = state.originalChildExecFile;
|
||||
childProcess.fork = state.originalChildFork;
|
||||
restoreProcessEnv(state.originalEnv);
|
||||
syncBuiltinESMExports();
|
||||
setState(undefined);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user