Skip to content

Commit 1b8ee38

Browse files
dorukardahansteipete
authored andcommitted
fix(cli): exit bounded hooks commands (openclaw#76922)
Co-authored-by: Peter Steinberger <steipete@gmail.com>
1 parent 989eb88 commit 1b8ee38

2 files changed

Lines changed: 146 additions & 6 deletions

File tree

src/cli/hooks-cli.process.test.ts

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Hooks CLI process tests cover plugin-owned handles that outlive command output.
2+
import { spawn } from "node:child_process";
3+
import fs from "node:fs/promises";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { afterEach, describe, expect, it } from "vitest";
7+
8+
const tempDirs: string[] = [];
9+
10+
afterEach(async () => {
11+
await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { force: true, recursive: true })));
12+
});
13+
14+
async function createLingeringPluginFixture(): Promise<{
15+
configPath: string;
16+
markerPath: string;
17+
stateDir: string;
18+
}> {
19+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-hooks-cli-"));
20+
tempDirs.push(root);
21+
const stateDir = path.join(root, "state");
22+
const pluginDir = path.join(root, "linger-plugin");
23+
const markerPath = path.join(root, "registered");
24+
await fs.mkdir(stateDir, { recursive: true });
25+
await fs.mkdir(pluginDir, { recursive: true });
26+
await fs.writeFile(
27+
path.join(pluginDir, "package.json"),
28+
JSON.stringify({
29+
name: "linger-plugin",
30+
version: "1.0.0",
31+
type: "module",
32+
openclaw: { extensions: ["./index.js"] },
33+
}),
34+
);
35+
await fs.writeFile(
36+
path.join(pluginDir, "openclaw.plugin.json"),
37+
JSON.stringify({
38+
id: "linger",
39+
name: "Linger",
40+
configSchema: { type: "object", additionalProperties: false, properties: {} },
41+
}),
42+
);
43+
await fs.writeFile(
44+
path.join(pluginDir, "index.js"),
45+
[
46+
'import fs from "node:fs";',
47+
"export default {",
48+
' id: "linger",',
49+
' name: "Linger",',
50+
" register() {",
51+
' fs.writeFileSync(process.env.LINGER_MARKER, "registered\\n");',
52+
" setInterval(() => {}, 60_000);",
53+
" },",
54+
"};",
55+
"",
56+
].join("\n"),
57+
);
58+
const configPath = path.join(stateDir, "openclaw.json");
59+
await fs.writeFile(
60+
configPath,
61+
JSON.stringify({
62+
plugins: {
63+
load: { paths: [pluginDir] },
64+
entries: { linger: { enabled: true } },
65+
},
66+
}),
67+
);
68+
return { configPath, markerPath, stateDir };
69+
}
70+
71+
async function runHooksList(fixture: Awaited<ReturnType<typeof createLingeringPluginFixture>>) {
72+
const child = spawn(
73+
process.execPath,
74+
["--import", "tsx", "src/entry.ts", "hooks", "list", "--json"],
75+
{
76+
cwd: path.resolve("."),
77+
env: {
78+
...process.env,
79+
LINGER_MARKER: fixture.markerPath,
80+
OPENCLAW_CONFIG_PATH: fixture.configPath,
81+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
82+
OPENCLAW_STATE_DIR: fixture.stateDir,
83+
NODE_ENV: undefined,
84+
VITEST: undefined,
85+
},
86+
stdio: ["ignore", "pipe", "pipe"],
87+
},
88+
);
89+
let stdout = "";
90+
let stderr = "";
91+
child.stdout.setEncoding("utf8");
92+
child.stderr.setEncoding("utf8");
93+
child.stdout.on("data", (chunk: string) => {
94+
stdout += chunk;
95+
});
96+
child.stderr.on("data", (chunk: string) => {
97+
stderr += chunk;
98+
});
99+
100+
return await new Promise<{
101+
code: number | null;
102+
signal: NodeJS.Signals | null;
103+
stderr: string;
104+
stdout: string;
105+
}>((resolve, reject) => {
106+
const timer = setTimeout(() => {
107+
child.kill("SIGKILL");
108+
reject(new Error("hooks list did not exit after emitting output"));
109+
}, 15_000);
110+
child.once("error", (error) => {
111+
clearTimeout(timer);
112+
reject(error);
113+
});
114+
child.once("close", (code, signal) => {
115+
clearTimeout(timer);
116+
resolve({ code, signal, stderr, stdout });
117+
});
118+
});
119+
}
120+
121+
describe("hooks CLI process lifecycle", () => {
122+
it("exits after JSON output when plugin registration leaves a ref'd handle", async () => {
123+
const fixture = await createLingeringPluginFixture();
124+
125+
const result = await runHooksList(fixture);
126+
127+
expect(result, result.stderr).toMatchObject({ code: 0, signal: null });
128+
expect(result.stderr).not.toContain("Error:");
129+
expect(JSON.parse(result.stdout)).toMatchObject({ hooks: expect.any(Array) });
130+
await expect(fs.readFile(fixture.markerPath, "utf8")).resolves.toBe("registered\n");
131+
}, 20_000);
132+
});

