Skip to content

Commit 62966ff

Browse files
committed
fix(gmail): keep setup command failures readable
1 parent 4d9187a commit 62966ff

8 files changed

Lines changed: 419 additions & 64 deletions

File tree

‎docs/cli/webhooks.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ This command connects Gmail transport but does not create a restricted reader ag
9696

9797
<Warning>Setup output is sensitive: `--json` includes `hookToken` and `pushToken`, and the push endpoint printed in either format can contain its token. Redact output before sharing it.</Warning>
9898

99+
Command failures show bounded tails from both stdout and stderr, with terminal colors and progress redraws removed. Exit codes and recorded termination reasons distinguish timeouts, signals, and output limits; exit code `124` alone does not mean a timeout. An omission marker (`…`) indicates truncated output. These diagnostics can still contain sensitive command output: redact them before sharing.
100+
99101
`--port`, `--max-bytes`, and `--renew-minutes` require positive integers, without unit suffixes. `--include-body` has no negative CLI flag: set `hooks.gmail.includeBody: false` and let `run` inherit it.
100102

101103
## `webhooks gmail run`

‎src/hooks/gmail-ops.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
1111
runCommandWithTimeout: vi.fn(),
1212
killProcessTree: vi.fn(),
1313
spawn: vi.fn(),
14+
log: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
1415
defaultRuntime: {
1516
log: vi.fn(),
1617
error: vi.fn(),
@@ -19,6 +20,8 @@ const mocks = vi.hoisted(() => ({
1920
},
2021
}));
2122

