Skip to content

Commit b6a1e24

Browse files
committed
test(runner): reset console routing between non-isolated files
enableConsoleCapture() replaces every console method with a forwarder and routeLogsToStderr()/`--json` mode latch loggingState.forceConsoleToStderr, which production only unwinds at process exit. loggingState is keyed off globalThis so it survives vi.resetModules(), so a shared Vitest worker carried both into the next file: the inherited forwarder writes to process.stderr and the next file's console.error spy records nothing. That is the source of the order-dependent `src/entry.run-main.test.ts > keeps expected conditions at exit 1` flake in shard core-unit-src-security-2 — it failed only on workers that ran src/mcp/codex-supervision-tools-serve.test.ts (serveCodexSupervisionToolsMcp -> routeLogsToStderr) first. Restore the worker's baseline console methods and logging state in the runner's existing cross-file cleanup, and drop the two consumer-side workarounds that were compensating for it.
1 parent 41acede commit b6a1e24

4 files changed

Lines changed: 63 additions & 11 deletions

File tree

‎src/entry.run-main.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { describe, expect, it, vi } from "vitest";
22
import { ExpectedCliError } from "./cli/failure-output.js";
33
import { runMainOrRootHelp } from "./entry.js";
4-
import { enableConsoleCapture } from "./logging.js";
54

