Skip to content

Commit f2db997

Browse files
committed
fix(gmail): preserve foreground CLI shutdown ownership
1 parent c1d4e50 commit f2db997

6 files changed

Lines changed: 151 additions & 22 deletions

File tree

‎openclaw.mjs‎

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -263,26 +263,6 @@ const respawnWithPackagedCompileCacheIfNeeded = () => {
263263
);
264264
};
265265

266-
// Codex owns the relay timeout by PID. Keep the launcher as that exact process
267-
// so a timeout cannot strand a compile-cache respawn child.
268-
const waitingForCompileCacheRespawn =
269-
!(process.platform !== "win32" && isNativeHookRelayInvocation(process.argv)) &&
270-
(respawnWithoutCompileCacheIfNeeded() || respawnWithPackagedCompileCacheIfNeeded());
271-
272-
// https://nodejs.org/api/module.html#module-compile-cache
273-
if (
274-
!waitingForCompileCacheRespawn &&
275-
module.enableCompileCache &&
276-
!isNodeCompileCacheDisabled() &&
277-
!isSourceCheckoutLauncher()
278-
) {
279-
try {
280-
module.enableCompileCache(resolvePackagedCompileCacheDirectory());
281-
} catch {
282-
// Ignore errors
283-
}
284-
}
285-
286266
const getErrorMessage = (err) =>
287267
err && typeof err === "object" && "message" in err && typeof err.message === "string"
288268
? err.message
@@ -427,6 +407,24 @@ const consumeLauncherRootOptionToken = (args, index) => {
427407
return 0;
428408
};
429409

