Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): remove downloads when their session ends
Sebastian B1e30a7da0871
diff --git a/server/browser/service-downloads.test.ts b/server/browser/service-downloads.test.tsnew file mode 100644index 0000000000..25f67af1dd--- /dev/null+++ b/server/browser/service-downloads.test.ts@@ -0,0 +1,109 @@+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { removeTempDir } from "../testing/cleanup.ts";+import type { Backend } from "./backends.ts";+import { CdpBrowser } from "./cdp/browser.ts";+import { BrowserService } from "./service.ts";+import { FakeBackend, FakeChrome } from "./testing/fake-chrome.ts";++const fixtures: Array<{ service: BrowserService; dataDir: string }> = [];+afterEach(async () => {+ for (const { service, dataDir } of fixtures.splice(0)) {+ try { await service.closeAll(); } finally { await removeTempDir(dataDir); }+ }+});++function setup(key = "bot:fixture") {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-browser-downloads-"));+ const backend: Backend = {+ kind: "local",+ caps: new FakeBackend().caps,+ async open(request) {+ const wire = new FakeChrome();+ const browser = await CdpBrowser.connect(wire, { downloadDir: request.downloadDir });+ const exited = new Promise<void>((resolve) => wire.onClose(() => resolve()));+ return { browser, pid: null, version: "153.0.0.0", exited, close: () => browser.close() };+ },+ };+ const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 1, idleMs: () => 1_000 });+ fixtures.push({ service, dataDir });+ const target = { key, session: "bot-fixture" };+ const profile = service.profile(target);+ const download = async () => {+ const run = await service.running(profile);+ writeFileSync(join(profile.downloadDir, "fixture-guid"), "fixture download");+ run.browser.connection.root.emit("Browser.downloadWillBegin", { guid: "fixture-guid", suggestedFilename: "report.txt" });+ run.browser.connection.root.emit("Browser.downloadProgress", { guid: "fixture-guid", state: "completed", receivedBytes: 16 });+ const file = run.browser.downloads!.list()[0]!;+ expect(service.download(target.session, file.id)?.path).toBe(file.path);+ expect(existsSync(file.path!)).toBe(true);+ writeFileSync(join(profile.downloadDir, "partial.crdownload"), "partial");+ return { run, file };+ };+ return { service, target, profile, download };+}++describe("browser download lifetime", () => {+ it("removes completed and partial files with their index across three idle cycles", async () => {+ const { service, target, profile, download } = setup();+ for (let cycle = 0; cycle < 3; cycle++) {+ const { file } = await download();+ expect(await service.closeUnused(target.session)).toBe(true);+ expect(service.download(target.session, file.id)).toBeUndefined();+ expect(existsSync(profile.downloadDir)).toBe(false);+ const next = await service.running(profile);+ expect(next.browser.downloads!.list()).toEqual([]);+ expect(readdirSync(profile.downloadDir)).toEqual([]);+ }+ });++ it.each(["close", "closeAll", "restart", "erase", "temporary", "capacity"] as const)("removes files when the browser ends by %s", async (stop) => {+ const { service, target, profile, download } = setup(stop === "temporary" ? "temp:fixture" : undefined);+ const { file } = await download();+ if (stop === "closeAll") await service.closeAll();+ else if (stop === "restart") await service.restart(target.session, "local-owner");+ else if (stop === "erase") await service.erase(target.key);+ else if (stop === "capacity") await service.running(service.profile({ key: "bot:other", session: "bot-other" }));+ else await service.close(target.session);+ expect(service.download(target.session, file.id)).toBeUndefined();+ expect(existsSync(profile.downloadDir)).toBe(false);+ expect(profile.control.closing).toBe(false);+ });++ it("removes files when Chrome exits unexpectedly", async () => {+ const { service, target, profile, download } = setup();+ const { run, file } = await download();+ run.browser.disconnect();+ await run.opened.exited;+ expect(service.download(target.session, file.id)).toBeUndefined();+ expect(existsSync(profile.downloadDir)).toBe(false);+ });++ it("removes unindexed files left by a previous server before opening the profile", async () => {+ const { service, profile } = setup();+ mkdirSync(join(profile.downloadDir, "old-id"), { recursive: true });+ writeFileSync(join(profile.downloadDir, "old-id", "report.txt"), "old download");+ writeFileSync(join(profile.downloadDir, "partial.crdownload"), "partial");+ const run = await service.running(profile);+ expect(run.browser.downloads!.list()).toEqual([]);+ expect(readdirSync(profile.downloadDir)).toEqual([]);+ });++ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("a failed download cleanup leaves closing reset and can be retried", async () => {+ const { service, target, profile, download } = setup();+ await download();+ chmodSync(profile.downloadDir, 0o500);+ try {+ await expect(service.close(target.session)).rejects.toThrow();+ expect(profile.control.closing).toBe(false);+ expect(profile.stopping).toBeNull();+ } finally {+ chmodSync(profile.downloadDir, 0o700);+ }+ await service.close(target.session);+ expect(existsSync(profile.downloadDir)).toBe(false);+ });+});diff --git a/server/browser/service.ts b/server/browser/service.tsindex b4d1b5e53e..b3e85359e2 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -204,6 +204,7 @@ export class BrowserService {async #open(profile: ProfileState, epoch: number): Promise<Running> {const fresh = profile.fresh;profile.fresh = false;+ rmSync(profile.downloadDir, { recursive: true, force: true });mkdirSync(profile.downloadDir, { recursive: true, mode: 0o700 });const opened = await this.#options.backend(profile.key).open({ key: profile.key, mode: "headless", fresh, viewport: profile.hub.viewport(), downloadDir: profile.downloadDir });const run: Running = { opened, browser: opened.browser, offs: [], closing: false };@@ -273,6 +274,11 @@ export class BrowserService {profile.run = null;profile.tabs.clear();if (run.closing) return;+ try {+ rmSync(profile.downloadDir, { recursive: true, force: true });+ } catch (error) {+ this.#options.log?.(`browser ${profile.key}: could not remove downloads: ${error}`);+ }profile.reopened = { kind: "crash", pages: [] };profile.control.settle();this.#options.log?.(`browser ${profile.key}: Chrome exited unexpectedly; the next call starts it again`);@@ -300,9 +306,13 @@ export class BrowserService {if (profile.run === run) profile.run = null;profile.tabs.clear();if (reopened) profile.reopened = reopened;- if (profile.temporary || erase) this.#erase(profile);- profile.control.closing = false;- profile.control.settle();+ try {+ if (profile.temporary || erase) this.#erase(profile);+ else rmSync(profile.downloadDir, { recursive: true, force: true });+ } finally {+ profile.control.closing = false;+ profile.control.settle();+ }}})().finally(() => { if (profile.stopping === stopping) profile.stopping = null; });profile.stopping = stopping;diff --git a/server/browser/tools.ts b/server/browser/tools.tsindex fe27f239c2..192fd19504 100644--- a/server/browser/tools.ts+++ b/server/browser/tools.ts@@ -131,7 +131,7 @@ export type ToolName = keyof typeof TOOL_INPUTS;export type ToolInput<N extends ToolName> = z.output<(typeof TOOL_INPUTS)[N]>;const DESCRIPTIONS: Record<ToolName, string> = {- agent_browser_status: "Your browser's state: its tabs, the tab in front with its address, title and loading state, who controls it, any open dialog or file picker, and finished downloads with their file paths.",+ agent_browser_status: "Your browser's state: its tabs, the tab in front with its address, title and loading state, who controls it, any open dialog or file picker, and finished downloads with their file paths. Download files and IDs expire when the browser closes, sleeps or restarts; copy files you need to keep.",agent_browser_open: "Open a page in your browser and answer with its snapshot: the page's accessibility tree with element refs (e12) that the other tools act on. Waits for the page to load, at most 15 s.",agent_browser_navigate: "Go to an address in the current tab, or go back, forward or reload. Refs from earlier snapshots stop applying to the new page.",agent_browser_snapshot: "The page's accessibility tree with element refs, across frames and shadow roots, plus what the page reported. Take one before acting when you have no current refs; refs expire when the page navigates or a person takes control. Capped near 20 KB; it lists what it left out.",