src/cli/hooks-cli.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { defaultRuntime } from "../runtime.js";
2424
import { shortenHomePath } from "../utils.js";
2525
import { formatCliCommand } from "./command-format.js";
2626
import { runNativeHookRelayCli, type NativeHookRelayCliOptions } from "./native-hook-relay-cli.js";
27+
import { requestExitAfterOneShotOutput } from "./one-shot-exit.js";
2728
import { runPluginInstallCommand } from "./plugins-install-command.js";
2829
import { runPluginUpdateCommand } from "./plugins-update-command.js";
2930

@@ -168,6 +169,13 @@ async function runHooksCliAction(action: () => Promise<void> | void): Promise<vo
168169
}
169170
}
170171

172+
async function runOneShotHooksCliAction(action: () => Promise<void> | void): Promise<void> {
173+
await runHooksCliAction(action);
174+
// Plugin registration can leave ref'd handles behind. Defer exit until runCli
175+
// finishes shared teardown and drains both output streams.
176+
requestExitAfterOneShotOutput();
177+
}
178+
171179
/**
172180
* Format the hooks list output
173181
*/
@@ -484,7 +492,7 @@ export function registerHooksCli(program: Command): void {
484492
.option("--json", "Output as JSON", false)
485493
.option("-v, --verbose", "Show more details including missing requirements", false)
486494
.action(async (opts) =>
487-
runHooksCliAction(async () => {
495+
runOneShotHooksCliAction(async () => {
488496
const config = getRuntimeConfig();
489497
const report = buildHooksReport(config);
490498
writeHooksOutput(formatHooksList(report, opts), opts.json);
@@ -496,7 +504,7 @@ export function registerHooksCli(program: Command): void {
496504
.description("Show detailed information about a hook")
497505
.option("--json", "Output as JSON", false)
498506
.action(async (name, opts) =>
499-
runHooksCliAction(async () => {
507+
runOneShotHooksCliAction(async () => {
500508
const config = getRuntimeConfig();
501509
const report = buildHooksReport(config);
502510
writeHooksOutput(formatHookInfo(report, name, opts), opts.json);
@@ -508,7 +516,7 @@ export function registerHooksCli(program: Command): void {
508516
.description("Check hooks eligibility status")
509517
.option("--json", "Output as JSON", false)
510518
.action(async (opts) =>
511-
runHooksCliAction(async () => {
519+
runOneShotHooksCliAction(async () => {
512520
const config = getRuntimeConfig();
513521
const report = buildHooksReport(config);
514522
writeHooksOutput(formatHooksCheck(report, opts), opts.json);
@@ -519,7 +527,7 @@ export function registerHooksCli(program: Command): void {
519527
.command("enable <name>")
520528
.description("Enable a hook")
521529
.action(async (name) =>
522-
runHooksCliAction(async () => {
530+
runOneShotHooksCliAction(async () => {
523531
await enableHook(name);
524532
}),
525533
);
@@ -528,7 +536,7 @@ export function registerHooksCli(program: Command): void {
528536
.command("disable <name>")
529537
.description("Disable a hook")
530538
.action(async (name) =>
531-
runHooksCliAction(async () => {
539+
runOneShotHooksCliAction(async () => {
532540
await disableHook(name);
533541
}),
534542
);
@@ -578,7 +586,7 @@ export function registerHooksCli(program: Command): void {
578586
});
579587

580588
hooks.action(async () =>
581-
runHooksCliAction(async () => {
589+
runOneShotHooksCliAction(async () => {
582590
const config = getRuntimeConfig();
583591
const report = buildHooksReport(config);
584592
defaultRuntime.log(formatHooksList(report, {}));

0 commit comments

Comments
 (0)