Skip to content

Commit 1cbcf14

Browse files
authored
fix(gmail): keep forwarding alive across watcher restarts (#130853)
* fix(gmail): keep forwarding alive across watcher restarts * fix(gmail): preserve foreground CLI shutdown ownership
1 parent d8d8c60 commit 1cbcf14

17 files changed

Lines changed: 632 additions & 375 deletions

‎docs/cli/webhooks.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ This command connects Gmail transport but does not create a restricted reader ag
104104
openclaw webhooks gmail run --account [email protected]
105105
```
106106

107-
Starts the Gmail watch and runs `gog gmail watch serve` plus periodic watch renewal in the foreground. An unexpected exit of the initial serve process schedules a restart after 2 seconds. Stop with Ctrl-C; investigate repeated exits in the logs.
107+
Starts the Gmail watch and runs `gog gmail watch serve` plus periodic watch renewal in the foreground. Unexpected serve-process exits continue to restart after 5 seconds. A bind conflict stops restarts; run only one watcher per listener and stop the other watcher before retrying. Ctrl-C or SIGTERM cancels pending restarts and renewal work and shuts down the serve process tree. Investigate repeated exits in the logs.
108108

109109
`run` accepts the same Pub/Sub, OpenClaw delivery, `gog gmail watch serve`, and Tailscale flags as `setup`, except:
110110

‎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"],

‎src/gateway/server-reload-handlers.test.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,6 @@ type GmailWatcherRestartParams = {
235235
error: (msg: string) => void;
236236
};
237237
onSkipped?: () => void;
238-
isCancelled?: () => boolean;
239238
signal?: AbortSignal;
240239
};
241240

@@ -3881,9 +3880,9 @@ describe("gateway Gmail hot reload handlers", () => {
38813880
const [restartParams] = hoisted.startGmailWatcherWithLogs.mock.calls[0] ?? [];
38823881
expect(restartParams).toMatchObject({ cfg: nextConfig });
38833882
expect(restartParams?.signal).toBe(abortController.signal);
3884-
expect(restartParams?.isCancelled?.()).toBe(false);
3883+
expect(restartParams?.signal?.aborted).toBe(false);
38853884
abortController.abort();
3886-
expect(restartParams?.isCancelled?.()).toBe(true);
3885+
expect(restartParams?.signal?.aborted).toBe(true);
38873886
expect(clearGmailRestartAbortController).toHaveBeenCalledWith(abortController);
38883887
});
38893888

‎src/gateway/server-reload-hot.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,6 @@ export function createGatewayReloadHandlers(params: GatewayReloadHandlerParams)
662662
await startGmailWatcherWithLogs({
663663
cfg: nextConfig,
664664
log: params.logHooks,
665-
isCancelled: () => restartAbortController.signal.aborted,
666665
signal: restartAbortController.signal,
667666
onSkipped: () =>
668667
params.logHooks.info(

‎src/gateway/server-startup-post-attach.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -921,7 +921,6 @@ export async function startGatewaySidecars(params: {
921921
await startGmailWatcherWithLogs({
922922
cfg: params.cfg,
923923
log: params.logHooks,
924-
isCancelled: isStopped,
925924
signal,
926925
});
927926
},

0 commit comments

Comments
 (0)