Skip to content

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

fix(browser): free a Windows profile held by an orphaned Chrome (exit code 21) (#4268)

Aditya Umalec4db8934ab0a
diff --git a/server/browser-engine.ts b/server/browser-engine.ts
index d05fa21752..a1cd9379ea 100644
--- a/server/browser-engine.ts
+++ b/server/browser-engine.ts
@@ -168,7 +168,7 @@ async function closeOnce(binaryPath: string, env: NodeJS.ProcessEnv, session: st
export async function startBrowserSession(binaryPath: string, env: NodeJS.ProcessEnv, timeoutMs = 30_000): Promise<boolean> {
const session = env.AGENT_BROWSER_SESSION;
if (!session || !/^[A-Za-z0-9_.-]{1,96}$/.test(session)) return false;
- await releaseBrowserProfile(env.AGENT_BROWSER_PROFILE);
+ await releaseBrowserProfile(env.AGENT_BROWSER_PROFILE, binaryPath, env.AGENT_BROWSER_EXECUTABLE_PATH);
return (await runBrowserCommand(binaryPath, env, ["open", "--json", "--no-webmcp"], Date.now() + timeoutMs)).ok;
}
@@ -239,7 +239,7 @@ export async function prepareBrowserSessionState(
const env = browserRuntimeEnv({ ...options.env, AGENT_BROWSER_SESSION: session, AGENT_BROWSER_HEADLESS: "1" });
ensureManagedBrowserConfig(env);
if (options.persistent === false) return;
- await releaseBrowserProfile(env.AGENT_BROWSER_PROFILE);
+ await releaseBrowserProfile(env.AGENT_BROWSER_PROFILE, binaryPath, env.AGENT_BROWSER_EXECUTABLE_PATH);
check();
const directory = browserSessionsDirectory(env);
const key = join(directory, session);
diff --git a/server/browser-processes.test.ts b/server/browser-processes.test.ts
index 8708e063ca..30b3a4721c 100644
--- a/server/browser-processes.test.ts
+++ b/server/browser-processes.test.ts
@@ -3,7 +3,7 @@
// hands its Chrome.
import { execFile, execFileSync, spawn, type ChildProcess } from "node:child_process";
import { randomUUID } from "node:crypto";
-import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { hostname, tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -246,4 +246,144 @@ describe("a browser on Windows", () => {
holder.kill("SIGKILL");
}
});
+
+ it("stops an orphaned Chrome that runs under the configured Chrome's own image name, and only that one", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-win-custom-chrome-"));
+ homes.push(root);
+ const dir = join(root, "Profile");
+ mkdirSync(join(dir, "lockfile"), { recursive: true });
+ const started = "2026-11-03T09:00:00.0000000Z";
+ const commands: string[][] = [];
+ vi.mocked(execFile).mockImplementation(((file: string, args: string[], options: { env?: NodeJS.ProcessEnv }, done: (error: Error | null, stdout: string) => void) => {
+ commands.push([file, ...args]);
+ let stdout = "";
+ if (file === "powershell.exe" && options.env?.OMB_PROCESS_ID) stdout = `${started}\r\n`;
+ else if (file === "powershell.exe") {
+ stdout = JSON.stringify([{
+ ProcessId: 4500, ParentProcessId: 4100, CommandLine: `"C:\\Chrome Dev\\chrome-dev.exe" "--user-data-dir=${dir}"`,
+ Name: "chrome-dev.exe", Started: started, ParentName: null, ParentStarted: null,
+ }]);
+ } else if (file === "taskkill") rmSync(join(dir, "lockfile"), { recursive: true, force: true });
+ queueMicrotask(() => done(null, stdout));
+ return {} as ChildProcess;
+ }) as unknown as typeof execFile);
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ const killed = () => commands.filter(([file]) => file === "taskkill");
+ // Without the configured Chrome, an image off the list is never stopped.
+ await releaseBrowserProfile(dir, "C:\\Tools\\agent-browser.exe");
+ expect(killed()).toEqual([]);
+ await releaseBrowserProfile(dir, "C:\\Tools\\agent-browser.exe", "C:\\Chrome Dev\\Chrome-Dev.exe");
+ expect(killed()).toEqual([["taskkill", "/PID", "4500", "/T", "/F"]]);
+ expect(existsSync(join(dir, "lockfile"))).toBe(false);
+ });
+
+ it("gives up after a bounded wait when the stopped Chrome's lock stays held", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-win-held-lock-"));
+ homes.push(root);
+ const dir = join(root, "Profile");
+ mkdirSync(join(dir, "lockfile"), { recursive: true });
+ const started = "2026-11-03T09:00:00.0000000Z";
+ const commands: string[][] = [];
+ vi.mocked(execFile).mockImplementation(((file: string, args: string[], options: { env?: NodeJS.ProcessEnv }, done: (error: Error | null, stdout: string) => void) => {
+ commands.push([file, ...args]);
+ let stdout = "";
+ if (file === "powershell.exe" && options.env?.OMB_PROCESS_ID) stdout = `${started}\r\n`;
+ else if (file === "powershell.exe") {
+ stdout = JSON.stringify([{
+ ProcessId: 4600, ParentProcessId: 4100, CommandLine: `"C:\\Chrome\\chrome.exe" "--user-data-dir=${dir}"`,
+ Name: "chrome.exe", Started: started, ParentName: null, ParentStarted: null,
+ }]);
+ }
+ queueMicrotask(() => done(null, stdout));
+ return {} as ChildProcess;
+ }) as unknown as typeof execFile);
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ const begun = Date.now();
+ await releaseBrowserProfile(dir);
+ expect(Date.now() - begun).toBeGreaterThanOrEqual(1_500);
+ expect(commands.filter(([file]) => file === "taskkill")).toEqual([["taskkill", "/PID", "4600", "/T", "/F"]]);
+ expect(existsSync(join(dir, "lockfile"))).toBe(true);
+ });
+
+ it("stops a Chrome whose daemon was killed under it, which would make every launch exit with code 21, and keeps a daemon's own", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-win-profile-"));
+ homes.push(root);
+ const dir = join(root, "Kept Profile");
+ mkdirSync(join(dir, "Default"), { recursive: true });
+ writeFileSync(join(dir, "Default", "Cookies"), "signed in");
+ writeFileSync(join(dir, "lockfile"), "");
+ // Windows keeps a running Chrome's lockfile undeletable; a folder by that name, which no system unlinks, stands in for it.
+ const hold = () => mkdirSync(join(dir, "lockfile"));
+ const release = () => rmSync(join(dir, "lockfile"), { recursive: true, force: true });
+ let parentImage = "";
+ let parentStarted = "";
+ let startedNow = "";
+ const started = "2026-11-03T09:00:00.0000000Z";
+ // The browser is this test's own live pid, so a Chrome kept under its daemon can be seen still running.
+ const browser = process.pid;
+ const commands: string[][] = [];
+ const chrome = (pid: number, args: string, Name = "chrome.exe") => ({
+ ProcessId: pid, ParentProcessId: 4100, CommandLine: `"C:\\Chrome\\${Name}" ${args}`, Name, Started: started,
+ ParentName: parentImage || null, ParentStarted: parentStarted || null,
+ });
+ vi.mocked(execFile).mockImplementation(((file: string, args: string[], options: { env?: NodeJS.ProcessEnv }, done: (error: Error | null, stdout: string) => void) => {
+ commands.push([file, ...args]);
+ let stdout = "";
+ if (file === "powershell.exe" && options.env?.OMB_PROCESS_ID) {
+ expect(options.env.OMB_PROCESS_ID).toBe(String(browser));
+ stdout = `${startedNow}\r\n`;
+ } else if (file === "powershell.exe") {
+ expect(options.env?.OMB_BROWSER_PROFILE).toBe(dir);
+ stdout = JSON.stringify([
+ chrome(browser, `"--user-data-dir=${dir.toUpperCase()}" --remote-debugging-port=0`),
+ chrome(4201, `--type=renderer "--user-data-dir=${dir}"`),
+ chrome(4300, `"--user-data-dir=${dir} backup" --remote-debugging-port=0`),
+ // Another program naming the profile is never stopped.
+ chrome(4400, `"--user-data-dir=${dir}"`, "python.exe"),
+ ]);
+ } else if (file === "tasklist") {
+ stdout = parentImage ? `"${parentImage}","4100","Console","1","12,345 K"\r\n` : "INFO: No tasks are running which match the specified criteria.\r\n";
+ } else if (file === "taskkill") {
+ expect(args).toEqual(["/PID", String(browser), "/T", "/F"]);
+ release();
+ }
+ queueMicrotask(() => done(null, stdout));
+ return {} as ChildProcess;
+ }) as unknown as typeof execFile);
+ Object.defineProperty(process, "platform", { value: "win32", configurable: true });
+ const killed = () => commands.filter(([file]) => file === "taskkill");
+ const listed = () => commands.filter(([file, ...args]) => file === "powershell.exe" && args.at(-1)!.includes("OMB_BROWSER_PROFILE")).length;
+ try {
+ // No Chrome holds the profile: nothing is listed.
+ await releaseBrowserProfile(dir);
+ expect(commands).toEqual([]);
+ hold();
+ // Its daemon still runs: the Chrome is kept.
+ parentImage = "agent-browser-win32-x64.exe";
+ parentStarted = "2026-11-03T08:59:59.0000000Z";
+ await releaseBrowserProfile(dir);
+ expect(killed()).toEqual([]);
+ // The next turn finds it under the same daemon without listing every process again.
+ await releaseBrowserProfile(dir);
+ expect(listed()).toBe(1);
+ parentImage = "my-engine.exe";
+ await releaseBrowserProfile(dir, "C:\\Tools\\My-Engine.exe");
+ expect(killed()).toEqual([]);
+ // Its daemon is gone and Windows gave the pid to a newer agent-browser, but by now the browser's pid runs another
+ // program too: nothing is stopped.
+ parentImage = "agent-browser-win32-x64.exe";
+ parentStarted = "2026-11-03T09:00:05.0000000Z";
+ startedNow = "2026-11-03T09:00:07.0000000Z";
+ await releaseBrowserProfile(dir);
+ expect(killed()).toEqual([]);
+ // The same Chrome still holds the profile: the browser process and its helpers go.
+ startedNow = started;
+ await releaseBrowserProfile(dir);
+ expect(killed()).toEqual([["taskkill", "/PID", String(browser), "/T", "/F"]]);
+ expect(existsSync(join(dir, "lockfile"))).toBe(false);
+ expect(readFileSync(join(dir, "Default", "Cookies"), "utf8")).toBe("signed in");
+ } finally {
+ release();
+ }
+ });
});
diff --git a/server/browser-processes.ts b/server/browser-processes.ts
index b5e24db29f..7901568177 100644
--- a/server/browser-processes.ts
+++ b/server/browser-processes.ts
@@ -4,7 +4,7 @@
import { execFile } from "node:child_process";
import { readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, unlinkSync } from "node:fs";
import { hostname } from "node:os";
-import { basename, isAbsolute, join, sep } from "node:path";
+import { basename, isAbsolute, join, sep, win32 } from "node:path";
/** `started` tells a process from a later one that reused its pid; a zombie has exited and counts as gone. */
type ListedProcess = { ppid: number; pgid: number; zombie: boolean; started: string; args?: string };
@@ -32,9 +32,9 @@ function temporaryProfile(args: string | undefined): string | null {
const PS = process.platform === "darwin" ? "/bin/ps" : "ps";
/** The C locale keeps `ps` start times in one fixed five-word form. */
-function execText(file: string, args: string[]): Promise<string | null> {
+function execText(file: string, args: string[], env: NodeJS.ProcessEnv = {}, timeout = 5_000): Promise<string | null> {
return new Promise((done) => {
- execFile(file, args, { encoding: "utf8", timeout: 5_000, windowsHide: true, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => done(error ? null : stdout));
+ execFile(file, args, { encoding: "utf8", timeout, windowsHide: true, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C", ...env } }, (error, stdout) => done(error ? null : stdout));
});
}
@@ -193,8 +193,9 @@ async function daemonOf(pid: number, table: Map<number, ListedProcess>): Promise
* 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
* lock goes. A daemon's own Chrome keeps it. The profile's contents are never touched. */
-export async function releaseBrowserProfile(dir: string | undefined): Promise<void> {
- if (!dir || process.platform === "win32") return;
+export async function releaseBrowserProfile(dir: string | undefined, binaryPath?: string, chromePath?: string): Promise<void> {
+ if (!dir) return;
+ if (process.platform === "win32") return releaseWindowsProfile(dir, binaryPath, chromePath);
let target: string;
try { target = readlinkSync(join(dir, "SingletonLock")); }
catch { heldProfiles.delete(dir); return; }
@@ -213,6 +214,83 @@ export async function releaseBrowserProfile(dir: string | undefined): Promise<vo
for (const name of ["SingletonLock", "SingletonSocket", "SingletonCookie"]) { try { unlinkSync(join(dir, name)); } catch {} }
}
+/** Windows has no tree to re-parent to: the Chromes naming the profile, each with its image, start time and its parent's (a
+ * pid the system gave on to a newer process is not the parent). Start times are UTC strings, which sort as they compare and
+ * keep their precision. The folder goes in through the environment, so no path is ever quoted into the script. */
+const WINDOWS_PROFILE_BROWSERS = "$d = $env:OMB_BROWSER_PROFILE; $all = @(Get-CimInstance Win32_Process); $by = @{}; foreach ($p in $all) { $by[$p.ProcessId] = $p }"
+ + " ; ConvertTo-Json -Compress -InputObject @($all | Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($d, [StringComparison]::OrdinalIgnoreCase) -ge 0 }"
+ + " | ForEach-Object { $q = $by[$_.ParentProcessId]; [pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; CommandLine = $_.CommandLine;"
+ + " Name = $_.Name; Started = $_.CreationDate.ToUniversalTime().ToString('o'); ParentName = $(if ($q) { $q.Name });"
+ + " ParentStarted = $(if ($q) { $q.CreationDate.ToUniversalTime().ToString('o') }) } })";
+
+/** One process's start time, read again right before it is stopped. */
+const WINDOWS_PROCESS_STARTED = "(Get-CimInstance Win32_Process -Filter ('ProcessId=' + [uint32]$env:OMB_PROCESS_ID)).CreationDate.ToUniversalTime().ToString('o')";
+
+/** The images Chrome-family browsers run as, besides the configured Chrome's own: no other program on the list is ever stopped. */
+const CHROMIUM_IMAGE = /^(?:chrome|chromium|msedge|brave|chrome-headless-shell)\.exe$/i;
+
+/** A Windows command line's arguments: spaces split them except inside double quotes, which may sit anywhere in one. */
+function windowsArgs(line: string): string[] {
+ const args: string[] = [];
+ let arg = "";
+ let quoted = false;
+ let started = false;
+ for (const char of line) {
+ if (char === "\"") { quoted = !quoted; started = true; }
+ else if (!quoted && /\s/.test(char)) { if (started) args.push(arg); arg = ""; started = false; }
+ else { arg += char; started = true; }
+ }
+ if (started) args.push(arg);
+ return args;
+}
+
+function lockReleased(lock: string): boolean {
+ try { unlinkSync(lock); return true; }
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT"; }
+}
+
+const heldWindowsProfiles = new Map<string, { browser: number; daemon: number; image: string }>();
+
+/** Windows Chrome keeps `lockfile` in its profile open and undeletable while it runs. One whose daemon was killed keeps running
+ * and makes every later launch on the profile exit with code 21 (profile in use), even after the app restarts, so it is
+ * stopped, once it is checked to be the same Chrome; a daemon's own Chrome (its parent runs `binaryPath` or another
+ * agent-browser) is kept. The profile's contents are never touched. */
+async function releaseWindowsProfile(dir: string, binaryPath?: string, chromePath?: string): Promise<void> {
+ const lock = join(dir, "lockfile");
+ if (lockReleased(lock)) { heldWindowsProfiles.delete(dir); return; }
+ // The Chrome kept last time still runs under the same daemon: every process is not listed again on each turn.
+ const held = heldWindowsProfiles.get(dir);
+ if (held && processAlive(held.browser) && await imageOf(held.daemon) === held.image) return;
+ heldWindowsProfiles.delete(dir);
+ const listing = await execText("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROFILE_BROWSERS], { OMB_BROWSER_PROFILE: dir }, 15_000);
+ let rows: unknown;
+ try { rows = JSON.parse(listing ?? ""); } catch { return; }
+ const flag = `--user-data-dir=${dir}`.toLowerCase();
+ const text = (value: unknown) => typeof value === "string" ? value : "";
+ const chromeImage = chromePath ? win32.basename(chromePath).toLowerCase() : undefined;
+ const isChrome = (name: string) => CHROMIUM_IMAGE.test(name) || name.toLowerCase() === chromeImage;
+ const browsers = (Array.isArray(rows) ? rows : [rows]).flatMap((row) => {
+ const { ProcessId: pid, ParentProcessId: ppid, CommandLine: line, Name: name, Started: started, ParentName: parent, ParentStarted: parentStarted } = (row ?? {}) as Record<string, unknown>;
+ if (!Number.isInteger(pid) || !Number.isInteger(ppid) || typeof line !== "string" || !isChrome(text(name)) || !text(started)) return [];
+ // A path's case does not matter on Windows.
+ const args = windowsArgs(line).map((arg) => arg.toLowerCase());
+ if (!args.includes(flag) || args.some((arg) => arg.startsWith("--type="))) return [];
+ // A parent started after the Chrome holds a reused pid: the Chrome's own parent is gone.
+ const daemon = text(parent) && text(parentStarted) && text(parentStarted) <= text(started) ? text(parent).toLowerCase() : "";
+ return [{ pid: pid as number, ppid: ppid as number, started: started as string, daemon }];
+ });
+ for (const { pid, ppid, started, daemon } of browsers) {
+ if (daemon.startsWith("agent-browser") || (binaryPath && daemon === win32.basename(binaryPath).toLowerCase())) {
+ heldWindowsProfiles.set(dir, { browser: pid, daemon: ppid, image: daemon });
+ return;
+ }
+ // Between the listing and now the pid may have gone to another program: only the same Chrome is stopped.
+ const now = await execText("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PROCESS_STARTED], { OMB_PROCESS_ID: String(pid) }, 15_000);
+ if (now?.trim() === started) await execText("taskkill", ["/PID", String(pid), "/T", "/F"]);
+ }
+ if (browsers.length) await within(2_000, async () => lockReleased(lock));
+}
+
function stillRuns(tree: BrowserProcessTree, table: Map<number, ListedProcess>, pid: number): boolean {
const entry = table.get(pid);
return !!entry && !entry.zombie && entry.started === tree.members.get(pid);