Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(browser): the bot's live page fills its panel on both engines, at a desktop's width (#3691)
Milind Soni49088dc76b80
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5712cda24e..e41b535760 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -452,7 +452,7 @@ jobs:env:OMB_UI_E2E: "1"OMB_UI_EVIDENCE_DIR: .omb-scratch/verify-evidence- run: pnpm exec vitest run scripts/testing/control-omb-ui.e2e.test.ts scripts/testing/bot-tools-ui.e2e.test.ts scripts/testing/thinking-timer-ui.e2e.test.ts scripts/testing/team-share-ui.e2e.test.ts scripts/testing/org-library-ui.e2e.test.ts scripts/testing/presets-ui.e2e.test.ts scripts/testing/browser-evidence.e2e.test.ts scripts/testing/rich-table-composer-ui.e2e.test.ts scripts/testing/computer-panel-focus-ui.e2e.test.ts scripts/testing/mobile-code-blocks-ui.e2e.test.ts+ run: pnpm exec vitest run scripts/testing/control-omb-ui.e2e.test.ts scripts/testing/bot-tools-ui.e2e.test.ts scripts/testing/thinking-timer-ui.e2e.test.ts scripts/testing/team-share-ui.e2e.test.ts scripts/testing/org-library-ui.e2e.test.ts scripts/testing/presets-ui.e2e.test.ts scripts/testing/browser-evidence.e2e.test.ts scripts/testing/browser-fill.e2e.test.ts scripts/testing/rich-table-composer-ui.e2e.test.ts scripts/testing/computer-panel-focus-ui.e2e.test.ts scripts/testing/mobile-code-blocks-ui.e2e.test.ts- name: Upload the renderer screenshotuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1if: always()diff --git a/docs/verification/browser-live.md b/docs/verification/browser-live.mdindex c532012c83..bb9882b999 100644--- a/docs/verification/browser-live.md+++ b/docs/verification/browser-live.md@@ -60,10 +60,14 @@ UI and harness, then removes its temporary data; the server log remains.6. Test narrow (390 px) and desktop widths, fullscreen, tabs, overflow typing,and explicit browser restart. No horizontal document overflow or permanentsettings panels should appear. Profile changes are disabled during control.- The complete browser image must fit the panel without changing the remote- page's resolution. Click the same test-page controls at each size: input- must follow the contained image, not its surrounding letterboxing. Empty- margins must not click the page; a drag begun on the image can finish there.+ The page fills the panel: it is never narrower than 1280 CSS pixels, so+ sites keep their desktop layout, and its height follows the panel's shape+ up to twice its width; only a taller panel shows bands above and below.+ Resizing the panel resizes the page once the bot's running action ends, and+ with no view open the page is 1280x720 again at the bot's next action.+ Click the same test-page controls at each size: input must land where the+ image shows them. Bands must not click the page; a drag begun on the image+ can finish there.7. Reconnect while a restart is still finishing, or change profiles before anearlier command finishes. A late response must not disconnect the new view,change its error state, or acknowledge an old frame as the new viewer.@@ -99,10 +103,30 @@ UI and harness, then removes its temporary data; the server log remains.that hangs (`while (true) {}`) is restarted for you after about 35 seconds. The panel reconnects, and sign-insare kept.+### A narrow panel filled++Run `node --experimental-strip-types scripts/control-omb.ts ui launch --entry threads`, turn on+`features.browser`, allow the test page's loopback port in `browserEngine.egress.allow`, open the+bot's screen and its Browser tab in Simple mode, and open the test page. The page must reach every+edge of the panel at 1280 CSS pixels wide; Maximize shows it at the window's own size; a preset+from the menu (new engine) still shows bands on purpose.++| | Midnight | Daylight |+| --- | --- | --- |+| Before: 1280x720 with bands |  |  |+| After: 1280x2406, the panel's shape |  |  |++| Maximized, before | Maximized, after | A wider Advanced panel | Tablet preset (new engine) |+| --- | --- | --- | --- |+|  |  |  |  |++`scripts/testing/browser-fill.e2e.test.ts` runs the agent-browser side against the pinned engine and+`server/browser/viewers/viewers.e2e.test.ts` the new engine's (`OMB_CDP_CHROME`).+Focused automated coverage:```sh-pnpm exec vitest run server/browser-engine.test.ts server/browser-runtime.test.ts \+pnpm exec vitest run server/browser-engine.test.ts server/browser-runtime.test.ts server/browser-page-size.test.ts \server/harness-mcp-proxy.test.ts server/browser-live.test.ts server/browser-dialogs.test.ts \server/browser-live-routes.test.ts server/browser-codex-path.integration.test.ts \src/lib/browser-stream-v1.test.ts src/lib/browser-stream-client.test.ts src/lib/browser-control.test.ts \diff --git a/docs/verification/images/browser-fill/after-daylight-simple.png b/docs/verification/images/browser-fill/after-daylight-simple.pngnew file mode 100644index 0000000000..0e8cfc07bfBinary files /dev/null and b/docs/verification/images/browser-fill/after-daylight-simple.png differdiff --git a/docs/verification/images/browser-fill/after-midnight-advanced-wide.png b/docs/verification/images/browser-fill/after-midnight-advanced-wide.pngnew file mode 100644index 0000000000..b310000ff7Binary files /dev/null and b/docs/verification/images/browser-fill/after-midnight-advanced-wide.png differdiff --git a/docs/verification/images/browser-fill/after-midnight-maximized.png b/docs/verification/images/browser-fill/after-midnight-maximized.pngnew file mode 100644index 0000000000..419955436fBinary files /dev/null and b/docs/verification/images/browser-fill/after-midnight-maximized.png differdiff --git a/docs/verification/images/browser-fill/after-midnight-simple.png b/docs/verification/images/browser-fill/after-midnight-simple.pngnew file mode 100644index 0000000000..ddd5bf822dBinary files /dev/null and b/docs/verification/images/browser-fill/after-midnight-simple.png differdiff --git a/docs/verification/images/browser-fill/after-new-engine-tablet-preset.png b/docs/verification/images/browser-fill/after-new-engine-tablet-preset.pngnew file mode 100644index 0000000000..72c87338faBinary files /dev/null and b/docs/verification/images/browser-fill/after-new-engine-tablet-preset.png differdiff --git a/docs/verification/images/browser-fill/before-daylight-simple.png b/docs/verification/images/browser-fill/before-daylight-simple.pngnew file mode 100644index 0000000000..959a04ca47Binary files /dev/null and b/docs/verification/images/browser-fill/before-daylight-simple.png differdiff --git a/docs/verification/images/browser-fill/before-midnight-maximized.png b/docs/verification/images/browser-fill/before-midnight-maximized.pngnew file mode 100644index 0000000000..19b32e0599Binary files /dev/null and b/docs/verification/images/browser-fill/before-midnight-maximized.png differdiff --git a/docs/verification/images/browser-fill/before-midnight-simple.png b/docs/verification/images/browser-fill/before-midnight-simple.pngnew file mode 100644index 0000000000..d2469db45eBinary files /dev/null and b/docs/verification/images/browser-fill/before-midnight-simple.png differdiff --git a/scripts/testing/browser-fill.e2e.test.ts b/scripts/testing/browser-fill.e2e.test.tsnew file mode 100644index 0000000000..bb606e613c--- /dev/null+++ b/scripts/testing/browser-fill.e2e.test.ts@@ -0,0 +1,164 @@+// A person watching a bot's agent-browser page in a narrow panel, against the pinned agent-browser and its Chrome:+// the page fills the panel at a desktop's width, a resize waits for the bot's running call, the bot's click lands on+// the page as it is laid out, its screenshot of the tall page comes as JPEG, and the standard page returns once nobody+// watches. Runs when agent-browser resolves (tools directory, OMB_AGENT_BROWSER_PATH or PATH) or OMB_UI_E2E=1 asks for+// the download; otherwise skipped.+import { randomBytes } from "node:crypto";+import { mkdirSync, mkdtempSync } from "node:fs";+import { createServer, type Server } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { agentBrowserIntegration, closeBrowserSession, prepareBrowserSessionState, resolveAgentBrowserBinary, setBrowserViewport } from "../../server/browser-engine.ts";+import { BrowserLive } from "../../server/browser-live.ts";+import { BROWSER_VIEWPORT, type PageSize } from "../../server/browser-page-size.ts";+import { relay, RelayPorts, relayTarget } from "../../server/browser-relay.ts";+import { BrowserRuntime, browserRuntimeEnv, type BrowserSpawnSpec } from "../../server/browser-runtime.ts";+import { openGate, type EgressGate } from "../../server/browser/egress/gate.ts";+import { refusalFor } from "../../server/browser/egress/policy.ts";+import { SseRecorder } from "../../server/browser/viewers/testing/v1-session.ts";+import { removeTempDir } from "../../server/testing/cleanup.ts";+import { ensureUiBrowser, UI_TOOLS_DIR } from "./control-omb-ui.ts";++const forced = process.env.OMB_UI_E2E === "1";+const enabled = forced || Boolean(resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }));+if (!enabled) {+ console.log(`skipping browser fill e2e: no agent-browser binary resolves (looked in ${UI_TOOLS_DIR}, OMB_AGENT_BROWSER_PATH and PATH); set OMB_UI_E2E=1 to install the pinned release`);+}+const run = enabled ? it : it.skip;+const posix = process.platform !== "win32";++/** A page taller than the standard viewport, whose Low button only a tall viewport shows; a click names the page's size. */+const PAGE = `<!doctype html><title>tall</title><body style="margin:0;height:4000px">+<button id="low" style="position:absolute;left:600px;top:1950px;width:200px;height:100px" onclick="document.title = 'clicked low at ' + innerWidth + 'x' + innerHeight">Low</button>+</body>`;++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++async function until<T>(read: () => Promise<T> | T, check: (value: T) => boolean, timeoutMs = 20_000): Promise<T> {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const value = await read();+ if (check(value)) return value;+ if (Date.now() > deadline) throw new Error(`still ${JSON.stringify(value)} after ${timeoutMs} ms`);+ await sleep(100);+ }+}++function jpegSize(bytes: Buffer): PageSize | null {+ for (let at = 2; at + 9 < bytes.length;) {+ if (bytes[at] !== 0xff) return null;+ const marker = bytes[at + 1]!;+ if (marker >= 0xc0 && marker <= 0xc2) return { height: bytes.readUInt16BE(at + 5), width: bytes.readUInt16BE(at + 7) };+ at += 2 + bytes.readUInt16BE(at + 2);+ }+ return null;+}++describe("an agent-browser page a person watches in a narrow panel", () => {+ let server: Server;+ let base = "";+ let home = "";+ let sockets = "";+ let spec: BrowserSpawnSpec;+ let runtime: BrowserRuntime;+ let live: BrowserLive;+ let gate: EgressGate | undefined;+ const applied: Array<{ size: PageSize; at: number }> = [];+ const session = `omb-fill-${randomBytes(3).toString("hex")}`;++ beforeAll(async () => {+ if (!enabled) return;+ const browser = await ensureUiBrowser(process.env, () => {}, UI_TOOLS_DIR);+ server = createServer((_req, res) => {+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });+ res.end(PAGE);+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ home = mkdtempSync(join(tmpdir(), "omb-fill-e2e-"));+ // Unix socket paths must stay short (macOS temp paths are long).+ sockets = mkdtempSync(join(posix ? "/tmp" : tmpdir(), "omb-fill-"));+ mkdirSync(join(home, "tmp"), { recursive: true });+ gate = await openGate({ decide: (destination, addresses) => refusalFor(destination, addresses, {+ host: "desktop", ownPort: () => false, botPort: async () => false, localNetwork: true, allowed: () => false,+ }) });+ const integration = agentBrowserIntegration({+ binaryPath: browser.binary, session, encryptionKey: randomBytes(32).toString("hex"), persistent: false, egressPort: gate.port,+ env: { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, ...(browser.chrome ? { AGENT_BROWSER_EXECUTABLE_PATH: browser.chrome } : {}) },+ });+ spec = { ...integration, env: { ...integration.env, HOME: home, USERPROFILE: home, TMPDIR: join(home, "tmp"), AGENT_BROWSER_SOCKET_DIR: sockets } };+ await prepareBrowserSessionState(browser.binary, session, { env: spec.env, persistent: false });+ runtime = new BrowserRuntime({+ applyViewport: (value, size) => {+ applied.push({ size, at: Date.now() });+ return setBrowserViewport(value.command, value.env, size);+ },+ closeBrowser: (name, value) => closeBrowserSession(value.command, browserRuntimeEnv({ ...value.env, AGENT_BROWSER_SESSION: name })),+ });+ live = new BrowserLive({ runtime });+ }, 600_000);++ afterAll(async () => {+ if (!enabled) return;+ live?.closeAll();+ await closeBrowserSession(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session })).catch(() => false);+ await runtime?.closeAll();+ await new Promise((resolve) => server?.close(resolve));+ await gate?.close();+ await removeTempDir(home);+ await removeTempDir(sockets);+ }, 60_000);++ const call = (name: string, args: Record<string, unknown> = {}) =>+ runtime.agentRpc(session, spec, "tools/call", { name: `agent_browser_${name}`, arguments: args }) as Promise<{ content: Array<{ type: string; text?: string; data?: string; mimeType?: string }>; isError?: boolean }>;+ const text = (result: { content: Array<{ text?: string }> }) => result.content.map((part) => part.text ?? "").join("\n");+ /** Read past the runtime, so it never sizes the page first. */+ const page = async <T>(script: string): Promise<T> => {+ const port = await new RelayPorts().port(relayTarget(spec, session));+ if (!port) throw new Error("the browser's daemon has no relay port");+ return (await relay(port, { action: "evaluate", script }, { timeoutMs: 20_000 })).data?.result as T;+ };+ const size = () => page<[number, number]>("[innerWidth, innerHeight]");+ const same = (expected: unknown) => (actual: unknown) => JSON.stringify(actual) === JSON.stringify(expected);++ run("fills the panel at a desktop's width, resizes only between the bot's calls, and gives the standard page back once nobody watches", async () => {+ expect(text(await call("open", { url: `${base}/` }))).toContain("Page observed after navigation.");+ expect(await size()).toEqual([BROWSER_VIEWPORT.width, BROWSER_VIEWPORT.height]);++ const view = new SseRecorder();+ await live.open({ botId: "bot-e2e", session, spec, owner: "local-owner", isCurrent: () => true, res: view.response, size: { width: 400, height: 750 } });+ const viewerId = String(view.events.find((event) => event.type === "ready")?.data.viewerId);+ await until(size, same([1280, 2400]));+ const frame = () => view.events.filter((event) => event.type === "frame").at(-1)?.data.metadata as { deviceWidth: number; deviceHeight: number } | undefined;+ await until(frame, (metadata) => metadata?.deviceWidth === 1280 && metadata.deviceHeight === 2400);++ const snapshot = text(await call("snapshot"));+ const low = /button "Low" \[ref=(e\d+)\]/u.exec(snapshot)?.[1];+ expect(low, snapshot).toBeTruthy();+ expect((await call("click", { selector: `@${low}` })).isError).not.toBe(true);+ expect(await page<string>("document.title")).toBe("clicked low at 1280x2400");++ const shot = await call("screenshot");+ const image = shot.content.find((part) => part.type === "image");+ expect(image?.mimeType).toBe("image/jpeg");+ expect(jpegSize(Buffer.from(image!.data!, "base64"))).toEqual({ width: 1280, height: 2400 });++ // The bot's call holds the browser: the person's resize lands only after it.+ const waited = call("wait_ms", { ms: 1_500 }).then(() => Date.now());+ await sleep(300);+ expect(await live.action({ viewerId, botId: "bot-e2e", owner: "local-owner", body: { type: "resize", width: 900, height: 700 } })).toEqual({ ok: true });+ const ended = await waited;+ await until(size, same([1280, 996]));+ const resized = applied.find((entry) => entry.size.height === 996)!;+ expect(resized.at).toBeGreaterThanOrEqual(ended - 50);++ view.destroy();+ await sleep(200);+ expect(await size()).toEqual([1280, 996]);+ expect((await call("get_url")).isError).not.toBe(true);+ expect(await size()).toEqual([BROWSER_VIEWPORT.width, BROWSER_VIEWPORT.height]);+ expect(applied.at(-1)?.size).toEqual(BROWSER_VIEWPORT);+ }, 300_000);+});diff --git a/server/browser-engine.ts b/server/browser-engine.tsindex 87749b3bee..9eacdc64b0 100644--- a/server/browser-engine.ts+++ b/server/browser-engine.ts@@ -9,7 +9,8 @@ import { writeFileAtomic } from "./atomic.ts";import { DATA_DIR } from "./config.ts";import { browserBundlePaths } from "./browser-bundle-release.ts";import { browserProcessesRunning, browserProcessTree, releaseBrowserProfile, stopBrowserProcesses } from "./browser-processes.ts";-import { BROWSER_VIEWPORT_ARGS, browserRuntimeEnv, ownsBrowserViewport } from "./browser-runtime.ts";+import { BROWSER_VIEWPORT, viewportArgs, type PageSize } from "./browser-page-size.ts";+import { browserRuntimeEnv, ownsBrowserViewport } from "./browser-runtime.ts";import { SIGN_IN_PROMPT } from "./system-prompt.ts";import { gateChromeSettings } from "./browser/egress/gate.ts";import {@@ -627,11 +628,11 @@ export function agentBrowserIntegration(input: {return { command: input.binaryPath, args: ["mcp", "--tools", "core", "--no-webmcp"], env };}-export function setBrowserViewport(binaryPath: string, env: NodeJS.ProcessEnv, timeoutMs = 30_000): Promise<boolean> {+export function setBrowserViewport(binaryPath: string, env: NodeJS.ProcessEnv, size: PageSize = BROWSER_VIEWPORT, timeoutMs = 30_000): Promise<boolean> {if (!ownsBrowserViewport(env)) return Promise.resolve(true);return new Promise((settle) => {let child: ReturnType<typeof spawn>;- try { child = spawn(binaryPath, [...BROWSER_VIEWPORT_ARGS, "--json", "--no-webmcp"], { env: browserRuntimeEnv(env), stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); }+ try { child = spawn(binaryPath, [...viewportArgs(size), "--json", "--no-webmcp"], { env: browserRuntimeEnv(env), stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); }catch { settle(false); return; }let output = "";let settled = false;diff --git a/server/browser-live.test.ts b/server/browser-live.test.tsindex 49074472e5..4397af9962 100644--- a/server/browser-live.test.ts+++ b/server/browser-live.test.ts@@ -79,6 +79,7 @@ beforeEach(() => {settled: vi.fn(async () => {}),launchReady: vi.fn(async () => {}),launched: vi.fn(async () => {}),+ pageSizes: { resize: vi.fn(async () => {}) },} as unknown as BrowserRuntime;live = new BrowserLive({ runtime });SocketFixture.instances = [];@@ -91,9 +92,9 @@ beforeEach(() => {});afterEach(() => { live.closeAll(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.useRealTimers(); });-async function open({ botId = "bot-a", session = "profile-a", owner = "admin-a", current = () => true, resume }: { botId?: string; session?: string; owner?: string; current?: () => boolean; resume?: string } = {}) {+async function open({ botId = "bot-a", session = "profile-a", owner = "admin-a", current = () => true, resume, size }: { botId?: string; session?: string; owner?: string; current?: () => boolean; resume?: string; size?: { width: number; height: number } } = {}) {const res = new ResponseFixture();- await live.open({ botId, session, owner, isCurrent: current, res: res as unknown as ServerResponse, ...(resume ? { resume } : {}),+ await live.open({ botId, session, owner, isCurrent: current, res: res as unknown as ServerResponse, ...(resume ? { resume } : {}), ...(size ? { size } : {}),spec: { command: "/trusted/agent-browser", args: ["mcp", "--tools", "core"], env: { AGENT_BROWSER_SESSION: session, AGENT_BROWSER_SOCKET_DIR: "/isolated/socket" } } });return { res, socket: SocketFixture.instances.at(-1)!, action: (body: unknown) => live.action({ viewerId: res.id, botId, owner, body }) };}@@ -120,10 +121,12 @@ describe("browser viewer protocol boundary", () => {expect(normalizeBrowserLiveMessage({ type: "tabs", tabs: [{ tabId: "t1", title: "Page", url: "https://user:[email protected]/", active: true, targetId: "private" }] })).toEqual({ type: "tabs", tabs: [{ tabId: "t1", title: "Page", url: "https://example.com/", active: true }] });expect(normalizeBrowserLiveMessage({ type: "status", connected: true, engine: "private" })).not.toHaveProperty("engine");});- it("rejects corrupt, oversized and non-image frames", () => {- for (const patch of [{ seq: -1 }, { seq: 1.5 }, { data: "<script>" }, { data: "/9j/" + "A".repeat(3 * 1024 * 1024) }, { metadata: { deviceWidth: 100000, deviceHeight: 100000 } }]) {+ it("rejects corrupt, oversized and non-image frames, and passes a busy page's frame at the largest size it sizes", () => {+ for (const patch of [{ seq: -1 }, { seq: 1.5 }, { data: "<script>" }, { data: "/9j/" + "A".repeat(4 * 1024 * 1024) }, { metadata: { deviceWidth: 100000, deviceHeight: 100000 } }]) {expect(normalizeBrowserLiveMessage({ ...frame, ...patch })).toBeNull();}+ // 2,768,256 characters: a 1280x2560 frame of a page of noise from agent-browser 0.37.0.+ expect(normalizeBrowserLiveMessage({ ...frame, data: "/9j/" + "A".repeat(2_768_252), metadata: { ...frame.metadata, deviceWidth: 1280, deviceHeight: 2560 } })).toMatchObject({ type: "frame" });});it("requires a valid integer port from successful stream status, not a caller URL", () => {expect(browserStreamPort(ready)).toBe(43210);@@ -319,40 +322,44 @@ describe("authenticated browser viewer relay", () => {await expect(reconnecting).rejects.toThrow("Reconnect to retry");expect(nativeClose).toHaveBeenCalledTimes(2);});- it("gives a headless browser it shows the standard page size, but never sizes an attached or headed one", async () => {- const view = (env: Record<string, string>, status = ready) => {- execute.mockReset().mockResolvedValueOnce(output(status)).mockResolvedValue(output({}));- const res = new ResponseFixture();- return live.open({ botId: "a", session: "s", owner: "a", isCurrent: () => true, res: res as unknown as ServerResponse,- spec: { command: "/engine", env: { AGENT_BROWSER_SESSION: "s", ...env } } });- };- await view({ AGENT_BROWSER_HEADLESS: "1" }, { ...ready, connected: false });- expect(execute.mock.calls.map((call) => call[1])).toEqual([- ["stream", "status", "--json", "--no-webmcp"], ["open", "--json", "--no-webmcp"], ["set", "viewport", "1280", "720", "--json", "--no-webmcp"],- ]);- expect(execute.mock.calls[2]?.[2]).toMatchObject({ timeout: 5_000 });- live.closeAll();- await view({ AGENT_BROWSER_HEADLESS: "1" });- expect(execute.mock.calls.map((call) => call[1].slice(0, 2))).toEqual([["stream", "status"], ["set", "viewport"]]);- live.closeAll();- await view({ AGENT_BROWSER_HEADLESS: "1", AGENT_BROWSER_CDP: "http://127.0.0.1:9222" });- expect(execute.mock.calls.map((call) => call[1][0])).toEqual(["stream"]);- live.closeAll();- await view({});- expect(execute.mock.calls.map((call) => call[1][0])).toEqual(["stream"]);- });- it("still opens the view when sizing the page fails or the session is busy again", async () => {- execute.mockReset().mockResolvedValueOnce(output(ready))- .mockRejectedValueOnce(Object.assign(new Error("Command failed"), { killed: true, signal: "SIGKILL", code: null }));- const res = new ResponseFixture();- await live.open({ botId: "a", session: "s", owner: "a", isCurrent: () => true, res: res as unknown as ServerResponse,- spec: { command: "/engine", env: { AGENT_BROWSER_SESSION: "s", AGENT_BROWSER_HEADLESS: "1" } } });+ it("has the page fill the panel of the view that asked last, once the bot's call ends, and the standard page when no view is left", async () => {+ const resize = vi.mocked(runtime.pageSizes.resize);+ const first = await open({ size: { width: 400, height: 750 } });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 400, height: 750 }, true);+ expect(execute.mock.calls.map((call) => call[1][0])).not.toContain("set");+ const second = await open({ owner: "admin-b", size: { width: 900, height: 700 } });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 900, height: 700 }, true);+ expect(await first.action({ type: "resize", width: 380, height: 760 })).toEqual({ ok: true });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 380, height: 760 }, false);+ const calls = resize.mock.calls.length;+ expect(await first.action({ type: "resize", width: 380, height: 40 })).toEqual({ ok: true });+ expect(resize).toHaveBeenCalledTimes(calls);+ await expect(first.action({ type: "resize", width: "wide", height: 760 })).rejects.toThrow("Invalid browser action.");+ first.res.destroy();+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 900, height: 700 }, false);+ second.res.destroy();+ expect(resize).toHaveBeenLastCalledWith("profile-a", null, false);+ });+ it("leaves the page of the person holding the browser as it is when another view opens or resizes", async () => {+ const resize = vi.mocked(runtime.pageSizes.resize);+ const holder = await open({ size: { width: 1400, height: 900 } });+ await holder.action({ type: "take" });+ const other = await open({ owner: "admin-b", size: { width: 400, height: 750 } });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 1400, height: 900 }, true);+ await other.action({ type: "resize", width: 420, height: 800 });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 1400, height: 900 }, true);+ await holder.action({ type: "resize", width: 1500, height: 900 });+ expect(resize).toHaveBeenLastCalledWith("profile-a", { width: 1500, height: 900 }, false);+ });+ it("still opens the view when sizing the page fails", async () => {+ vi.mocked(runtime.pageSizes.resize).mockRejectedValue(new Error("engine without viewport"));+ const { res } = await open({ size: { width: 400, height: 750 } });expect(res.id).toBeTruthy();- expect(res.events("waiting")).toHaveLength(0);+ expect(res.events("ready")).toHaveLength(1);});- it("opens no stream socket when the viewer closes while the page is being sized", async () => {+ it("opens no stream socket when the viewer closes while the browser is still starting", async () => {let finish!: (value: ReturnType<typeof output>) => void;- execute.mockReset().mockResolvedValueOnce(output(ready)).mockImplementationOnce(() => new Promise((resolve) => finish = resolve));+ execute.mockReset().mockResolvedValueOnce(output({ ...ready, connected: false })).mockImplementationOnce(() => new Promise((resolve) => finish = resolve));const res = new ResponseFixture();const opening = live.open({ botId: "a", session: "s", owner: "a", isCurrent: () => true, res: res as unknown as ServerResponse,spec: { command: "/engine", env: { AGENT_BROWSER_SESSION: "s", AGENT_BROWSER_HEADLESS: "1" } } });diff --git a/server/browser-live.ts b/server/browser-live.tsindex 6046742ae3..a4c25f1f4e 100644--- a/server/browser-live.ts+++ b/server/browser-live.ts@@ -2,7 +2,9 @@ import { execFile } from "node:child_process";import { randomUUID } from "node:crypto";import type { ServerResponse } from "node:http";import { promisify } from "node:util";-import { BROWSER_VIEWPORT_ARGS, attachesToChrome, browserRuntimeEnv, ownsBrowserViewport, type BrowserRuntime } from "./browser-runtime.ts";+import type { PageSize } from "./browser-page-size.ts";+import { attachesToChrome, browserRuntimeEnv, type BrowserRuntime } from "./browser-runtime.ts";+import { requestedSize } from "./browser/viewers/viewport.ts";import { closeBrowserSession } from "./browser-engine.ts";import { DialogWatch, localDevToolsUrl } from "./browser-dialogs.ts";import type { Cdp, CdpListeners } from "./browser-sites.ts";@@ -10,11 +12,12 @@ import { relay } from "./browser-relay.ts";import { BROWSER_HELD_ELSEWHERE } from "../shared/browser-held.ts";const execute = promisify(execFile);-const MAX_FRAME = 3 * 1024 * 1024;-const MAX_BUFFER = 4 * 1024 * 1024;+/** A frame of the largest page the view sizes (MAX_PAGE_PIXELS) is up to about 2.8 MB of base64 for a page of noise, and two+ * may be on their way to a view at once. */+const MAX_FRAME = 4 * 1024 * 1024;+const MAX_BUFFER = 8 * 1024 * 1024;const HEARTBEAT_MS = 10_000;const COMMAND_TIMEOUT_MS = 30_000;-const VIEWPORT_TIMEOUT_MS = 5_000;const STATUS_PROBE_MS = 10_000;const BUSY_RETRY_MS = [1_000, 2_000, 5_000];const BUSY_LIMIT_MS = 10 * 60_000;@@ -165,7 +168,9 @@ export function browserRestartRefusal(interrupted: boolean, busyBots: ReadonlyArtype Action = { type: "take" | "release" | "restart" } | { type: "ack"; seq: number }| { type: "command"; args: string[] } | { type: "input"; message: ObjectValue } | { type: "inputs"; messages: ObjectValue[] }- | { type: "dialog"; accept: boolean; promptText?: string };+ | { type: "dialog"; accept: boolean; promptText?: string }+ /** The panel's size in CSS pixels, which the page fills; null for a collapsed panel, which leaves the page as it is. */+ | { type: "resize"; size: PageSize | null };/** A move the next one replaces changes nothing the page keeps. */function withoutReplacedMoves(messages: ObjectValue[]): ObjectValue[] {@@ -182,6 +187,10 @@ export function parseBrowserLiveAction(value: unknown): Action {if (!body) throw invalid();if (body.type === "take" || body.type === "release" || body.type === "restart") return { type: body.type };if (body.type === "ack" && integer(body.seq, 1, Number.MAX_SAFE_INTEGER)) return { type: "ack", seq: body.seq };+ if (body.type === "resize") {+ if (!number(body.width, 0, 100_000) || !number(body.height, 0, 100_000)) throw invalid();+ return { type: "resize", size: requestedSize(body.width, body.height) };+ }if (body.type === "dialog") {if (typeof body.accept !== "boolean" || (body.promptText !== undefined && !text(body.promptText, 4096))) throw invalid();return { type: "dialog", accept: body.accept, ...(body.promptText === undefined ? {} : { promptText: body.promptText }) };@@ -243,6 +252,8 @@ interface OpenOptions {res: ServerResponse;/** The id of the view this panel had before its stream dropped: the one view that may carry on with its hold. */resume?: string | null;+ /** The panel's size in CSS pixels, which the page fills from the start. */+ size?: PageSize | null;}interface Viewer extends OpenOptions {id: string;@@ -269,6 +280,8 @@ interface Viewer extends OpenOptions {unwatch: () => void;/** Set once its stream dropped: runs when its last in-flight action has finished. */idle?: () => void;+ /** The panel size this view asked for last, and when, among all views. */+ requested?: PageSize & { order: number };}/** A person's hold whose view's stream dropped. Agents stay paused until that panel reconnects, the person hands back, or it expires. */interface Parked {@@ -294,6 +307,7 @@ export class BrowserLive {/** Each watched browser's page dialogs, and the views that watch them. */private readonly dialogs = new Map<string, { watch: DialogWatch; views: Set<string> }>();private readonly devTools?: BrowserLiveDevTools;+ private order = 0;constructor({ runtime, devTools }: { runtime: BrowserRuntime; devTools?: BrowserLiveDevTools }) {this.runtime = runtime;this.devTools = devTools;@@ -399,6 +413,7 @@ export class BrowserLive {viewer.abort.abort();viewer.unwatch();this.viewers.delete(viewer.id);+ if (viewer.requested) this.fit(viewer.session);clearTimeout(viewer.heartbeat); clearTimeout(viewer.drainTimer);viewer.socket?.close();viewer.hiddenFrame = undefined; viewer.pendingFrame = undefined; viewer.unacked.clear();@@ -417,6 +432,13 @@ export class BrowserLive {this.control(viewer.session);}+ /** The page fills the panel of the view that asked last, once the bot's running call ends; with no view left, the bot's next call gives it the standard size. */+ private fit(session: string, fresh = false): void {+ const latest = [...this.viewers.values()].filter((viewer) => viewer.session === session && viewer.requested)+ .sort((a, b) => b.requested!.order - a.requested!.order)[0]?.requested;+ void this.runtime.pageSizes.resize(session, latest ? { width: latest.width, height: latest.height } : null, fresh).catch(() => undefined);+ }+/** It holds the browser and is still this person's view of this bot's session (not signed out or switched away). */private holds(viewer: Viewer): boolean {try { return this.runtime.heldBy(viewer.session) === viewer.id && viewer.isCurrent(); } catch { return false; }@@ -549,9 +571,6 @@ export class BrowserLive {const port = browserStreamPort(status);// `open` without a URL is an idempotent launch, never navigation away from the bot's page.if (status.connected !== true) await this.command(viewer, ["open"]);- if (ownsBrowserViewport(viewer.spec.env ?? {})) {- await this.command(viewer, [...BROWSER_VIEWPORT_ARGS], VIEWPORT_TIMEOUT_MS).catch(() => undefined);- }await this.runtime.launched(viewer.session, viewer.spec);return port;}@@ -700,6 +719,8 @@ export class BrowserLive {}const viewer: Viewer = { ...options, id: randomUUID(), closed: false, blocked: false, pendingActions: 0, restarting: false, pressedKeys: new Map(), pressedButtons: new Set(), pointer: { x: 0, y: 0 }, unacked: new Map(), waiting: false, abort: new AbortController(), unwatch: () => {} };if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);+ // A view that opens while another holds the browser leaves the holder's page as it is.+ if (options.size && !this.runtime.heldBy(options.session)) viewer.requested = { ...options.size, order: ++this.order };viewer.unwatch = this.runtime.watch(viewer.session, viewer.spec);this.viewers.set(viewer.id, viewer);options.res.once("close", () => this.close(viewer, true, true));@@ -712,6 +733,7 @@ export class BrowserLive {if (parked && viewer.resume === parked.viewer.id) await this.claim(viewer, parked);if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);viewer.port = port;+ this.fit(viewer.session, true);await this.watchDialogs(viewer);if (!this.current(viewer)) throw new BrowserLiveError("This browser view is no longer available.", 409);const socket = new WebSocket(`ws://127.0.0.1:${port}/?pacing=ack&maxFps=15`);@@ -798,6 +820,14 @@ export class BrowserLive {this.rendered(viewer, action.seq);return { ok: true };}+ if (action.type === "resize") {+ const holder = this.runtime.heldBy(viewer.session);+ if (action.size && (!holder || holder === viewer.id)) {+ viewer.requested = { ...action.size, order: ++this.order };+ this.fit(viewer.session);+ }+ return { ok: true };+ }if (action.type === "release") {this.abandonPressedInput(viewer);this.runtime.release(viewer.session, viewer.id); this.control(viewer.session);diff --git a/server/browser-page-size.test.ts b/server/browser-page-size.test.tsnew file mode 100644index 0000000000..a3edafd4db--- /dev/null+++ b/server/browser-page-size.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from "vitest";++import { BROWSER_VIEWPORT, MAX_PAGE_PIXELS, PageSizes, streamedPage, type PageSize } from "./browser-page-size.ts";++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => { resolve = done; });+ return { promise, resolve };+}++/** A browser lane with one bot call that runs until `finish`, and the sizes its page was given. */+function setup({ watched = true } = {}) {+ const applied: PageSize[] = [];+ const call = deferred();+ let lane: Promise<unknown> = Promise.resolve();+ const state = { watched };+ const sizes = new PageSizes({+ apply: async (_session, size) => { applied.push(size); },+ lane: (_session, work) => { const turn = lane.then(work); lane = turn.then(() => undefined, () => undefined); return turn; },+ watched: () => state.watched,+ });+ const botCall = () => { lane = lane.then(() => call.promise); };+ return { sizes, applied, state, botCall, finish: call.resolve };+}++describe("the page size of a watched agent-browser page", () => {+ it("is the standard page until a panel asks, then that panel's shape at a desktop's width, applied once the bot's call ends", async () => {+ const { sizes, applied, botCall, finish } = setup();+ expect(sizes.wanted("s")).toEqual(BROWSER_VIEWPORT);+ botCall();+ const resizing = sizes.resize("s", { width: 400, height: 750 });+ expect(sizes.wanted("s")).toEqual({ width: 1280, height: 2400 });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(applied).toEqual([]);+ finish();+ await resizing;+ expect(applied).toEqual([{ width: 1280, height: 2400 }]);+ expect(await sizes.beforeCall("s")).toBe(false);+ });++ it("applies only the newest of the sizes a drag asked for while the bot's call ran", async () => {+ const { sizes, applied, botCall, finish } = setup();+ botCall();+ const first = sizes.resize("s", { width: 400, height: 750 });+ const second = sizes.resize("s", { width: 420, height: 700 });+ const last = sizes.resize("s", { width: 1440, height: 819 });+ expect(second).toBe(first);+ finish();+ await Promise.all([first, last]);+ expect(applied).toEqual([{ width: 1440, height: 819 }]);+ });++ it("leaves an unwatched page to the bot's next call, which sizes it first, and sizes a new browser again", async () => {+ const { sizes, applied, state } = setup({ watched: false });+ await sizes.resize("s", { width: 400, height: 750 });+ expect(applied).toEqual([]);+ expect(await sizes.beforeCall("s")).toBe(true);+ expect(applied).toEqual([{ width: 1280, height: 2400 }]);+ await sizes.resize("s", null);+ expect(await sizes.beforeCall("s")).toBe(true);+ expect(applied.at(-1)).toEqual(BROWSER_VIEWPORT);+ sizes.forget("s");+ expect(await sizes.beforeCall("s")).toBe(true);+ expect(applied).toHaveLength(3);+ state.watched = true;+ await sizes.resize("s", null, true);+ expect(applied).toHaveLength(4);+ });++ it("keeps a page whose frames the live stream sends whole within 1280x2560's pixels, in the panel's shape and a desktop wide", () => {+ expect(streamedPage({ width: 365, height: 686 })).toEqual({ width: 1280, height: 2406 });+ expect(streamedPage({ width: 1440, height: 819 })).toEqual({ width: 1440, height: 819 });+ expect(streamedPage({ width: 3840, height: 2160 })).toEqual({ width: 2413, height: 1357 });+ expect(streamedPage({ width: 1600, height: 3200 })).toEqual({ width: 1280, height: 2560 });+ for (const panel of [{ width: 3840, height: 2160 }, { width: 2000, height: 2000 }, { width: 100, height: 2160 }]) {+ const page = streamedPage(panel);+ expect(page.width * page.height).toBeLessThanOrEqual(MAX_PAGE_PIXELS);+ expect(page.width).toBeGreaterThanOrEqual(1280);+ }+ });++ it("asks for a JPEG screenshot of a page larger than the standard one, unless the bot chose a format", () => {+ const { sizes } = setup({ watched: false });+ const screenshot = { name: "agent_browser_screenshot", arguments: { fullPage: true } };+ expect(sizes.callArguments("s", screenshot)).toBe(screenshot);+ void sizes.resize("s", { width: 400, height: 750 });+ expect(sizes.callArguments("s", screenshot)).toEqual({ name: "agent_browser_screenshot", arguments: { fullPage: true, format: "jpeg", quality: 80 } });+ const png = { name: "agent_browser_screenshot", arguments: { format: "png" } };+ expect(sizes.callArguments("s", png)).toBe(png);+ const click = { name: "agent_browser_click", arguments: { selector: "@e1" } };+ expect(sizes.callArguments("s", click)).toBe(click);+ });+});diff --git a/server/browser-page-size.ts b/server/browser-page-size.tsnew file mode 100644index 0000000000..0a3fcd93a0--- /dev/null+++ b/server/browser-page-size.ts@@ -0,0 +1,128 @@+// The size of a bot's page on the agent-browser engine: the standard page while nobody watches, and the shape of the+// watching person's panel, at a desktop's width, while someone does.+import { fillPage } from "./browser/viewers/viewport.ts";++export type PageSize = { width: number; height: number };++/** Page size in CSS pixels. agent-browser sizes the Chrome window, and headless full Chrome (Chrome for Testing) takes its+ * emulated UI out of it (page 1280×577, screencast 1280×720); `set viewport` is agent-browser's only page-size control. */+export const BROWSER_VIEWPORT: PageSize = { width: 1280, height: 720 };++export const viewportArgs = (size: PageSize): string[] => ["set", "viewport", String(size.width), String(size.height)];++/** A screenshot of a page larger than the standard one comes as JPEG unless the bot asked for a format: a tall PNG of a+ * busy page can pass the 5 MB that Claude's API (2026) takes for one image. */+const ENLARGED_PICTURE = { format: "jpeg", quality: 80 } as const;++/** agent-browser's live stream sends frames at the page's own size (0.37.0 ignores a size cap), and a frame of a page of+ * noise this large is about 2.8 MB of base64: a larger panel gets this many pixels in its shape, drawn larger. */+export const MAX_PAGE_PIXELS = 1280 * 2560;++/** The page that fills `panel` within MAX_PAGE_PIXELS, still at least a desktop wide. */+export function streamedPage(panel: PageSize): PageSize {+ const page = fillPage(panel);+ const pixels = page.width * page.height;+ if (pixels <= MAX_PAGE_PIXELS) return page;+ const scale = Math.sqrt(MAX_PAGE_PIXELS / pixels);+ return { width: Math.floor(page.width * scale), height: Math.floor(page.height * scale) };+}++const key = (size: PageSize) => `${size.width}x${size.height}`;++export interface PageSizeHost {+ /** Sizes the session's running page; resolves once the engine answered or gave up. */+ apply(session: string, size: PageSize): Promise<unknown>;+ /** Runs `work` in the session's browser lane, after the bot's call running now; null when that call outlasted the wait. */+ lane(session: string, work: () => Promise<void>): Promise<void | null>;+ /** Someone watches the session's browser, and it is not closing. */+ watched(session: string): boolean;+}++/**+ * Each session's page size: the one its watchers' panels want, and the one its browser was last given. A change waits for+ * the bot's call running in the browser's lane, so no action sees the page change under it; while nobody watches, the+ * bot's next call applies it.+ */+export class PageSizes {+ readonly #host: PageSizeHost;+ readonly #sessions = new Map<string, { wanted: PageSize; applied: string | null; applying: Promise<void> | null }>();++ constructor(host: PageSizeHost) {+ this.#host = host;+ }++ #entry(session: string) {+ let entry = this.#sessions.get(session);+ if (!entry) this.#sessions.set(session, entry = { wanted: BROWSER_VIEWPORT, applied: null, applying: null });+ return entry;+ }++ wanted(session: string): PageSize {+ return this.#sessions.get(session)?.wanted ?? BROWSER_VIEWPORT;+ }++ /** The browser may be a new one, sized as Chrome chose: the next call sizes it again. */+ forget(session: string): void {+ const entry = this.#sessions.get(session);+ if (!entry) return;+ if (entry.wanted === BROWSER_VIEWPORT && !entry.applying) this.#sessions.delete(session);+ else entry.applied = null;+ }++ /**+ * The page a watching panel of `panel` CSS pixels needs, or the standard one (null). `fresh` sizes it even when this+ * server sized it so before, for a browser a view just started.+ */+ resize(session: string, panel: PageSize | null, fresh = false): Promise<void> {+ const entry = this.#entry(session);+ entry.wanted = panel ? streamedPage(panel) : BROWSER_VIEWPORT;+ if (fresh) entry.applied = null;+ if (!entry.applying && this.#behind(session, entry)) entry.applying = this.#follow(session, entry);+ return entry.applying ?? Promise.resolve();+ }++ #behind(session: string, entry: { wanted: PageSize; applied: string | null }): boolean {+ return this.#host.watched(session) && entry.applied !== key(entry.wanted);+ }++ /** Applies the newest wanted size until the page has it; a size wanted meanwhile is picked up before this ends. */+ async #follow(session: string, entry: { wanted: PageSize; applied: string | null; applying: Promise<void> | null }): Promise<void> {+ try {+ while (this.#behind(session, entry)) {+ await this.#host.lane(session, async () => {+ const wanted = entry.wanted;+ if (!this.#behind(session, entry)) return;+ await this.#host.apply(session, wanted).catch(() => undefined);+ entry.applied = key(wanted);+ });+ }+ } finally {+ entry.applying = null;+ }+ }++ /** Before a bot's call, in its lane: true when the page had to be sized first. */+ async beforeCall(session: string): Promise<boolean> {+ const entry = this.#entry(session);+ const wanted = entry.wanted;+ if (entry.applied === key(wanted)) return false;+ await this.#host.apply(session, wanted).catch(() => undefined);+ entry.applied = key(wanted);+ return true;+ }++ /** A browser the engine relaunched under a call: sized again at once. */+ async again(session: string): Promise<void> {+ this.forget(session);+ await this.beforeCall(session);+ }++ /** A call's arguments as the engine gets them: a screenshot of an enlarged page is a JPEG unless the bot chose. */+ callArguments(session: string, params: unknown): unknown {+ const call = params as { name?: unknown; arguments?: Record<string, unknown> } | null;+ const size = this.wanted(session);+ if (call?.name !== "agent_browser_screenshot" || size.width * size.height <= BROWSER_VIEWPORT.width * BROWSER_VIEWPORT.height) return params;+ if (call.arguments?.format !== undefined) return params;+ return { ...call, arguments: { ...call.arguments, ...ENLARGED_PICTURE } };+ }+}diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.tsindex 4b652bc504..54f1406f8c 100644--- a/server/browser-runtime.test.ts+++ b/server/browser-runtime.test.ts@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import { addHeldSecretScrubber, HELD_SECRET_MASK } from "../shared/redact.ts";+import { BROWSER_VIEWPORT } from "./browser-page-size.ts";import { BROWSER_CALL_DEFAULTS, BROWSER_HOVER_TOOL, BROWSER_RESTART_TOOL, BROWSER_UPLOAD_TOOL, BrowserRuntime, TransportError, browserRuntimeEnv, formatBrowserTiming, type BrowserSpawnSpec, type BrowserTiming } from "./browser-runtime.ts";import { HARNESS_CALL_BUDGET_MS, HARNESS_PROXY_TIMEOUT_MS } from "./harness-budget.ts";import { RelayPorts } from "./browser-relay.ts";@@ -754,7 +755,7 @@ describe("server-owned browser MCP runtime", () => {order.push(first.content[0]!.text);await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "second" } });expect(applyViewport).toHaveBeenCalledOnce();- expect(applyViewport).toHaveBeenCalledWith(spec());+ expect(applyViewport).toHaveBeenCalledWith(spec(), BROWSER_VIEWPORT);expect(order[0]).toBe("viewport");expect(order[1]).toContain("first");await value.close("s");@@ -762,6 +763,31 @@ describe("server-owned browser MCP runtime", () => {expect(applyViewport).toHaveBeenCalledTimes(2);});+ it("sizes the page for the panel a person watches once the bot's call ends, and back to the standard page at the bot's next call after they leave", async () => {+ const sizes: Array<{ width: number; height: number }> = [];+ const value = runtime({ applyViewport: async (_spec, size) => { sizes.push(size); } });+ await value.agentRpc("s", spec(), "tools/call", { name: "echo" });+ expect(sizes).toEqual([BROWSER_VIEWPORT]);+ const unwatch = value.watch("s", spec());+ const typing = deferred<{ ok: boolean; text: string }>();+ const holding = value.withSecretInput("s", spec(), () => typing.promise);+ const resizing = value.pageSizes.resize("s", { width: 400, height: 750 });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(sizes).toEqual([BROWSER_VIEWPORT]);+ typing.resolve({ ok: true, text: "typed" });+ await holding;+ await resizing;+ expect(sizes).toEqual([BROWSER_VIEWPORT, { width: 1280, height: 2400 }]);+ const shot = await value.agentRpc("s", spec(), "tools/call", { name: "agent_browser_screenshot", arguments: {} }) as { content: Array<{ text: string }> };+ expect(sizes).toHaveLength(2);+ expect(JSON.parse(shot.content[0]!.text)).toMatchObject({ name: "agent_browser_screenshot", arguments: { format: "jpeg", quality: 80 } });+ unwatch();+ await value.pageSizes.resize("s", null);+ expect(sizes).toHaveLength(2);+ await value.agentRpc("s", spec(), "tools/call", { name: "echo" });+ expect(sizes).toEqual([BROWSER_VIEWPORT, { width: 1280, height: 2400 }, BROWSER_VIEWPORT]);+ });+it("prepares the browser before the engine may start it, and gives it its identity before the bot's command runs", async () => {const order: string[] = [];const launch = {diff --git a/server/browser-runtime.ts b/server/browser-runtime.tsindex f6ed377774..09231f4d49 100644--- a/server/browser-runtime.ts+++ b/server/browser-runtime.ts@@ -2,6 +2,7 @@ import { killCliTree, spawnCli } from "./procs.ts";import { scrubHeldSecrets } from "../shared/redact.ts";import { DEFAULT_BROWSER_RESULT_BUDGET, describePageChange, OBSERVE_PAGE_SCRIPT, parsePageState, READ_OPEN_PAGE_ONLY, readsAroundBrowser, scrubBrowserResult, shapeBrowserToolResult, slimBrowserToolList, stripHarnessOwnedArguments, type PageState } from "./browser-tool-shape.ts";import { BrowserLanes } from "./browser-lane.ts";+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";@@ -68,11 +69,6 @@ export function browserRuntimeEnv(overrides: Record<string, string | undefined>)return { ...env, ...overrides };}-/** Page size in CSS pixels. agent-browser sizes the Chrome window, and headless full Chrome (Chrome for Testing) takes its- * emulated UI out of it (page 1280×577, screencast 1280×720); `set viewport` is agent-browser's only page-size control. */-export const BROWSER_VIEWPORT = { width: 1280, height: 720 } as const;-export const BROWSER_VIEWPORT_ARGS = ["set", "viewport", String(BROWSER_VIEWPORT.width), String(BROWSER_VIEWPORT.height)] as const;-export function attachesToChrome(env: NodeJS.ProcessEnv): boolean {return Boolean(env.AGENT_BROWSER_CDP || env.AGENT_BROWSER_AUTO_CONNECT);}@@ -287,7 +283,7 @@ class BrowserClient {}}-export type ApplyViewport = (spec: BrowserSpawnSpec) => Promise<unknown>;+export type ApplyViewport = (spec: BrowserSpawnSpec, size: PageSize) => Promise<unknown>;type LaunchSpec = { command: string; env?: Record<string, string | undefined> };/** The browser the engine starts, prepared by OMB. */@@ -323,7 +319,7 @@ interface Gate {reopened: "idle" | "restart" | null;}-type ClientEntry = { key: string; client: BrowserClient; viewport?: Promise<unknown> };+type ClientEntry = { key: string; client: BrowserClient };/** Closes one session's native browser daemon; true only when it is gone. */export type CloseBrowser = (session: string, spec: BrowserSpawnSpec) => Promise<boolean>;@@ -344,6 +340,12 @@ export class BrowserRuntime {private relayCommand?: RelayCommand;private steps?: Pick<BrowserSteps, "before" | "after" | "signIn" | "note" | "forget" | "recentFrame" | "personTook">;private lanes = new BrowserLanes();+ /** The page size people's views want; the agent-browser live view sets it, and every bot call applies it first. */+ 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); },+ });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. */private scrub: (text: string) => string;@@ -514,9 +516,7 @@ export class BrowserRuntime {await entry.client.ready;beforeDispatch?.();if (method === "tools/call" && this.gate(session).owner !== null) throw new Error(BROWSER_CONTROL_REFUSAL);- if (method === "tools/call" && this.applyViewport) {- entry.viewport ??= this.applyViewport(spec).catch(() => undefined);- await entry.viewport;+ if (method === "tools/call" && await this.pageSizes.beforeCall(session)) {beforeDispatch?.();if (this.gate(session).owner !== null) throw new Error(BROWSER_CONTROL_REFUSAL);}@@ -531,13 +531,13 @@ export class BrowserRuntime {.then((result) => firstText(result).trim(), (error: unknown) => { if (error instanceof TransportError) throw error; return ""; });if (toolName === "agent_browser_eval" && await this.holds.refuses(session, pageUrl)) return { isError: true, content: [{ type: "text", text: SECRET_ON_PAGE }] };// Launch and session parameters OMB owns never reach the engine from a call.- const request = method === "tools/call" ? stripHarnessOwnedArguments(params) : params;+ const request = method === "tools/call" ? this.pageSizes.callArguments(session, stripHarnessOwnedArguments(params)) : params;const args = (request as { arguments?: unknown } | null)?.arguments;const call: StepCall | null = this.steps && method === "tools/call" && toolName !== undefined ? {session, spec, tool: toolName, args: args && typeof args === "object" ? args as Record<string, unknown> : {}, ctx,stopped: () => gate.owner !== null || gate.uncertain || gate.closing,alive: () => { try { beforeDispatch?.(); return true; } catch { return false; } },- resize: async () => { if (this.applyViewport) await (entry.viewport = this.applyViewport(spec).catch(() => undefined)); },+ resize: () => this.pageSizes.again(session),} : null;const stepsStarted = performance.now();const stepState = call ? await this.steps!.before(call) : null;@@ -676,6 +676,7 @@ export class BrowserRuntime {}, (params) => this.latchLostCall(session, toolNameOf(params) ?? "browser"));const entry: ClientEntry = { key, client };this.clients.set(session, entry);+ this.pageSizes.forget(session);return entry;}diff --git a/server/browser/cdp/actions.ts b/server/browser/cdp/actions.tsindex 6b4c23f169..5deb7fbfd8 100644--- a/server/browser/cdp/actions.ts+++ b/server/browser/cdp/actions.ts@@ -18,7 +18,7 @@ const POLL_MS = 100;export const MAX_TYPED_KEYS = 500;const DRAG_LEAD_PX = 12;-/** A ref from a snapshot, a selector, or a point in the 1280x720 viewport (CSS pixels). */+/** A ref from a snapshot, a selector, or a point in the viewport as it is laid out now (CSS pixels). */export type Target = { ref: string } | { selector: string } | Point;export interface ActionContext {@@ -183,9 +183,19 @@ async function untilDialog(context: ActionContext, action: Promise<void>): Promi/** Shown to people watching before the agent's pointer acts there; the action waits for it. */export type PointerReporter = (point: Point, phase: "move" | "click") => Promise<void>;+/** A point the bot passed, refused outside the viewport as it is now: a person's panel can resize it between two calls. */+async function inViewport(context: ActionContext, point: Point): Promise<Point> {+ const size = await valueInWorld<[number, number]>(context.frames, context.frames.mainFrameId, "[innerWidth, innerHeight]").catch(() => null);+ if (size && (point.x >= size[0] || point.y >= size[1])) {+ throw new DriverError("refused", `${Math.round(point.x)},${Math.round(point.y)} is outside the page's viewport, which is ${size[0]}x${size[1]} CSS pixels now. Take a new screenshot and aim inside it.`);+ }+ return point;+}+/** Where to act: found, shown to people watching, then found again, since the page may have moved meanwhile. */async function pointAfterShowing(context: ActionContext, at: Point | (NodeHandle & { ref?: string }), deadline: number, phase: "move" | "click", pointer: PointerReporter | undefined, options: { wantEnabled?: boolean } = {}): Promise<Point> {if ("x" in at) {+ await inViewport(context, at);await pointer?.(at, phase);return at;}@@ -394,7 +404,7 @@ export async function drag(context: ActionContext, from: Target, to: Target, { tconst deadline = Date.now() + timeoutMs;const source = isPoint(from) ? null : await element(context, from);const start = await pointAfterShowing(context, source ?? (from as Point), deadline, "move", pointer);- const end = isPoint(to) ? to : await actionablePoint(context, await element(context, to), deadline, { hitTest: false });+ const end = isPoint(to) ? await inViewport(context, to) : await actionablePoint(context, await element(context, to), deadline, { hitTest: false });const sourceFrame = source?.frameId ?? context.frames.mainFrameId;const session = context.session;const intercepted: { data: Record<string, unknown> | null } = { data: null };@@ -440,7 +450,7 @@ export async function scroll(context: ActionContext, target: Target | null, deltawait context.bringToFront();const point = target === null? await valueInWorld<Point>(context.frames, context.frames.mainFrameId, VIEWPORT_CENTER)- : isPoint(target) ? target : await actionablePoint(context, await element(context, target), Date.now() + timeoutMs, { hitTest: false });+ : isPoint(target) ? await inViewport(context, target) : await actionablePoint(context, await element(context, target), Date.now() + timeoutMs, { hitTest: false });await context.mouse.move(point.x, point.y);await context.mouse.wheel(deltaX, deltaY);await valueInWorld(context.frames, context.frames.mainFrameId, NEXT_FRAME, { awaitPromise: true }).catch(() => {});diff --git a/server/browser/cdp/browser.ts b/server/browser/cdp/browser.tsindex 837f141833..65472857d3 100644--- a/server/browser/cdp/browser.ts+++ b/server/browser/cdp/browser.ts@@ -8,7 +8,7 @@ import { RefCounter } from "./refs.ts";import { applyPermissions, releaseSession, setUpWorkerSession, type TargetSetup } from "./targets.ts";import type { CdpTransport } from "./transport.ts";-/** Every headless page is this size, so pictures, boxes and clicks agree. */+/** 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;diff --git a/server/browser/cdp/driver-parts.test.ts b/server/browser/cdp/driver-parts.test.tsindex 171b5fe722..d9ec64154f 100644--- a/server/browser/cdp/driver-parts.test.ts+++ b/server/browser/cdp/driver-parts.test.ts@@ -7,6 +7,7 @@ import { humanChecksIn, reportableUrl } from "./health.ts";import { headedUserAgent, identityDifferences, identityFromProbe } from "./identity.ts";import { editingCommands, Keyboard, keyDescription, parseChord } from "./keyboard.ts";import { parseRef, RefCounter, RefTable } from "./refs.ts";+import { pictureScale } from "./screencast.ts";import { parseSelector } from "./selectors.ts";import { isSensitiveInput } from "./sensitive.ts";@@ -180,6 +181,17 @@ describe("small rules", () => {]).map((check) => check.kind)).toEqual(["Cloudflare Turnstile", "reCAPTCHA", "hCaptcha"]);});+ it("draws a picture one pixel per CSS pixel up to 1280 wide, 1568 tall and 1.2 megapixels, and in hundredths below that", () => {+ expect(pictureScale({ width: 1280, height: 800 })).toBe(1);+ expect(pictureScale({ width: 390, height: 844 })).toBe(1);+ expect(pictureScale({ width: 1280, height: 937 })).toBe(1);+ expect(pictureScale({ width: 1280, height: 2400 })).toBe(0.62);+ expect(pictureScale({ width: 1280, height: 2560 })).toBe(0.6);+ expect(pictureScale({ width: 2400, height: 1300 })).toBe(0.53);+ expect(pictureScale({ width: 1280, height: 16_384 })).toBe(0.09);+ expect(pictureScale({ width: 0, height: 0 })).toBe(1);+ });+it("treats passwords, codes and card numbers as values a snapshot never shows", () => {expect(isSensitiveInput("password", [])).toBe(true);expect(isSensitiveInput("text", ["one-time-code"])).toBe(true);diff --git a/server/browser/cdp/page.ts b/server/browser/cdp/page.tsindex a6c4607924..76c2cd4f78 100644--- a/server/browser/cdp/page.ts+++ b/server/browser/cdp/page.ts@@ -335,7 +335,7 @@ export class CdpPage implements ActionContext, WaitContext {height: Math.max(1, Math.max(...ys) - Math.min(...ys)),};}- return captureScreenshot(this.session, await this.devicePixelRatio(), { ...options, ...(clip ? { clip } : {}) });+ return captureScreenshot(this.session, (await this.devicePixelRatio()) * (this.#emulated?.zoom ?? 1), { ...options, ...(clip ? { clip } : {}) });}async evaluate(expression: string, options: EvaluateOptions = {}): Promise<unknown> {diff --git a/server/browser/cdp/s4-pages.e2e.test.ts b/server/browser/cdp/s4-pages.e2e.test.tsindex 89af4485e7..aa19317124 100644--- a/server/browser/cdp/s4-pages.e2e.test.ts+++ b/server/browser/cdp/s4-pages.e2e.test.ts@@ -9,7 +9,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";import { hostTimeout } from "../../testing/host-timeout.ts";import type { CdpPage } from "./page.ts";-import { Screencast, type ScreencastFrame } from "./screencast.ts";+import { PICTURE_LIMITS, pictureScale, Screencast, type ScreencastFrame } from "./screencast.ts";import { FixtureServer } from "./testing/fixtures.ts";import { CHROME, forbiddenCommands, inPageWorld, startChrome, type RunningChrome } from "./testing/real-chrome.ts";@@ -266,17 +266,26 @@ suite("S4 pages, tabs and page state on real Chrome", () => {expect(page.takeHealth().failedRequests).toEqual([]);});- it("takes pictures at most 1280 pixels wide: the viewport, an element and the whole page", async () => {+ it("takes pictures one pixel per CSS pixel within the limits a model takes as they are: the viewport, an element and the whole page", async () => {await open(`<div id="box" style="margin:40px;width:200px;height:100px;background:red"></div><div style="height:3000px"></div>`);expect(await read("[innerWidth, innerHeight]")).toEqual([1280, 720]);- expect(pngSize((await page.screenshot()).data)).toEqual({ width: 1280, height: 720 });+ const viewport = await page.screenshot();+ // The viewport's width: 1280 where scrollbars overlay the page (macOS), less a 15-16 px classic scrollbar elsewhere.+ expect(viewport).toMatchObject({ scale: 1, region: { height: 720 }, width: viewport.region.width, height: 720 });+ expect(viewport.region.width).toBeGreaterThanOrEqual(1_260);+ expect(viewport.region.width).toBeLessThanOrEqual(1_280);+ expect(pngSize(viewport.data)).toEqual({ width: viewport.region.width, height: 720 });const element = await page.screenshot({ target: { selector: "#box" } });expect(pngSize(element.data)).toEqual({ width: 200, height: 100 });const full = await page.screenshot({ fullPage: true });// The document's width: 1280 where scrollbars overlay the page (macOS), less a 15-16 px classic scrollbar elsewhere.- expect(pngSize(full.data).width).toBeGreaterThanOrEqual(1_260);- expect(pngSize(full.data).width).toBeLessThanOrEqual(1_280);- expect(pngSize(full.data).height).toBeGreaterThan(3000);+ expect(full.region.width).toBeGreaterThanOrEqual(1_260);+ expect(full.region.width).toBeLessThanOrEqual(1_280);+ expect(full.region.height).toBeGreaterThan(3000);+ expect(full.scale).toBe(pictureScale(full.region));+ expect(pngSize(full.data)).toEqual({ width: full.width, height: full.height });+ expect(full.height).toBeLessThanOrEqual(PICTURE_LIMITS.maxHeight);+ expect(full.width * full.height).toBeLessThanOrEqual(PICTURE_LIMITS.maxPixels);const retina = await startChrome("retina", { launch: { screen: { width: 1512, height: 982, deviceScaleFactor: 2 } } });extra.push(retina);const sharp = await retina.browser.waitForPage();@@ -285,7 +294,12 @@ suite("S4 pages, tabs and page state on real Chrome", () => {expect(await sharp.evaluate("[innerWidth, innerHeight, screen.width, screen.height]")).toEqual([1280, 720, 1512, 982]);const shot = await sharp.screenshot();expect(pngSize(shot.data)).toEqual({ width: 1280, height: 720 });- expect(pngSize((await sharp.screenshot({ maxWidth: 2560 })).data)).toEqual({ width: 2560, height: 1440 });+ await sharp.emulateSize({ width: 1280, height: 2400 });+ const tall = await sharp.screenshot();+ expect(tall).toMatchObject({ scale: 0.62, region: { width: 1280, height: 2400 }, width: 794, height: 1488 });+ expect(pngSize(tall.data)).toEqual({ width: 794, height: 1488 });+ await sharp.emulateSize({ width: 390, height: 844 });+ expect(pngSize((await sharp.screenshot()).data)).toEqual({ width: 390, height: 844 });});it("fits each headless window so its page is exactly the viewport asked for", async () => {diff --git a/server/browser/cdp/screencast.ts b/server/browser/cdp/screencast.tsindex 0c638b09df..603c006af8 100644--- a/server/browser/cdp/screencast.ts+++ b/server/browser/cdp/screencast.ts@@ -6,7 +6,20 @@ import type { CdpSession, Params } from "./connection.ts";/** Chromium keeps at most three frames unacknowledged, so acking 100 ms after arrival caps a stream near 30 fps. */export const ACK_PACE_MS = 100;-export const MAX_SCREENSHOT_WIDTH = 1280;+/**+ * The largest picture a bot is sent. Claude's API (2026) shrinks an image past 1568 pixels on its long edge or about 1.2+ * megapixels before the model sees it, without saying so, which would move every point the model reads off it; past+ * 8000 pixels it refuses the image.+ */+export const PICTURE_LIMITS = { maxWidth: 1280, maxHeight: 1568, maxPixels: 1_200_000 } as const;++/** A picture's pixels per CSS pixel of a region of `size`: one, or in hundredths below one as PICTURE_LIMITS needs. */+export function pictureScale(size: { width: number; height: number }): number {+ const width = Math.max(1, size.width);+ const height = Math.max(1, size.height);+ const fit = Math.min(1, PICTURE_LIMITS.maxWidth / width, PICTURE_LIMITS.maxHeight / height, Math.sqrt(PICTURE_LIMITS.maxPixels / (width * height)));+ return fit >= 1 ? 1 : Math.max(0.01, Math.floor(fit * 100) / 100);+}export interface ScreencastFrame {data: Buffer;@@ -86,7 +99,6 @@ export class Screencast {export interface ScreenshotOptions {format?: "png" | "jpeg";quality?: number;- maxWidth?: number;fullPage?: boolean;/** CSS pixels in page coordinates. */clip?: { x: number; y: number; width: number; height: number };@@ -97,6 +109,10 @@ export interface Screenshot {format: "png" | "jpeg";width: number;height: number;+ /** The picture's pixels per CSS pixel: 1, or less for a region larger than PICTURE_LIMITS. */+ scale: number;+ /** What it shows, in CSS pixels. */+ region: { width: number; height: number };}interface LayoutMetrics {@@ -104,28 +120,32 @@ interface LayoutMetrics {cssContentSize: { width: number; height: number };}-/** At most `maxWidth` device pixels wide; a capture at a smaller scale repaints, so callers pause a live screencast first. */+/**+ * One picture pixel per CSS pixel within PICTURE_LIMITS, of the region it names: the viewport without a classic+ * scrollbar, the whole page, or a clip. The capture is always clipped and so repaints: callers pause a live screencast first.+ */export async function captureScreenshot(session: CdpSession, devicePixelRatio: number, options: ScreenshotOptions = {}): Promise<Screenshot> {const format = options.format ?? "png";- const maxWidth = options.maxWidth ?? MAX_SCREENSHOT_WIDTH;const metrics = await session.send<LayoutMetrics>("Page.getLayoutMetrics");const viewport = metrics.cssVisualViewport;const region = options.clip?? (options.fullPage? { x: 0, y: 0, width: Math.ceil(metrics.cssContentSize.width), height: Math.min(Math.ceil(metrics.cssContentSize.height), 16_384) }: { x: viewport.pageX, y: viewport.pageY, width: viewport.clientWidth, height: viewport.clientHeight });- const scale = Math.min(1, maxWidth / Math.max(1, region.width * devicePixelRatio));- const needsClip = options.clip !== undefined || options.fullPage === true || scale < 1;+ const scale = pictureScale(region);const { data } = await session.send<{ data: string }>("Page.captureScreenshot", {format,...(format === "jpeg" ? { quality: Math.min(100, Math.max(1, Math.round(options.quality ?? 80))) } : {}),- ...(needsClip ? { clip: { ...region, scale } } : {}),+ // Chrome draws a clip at its scale times the device pixel ratio (measured on 156).+ clip: { ...region, scale: scale / devicePixelRatio },...(options.fullPage ? { captureBeyondViewport: true } : {}),});return {data: Buffer.from(data, "base64"),format,- width: Math.round(region.width * devicePixelRatio * scale),- height: Math.round(region.height * devicePixelRatio * scale),+ width: Math.round(region.width * scale),+ height: Math.round(region.height * scale),+ scale,+ region: { width: region.width, height: region.height },};}diff --git a/server/browser/dispatch.ts b/server/browser/dispatch.tsindex 11b118f765..467beac655 100644--- a/server/browser/dispatch.ts+++ b/server/browser/dispatch.ts@@ -11,6 +11,7 @@ import { DriverError, isUnanswered } from "./cdp/errors.ts";import { callOnNode, valueInWorld } from "./cdp/evaluate.ts";import type { PointerReporter } from "./cdp/actions.ts";import { navigable } from "./cdp/page.ts";+import type { Screenshot } from "./cdp/screencast.ts";import { resolveElement } from "./cdp/selectors.ts";import { MAX_VISIBLE_TEXT_LENGTH } from "./cdp/snapshot.ts";import { BROWSER_CONTROL_REFUSAL, type ProfileControl } from "./control.ts";@@ -180,6 +181,16 @@ async function act(context: ToolContext, tab: Tab | null, run: () => Promise<Too});}+/** How a picture's pixels map to the CSS pixels the point tools take, so a point read off it lands where it was seen. */+export function pictureNote(shot: Pick<Screenshot, "width" | "height" | "scale" | "region">, of: "viewport" | "page" | "element" = "viewport"): string {+ const pixels = `${shot.width}x${shot.height} pixels`;+ const region = `${Math.round(shot.region.width)}x${Math.round(shot.region.height)} CSS-pixel`;+ if (of !== "viewport") return `${pixels}: the ${region} ${of === "page" ? "page" : "element"}${shot.scale === 1 ? "" : ` drawn at ${shot.scale}`}.`;+ return shot.scale === 1+ ? `${pixels}, one per CSS pixel of the viewport, so x and y read off it are the point the click, hover and drag tools take.`+ : `${pixels}: the ${region} viewport drawn at ${shot.scale}, so divide x and y read off it by ${shot.scale} for the point the click, hover and drag tools take.`;+}+async function snapshotResult(context: ToolContext, tab: Tab, { includeImage = false, save = false }: { includeImage?: boolean; save?: boolean } = {}): Promise<ToolResult> {const snapshot = await tab.page.snapshot();await context.browser.refreshTargets().catch(() => undefined);@@ -187,10 +198,11 @@ async function snapshotResult(context: ToolContext, tab: Tab, { includeImage = fif (!includeImage && !save) return textResult(text);const shot = await context.paused(tab, () => tab.page.screenshot());const saved = save ? context.saveScreenshot(shot.data, tab.page.url()) : null;+ const shown = includeImage || !save;return {content: [- { type: "text", text: saved ? `${text}\nScreenshot saved at ${saved}` : text },- ...(includeImage || !save ? [{ type: "image" as const, data: shot.data.toString("base64"), mimeType: "image/png" }] : []),+ { type: "text", text: `${text}${saved ? `\nScreenshot saved at ${saved}` : ""}${shown ? `\nThe screenshot is ${pictureNote(shot)}` : ""}` },+ ...(shown ? [{ type: "image" as const, data: shot.data.toString("base64"), mimeType: "image/png" }] : []),],};}@@ -278,7 +290,8 @@ export async function executeTool(context: ToolContext, call: ToolCall): Promisereturn act(context, tab, async () => {await tab.page.bringToFront();const shot = await context.paused(tab, () => tab.page.screenshot({ fullPage: call.input.fullPage === true, ...(target && !("x" in target) ? { target } : {}) }));- return { content: [{ type: "text", text: `Screenshot of ${pageLabel(describe(tab))}, ${shot.width}x${shot.height} pixels.` }, { type: "image", data: shot.data.toString("base64"), mimeType: "image/png" }] };+ const note = pictureNote(shot, target ? "element" : call.input.fullPage === true ? "page" : "viewport");+ return { content: [{ type: "text", text: `Screenshot of ${pageLabel(describe(tab))}, ${note}` }, { type: "image", data: shot.data.toString("base64"), mimeType: "image/png" }] };});}case "agent_browser_click": {diff --git a/server/browser/service.test.ts b/server/browser/service.test.tsindex a9973ab006..751a799d79 100644--- a/server/browser/service.test.ts+++ b/server/browser/service.test.ts@@ -103,6 +103,27 @@ describe("the bots' browser tools", () => {expect(text(unknown)).toContain("There is no browser tool named agent_browser_teleport.");});+ it("says how a screenshot's pixels map to the CSS pixels a point takes, and refuses a point outside the viewport as it is now", async () => {+ const { service, call, text, target, backend } = setup();+ await call("agent_browser_open", { url: "https://example.com/swap" });+ expect(text(await call("agent_browser_screenshot"))).toContain("Screenshot of t1: \"Swap\" at https://example.com/swap, 1280x800 pixels, one per CSS pixel of the viewport");+ const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 800, maxHeight: 1500, size: { width: 400, height: 750 } }, (output) => {+ if (output.type === "frame") output.ack();+ });+ await sleep(20);+ expect(backend.chrome.viewport).toEqual({ width: 1280, height: 2400 });+ expect(text(await call("agent_browser_screenshot"))).toContain("794x1488 pixels: the 1280x2400 CSS-pixel viewport drawn at 0.62, so divide x and y read off it by 0.62");+ expect(text(await call("agent_browser_click", { x: 200, y: 2000 }))).toContain("Clicked 200,2000.");+ await viewer.close();+ await sleep(20);+ const refused = await call("agent_browser_click", { x: 200, y: 2000 });+ expect(refused.isError).toBe(true);+ expect(text(refused)).toContain("200,2000 is outside the page's viewport, which is 1280x800 CSS pixels now. Take a new screenshot and aim inside it.");+ expect((await call("agent_browser_hover", { x: 1280, y: 10 })).isError).toBe(true);+ expect((await call("agent_browser_drag", { from: { x: 10, y: 10 }, to: { x: 10, y: 900 } })).isError).toBe(true);+ expect((await call("agent_browser_click", { x: 1279, y: 799 })).isError).toBeUndefined();+ });+it("names a tab the page opened, which comes to the front", async () => {const { call, text, backend } = setup();await call("agent_browser_open", { url: "https://example.com/form" });diff --git a/server/browser/tools.ts b/server/browser/tools.tsindex 37e47dbb53..fe27f239c2 100644--- a/server/browser/tools.ts+++ b/server/browser/tools.ts@@ -12,8 +12,8 @@ const tab = z.string().regex(/^(?:new|t[1-9]\d{0,8})$/u).describe("The tab, as tconst actTab = z.string().regex(/^t[1-9]\d{0,8}$/u).describe("The tab to act in, as t1, t2…. Omit it for the tab in front.");const ref = z.string().min(1).max(64).describe("An element ref from the latest snapshot, such as e12.");const selector = z.string().min(1).max(2_048).describe("A CSS selector, role=button[name=\"Save\"] or text=Save, matching exactly one element in the page (not inside frames). Prefer a ref.");-const x = z.number().min(0).max(16_384).describe("A point in the page's viewport, in CSS pixels; pass y too.");-const y = z.number().min(0).max(16_384).describe("A point in the page's viewport, in CSS pixels; pass x too.");+const x = z.number().min(0).max(16_384).describe("A point in the page's viewport as it is now, in CSS pixels, as your latest screenshot maps them; pass y too.");+const y = z.number().min(0).max(16_384).describe("A point in the page's viewport as it is now, in CSS pixels, as your latest screenshot maps them; pass x too.");const timeoutMs = z.number().int().min(0).max(60_000).describe("How long to wait at most, in milliseconds. Defaults to 15000.");const point = z.object({ ref: ref.optional(), selector: selector.optional(), x: x.optional(), y: y.optional() });@@ -136,7 +136,7 @@ const DESCRIPTIONS: Record<ToolName, string> = {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.",agent_browser_read: "The page's visible text, or one element's, for reading long content or a single value such as a price. Pass offset to read on.",- agent_browser_screenshot: "A PNG of the visible page (1280 px wide at most), the whole page, or one element. Use it when the tree is not enough to see the page.",+ agent_browser_screenshot: "A PNG of the visible page, the whole page, or one element; its answer says how the picture's pixels map to the page's CSS pixels, which change when a person resizes the panel watching the browser. Use it when the tree is not enough to see the page.",agent_browser_click: "Click one element by ref (preferred) or selector, or a point. Waits until the element is visible, still and not covered. Returns early when the click opens a dialog.",agent_browser_fill: "Clear a text field and put text in it, as a paste would. Set submit to press Enter afterwards.",agent_browser_type: "Type text key by key into a field (by ref or selector) or wherever the focus is, for fields that react to each key.",diff --git a/server/browser/viewers/core.test.ts b/server/browser/viewers/core.test.tsindex 03a38bc69b..0066c070fd 100644--- a/server/browser/viewers/core.test.ts+++ b/server/browser/viewers/core.test.ts@@ -7,8 +7,8 @@ import { removeTempDir } from "../../testing/cleanup.ts";import { BrowserService } from "../service.ts";import { FakeBackend, FakeChrome, type FakeDocument } from "../testing/fake-chrome.ts";import { personUrl } from "../dispatch.ts";-import { ACK_PACE_MS, requestedSize, SETTLE_MS, type ViewerOutput } from "./core.ts";-import { MIN_WINDOW_WIDTH, UNATTACHED_VIEWPORT, viewportFor } from "./viewport.ts";+import { ACK_PACE_MS, SETTLE_MS, type ViewerOutput } from "./core.ts";+import { fillPage, MIN_WINDOW_WIDTH, requestedSize, UNATTACHED_VIEWPORT, viewportFor } from "./viewport.ts";const folders: string[] = [];const services: BrowserService[] = [];@@ -56,23 +56,35 @@ async function setup({ pageLimit = null, document = PAGE }: { pageLimit?: { widt}describe("the page fills the panel", () => {- it("is 1280x800 with nobody watching, the viewer's panel size while one watches, and 1280x800 again when it leaves", async () => {+ it("is 1280x800 with nobody watching, the viewer's panel shape at a desktop's width at least while one watches, and 1280x800 again when it leaves", async () => {const { watch, chrome } = await setup();expect(chrome().viewport).toEqual(UNATTACHED_VIEWPORT);const { viewer, outputs } = await watch({ size: { width: 1600, height: 1000 } });await until(() => chrome().viewport, same({ width: 1600, height: 1000 }));await until(() => outputs, (seen) => seen.some((output) => output.type === "viewport" && output.width === 1600 && output.height === 1000));await viewer.input({ type: "resize", width: 1200, height: 900 });- expect(chrome().viewport).toEqual({ width: 1200, height: 900 });+ expect(chrome().viewport).toEqual({ width: 1280, height: 960 });await viewer.close();await until(() => chrome().viewport, same(UNATTACHED_VIEWPORT));});+ it("gives a narrow panel a desktop page of its shape, never a phone's, and no taller than twice its width", async () => {+ const { watch, chrome, call } = await setup();+ const { viewer, outputs } = await watch({ size: { width: 400, height: 750 } });+ await until(() => chrome().viewport, same({ width: 1280, height: 2400 }));+ await until(() => outputs.filter((output) => output.type === "viewport").at(-1), (last) => last?.type === "viewport" && last.width === 1280 && last.height === 2400);+ expect((await call("agent_browser_eval", { expression: "[innerWidth, innerHeight]" })).content[0]?.text).toBe("[1280,2400]");+ await viewer.input({ type: "resize", width: 300, height: 900 });+ expect(chrome().viewport).toEqual({ width: 1280, height: 2560 });+ expect(fillPage({ width: 365, height: 686 })).toEqual({ width: 1280, height: 2406 });+ expect(fillPage({ width: 1440, height: 819 })).toEqual({ width: 1440, height: 819 });+ });+it("follows the latest request, keeps its size for a collapsed panel, and stops at 3840x2160", async () => {const { watch, chrome } = await setup();const first = await watch({ size: { width: 1400, height: 900 } });const second = await watch({ size: { width: 1000, height: 700 } });- await until(() => chrome().viewport, same({ width: 1000, height: 700 }));+ await until(() => chrome().viewport, same({ width: 1280, height: 896 }));await first.viewer.input({ type: "resize", width: 1500, height: 950 });expect(chrome().viewport).toEqual({ width: 1500, height: 950 });await second.viewer.input({ type: "resize", width: 1800, height: 40 });@@ -99,18 +111,21 @@ describe("the page fills the panel", () => {expect(chrome().viewport).toEqual(UNATTACHED_VIEWPORT);expect((await snapshot).isError).toBeUndefined();await resizing;- await until(() => chrome().viewport, same({ width: 1200, height: 900 }));+ await until(() => chrome().viewport, same({ width: 1280, height: 960 }));});- it("never makes a window larger than its screen: a filled panel keeps its shape, a set size its width", async () => {+ it("never makes a window larger than its screen: a filled panel keeps its shape, emulated past the screen, a set size its width", async () => {const { watch, chrome, page } = await setup({ pageLimit: { width: 1440, height: 757 } });expect(chrome().viewport).toEqual({ width: 1211, height: 757 });const { viewer, outputs } = await watch({ size: { width: 1600, height: 1000 } });await until(() => chrome().viewport, same({ width: 1211, height: 757 }));- await viewer.input({ type: "resize", width: 1000, height: 700 });- expect(chrome().viewport).toEqual({ width: 1000, height: 700 });+ await viewer.input({ type: "resize", width: 400, height: 750 });+ expect(chrome().viewport).toEqual({ width: 1280, height: 757 });+ expect(page().emulated).toEqual({ width: 1280, height: 2400 });+ expect(outputs.filter((output) => output.type === "viewport").at(-1)).toMatchObject({ width: 1280, height: 2400 });await viewer.input({ type: "resize", width: 2000, height: 800 });expect(chrome().viewport).toEqual({ width: 1440, height: 576 });+ expect(page().emulated).toBeNull();await viewer.input({ type: "takeControl" });await viewer.input({ type: "viewport", setting: { mode: "preset", preset: "tablet" } });expect(chrome().viewport).toEqual({ width: 820, height: 757 });@@ -164,9 +179,9 @@ describe("the page fills the panel", () => {const { watch, chrome, page } = await setup({ pageLimit: { width: 1440, height: 757 } });page().bar = 56;const { viewer, outputs } = await watch({ size: { width: 1600, height: 1000 } });- await viewer.input({ type: "resize", width: 1000, height: 900 });+ await viewer.input({ type: "resize", width: 2000, height: 1100 });expect(chrome().window.height).toBe(757 + 143);- expect(outputs.filter((output) => output.type === "viewport").at(-1)).toMatchObject({ width: 841, height: 701 });+ expect(outputs.filter((output) => output.type === "viewport").at(-1)).toMatchObject({ width: 1376, height: 701 });});it("emulates a page narrower than any window on a tab that opens later too", async () => {@@ -266,7 +281,7 @@ describe("viewers of one browser", () => {expect(other.outputs.slice(beforeTake)).toContainEqual(expect.objectContaining({ type: "control", controller: "another-viewer", held: true, owned: false }));const seen = other.outputs.length;await other.viewer.input({ type: "resize", width: 1100, height: 800 });- expect(chrome().viewport).toEqual({ width: 1000, height: 700 });+ expect(chrome().viewport).toEqual({ width: 1280, height: 896 });await holder.viewer.input({ type: "navigate", url: "example.org/next" });await sleep(30);const later = other.outputs.slice(seen);diff --git a/server/browser/viewers/core.ts b/server/browser/viewers/core.tsindex 046e62c02e..13d15a4142 100644--- a/server/browser/viewers/core.ts+++ b/server/browser/viewers/core.ts@@ -1,6 +1,6 @@// People watching and driving a bot's browser. Every viewer gets its own CDP session on the tab in front, with its own-// screencast sized to it, and the page fills the panel: in fill mode the window is resized to the size the latest-// viewer asked for, 1280x800 with nobody watching. Frames come at the screen's real device scale, so they stay sharp.+// screencast sized to it, and the page fills the panel: in fill mode it takes the shape of the latest viewer's panel at+// a desktop's width, 1280x800 with nobody watching. Frames come at the screen's real device scale, so they stay sharp.//// Adapted from pingdotgg/t3code@00cdceb1 apps/server/src/preview/ServerBrowser.ts (attachViewer,// dispatchViewerInput, releaseViewerInput, applySetting, withScreencastsPaused), MIT License, Copyright (c) 2026 T3@@ -21,7 +21,7 @@ import type { ProfileControl, TakeResult } from "../control.ts";import { personUrl } from "../dispatch.ts";import type { Tab } from "../tabs.ts";import { ACCEPT_OF, chooseOption, cursorAt, editableAt, selectAt, type SelectPopup } from "./popups.ts";-import { MIN_WINDOW_WIDTH, VIEWPORT_LIMITS, VIEWPORT_PRESETS, viewportFor, ZOOM_LIMITS, zoomedLayout, type ViewportSetting } from "./viewport.ts";+import { fitsScreen, MIN_WINDOW_WIDTH, requestedSize, VIEWPORT_PRESETS, viewportFor, ZOOM_LIMITS, zoomedLayout, type ViewportSetting } from "./viewport.ts";/** Chromium keeps three frames unacknowledged, so acking 100 ms after arrival caps a viewer near 30 fps. */export const ACK_PACE_MS = { hi: 100, lo: 200 } as const;@@ -123,13 +123,6 @@ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));const appliedKey = (size: { width: number; height: number }, zoom: number) => `${size.width}x${size.height}@${zoom}`;-/** A viewer's resize request, or null when it is out of range (a collapsed panel, say) and the page keeps its size. */-export function requestedSize(width: unknown, height: unknown): { width: number; height: number } | null {- const w = Math.min(Math.round(num(width)), VIEWPORT_LIMITS.maxWidth);- const h = Math.min(Math.round(num(height)), VIEWPORT_LIMITS.maxHeight);- return w >= VIEWPORT_LIMITS.minWidth && h >= VIEWPORT_LIMITS.minHeight ? { width: w, height: h } : null;-}-export class Viewer {readonly id = randomUUID();readonly options: Required<Omit<ViewerOptions, "size">>;@@ -458,7 +451,7 @@ export class ViewerHub {return viewportFor(this.setting, latest ? { width: latest.width, height: latest.height } : null, this.host.pageLimit());}- /** Resizes the real window; a zoom, or a preset narrower than any Chrome window, is emulated, as DevTools' device mode does. */+ /** Resizes the real window; a zoom, or a page narrower than any Chrome window or larger than the screen, is emulated, as DevTools' device mode does. */applyViewport(): Promise<void> {this.#applying = this.#applying.then(() => this.#apply(), () => this.#apply());return this.#applying;@@ -469,7 +462,7 @@ export class ViewerHub {if (!browser) return;const size = this.viewport();const zoom = this.zoom;- const emulated = size.width < MIN_WINDOW_WIDTH || zoom !== 1;+ const emulated = size.width < MIN_WINDOW_WIDTH || zoom !== 1 || !fitsScreen(size, this.host.pageLimit());const key = appliedKey(size, zoom);const active = this.host.active();if (this.#applied === key && browser.viewport?.width === Math.max(size.width, MIN_WINDOW_WIDTH)) return;diff --git a/server/browser/viewers/live-v1.test.ts b/server/browser/viewers/live-v1.test.tsindex 3316a3e09d..f5625cc619 100644--- a/server/browser/viewers/live-v1.test.ts+++ b/server/browser/viewers/live-v1.test.ts@@ -26,9 +26,9 @@ function setup() {const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 10, idleMs: () => 600_000, takeoverMs: 200 });const live = new LiveV1({ service, target: (session) => ({ session, key: `bot:${session}` }) });cleanups.push(async () => { live.closeAll(); await service.closeAll(); });- const open = async (session = "a", owner = "local-owner") => {+ const open = async (session = "a", owner = "local-owner", size: { width: number; height: number } | null = null) => {const sse = new SseRecorder();- await live.open({ botId: "bot", session, owner, isCurrent: () => true, res: sse.response });+ await live.open({ botId: "bot", session, owner, isCurrent: () => true, res: sse.response, size });const viewerId = String(sse.events.find((event) => event.type === "ready")?.data.viewerId);return { sse, viewerId, action: (body: Record<string, unknown>) => live.action({ viewerId, botId: "bot", owner, body }) };};@@ -59,6 +59,18 @@ describe("the v1 live view on the new browser", () => {.toContain("open: an event the v1 contract does not have: stalled");});+ it("fills the panel a view opened at, and follows its resizes, as the stream does", async () => {+ const { open, backend } = setup();+ const { action } = await open("a", "local-owner", { width: 400, height: 750 });+ await sleep(30);+ expect(backend.chrome.viewport).toEqual({ width: 1280, height: 2400 });+ expect(await action({ type: "resize", width: 1440, height: 819 })).toEqual({ ok: true });+ await sleep(30);+ expect(backend.chrome.viewport).toEqual({ width: 1440, height: 819 });+ expect(await action({ type: "resize", width: 1440, height: 20 })).toEqual({ ok: true });+ expect(backend.chrome.viewport).toEqual({ width: 1440, height: 819 });+ });+it("opens at most two views of one browser and eight in all", async () => {const { open } = setup();await open("a");diff --git a/server/browser/viewers/live-v1.ts b/server/browser/viewers/live-v1.tsindex d7da9a4a08..463983d934 100644--- a/server/browser/viewers/live-v1.ts+++ b/server/browser/viewers/live-v1.ts@@ -27,6 +27,8 @@ export interface LiveOpenOptions {owner: string;isCurrent: () => boolean;res: ServerResponse;+ /** The panel's size in CSS pixels, which the page fills from the start. */+ size?: { width: number; height: number } | null;}interface V1Viewer {@@ -192,7 +194,7 @@ export class LiveV1 {}, WAITING_AFTER_MS);waiting.unref?.();try {- const core = await this.#service.attachViewer(target, { owner: options.owner, canOperate: true, ...LO_TIER, pace: "lo", pointer: false }, (output) => this.#output(viewer, output));+ const core = await this.#service.attachViewer(target, { owner: options.owner, canOperate: true, ...LO_TIER, pace: "lo", pointer: false, ...(options.size ? { size: options.size } : {}) }, (output) => this.#output(viewer, output));(viewer as { id: string }).id = core.id;viewer.core = core;if (!this.#current(viewer)) { this.#close(viewer); return; }@@ -261,6 +263,10 @@ export class LiveV1 {}return { ok: true };}+ if (action.type === "resize") {+ if (action.size) await core.input({ type: "resize", ...action.size });+ return { ok: true };+ }if (action.type === "restart") {if (viewer.restarting) throw new BrowserLiveError("The browser is already restarting.", 409);viewer.restarting = true;diff --git a/server/browser/viewers/stream-v2.e2e.test.ts b/server/browser/viewers/stream-v2.e2e.test.tsindex 46e7dc536f..6be7c773ec 100644--- a/server/browser/viewers/stream-v2.e2e.test.ts+++ b/server/browser/viewers/stream-v2.e2e.test.ts@@ -16,6 +16,7 @@ import { CHROME } from "../cdp/testing/real-chrome.ts";import type { BrowserTarget } from "../service.ts";import { jpegSize, startService, until, type RealService } from "../testing/real-service.ts";import { StreamV2 } from "./stream-v2.ts";+import { fillPage } from "./viewport.ts";const suite = CHROME ? describe : describe.skip;const LOOPBACK = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;@@ -155,8 +156,13 @@ suite("the v2 stream on real Chrome", () => {expect(client.messages).toContainEqual(expect.objectContaining({ type: "viewport", width: 1600, height: 1000 }));// Watching is enough to size the page; nobody has to take control for it.client.send({ type: "resize", width: 1200, height: 900 });- await until(pageSize, same([1200, 900, 2]));- await until(() => client.frames.at(-1), (frame) => frame?.width === 2400 && frame.height === 1800);+ await until(pageSize, same([1280, 960, 2]));+ await until(() => client.frames.at(-1), (frame) => frame?.width === 2560 && frame.height === 1920);+ // A narrow, tall panel: a desktop page of its shape, taller than the screen, in frames as tall as the viewer takes.+ client.send({ type: "resize", width: 400, height: 750 });+ await until(pageSize, same([1280, 2400, 2]));+ await until(() => client.frames.at(-1), (frame) => frame?.height === 2000 && Math.abs(frame.width - 1067) <= 1);+ expect(client.messages.filter((message) => message.type === "viewport").at(-1)).toMatchObject({ width: 1280, height: 2400 });await client.close();await until(pageSize, same([1280, 800, 2]));}, hostTimeout(90_000));@@ -164,7 +170,7 @@ suite("the v2 stream on real Chrome", () => {it("ends every drag of the panel on a sharp frame of the final size, on a page that never repaints by itself", async () => {await opened("/still", STILL);const client = await connect("width=1200&height=800&maxWidth=3200&maxHeight=2000");- await until(pageSize, same([1200, 800, 2]));+ await until(pageSize, same([1280, 853, 2]));for (let trial = 0; trial < 6; trial++) {const grow = trial % 2 === 0;const sizes = Array.from({ length: 10 }, (_, step) => (grow ? [1240 + step * 40, 820 + step * 20] : [1560 - step * 40, 980 - step * 20]));@@ -172,9 +178,9 @@ suite("the v2 stream on real Chrome", () => {client.send({ type: "resize", width, height });await sleep(150);}- const [width, height] = sizes.at(-1)!;- await until(pageSize, same([width, height, 2]));- await until(() => client.frames.at(-1), (frame) => frame?.width === width! * 2 && frame.height === height! * 2, 3_000);+ const page = fillPage({ width: sizes.at(-1)![0]!, height: sizes.at(-1)![1]! });+ await until(pageSize, same([page.width, page.height, 2]));+ await until(() => client.frames.at(-1), (frame) => frame?.width === page.width * 2 && frame.height === page.height * 2, 3_000);}await client.close();}, hostTimeout(120_000));@@ -183,11 +189,11 @@ suite("the v2 stream on real Chrome", () => {await opened("/held", STILL);const holder = await connect("width=1200&height=800&maxWidth=2400&maxHeight=1600");await takeControl(holder);- await until(pageSize, same([1200, 800, 2]));+ await until(pageSize, same([1280, 853, 2]));const other = await connect("width=700&height=1000&maxWidth=1400&maxHeight=2000");await until(() => other.messages.filter((message) => message.type === "control").at(-1), (control) => control?.controller === "another-viewer");await sleep(1_000);- expect(await pageSize()).toEqual([1200, 800, 2]);+ expect(await pageSize()).toEqual([1280, 853, 2]);await other.close();holder.send({ type: "resize", width: 1512, height: 900 });holder.send({ type: "frameCap", maxWidth: 3024, maxHeight: 1800 });diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.tsindex 53498ed0b5..1c5117204f 100644--- a/server/browser/viewers/stream-v2.ts+++ b/server/browser/viewers/stream-v2.ts@@ -13,7 +13,8 @@ import { WebSocketServer, type RawData, type WebSocket } from "ws";import { BrowserHostError, SETUP_COMMAND } from "../chrome/host-setup.ts";import type { BrowserService, BrowserTarget } from "../service.ts";-import { FRAME_CAP_LIMITS, requestedSize, type Viewer, type ViewerOptions, type ViewerOutput } from "./core.ts";+import { FRAME_CAP_LIMITS, type Viewer, type ViewerOptions, type ViewerOutput } from "./core.ts";+import { requestedSize } from "./viewport.ts";import { displayUrl } from "./live-v1.ts";/** Close codes the stream client acts on. */diff --git a/server/browser/viewers/viewers.e2e.test.ts b/server/browser/viewers/viewers.e2e.test.tsindex 22af0129a3..8ccc1bbf12 100644--- a/server/browser/viewers/viewers.e2e.test.ts+++ b/server/browser/viewers/viewers.e2e.test.ts@@ -19,19 +19,28 @@ const suite = CHROME ? describe : describe.skip;/** A page that keeps painting, so a screencast keeps sending frames. */const ANIMATED = `<!doctype html><title>animated</title><style>@keyframes spin{to{transform:rotate(360deg)}}#s{width:60px;height:60px;background:#36c;animation:spin 1s linear infinite}</style><div id="s"></div><div style="height:4000px"></div>`;-/** Buttons A and B swap places on a page narrower than 1000 CSS pixels, or once /state says so; a click notes the width. */+/** Buttons A and B swap places on a page taller than 1500 CSS pixels, or once /state says so; a click notes the page's size. */const SWAP = `<!doctype html><title>swap</title><style>body{margin:0} button{position:absolute;left:100px;width:300px;height:120px;font-size:30px}#a{top:100px} #b{top:300px}-@media (max-width: 1000px) { #a{top:300px} #b{top:100px} }+@media (min-height: 1500px) { #a{top:300px} #b{top:100px} }body.swapped #a{top:300px} body.swapped #b{top:100px}</style>-<button id="a" onclick="document.body.dataset.clicked='a:'+innerWidth">A</button>-<button id="b" onclick="document.body.dataset.clicked='b:'+innerWidth">B</button>+<button id="a" onclick="document.body.dataset.clicked='a:'+innerWidth+'x'+innerHeight">A</button>+<button id="b" onclick="document.body.dataset.clicked='b:'+innerWidth+'x'+innerHeight">B</button><script>setInterval(async () => { if (await (await fetch("/state", { cache: "no-store" })).text() === "swap") document.body.classList.add("swapped"); }, 10);</script>`;+/** A page taller than its viewport whose Low button and field sit where only a tall viewport shows them; a press notes where it landed. */+const TALL = `<!doctype html><title>tall</title><style>body{margin:0;height:4000px}</style>+<button id="low" style="position:absolute;left:600px;top:1950px;width:200px;height:100px">Low</button>+<input id="field" aria-label="Field" style="position:absolute;left:100px;top:2150px;width:300px">+<script>addEventListener("mousedown", (event) => { document.title = "at " + event.clientX + "," + event.clientY + " on " + (event.target.id || event.target.tagName) + " of " + innerWidth + "x" + innerHeight; });</script>`;+const SCREEN: ScreenSpec = { width: 2560, height: 1600, deviceScaleFactor: 2 };+/** Width and height from a PNG's header. */+const pngSize = (data: Buffer) => ({ width: data.readUInt32BE(16), height: data.readUInt32BE(20) });+interface Seen { width: number; height: number; still: boolean; at: number }suite("viewers of the new browser on real Chrome", () => {@@ -79,15 +88,15 @@ suite("viewers of the new browser on real Chrome", () => {const pageSize = (target: BrowserTarget) => real.peek<[number, number, number]>(target, "[innerWidth, innerHeight, devicePixelRatio]");const same = (expected: unknown[]) => (actual: unknown[]) => JSON.stringify(actual) === JSON.stringify(expected);- it("fills the panel: the page takes the viewer's size, frames come at the screen's scale, and 1280x800 returns when it leaves", async () => {+ it("fills the panel: the page takes the viewer's shape at a desktop's width, frames come at the screen's scale, and 1280x800 returns when it leaves", async () => {const target = await opened();expect(await pageSize(target)).toEqual([1280, 800, 2]);const { viewer, frames } = await watch(target, { size: { width: 1600, height: 1000 } });await until(() => pageSize(target), same([1600, 1000, 2]));await until(() => frames.at(-1), (frame) => frame?.width === 3200 && frame.height === 2000);await viewer.input({ type: "resize", width: 1200, height: 900 });- await until(() => pageSize(target), same([1200, 900, 2]));- await until(() => frames.at(-1), (frame) => frame?.width === 2400 && frame.height === 1800);+ await until(() => pageSize(target), same([1280, 960, 2]));+ await until(() => frames.at(-1), (frame) => frame?.width === 2560 && frame.height === 1920);await viewer.close();await until(() => pageSize(target), same([1280, 800, 2]));}, hostTimeout(90_000));@@ -98,26 +107,27 @@ suite("viewers of the new browser on real Chrome", () => {const second = await watch(target, { size: { width: 1400, height: 900 } });await until(() => pageSize(target), same([1400, 900, 2]));await first.viewer.input({ type: "resize", width: 900, height: 600 });- await until(() => pageSize(target), same([900, 600, 2]));+ await until(() => pageSize(target), same([1280, 853, 2]));await second.viewer.input({ type: "takeControl" });await second.viewer.input({ type: "viewport", setting: { mode: "preset", preset: "phone" } });await until(() => pageSize(target), same([390, 844, 2]));await second.viewer.input({ type: "viewport", setting: { mode: "fill" } });- await until(() => pageSize(target), same([900, 600, 2]));+ await until(() => pageSize(target), same([1280, 853, 2]));await second.viewer.input({ type: "releaseControl" });await first.viewer.close();await second.viewer.close();}, hostTimeout(90_000));- it("lays a tab that opens later out at a panel narrower than any window too, and leaves it so when the bot comes back", async () => {+ it("lays a tab that opens later out at a narrow panel's desktop page taller than the screen too, and leaves it so when the bot comes back", async () => {const target = await opened();const { viewer } = await watch(target, { size: { width: 400, height: 700 } });- await until(() => pageSize(target), same([400, 700, 2]));+ await until(() => pageSize(target), same([1280, 2240, 2]));const windowWidth = await real.peek<number>(target, "outerWidth");+ expect(await real.peek<number>(target, "outerHeight")).toBeLessThanOrEqual(SCREEN.height);expect((await real.call(target, "agent_browser_tabs", { action: "new", url: page })).isError).toBeUndefined();- await until(() => pageSize(target), same([400, 700, 2]));+ await until(() => pageSize(target), same([1280, 2240, 2]));expect((await real.call(target, "agent_browser_tabs", { action: "switch", tab: "t1" })).isError).toBeUndefined();- expect(await pageSize(target)).toEqual([400, 700, 2]);+ expect(await pageSize(target)).toEqual([1280, 2240, 2]);expect(await real.peek<number>(target, "outerWidth")).toBe(windowWidth);await viewer.close();}, hostTimeout(90_000));@@ -158,15 +168,47 @@ suite("viewers of the new browser on real Chrome", () => {let resized: Promise<void> | null = null;const viewer: Viewer = await real.service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 2560, maxHeight: 1600, size: { width: 1280, height: 800 } }, (output) => {if (output.type === "frame") output.ack();- else if (output.type === "pointer" && output.phase === "move") resized ??= viewer.input({ type: "resize", width: 900, height: 800 });+ else if (output.type === "pointer" && output.phase === "move") resized ??= viewer.input({ type: "resize", width: 400, height: 750 });});await until(() => pageSize(target), same([1280, 800, 2]));expect(real.text(await real.call(target, "agent_browser_click", { ref }))).toContain(`Clicked ${ref}.`);expect(resized).not.toBeNull();await resized;- expect(await until(() => real.peek<string | undefined>(target, "document.body.dataset.clicked"), (value) => value !== undefined)).toBe("a:1280");- await until(() => pageSize(target), same([900, 800, 2]));+ expect(await until(() => real.peek<string | undefined>(target, "document.body.dataset.clicked"), (value) => value !== undefined)).toBe("a:1280x800");+ await until(() => pageSize(target), same([1280, 2400, 2]));+ await viewer.close();+ }, hostTimeout(90_000));++ it("lets the bot see, click, type and scroll a narrow panel's tall page as it is laid out, and the standard page once nobody watches", async () => {+ const target = await opened(fx.page("/tall", TALL));+ const { viewer } = await watch(target, { size: { width: 400, height: 750 } });+ await until(() => pageSize(target), same([1280, 2400, 2]));+ const picture = await real.call(target, "agent_browser_screenshot");+ // The viewport is 1280 CSS pixels wide less the scrollbar a platform with classic scrollbars draws.+ const note = /(\d+)x1488 pixels: the (\d+)x2400 CSS-pixel viewport drawn at 0\.62, so divide x and y read off it by 0\.62/u.exec(real.text(picture));+ expect(note, real.text(picture)).not.toBeNull();+ const [width, region] = [Number(note![1]), Number(note![2])];+ expect(width).toBe(Math.round(region * 0.62));+ expect(pngSize(Buffer.from(picture.content.find((part) => part.type === "image")!.data!, "base64"))).toEqual({ width, height: 1488 });+ // The Low button's middle, read off the picture at 434,1240, divided by the scale its answer gave.+ expect((await real.call(target, "agent_browser_click", { x: 434 / 0.62, y: 1240 / 0.62 })).isError).toBeUndefined();+ expect(await real.peek<string>(target, "document.title")).toBe("at 700,2000 on low of 1280x2400");+ const outside = await real.call(target, "agent_browser_click", { x: 700, y: 2500 });+ expect(outside.isError).toBe(true);+ expect(real.text(outside)).toContain("outside the page's viewport, which is 1280x2400 CSS pixels now");+ const ref = /textbox "Field" \[ref=(e\d+)\]/u.exec(real.text(await real.call(target, "agent_browser_snapshot")))![1]!;+ expect((await real.call(target, "agent_browser_type", { ref, text: "typed low" })).isError).toBeUndefined();+ expect(await real.peek<string>(target, "document.getElementById('field').value")).toBe("typed low");+ expect(real.text(await real.call(target, "agent_browser_scroll", { dy: 600 }))).toContain("Scrolled by 0,600.");+ // A platform may scroll smoothly, and by more or less than the wheel's pixels: aim where the page came to rest.+ let top = -1;+ await until(async () => { const before = top; top = await real.peek<number>(target, "Math.round(scrollY)"); return top > 0 && top === before; }, Boolean);+ expect((await real.call(target, "agent_browser_click", { x: 700, y: 2000 - top })).isError).toBeUndefined();+ expect(await real.peek<string>(target, "document.title")).toBe(`at 700,${2000 - top} on low of 1280x2400`);await viewer.close();+ await until(() => pageSize(target), same([1280, 800, 2]));+ expect(real.text(await real.call(target, "agent_browser_screenshot"))).toMatch(/\d+x800 pixels, one per CSS pixel of the viewport/u);+ expect(real.text(await real.call(target, "agent_browser_click", { x: 700, y: 2000 }))).toContain("which is 1280x800 CSS pixels now");}, hostTimeout(90_000));it("ends a scroll on a sharp frame at full size", async () => {diff --git a/server/browser/viewers/viewport.ts b/server/browser/viewers/viewport.tsindex e914bddd82..346611d239 100644--- a/server/browser/viewers/viewport.ts+++ b/server/browser/viewers/viewport.ts@@ -15,6 +15,28 @@ export const VIEWPORT_PRESETS = {phone: { width: 390, height: 844 },} as const;+/** The standard page's width: a filled panel never makes the page narrower, so sites keep the desktop layout the bot knows. */+export const DESKTOP_WIDTH = UNATTACHED_VIEWPORT.width;+/** A filled page is at most this many times as tall as it is wide; a panel taller than that shows bands above and below it. */+export const MAX_FILL_RATIO = 2;++/** The page that fills a panel of `panel` CSS pixels when the viewer scales it to the panel: the panel's shape, at least a desktop wide. */+export function fillPage(panel: { width: number; height: number }): { width: number; height: number } {+ const width = Math.max(Math.round(panel.width), DESKTOP_WIDTH);+ return { width, height: Math.min(Math.round(panel.height * width / panel.width), MAX_FILL_RATIO * width) };+}++export const fitsScreen = (size: { width: number; height: number }, limit: { width: number; height: number } | null) =>+ !limit || (size.width <= limit.width && size.height <= limit.height);++/** A viewer's panel size, or null when it is out of range (a collapsed panel, say) and the page keeps its size. */+export function requestedSize(width: unknown, height: unknown): { width: number; height: number } | null {+ const finite = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);+ const w = Math.min(Math.round(finite(width)), VIEWPORT_LIMITS.maxWidth);+ const h = Math.min(Math.round(finite(height)), VIEWPORT_LIMITS.maxHeight);+ return w >= VIEWPORT_LIMITS.minWidth && h >= VIEWPORT_LIMITS.minHeight ? { width: w, height: h } : null;+}+export type ViewportSetting =| { mode: "fill" }| { mode: "preset"; preset: keyof typeof VIEWPORT_PRESETS; landscape?: boolean }@@ -22,11 +44,18 @@ export type ViewportSetting =/*** The CSS size `setting` gives the page, `requested` being the panel size of the viewer that asked last, within `limit`,- * the largest page the screen fits: a filled panel gets a page of its own shape, which the viewer scales to fill it; a- * set size is cut to fit.+ * the largest page the screen fits: with nobody watching, the standard size fitted to the screen; a filled panel gets+ * its own shape at a desktop's width, which the viewer scales to fill it, shown smaller by a window held to its screen+ * while that keeps it as wide as the standard page, and emulated otherwise; a set size is cut to fit.*/export function viewportFor(setting: ViewportSetting, requested: { width: number; height: number } | null, limit: { width: number; height: number } | null = null): { width: number; height: number } {- if (setting.mode === "fill") return fitPage(requested ?? { ...UNATTACHED_VIEWPORT }, limit);+ if (setting.mode === "fill") {+ const standard = fitPage({ ...UNATTACHED_VIEWPORT }, limit);+ if (!requested) return standard;+ const page = fillPage(requested);+ const fitted = fitPage(page, limit);+ return fitted.width >= standard.width ? fitted : page;+ }const size = setting.mode === "fixed" ? { width: setting.width, height: setting.height } : presetSize(setting);if (!limit) return size;return { width: size.width < MIN_WINDOW_WIDTH ? size.width : Math.min(size.width, limit.width), height: Math.min(size.height, limit.height) };diff --git a/server/host/browser.ts b/server/host/browser.tsindex efb0fae4f7..3fe755c3b0 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -101,7 +101,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {const agentBrowserRuntime = new BrowserRuntime({closeBrowser: (session, spec) => closeBrowserSession(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session })),- applyViewport: (spec) => setBrowserViewport(spec.command, spec.env),+ applyViewport: (spec, size) => setBrowserViewport(spec.command, spec.env, size),launch: chromeLauncher,relayCommand: (spec, session, command, timeoutMs) => relayCommand(spec, session, command, timeoutMs).catch((error: unknown) => {throw error instanceof RelayTimeout ? new TransportError(error.message) : error;diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.tsindex 21e8b08b77..6a6afcbd3b 100644--- a/server/routes/browser-viewers.test.ts+++ b/server/routes/browser-viewers.test.ts@@ -52,6 +52,8 @@ interface Fixture {pickerChecks: number;/** The v1 views opened, by the view each asked to carry on from. */resumes: Array<string | null | undefined>;+ /** The panel size each v1 view opened at. */+ sizes: Array<{ width: number; height: number } | null | undefined>;/** Whose browser each view was opened on, and each check that the view still shows it. */opened: Audience[];checked: Audience[];@@ -73,7 +75,7 @@ async function serve({ attach, current = () => true, download, audience = () =>download?: (id: string) => Download | undefined;audience?: (threadId: string | null) => Audience | null;} = {}): Promise<Fixture> {- const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;+ const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], sizes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;folders.push(fixture.dataDir);const viewer = { id: "viewer", input: async (message: unknown) => { fixture.inputs.push(message); }, close: async () => {} } as unknown as Viewer;const service = {@@ -92,6 +94,7 @@ async function serve({ attach, current = () => true, download, audience = () =>viewers: {open: async (options) => {fixture.resumes.push(options.resume);+ fixture.sizes.push(options.size);fixture.isCurrent = options.isCurrent;options.res.writeHead(204).end();},@@ -299,6 +302,14 @@ describe("the v1 live view", () => {expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/live`)).status).toBe(204);expect(fixture.resumes).toEqual(["old-viewer", null]);});++ it("opens the view at the panel's size, and leaves a collapsed or missing one to the page", async () => {+ const fixture = await serve();+ for (const query of ["?width=365&height=686", "?width=365&height=40", "", "?width=wide&height=686"]) {+ expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/live${query}`)).status).toBe(204);+ }+ expect(fixture.sizes).toEqual([{ width: 365, height: 686 }, null, null, null]);+ });});describe("the page's file picker and downloads", () => {diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.tsindex 4653ad0fdb..f7db2b468e 100644--- a/server/routes/browser-viewers.ts+++ b/server/routes/browser-viewers.ts@@ -12,6 +12,7 @@ import type { Audience } from "../audience.ts";import { storeUploads } from "../browser-upload.ts";import type { BrowserLive } from "../browser-live.ts";import type { LiveRouter } from "../browser/engines.ts";+import { requestedSize } from "../browser/viewers/viewport.ts";import { messageFileDisposition } from "../message-file.ts";import { isSameOrigin, type RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -127,7 +128,8 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHaif (live) {if (method === "GET" && live[2] === "live") {req.socket.setTimeout(0);- return await deps.viewers.open({ botId: browser.botId, session: browser.session, spec: browser.spec, owner, isCurrent, res, resume: url.searchParams.get("resume") });+ const size = requestedSize(Number(url.searchParams.get("width")), Number(url.searchParams.get("height")));+ return await deps.viewers.open({ botId: browser.botId, session: browser.session, spec: browser.spec, owner, isCurrent, res, resume: url.searchParams.get("resume"), size });}if (method === "POST" && live[2] === "action") {const body = await readBody(req, 32_768);diff --git a/src/components/BrowserPanel.test.ts b/src/components/BrowserPanel.test.tsindex 934f1fe224..f4085f18ce 100644--- a/src/components/BrowserPanel.test.ts+++ b/src/components/BrowserPanel.test.ts@@ -115,11 +115,11 @@ describe("the browser panel's connection", () => {expect(host.querySelector("[data-browser-transport]")!.getAttribute("data-browser-transport")).toBe("stream");});- it("uses the v1 live view on agent-browser, and when the stream is refused before it opens", async () => {+ it("uses the v1 live view on agent-browser, sized to the panel, and when the stream is refused before it opens", async () => {fixture.state.config.browserEngine = { kind: "engine", engine: "agent-browser" };await render();expect(FakeSocket.instances).toHaveLength(0);- expect(FixtureEventSource.instances[0]!.url).toBe("/api/bots/pepper/browser/live");+ expect(FixtureEventSource.instances[0]!.url).toBe("/api/bots/pepper/browser/live?width=1600&height=1000");act(() => root.unmount());root = createRoot(host);fixture.state.config.browserEngine = { kind: "engine", engine: "chrome" };@@ -216,7 +216,7 @@ describe("a v1 live view whose stream dropped", () => {expect(host.textContent).toContain("Browser disconnected");await act(async () => button("Reconnect").click());await flush();- expect(live().url).toBe("/api/bots/pepper/browser/live?resume=old-viewer");+ expect(live().url).toBe("/api/bots/pepper/browser/live?resume=old-viewer&width=1600&height=1000");await emit("ready", { viewerId: "new-viewer" });expect(host.textContent).not.toContain("Browser disconnected");});@@ -251,7 +251,7 @@ describe("a v1 live view whose stream dropped", () => {expect(host.textContent).toContain("Browser disconnected");await act(async () => { window.dispatchEvent(new Event("focus")); });expect(FixtureEventSource.instances).toHaveLength(7);- expect(live().url).toBe("/api/bots/pepper/browser/live?resume=old-viewer");+ expect(live().url).toBe("/api/bots/pepper/browser/live?resume=old-viewer&width=1600&height=1000");await emit("ready", { viewerId: "back-viewer" });expect(host.textContent).not.toContain("Browser disconnected");});diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsxindex bcd80213f1..388cc51c7e 100644--- a/src/components/BrowserPanel.tsx+++ b/src/components/BrowserPanel.tsx@@ -33,9 +33,9 @@ function tabsOf(value: unknown): BrowserTab[] {}/**- * A bot's browser: the page fills the panel, streamed over the v2 WebSocket when the new engine runs it, else over the- * v1 live view. Security: a new connection never silently restores permission to type and never replays old input.- * Only the server returns a hold, and only to this panel's reconnect after its own v1 stream dropped.+ * A bot's browser: the page fills the panel on either engine, streamed over the v2 WebSocket when the new engine runs+ * it, else over the v1 live view. Security: a new connection never silently restores permission to type and never+ * replays old input. Only the server returns a hold, and only to this panel's reconnect after its own v1 stream dropped.*/export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserSignIn; page?: BrowserPage }) {const { state } = useStore();@@ -115,7 +115,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserSreturn createLiveStreamClient(bot.id, events, (body, viewerId) => api(withBrowserScope(`/api/bots/${encodeURIComponent(bot.id)}/browser/action`, scope), {// 120 s matches the server's browser requestTimeoutMs.method: "POST", body: JSON.stringify({ ...body, viewerId }), timeoutMs: 120_000,- }), resume.current, scope);+ }), resume.current, scope, { width: target.width, height: target.height });}, [bot.id, bot.browserProfile, scopedThread, stream]);const interact = useCallback((input: PreviewStreamInput) => {@@ -317,7 +317,6 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserSref={surface}connect={connect}input={interact}- followSize={stream}label={`${bot.name}’s browser page`}onClient={onClient}onControl={onControl}diff --git a/src/components/browser/StreamSurface.tsx b/src/components/browser/StreamSurface.tsxindex 319442640e..f89dacbcbf 100644--- a/src/components/browser/StreamSurface.tsx+++ b/src/components/browser/StreamSurface.tsx@@ -171,8 +171,6 @@ export function StreamSurface(props: {readonly connect: SurfaceConnect;/** Page input and toolbar commands, through the panel's control rules. */readonly input: (input: PreviewStreamInput) => void;- /** Sends the surface size, so the page fills it. */- readonly followSize?: boolean;readonly label?: string;readonly onClient?: (client: PreviewStreamClient | null) => void;readonly onControl?: (control: PreviewStreamControl | null) => void;@@ -188,7 +186,7 @@ export function StreamSurface(props: {readonly className?: string;readonly ref?: Ref<StreamSurfaceHandle>;}) {- const { connect, followSize = true, ref } = props;+ const { connect, ref } = props;const propsRef = useRef(props);propsRef.current = props;const canvasRef = useRef<HTMLCanvasElement | null>(null);@@ -317,7 +315,7 @@ export function StreamSurface(props: {const previous = sizeRef.current;if (previous?.width === size.width && previous.height === size.height) return;sizeRef.current = size;- if (followSize) clientRef.current?.send({ type: "resize", ...size });+ clientRef.current?.send({ type: "resize", ...size });// Outgrowing the cap restarts the screencast, so grow it once the size settles rather than on every throttled// resize of a drag.if (capTimer !== null) clearTimeout(capTimer);@@ -335,7 +333,7 @@ export function StreamSurface(props: {if (timer !== null) clearTimeout(timer);if (capTimer !== null) clearTimeout(capTimer);};- }, [followSize]);+ }, []);useEffect(() => {const canvas = canvasRef.current;@@ -358,7 +356,7 @@ export function StreamSurface(props: {if (next?.dialog?.message !== previous?.dialog?.message || next?.dialog?.defaultValue !== previous?.dialog?.defaultValue) setPromptText(next?.dialog?.defaultValue ?? "");if (next?.controller !== "you") {setSelect(null);- } else if (previous?.controller !== "you" && followSize && sizeRef.current) {+ } else if (previous?.controller !== "you" && sizeRef.current) {clientRef.current?.send({ type: "resize", ...sizeRef.current });}if (!operable(next)) {@@ -442,7 +440,7 @@ export function StreamSurface(props: {setAgentCursor(null);clearInput();};- }, [capKnown, clearInput, connect, followSize, hostSetup, notify]);+ }, [capKnown, clearInput, connect, hostSetup, notify]);useEffect(() => {const canvas = canvasRef.current;diff --git a/src/lib/browser-stream-v1.test.ts b/src/lib/browser-stream-v1.test.tsindex d2a3a79930..dc0f8f8928 100644--- a/src/lib/browser-stream-v1.test.ts+++ b/src/lib/browser-stream-v1.test.ts@@ -116,6 +116,45 @@ describe("the v1 live client", () => {expect(handlers.onMessage).toHaveBeenCalledWith({ type: "url", url: "https://a.test/next" });});+ it("opens at the panel's size and sends each new size to its view while it only watches, the newest once the last is answered", async () => {+ const post = vi.fn<(body: Record<string, unknown>, viewerId: string) => Promise<unknown>>().mockResolvedValue({ ok: true });+ const client = createLiveStreamClient("pepper", events(), post, { viewer: "" }, {}, { width: 365.4, height: 686 });+ const source = FixtureEventSource.instances.at(-1)!;+ expect(source.url).toBe("/api/bots/pepper/browser/live?width=365&height=686");+ expect(client.send({ type: "resize", width: 400, height: 700 })).toBe(true);+ expect(post).not.toHaveBeenCalled();+ source.emit("ready", { viewerId: "v1" });+ expect(post).toHaveBeenLastCalledWith({ type: "resize", width: 400, height: 700 }, "v1");+ source.emit("control", { held: false, owned: false, controlling: false });+ await new Promise((resolve) => setTimeout(resolve, 0));+ const answer = deferred();+ post.mockReturnValueOnce(answer.promise.then(() => ({ ok: true })));+ client.send({ type: "resize", width: 420, height: 700 });+ client.send({ type: "resize", width: 440, height: 700 });+ client.send({ type: "resize", width: 460, height: 720 });+ expect(post.mock.calls.filter(([body]) => body.type === "resize")).toHaveLength(2);+ answer.resolve();+ await vi.waitFor(() => expect(post).toHaveBeenLastCalledWith({ type: "resize", width: 460, height: 720 }, "v1"));+ expect(post.mock.calls.filter(([body]) => body.type === "resize")).toHaveLength(3);+ });++ it("keeps going when a server without resizing refuses a size", async () => {+ const post = vi.fn<(body: Record<string, unknown>, viewerId: string) => Promise<unknown>>()+ .mockImplementation(async (body) => { if (body.type === "resize") throw Object.assign(new Error("Invalid browser action."), { status: 400 }); return { ok: true }; });+ const handlers = events({ onMessage: vi.fn(), onGone: vi.fn() });+ const client = createLiveStreamClient("pepper", handlers, post, { viewer: "" }, {}, { width: 365, height: 686 });+ const source = FixtureEventSource.instances.at(-1)!;+ source.emit("ready", { viewerId: "v1" });+ source.emit("control", { held: true, owned: true, controlling: true });+ client.send({ type: "resize", width: 500, height: 700 });+ await new Promise((resolve) => setTimeout(resolve, 0));+ client.transport.send({ type: "text", text: "hi" });+ await client.transport.settle();+ expect(post).toHaveBeenLastCalledWith({ type: "input_keyboard", eventType: "char", text: "hi" }, "v1");+ expect(handlers.onMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "notice" }));+ expect(handlers.onGone).not.toHaveBeenCalled();+ });+it("takes control with a POST, then sends input in order while it controls", async () => {const { client, post, handlers, source } = open();source.emit("ready", { viewerId: "v1" });diff --git a/src/lib/browser-stream-v1.ts b/src/lib/browser-stream-v1.tsindex e225463cdf..a1f50221a1 100644--- a/src/lib/browser-stream-v1.ts+++ b/src/lib/browser-stream-v1.ts@@ -169,8 +169,10 @@ export function liveControl(value: { held?: unknown; owned?: unknown; controllin* Opens the v1 view of a bot's browser. Frames come as base64 JPEG and wait for an acknowledgement each; the view* reconnects a few times after a dropped connection, never replaying input, and asks the server for the hold its last* view had. It reconnects at once when the window is focused, shown or back online, also after its retries ran out.+ * The panel's size (`initialSize`, then each resize) goes with every connection and to the open view, so the page fills+ * the panel; a server without resizing refuses the action and its page keeps its own size.*/-export function createLiveStreamClient(botId: string, events: PreviewStreamEvents, post: LivePost, resume: LiveResume = { viewer: "" }, scope: Readonly<Record<string, string>> = {}): LiveStreamClient {+export function createLiveStreamClient(botId: string, events: PreviewStreamEvents, post: LivePost, resume: LiveResume = { viewer: "" }, scope: Readonly<Record<string, string>> = {}, initialSize: { width: number; height: number } | null = null): LiveStreamClient {let stopped = false;/** Stopped because its retries ran out, not refused for good: coming back to the window tries again. */let revivable = false;@@ -185,6 +187,9 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEventlet retry: ReturnType<typeof setTimeout> | null = null;/** Inputs one request may carry: what this view's server said, 1 for one that takes no batches. */let inputBatch = 1;+ let size = initialSize;+ /** The size on its way to the open view; a newer one waits for its answer. */+ let sizing: { width: number; height: number } | null = null;const dropped = (live: EventSource, retryable: boolean) => {live.close();@@ -222,10 +227,28 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEventnotice(cause instanceof Error ? cause.message : String(cause));}, () => inputBatch);+ /** One resize request at a time, the newest size last; a refusal changes nothing. */+ const sendSize = () => {+ const wanted = size;+ const to = viewerId;+ if (sizing || !wanted || !to) return;+ sizing = wanted;+ void post({ type: "resize", width: Math.round(wanted.width), height: Math.round(wanted.height) }, to).catch(() => undefined).finally(() => {+ sizing = null;+ if (size !== wanted && viewerId === to) sendSize();+ });+ };+const connect = () => {retry = null;if (stopped) return;- const query = withBrowserScope(resume.viewer ? `?resume=${encodeURIComponent(resume.viewer)}` : "", scope);+ const params = new URLSearchParams(resume.viewer ? { resume: resume.viewer } : {});+ const opening = size;+ if (size) {+ params.set("width", String(Math.round(size.width)));+ params.set("height", String(Math.round(size.height)));+ }+ const query = withBrowserScope(params.size ? `?${params.toString()}` : "", scope);const live = new EventSource(`/api/bots/${encodeURIComponent(botId)}/browser/live${query}`);source = live;heardAt = Date.now();@@ -241,6 +264,7 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEventinputBatch = Number.isSafeInteger(data.inputBatch) ? Math.max(1, Math.min(Number(data.inputBatch), 64)) : 1;resume.viewer = "";events.onConnectedChange(true);+ if (size !== opening) sendSize();});listen("heartbeat", () => { attempts = 0; });listen("frame", (data) => {@@ -308,10 +332,15 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEventif (page) document.addEventListener("visibilitychange", returned);const send = (input: PreviewStreamInput) => {+ if (input.type === "resize") {+ size = { width: input.width, height: input.height };+ sendSize();+ return true;+ }if (!viewerId || !control?.canOperate) return false;- if (!["takeControl", "resize", "restart"].includes(input.type) && control.controller !== "you") return false;+ if (!["takeControl", "restart"].includes(input.type) && control.controller !== "you") return false;const action = liveAction(input);- if (!action) return input.type === "resize";+ if (!action) return false;// The page's question holds the input queued behind it, so its answer goes straight to the server.if (input.type === "dialog" && !Array.isArray(action)) {void postTo(action, viewerId).catch((cause: unknown) => notice(cause instanceof Error ? cause.message : String(cause)));