test(mcp): restore os.homedir spy after each test to prevent cross-file leak
Issue for this PR
Closes #1042
Type of change
- Bug fix
- New feature
- Refactor / code improvement
- Documentation
What does this PR do?
The beforeEach in packages/opencode/test/mcp/lifecycle.test.ts:250 installs spyOn(os, "homedir").mockImplementation(...) and returns a fresh mkdtempSync(... "mcp-lifecycle-home-...") on every call. There is no matching afterEach that restores the spy. When bun runs the full test suite, the spy persists past this file into any downstream file in the same worker process. The next test that calls os.homedir() gets a different random path per invocation — inside a single expect().toEqual(...) call, the value returned to the "actual" side and the value used to build the "expected" side can differ, and the assertion fails on paths that visibly contain the mcp-lifecycle-home- prefix from this file.
The most visible casualty is test/permission/next.test.ts, where 6 tilde / $HOME-expansion tests fail intermittently on CI:
error: expect(received).toEqual(expected)
[
{
"action": "allow",
- "pattern": "/tmp/mcp-lifecycle-home-Zz7Y0f/projects/*",
+ "pattern": "/tmp/mcp-lifecycle-home-VvysFV/projects/*",
"permission": "external_directory",
}
]
The failure is file-order dependent — it passes in isolation and only surfaces when the full suite runs in the leaking order.
Fix: import afterEach from bun:test and add afterEach(() => mock.restore()) right after the beforeEach block in lifecycle.test.ts. Blanket mock.restore() tears down the os.homedir spy (and any other spy installed during a test) between tests, so the mock cannot escape the file boundary. This matches the pattern already used elsewhere in the suite and keeps the fix a single import addition plus a 3-line hook.
How did you verify your code works?
bun test test/mcp/lifecycle.test.ts— 31 pass, 0 fail (fix's own file still green)bun test test/permission/next.test.ts— 80 pass, 0 fail (previously affected file green in isolation, same as before the fix)bun test test/mcp/lifecycle.test.ts test/permission/next.test.ts— 111 pass, 0 fail (both files together in one bun invocation — the shared-worker scenario that reproduced the leak)bun run typecheck— clean (exit 0)bun run script/upstream/analyze.ts --markers --base origin/main --strict— cleanbun run script/upstream/analyze.ts --branding— 0 leaks
Screenshots / recordings
n/a — no UI change.
Checklist
- I have tested my changes locally
- I have not included unrelated changes in this PR
Summary by cubic
Fix flaky tests by restoring the os.homedir spy after each test in packages/opencode/test/mcp/lifecycle.test.ts. Adds afterEach(() => mock.restore()) from bun:test to stop cross-file leaks that broke tilde/$HOME expansion checks in test/permission/next.test.ts.
Summary by CodeRabbit
- Tests
- Improved test isolation by automatically restoring mocks after each test.
- Prevented environment-related assertions from being affected by previous tests.