Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): compare fnm's PATH link by the Node version it names (#4036)
Sapun-net57ca30240066
diff --git a/server/browser-launch-key.ts b/server/browser-launch-key.tsnew file mode 100644index 0000000000..9dcda9f103--- /dev/null+++ b/server/browser-launch-key.ts@@ -0,0 +1,39 @@+import { realpathSync } from "node:fs";+import { posix, win32 } from "node:path";+import type { BrowserSpawnSpec } from "./browser-runtime.ts";++/** fnm's shell hook (`fnm env`, which a person's profile runs) puts a per-shell `<pid>_<epoch-ms>` link to the active+ * Node version on PATH: the link's name says nothing, the installation it resolves to does. Unix puts the link's+ * `bin` on PATH, Windows the link itself. */+const FNM_PER_SHELL = /(?:^|[\\/])fnm_multishells[\\/][^\\/]+(?:[\\/]bin)?[\\/]?$/u;+const FNM_UNRESOLVED = "fnm-multishell";++function fnmTarget(entry: string): string {+ try { return realpathSync.native(entry); }+ catch { return FNM_UNRESOLVED; }+}++function stablePath(path: string, platform: NodeJS.Platform): string {+ const entries: string[] = [];+ const seen = new Set<string>();+ for (const entry of path.split((platform === "win32" ? win32 : posix).delimiter)) {+ if (!FNM_PER_SHELL.test(entry)) {+ entries.push(entry);+ continue;+ }+ const target = fnmTarget(entry);+ if (seen.has(target)) continue;+ seen.add(target);+ entries.push(target);+ }+ return entries.join((platform === "win32" ? win32 : posix).delimiter);+}++/** A running browser answers only the launch settings it started with: agent-browser relaunches Chrome without a word+ * when a command carries others, so a call with different ones is refused instead. */+export function launchSettingsKey(spec: BrowserSpawnSpec, platform: NodeJS.Platform = process.platform): string {+ const env = Object.entries(spec.env)+ .map(([name, value]) => [name, name === "PATH" && value !== undefined ? stablePath(value, platform) : value] as const)+ .sort(([a], [b]) => a.localeCompare(b));+ return JSON.stringify([spec.command, spec.args, env]);+}diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.tsindex acdcd2ee3e..6cb7048f5e 100644--- a/server/browser-runtime.test.ts+++ b/server/browser-runtime.test.ts@@ -1,10 +1,11 @@-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { delimiter, join, posix, win32 } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { addHeldSecretScrubber, HELD_SECRET_MASK } from "../shared/redact.ts";import { BROWSER_VIEWPORT } from "./browser-page-size.ts";import { BROWSER_CALL_DEFAULTS, BROWSER_HOVER_TOOL, BROWSER_RESTART_TOOL, BROWSER_UPLOAD_TOOL, BrowserRuntime, TransportError, browserRuntimeEnv, formatBrowserTiming, type BrowserSpawnSpec, type BrowserTiming } from "./browser-runtime.ts";+import { launchSettingsKey } from "./browser-launch-key.ts";import { HARNESS_CALL_BUDGET_MS, HARNESS_PROXY_TIMEOUT_MS } from "./harness-budget.ts";import { RelayPorts } from "./browser-relay.ts";import { BrowserSteps, type StepCall, type StepContext } from "./browser-steps.ts";@@ -1019,6 +1020,100 @@ describe("server-owned browser MCP runtime", () => {});});+describe("browser launch settings", () => {+ const basePath = process.env.PATH ?? "/usr/bin:/bin";+ const joined = (...entries: string[]) => entries.join(delimiter);+ const fnm = (id: string) => `/Users/person/.local/state/fnm_multishells/${id}/bin`;++ it("keeps the running browser when only fnm's per-shell PATH link changes", async () => {+ const value = runtime();+ const first = spec();+ first.env.PATH = joined(fnm("4101_1793469937867"), basePath);+ const started = await value.agentRpc("fnm", first, "tools/list", {}) as { pid: number };+ const replaced: BrowserSpawnSpec = { ...first, env: { ...first.env, PATH: joined(fnm("4102_1793470001123"), basePath) } };+ expect((await value.agentRpc("fnm", replaced, "tools/list", {}) as { pid: number }).pid).toBe(started.pid);+ // A re-probed PATH keeps the link it captured before and appends the one it read now.+ const accumulated: BrowserSpawnSpec = { ...first, env: { ...first.env, PATH: joined(fnm("4101_1793469937867"), fnm("4103_1793470009999"), basePath) } };+ expect((await value.agentRpc("fnm", accumulated, "tools/list", {}) as { pid: number }).pid).toBe(started.pid);+ });++ it("still refuses a call whose launch settings really changed", async () => {+ const value = runtime();+ const first = spec();+ first.env.PATH = basePath;+ await value.agentRpc("changed", first, "tools/list", {});+ const changes: Array<[string, BrowserSpawnSpec]> = [+ ["command", { ...first, command: `${process.execPath}-other` }],+ ["args", { ...first, args: [...first.args, "--headed"] }],+ ["executable", { ...first, env: { ...first.env, AGENT_BROWSER_EXECUTABLE_PATH: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" } }],+ ["profile", { ...first, env: { ...first.env, AGENT_BROWSER_PROFILE: "/tmp/omb-profile-b" } }],+ ["restore", { ...first, env: { ...first.env, AGENT_BROWSER_RESTORE: "omb-other" } }],+ ["proxy", { ...first, env: { ...first.env, AGENT_BROWSER_PROXY: "socks5://127.0.0.1:64123" } }],+ ["headless", { ...first, env: { ...first.env, AGENT_BROWSER_HEADLESS: "0" } }],+ ["a PATH directory", { ...first, env: { ...first.env, PATH: joined("/opt/homebrew/bin", basePath) } }],+ ];+ for (const [name, changed] of changes) {+ await expect(value.agentRpc("changed", changed, "tools/list", {}), name).rejects.toThrow(/launch settings changed/);+ }+ });++ it("keys the Node version fnm selects in both PATH forms", () => {+ const root = mkdtempSync(join(tmpdir(), "omb-fnm-"));+ try {+ const state = join(root, "state", "fnm_multishells");+ const install = (version: string) => {+ const dir = join(root, "node-versions", version, "installation");+ mkdirSync(join(dir, "bin"), { recursive: true });+ return dir;+ };+ const link = (id: string, target: string) => {+ mkdirSync(state, { recursive: true });+ const path = join(state, id);+ symlinkSync(target, path, process.platform === "win32" ? "junction" : undefined);+ return path;+ };+ const older = install("v20.18.0");+ const newer = install("v22.12.0");+ const firstLink = link("4101_1793469937867", older);+ const secondLink = link("4102_1793470001123", older);+ const upgradeLink = link("4103_1793470009999", newer);+ // Unix puts the link's bin on PATH, Windows the link itself.+ const forms = [(path: string) => join(path, "bin"), (path: string) => path];+ for (const onPath of forms) {+ const key = (...entries: string[]) => launchSettingsKey({ command: "chrome", args: [], env: { PATH: entries.join(delimiter) } });+ expect(key(onPath(firstLink), "/usr/bin")).toBe(key(onPath(secondLink), "/usr/bin"));+ expect(key(onPath(firstLink), "/usr/bin")).not.toBe(key(onPath(upgradeLink), "/usr/bin"));+ }+ } finally { rmSync(root, { recursive: true, force: true }); }+ });++ it("leaves ordinary PATH entries exactly as they were", () => {+ const key = (path: string) => launchSettingsKey({ command: "chrome", args: [], env: { PATH: path } });+ const path = joined("/usr/bin", "/bin");+ expect(key(path)).toBe(JSON.stringify(["chrome", [], [["PATH", path]]]));+ expect(key(path)).not.toBe(key(joined("/usr/bin", "/usr/bin", "/bin")));+ expect(key(path)).not.toBe(key(joined("/bin", "/usr/bin")));+ });++ it("treats an fnm link that is already gone as one stable entry", () => {+ // Literal paths so the case reads the same on every host: the link cannot resolve either way.+ const forms: Array<[NodeJS.Platform, (id: string) => string]> = [+ ["darwin", (id) => `/nowhere/fnm_multishells/${id}/bin`],+ ["win32", (id) => `/nowhere/fnm_multishells/${id}`],+ ];+ for (const [platform, entry] of forms) {+ const separator = (platform === "win32" ? win32 : posix).delimiter;+ const key = (id: string) => launchSettingsKey({ command: "chrome", args: [], env: { PATH: [entry(id), "/usr/bin"].join(separator) } }, platform);+ expect(key("1_1"), platform).toBe(key("2_2"));+ }+ });++ it("does not fold a directory below the link into the link's target", () => {+ const key = (id: string) => launchSettingsKey({ command: "chrome", args: [], env: { PATH: joined(`/nowhere/fnm_multishells/${id}/bin/extra`, "/usr/bin") } });+ expect(key("1_1")).not.toBe(key("2_2"));+ });+});+describe("browser MCP shaping at the runtime boundary", () => {it("strips harness-owned arguments before dispatch and bounds what a result puts into the conversation", async () => {const value = new BrowserRuntime({ idleMs: 500 });diff --git a/server/browser-runtime.ts b/server/browser-runtime.tsindex f726224587..50b474f521 100644--- a/server/browser-runtime.ts+++ b/server/browser-runtime.ts@@ -6,6 +6,7 @@ import { PageSizes, type PageSize } from "./browser-page-size.ts";import { SECRET_ON_PAGE, SecretHolds, type SecretHold } from "./browser-secret-hold.ts";import type { BrowserSteps, StepCall, StepContext } from "./browser-steps.ts";import { HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";+import { launchSettingsKey } from "./browser-launch-key.ts";export interface BrowserSpawnSpec {command: string;@@ -54,6 +55,7 @@ const LANE_BUSY = "Your previous browser call is still running; wait for it to fexport const BROWSER_CALL_DEFAULTS = { requestTimeoutMs: 120_000, laneWaitMs: 30_000, callBudgetMs: HARNESS_CALL_BUDGET_MS, followUpReserveMs: 15_000 } as const;const RESTART_COST = "a restart closes every tab and loses page state such as form input";const LATE = Symbol("late");+const PAGE_ACTIONS: ReadonlySet<string> = new Set(["agent_browser_click", "agent_browser_fill", "agent_browser_type", "agent_browser_press","agent_browser_check", "agent_browser_uncheck", "agent_browser_select", BROWSER_UPLOAD_TOOL, BROWSER_HOVER_TOOL,@@ -667,7 +669,7 @@ export class BrowserRuntime {}private connect(session: string, spec: BrowserSpawnSpec): ClientEntry {- const key = JSON.stringify([spec.command, spec.args, Object.entries(spec.env).sort(([a], [b]) => a.localeCompare(b))]);+ const key = launchSettingsKey(spec);const existing = this.clients.get(session);if (existing && existing.key !== key) throw new Error("Browser launch settings changed. Close the browser before reconnecting.");if (existing) return existing;