410+
// Mirror the entry's foreground Gmail policy before any built modules can load.
411+
// A compile-cache wrapper would kill its owner before descendant cleanup finishes.
412+
const isForegroundGmailRunInvocation = (argv) => {
413+
const args = argv.slice(2);
414+
const commandPath = [];
415+
for (let index = 0; index < args.length && commandPath.length < 3; index += 1) {
416+
const consumed = consumeLauncherRootOptionToken(args, index);
417+
if (consumed > 0) {
418+
index += consumed - 1;
419+
} else if (!args[index] || args[index].startsWith("-")) {
420+
break;
421+
} else {
422+
commandPath.push(args[index]);
423+
}
424+
}
425+
return commandPath.join(" ") === "webhooks gmail run";
426+
};
427+
430428
const hasLauncherContainerTarget = (argv) => {
431429
if (normalizeLauncherMetadataValue(process.env.OPENCLAW_CONTAINER)) {
432430
return true;
@@ -769,6 +767,27 @@ const tryOutputPrecomputedCommandHelp = () => {
769767
return true;
770768
};
771769

770+
// Codex owns the relay timeout by PID. Keep the launcher as that exact process
771+
// so a timeout cannot strand a compile-cache respawn child.
772+
const waitingForCompileCacheRespawn =
773+
!isForegroundGmailRunInvocation(process.argv) &&
774+
!(process.platform !== "win32" && isNativeHookRelayInvocation(process.argv)) &&
775+
(respawnWithoutCompileCacheIfNeeded() || respawnWithPackagedCompileCacheIfNeeded());
776+
777+
// https://nodejs.org/api/module.html#module-compile-cache
778+
if (
779+
!waitingForCompileCacheRespawn &&
780+
module.enableCompileCache &&
781+
!isNodeCompileCacheDisabled() &&
782+
!isSourceCheckoutLauncher()
783+
) {
784+
try {
785+
module.enableCompileCache(resolvePackagedCompileCacheDirectory());
786+
} catch {
787+
// Ignore errors
788+
}
789+
}
790+
772791
if (!waitingForCompileCacheRespawn) {
773792
if (!isHelpFastPathDisabled() && (await tryOutputBareRootHelp())) {
774793
// OK

‎src/cli/respawn-policy.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// CLI respawn skip policy for help, interactive TTY commands, and foreground Gateway runs.
22
import { resolveCliArgvInvocation } from "./argv-invocation.js";
3-
import { getCommandPositionalsWithRootOptions } from "./argv.js";
3+
import { getCommandPathWithRootOptions, getCommandPositionalsWithRootOptions } from "./argv.js";
44

55
const GATEWAY_RUN_BOOLEAN_FLAGS = [
66
"--allow-unconfigured",
@@ -29,6 +29,11 @@ const GATEWAY_RUN_VALUE_FLAGS = [
2929

3030
const INTERACTIVE_TTY_COMMANDS = new Set(["tui", "terminal", "chat"]);
3131

32+
/** Gmail owns a shutdown grace period longer than the generic respawn wrapper allows. */
33+
export function isForegroundGmailRunArgv(argv: string[]): boolean {
34+
return getCommandPathWithRootOptions(argv, 3).join(" ") === "webhooks gmail run";
35+
}
36+
3237
export function isNativeHookRelayArgv(argv: string[]): boolean {
3338
const { commandPath } = resolveCliArgvInvocation(argv);
3439
return commandPath[0] === "hooks" && commandPath[1] === "relay";
@@ -77,6 +82,7 @@ export function shouldSkipRespawnForArgv(
7782
return (
7883
invocation.hasHelpOrVersion ||
7984
isInteractiveTtyCommandArgv(argv) ||
85+
isForegroundGmailRunArgv(argv) ||
8086
shouldKeepNativeHookRelayInProcess(argv, platform) ||
8187
(invocation.primary === "gateway" && isForegroundGatewayRunArgv(argv))
8288
);
@@ -90,6 +96,7 @@ export function shouldSkipStartupEnvironmentRespawnForArgv(
9096
const invocation = resolveCliArgvInvocation(argv);
9197
return (
9298
invocation.hasHelpOrVersion ||
99+
isForegroundGmailRunArgv(argv) ||
93100
// Codex owns the relay subprocess timeout. A detached startup respawn can
94101
// outlive the launcher when Codex kills it, stranding the relay child.
95102
shouldKeepNativeHookRelayInProcess(argv, platform) ||

‎src/entry.compile-cache.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,26 @@ describe("entry compile cache", () => {
166166
).toBeDefined();
167167
});
168168

169+
it.each(["linux", "win32"] as const)(
170+
"keeps foreground Gmail cleanup in process with inherited compile cache on %s",
171+
async (platform) => {
172+
const root = tempDirs.make("openclaw-compile-cache-gmail-");
173+
const entryFile = path.join(root, "src", "entry.ts");
174+
await fs.mkdir(path.dirname(entryFile), { recursive: true });
175+
await fs.writeFile(entryFile, "export {};\n", "utf8");
176+
177+
expect(
178+
buildOpenClawCompileCacheRespawnPlan({
179+
currentFile: entryFile,
180+
env: { NODE_COMPILE_CACHE: "/tmp/openclaw-cache" },
181+
installRoot: root,
182+
argv: ["node", entryFile, "webhooks", "--profile", "fixture", "gmail", "run"],
183+
platform,
184+
}),
185+
).toBeUndefined();
186+
},
187+
);
188+
169189
it("keeps interactive no-cache respawn plans attached to the terminal", async () => {
170190
const root = tempDirs.make("openclaw-compile-cache-interactive-");
171191
const entryFile = path.join(root, "dist", "entry.js");

‎src/entry.compile-cache.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import os from "node:os";
66
import path from "node:path";
77
import process from "node:process";
88
import {
9+
isForegroundGmailRunArgv,
910
isTerminalInteractiveRespawnArgv,
1011
shouldKeepNativeHookRelayInProcess,
1112
} from "./cli/respawn-policy.js";
@@ -120,7 +121,7 @@ function buildOpenClawCompileCacheRespawnPlan(params: {
120121
const env = params.env ?? process.env;
121122
const argv = params.argv ?? process.argv;
122123
const platform = params.platform ?? process.platform;
123-
if (shouldKeepNativeHookRelayInProcess(argv, platform)) {
124+
if (isForegroundGmailRunArgv(argv) || shouldKeepNativeHookRelayInProcess(argv, platform)) {
124125
return undefined;
125126
}
126127
if (!isSourceCheckoutInstallRoot(params.installRoot)) {

‎src/entry.respawn.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,34 @@ describe("buildCliRespawnPlan", () => {
4949
).toBeNull();
5050
});
5151

52+
it.each(["darwin", "linux", "win32"] as const)(
53+
"leaves foreground Gmail shutdown with its lifecycle owner on %s",
54+
(platform) => {
55+
for (const args of [
56+
["webhooks", "gmail", "run", "--account", "[email protected]"],
57+
["--profile", "fixture", "webhooks", "gmail", "run"],
58+
]) {
59+
expect(
60+
buildCliRespawnPlan({
61+
argv: ["node", "openclaw", ...args],
62+
env: {},
63+
execArgv: [],
64+
autoNodeExtraCaCerts: "/etc/ssl/certs/ca-certificates.crt",
65+
platform,
66+
}),
67+
).toBeNull();
68+
}
69+
expect(
70+
buildCliRespawnPlan({
71+
argv: ["node", "openclaw", "webhooks", "gmail", "setup"],
72+
env: {},
73+
execArgv: [],
74+
platform,
75+
}),
76+
).not.toBeNull();
77+
},
78+
);
79+
5280
it("adds NODE_EXTRA_CA_CERTS and warning suppression in one respawn", () => {
5381
const plan = buildCliRespawnPlan({
5482
argv: ["node", "openclaw", "status"],

‎test/openclaw-launcher.e2e.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -823,6 +823,60 @@ describe("openclaw launcher", () => {
823823
},
824824
);
825825

826+
it.runIf(process.platform !== "win32").each([true, false])(
827+
"preserves foreground Gmail shutdown grace with compile cache (source=%s)",
828+
async (sourceCheckout) => {
829+
const fixtureRoot = await makeLauncherFixture(fixtureRoots);
830+
if (sourceCheckout) {
831+
await addGitMarker(fixtureRoot);
832+
}
833+
const readyPath = path.join(fixtureRoot, "gmail-ready.json");
834+
const stoppedPath = path.join(fixtureRoot, "gmail-stopped.txt");
835+
await fs.writeFile(
836+
path.join(fixtureRoot, "dist", "entry.js"),
837+
[
838+
'import { writeFileSync } from "node:fs";',
839+
`process.on("SIGTERM", () => setTimeout(() => { writeFileSync(${JSON.stringify(stoppedPath)}, "stopped"); process.exit(0); }, 3025));`,
840+
`writeFileSync(${JSON.stringify(readyPath)}, JSON.stringify({ pid: process.pid }));`,
841+
"setInterval(() => {}, 1000);",
842+
].join("\n"),
843+
);
844+
const launcher = spawn(
845+
process.execPath,
846+
[
847+
path.join(fixtureRoot, "openclaw.mjs"),
848+
"webhooks",
849+
"--profile",
850+
"fixture",
851+
"gmail",
852+
"run",
853+
],
854+
{
855+
cwd: fixtureRoot,
856+
env: launcherEnv({ NODE_COMPILE_CACHE: path.join(fixtureRoot, ".node-cache") }),
857+
stdio: "ignore",
858+
},
859+
);
860+
let ownerPid: number | undefined;
861+
try {
862+
ownerPid = (await waitForJsonFile<{ pid: number }>(readyPath, 5000)).pid;
863+
launcher.kill("SIGTERM");
864+
await expect(waitForProcessExit(launcher, "foreground Gmail", 5000)).resolves.toEqual({
865+
code: 0,
866+
signal: null,
867+
});
868+
await expect(fs.readFile(stoppedPath, "utf8")).resolves.toBe("stopped");
869+
expect(isProcessAlive(ownerPid)).toBe(false);
870+
} finally {
871+
for (const pid of [ownerPid, launcher.pid]) {
872+
if (isProcessAlive(pid)) {
873+
process.kill(pid!, "SIGKILL");
874+
}
875+
}
876+
}
877+
},
878+
);
879+
826880
it.runIf(process.platform !== "win32").each([
827881
{ signal: "SIGINT" as const, exitCode: 130 },
828882
{ signal: "SIGTERM" as const, exitCode: 143 },

0 commit comments

Comments
 (0)