23+
vi.mock("../logging/subsystem.js", () => ({ createSubsystemLogger: () => mocks.log }));
24+
2225
vi.mock("node:child_process", async () => {
2326
const { mockNodeBuiltinModule } = await import("openclaw/plugin-sdk/test-node-mocks");
2427
return mockNodeBuiltinModule(
@@ -199,6 +202,32 @@ describe("runGmailService", () => {
199202
expect(children.filter((child) => child.alive)).toHaveLength(1);
200203
});
201204

205+
it("logs bounded registration failures and keeps serving and renewing", async () => {
206+
mocks.runCommandWithTimeout.mockResolvedValue({
207+
code: 124,
208+
signal: "SIGTERM",
209+
killed: true,
210+
termination: "timeout",
211+
stdout: `${"x".repeat(30_000)}\nregistration stdout tail`,
212+
stderr: `${"noise\n".repeat(1000)}\u001b[31mregistration stderr tail\u001b[0m`,
213+
});
214+
await runGmailService({});
215+
await vi.advanceTimersByTimeAsync(120_000);
216+
expect(children.filter((child) => child.alive)).toHaveLength(1);
217+
expect(mocks.runCommandWithTimeout).toHaveBeenCalledTimes(3);
218+
expect(mocks.log.error).toHaveBeenCalledTimes(3);
219+
for (const [message] of mocks.log.error.mock.calls) {
220+
expect(message.length).toBeLessThan(2000);
221+
expect(message).toContain("gog gmail watch start failed");
222+
expect(message).toContain("registration stdout tail");
223+
expect(message).toContain("registration stderr tail");
224+
expect(message).toContain("termination=timeout");
225+
expect(message).toContain("code=124");
226+
expect(message).toContain("signal=SIGTERM");
227+
expect(message).not.toContain("\u001b");
228+
}
229+
});
230+
202231
it("keeps renewal single-flight and cancels it on shutdown", async () => {
203232
const renewal = createDeferred<typeof commandSuccess>();
204233
let renewalSignal: AbortSignal | undefined;

‎src/hooks/gmail-ops.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
resolveGatewayPort,
1010
validateConfigObjectWithPlugins,
1111
} from "../config/config.js";
12+
import { formatCommandResult } from "../process/command-error.js";
1213
import { runCommandWithTimeout } from "../process/exec.js";
1314
import { defaultRuntime } from "../runtime.js";
1415
import { displayPath } from "../utils.js";
@@ -340,7 +341,6 @@ async function startGmailWatch(cfg: Pick<GmailHookRuntimeConfig, "account" | "la
340341
const args = [resolveGogExecutable(), ...buildGogWatchStartArgs(cfg)];
341342
const result = await runCommandWithTimeout(args, { timeoutMs: 120_000 });
342343
if (result.code !== 0) {
343-
const message = result.stderr || result.stdout || "gog watch start failed";
344-
throw new Error(message);
344+
throw new Error(formatCommandResult("gog gmail watch start", result));
345345
}
346346
}
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { SpawnResult } from "../process/exec.js";
3+
import { withEnvAsync } from "../test-utils/env.js";
4+
import { withMockedPlatform } from "../test-utils/vitest-spies.js";
5+
6+
const mocks = vi.hoisted(() => ({ run: vi.fn(), hasBinary: vi.fn() }));
7+
vi.mock("../process/exec.js", () => ({ runCommandWithTimeout: mocks.run }));
8+
vi.mock("../skills/loading/config.js", () => ({ hasBinary: mocks.hasBinary }));
9+
10+
const success = {
11+
code: 0,
12+
stdout: "",
13+
stderr: "",
14+
signal: null,
15+
killed: false,
16+
termination: "exit",
17+
} satisfies SpawnResult;
18+
const progress = Array.from({ length: 1000 }, (_, i) => `progress ${i}`).join("\r");
19+
const noisy = {
20+
...success,
21+
code: 7,
22+
stdout: `${"x".repeat(30_000)}\r\nstdout final detail 🦞\r\n`,
23+
stderr: `${progress}\r\n\u001b[31mstderr final detail\u001b[0m\r\n`,
24+
};
25+
26+
async function rejection(run: () => Promise<unknown>): Promise<Error> {
27+
try {
28+
await run();
29+
} catch (error) {
30+
if (error instanceof Error) {
31+
return error;
32+
}
33+
throw error;
34+
}
35+
throw new Error("Expected command failure");
36+
}
37+
38+
beforeEach(() => {
39+
vi.resetModules();
40+
mocks.run.mockReset();
41+
mocks.hasBinary.mockReset().mockReturnValue(true);
42+
});
43+
afterEach(() => vi.restoreAllMocks());
44+
45+
describe("Gmail setup failure diagnostics", () => {
46+
it.each(["gcloud", "login", "brew", "tailscale status", "tailscale serve"])(
47+
"%s retains bounded tails from both streams",
48+
async (boundary) =>
49+
withEnvAsync({ PATH: "" }, async () => {
50+
const utils = await import("./gmail-setup-utils.js");
51+
mocks.run.mockResolvedValue(noisy);
52+
const run = async () => {
53+
if (boundary === "login") {
54+
mocks.run.mockResolvedValueOnce({ ...success, code: 1 });
55+
return utils.ensureGcloudAuth();
56+
}
57+
if (boundary === "brew") {
58+
mocks.hasBinary.mockImplementation((bin: string) => bin === "brew");
59+
return withMockedPlatform("darwin", () => utils.ensureDependency("gog", ["gogcli"]));
60+
}
61+
if (boundary.startsWith("tailscale")) {
62+
if (boundary === "tailscale serve") {
63+
mocks.run.mockResolvedValueOnce({
64+
...success,
65+
stdout: '{"Self":{"DNSName":"fixture.example."}}',
66+
});
67+
}
68+
return utils.ensureTailscaleEndpoint({ mode: "serve", path: "/gmail", port: 8788 });
69+
}
70+
return utils.runGcloud([
71+
"pubsub",
72+
"subscriptions",
73+
"update",
74+
"fixture",
75+
"--push-endpoint",
76+
"https://example.com/?token=do-not-echo-argv",
77+
]);
78+
};
79+
const { message } = await rejection(run);
80+
expect(message.length).toBeLessThan(2000);
81+
expect(message).toContain("code=7");
82+
expect(message).toContain("stderr:");
83+
expect(message).toContain("stdout:");
84+
expect(message).toContain("stdout final detail 🦞");
85+
expect(message).toContain("stderr final detail");
86+
expect(message).toContain("progress 999");
87+
expect(message).toContain("…");
88+
expect(message).not.toContain("\r");
89+
expect(message).not.toContain(String.fromCharCode(27));
90+
expect(message).not.toContain("do-not-echo-argv");
91+
if (boundary === "brew") {
92+
expect(message).toMatch(/brew install.*gog/);
93+
}
94+
}),
95+
);
96+
97+
it.each([
98+
{
99+
termination: "timeout",
100+
code: 124,
101+
signal: "SIGKILL",
102+
killed: true,
103+
reason: "termination=timeout",
104+
},
105+
{
106+
termination: "no-output-timeout",
107+
code: 124,
108+
signal: "SIGTERM",
109+
killed: true,
110+
reason: "termination=no-output-timeout",
111+
},
112+
{
113+
termination: "signal",
114+
code: null,
115+
signal: null,
116+
killed: false,
117+
reason: "termination=signal",
118+
},
119+
{
120+
termination: "signal",
121+
code: null,
122+
signal: "SIGTERM",
123+
killed: true,
124+
reason: "termination=signal",
125+
},
126+
{
127+
termination: "signal",
128+
code: null,
129+
signal: "SIGKILL",
130+
killed: true,
131+
outputLimitExceeded: true,
132+
reason: "termination=output-limit",
133+
},
134+
{ termination: "exit", code: 124, signal: null, killed: false, reason: "termination=exit" },
135+
] satisfies Array<Partial<SpawnResult> & { reason: string }>)(
136+
"retains $reason with code=$code even without output",
137+
async ({ reason, ...metadata }) =>
138+
withEnvAsync({ PATH: "" }, async () => {
139+
const { runGcloud } = await import("./gmail-setup-utils.js");
140+
mocks.run.mockResolvedValue({ ...success, ...metadata });
141+
const { message } = await rejection(() => runGcloud(["config", "list"]));
142+
expect(message).toContain(reason);
143+
expect(message).toContain(`code=${metadata.code}`);
144+
if (metadata.signal) {
145+
expect(message).toContain(`signal=${metadata.signal}`);
146+
}
147+
if (metadata.killed) {
148+
expect(message).toContain("killed=true");
149+
}
150+
if (metadata.termination === "exit") {
151+
expect(message).not.toMatch(/timeout|timed out/);
152+
}
153+
}),
154+
);
155+
156+
it("bounds invalid JSON diagnostics while retaining the parser cause and successful exit metadata", async () => {
157+
const { ensureTailscaleEndpoint } = await import("./gmail-setup-utils.js");
158+
mocks.run.mockResolvedValue({
159+
...noisy,
160+
code: 0,
161+
stdout: `{"value":"${"x".repeat(30_000)}"}invalid-tail`,
162+
});
163+
const error = await rejection(() =>
164+
ensureTailscaleEndpoint({ mode: "serve", path: "/gmail", port: 8788 }),
165+
);
166+
expect(error.message.length).toBeLessThan(3000);
167+
expect(error.message).toContain("returned invalid JSON");
168+
expect(error.message).toContain("code=0");
169+
expect(error.message).toContain("stdout:");
170+
expect(error.message).toContain("invalid-tail");
171+
expect(error.message).toContain("stderr final detail");
172+
expect(error.cause).toBeInstanceOf(SyntaxError);
173+
});
174+
175+
it("keeps successful gcloud output untouched", async () =>
176+
withEnvAsync({ PATH: "" }, async () => {
177+
const { runGcloud } = await import("./gmail-setup-utils.js");
178+
const result = { ...noisy, code: 0 };
179+
mocks.run.mockResolvedValue(result);
180+
expect(await runGcloud(["config", "list"])).toBe(result);
181+
}));
182+
});
183+
184+
describe("Gmail setup decisions", () => {
185+
it.each([
186+
{ code: 0, stdout: "[email protected]\n", login: false },
187+
{ code: 0, stdout: " \n", login: true },
188+
{ code: 1, stdout: "[email protected]\n", login: true },
189+
])("auth list code=$code login=$login", async ({ code, stdout, login }) =>
190+
withEnvAsync({ PATH: "" }, async () => {
191+
const { ensureGcloudAuth } = await import("./gmail-setup-utils.js");
192+
mocks.run.mockResolvedValueOnce({ ...success, code, stdout }).mockResolvedValue(success);
193+
await ensureGcloudAuth();
194+
expect(mocks.run).toHaveBeenCalledTimes(login ? 2 : 1);
195+
if (login) {
196+
expect(mocks.run.mock.calls[1]?.[0].slice(1)).toEqual(["auth", "login"]);
197+
}
198+
}),
199+
);
200+
201+
it.each([0, 1])("provisions only according to describe exit code %i", async (code) =>
202+
withEnvAsync({ PATH: "" }, async () => {
203+
const { ensureTopic, ensureSubscription } = await import("./gmail-setup-utils.js");
204+
mocks.run.mockResolvedValueOnce({ ...success, code }).mockResolvedValue(success);
205+
await ensureTopic("project", "topic");
206+
expect(mocks.run.mock.calls.map(([args]) => args.slice(1, 4))).toEqual(
207+
code === 0
208+
? [["pubsub", "topics", "describe"]]
209+
: [
210+
["pubsub", "topics", "describe"],
211+
["pubsub", "topics", "create"],
212+
],
213+
);
214+
mocks.run
215+
.mockReset()
216+
.mockResolvedValueOnce({ ...success, code })
217+
.mockResolvedValue(success);
218+
await ensureSubscription("project", "subscription", "topic", "https://example.com/push");
219+
expect(mocks.run.mock.calls.map(([args]) => args.slice(1, 4))).toEqual([
220+
["pubsub", "subscriptions", "describe"],
221+
["pubsub", "subscriptions", code === 0 ? "update" : "create"],
222+
]);
223+
}),
224+
);
225+
226+
it.each([
227+
{ state: "installed", platform: "darwin", expected: undefined },
228+
{ state: "missing", platform: "linux", expected: "gog not installed; install it and retry" },
229+
{
230+
state: "no brew",
231+
platform: "darwin",
232+
expected: "Homebrew not installed (install brew and retry)",
233+
},
234+
{
235+
state: "post install missing",
236+
platform: "darwin",
237+
expected: "gog still not available after brew install",
238+
},
239+
] as const)("retains dependency guidance: $state", async ({ state, platform, expected }) => {
240+
const { ensureDependency } = await import("./gmail-setup-utils.js");
241+
mocks.hasBinary.mockImplementation(
242+
(bin: string) =>
243+
state === "installed" || (state === "post install missing" && bin === "brew"),
244+
);
245+
mocks.run.mockResolvedValue(success);
246+
await withMockedPlatform(platform, async () => {
247+
const result = ensureDependency("gog", ["gogcli"]);
248+
if (expected) {
249+
await expect(result).rejects.toThrow(expected);
250+
} else {
251+
await expect(result).resolves.toBeUndefined();
252+
}
253+
});
254+
expect(mocks.run).toHaveBeenCalledTimes(state === "post install missing" ? 1 : 0);
255+
});
256+
});

0 commit comments

Comments
 (0)