Skip to content

Commit 3444052

Browse files
fix(voice-call): ngrok tunnels no longer survive cleanup (#110122)
* fix(voice-call): ngrok tunnels no longer survive cleanup * fix(voice-call): document bounded ngrok shutdown * fix(voice-call): reap ngrok after startup timeout * fix(voice-call): type ngrok process with ignored stdin * fix(voice-call): compose ngrok timeout lifecycle
1 parent af0d189 commit 3444052

3 files changed

Lines changed: 296 additions & 41 deletions

File tree

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Voice Call process tests exercise real tunnel child shutdown behavior.
2+
import fs from "node:fs/promises";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { describe, expect, it } from "vitest";
6+
import { startTunnel } from "./tunnel.js";
7+
8+
function isProcessAlive(pid: number): boolean {
9+
try {
10+
process.kill(pid, 0);
11+
return true;
12+
} catch {
13+
return false;
14+
}
15+
}
16+
17+
async function readPid(pidPath: string): Promise<number> {
18+
let pid = Number.NaN;
19+
await expect
20+
.poll(
21+
async () => {
22+
try {
23+
pid = Number.parseInt(await fs.readFile(pidPath, "utf8"), 10);
24+
return Number.isInteger(pid) && pid > 0;
25+
} catch {
26+
return false;
27+
}
28+
},
29+
{ timeout: 2_000, interval: 20 },
30+
)
31+
.toBe(true);
32+
return pid;
33+
}
34+
35+
async function waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
36+
try {
37+
await expect.poll(() => isProcessAlive(pid), { timeout: timeoutMs, interval: 20 }).toBe(false);
38+
return true;
39+
} catch {
40+
return false;
41+
}
42+
}
43+
44+
describe.skipIf(process.platform === "win32")("voice-call tunnel child shutdown", () => {
45+
it("force-kills ngrok when it ignores graceful shutdown", async () => {
46+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-ngrok-stop-"));
47+
const pidPath = path.join(tempDir, "ngrok.pid");
48+
const ngrokPath = path.join(tempDir, "ngrok");
49+
const previousPath = process.env.PATH;
50+
const previousPidPath = process.env.OPENCLAW_NGROK_PID_FILE;
51+
let childPid: number | undefined;
52+
53+
await fs.writeFile(
54+
ngrokPath,
55+
[
56+
"#!/usr/bin/env node",
57+
'const fs = require("node:fs");',
58+
'process.on("SIGTERM", () => {});',
59+
"fs.writeFileSync(process.env.OPENCLAW_NGROK_PID_FILE, String(process.pid));",
60+
'process.stdout.write(JSON.stringify({ msg: "started tunnel", url: "https://bounded.ngrok.test" }) + "\\n");',
61+
"setInterval(() => {}, 1000);",
62+
].join("\n"),
63+
{ mode: 0o755 },
64+
);
65+
process.env.PATH = `${tempDir}${path.delimiter}${previousPath ?? ""}`;
66+
process.env.OPENCLAW_NGROK_PID_FILE = pidPath;
67+
68+
try {
69+
const tunnel = await startTunnel({
70+
provider: "ngrok",
71+
port: 3334,
72+
path: "/voice/webhook",
73+
});
74+
if (!tunnel) {
75+
throw new Error("Expected ngrok tunnel to start");
76+
}
77+
childPid = await readPid(pidPath);
78+
79+
await tunnel.stop();
80+
81+
expect(await waitForProcessExit(childPid, 1_000)).toBe(true);
82+
} finally {
83+
process.env.PATH = previousPath;
84+
if (previousPidPath === undefined) {
85+
delete process.env.OPENCLAW_NGROK_PID_FILE;
86+
} else {
87+
process.env.OPENCLAW_NGROK_PID_FILE = previousPidPath;
88+
}
89+
if (childPid && isProcessAlive(childPid)) {
90+
process.kill(childPid, "SIGKILL");
91+
await waitForProcessExit(childPid, 1_000);
92+
}
93+
await fs.rm(tempDir, { recursive: true, force: true });
94+
}
95+
});
96+
97+
it("force-kills ngrok before rejecting a startup timeout", async () => {
98+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-ngrok-timeout-"));
99+
const pidPath = path.join(tempDir, "ngrok.pid");
100+
const signalPath = path.join(tempDir, "ngrok.signal");
101+
const ngrokPath = path.join(tempDir, "ngrok");
102+
const previousPath = process.env.PATH;
103+
const previousPidPath = process.env.OPENCLAW_NGROK_PID_FILE;
104+
const previousSignalPath = process.env.OPENCLAW_NGROK_SIGNAL_FILE;
105+
let childPid: number | undefined;
106+
107+
await fs.writeFile(
108+
ngrokPath,
109+
[
110+
"#!/usr/bin/env node",
111+
'const fs = require("node:fs");',
112+
'process.on("SIGTERM", () => fs.writeFileSync(process.env.OPENCLAW_NGROK_SIGNAL_FILE, "SIGTERM"));',
113+
"fs.writeFileSync(process.env.OPENCLAW_NGROK_PID_FILE, String(process.pid));",
114+
"setInterval(() => {}, 1000);",
115+
].join("\n"),
116+
{ mode: 0o755 },
117+
);
118+
process.env.PATH = `${tempDir}${path.delimiter}${previousPath ?? ""}`;
119+
process.env.OPENCLAW_NGROK_PID_FILE = pidPath;
120+
process.env.OPENCLAW_NGROK_SIGNAL_FILE = signalPath;
121+
122+
try {
123+
const result = startTunnel({
124+
provider: "ngrok",
125+
port: 3334,
126+
path: "/voice/webhook",
127+
});
128+
childPid = await readPid(pidPath);
129+
130+
await expect(result).rejects.toThrow("ngrok startup timed out (30s)");
131+
132+
await expect
133+
.poll(
134+
async () => {
135+
try {
136+
return await fs.readFile(signalPath, "utf8");
137+
} catch {
138+
return "";
139+
}
140+
},
141+
{ timeout: 1_000, interval: 20 },
142+
)
143+
.toBe("SIGTERM");
144+
expect(await waitForProcessExit(childPid, 1_000)).toBe(true);
145+
} finally {
146+
process.env.PATH = previousPath;
147+
if (previousPidPath === undefined) {
148+
delete process.env.OPENCLAW_NGROK_PID_FILE;
149+
} else {
150+
process.env.OPENCLAW_NGROK_PID_FILE = previousPidPath;
151+
}
152+
if (previousSignalPath === undefined) {
153+
delete process.env.OPENCLAW_NGROK_SIGNAL_FILE;
154+
} else {
155+
process.env.OPENCLAW_NGROK_SIGNAL_FILE = previousSignalPath;
156+
}
157+
if (childPid && isProcessAlive(childPid)) {
158+
process.kill(childPid, "SIGKILL");
159+
await waitForProcessExit(childPid, 1_000);
160+
}
161+
await fs.rm(tempDir, { recursive: true, force: true });
162+
}
163+
}, 40_000);
164+
});

