Skip to content

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

A bot's browser waits for its open tabs to have their identity (#4331)

Milind Soni76c8b525b69f
diff --git a/scripts/testing/browser-identity.e2e.test.ts b/scripts/testing/browser-identity.e2e.test.ts
index 6c72fa7c46..2b7245b9d1 100644
--- a/scripts/testing/browser-identity.e2e.test.ts
+++ b/scripts/testing/browser-identity.e2e.test.ts
@@ -9,8 +9,10 @@ import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";
+import { connectCdp } from "../../server/browser-sites.ts";
import { ChromeLauncher } from "../../server/browser/chrome/launcher.ts";
import { chromeHost, installedGoogleChrome, isHeadlessShell } from "../../server/browser/chrome/resolve.ts";
+import { IdentitySidecars, startIdentitySidecar } from "../../server/browser/chrome/sidecar.ts";
import { removeTempDir } from "../../server/testing/cleanup.ts";
import { verifyBrowserIdentity } from "../verify-browser-identity.ts";
import { expectedUserAgent } from "./browser-identity-probe.ts";
@@ -30,15 +32,40 @@ function chromeOmbPicks(): string | null {
return plan.kind === "chrome" ? plan.chrome.path : null;
}
+/** The agent-browser and the full Chrome this machine would use. */
+async function realBrowser(): Promise<{ engine: string; chrome: string }> {
+ const picked = process.env.OMB_CHROME_PATH?.trim() || chromeOmbPicks();
+ const engine = picked ? resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }) : null;
+ const browser = engine ? { binary: engine, chrome: picked } : await ensureUiBrowser(process.env, () => {}, UI_TOOLS_DIR);
+ const chrome = picked || browser.chrome || installedGoogleChrome(chromeHost({ dataDir: out, env: machineEnv }));
+ if (!chrome || isHeadlessShell(chrome)) throw new Error(`a full Chrome is needed, not ${chrome ?? "nothing"}: set OMB_CHROME_PATH`);
+ console.log(`browser identity e2e: agent-browser ${browser.binary}, Chrome ${chrome}`);
+ return { engine: browser.binary, chrome };
+}
+
+/** The real connection, with a page's or a frame's override answered late, as on a busy machine. */
+const slowOverride = (lateMs: number): typeof connectCdp => async (url, timeoutMs, listeners = {}) => {
+ const types = new Map<string, string>();
+ const cdp = await connectCdp(url, timeoutMs, { ...listeners, event(message) {
+ if (message.method === "Target.attachedToTarget") {
+ const { sessionId, targetInfo } = (message.params ?? {}) as { sessionId?: string; targetInfo?: { type?: string } };
+ if (sessionId) types.set(sessionId, targetInfo?.type ?? "");
+ }
+ listeners.event?.(message);
+ } });
+ return {
+ send: async (method, params, sessionId) => {
+ if (method === "Emulation.setUserAgentOverride" && sessionId && ["page", "iframe"].includes(types.get(sessionId) ?? "")) await new Promise((resolve) => setTimeout(resolve, lateMs));
+ return cdp.send(method, params, sessionId);
+ },
+ close: () => cdp.close(),
+ };
+};
+
describe.skipIf(!enabled)("a bot's browser on a real Chrome", () => {
it("opens a page 1280x720 inside whose user agent is Chrome's own, byte for byte, with the same complete client hints in the page, a worker, a service worker and a cross-site frame", async () => {
- const picked = process.env.OMB_CHROME_PATH?.trim() || chromeOmbPicks();
- const engine = picked ? resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }) : null;
- const browser = engine ? { binary: engine, chrome: picked } : await ensureUiBrowser(process.env, () => {}, UI_TOOLS_DIR);
- const chrome = picked || browser.chrome || installedGoogleChrome(chromeHost({ dataDir: out, env: machineEnv }));
- if (!chrome || isHeadlessShell(chrome)) throw new Error(`a full Chrome is needed, not ${chrome ?? "nothing"}: set OMB_CHROME_PATH`);
- console.log(`browser identity e2e: agent-browser ${browser.binary}, Chrome ${chrome}`);
- const { readout } = await verifyBrowserIdentity({ engine: browser.binary, chrome, out, sessionPrefix: "omb-id-e2e" });
+ const { engine, chrome } = await realBrowser();
+ const { readout } = await verifyBrowserIdentity({ engine, chrome, out, sessionPrefix: "omb-id-e2e" });
const failed = readout.checks.filter((check) => !check.pass).map((check) => `${check.check}: ${check.detail}`);
expect(failed).toEqual([]);
const page = readout.reports.page!;
@@ -53,4 +80,11 @@ describe.skipIf(!enabled)("a bot's browser on a real Chrome", () => {
expect(readout.reports.headers.document?.["user-agent"]).toBe(page.ua);
expect(readout.reports.headers.document?.["sec-ch-ua"]).not.toMatch(/Headless/u);
}, 240_000);
+
+ it("gives the first page the same complete client hints when the identity is slow to land", async () => {
+ const { engine, chrome } = await realBrowser();
+ const sidecars = new IdentitySidecars({ start: (url, identity, _connect, options) => startIdentitySidecar(url, identity, slowOverride(600), options) });
+ const { readout } = await verifyBrowserIdentity({ engine, chrome, out, sessionPrefix: "omb-id-slow", sidecars });
+ expect(readout.checks.filter((check) => !check.pass).map((check) => `${check.check}: ${check.detail}`)).toEqual([]);
+ }, 240_000);
});
diff --git a/scripts/verify-browser-identity.ts b/scripts/verify-browser-identity.ts
index 74ae47aaf2..a7963b2c8c 100644
--- a/scripts/verify-browser-identity.ts
+++ b/scripts/verify-browser-identity.ts
@@ -12,6 +12,7 @@ import { pathToFileURL } from "node:url";
import { agentBrowserIntegration, closeBrowserSession, prepareBrowserSessionState, resolveAgentBrowserBinary, setBrowserViewport } from "../server/browser-engine.ts";
import { BrowserRuntime, browserRuntimeEnv, type BrowserSpawnSpec } from "../server/browser-runtime.ts";
import { ChromeLauncher } from "../server/browser/chrome/launcher.ts";
+import type { IdentitySidecars } from "../server/browser/chrome/sidecar.ts";
import { openGate } from "../server/browser/egress/gate.ts";
import { refusalFor } from "../server/browser/egress/policy.ts";
import { DATA_DIR } from "../server/config.ts";
@@ -151,6 +152,8 @@ export interface BotBrowserOptions {
out: string;
sessionPrefix?: string;
log?: (line: string) => void;
+ /** The identity connections, in place of the server's own: a test can slow one down. */
+ sidecars?: IdentitySidecars;
}
/** A browser tool call, as the bot makes it. */
@@ -171,7 +174,7 @@ export async function withBotBrowser<T>(options: BotBrowserOptions, work: (call:
// runner's HOME is a temporary folder, so the real one comes from the user database.
const home = userInfo().homedir;
const session = `${options.sessionPrefix ?? "omb-identity"}-${randomBytes(3).toString("hex")}`;
- const launcher = new ChromeLauncher({ dataDir: join(scratch, "data"), env: { ...process.env, HOME: home, USERPROFILE: home, OMB_CHROME_PATH: options.chrome }, log });
+ const launcher = new ChromeLauncher({ dataDir: join(scratch, "data"), env: { ...process.env, HOME: home, USERPROFILE: home, OMB_CHROME_PATH: options.chrome }, log, ...(options.sidecars ? { sidecars: options.sidecars } : {}) });
// Where the launcher adds nothing (OMB_BROWSER_LEGACY_SHELL=1, a headless shell), agent-browser would otherwise look for a
// browser of its own, such as an installed Google Chrome, instead of the one named here.
const launcherEnv = launcher.env();
diff --git a/server/browser/chrome/sidecar.test.ts b/server/browser/chrome/sidecar.test.ts
index a3970bcfb7..5cee9cd44f 100644
--- a/server/browser/chrome/sidecar.test.ts
+++ b/server/browser/chrome/sidecar.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
import type { Cdp, CdpListeners } from "../../browser-sites.ts";
import { NO_PASSKEY_AUTHENTICATOR } from "../cdp/passkeys.ts";
import type { ChromeIdentity } from "./identity.ts";
-import { IdentitySidecars, startIdentitySidecar } from "./sidecar.ts";
+import { IDENTITY_LANDS_MS, IdentitySidecars, startIdentitySidecar } from "./sidecar.ts";
const IDENTITY: ChromeIdentity = {
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/153.0.0.0 Safari/537.36",
@@ -29,7 +29,53 @@ function fakeBrowser() {
return { sent, connect, attach, settle, on, drop: () => listeners.closed?.() };
}
+/** A browser with a tab open: it attaches as auto-attach is asked for, and its override is answered when the test says. */
+function browserWithOpenTab() {
+ const sent: string[] = [];
+ let listeners: CdpListeners = {};
+ let answer = () => {};
+ const answered = new Promise<void>((resolve) => { answer = () => resolve(); });
+ const cdp: Cdp = {
+ send: async (method, _params, sessionId) => {
+ sent.push(sessionId ? `${sessionId} ${method}` : method);
+ if (method === "Target.setAutoAttach" && !sessionId) listeners.event?.({ method: "Target.attachedToTarget", params: { sessionId: "tab-1", targetInfo: { type: "page", url: "about:blank" }, waitingForDebugger: false } });
+ if (method === "Emulation.setUserAgentOverride") await answered;
+ return {};
+ },
+ close: () => listeners.closed?.(),
+ };
+ const connect = async (_url: string, _timeoutMs?: number, given: CdpListeners = {}) => { listeners = given; return cdp; };
+ return { sent, connect, answer: () => answer() };
+}
+
describe("the identity sidecar", () => {
+ it("doesn't hand the browser over until a tab already open has its identity, so the next page can't commit without it", async () => {
+ const browser = browserWithOpenTab();
+ let started = false;
+ const start = startIdentitySidecar("ws://127.0.0.1:9/devtools/browser/x", IDENTITY, browser.connect).then(() => { started = true; });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(browser.sent).toContain("tab-1 Emulation.setUserAgentOverride");
+ expect(started).toBe(false);
+ browser.answer();
+ await start;
+ expect(started).toBe(true);
+ expect(browser.sent).toContain("tab-1 Runtime.runIfWaitingForDebugger");
+ });
+
+ it("a tab that never answers holds the browser's start only so long", async () => {
+ vi.useFakeTimers();
+ try {
+ const browser = browserWithOpenTab();
+ let started = false;
+ const start = startIdentitySidecar("ws://127.0.0.1:9/devtools/browser/x", IDENTITY, browser.connect).then(() => { started = true; });
+ await vi.advanceTimersByTimeAsync(IDENTITY_LANDS_MS - 1);
+ expect(started).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ await start;
+ expect(started).toBe(true);
+ } finally { vi.useRealTimers(); }
+ });
+
it("holds every new page and worker until it has the browser's own identity, then lets it run", async () => {
const browser = fakeBrowser();
await startIdentitySidecar("ws://127.0.0.1:9/devtools/browser/x", IDENTITY, browser.connect);
diff --git a/server/browser/chrome/sidecar.ts b/server/browser/chrome/sidecar.ts
index fe85a25196..7a9a18b98c 100644
--- a/server/browser/chrome/sidecar.ts
+++ b/server/browser/chrome/sidecar.ts
@@ -13,6 +13,9 @@ import type { ChromeIdentity } from "./identity.ts";
/** The pages and workers the browser session attaches to itself; frames and dedicated workers come through their page. */
const BROWSER_TARGETS = [{ type: "page" }, { type: "service_worker" }, { type: "shared_worker" }, { exclude: true }];
const PAUSED_ON_START = { autoAttach: true, waitForDebuggerOnStart: true, flatten: true };
+/** How long a browser's start waits for its open tabs to take the identity: a tab that never answers must not keep the browser
+ * from starting. */
+export const IDENTITY_LANDS_MS = 3_000;
export interface IdentitySidecar {
/** Resolves when the browser closes the connection: it exited, or was replaced. */
@@ -32,10 +35,13 @@ export async function startIdentitySidecar(url: string, identity: SidecarIdentit
let onClosed!: () => void;
const closed = new Promise<void>((resolve) => { onClosed = resolve; });
let cdp: Cdp | null = null;
+ const applying = new Set<Promise<void>>();
const configure = (message: CdpEvent) => {
if (message.method !== "Target.attachedToTarget" || !cdp) return;
const { sessionId, targetInfo } = (message.params ?? {}) as { sessionId?: string; targetInfo?: { type?: string } };
- if (typeof sessionId === "string") void applyIdentity(cdp, sessionId, targetInfo?.type ?? "", identity, options);
+ if (typeof sessionId !== "string") return;
+ const applied = applyIdentity(cdp, sessionId, targetInfo?.type ?? "", identity, options).finally(() => { applying.delete(applied); });
+ applying.add(applied);
};
cdp = await connect(url, 15_000, { event: configure, closed: () => onClosed() });
try {
@@ -44,9 +50,19 @@ export async function startIdentitySidecar(url: string, identity: SidecarIdentit
cdp.close();
throw error;
}
+ await identityLanded(applying);
return { closed, close: () => cdp?.close() };
}
+/** A tab already open isn't paused, so it can navigate before its override lands. Chrome 156 then gives that page and its frames
+ * empty high-entropy client hints, because the launcher's --user-agent leaves the override their only source. */
+async function identityLanded(applying: ReadonlySet<Promise<void>>): Promise<void> {
+ if (!applying.size) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([Promise.allSettled(applying), new Promise((resolve) => { timer = setTimeout(resolve, IDENTITY_LANDS_MS); })]);
+ clearTimeout(timer);
+}
+
/** A paused worker answers its overrides only once it runs, so a worker is sent them and released at once. */
async function applyIdentity(cdp: Cdp, sessionId: string, type: string, identity: SidecarIdentity, options: SidecarOptions): Promise<void> {
try {