Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): keep a Windows daemon's own Chrome that its launcher runs under cmd.exe
aivsomkar7fa236f48592
diff --git a/server/browser-processes.test.ts b/server/browser-processes.test.tsindex a10c602294..a874db7c3a 100644--- a/server/browser-processes.test.ts+++ b/server/browser-processes.test.ts@@ -427,4 +427,32 @@ describe("a browser on Windows", () => {expect(killed()).toEqual([["taskkill", "/PID", String(browser), "/T", "/F"]]);expect(existsSync(join(dir, "lockfile"))).toBe(false);});++ it.runIf(process.platform === "win32")("lists a real browser under cmd.exe with its daemon, keeps it for that daemon and stops it for another", async () => {+ const root = mkdtempSync(join(tmpdir(), "omb-win-cmd-"));+ homes.push(root);+ const dir = join(root, "Kept Profile");+ mkdirSync(join(dir, "lockfile"), { recursive: true });+ const ready = join(root, "ready").replaceAll("\\", "/");+ // This test's node is the daemon; the node under cmd.exe names the profile as the bot's Chrome does.+ const browser = `require('node:fs').writeFileSync('${ready}', ''); ${IDLE}`;+ const shell = spawn("cmd.exe", ["/d", "/s", "/c", `""${process.execPath}" -e "${browser}" -- "--user-data-dir=${dir}""`], { stdio: "ignore", windowsHide: true, windowsVerbatimArguments: true });+ const exited = new Promise((resolve) => shell.once("exit", resolve));+ try {+ await vi.waitFor(() => expect(existsSync(ready)).toBe(true), { timeout: 15_000 });+ const killed = () => vi.mocked(execFile).mock.calls.filter(([file]) => file === "taskkill");+ vi.mocked(execFile).mockClear();+ await releaseBrowserProfile(dir, process.execPath, process.execPath);+ expect(vi.mocked(execFile).mock.calls.some(([file]) => file === "powershell.exe"), "the profile's browsers were listed").toBe(true);+ expect(killed(), "its daemon's browser is kept").toEqual([]);+ rmSync(join(dir, "lockfile"), { recursive: true, force: true });+ await releaseBrowserProfile(dir);+ mkdirSync(join(dir, "lockfile"));+ await releaseBrowserProfile(dir, "C:\\Tools\\agent-browser.exe", process.execPath);+ expect(killed()).toHaveLength(1);+ await Promise.race([exited, new Promise((_, reject) => setTimeout(() => reject(new Error("the stopped browser's shell still runs")), 10_000))]);+ } finally {+ shell.kill();+ }+ }, 60_000);});diff --git a/server/browser-processes.ts b/server/browser-processes.tsindex 7901568177..8d16580b31 100644--- a/server/browser-processes.ts+++ b/server/browser-processes.ts@@ -214,14 +214,15 @@ export async function releaseBrowserProfile(dir: string | undefined, binaryPath?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+/** Windows has no tree to re-parent to: the Chromes naming the profile, each with its image, start time and its parent's and+ * grandparent'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;"+ + " | ForEach-Object { $q = $by[$_.ParentProcessId]; $g = $(if ($q) { $by[$q.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') }) } })";+ + " ParentStarted = $(if ($q) { $q.CreationDate.ToUniversalTime().ToString('o') }); GrandparentId = $(if ($q) { $q.ParentProcessId });"+ + " GrandparentName = $(if ($g) { $g.Name }); GrandparentStarted = $(if ($g) { $g.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')";@@ -253,8 +254,8 @@ const heldWindowsProfiles = new Map<string, { browser: number; daemon: number; i/** 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. */+ * stopped, once it is checked to be the same Chrome; a daemon's own Chrome (its parent, or the cmd.exe its launcher runs+ * in, 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; }@@ -269,19 +270,28 @@ async function releaseWindowsProfile(dir: string, binaryPath?: string, chromePatconst 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;+ // A parent started after its child holds a reused pid: the child's own parent is gone.+ const parentOf = (name: unknown, parentStarted: unknown, started: unknown) =>+ text(name) && text(parentStarted) && text(parentStarted) <= text(started) ? text(name).toLowerCase() : "";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>;+ const {+ ProcessId: pid, ParentProcessId: ppid, CommandLine: line, Name: name, Started: started, ParentName: parent, ParentStarted: parentStarted,+ GrandparentId: gppid, GrandparentName: grandparent, GrandparentStarted: grandparentStarted,+ } = (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 }];+ const daemon = parentOf(parent, parentStarted, started);+ // Rust's Command runs a .cmd launcher through cmd.exe, so that Chrome's daemon is the shell's parent.+ if (daemon === "cmd.exe") {+ return [{ pid: pid as number, started: started as string, daemonPid: gppid as number, daemon: Number.isInteger(gppid) ? parentOf(grandparent, grandparentStarted, parentStarted) : "" }];+ }+ return [{ pid: pid as number, started: started as string, daemonPid: ppid as number, daemon }];});- for (const { pid, ppid, started, daemon } of browsers) {+ for (const { pid, started, daemonPid, daemon } of browsers) {if (daemon.startsWith("agent-browser") || (binaryPath && daemon === win32.basename(binaryPath).toLowerCase())) {- heldWindowsProfiles.set(dir, { browser: pid, daemon: ppid, image: daemon });+ heldWindowsProfiles.set(dir, { browser: pid, daemon: daemonPid, image: daemon });return;}// Between the listing and now the pid may have gone to another program: only the same Chrome is stopped.