‎extensions/voice-call/src/tunnel.test.ts‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,16 @@ class FakeChildProcess extends EventEmitter {
1212
readonly stdout = new PassThrough();
1313
readonly stderr = new PassThrough();
1414
killedWith: NodeJS.Signals | null = null;
15+
readonly killSignals: NodeJS.Signals[] = [];
16+
readonly ignoredSignals = new Set<NodeJS.Signals>();
17+
closeOnKill = true;
1518

1619
kill(signal: NodeJS.Signals = "SIGTERM"): boolean {
1720
this.killedWith = signal;
18-
queueMicrotask(() => this.emit("close", null));
21+
this.killSignals.push(signal);
22+
if (this.closeOnKill && !this.ignoredSignals.has(signal)) {
23+
queueMicrotask(() => this.emit("close", null));
24+
}
1925
return true;
2026
}
2127

@@ -170,6 +176,67 @@ describe("voice-call tunnels", () => {
170176
);
171177
});
172178

179+
it("bounds ngrok stop even when forced termination never emits close", async () => {
180+
vi.useFakeTimers();
181+
try {
182+
const proc = nextProcess();
183+
proc.closeOnKill = false;
184+
const result = startNgrokTunnel({ port: 3334, path: "/voice/webhook" });
185+
emitNgrokUrl(proc, "https://stuck.ngrok.io");
186+
const tunnel = await result;
187+
188+
const stop = tunnel.stop();
189+
await vi.advanceTimersByTimeAsync(3_000);
190+
191+
await expect(stop).resolves.toBeUndefined();
192+
expect(proc.killedWith).toBe("SIGKILL");
193+
} finally {
194+
vi.useRealTimers();
195+
}
196+
});
197+
198+
it("unrefs the ngrok startup timeout", async () => {
199+
const unrefSpy = vi.fn();
200+
const setTimeoutOriginal = globalThis.setTimeout.bind(globalThis);
201+
const setTimeoutSpy = vi
202+
.spyOn(globalThis, "setTimeout")
203+
.mockImplementation((handler: TimerHandler, timeout?: number) => {
204+
const timer = Reflect.apply(setTimeoutOriginal, globalThis, [handler, timeout]);
205+
Object.defineProperty(timer, "unref", { value: unrefSpy, configurable: true });
206+
return timer;
207+
});
208+
try {
209+
const proc = nextProcess();
210+
const result = startNgrokTunnel({ port: 3334, path: "/voice/webhook" });
211+
emitNgrokUrl(proc, "https://unref.ngrok.io");
212+
213+
await result;
214+
215+
expect(unrefSpy).toHaveBeenCalledOnce();
216+
} finally {
217+
setTimeoutSpy.mockRestore();
218+
}
219+
});
220+
221+
it("force-kills ngrok before rejecting a startup timeout", async () => {
222+
vi.useFakeTimers();
223+
try {
224+
const proc = nextProcess();
225+
proc.ignoredSignals.add("SIGTERM");
226+
const result = startNgrokTunnel({ port: 3334, path: "/voice/webhook" });
227+
const rejection = expect(result).rejects.toThrow("ngrok startup timed out (30s)");
228+
229+
await vi.advanceTimersByTimeAsync(30_000);
230+
expect(proc.killSignals).toEqual(["SIGTERM"]);
231+
232+
await vi.advanceTimersByTimeAsync(2_000);
233+
await rejection;
234+
expect(proc.killSignals).toEqual(["SIGTERM", "SIGKILL"]);
235+
} finally {
236+
vi.useRealTimers();
237+
}
238+
});
239+
173240
it("parses complete ngrok log lines before bounding the incomplete tail", async () => {
174241
const proc = nextProcess();
175242
const result = startNgrokTunnel({ port: 3334, path: "/voice/webhook" });

0 commit comments

Comments
 (0)