Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(browser): close profile owners after a daemon pid is replaced

leonongoingc693badfec13
diff --git a/server/browser-engine.test.ts b/server/browser-engine.test.ts
index 2fe440061a..7588043dca 100644
--- a/server/browser-engine.test.ts
+++ b/server/browser-engine.test.ts
@@ -6,6 +6,7 @@ import { tmpdir } from "node:os";
import { delimiter, join, resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { browserProfileProcessTrees } from "./browser-processes.ts";
import { credentialStoreFlags } from "./browser/egress/gate.ts";
import { browserRoot } from "./browser/chrome/profile.ts";
import { strays } from "./browser/chrome/processes.ts";
@@ -406,6 +407,32 @@ describe("a browser daemon that will not close (#2603)", () => {
return { actual, binaryPath, env, pids, profile: files.PROFILE_DIR, lateHelper: () => Number(readFileSync(`${files.HELPER_PID}.late`, "utf8")) };
}
+ it.skipIf(!posix)("only discovers profile owners from the requested binary and session", async () => {
+ const { actual, binaryPath, pids, profile } = await engine({ close: () => 1 });
+ expect(await browserProfileProcessTrees(profile, binaryPath, "work")).toMatchObject([{ daemon: pids.daemon }]);
+ expect(await browserProfileProcessTrees(profile, binaryPath, "another-session")).toEqual([]);
+ expect(await browserProfileProcessTrees(profile, "/another/agent-browser", "work")).toEqual([]);
+ expect(await browserProfileProcessTrees(profile + "-another", binaryPath, "work")).toEqual([]);
+ for (const pid of Object.values(pids)) expect(gone(actual, pid), String(pid)).toBe(false);
+ });
+
+ it.skipIf(!posix)("closes the profile's predecessor after its session pid file was replaced", async () => {
+ let replacement = 0;
+ const { actual, binaryPath, env, pids, profile } = await engine({ close: () => {
+ process.kill(replacement, "SIGTERM");
+ return 0;
+ } });
+ const newer = actual.spawn(binaryPath, ["-e", "setInterval(() => {}, 1000)"], {
+ detached: true, stdio: "ignore",
+ env: { PATH: process.env.PATH, AGENT_BROWSER_DAEMON: "1", AGENT_BROWSER_SESSION: "work" },
+ });
+ replacement = newer.pid!;
+ groups.push(replacement);
+ writeFileSync(browserDaemonFile(env, ".pid"), String(replacement));
+ expect(await closeBrowserSession(binaryPath, { ...env, AGENT_BROWSER_PROFILE: profile }, 1_000)).toBe(true);
+ for (const pid of [...Object.values(pids), replacement]) expect(gone(actual, pid), String(pid)).toBe(true);
+ });
+
it.skipIf(!posix)("stops the daemon and the browser under it when close fails, and removes the profile folder it would have", async () => {
const { actual, binaryPath, env, pids, profile } = await engine({ close: () => 1 });
expect(existsSync(profile)).toBe(true);
diff --git a/server/browser-engine.ts b/server/browser-engine.ts
index a1cd9379ea..1ec2195db6 100644
--- a/server/browser-engine.ts
+++ b/server/browser-engine.ts
@@ -8,7 +8,7 @@ import { delimiter, dirname, join, resolve } from "node:path";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
import { browserBundlePaths } from "./browser-bundle-release.ts";
-import { browserProcessesRunning, browserProcessTree, releaseBrowserProfile, stopBrowserProcesses } from "./browser-processes.ts";
+import { browserProcessesRunning, browserProcessTree, browserProfileProcessTrees, releaseBrowserProfile, stopBrowserProcesses } from "./browser-processes.ts";
import { BROWSER_VIEWPORT, viewportArgs, type PageSize } from "./browser-page-size.ts";
import { browserRuntimeEnv, ownsBrowserViewport } from "./browser-runtime.ts";
import { spawnBotWork } from "./oom-score.ts";
@@ -130,7 +130,16 @@ export function closeBrowserSession(binaryPath: string, env: NodeJS.ProcessEnv,
const session = env.AGENT_BROWSER_SESSION;
if (!session || !/^[A-Za-z0-9_.-]{1,96}$/.test(session)) return Promise.resolve(false);
const key = browserDaemonFile(env, ".pid");
- const attempt = (closingBrowsers.get(key) ?? Promise.resolve(true)).then(() => closeOnce(binaryPath, env, session, timeoutMs)).catch(() => false).finally(() => {
+ const attempt = (closingBrowsers.get(key) ?? Promise.resolve(true)).then(async () => {
+ const trees = await browserProfileProcessTrees(env.AGENT_BROWSER_PROFILE, binaryPath, session);
+ if (trees === null) return false;
+ const closed = await closeOnce(binaryPath, env, session, timeoutMs);
+ let stopped = true;
+ for (const tree of trees) {
+ if (await browserProcessesRunning(tree) && !await stopBrowserProcesses(tree)) stopped = false;
+ }
+ return closed && stopped;
+ }).catch(() => false).finally(() => {
if (closingBrowsers.get(key) === attempt) closingBrowsers.delete(key);
});
closingBrowsers.set(key, attempt);
diff --git a/server/browser-processes.ts b/server/browser-processes.ts
index 080e6f59f9..9ad7f075ea 100644
--- a/server/browser-processes.ts
+++ b/server/browser-processes.ts
@@ -189,6 +189,23 @@ async function daemonOf(pid: number, table: Map<number, ListedProcess>): Promise
return null;
}
+export async function browserProfileProcessTrees(dir: string | undefined, binaryPath: string, session: string): Promise<BrowserProcessTree[] | null> {
+ if (!dir || process.platform === "win32") return [];
+ const table = await processTable(true);
+ if (!table) return null;
+ const daemons = new Set<number>();
+ const trees: BrowserProcessTree[] = [];
+ for (const [pid, entry] of table) {
+ if (entry.zombie || !namesProfile(entry.args ?? "", dir) || /(?:^|\s)--type=/.test(entry.args ?? "")) continue;
+ const daemon = await daemonOf(pid, table);
+ if (daemon === null || daemons.has(daemon)) continue;
+ daemons.add(daemon);
+ const tree = await browserProcessTree(binaryPath, daemon, session);
+ if (tree) trees.push(tree);
+ }
+ return trees;
+}
+
/** POSIX Chrome locks its profile with a SingletonLock symlink to `<host>-<pid>`. A later launch on the profile hands itself
* to the Chrome the lock names and exits, and refuses a lock that names another host (a renamed Mac, a moved Cloud volume).
* A Chrome whose daemon was killed keeps running, re-parented, and would take every later launch, so it is stopped; then the