Skip to content

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

Release-gate flakes: browser panel sizing, and four tests made deterministic (#6877)

Milind Sonibe12271c9389
diff --git a/server/browser/cdp/browser.ts b/server/browser/cdp/browser.ts
index 65472857d3..4f3cd97f1a 100644
--- a/server/browser/cdp/browser.ts
+++ b/server/browser/cdp/browser.ts
@@ -11,6 +11,8 @@ import type { CdpTransport } from "./transport.ts";
/** The page size a headless browser connected without one is fitted to; setViewport changes it. */
export const VIEWPORT = { width: 1280, height: 720 } as const;
const FIT_ROUNDS = 3;
+/** How often a page that still reports an ended emulation's layout is measured again, 25 ms apart, before it is taken at its word. */
+const ENDED_EMULATION_POLLS = 80;
export interface BrowserOptions {
/** The binary's calibrated headed identity, applied to every page, frame and worker. Null in a window, which is natively that identity. */
@@ -172,13 +174,19 @@ export class CdpBrowser implements PageHost {
try {
const { windowId } = await root.send<{ windowId: number }>("Browser.getWindowForTarget", { targetId: page.targetId });
let size = await measure();
+ // An emulation that just ended can still be what the page reports: the window is fitted once its own page shows.
+ const ended = page.takeEndedEmulation();
+ for (let poll = 0; ended && poll < ENDED_EMULATION_POLLS && size[0] === ended.width && size[1] === ended.height; poll++) {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ size = await measure();
+ }
const screen = this.#options.screen;
for (let round = 0; round < FIT_ROUNDS && (size[0] !== viewport.width || size[1] !== viewport.height); round++) {
const { bounds } = await root.send<{ bounds: { width?: number; height?: number } }>("Browser.getWindowBounds", { windowId });
if (!bounds.width || !bounds.height) break;
const width = Math.min(bounds.width + viewport.width - size[0], screen?.width ?? Infinity);
const height = Math.min(bounds.height + viewport.height - size[1], screen?.height ?? Infinity);
- if (width === bounds.width && height === bounds.height) break;
+ if ((width === bounds.width && height === bounds.height) || width < 1 || height < 1) break;
await root.send("Browser.setWindowBounds", { windowId, bounds: { width, height } });
const before = size;
for (let poll = 0; poll < 20 && size[0] === before[0] && size[1] === before[1]; poll++) {
diff --git a/server/browser/cdp/page.ts b/server/browser/cdp/page.ts
index a21603546e..dafbcfedc0 100644
--- a/server/browser/cdp/page.ts
+++ b/server/browser/cdp/page.ts
@@ -90,6 +90,7 @@ export class CdpPage implements ActionContext, WaitContext {
#devicePixelRatio: number | null = null;
#documentStatus: { loaderId: string; status: number } | null = null;
#emulated: { width: number; height: number; zoom: number } | null = null;
+ #endedEmulation: { width: number; height: number } | null = null;
constructor(host: PageHost, session: CdpSession, info: TargetInfo) {
this.#host = host;
@@ -288,8 +289,10 @@ export class CdpPage implements ActionContext, WaitContext {
/** Lays the page out at `size` whatever its window's size, drawn `zoom` times larger, as DevTools' device mode does; null ends that. */
async emulateSize(size: { width: number; height: number } | null, zoom = 1): Promise<void> {
if (!size) {
+ const ended = this.#emulated;
this.#emulated = null;
await this.session.send("Emulation.clearDeviceMetricsOverride");
+ if (ended) this.#endedEmulation = { width: ended.width, height: ended.height };
return;
}
const ratio = await this.devicePixelRatio().catch(() => 1);
@@ -297,6 +300,17 @@ export class CdpPage implements ActionContext, WaitContext {
this.#emulated = { width: size.width, height: size.height, zoom };
}
+ /**
+ * The layout of an emulation that ended since this was last asked. Chrome answers the end before the page's renderer
+ * takes it, so the page can report this size a moment longer; a window fitted from that measure is sized for a page
+ * that is not there.
+ */
+ takeEndedEmulation(): { width: number; height: number } | null {
+ const ended = this.#endedEmulation;
+ this.#endedEmulation = null;
+ return ended;
+ }
+
async devicePixelRatio(): Promise<number> {
if (this.#devicePixelRatio === null) {
const ratio = await valueInWorld<number>(this.frames, this.frames.mainFrameId, "devicePixelRatio");
diff --git a/server/browser/testing/fake-chrome.ts b/server/browser/testing/fake-chrome.ts
index 41aaaeaa2c..7d7ed7423b 100644
--- a/server/browser/testing/fake-chrome.ts
+++ b/server/browser/testing/fake-chrome.ts
@@ -37,6 +37,10 @@ export interface FakePage {
focused: number | null;
/** Emulation.setDeviceMetricsOverride's size, which the page then reports instead of its window's. */
emulated?: { width: number; height: number } | null;
+ /** A window resize landed after the emulation: the page is drawn at its window's size, and still reports the emulated one. */
+ viewLost?: boolean;
+ /** The size of an emulation that ended, and how many more measures answer with it. */
+ lagging?: { width: number; height: number; measures: number } | null;
/** A bar of this height over the page, as Chrome's first tab has. */
bar?: number;
screencasts: Map<string, { params: Record<string, unknown>; acked: number; sent: number }>;
@@ -63,6 +67,8 @@ export class FakeChrome implements CdpTransport {
hang: (method: string) => boolean = () => false;
/** Milliseconds before a command answers, to stand for a slow page. */
delay: (method: string) => number = () => 0;
+ /** How many measures a page still answers with an emulation's size after it ended, as a renderer that has not yet taken the end does. */
+ lateClears = 0;
/** What the next navigations fail with, in order, such as net::ERR_ABORTED. */
readonly navigationErrors: string[];
readonly #documents: (url: string) => FakeDocument;
@@ -241,7 +247,11 @@ export class FakeChrome implements CdpTransport {
#evaluate(page: FakePage, expression: string): unknown {
const viewport = page.emulated ?? { width: this.viewport.width, height: this.viewport.height - (page.bar ?? 0) };
- if (expression === "[innerWidth, innerHeight]") return [viewport.width, viewport.height];
+ if (expression === "[innerWidth, innerHeight]") {
+ const lagging = page.lagging;
+ if (!lagging || page.emulated || lagging.measures-- <= 0) return [viewport.width, viewport.height];
+ return [lagging.width, lagging.height];
+ }
if (expression === "devicePixelRatio") return this.dpr;
if (expression === "document.readyState") return "complete";
if (expression === "document.title") return page.title;
@@ -274,8 +284,10 @@ export class FakeChrome implements CdpTransport {
return { frameTree: { frame: { id: page.targetId, url: page.url, loaderId: page.loaderId } } };
case "Emulation.setDeviceMetricsOverride":
page.emulated = { width: Number(params.width), height: Number(params.height) };
+ page.viewLost = false;
return {};
case "Emulation.clearDeviceMetricsOverride":
+ page.lagging = page.emulated && this.lateClears > 0 ? { ...page.emulated, measures: this.lateClears } : null;
page.emulated = null;
return {};
case "Page.createIsolatedWorld":
@@ -394,10 +406,19 @@ export class FakeChrome implements CdpTransport {
const cast = page.screencasts.get(sessionId);
if (!cast) return;
cast.sent++;
- const viewport = this.viewport;
+ const viewport = page.emulated && !page.viewLost ? page.emulated : this.viewport;
this.event("Page.screencastFrame", { data: JPEG, sessionId: cast.sent, metadata: { deviceWidth: viewport.width, deviceHeight: viewport.height, offsetTop: 0, pageScaleFactor: 1, scrollOffsetX: 0, scrollOffsetY: 0, timestamp: Date.now() / 1000 } }, sessionId);
}
+ /** A window resize lands after its pages were emulated, as a slow one does: they are drawn at the window's size again. */
+ landResize(): void {
+ for (const page of this.pages.values()) {
+ if (!page.emulated) continue;
+ page.viewLost = true;
+ this.paint(page);
+ }
+ }
+
/** The page repaints: every screencast on it gets a frame. */
paint(page: FakePage): void {
for (const sessionId of page.screencasts.keys()) this.#frame(page, sessionId);
diff --git a/server/browser/viewers/core.test.ts b/server/browser/viewers/core.test.ts
index 2f8efdfeb0..fa57147901 100644
--- a/server/browser/viewers/core.test.ts
+++ b/server/browser/viewers/core.test.ts
@@ -138,6 +138,39 @@ describe("the page fills the panel", () => {
expect(chrome().window.height).toBeLessThanOrEqual(757 + 143);
});
+ it("fits the window to the page's own size once a tall panel's emulation ends, though the page reports the emulated size a moment longer", async () => {
+ const { watch, chrome, page } = await setup({ pageLimit: { width: 1440, height: 757 } });
+ const { viewer } = await watch({ size: { width: 1600, height: 1000 } });
+ await viewer.input({ type: "resize", width: 400, height: 750 });
+ expect(page().emulated).toEqual({ width: 1280, height: 2400 });
+ chrome().lateClears = 2;
+ const before = chrome().sent.length;
+ await viewer.input({ type: "resize", width: 1280, height: 700 });
+ expect(page().emulated).toBeNull();
+ expect(chrome().viewport).toEqual({ width: 1280, height: 700 });
+ // One resize, from the window's own page: a measure of the emulated 2400 would ask for a window of no height.
+ expect(chrome().sent.slice(before).filter((sent) => sent.method === "Browser.setWindowBounds").map((sent) => sent.params.bounds)).toEqual([{ width: 1280, height: 843 }]);
+ });
+
+ it("applies a tall panel's emulation again when the window's resize lands after it and the frames show the window's size", async () => {
+ const { watch, chrome, page } = await setup({ pageLimit: { width: 1440, height: 757 } });
+ const { viewer, outputs } = await watch({ size: { width: 1600, height: 1000 } });
+ await viewer.input({ type: "resize", width: 400, height: 750 });
+ const drawn = () => { const frame = outputs.filter((output) => output.type === "frame" && !output.still).at(-1); return frame?.type === "frame" ? [frame.metadata.deviceWidth, frame.metadata.deviceHeight] : null; };
+ chrome().paint(page());
+ await until(drawn, same([1280, 2400]));
+ const emulations = () => chrome().sentTo(page()).filter((sent) => sent.method === "Emulation.setDeviceMetricsOverride").length;
+ const before = emulations();
+ chrome().landResize();
+ // The page still reports 1280x2400 and is drawn 1280x757: only its frames show it.
+ await until(() => page().viewLost, same(false));
+ expect(emulations()).toBe(before + 1);
+ expect(page().emulated).toEqual({ width: 1280, height: 2400 });
+ chrome().paint(page());
+ await until(drawn, same([1280, 2400]));
+ expect(emulations()).toBe(before + 1);
+ });
+
it("resizes the real window, so a page narrower than any window comes from a preset only, emulated", async () => {
const { watch, chrome, page } = await setup();
const { viewer } = await watch({ size: { width: 1600, height: 1000 } });
diff --git a/server/browser/viewers/core.ts b/server/browser/viewers/core.ts
index 3f1beb9d38..15ce112314 100644
--- a/server/browser/viewers/core.ts
+++ b/server/browser/viewers/core.ts
@@ -23,6 +23,7 @@ import { extensionInput, type InstalledExtension } from "../extensions.ts";
import type { HoldLimits } from "../hold.ts";
import type { Tab } from "../tabs.ts";
import { ACCEPT_OF, chooseOption, cursorAt, editableAt, selectAt, type SelectPopup } from "./popups.ts";
+import { DrawnView, type FrameMetadata } from "./drawn-view.ts";
import { ViewerHold } from "./hold.ts";
import { fitsScreen, MIN_WINDOW_WIDTH, requestedSize, VIEWPORT_PRESETS, viewportFor, ZOOM_LIMITS, zoomedLayout, type ViewportSetting } from "./viewport.ts";
@@ -41,15 +42,7 @@ const TEXT_LIMIT = 10_000;
const HELD_LIMIT = 64;
const CURSOR_EVERY_MS = 120;
-export interface FrameMetadata {
- deviceWidth: number;
- deviceHeight: number;
- offsetTop: number;
- pageScaleFactor: number;
- scrollOffsetX: number;
- scrollOffsetY: number;
- timestamp?: number;
-}
+export type { FrameMetadata } from "./drawn-view.ts";
export type Controller = "agent" | "you" | "another-viewer" | "unclaimed";
@@ -280,6 +273,7 @@ export class Viewer {
return;
}
this.#frameSeen = true;
+ if (this.tab) this.#hub.drawn.frame(this.tab, params.metadata as FrameMetadata);
if (this.#framesInFlight > 0) this.#mayHaveDropped = true;
this.#framesInFlight++;
const arrivedAt = Date.now();
@@ -443,6 +437,8 @@ export class ViewerHub {
#emulated = false;
#applying: Promise<void> = Promise.resolve();
readonly #hold: ViewerHold;
+ /** Applies a page's emulation again when its frames show the window's size instead. */
+ readonly drawn = new DrawnView((tab, work) => this.paused(tab, work));
constructor(host: HubHost) {
this.host = host;
diff --git a/server/browser/viewers/drawn-view.ts b/server/browser/viewers/drawn-view.ts
new file mode 100644
index 0000000000..1557ce0734
--- /dev/null
+++ b/server/browser/viewers/drawn-view.ts
@@ -0,0 +1,51 @@
+// The size a bot's page is drawn at, against the size it is laid out at. An emulated page (a panel taller than the
+// screen, a preset narrower than any window, a zoom) is laid out at a size its window does not have. A window whose
+// resize lands after the emulation was applied takes the page's view back to the window's size (Chrome 157). The page
+// cannot see that: it goes on reporting the emulated layout while every frame shows the window's, until the emulation
+// is applied again.
+import type { Tab } from "../tabs.ts";
+
+export interface FrameMetadata {
+ deviceWidth: number;
+ deviceHeight: number;
+ offsetTop: number;
+ pageScaleFactor: number;
+ scrollOffsetX: number;
+ scrollOffsetY: number;
+ timestamp?: number;
+}
+
+/** How often one page's emulation is applied again with no frame at its size in between: past that the page is left as it draws. */
+const MAX_RESTORES = 5;
+
+export class DrawnView {
+ readonly #turn: (tab: Tab, work: () => Promise<void>) => Promise<void>;
+ readonly #restores = new WeakMap<Tab, number>();
+ readonly #pending = new WeakSet<Tab>();
+
+ /** `turn` runs `work` when no size change or capture of the tab is under way. */
+ constructor(turn: (tab: Tab, work: () => Promise<void>) => Promise<void>) {
+ this.#turn = turn;
+ }
+
+ /** A live frame of `tab` came. Drawn at another size than the page's emulated layout, the emulation is applied again. */
+ frame(tab: Tab, metadata: FrameMetadata): void {
+ const emulated = tab.page.emulated;
+ if (!emulated) return;
+ // A zoom's layout is rounded to whole pixels, so a frame may be one off.
+ if (Math.abs(metadata.deviceWidth - emulated.width) <= 1 && Math.abs(metadata.deviceHeight - emulated.height) <= 1) {
+ this.#restores.delete(tab);
+ return;
+ }
+ const restores = this.#restores.get(tab) ?? 0;
+ if (this.#pending.has(tab) || restores >= MAX_RESTORES) return;
+ this.#pending.add(tab);
+ this.#restores.set(tab, restores + 1);
+ const restore = async () => {
+ this.#pending.delete(tab);
+ const now = tab.page.emulated;
+ if (now && !tab.page.closed) await tab.page.emulateSize({ width: now.width, height: now.height }, now.zoom);
+ };
+ void this.#turn(tab, restore).catch(() => { this.#pending.delete(tab); });
+ }
+}
diff --git a/server/checkpoints-perf.test.ts b/server/checkpoints-perf.test.ts
index d39fc4ec04..6aac50822f 100644
--- a/server/checkpoints-perf.test.ts
+++ b/server/checkpoints-perf.test.ts
@@ -786,7 +786,7 @@ describe("a folder being read ahead when its turn starts", () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const reading = prime(bot, cwd);
const turn = snapshot(bot, cwd, "the turn", undefined, { pin: "dispatch-1" });
- await vi.waitFor(() => expect(subcommands()).toContain("add"));
+ await vi.waitFor(() => expect(subcommands()).toContain("add"), { timeout: 15_000 });
giveUp(timeoutError("add"));
expect(await reading).toBe(false);
expect(await turn).toBeNull();
diff --git a/server/drivers/antigravity-turn-outcome.test.ts b/server/drivers/antigravity-turn-outcome.test.ts
index f76147ee05..4345a93109 100644
--- a/server/drivers/antigravity-turn-outcome.test.ts
+++ b/server/drivers/antigravity-turn-outcome.test.ts
@@ -2,7 +2,7 @@
// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
// - apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts (the error
// payload fixtures and the cases of the two reader tests).
-import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { DatabaseSync } from "node:sqlite";
@@ -180,8 +180,8 @@ describe("watchAntigravityPromptOutcome", () => {
const file = join(conversations, "session.db");
append(file, [[USER_INPUT, "first"]]);
const check = await watchAntigravityPromptOutcome(NAME, directory, "session");
- rmSync(file);
- append(join(conversations, "other.db"), [[USER_INPUT, "hold the inode"]]);
+ // Moved aside, not deleted: the first log stays on disk, so the file system cannot hand its inode to the new one.
+ renameSync(file, join(conversations, "replaced.db"));
append(file, [[USER_INPUT, "second"], [USER_INPUT, "third"], [ERROR_MESSAGE, QUOTA_ERROR]]);
expect(await check({ stopReason: "end_turn" })).toBeUndefined();
});
diff --git a/server/host-lazy-claim.e2e.test.ts b/server/host-lazy-claim.e2e.test.ts
index 74905e0f3b..d8814decaf 100644
--- a/server/host-lazy-claim.e2e.test.ts
+++ b/server/host-lazy-claim.e2e.test.ts
@@ -93,6 +93,8 @@ describe("lazy host claim and pin on use (issue #1650)", () => {
TEMP: home, TMP: home, TMPDIR: home,
OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_STATIC_DIR: ui, OMB_TEST_VM_STATE: stateFile,
OMB_USER_DATA: join(home, "user-data"), OMB_TEST_DESKTOP_CUA_CONNECTION: join(home, "user-data", "cua-connection.json"),
+ // The env is built from scratch, so the suite's own switches are repeated: no boot downloads the model list or the announcements.
+ OMB_DISABLE_MODEL_MANIFEST_FETCH: "1", OMB_DISABLE_ANNOUNCEMENTS: "1",
OMB_COMPUTER_CALL_WAIT_MS: String(CALL_WAIT_MS),
OMB_COMPUTER_CALL_ACT_WITHIN_MS: String(ACT_WITHIN_MS), ...env,
}, stdio: ["ignore", "pipe", "pipe"],
@@ -103,7 +105,10 @@ describe("lazy host claim and pin on use (issue #1650)", () => {
await until(async () => {
if (proc.exitCode !== null) throw new Error(`server exited during boot:\n${output}`);
try { return (await fetch(base + "/api/health")).ok; } catch { return false; }
- }, Boolean);
+ }, Boolean).catch((error: unknown) => {
+ if (proc.exitCode !== null) throw error;
+ throw new Error(`the server was running and not yet healthy when the wait ended; it had printed:\n${output}`, { cause: error });
+ });
}
async function stop() {
if (!child) return;
diff --git a/server/host/check-backs.test.ts b/server/host/check-backs.test.ts
index 7d59f4210c..4afaee77a7 100644
--- a/server/host/check-backs.test.ts
+++ b/server/host/check-backs.test.ts
@@ -39,6 +39,19 @@ function harness(over: Partial<CheckBackDeps> = {}, dir = mkdtempSync(join(tmpdi
return { h, manager };
}
+/** A due check-back as a server finds it on disk after `tries` refused starts, so a test near the limit does not spend them one save at a time. */
+function storedWithTries(tries: number, over: Partial<CheckBackDeps> = {}) {
+ const first = harness();
+ first.manager.create(asked());
+ const file = join(first.h.dir, CHECK_BACK_FILE);
+ const saved = JSON.parse(readFileSync(file, "utf8"));
+ saved.checkBacks[0].tries = tries;
+ writeFileSync(file, JSON.stringify(saved));
+ const again = harness(over, first.h.dir);
+ again.h.clock = T0 + 5 * MIN;
+ return again;
+}
+
const asked = (over: Partial<NewCheckBack> = {}): NewCheckBack => ({
botId: "scout", threadId: "t1", note: "see if CI passed", dueAt: T0 + 5 * MIN, zone: "Europe/Berlin",
origin: { kind: "user", request: "fix the build and tell me when CI is green", person: "p_aaaaaaaaaaaaaaaaaaaaaa" }, ...over,
@@ -180,31 +193,34 @@ describe("check-backs", () => {
await manager.tick();
expect(h.started).toHaveLength(1);
- expect(manager.create(asked({ dueAt: h.clock + 5 * MIN })).ok).toBe(true);
- h.refuseStart = "This bot is paused.";
- h.clock += 5 * MIN;
- for (let i = 0; i < START_TRIES; i++) {
- h.clock += START_RETRY_MS;
- await manager.tick();
- }
- expect([...h.lines.values()].at(-1)).toMatchObject({ status: "failed", why: "This bot is paused." });
- expect(manager.nextDueAt()).toBeNull();
+ // The count of refusals is stored, so a restart two short of giving up needs two more, not all of them.
+ const stored = storedWithTries(START_TRIES - 2);
+ stored.h.refuseStart = "This bot is paused.";
+ stored.h.clock += START_RETRY_MS;
+ await stored.manager.tick();
+ expect(stored.manager.nextDueAt()).not.toBeNull();
+ expect([...stored.h.lines.values()]).toEqual([]);
+ stored.h.clock += START_RETRY_MS;
+ await stored.manager.tick();
+ expect([...stored.h.lines.values()].at(-1)).toMatchObject({ status: "failed", why: "This bot is paused." });
+ expect(stored.manager.nextDueAt()).toBeNull();
});
it("waits out a paused bot without using up its tries", async () => {
- const { h, manager } = harness({ paused: (error) => (error as { code?: string }).code === "bot_paused" });
- manager.create(asked());
- h.clock += 5 * MIN;
- const paused = Object.assign(new Error("Scout is paused."), { code: "bot_paused" });
- const start = async () => { throw paused; };
- const held = harness({ paused: (error) => (error as { code?: string }).code === "bot_paused", start }, h.dir);
- held.h.clock = h.clock;
- for (let i = 0; i < START_TRIES + 5; i++) {
+ let refusal: Error = Object.assign(new Error("Scout is paused."), { code: "bot_paused" });
+ // One refusal short of giving up: a pause that counted as a try would end it at the first tick.
+ const held = storedWithTries(START_TRIES - 1, { paused: (error) => (error as { code?: string }).code === "bot_paused", start: async () => { throw refusal; } });
+ for (let i = 0; i < 5; i++) {
held.h.clock += START_RETRY_MS;
await held.manager.tick();
}
expect(held.manager.nextDueAt()).not.toBeNull();
- expect([...held.h.lines.values()].some((line) => line.status === "failed")).toBe(false);
+ expect([...held.h.lines.values()]).toEqual([]);
+ // The count stood one short all along: the next refusal that is no pause is the last.
+ refusal = new Error("Under maintenance.");
+ held.h.clock += START_RETRY_MS;
+ await held.manager.tick();
+ expect([...held.h.lines.values()].at(-1)).toMatchObject({ status: "failed", why: "Under maintenance." });
});
it("names the soonest one to wake a sleeping Cloud", () => {