65
describe("entry run-main boundary", () => {
76
it("retains JSON console routing through process finalization", async () => {
@@ -26,7 +25,6 @@ describe("entry run-main boundary", () => {
2625
humanOutput: message,
2726
machineOutput: message,
2827
});
29-
enableConsoleCapture();
3028
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
3129
process.exitCode = undefined;
3230

‎src/mcp/codex-supervision-tools-serve.test.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
// Codex supervision MCP tests cover the retired Supervisor command bridge.
22
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
33
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
4-
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { beforeEach, describe, expect, it, vi } from "vitest";
55
import type { AnyAgentTool } from "../agents/tools/common.js";
6-
import { loggingState } from "../logging/state.js";
76
import {
87
createCodexSupervisionToolsMcpServer,
98
serveCodexSupervisionToolsMcp,
@@ -49,7 +48,6 @@ const TOOL_NAMES = [
4948
"codex_session_send",
5049
"codex_session_interrupt",
5150
] as const;
52-
let originalForceConsoleToStderr = false;
5351

5452
function createTools(): AnyAgentTool[] {
5553
return TOOL_NAMES.map(
@@ -66,18 +64,13 @@ function createTools(): AnyAgentTool[] {
6664

6765
describe("createCodexSupervisionToolsMcpServer", () => {
6866
beforeEach(() => {
69-
originalForceConsoleToStderr = loggingState.forceConsoleToStderr;
7067
ensureStandalonePluginToolRegistryLoadedMock.mockClear();
7168
resolvePluginToolsMock.mockReset();
7269
resolvePluginToolsMock.mockReturnValue([]);
7370
connectToolsMcpServerToStdioMock.mockClear();
7471
disposeRegisteredAgentHarnessesMock.mockClear();
7572
});
7673

77-
afterEach(() => {
78-
loggingState.forceConsoleToStderr = originalForceConsoleToStderr;
79-
});
80-
8174
it("fails closed when the external Codex plugin tools are unavailable", () => {
8275
expect(() =>
8376
createCodexSupervisionToolsMcpServer({

‎test/non-isolated-runner.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ function fixtureFiles(): Record<string, string> {
4848
path.join(repoRoot, "src", "infra", "agent-run-registry.ts"),
4949
);
5050
const agentEventsPath = JSON.stringify(path.join(repoRoot, "src", "infra", "agent-events.ts"));
51+
const loggingConsolePath = JSON.stringify(path.join(repoRoot, "src", "logging", "console.ts"));
52+
const loggingStatePath = JSON.stringify(path.join(repoRoot, "src", "logging", "state.ts"));
5153

5254
return {
5355
"01-dep.ts": 'export function flavor(): string {\n return "real";\n}\n',
@@ -161,6 +163,39 @@ function fixtureFiles(): Record<string, string> {
161163
"});",
162164
"",
163165
].join("\n"),
166+
"06-a-console-routing.test.ts": [
167+
`import { enableConsoleCapture, routeLogsToStderr } from ${loggingConsolePath};`,
168+
`import { loggingState } from ${loggingStatePath};`,
169+
'import { expect, it } from "vitest";',
170+
'it("latches console capture and stderr routing", () => {',
171+
" const native = console.error;",
172+
" routeLogsToStderr();",
173+
" enableConsoleCapture();",
174+
" expect(loggingState.forceConsoleToStderr).toBe(true);",
175+
" expect(loggingState.consolePatched).toBe(true);",
176+
" expect(console.error).not.toBe(native);",
177+
"});",
178+
"",
179+
].join("\n"),
180+
// Production never unwinds those latches: a stdio MCP server or a `--json`
181+
// one-shot owns the console until the process exits. The next file must still
182+
// see its own console.error spy, not the previous file's stderr forwarder.
183+
"06-b-console-routing.test.ts": [
184+
`import { enableConsoleCapture } from ${loggingConsolePath};`,
185+
`import { loggingState } from ${loggingStatePath};`,
186+
'import { expect, it, vi } from "vitest";',
187+
'it("starts from unrouted, unpatched console state", () => {',
188+
" expect(loggingState.forceConsoleToStderr).toBe(false);",
189+
" expect(loggingState.consolePatched).toBe(false);",
190+
" expect(loggingState.rawConsole).toBeNull();",
191+
' const spy = vi.spyOn(console, "error").mockImplementation(() => {});',
192+
" enableConsoleCapture();",
193+
' console.error("routed line");',
194+
' expect(spy.mock.calls).toEqual([["routed line"]]);',
195+
" spy.mockRestore();",
196+
"});",
197+
"",
198+
].join("\n"),
164199
};
165200
}
166201

@@ -216,7 +251,7 @@ it("cleans every shared runner surface between files", async () => {
216251
// The collection failure is intentional. Every behavior test after it must
217252
// pass; any leaked surface turns the summary into a second failure.
218253
expect(output).toContain("synthetic collect failure");
219-
expect(output).toContain("1 failed | 9 passed");
254+
expect(output).toContain("1 failed | 11 passed");
220255
expect(output).not.toContain("first-file");
221256
} finally {
222257
await fs.rm(root, { recursive: true, force: true });

‎test/non-isolated-runner.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import path from "node:path";
33
import { TestRunner, type RunnerTask, type RunnerTestFile, vi } from "vitest";
44
import { resetAgentEventsForTest } from "../src/infra/agent-events.js";
5+
import { loggingState } from "../src/logging/state.js";
56
import { clearNamedPluginRuntimeStoresForTest } from "../src/plugin-sdk/runtime-store-registry.js";
67
import {
78
type CustomElementTracking,
@@ -40,6 +41,17 @@ const DIAGNOSTIC_EVENT_LISTENER_PRESENCE = Symbol.for(
4041
const SESSION_SUSPENSION_TEST_API = Symbol.for("openclaw.sessionSuspensionTestApi");
4142
// Shared-worker scoped: the registry lives on the worker global, not in the module graph.
4243
const CUSTOM_ELEMENT_TRACKING = Symbol.for("openclaw.nonIsolatedCustomElementTracking");
44+
const nativeConsoleMethods = {
45+
log: console.log,
46+
info: console.info,
47+
warn: console.warn,
48+
error: console.error,
49+
debug: console.debug,
50+
trace: console.trace,
51+
};
52+
// loggingState is keyed off globalThis precisely so it survives module reloads,
53+
// so vi.resetModules() below cannot undo what a file latched into it.
54+
const baselineLoggingState = { ...loggingState };
4355
const nativeTimerGlobals = {
4456
setTimeout: globalThis.setTimeout,
4557
clearTimeout: globalThis.clearTimeout,
@@ -146,6 +158,19 @@ function restoreNativeTimerGlobals(): void {
146158
Object.assign(globalThis, nativeTimerGlobals);
147159
}
148160

161+
// enableConsoleCapture() swaps every console method for a forwarder and latches
162+
// routing that production only unwinds at process exit (stdio MCP servers, `--json`
163+
// one-shot commands), so a shared worker carries both into the next file. That
164+
// forwarder writes to process.stderr once forceConsoleToStderr is latched, and the
165+
// next file's console spy then records nothing.
166+
function restoreConsoleRoutingState(): void {
167+
Object.assign(console, nativeConsoleMethods);
168+
// The EPIPE handlers really are attached to the worker's stdout/stderr; resetting
169+
// this flag would let the next enableConsoleCapture() stack a second pair.
170+
const { streamErrorHandlersInstalled } = loggingState;
171+
Object.assign(loggingState, baselineLoggingState, { streamErrorHandlersInstalled });
172+
}
173+
149174
function restoreMocksThenRealTimers(): void {
150175
// A spy created while fake timers are active captures the fake timer as its
151176
// "original" implementation. Restore spies first, then swap timers back.
@@ -435,6 +460,7 @@ export default class OpenClawNonIsolatedRunner extends TestRunner {
435460
// not carry file-scoped timers, stubs, spies, or stale module state
436461
// forward into the next file.
437462
restoreMocksThenRealTimers();
463+
restoreConsoleRoutingState();
438464
vi.unstubAllGlobals();
439465
const testHome = getSharedTestHome();
440466
vi.unstubAllEnvs();

0 commit comments

Comments
 (0)