Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Browser: a bot call nearing its budget hears "still starting", and a Chrome that dies first says so at once (#7012)
Milind Sonif6f04fede93e
diff --git a/server/browser/input-log.test.ts b/server/browser/input-log.test.tsindex 53857c1b29..c00101348c 100644--- a/server/browser/input-log.test.ts+++ b/server/browser/input-log.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { buildDevsReport } from "../devs-report.ts";import { actionKind, botReason, createBrowserInputLog, pageAction } from "./input-log.ts";+import { BROWSER_STARTING } from "./service.ts";describe("the browser input log", () => {it("prints one line a drop with its reason, engine, transport and session, and counts every one", () => {@@ -56,6 +57,8 @@ describe("the browser input log", () => {expect(botReason("Element '#covered' is covered by <div#cover> at its click point, so the input would land on that element instead.")).toBe("target_not_actionable");expect(botReason("Browser tools are paused while a person controls this browser.")).toBe("person_holds_control");expect(botReason("The browser engine is stuck. Press Restart.")).toBe("browser_stuck");+ expect(botReason(BROWSER_STARTING), "still starting is not a lost call").toBe("browser_starting");+ expect(botReason("The browser did not answer this agent_browser_click call.")).toBe("call_lost");expect(botReason("Something nobody expected")).toBe("engine_error");});diff --git a/server/browser/input-log.ts b/server/browser/input-log.tsindex 2465fadfd6..722d99e910 100644--- a/server/browser/input-log.ts+++ b/server/browser/input-log.ts@@ -19,7 +19,7 @@ export const CLIENT_REASONS = ["stale_after_wait", "queue_full", "queue_halted",export type ClientReason = typeof CLIENT_REASONS[number];export const BOT_REASONS = [- "person_holds_control", "browser_stuck", "call_lost", "browser_closing", "browser_busy", "no_room", "target_not_found",+ "person_holds_control", "browser_stuck", "browser_starting", "call_lost", "browser_closing", "browser_busy", "no_room", "target_not_found","target_not_actionable", "timed_out", "typed_not_landed", "engine_error", "threw",] as const;export type BotReason = typeof BOT_REASONS[number];@@ -55,6 +55,8 @@ export function actionKind(type: unknown): string {const BOT_TEXT: Array<[RegExp, BotReason]> = [[/paused while a person controls/i, "person_holds_control"],[/browser engine is stuck|press restart/i, "browser_stuck"],+ // Before "did not run": a call that answered while the browser was still starting is not a lost call.+ [/browser is still starting/i, "browser_starting"],[/did not (?:answer|run)|may still be running|timed out; restart/i, "call_lost"],[/browser is closing/i, "browser_closing"],[/browsers are already open|no room/i, "no_room"],diff --git a/server/browser/service.test.ts b/server/browser/service.test.tsindex 4e5956cd9b..a657b0948d 100644--- a/server/browser/service.test.ts+++ b/server/browser/service.test.ts@@ -7,7 +7,7 @@ import { removeTempDir } from "../testing/cleanup.ts";import { forbiddenCommand } from "./cdp/testing/real-chrome.ts";import { BROWSER_CONTROL_REFUSAL } from "./control.ts";import { REDDIT_REFUSAL } from "./egress/reddit.ts";-import { BrowserService, type BrowserServiceOptions } from "./service.ts";+import { BROWSER_STARTING, BrowserService, type BrowserServiceOptions } from "./service.ts";import type { Backend } from "./backends.ts";import { FakeBackend, FakeChrome, type FakeDocument, type FakePage } from "./testing/fake-chrome.ts";import { TOOL_LIST } from "./tools.ts";@@ -502,6 +502,62 @@ describe("browsers on one computer", () => {}});+ it("never tears down a start that outlasts a call's budget: the bot hears it is still starting, and its next call takes that browser", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });+ try {+ let ready = false;+ const slow = new FakeBackend(() => {+ const chrome = new FakeChrome({ documents });+ // The first tab runs 20 s in; later tabs at once.+ chrome.delay = (method) => (method === "Page.enable" && !ready ? (ready = true, 20_000) : 0);+ return chrome;+ });+ backends.push(slow);+ const { call, text } = setup({ backend: () => slow, callBudgetMs: 30_000 });+ const answer = async (name: string, args: Record<string, unknown>) => {+ let result: Awaited<ReturnType<typeof call>> | null = null;+ void call(name, args).then((value) => { result = value; });+ for (let waited = 0; result === null && waited < 120_000; waited += 1_000) await vi.advanceTimersByTimeAsync(1_000);+ return result!;+ };+ const first = await answer("agent_browser_open", { url: "https://example.com/form" });+ // 30 s budget, 15 s kept back: the call answers at 15 s, while the first tab runs at 20 s.+ expect(first).toMatchObject({ isError: true });+ expect(text(first)).toBe(BROWSER_STARTING);+ const next = await answer("agent_browser_open", { url: "https://example.com/swap" });+ expect(next.isError).toBeUndefined();+ expect(text(next)).toContain("Opened https://example.com/swap");+ expect(slow.chromes, "one Chrome, never torn down and started again").toHaveLength(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it("says at once that the browser could not start when Chrome dies before its first tab runs", async () => {+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });+ try {+ const dying = new FakeBackend(() => {+ const chrome = new FakeChrome({ documents });+ chrome.delay = (method) => {+ if (method !== "Page.enable") return 0;+ setTimeout(() => chrome.exit("Chrome crashed"), 1_000);+ return 600_000;+ };+ return chrome;+ });+ backends.push(dying);+ const { call, text } = setup({ backend: () => dying });+ let result: Awaited<ReturnType<typeof call>> | null = null;+ void call("agent_browser_open", { url: "https://example.com/form" }).then((answer) => { result = answer; });+ let waited = 0;+ for (; result === null && waited < 120_000; waited += 1_000) await vi.advanceTimersByTimeAsync(1_000);+ expect(text(result!)).toContain("The browser could not start: Chrome closed before its first tab opened.");+ expect(waited, "not after the first-tab wait").toBeLessThanOrEqual(5_000);+ } finally {+ vi.useRealTimers();+ }+ });+it("makes room by closing the least recently used idle browser, and waits, then refuses, when none is idle", async () => {const { service, call, backend } = setup({ maxRunning: 1, capacityWaitMs: 100 });const other = { session: "bot-b", key: "bot:b" };diff --git a/server/browser/service.ts b/server/browser/service.tsindex 355aee08d1..6a433863fb 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -49,6 +49,10 @@ const CAPACITY_WAIT_MS = 30_000;* (chrome/launch.ts). On a busy or CPU-capped computer the first tab can take longer than 15 s, and refusing it then only* made the bot start Chrome again from nothing. */const FIRST_TAB_MS = 60_000;+/** What a bot's call keeps back from its budget while the browser starts: the call answers "still starting" by then, so+ * it never ends as a lost call, and the start carries on for its next call. */+const STARTING_MARGIN_MS = 15_000;+export const BROWSER_STARTING = "The browser is still starting (this computer is busy), so this call did not run. Call again in a moment: the next call uses the same browser once it is up.";const SERVER_TAB_LIMIT = 32;const PROFILE_TAB_LIMIT = 8;@@ -260,7 +264,12 @@ export class BrowserService {}));try {this.#stillWanted(profile, epoch);- await browser.waitForPage(() => true, FIRST_TAB_MS);+ // A Chrome that dies before any tab runs says so at once, not when the wait ends.+ const firstTab = browser.waitForPage(() => true, FIRST_TAB_MS);+ const died = opened.exited.then(() => { throw new Error("Chrome closed before its first tab opened."); });+ firstTab.catch(() => undefined);+ died.catch(() => undefined);+ await Promise.race([firstTab, died]);for (const page of browser.pages()) await page.ready.then(() => adopt(page, "restored"), () => undefined);if (fresh) await this.#onlyBlankTab(profile, browser);// Chrome gives a new window's keyboard to its address bar, and the bot's DevTools Protocol work never moves it: on a@@ -496,7 +505,9 @@ export class BrowserService {if (!parsed.ok) return errorResult(parsed.error);let run: Running;try {- run = await this.running(profile);+ const started = await this.#startedBy(profile, deadline);+ if (started === null) return errorResult(BROWSER_STARTING);+ run = started;} catch (error) {return errorResult(`The browser could not start: ${error instanceof Error ? error.message : String(error)}`);}@@ -525,6 +536,21 @@ export class BrowserService {}}+ /** The running browser, or null when it is still starting as the call's budget nears its end. The start is shared and+ * carries on; nothing is latched, so the next call takes the same browser. */+ async #startedBy(profile: ProfileState, deadline: number): Promise<Running | null> {+ const starting = this.running(profile);+ let timer: ReturnType<typeof setTimeout> | undefined;+ const late = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), Math.max(0, deadline - Date.now() - STARTING_MARGIN_MS)); timer.unref?.(); });+ try {+ const outcome = await Promise.race([starting, late]);+ if (outcome === null) starting.catch(() => undefined);+ return outcome;+ } finally {+ clearTimeout(timer);+ }+ }+#context(profile: ProfileState, run: Running, deadline: number): ToolContext {return {control: profile.control,