Skip to content

Commit e9b959a

Browse files
steipetePeter Steinberger
andauthored
fix(cli): preserve machine output through fatal terminal restores (#117487)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent 94c5b54 commit e9b959a

10 files changed

Lines changed: 310 additions & 67 deletions

‎src/cli/config-output-mode.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,10 @@ function resolveConfigSubcommand(argv: readonly string[]): string | null {
4343
return null;
4444
}
4545

46-
/** Config get reserves stdout for the requested value, including bare scalar output. */
46+
/** Config values, paths, and schemas reserve stdout for machine-consumed output. */
4747
export function isConfigMachineOutput(argv: readonly string[]): boolean {
48-
return resolveConfigSubcommand(argv) === "get";
48+
const subcommand = resolveConfigSubcommand(argv);
49+
return subcommand === "get" || subcommand === "file" || subcommand === "schema";
4950
}
5051

5152
/** Config set uses --json as a parser alias except when dry-run emits a JSON report. */

‎src/cli/machine-output-modes.test.ts‎

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -67,23 +67,21 @@ describe("built-in machine-output resolvers", () => {
6767
).toBe(true);
6868
});
6969

70-
it("reserves raw cron scratch and config get output", () => {
70+
it("reserves raw cron scratch output", () => {
7171
expect(isCronMachineOutput(["node", "openclaw", "cron", "scratch", "job"])).toBe(true);
72-
expect(isConfigMachineOutput(["node", "openclaw", "config", "get", "gateway.port"])).toBe(true);
72+
});
73+
74+
it.each(["get", "file", "schema"])("reserves config %s machine output", (subcommand) => {
75+
expect(isConfigMachineOutput(["node", "openclaw", "config", subcommand])).toBe(true);
7376
expect(
74-
isConfigMachineOutput([
75-
"node",
76-
"openclaw",
77-
"config",
78-
"--section",
79-
"agents",
80-
"get",
81-
"gateway.port",
82-
]),
77+
isConfigMachineOutput(["node", "openclaw", "config", "--section", "agents", subcommand]),
8378
).toBe(true);
8479
});
8580

8681
it("treats config set --json as parse-only except for JSON dry-run reports", () => {
82+
expect(isConfigMachineOutput(["node", "openclaw", "config", "set", "gateway.port"])).toBe(
83+
false,
84+
);
8785
expect(
8886
isConfigSetJsonParseOnly([
8987
"node",

‎src/cli/one-shot-exit.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,4 +296,86 @@ describe("one-shot CLI exit", () => {
296296
expect(result.stderr).toBe("");
297297
expect(result.stdout).toHaveLength(payloadBytes);
298298
});
299+
300+
it.each([
301+
{ name: "deferred hooks success", exitCode: 0, explicitRequest: true },
302+
{ name: "deferred hooks failure", exitCode: 1, explicitRequest: true },
303+
{ name: "automatic macOS system-CA success", exitCode: 0, explicitRequest: false },
304+
])("keeps real dual-TTY JSON clean for $name", ({ exitCode, explicitRequest }) => {
305+
const env = { ...process.env };
306+
delete env.VITEST;
307+
delete env.VITEST_POOL_ID;
308+
delete env.VITEST_WORKER_ID;
309+
const oneShotExitUrl = new URL("./one-shot-exit.ts", import.meta.url).href;
310+
const runtimeUrl = new URL("../runtime.ts", import.meta.url).href;
311+
const loggingStateUrl = new URL("../logging/state.ts", import.meta.url).href;
312+
const script = `
313+
import { requestExitAfterOneShotOutput, runCliWithExitFinalization } from ${JSON.stringify(oneShotExitUrl)};
314+
import { defaultRuntime } from ${JSON.stringify(runtimeUrl)};
315+
import { loggingState } from ${JSON.stringify(loggingStateUrl)};
316+
Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
317+
Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
318+
loggingState.forceConsoleToStderr = true;
319+
await runCliWithExitFinalization({
320+
run: async () => {
321+
defaultRuntime.writeStdout(JSON.stringify({ ok: ${exitCode === 0} }));
322+
${explicitRequest ? `requestExitAfterOneShotOutput(defaultRuntime, ${exitCode});` : ""}
323+
},
324+
onError: (error) => { throw error; },
325+
${explicitRequest ? "" : 'env: { NODE_USE_SYSTEM_CA: "1" }, execArgv: [], platform: "darwin", markers: {},'}
326+
});
327+
`;
328+
329+
const result = spawnSync(
330+
process.execPath,
331+
["--import", "tsx", "--input-type=module", "--eval", script],
332+
{ encoding: "utf8", env, timeout: 30_000 },
333+
);
334+
335+
expect(result.error).toBeUndefined();
336+
expect(result.status).toBe(exitCode);
337+
expect(result.signal).toBeNull();
338+
expect(JSON.parse(result.stdout)).toEqual({ ok: exitCode === 0 });
339+
expect(result.stderr).toContain("\x1b[?25h");
340+
});
341+
342+
it.each([
343+
{ name: "fatal unhandled rejection", errorCode: "ERR_OUT_OF_MEMORY", exitCode: 1 },
344+
{ name: "invalid configuration rejection", errorCode: "INVALID_CONFIG", exitCode: 78 },
345+
])("keeps real dual-TTY JSON clean after $name", ({ errorCode, exitCode }) => {
346+
const env = { ...process.env };
347+
delete env.VITEST;
348+
delete env.VITEST_POOL_ID;
349+
delete env.VITEST_WORKER_ID;
350+
const runtimeUrl = new URL("../runtime.ts", import.meta.url).href;
351+
const loggingStateUrl = new URL("../logging/state.ts", import.meta.url).href;
352+
const unhandledRejectionsUrl = new URL("../infra/unhandled-rejections.ts", import.meta.url)
353+
.href;
354+
const script = `
355+
import { defaultRuntime } from ${JSON.stringify(runtimeUrl)};
356+
import { loggingState } from ${JSON.stringify(loggingStateUrl)};
357+
import { installUnhandledRejectionHandler } from ${JSON.stringify(unhandledRejectionsUrl)};
358+
Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true });
359+
Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
360+
loggingState.forceConsoleToStderr = true;
361+
installUnhandledRejectionHandler();
362+
defaultRuntime.writeJson({ ok: false });
363+
const error = Object.assign(new Error("expected fatal test"), {
364+
code: ${JSON.stringify(errorCode)},
365+
});
366+
process.emit("unhandledRejection", error, Promise.resolve());
367+
`;
368+
369+
const result = spawnSync(
370+
process.execPath,
371+
["--import", "tsx", "--input-type=module", "--eval", script],
372+
{ encoding: "utf8", env, timeout: 30_000 },
373+
);
374+
375+
expect(result.error).toBeUndefined();
376+
expect(result.status).toBe(exitCode);
377+
expect(result.signal).toBeNull();
378+
expect(JSON.parse(result.stdout)).toEqual({ ok: false });
379+
expect(result.stderr).toContain("\x1b[?25h");
380+
});
299381
});

‎src/cli/run-main.exit.test.ts‎

Lines changed: 46 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ const loadPluginCliDescriptorsMock = vi.hoisted(() =>
8383
const resolveManifestCommandAliasOwnerMock = vi.hoisted(() => vi.fn());
8484
const resolveManifestToolOwnerMock = vi.hoisted(() => vi.fn());
8585
const resolveManifestCliCommandSurfaceOwnerMock = vi.hoisted(() => vi.fn());
86-
const restoreTerminalStateMock = vi.hoisted(() => vi.fn());
86+
const restoreRuntimeTerminalStateMock = vi.hoisted(() => vi.fn());
8787
const hasEnvHttpProxyAgentConfiguredMock = vi.hoisted(() => vi.fn(() => false));
8888
const ensureGlobalUndiciEnvProxyDispatcherMock = vi.hoisted(() => vi.fn());
8989
const readConfigFileSnapshotMock = vi.hoisted(() =>
@@ -350,9 +350,13 @@ vi.mock("../plugins/manifest-command-aliases.runtime.js", () => ({
350350
resolveManifestToolOwner: resolveManifestToolOwnerMock,
351351
}));
352352

353-
vi.mock("../../packages/terminal-core/src/restore.js", () => ({
354-
restoreTerminalState: restoreTerminalStateMock,
355-
}));
353+
vi.mock("../runtime.js", async (importOriginal) => {
354+
const actual = await importOriginal<typeof import("../runtime.js")>();
355+
return {
356+
...actual,
357+
restoreRuntimeTerminalState: restoreRuntimeTerminalStateMock,
358+
};
359+
});
356360

357361
vi.mock("../infra/net/proxy-env.js", () => ({
358362
hasEnvHttpProxyAgentConfigured: hasEnvHttpProxyAgentConfiguredMock,
@@ -4071,43 +4075,48 @@ describe("runCli exit behavior", () => {
40714075
]);
40724076
});
40734077

4074-
it("restores terminal state before uncaught CLI exits", async () => {
4075-
buildProgramMock.mockReturnValueOnce({
4076-
commands: [{ name: () => "status" }],
4077-
parseAsync: vi.fn().mockResolvedValueOnce(undefined),
4078-
});
4078+
it.each([false, true])(
4079+
"restores terminal state before uncaught CLI exits (machine output: %s)",
4080+
async (machineOutput) => {
4081+
buildProgramMock.mockReturnValueOnce({
4082+
commands: [{ name: () => "status" }],
4083+
parseAsync: vi.fn().mockResolvedValueOnce(undefined),
4084+
});
40794085

4080-
const processOnSpy = vi.spyOn(process, "on");
4081-
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
4082-
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
4083-
throw new Error(`process.exit(${String(code)})`);
4084-
}) as typeof process.exit);
4086+
const processOnSpy = vi.spyOn(process, "on");
4087+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
4088+
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
4089+
throw new Error(`process.exit(${String(code)})`);
4090+
}) as typeof process.exit);
40854091

4086-
await runCli(["node", "openclaw", "status"]);
4092+
await runCli(["node", "openclaw", "status"]);
40874093

4088-
const handler = processOnSpy.mock.calls.find(([event]) => event === "uncaughtException")?.[1];
4089-
if (typeof handler !== "function") {
4090-
throw new Error("uncaughtException handler was not registered");
4091-
}
4094+
const handler = processOnSpy.mock.calls.find(([event]) => event === "uncaughtException")?.[1];
4095+
if (typeof handler !== "function") {
4096+
throw new Error("uncaughtException handler was not registered");
4097+
}
40924098

4093-
try {
4094-
expect(() => handler(new Error("boom"))).toThrow("process.exit(1)");
4095-
expect(consoleErrorSpy).toHaveBeenCalledWith(
4096-
"[openclaw] OpenClaw hit an unexpected runtime error.",
4097-
);
4098-
expect(consoleErrorSpy).toHaveBeenCalledWith("[openclaw] Reason: boom");
4099-
expect(restoreTerminalStateMock).toHaveBeenCalledWith("uncaught exception", {
4100-
resumeStdinIfPaused: false,
4101-
});
4102-
} finally {
4103-
if (typeof handler === "function") {
4104-
process.off("uncaughtException", handler);
4099+
try {
4100+
loggingState.forceConsoleToStderr = machineOutput;
4101+
expect(() => handler(new Error("boom"))).toThrow("process.exit(1)");
4102+
expect(consoleErrorSpy).toHaveBeenCalledWith(
4103+
"[openclaw] OpenClaw hit an unexpected runtime error.",
4104+
);
4105+
expect(consoleErrorSpy).toHaveBeenCalledWith("[openclaw] Reason: boom");
4106+
expect(restoreRuntimeTerminalStateMock).toHaveBeenCalledWith("uncaught exception", {
4107+
resumeStdinIfPaused: false,
4108+
});
4109+
} finally {
4110+
loggingState.forceConsoleToStderr = false;
4111+
if (typeof handler === "function") {
4112+
process.off("uncaughtException", handler);
4113+
}
4114+
consoleErrorSpy.mockRestore();
4115+
exitSpy.mockRestore();
4116+
processOnSpy.mockRestore();
41054117
}
4106-
consoleErrorSpy.mockRestore();
4107-
exitSpy.mockRestore();
4108-
processOnSpy.mockRestore();
4109-
}
4110-
});
4118+
},
4119+
);
41114120

41124121
it("does not exit for transient uncaught CLI exceptions", async () => {
41134122
buildProgramMock.mockReturnValueOnce({
@@ -4136,7 +4145,7 @@ describe("runCli exit behavior", () => {
41364145
expect(consoleWarnSpy.mock.calls).toEqual([
41374146
["[openclaw] Non-fatal uncaught exception (continuing):", hostUnreachable.stack],
41384147
]);
4139-
expect(restoreTerminalStateMock).not.toHaveBeenCalled();
4148+
expect(restoreRuntimeTerminalStateMock).not.toHaveBeenCalled();
41404149
expect(exitSpy).not.toHaveBeenCalled();
41414150
} finally {
41424151
if (typeof handler === "function") {

‎src/cli/run-main.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,15 +1456,15 @@ async function runCliWithPreparedOutputMode(
14561456
isBenignUncaughtExceptionError,
14571457
isUncaughtExceptionHandled,
14581458
},
1459-
{ restoreTerminalState },
1459+
{ restoreRuntimeTerminalState },
14601460
] = await startupTrace.measure("core-imports", () =>
14611461
Promise.all([
14621462
import("./program.js"),
14631463
import("../infra/errors.js"),
14641464
import("./failure-output.js"),
14651465
import("../infra/fatal-error-hooks.js"),
14661466
import("../infra/unhandled-rejections.js"),
1467-
import("../../packages/terminal-core/src/restore.js"),
1467+
import("../runtime.js"),
14681468
]),
14691469
);
14701470
const program = await startupTrace.measure("build-program", () => buildProgram());
@@ -1494,7 +1494,7 @@ async function runCliWithPreparedOutputMode(
14941494
for (const message of runFatalErrorHooks({ reason: "uncaught_exception", error })) {
14951495
console.error("[openclaw]", message);
14961496
}
1497-
restoreTerminalState("uncaught exception", { resumeStdinIfPaused: false });
1497+
restoreRuntimeTerminalState("uncaught exception", { resumeStdinIfPaused: false });
14981498
process.exit(1);
14991499
});
15001500

‎src/index.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ if (!isMain) {
9797
}
9898

9999
if (isMain) {
100-
const { restoreTerminalState } = await import("../packages/terminal-core/src/restore.js");
100+
const { restoreRuntimeTerminalState } = await import("./runtime.js");
101101

102102
// Global error handlers to prevent silent crashes from unhandled rejections/exceptions.
103103
// These log the error and exit gracefully instead of crashing without trace.
@@ -124,7 +124,7 @@ if (isMain) {
124124
for (const message of runFatalErrorHooks({ reason: "uncaught_exception", error })) {
125125
console.error("[openclaw]", message);
126126
}
127-
restoreTerminalState("uncaught exception", { resumeStdinIfPaused: false });
127+
restoreRuntimeTerminalState("uncaught exception", { resumeStdinIfPaused: false });
128128
process.exit(1);
129129
});
130130

@@ -145,7 +145,7 @@ if (isMain) {
145145
for (const message of runFatalErrorHooks({ reason: "legacy_cli_failure", error: err })) {
146146
console.error("[openclaw]", message);
147147
}
148-
restoreTerminalState("legacy cli failure", { resumeStdinIfPaused: false });
148+
restoreRuntimeTerminalState("legacy cli failure", { resumeStdinIfPaused: false });
149149
process.exitCode = 1;
150150
},
151151
});

‎src/infra/unhandled-rejections.fatal-detection.test.ts‎

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22
import process from "node:process";
33
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from "vitest";
44

5-
const restoreTerminalStateMock = vi.hoisted(() => vi.fn());
5+
const restoreRuntimeTerminalStateMock = vi.hoisted(() => vi.fn());
66

7-
vi.mock("../../packages/terminal-core/src/restore.js", () => ({
8-
restoreTerminalState: restoreTerminalStateMock,
7+
vi.mock("../runtime.js", () => ({
8+
restoreRuntimeTerminalState: restoreRuntimeTerminalStateMock,
99
}));
1010

11+
import { loggingState } from "../logging/state.js";
1112
import { resetFatalErrorHooksForTest } from "./fatal-error-hooks.js";
1213
import {
1314
installUnhandledRejectionHandler,
@@ -20,6 +21,7 @@ describe("installUnhandledRejectionHandler - fatal detection", () => {
2021
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
2122
let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
2223
let originalExit: typeof process.exit;
24+
const originalForceConsoleToStderr = loggingState.forceConsoleToStderr;
2325

2426
beforeAll(() => {
2527
originalExit = process.exit.bind(process);
@@ -43,6 +45,7 @@ describe("installUnhandledRejectionHandler - fatal detection", () => {
4345

4446
afterEach(() => {
4547
vi.clearAllMocks();
48+
loggingState.forceConsoleToStderr = originalForceConsoleToStderr;
4649
consoleErrorSpy.mockRestore();
4750
consoleWarnSpy.mockRestore();
4851
});
@@ -71,16 +74,16 @@ describe("installUnhandledRejectionHandler - fatal detection", () => {
7174
expectedRestoreReason?: string,
7275
): void {
7376
exitCalls = [];
74-
restoreTerminalStateMock.mockClear();
77+
restoreRuntimeTerminalStateMock.mockClear();
7578
emitUnhandled(reason);
7679
expect(exitCalls).toEqual(expected);
7780
if (expectedRestoreReason) {
78-
expect(restoreTerminalStateMock).toHaveBeenCalledWith(expectedRestoreReason, {
81+
expect(restoreRuntimeTerminalStateMock).toHaveBeenCalledWith(expectedRestoreReason, {
7982
resumeStdinIfPaused: false,
8083
});
8184
return;
8285
}
83-
expect(restoreTerminalStateMock).not.toHaveBeenCalled();
86+
expect(restoreRuntimeTerminalStateMock).not.toHaveBeenCalled();
8487
}
8588

8689
describe("fatal errors", () => {
@@ -105,6 +108,35 @@ describe("installUnhandledRejectionHandler - fatal detection", () => {
105108
"Out of memory",
106109
);
107110
});
111+
112+
it.each([
113+
{
114+
name: "fatal runtime rejection",
115+
errorCode: "ERR_OUT_OF_MEMORY",
116+
exitCode: 1,
117+
restoreReason: "fatal unhandled rejection",
118+
},
119+
{
120+
name: "invalid configuration rejection",
121+
errorCode: "INVALID_CONFIG",
122+
exitCode: 78,
123+
restoreReason: "configuration error",
124+
},
125+
])(
126+
"routes $name terminal resets through the machine-aware runtime owner",
127+
({ errorCode, exitCode, restoreReason }) => {
128+
loggingState.forceConsoleToStderr = true;
129+
130+
emitUnhandled(
131+
Object.assign(new Error("expected machine-output failure"), { code: errorCode }),
132+
);
133+
134+
expect(exitCalls).toEqual([exitCode]);
135+
expect(restoreRuntimeTerminalStateMock).toHaveBeenCalledWith(restoreReason, {
136+
resumeStdinIfPaused: false,
137+
});
138+
},
139+
);
108140
});
109141

110142
describe("scoped uncaught exception handlers", () => {

0 commit comments

Comments
 (0)