Skip to content

Commit 814f193

Browse files
NianJiuZststeipete
andauthored
fix(browser): stop agent-launched managed Chrome (#109723)
* fix(browser): safely stop cross-runtime managed Chrome Co-authored-by: NianJiuZst <[email protected]> * test(browser): keep shared Chrome lifecycle mocks current Co-authored-by: NianJiuZst <[email protected]> --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: NianJiuZst <[email protected]>
1 parent 03f3334 commit 814f193

6 files changed

Lines changed: 227 additions & 6 deletions

‎extensions/browser/src/browser/chrome.internal.test.ts‎

Lines changed: 120 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { execFile } from "node:child_process";
33
import { EventEmitter, once } from "node:events";
44
import fs from "node:fs";
55
import fsp from "node:fs/promises";
6-
import { createServer } from "node:http";
6+
import { Agent, createServer } from "node:http";
77
import type { AddressInfo } from "node:net";
88
import os from "node:os";
99
import path from "node:path";
@@ -13,11 +13,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1313
import { WebSocketServer } from "ws";
1414

1515
const spawnMock = vi.hoisted(() => vi.fn());
16+
const execFileSyncMock = vi.hoisted(() => vi.fn());
1617

1718
vi.mock("node:child_process", async () => {
1819
const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");
1920
return {
2021
...actual,
22+
execFileSync: (...args: unknown[]) => {
23+
const mock = execFileSyncMock.getMockImplementation();
24+
return mock
25+
? mock(...args)
26+
: (actual.execFileSync as unknown as (...actualArgs: unknown[]) => unknown)(...args);
27+
},
2128
spawn: (...args: unknown[]) => spawnMock(...args),
2229
};
2330
});
@@ -67,6 +74,7 @@ import {
6774
launchOpenClawChrome,
6875
ManagedChromeCleanupError,
6976
resolveOpenClawUserDataDir,
77+
stopOwnedOpenClawChrome,
7078
} from "./chrome.js";
7179
import type { ResolvedBrowserConfig, ResolvedBrowserProfile } from "./config.js";
7280
import { BROWSER_ERROR_REASONS, BrowserProfileUnavailableError } from "./errors.js";
@@ -401,6 +409,7 @@ describe("chrome.ts internal", () => {
401409
vi.unstubAllGlobals();
402410
vi.restoreAllMocks();
403411
spawnMock.mockReset();
412+
execFileSyncMock.mockReset();
404413
ensurePortAvailableMock.mockReset();
405414
ensurePortAvailableMock.mockImplementation(async () => {});
406415
registerManagedProxyBrowserCdpBypassMock.mockReset();
@@ -1261,6 +1270,116 @@ describe("chrome.ts internal", () => {
12611270
}
12621271
});
12631272

1273+
it("stops a managed Chrome from another runtime through a pinned CDP connection", async () => {
1274+
const originalPlatform = process.platform;
1275+
const executablePath = path.join(tmpDir, "chrome");
1276+
await fsp.writeFile(executablePath, "");
1277+
const existsSync = fs.existsSync.bind(fs);
1278+
vi.spyOn(fs, "existsSync").mockImplementation((candidate) => {
1279+
const value = String(candidate);
1280+
return (
1281+
value.endsWith("Local State") || value.endsWith("Preferences") || existsSync(candidate)
1282+
);
1283+
});
1284+
1285+
const managedPid = 43213;
1286+
let managedProcessAlive = true;
1287+
let processStartTime = "Fri Jul 17 12:00:00 2026";
1288+
let rotateProcessIdentity = true;
1289+
const killSpy = vi.spyOn(process, "kill").mockImplementation(((pid, signal) => {
1290+
if (pid === managedPid && signal === 0 && !managedProcessAlive) {
1291+
const error = new Error("no such process") as NodeJS.ErrnoException;
1292+
error.code = "ESRCH";
1293+
throw error;
1294+
}
1295+
return true;
1296+
}) as typeof process.kill);
1297+
const connectionSpy = vi.spyOn(Agent.prototype, "createConnection");
1298+
1299+
Object.defineProperty(process, "platform", { value: "darwin" });
1300+
try {
1301+
await withMockChromeCdpServer({
1302+
wsPath: "/devtools/browser/CROSS_PROCESS_OWNER",
1303+
onConnection: (server) => {
1304+
server.on("connection", (socket) => {
1305+
socket.on("message", (raw) => {
1306+
const message = JSON.parse(rawDataToString(raw)) as {
1307+
id: number;
1308+
method: string;
1309+
};
1310+
if (message.method === "SystemInfo.getProcessInfo") {
1311+
if (rotateProcessIdentity) {
1312+
processStartTime = "Fri Jul 17 12:01:00 2026";
1313+
rotateProcessIdentity = false;
1314+
}
1315+
socket.send(
1316+
JSON.stringify({
1317+
id: message.id,
1318+
result: { processInfo: [{ type: "browser", id: managedPid }] },
1319+
}),
1320+
);
1321+
return;
1322+
}
1323+
expect(message.method).toBe("Browser.close");
1324+
managedProcessAlive = false;
1325+
socket.send(JSON.stringify({ id: message.id, result: {} }));
1326+
});
1327+
});
1328+
},
1329+
run: async (baseUrl) => {
1330+
const port = Number(new URL(baseUrl).port);
1331+
const profile = {
1332+
...makeProfile(port),
1333+
cdpUrl: baseUrl,
1334+
driver: "openclaw",
1335+
executablePath,
1336+
} as ResolvedBrowserProfile;
1337+
const userDataDir = resolveOpenClawUserDataDir(profile.name);
1338+
execFileSyncMock.mockImplementation((command: string, args: string[]) => {
1339+
if (command === "ps" && args.includes("command=")) {
1340+
return `${executablePath} --remote-debugging-port=${port} --user-data-dir=${userDataDir}\n`;
1341+
}
1342+
if (command === "ps" && args.includes("lstart=")) {
1343+
return `${processStartTime}\n`;
1344+
}
1345+
if (command === "lsof") {
1346+
return `p${managedPid}\n`;
1347+
}
1348+
throw new Error(`unexpected command: ${command}`);
1349+
});
1350+
await fsp.mkdir(userDataDir, { recursive: true });
1351+
await fsp.symlink(
1352+
`${os.hostname()}-${managedPid}`,
1353+
path.join(userDataDir, "SingletonLock"),
1354+
);
1355+
1356+
try {
1357+
const resolved = makeResolved({
1358+
ssrfPolicy: { dangerouslyAllowPrivateNetwork: true },
1359+
});
1360+
await expect(stopOwnedOpenClawChrome(resolved, profile)).resolves.toBe(false);
1361+
expect(managedProcessAlive).toBe(true);
1362+
expect(killSpy).not.toHaveBeenCalledWith(managedPid, "SIGTERM");
1363+
await expect(
1364+
fsp.lstat(path.join(userDataDir, "SingletonLock")),
1365+
).resolves.toBeTruthy();
1366+
1367+
await expect(stopOwnedOpenClawChrome(resolved, profile)).resolves.toBe(true);
1368+
expect(
1369+
connectionSpy.mock.calls.some(([options]) => typeof options.lookup === "function"),
1370+
).toBe(true);
1371+
expect(killSpy).not.toHaveBeenCalledWith(managedPid, "SIGTERM");
1372+
expect(fs.existsSync(path.join(userDataDir, "SingletonLock"))).toBe(false);
1373+
} finally {
1374+
await fsp.rm(userDataDir, { recursive: true, force: true });
1375+
}
1376+
},
1377+
});
1378+
} finally {
1379+
Object.defineProperty(process, "platform", { value: originalPlatform });
1380+
}
1381+
});
1382+
12641383
it("does not stop a current-host lock pid without managed Chrome ownership proof", async () => {
12651384
const originalPlatform = process.platform;
12661385
const executablePath = path.join(tmpDir, "chrome");

‎extensions/browser/src/browser/chrome.ts‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1351,8 +1351,10 @@ export async function isChromeCdpOwnedByPid(
13511351
}
13521352

13531353
async function requestGracefulChromeClose(
1354-
running: RunningChrome,
1354+
running: Pick<RunningChrome, "pid" | "cdpPort">,
13551355
timeoutMs: number,
1356+
ssrfPolicy?: SsrFPolicy,
1357+
ownsCurrentProcess?: () => boolean,
13561358
): Promise<boolean> {
13571359
const commandTimeoutMs = Math.max(
13581360
1,
@@ -1363,6 +1365,7 @@ async function requestGracefulChromeClose(
13631365
const endpoint = await getChromeWebSocketEndpoint(
13641366
cdpUrlForPort(running.cdpPort),
13651367
Math.min(commandTimeoutMs, CHROME_STOP_PROBE_TIMEOUT_MS),
1368+
ssrfPolicy,
13661369
);
13671370
if (!endpoint) {
13681371
return false;
@@ -1373,7 +1376,10 @@ async function requestGracefulChromeClose(
13731376
// The fixed port can be rebound while this handle remains retained.
13741377
// Never ask a replacement browser to close on behalf of the old child.
13751378
const processInfo = await send("SystemInfo.getProcessInfo");
1376-
if (!cdpProcessListOwnsBrowser(processInfo, running.pid)) {
1379+
if (
1380+
!cdpProcessListOwnsBrowser(processInfo, running.pid) ||
1381+
(ownsCurrentProcess && !ownsCurrentProcess())
1382+
) {
13771383
return;
13781384
}
13791385
commandSent = true;
@@ -1395,6 +1401,59 @@ async function requestGracefulChromeClose(
13951401
}
13961402
}
13971403

1404+
/** Stop only the exact managed Chrome owned by this profile across runtimes. */
1405+
export async function stopOwnedOpenClawChrome(
1406+
resolved: ResolvedBrowserConfig,
1407+
profile: ResolvedBrowserProfile,
1408+
timeoutMs = CHROME_STOP_TIMEOUT_MS,
1409+
): Promise<boolean> {
1410+
if (!profile.cdpIsLoopback || profile.attachOnly || profile.driver !== "openclaw") {
1411+
return false;
1412+
}
1413+
1414+
let exe: BrowserExecutable | null;
1415+
try {
1416+
exe = resolveBrowserExecutable(resolved, profile);
1417+
} catch {
1418+
return false;
1419+
}
1420+
if (!exe) {
1421+
return false;
1422+
}
1423+
1424+
const userDataDir = resolveOpenClawUserDataDir(profile.name);
1425+
const pid = readCurrentHostSingletonPid(userDataDir);
1426+
if (pid == null) {
1427+
return false;
1428+
}
1429+
const identity = readOwnedManagedChromeIdentity({ pid, exe, profile, userDataDir });
1430+
if (!identity) {
1431+
return false;
1432+
}
1433+
1434+
// Browser runtimes do not share child handles; revalidate the exact process
1435+
// before either CDP close or signal-based cleanup can affect a replacement.
1436+
const gracefulCloseRequested = await requestGracefulChromeClose(
1437+
{ pid, cdpPort: profile.cdpPort },
1438+
timeoutMs,
1439+
resolved.ssrfPolicy,
1440+
() => {
1441+
const current = readOwnedManagedChromeIdentity({ pid, exe, profile, userDataDir });
1442+
return current !== null && sameManagedChromeIdentity(identity, current);
1443+
},
1444+
);
1445+
const stoppedGracefully = gracefulCloseRequested && (await waitForPidExit(pid, timeoutMs));
1446+
if (
1447+
!stoppedGracefully &&
1448+
isPidAlive(pid) &&
1449+
!(await terminateOwnedStaleChromeProcess({ identity, exe, profile, userDataDir }, timeoutMs))
1450+
) {
1451+
return false;
1452+
}
1453+
clearRecoveredChromeSingletonArtifacts(userDataDir, pid);
1454+
return true;
1455+
}
1456+
13981457
/** Stop a managed Chrome process and wait for shutdown. */
13991458
export async function stopOpenClawChrome(
14001459
running: RunningChrome,

‎extensions/browser/src/browser/server-context.availability.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
isChromeReachable,
2323
launchOpenClawChrome,
2424
ManagedChromeCleanupError,
25+
stopOwnedOpenClawChrome,
2526
stopOpenClawChrome,
2627
} from "./chrome.js";
2728
import type { ResolvedBrowserProfile } from "./config.js";
@@ -624,14 +625,24 @@ export function createProfileAvailability({
624625
};
625626

626627
const stopRunningBrowser = async (): Promise<{ stopped: boolean }> => {
627-
assertProfileLifecycleContext({ state: state(), runtime, configRevision });
628+
const current = state();
629+
assertProfileLifecycleContext({ state: current, runtime, configRevision });
628630
resetManagedLaunchFailure(runtime);
631+
let stoppedOwnedProcess = false;
629632
const result = await beginProfileTransition({
630-
state: state(),
633+
state: current,
631634
runtime,
632635
reason: "stop requested",
636+
afterCleanup: async () => {
637+
if (profile.attachOnly || capabilities.mode !== "local-managed") {
638+
return;
639+
}
640+
stoppedOwnedProcess = await stopOwnedOpenClawChrome(current.resolved, profile);
641+
},
633642
});
634-
return { stopped: result.stopped || profile.attachOnly || capabilities.isRemote };
643+
return {
644+
stopped: result.stopped || stoppedOwnedProcess || profile.attachOnly || capabilities.isRemote,
645+
};
635646
};
636647

637648
return {

‎extensions/browser/src/browser/server-context.chrome-test-harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,6 @@ vi.mock("./chrome.js", () => ({
4141
throw new Error("unexpected launch");
4242
}),
4343
resolveOpenClawUserDataDir: vi.fn(() => chromeUserDataDir.dir),
44+
stopOwnedOpenClawChrome: vi.fn(async () => false),
4445
stopOpenClawChrome: vi.fn(async () => {}),
4546
}));

‎extensions/browser/src/browser/server-context.stop-running-browser.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ const pwAiMocks = vi.hoisted(() => {
1818
};
1919
});
2020

21+
const chromeMocks = vi.hoisted(() => ({
22+
stopOwnedOpenClawChrome: vi.fn(async () => false),
23+
}));
24+
2125
vi.mock("./pw-ai.js", () => ({ pwAi: pwAiMocks }));
2226
vi.mock("./chrome.js", () => ({
2327
isChromeCdpOwnedByPid: vi.fn(async () => true),
@@ -27,6 +31,7 @@ vi.mock("./chrome.js", () => ({
2731
throw new Error("unexpected launch");
2832
}),
2933
resolveOpenClawUserDataDir: vi.fn(() => "/tmp/openclaw-test"),
34+
stopOwnedOpenClawChrome: chromeMocks.stopOwnedOpenClawChrome,
3035
stopOpenClawChrome: vi.fn(async () => {}),
3136
}));
3237
vi.mock("./chrome-mcp.js", () => ({
@@ -38,6 +43,7 @@ vi.mock("./chrome-mcp.js", () => ({
3843

3944
afterEach(() => {
4045
vi.clearAllMocks();
46+
chromeMocks.stopOwnedOpenClawChrome.mockResolvedValue(false);
4147
});
4248

4349
function createStopHarness(profile: ReturnType<typeof makeBrowserProfile>) {
@@ -58,6 +64,7 @@ describe("createProfileAvailability.stopRunningBrowser", () => {
5864

5965
await expect(profileCtx.stopRunningBrowser()).resolves.toEqual({ stopped: true });
6066
expect(pwAiMocks.closePlaywrightBrowserConnection).not.toHaveBeenCalled();
67+
expect(chromeMocks.stopOwnedOpenClawChrome).not.toHaveBeenCalled();
6168
});
6269

6370
it("stops an unused remote CDP profile without loading Playwright", async () => {
@@ -71,6 +78,7 @@ describe("createProfileAvailability.stopRunningBrowser", () => {
7178

7279
await expect(profileCtx.stopRunningBrowser()).resolves.toEqual({ stopped: true });
7380
expect(pwAiMocks.closePlaywrightBrowserConnection).not.toHaveBeenCalled();
81+
expect(chromeMocks.stopOwnedOpenClawChrome).not.toHaveBeenCalled();
7482
});
7583

7684
it("keeps never-started local managed profiles as not stopped", async () => {
@@ -80,4 +88,26 @@ describe("createProfileAvailability.stopRunningBrowser", () => {
8088
await expect(profileCtx.stopRunningBrowser()).resolves.toEqual({ stopped: false });
8189
expect(pwAiMocks.closePlaywrightBrowserConnection).not.toHaveBeenCalled();
8290
});
91+
92+
it("stops a local managed browser launched by another runtime", async () => {
93+
chromeMocks.stopOwnedOpenClawChrome.mockResolvedValue(true);
94+
const profile = makeBrowserProfile();
95+
const { profileCtx } = createStopHarness(profile);
96+
97+
await expect(profileCtx.stopRunningBrowser()).resolves.toEqual({ stopped: true });
98+
expect(chromeMocks.stopOwnedOpenClawChrome).toHaveBeenCalledOnce();
99+
expect(pwAiMocks.closePlaywrightBrowserConnection).not.toHaveBeenCalled();
100+
});
101+
102+
it.each(["existing-session", "extension"] as const)(
103+
"does not attempt to terminate a personal %s browser",
104+
async (driver) => {
105+
const profile = makeBrowserProfile({ driver });
106+
const { profileCtx } = createStopHarness(profile);
107+
108+
await profileCtx.stopRunningBrowser();
109+
110+
expect(chromeMocks.stopOwnedOpenClawChrome).not.toHaveBeenCalled();
111+
},
112+
);
83113
});

‎extensions/browser/src/browser/server.control-server.test-harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,7 @@ vi.mock("./chrome.js", () => ({
530530
};
531531
}),
532532
resolveOpenClawUserDataDir: vi.fn(() => chromeUserDataDir.dir),
533+
stopOwnedOpenClawChrome: vi.fn(async () => false),
533534
stopOpenClawChrome: vi.fn(async () => {
534535
state.reachable = false;
535536
}),

0 commit comments

Comments
 (0)