Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep desktop browser tabs open while viewed
skygunnerad1765ff2618
diff --git a/docs/browser-packaging.md b/docs/browser-packaging.mdindex 8d9c49ee7c..f8bb392f36 100644--- a/docs/browser-packaging.md+++ b/docs/browser-packaging.md@@ -203,10 +203,11 @@ same rules hold on the desktop, a server and Cloud:fill_login's typing; a preview frame only holds off a close while it istaken), no turn that has used it and is still running, and no personholding it or using it through a Browser panel (opening the panel, a- click, a key, an address, taking or handing back control). A panel that- only watches does not keep it open: the panel says the browser closed- after it sat unused and offers to open it again, and on the new engine- it shows the browser again by itself once the bot's next call starts it.+ click, a key, an address, taking or handing back control). On desktop,+ an open Browser panel also keeps an agent-browser session open while you+ watch it. On servers, watching alone does not extend the idle time. An+ idle-closed panel offers to open the browser again. With the new engine,+ it shows the browser again once the bot's next call starts it.It never reconnects on its own, which would start the browser again.Saved sign-ins stay, and the bot's next browser call opens it again and istold its pages are gone. A temporary browser saves nothing, so it startsdiff --git a/server/browser-launch-key.ts b/server/browser-launch-key.tsindex 9dcda9f103..931906ae7f 100644--- a/server/browser-launch-key.ts+++ b/server/browser-launch-key.ts@@ -8,6 +8,14 @@ import type { BrowserSpawnSpec } from "./browser-runtime.ts";const FNM_PER_SHELL = /(?:^|[\\/])fnm_multishells[\\/][^\\/]+(?:[\\/]bin)?[\\/]?$/u;const FNM_UNRESOLVED = "fnm-multishell";+export function attachesToChrome(env: NodeJS.ProcessEnv): boolean {+ return Boolean(env.AGENT_BROWSER_CDP || env.AGENT_BROWSER_AUTO_CONNECT);+}++export function ownsBrowserViewport(env: NodeJS.ProcessEnv): boolean {+ return env.AGENT_BROWSER_HEADLESS === "1" && !attachesToChrome(env);+}+function fnmTarget(entry: string): string {try { return realpathSync.native(entry); }catch { return FNM_UNRESOLVED; }diff --git a/server/browser-lifecycle-cleanup.ts b/server/browser-lifecycle-cleanup.tsindex b16f9874e6..49bf86df6a 100644--- a/server/browser-lifecycle-cleanup.ts+++ b/server/browser-lifecycle-cleanup.ts@@ -411,7 +411,7 @@ export class BrowserSweep {engine: () => string | null;owns: (session: string) => boolean;live: (session: string) => boolean;- /** A turn holds it until it finishes: never closed while one does. */+ /** The session is in use and skipped by this sweep. */held: (session: string) => boolean;closeIdle: (session: string) => Promise<boolean>;intervalMs?: number;diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.tsindex 07db06be91..03b2c8651b 100644--- a/server/browser-runtime.test.ts+++ b/server/browser-runtime.test.ts@@ -660,6 +660,7 @@ describe("server-owned browser MCP runtime", () => {expect(closeBrowser).toHaveBeenCalledWith("s", expect.objectContaining({ command: process.execPath }));const next = await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "again" } }) as { content: Array<{ text: string }> };expect(next.content[0].text).toMatch(/sat unused and was closed.*saved sign-ins are kept/);+ expect(next.content[0].text).not.toContain("to free memory");expect(next.content[1].text).toContain("again");const after = await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "third" } }) as { content: Array<{ text: string }> };expect(after.content.map((part) => part.text).join("\n")).not.toMatch(/sat unused/);diff --git a/server/browser-runtime.ts b/server/browser-runtime.tsindex b7a4f9689e..e3d6629e0a 100644--- a/server/browser-runtime.ts+++ b/server/browser-runtime.ts@@ -6,7 +6,8 @@ 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";+import { attachesToChrome, launchSettingsKey } from "./browser-launch-key.ts";+export { attachesToChrome, ownsBrowserViewport } from "./browser-launch-key.ts";import { refusedSlot, SharedToolLists, slotRefusal, type BrowserRoom } from "./browser-room.ts";export interface BrowserSpawnSpec {@@ -49,7 +50,7 @@ const RELAYED_TOOL_SPECS = [type RelayedToolSpec = (typeof RELAYED_TOOL_SPECS)[number];const RELAYED_TOOLS: ReadonlyMap<string, RelayedToolSpec> = new Map(RELAYED_TOOL_SPECS.map((spec) => [spec.name, spec]));const BROWSER_INTERRUPTED = `The browser engine is stuck. Press Restart in the Browser panel, or call ${BROWSER_RESTART_TOOL}, before using browser tools again.`;-const idleClosedNote = (saves: boolean) => `Your browser sat unused and was closed to free memory; this call opened it again. Pages you had open are gone (${saves ? "saved sign-ins are kept" : "it is a temporary browser, so its sign-ins are gone too"}), so open the page you need again before using earlier @eN refs.`;+const idleClosedNote = (saves: boolean) => `Your browser sat unused and was closed; this call opened it again. Pages you had open are gone (${saves ? "saved sign-ins are kept" : "it is a temporary browser, so its sign-ins are gone too"}), so open the page you need again before using earlier @eN refs.`;const PERSON_RESTARTED = "The person restarted your browser from the Browser panel; this call ran in the fresh browser. Pages you had open are gone, so open the page you need again before using earlier @eN refs, and check whether an interrupted action already happened before repeating it.";const LANE_BUSY = "Your previous browser call is still running; wait for it to finish, then call again.";/** One bot call, lane wait included, answers within `callBudgetMs`; the engine's action keeps `followUpReserveMs` of it for the reads after. */@@ -72,14 +73,6 @@ export function browserRuntimeEnv(overrides: Record<string, string | undefined>)return { ...env, ...overrides };}-export function attachesToChrome(env: NodeJS.ProcessEnv): boolean {- return Boolean(env.AGENT_BROWSER_CDP || env.AGENT_BROWSER_AUTO_CONNECT);-}--export function ownsBrowserViewport(env: NodeJS.ProcessEnv): boolean {- return env.AGENT_BROWSER_HEADLESS === "1" && !attachesToChrome(env);-}-export class TransportError extends Error {}/** One timed browser action (ms), logged with OMB_BROWSER_TIMING=1; `inFlight` is this session's work already running. */@@ -348,7 +341,7 @@ export class BrowserRuntime {readonly pageSizes = new PageSizes({apply: (session, size) => { const spec = this.gates.get(session)?.spec; return spec && this.applyViewport ? this.applyViewport(spec, size) : Promise.resolve(); },lane: (session, work) => this.lanes.run(session, work, this.options.laneWaitMs),- watched: (session) => { const gate = this.gates.get(session); return Boolean(gate && gate.watchers > 0 && !gate.closing); },+ watched: (session) => this.watched(session),});private holds = new SecretHolds((session, clear) => this.lanes.run(session, () => this.agentAction(session, clear, false), this.options.laneWaitMs).then((ran) => ran !== null));/** Strips held secrets (a filled password, a one-time code) from every tool result before the bot reads it. */@@ -826,6 +819,7 @@ export class BrowserRuntime {};}+ watched(session: string): boolean { const gate = this.gates.get(session); return Boolean(gate && gate.watchers > 0 && !gate.closing); }async settled(session: string): Promise<void> { await this.gates.get(session)?.idleClose; }/** A bot call, a person's action or hold, or a close is under way in this session's browser. */diff --git a/server/browser/checklist.e2e.test.ts b/server/browser/checklist.e2e.test.tsindex da54e79506..a734541cff 100644--- a/server/browser/checklist.e2e.test.ts+++ b/server/browser/checklist.e2e.test.ts@@ -226,7 +226,9 @@ suite("the bots' browser service on real Chrome", () => {await real.call(target, "agent_browser_open", { url: page("/idle", "<p>idle</p>") });await new Promise((resolve) => setTimeout(resolve, 20));expect(await real.service.closeIdle(1)).toContain(target.key);- expect(real.text(await real.call(target, "agent_browser_status"))).toContain("Your browser sat unused and was closed to free memory");+ const reopened = real.text(await real.call(target, "agent_browser_status"));+ expect(reopened).toContain("Your browser sat unused and was closed");+ expect(reopened).not.toContain("to free memory");}, hostTimeout(90_000));});diff --git a/server/browser/service.test.ts b/server/browser/service.test.tsindex a657b0948d..a17e4a9693 100644--- a/server/browser/service.test.ts+++ b/server/browser/service.test.ts@@ -393,7 +393,8 @@ describe("browsers on one computer", () => {expect(await service.closeIdle(1)).toEqual(["bot:a"]);expect(backend.chromes).toHaveLength(1);const reopened = text(await call("agent_browser_status"));- expect(reopened).toContain("Your browser sat unused and was closed to free memory");+ expect(reopened).toContain("Your browser sat unused and was closed");+ expect(reopened).not.toContain("to free memory");expect(backend.chromes).toHaveLength(2);});@@ -412,7 +413,9 @@ describe("browsers on one computer", () => {expect(await service.closeUnused(target.session)).toBe(true);expect(service.runs(target.session)).toBe(false);expect(await service.closeUnused(target.session)).toBe(false);- expect(text(await call("agent_browser_status"))).toContain("Your browser sat unused and was closed to free memory");+ const reopened = text(await call("agent_browser_status"));+ expect(reopened).toContain("Your browser sat unused and was closed");+ expect(reopened).not.toContain("to free memory");expect(backend.chromes).toHaveLength(2);});@@ -434,7 +437,9 @@ describe("browsers on one computer", () => {expect(service.profiles()[0]!.hub.size).toBe(1);expect(backend.chromes).toHaveLength(1);outputs.length = 0;- expect(text(await call("agent_browser_status"))).toContain("Your browser sat unused and was closed to free memory");+ const reopened = text(await call("agent_browser_status"));+ expect(reopened).toContain("Your browser sat unused and was closed");+ expect(reopened).not.toContain("to free memory");expect(backend.chromes).toHaveLength(2);expect(outputs).toContain("awake");for (let waited = 0; !outputs.includes("frame") && waited < 1_000; waited += 10) await sleep(10);diff --git a/server/browser/service.ts b/server/browser/service.tsindex 6a433863fb..f6768737aa 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -149,7 +149,7 @@ function reopenedNote(reopened: NonNullable<Reopened>, temporary: boolean): striconst refs = " Refs from before are gone: take a snapshot before acting on refs.";if (reopened.kind === "restart") return `The browser was restarted; this call ran in the fresh browser, on one blank tab.${refs} Check whether an interrupted action already happened before repeating it.`;if (reopened.kind === "crash") return `Your browser stopped unexpectedly, and this call started it again.${pages}${refs}`;- return `Your browser sat unused and was closed to free memory; this call opened it again.${temporary ? " It is a temporary browser, so its sign-ins are gone too." : pages}${refs}`;+ return `Your browser sat unused and was closed; this call opened it again.${temporary ? " It is a temporary browser, so its sign-ins are gone too." : pages}${refs}`;}export class BrowserService {diff --git a/server/host/browser.test.ts b/server/host/browser.test.tsindex 9d2b7473dc..d6ec8fc32d 100644--- a/server/host/browser.test.ts+++ b/server/host/browser.test.ts@@ -695,6 +695,34 @@ describe("a running turn's agent-browser browser", () => {}});+ it.each([true, false])("keeps watched desktop tabs past the idle cutoff (used by a bot: %s)", async (usedByBot) => {+ ready();+ const session = "bot-scout";+ const { host } = setup(undefined);+ daemons([session]);+ const closing = vi.spyOn(BrowserRuntime.prototype, "closeIfIdle");+ await host.browserRuntime.closeIfIdle(session, HOUR * 1_000, keepsSignIns);+ const agentBrowser = closing.mock.contexts[0] as BrowserRuntime;+ closing.mockRestore();+ if (usedByBot) host.usedBrowserSessions.set(session, keepsSignIns);+ const unwatch = agentBrowser.watch(session, keepsSignIns);+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ anHourLater();+ try {+ host.browserSweep.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(runningBrowserSessionNames).toHaveBeenCalled();+ expect(closedSessions()).toEqual([]);+ unwatch();+ await vi.advanceTimersByTimeAsync(60_000);+ expect(closedSessions()).toEqual([session]);+ } finally {+ unwatch();+ await host.browserSweep.closeAll();+ vi.useRealTimers();+ }+ });+it("is closed for a bot waiting on a full limit only once it sat unused for the idle time and keeps its sign-ins", async () => {ready();const { host } = setup(undefined, { cloudHome: true, turnResources: holding(["bot-a", "bot-t"]), browsersAtOnce: () => 2 });diff --git a/server/host/browser.ts b/server/host/browser.tsindex f0dd46d71c..23603e0b69 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -383,7 +383,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {engine: () => { const engine = browserEngineStatus(); return engine.kind === "ready" ? engine.binaryPath : null; },owns: (session) => belongs(session) || (Boolean(CLOUD_HOME) && BOT_SESSION.test(session)),live: (session) => usedBrowserSessions.has(session) && belongs(session),- held: (session) => !turnResources.free(`browser:${session}`),+ held: (session) => !turnResources.free(`browser:${session}`) || (DESKTOP_MANAGED && agentBrowserRuntime.watched(session)),closeIdle: (session) => browserRuntime.closeIfIdle(session, idleMs(), usedBrowserSessions.get(session)),});// A browser that has ended keeps no loopback listener: its gate opens again with it, on the same port where it can, and