Skip to content

Commit 13fd888

Browse files
authored
fix(tui): stop auth child on exit (#126476)
1 parent c5fd625 commit 13fd888

7 files changed

Lines changed: 338 additions & 33 deletions
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
2+
import { tmpdir } from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { sleep } from "../utils/sleep.js";
6+
import {
7+
disposeActiveTuiFixtures,
8+
startTuiFixture,
9+
} from "./tui-pty-harness-fixture-test-support.js";
10+
11+
const STARTUP_TIMEOUT_MS = 60_000;
12+
const EXIT_TIMEOUT_MS = 4_000;
13+
const tempDirs: string[] = [];
14+
15+
async function createCodexFixture(exitMs?: number) {
16+
const dir = await mkdtemp(path.join(tmpdir(), "openclaw-tui-auth-"));
17+
tempDirs.push(dir);
18+
const scriptPath = path.join(dir, "codex-fixture.cjs");
19+
await writeFile(
20+
scriptPath,
21+
[
22+
'console.log("AUTH_CHILD_STARTED:" + process.pid);',
23+
exitMs === undefined
24+
? "setInterval(() => {}, 1000);"
25+
: `setTimeout(() => process.exit(0), ${String(exitMs)});`,
26+
].join("\n"),
27+
"utf8",
28+
);
29+
if (process.platform === "win32") {
30+
await writeFile(
31+
path.join(dir, "codex.cmd"),
32+
`@"${process.execPath}" "${scriptPath}" %*\r\n`,
33+
"utf8",
34+
);
35+
} else {
36+
const launcherPath = path.join(dir, "codex");
37+
await writeFile(launcherPath, `#!/bin/sh\nexec "${process.execPath}" "${scriptPath}" "$@"\n`);
38+
await chmod(launcherPath, 0o755);
39+
}
40+
return {
41+
pathEnv: `${dir}${path.delimiter}${process.env.PATH ?? ""}`,
42+
};
43+
}
44+
45+
async function waitForProcessExit(pid: number, timeoutMs: number): Promise<void> {
46+
const deadline = Date.now() + timeoutMs;
47+
while (Date.now() < deadline) {
48+
try {
49+
process.kill(pid, 0);
50+
} catch {
51+
return;
52+
}
53+
await sleep(10);
54+
}
55+
throw new Error(`auth child ${String(pid)} remained alive`);
56+
}
57+
58+
describe.sequential("TUI auth child lifecycle", () => {
59+
afterEach(async () => {
60+
await disposeActiveTuiFixtures();
61+
for (const dir of tempDirs.splice(0)) {
62+
await rm(dir, { recursive: true, force: true });
63+
}
64+
});
65+
66+
it.skipIf(process.platform === "win32")(
67+
"terminates the foreground auth child when SIGTERM exits the TUI",
68+
async () => {
69+
const auth = await createCodexFixture();
70+
const fixture = await startTuiFixture({
71+
env: {
72+
PATH: auth.pathEnv,
73+
},
74+
});
75+
await fixture.run.waitForOutput("local ready", STARTUP_TIMEOUT_MS);
76+
await fixture.run.write("/auth openai\r", { delay: false });
77+
await fixture.run.waitForOutput("AUTH_CHILD_STARTED:", STARTUP_TIMEOUT_MS);
78+
const pidMatch = fixture.run.visibleOutput().match(/AUTH_CHILD_STARTED:(\d+)/u);
79+
expect(pidMatch).not.toBeNull();
80+
const authPid = Number(pidMatch?.[1]);
81+
82+
process.kill(fixture.run.pid, "SIGTERM");
83+
84+
await expect(fixture.run.waitForExit(EXIT_TIMEOUT_MS)).resolves.toBeDefined();
85+
await expect(waitForProcessExit(authPid, 750)).resolves.toBeUndefined();
86+
},
87+
STARTUP_TIMEOUT_MS + EXIT_TIMEOUT_MS,
88+
);
89+
90+
it(
91+
"resumes the TUI after normal auth completion",
92+
async () => {
93+
const auth = await createCodexFixture(50);
94+
const fixture = await startTuiFixture({
95+
env: {
96+
PATH: auth.pathEnv,
97+
},
98+
});
99+
await fixture.run.waitForOutput("local ready", STARTUP_TIMEOUT_MS);
100+
await fixture.run.write("/auth openai\r", { delay: false });
101+
await fixture.run.waitForOutput("auth flow finished for openai", STARTUP_TIMEOUT_MS);
102+
await fixture.run.write("/gateway-status\r", { delay: false });
103+
await fixture.run.waitForOutput("fixture gateway ok", STARTUP_TIMEOUT_MS);
104+
},
105+
STARTUP_TIMEOUT_MS * 2,
106+
);
107+
});

‎src/tui/tui-auth-child.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import type { ChildProcess } from "node:child_process";
2+
import { EventEmitter } from "node:events";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
5+
const killTreeMocks = vi.hoisted(() => ({ signalProcessTree: vi.fn() }));
6+
7+
vi.mock("../process/kill-tree.js", () => ({
8+
signalProcessTree: killTreeMocks.signalProcessTree,
9+
}));
10+
11+
import { createTuiAuthChildOwner } from "./tui-auth-child.js";
12+
13+
function createChild(pid: number): ChildProcess {
14+
return Object.assign(new EventEmitter(), {
15+
exitCode: null,
16+
kill: vi.fn(),
17+
pid,
18+
signalCode: null,
19+
}) as unknown as ChildProcess;
20+
}
21+
22+
function emitExit(
23+
child: ChildProcess,
24+
exitCode: number | null,
25+
signal: NodeJS.Signals | null,
26+
): void {
27+
Object.assign(child, { exitCode, signalCode: signal });
28+
child.emit("exit", exitCode, signal);
29+
}
30+
31+
describe("TUI auth child owner", () => {
32+
afterEach(() => {
33+
killTreeMocks.signalProcessTree.mockReset();
34+
});
35+
36+
it("does not spawn after terminal close", async () => {
37+
const owner = createTuiAuthChildOwner();
38+
const spawnChild = vi.fn(() => createChild(101));
39+
owner.close();
40+
41+
await expect(owner.spawnAndWait(spawnChild)).rejects.toThrow("owner is closed");
42+
expect(spawnChild).not.toHaveBeenCalled();
43+
expect(owner.running).toBe(false);
44+
});
45+
46+
it("waits for normal completion and releases the exact child", async () => {
47+
const owner = createTuiAuthChildOwner();
48+
const child = createChild(102);
49+
const result = owner.spawnAndWait(() => child);
50+
expect(owner.running).toBe(true);
51+
const secondSpawn = vi.fn(() => createChild(202));
52+
await expect(owner.spawnAndWait(secondSpawn)).rejects.toThrow("already running");
53+
expect(secondSpawn).not.toHaveBeenCalled();
54+
55+
emitExit(child, 0, null);
56+
57+
await expect(result).resolves.toEqual({ exitCode: 0, signal: null });
58+
expect(owner.running).toBe(false);
59+
expect(killTreeMocks.signalProcessTree).not.toHaveBeenCalled();
60+
});
61+
62+
it("cancels gracefully, then force-kills only the still-active child", async () => {
63+
const owner = createTuiAuthChildOwner();
64+
const child = createChild(103);
65+
const result = owner.spawnAndWait(() => child);
66+
67+
owner.close();
68+
owner.close();
69+
70+
expect(killTreeMocks.signalProcessTree).toHaveBeenCalledTimes(1);
71+
expect(killTreeMocks.signalProcessTree).toHaveBeenCalledWith(103, "SIGTERM", {
72+
detached: false,
73+
});
74+
await new Promise((resolve) => {
75+
setTimeout(resolve, 1_050);
76+
});
77+
expect(killTreeMocks.signalProcessTree).toHaveBeenLastCalledWith(103, "SIGKILL", {
78+
detached: false,
79+
});
80+
81+
emitExit(child, null, "SIGKILL");
82+
await expect(result).resolves.toEqual({ exitCode: null, signal: "SIGKILL" });
83+
});
84+
85+
it("clears force escalation when the owned child exits", async () => {
86+
const owner = createTuiAuthChildOwner();
87+
const child = createChild(104);
88+
const result = owner.spawnAndWait(() => child);
89+
owner.close();
90+
emitExit(child, null, "SIGTERM");
91+
92+
await expect(result).resolves.toEqual({ exitCode: null, signal: "SIGTERM" });
93+
await new Promise((resolve) => {
94+
setTimeout(resolve, 1_050);
95+
});
96+
expect(killTreeMocks.signalProcessTree).toHaveBeenCalledTimes(1);
97+
});
98+
});

‎src/tui/tui-auth-child.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import type { ChildProcess } from "node:child_process";
2+
import { signalProcessTree } from "../process/kill-tree.js";
3+
4+
const AUTH_CHILD_FORCE_EXIT_MS = 1_000;
5+
6+
type TuiAuthChildResult = {
7+
exitCode: number | null;
8+
signal: NodeJS.Signals | null;
9+
};
10+
11+
type ActiveAuthChild = {
12+
child: ChildProcess;
13+
forceTimer?: ReturnType<typeof setTimeout>;
14+
};
15+
16+
function isChildRunning(child: ChildProcess): boolean {
17+
return child.exitCode === null && child.signalCode === null;
18+
}
19+
20+
function signalAuthChild(child: ChildProcess, signal: "SIGTERM" | "SIGKILL"): void {
21+
if (child.pid) {
22+
// Auth shares the TUI foreground process group. POSIX must target only this PID;
23+
// Windows uses taskkill /T here so a cmd.exe launcher cannot strand its CLI child.
24+
signalProcessTree(child.pid, signal, { detached: false });
25+
return;
26+
}
27+
child.kill(signal);
28+
}
29+
30+
export function createTuiAuthChildOwner() {
31+
let active: ActiveAuthChild | null = null;
32+
let closed = false;
33+
34+
const clearActive = (owned: ActiveAuthChild): void => {
35+
if (owned.forceTimer) {
36+
clearTimeout(owned.forceTimer);
37+
owned.forceTimer = undefined;
38+
}
39+
if (active === owned) {
40+
active = null;
41+
}
42+
};
43+
44+
const cancel = (owned: ActiveAuthChild): void => {
45+
if (!isChildRunning(owned.child)) {
46+
return;
47+
}
48+
signalAuthChild(owned.child, "SIGTERM");
49+
owned.forceTimer = setTimeout(() => {
50+
if (active !== owned || !isChildRunning(owned.child)) {
51+
return;
52+
}
53+
signalAuthChild(owned.child, "SIGKILL");
54+
}, AUTH_CHILD_FORCE_EXIT_MS);
55+
owned.forceTimer.unref?.();
56+
};
57+
58+
return {
59+
get running(): boolean {
60+
return active !== null && isChildRunning(active.child);
61+
},
62+
spawnAndWait: async (spawnChild: () => ChildProcess): Promise<TuiAuthChildResult> => {
63+
if (closed) {
64+
throw new Error("TUI auth child owner is closed");
65+
}
66+
if (active) {
67+
throw new Error("TUI auth child is already running");
68+
}
69+
const owned: ActiveAuthChild = { child: spawnChild() };
70+
active = owned;
71+
return await new Promise<TuiAuthChildResult>((resolve, reject) => {
72+
let settled = false;
73+
const settle = (complete: () => void): void => {
74+
if (settled) {
75+
return;
76+
}
77+
settled = true;
78+
clearActive(owned);
79+
complete();
80+
};
81+
owned.child.once("error", (error) => settle(() => reject(error)));
82+
owned.child.once("exit", (exitCode, signal) => settle(() => resolve({ exitCode, signal })));
83+
});
84+
},
85+
close: (): void => {
86+
if (closed) {
87+
return;
88+
}
89+
closed = true;
90+
if (active) {
91+
cancel(active);
92+
}
93+
},
94+
};
95+
}

‎src/tui/tui-pty-local-test-support.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ describe("local TUI PTY fixture support", () => {
124124
const run = {
125125
cols: 100,
126126
output: () => output,
127+
pid: 123,
127128
rows: 30,
128129
visibleOutput: () => output.replace(/\s+/gu, " "),
129130
write: async (data: string) => {

‎src/tui/tui-pty-test-support.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ type PtyExitEvent = Parameters<Parameters<IPty["onExit"]>[0]>[0];
1515
export type PtyRun = {
1616
cols: number;
1717
output: () => string;
18+
pid: number;
1819
rows: number;
1920
visibleOutput: () => string;
2021
write: (data: string, opts?: { delay?: boolean }) => Promise<void>;
@@ -370,6 +371,7 @@ export function startPty(
370371
const run: PtyRun = {
371372
cols,
372373
output: () => output,
374+
pid: pty.pid,
373375
rows,
374376
visibleOutput: () => visibleOutput,
375377
write: async (data, writeOpts) => await writePtyInput(pty, data, ptyEnv, writeOpts),

0 commit comments

Comments
 (0)