Skip to content

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

Browser: log every input that does not reach the page, and test person and bot input on the default engine (#6891)

Milind Soni49e32fb42ceb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a74cdeb02c..312ca774fe 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -597,7 +597,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/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 scripts/testing/inline-page-height-ui.e2e.test.ts scripts/testing/room-pages-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/browser-evidence.e2e.test.ts scripts/testing/browser-fill.e2e.test.ts scripts/testing/browser-input.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 scripts/testing/inline-page-height-ui.e2e.test.ts scripts/testing/room-pages-ui.e2e.test.ts
- name: Upload the renderer screenshot
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
diff --git a/docs/verification/browser-live.md b/docs/verification/browser-live.md
index 94c63baa7d..9f48b4b577 100644
--- a/docs/verification/browser-live.md
+++ b/docs/verification/browser-live.md
@@ -129,6 +129,14 @@ from the menu (new engine) still shows bands on purpose.
`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`).
+`scripts/testing/browser-input.e2e.test.ts` drives input on the pinned engine through the real server: a person takes
+control, clicks a button and types a word with the action requests the panel sends, and a bot's click and fill tools
+change the page; a refused action leaves a `browser input:` line in the server log. CI's `ui-smoke` job runs it.
+
+Input that does not reach a page is logged as `browser input: <who> <what> dropped reason=<code> engine=<engine>
+transport=<v1|v2|tools> session=<id>`, counted since the server started, and the counts go into a `@devs` report.
+The codes are listed in `server/browser/input-log.ts`. A line never carries page content, typed text or an address.
+
Focused automated coverage:
```sh
diff --git a/scripts/testing/browser-input.e2e.test.ts b/scripts/testing/browser-input.e2e.test.ts
new file mode 100644
index 0000000000..57020a9c25
--- /dev/null
+++ b/scripts/testing/browser-input.e2e.test.ts
@@ -0,0 +1,202 @@
+// A person's and a bot's input to a page, on the default engine, through the real server: the pinned agent-browser and
+// its Chrome, the live view's event stream and action requests as the app sends them, and the bot's tools as a model
+// calls them. The page reports what it saw to this test's own server. 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 { execFile } from "node:child_process";
+import { readFileSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { afterAll, beforeAll, describe, expect, it, onTestFailed } from "vitest";
+
+import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";
+import type { PreviewStreamInput } from "../../src/lib/browser-stream-client.ts";
+import { liveAction } from "../../src/lib/browser-live-action.ts";
+import { launchVerificationServer, runControlOmb, type VerificationServer } from "../control-omb.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 input 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;
+
+/** Fixed positions, so a person's click is aimed without reading the page. */
+const PAGE = `<!doctype html><title>Input fixture</title><body style="margin:0;font:16px sans-serif">
+<button id="press" style="position:absolute;left:40px;top:40px;width:200px;height:40px">Press</button>
+<input id="name" aria-label="Name" style="position:absolute;left:40px;top:100px;width:200px;height:30px">
+<script>
+const say = (what) => fetch("/seen?" + new URLSearchParams({ what }));
+document.getElementById("press").addEventListener("click", (event) => say("click:" + event.isTrusted));
+document.getElementById("name").addEventListener("input", (event) => say("input:" + event.target.value));
+say("load");
+</script>`;
+const PRESS = { x: 140, y: 60 };
+const NAME = { x: 140, y: 115 };
+
+type Body = Record<string, unknown>;
+type Answer = { status: number; body: any };
+
+/** The app's v1 action for an input: the body the panel posts. */
+function action(input: PreviewStreamInput): Body {
+ const body = liveAction(input);
+ if (!body || Array.isArray(body)) throw new Error(`no single v1 action for ${input.type}`);
+ return body;
+}
+
+const mouse = (kind: "move" | "down" | "up", at: { x: number; y: number }) =>
+ action({ type: "mouse", action: kind, ...at, button: kind === "move" ? "none" : "left", buttons: kind === "down" ? 1 : 0, clickCount: kind === "move" ? 0 : 1, modifiers: 0 });
+
+/** A letter's key-down and key-up as the panel's keyboard handler sends them. */
+function keys(letter: string): Body[] {
+ const key = { type: "key", key: letter, code: `Key${letter.toUpperCase()}`, keyCode: letter.toUpperCase().charCodeAt(0), modifiers: 0 } as const;
+ return [action({ ...key, action: "down", text: letter }), action({ ...key, action: "up" })];
+}
+
+describe("input to a page on the default browser engine", () => {
+ let pages: Server;
+ let base = "";
+ let fixture: VerificationServer;
+ let url = "";
+ let bot: { id: string; threadId: string };
+ let binary = "";
+ const seen: string[] = [];
+ const closers: Array<() => void> = [];
+
+ const api = async (method: string, path: string, body?: unknown): Promise<Answer> => {
+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ return { status: response.status, body: await response.json().catch(() => null) };
+ };
+ const serverLog = () => readFileSync(fixture.info.logPath, "utf8");
+ /** A failure's own evidence: the end of the server's log, which goes with the fixture otherwise. */
+ const showServerLog = () => onTestFailed(() => {
+ let log = "(the server log could not be read)";
+ try { log = serverLog().split("\n").slice(-60).join("\n"); } catch {}
+ console.log(`server log, last lines:\n${log}`);
+ });
+ /** The server's lines about input that did not reach the page, without each browser's own session id. */
+ const dropLines = () => serverLog().split("\n").filter((line) => line.startsWith("browser input:")).map((line) => line.replace(/ session=\S+/, ""));
+
+ beforeAll(async () => {
+ if (!enabled) return;
+ const browser = await ensureUiBrowser(process.env, () => {}, UI_TOOLS_DIR);
+ binary = browser.binary;
+ pages = createServer((req, res) => {
+ const at = new URL(req.url ?? "/", "http://fixture.invalid");
+ if (at.pathname === "/seen") { seen.push(at.searchParams.get("what") ?? ""); res.writeHead(204); res.end(); return; }
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
+ res.end(PAGE);
+ });
+ await new Promise<void>((resolve) => pages.listen(0, "127.0.0.1", resolve));
+ base = `http://127.0.0.1:${(pages.address() as { port: number }).port}`;
+ fixture = await launchVerificationServer({}, undefined, undefined, { binaryPath: browser.binary, executablePath: browser.chrome ?? "" }, undefined, { scripted: true });
+ url = fixture.info.url;
+ // A self-hosted server's bots reach this machine's own pages only where an admin allows it.
+ expect((await api("PATCH", "/api/config", { features: { browser: true }, browserEngine: { egress: { allow: ["127.0.0.1"] } } })).status).toBe(200);
+ bot = (await api("POST", "/api/bots", { name: "Visitor" })).body.bot;
+ expect((await api("PATCH", `/api/bots/${bot.id}`, { computer: "browser", browserProfile: "guest" })).status).toBe(200);
+ }, 600_000);
+
+ afterAll(async () => {
+ if (!enabled) return;
+ for (const close of closers) close();
+ // A failed test can leave the engine's daemon running: close --all is scoped to this fixture's HOME.
+ if (fixture) await promisify(execFile)(binary, ["close", "--all"], { env: { HOME: fixture.info.dataDir, USERPROFILE: fixture.info.dataDir, PATH: process.env.PATH }, timeout: 15_000 }).catch(() => undefined);
+ await fixture?.close();
+ await new Promise((resolve) => pages?.close(resolve));
+ }, 60_000);
+
+ /** One connection of the live view: its event stream read, each frame acknowledged. */
+ async function connectView() {
+ const abort = new AbortController();
+ closers.push(() => abort.abort());
+ const stream = await fetch(`${url}/api/bots/${bot.id}/browser/live`, { headers: { origin: url, accept: "text/event-stream" }, signal: abort.signal });
+ expect(stream.status).toBe(200);
+ const view = { viewerId: "", inputBatch: 1, frames: 0, ended: false, error: "", retryable: false };
+ const post = (body: Body) => api("POST", `/api/bots/${bot.id}/browser/action`, { ...body, viewerId: view.viewerId });
+ void (async () => {
+ const decoder = new TextDecoder();
+ let buffer = "";
+ for await (const chunk of stream.body as unknown as AsyncIterable<Uint8Array>) {
+ buffer += decoder.decode(chunk, { stream: true });
+ for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) {
+ const block = buffer.slice(0, end);
+ buffer = buffer.slice(end + 2);
+ const name = /^event: (.*)$/m.exec(block)?.[1];
+ let data: any = {};
+ try { data = JSON.parse(/^data: (.*)$/m.exec(block)?.[1] ?? "{}"); } catch { continue; }
+ if (name === "ready") { view.viewerId = data.viewerId; view.inputBatch = Number(data.inputBatch) || 1; }
+ if (name === "frame") { view.frames += 1; void post({ type: "ack", seq: data.seq }).catch(() => undefined); }
+ if (name === "error") { view.error = String(data.message); view.retryable = data.retryable === true; }
+ }
+ }
+ })().catch(() => undefined).finally(() => { view.ended = true; });
+ await expect.poll(() => view.viewerId !== "" || view.ended, { timeout: 90_000, interval: 100 }).toBe(true);
+ return { view, post, close: () => abort.abort() };
+ }
+
+ /** The live view as the panel opens it: like the panel, it connects again, up to five times, after an error the server
+ * calls retryable (an engine slow to start on a busy machine is restarted, and the view told to reconnect). */
+ async function openView() {
+ let opened = await connectView();
+ for (let attempt = 1; attempt < 5 && !opened.view.viewerId && opened.view.retryable; attempt++) {
+ opened.close();
+ opened = await connectView();
+ }
+ expect({ error: opened.view.error, ready: opened.view.viewerId !== "" }).toEqual({ error: "", ready: true });
+ await expect.poll(() => opened.view.frames, { timeout: 60_000, interval: 100 }).toBeGreaterThan(0);
+ return opened;
+ }
+
+ run("the bot's click and fill tools change the page, and a missing target is an error the server logs", async () => {
+ showServerLog();
+ const planPath = join(fixture.info.dataDir, "room-plan.json");
+ const evidence = () => { try { return readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)); } catch { return []; } };
+ seen.length = 0;
+ writeFileSync(planPath, JSON.stringify({ [bot.id]: { turns: [{ timeoutMs: 180_000, steps: [
+ { server: "browser", tool: "agent_browser_open", arguments: { url: `${base}/` } },
+ { server: "browser", tool: "agent_browser_click", arguments: { selector: "#press" } },
+ { server: "browser", tool: "agent_browser_fill", arguments: { selector: "#name", text: "hello" } },
+ { server: "browser", tool: "agent_browser_click", arguments: { selector: "#missing" }, expectError: true },
+ ], reply: "Done." }] } }));
+ await runControlOmb(["send", "--bot", bot.id, "--task", bot.threadId, "--text", "Use the page.", "--url", url]);
+ const results = () => evidence().flatMap((turn: any) => turn.evidence).filter((entry: any) => entry.step?.server === "browser").map((entry: any) => entry.response.result.isError === true);
+ await expect.poll(results, { timeout: 180_000, interval: 200 }).toEqual([false, false, false, true]);
+ await expect.poll(() => seen.includes("click:true") && seen.includes("input:hello"), { timeout: 15_000, interval: 100 }).toBe(true);
+ await expect.poll(dropLines, { timeout: 10_000, interval: 100 }).toContain("browser input: bot click dropped reason=target_not_found engine=agent-browser transport=tools");
+ expect(serverLog()).not.toContain("#missing");
+ }, 300_000);
+
+ run("a person takes control, clicks a button and types a word, and the page sees both", async () => {
+ showServerLog();
+ const { view, post, close } = await openView();
+ // A failure here must not leave the browser held for whatever runs next.
+ try {
+ expect(await post({ type: "take" })).toMatchObject({ status: 200, body: { ok: true } });
+ seen.length = 0;
+ expect(await post(action({ type: "navigate", url: `${base}/` }))).toEqual({ status: 200, body: { ok: true } });
+ await expect.poll(() => seen.includes("load"), { timeout: 30_000, interval: 100 }).toBe(true);
+
+ for (const kind of ["move", "down", "up"] as const) expect(await post(mouse(kind, PRESS))).toEqual({ status: 200, body: { ok: true } });
+ await expect.poll(() => seen.includes("click:true"), { timeout: 15_000, interval: 100 }).toBe(true);
+
+ for (const kind of ["move", "down", "up"] as const) expect(await post(mouse(kind, NAME))).toEqual({ status: 200, body: { ok: true } });
+ const typed = [..."word"].flatMap(keys);
+ // The panel sends what queued behind a request as one batch where the server said it takes batches.
+ if (view.inputBatch >= typed.length) expect(await post({ type: "input_batch", events: typed })).toEqual({ status: 200, body: { ok: true } });
+ else for (const body of typed) expect(await post(body)).toEqual({ status: 200, body: { ok: true } });
+ // Each report is its own request, so they may arrive out of order.
+ await expect.poll(() => seen.filter((entry) => entry.startsWith("input:")).sort(), { timeout: 15_000, interval: 100 }).toEqual(["input:w", "input:wo", "input:wor", "input:word"]);
+
+ expect(await post({ type: "release" })).toEqual({ status: 200, body: { ok: true } });
+ const refused = await post(mouse("down", PRESS));
+ expect(refused).toEqual({ status: 409, body: { error: "Browser control changed. Try again." } });
+ await expect.poll(dropLines, { timeout: 10_000, interval: 100 }).toContain("browser input: person input_mouse dropped reason=not_controlling engine=agent-browser transport=v1");
+ expect(seen.filter((entry) => entry.startsWith("click:"))).toEqual(["click:true"]);
+ } finally {
+ await post({ type: "release" }).catch(() => undefined);
+ close();
+ }
+ }, 300_000);
+});
diff --git a/server/browser-live.ts b/server/browser-live.ts
index 04d792456b..2578c0ae2c 100644
--- a/server/browser-live.ts
+++ b/server/browser-live.ts
@@ -11,6 +11,7 @@ import { DialogWatch, localDevToolsUrl } from "./browser-dialogs.ts";
import type { Cdp, CdpListeners } from "./browser-sites.ts";
import { relay } from "./browser-relay.ts";
import { HOLD_LIMITS, HoldClock, type HoldLimits } from "./browser/hold.ts";
+import type { PersonReason } from "./browser/input-log.ts";
import { BROWSER_HELD_ELSEWHERE } from "../shared/browser-held.ts";
const execute = promisify(execFile);
@@ -40,15 +41,15 @@ export const BROWSER_ASLEEP_ERROR = { type: "error", retryable: false, asleep: t
export const BROWSER_WAITING = { type: "waiting", reason: "busy" };
export class BrowserLiveError extends Error {
- readonly status: number;
- constructor(message: string, status = 400) { super(message); this.name = "BrowserLiveError"; this.status = status; }
+ readonly status: number; readonly reason: PersonReason | undefined;
+ constructor(message: string, status = 400, reason?: PersonReason) { super(message); this.name = "BrowserLiveError"; this.status = status; this.reason = reason; }
}
export class BrowserActionFailedError extends BrowserLiveError {
readonly settled = true;
constructor(args: readonly string[]) {
const opening = args[0] === "open" || (args[0] === "tab" && args[1] === "new" && args.length > 2);
- super(opening ? "This page could not be opened. Check the address and try again." : "The browser could not do that. Try again.", 422);
+ super(opening ? "This page could not be opened. Check the address and try again." : "The browser could not do that. Try again.", 422, "action_failed");
this.name = "BrowserActionFailedError";
}
}
@@ -56,7 +57,7 @@ export class BrowserActionFailedError extends BrowserLiveError {
/** Another command, usually the bot's own, holds the session; not a missing engine. */
export class BrowserBusyError extends BrowserLiveError {
constructor(message = "The browser is busy with another action and did not answer in time. Try again shortly.") {
- super(message, 503); this.name = "BrowserBusyError";
+ super(message, 503, "busy"); this.name = "BrowserBusyError";
}
}
@@ -68,7 +69,7 @@ class BrowserUnresponsiveError extends BrowserLiveError {
/** A person's input or command went unanswered, but the engine answered a read queued behind it, so it has ended. */
export class BrowserSlowActionError extends BrowserLiveError {
readonly settled = true;
- constructor() { super("The browser was slow to take that. Check the page before you repeat it.", 409); this.name = "BrowserSlowActionError"; }
+ constructor() { super("The browser was slow to take that. Check the page before you repeat it.", 409, "slow"); this.name = "BrowserSlowActionError"; }
}
/** The browser answered that it did not take an input, which therefore had no effect. */
@@ -77,7 +78,7 @@ const INPUT_REFUSED = "The page did not take some of your input. Check the page,
/** An input, or the release of a key or button, the browser never confirmed: its state in the page is unknown. */
class BrowserInputUnconfirmedError extends BrowserLiveError {
- constructor() { super("The browser could not confirm this input. Choose Restart browser… in the browser menu before continuing.", 503); this.name = "BrowserInputUnconfirmedError"; }
+ constructor() { super("The browser could not confirm this input. Choose Restart browser… in the browser menu before continuing.", 503, "unconfirmed"); this.name = "BrowserInputUnconfirmedError"; }
}
/** execFile's own timeout killed a command that had not exited (not a missing binary, a failure, an abort or an overflow). */
@@ -188,7 +189,7 @@ function withoutReplacedMoves(messages: ObjectValue[]): ObjectValue[] {
/** HTTP bodies can select a fixed action, never a CLI command, flag, port or CDP method. */
export function parseBrowserLiveAction(value: unknown): Action {
const body = object(value);
- const invalid = () => new BrowserLiveError("Invalid browser action.");
+ const invalid = () => new BrowserLiveError("Invalid browser action.", 400, "invalid_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 };
@@ -662,7 +663,7 @@ export class BrowserLive {
}
private async input(viewer: Viewer, message: ObjectValue): Promise<void> {
- if (!viewer.port) throw new BrowserLiveError("The browser stream is not connected.", 409);
+ if (!viewer.port) throw new BrowserLiveError("The browser stream is not connected.", 409, "stream_not_connected");
let command: ObjectValue;
const { type, eventType, ...fields } = message;
const key = String(fields.code || fields.key);
@@ -680,7 +681,7 @@ export class BrowserLive {
} else command = { action: "input_keyboard", type: eventType, key: fields.key,
...(fields.code === undefined ? {} : { code: fields.code }), ...(fields.text === undefined ? {} : { text: fields.text }) };
if (command.action === "input_keyboard" && eventType === "keyDown") {
- if (viewer.pressedKeys.size >= 64 && !viewer.pressedKeys.has(key)) throw new BrowserLiveError("Too many keys are held. Restart the browser before continuing.", 409);
+ if (viewer.pressedKeys.size >= 64 && !viewer.pressedKeys.has(key)) throw new BrowserLiveError("Too many keys are held. Restart the browser before continuing.", 409, "too_many_keys");
viewer.pressedKeys.set(key, String(fields.key));
}
if (type === "input_mouse") viewer.pointer = { x: fields.x as number, y: fields.y as number };
@@ -858,7 +859,7 @@ export class BrowserLive {
this.end(left.viewer.session, left.viewer.person);
return { ok: true };
}
- throw new BrowserLiveError("This browser view is no longer available. Reopen the browser panel.", 404);
+ throw new BrowserLiveError("This browser view is no longer available. Reopen the browser panel.", 404, "view_gone");
}
const action = parseBrowserLiveAction(body);
if (action.type === "restart") {
@@ -904,7 +905,7 @@ export class BrowserLive {
const before = this.viewers.get(this.drivers.get(viewer.session) ?? "");
if (before && before !== viewer) await this.releaseHeld(before);
await this.left.get(viewer.session)?.settled;
- if (!this.current(viewer)) { this.close(viewer, true, true); throw new BrowserLiveError("This browser view closed.", 409); }
+ if (!this.current(viewer)) { this.close(viewer, true, true); throw new BrowserLiveError("This browser view closed.", 409, "view_gone"); }
if (this.ownedBy(viewer)) {
this.drivers.set(viewer.session, viewer.id);
this.left.delete(viewer.session);
@@ -912,7 +913,7 @@ export class BrowserLive {
this.clock(viewer.session).watched(true);
}
return { ok: true, waited: waited === true };
- } catch { throw this.refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly."); }
+ } catch { throw this.refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.", "take_refused"); }
finally { this.control(viewer.session); }
}
if (!this.controlling(viewer)) throw this.refusal(viewer, "Browser control changed. Try again.");
@@ -923,12 +924,12 @@ export class BrowserLive {
if (!await watch.answer(action.accept, action.promptText)) throw new BrowserLiveError("The page did not take that answer. Try again.", 503);
return { ok: true };
}
- if (viewer.pendingActions >= 32) throw new BrowserLiveError("Too many browser actions are pending. Try again shortly.", 429);
+ if (viewer.pendingActions >= 32) throw new BrowserLiveError("Too many browser actions are pending. Try again shortly.", 429, "too_many_pending");
viewer.pendingActions += 1;
let refused = false;
try {
await this.runtime.withHumanAction(viewer.session, viewer.person, async () => {
- if (!this.current(viewer)) throw new BrowserLiveError("This browser view closed.", 409);
+ if (!this.current(viewer)) throw new BrowserLiveError("This browser view closed.", 409, "view_gone");
const take = async (message: ObjectValue) => {
try { await this.input(viewer, message); }
catch (error) { if (!(error instanceof BrowserInputRefusedError)) throw error; refused = true; }
@@ -942,7 +943,7 @@ export class BrowserLive {
return refused ? { ok: true, notice: INPUT_REFUSED } : { ok: true };
} catch (error) {
if (error instanceof BrowserInputUnconfirmedError && viewer.pendingActions === 1 && await this.restartUnresponsive(viewer)) {
- throw new BrowserLiveError(restartedNote(viewer.spec.env?.AGENT_BROWSER_RESTORE_SAVE !== "never"), 503);
+ throw new BrowserLiveError(restartedNote(viewer.spec.env?.AGENT_BROWSER_RESTORE_SAVE !== "never"), 503, "browser_restarted");
}
throw error instanceof BrowserLiveError ? error : this.refusal(viewer, "Browser control changed. Try again.");
}
@@ -953,10 +954,10 @@ export class BrowserLive {
}
}
- private refusal(viewer: Viewer, otherwise: string): BrowserLiveError {
+ private refusal(viewer: Viewer, otherwise: string, reason: PersonReason = "not_controlling"): BrowserLiveError {
const holder = this.runtime.heldBy(viewer.session);
- if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
- return new BrowserLiveError(this.runtime.interrupted(viewer.session) ? RESTART_NEEDED : otherwise, 409);
+ if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409, "held_elsewhere");
+ return this.runtime.interrupted(viewer.session) ? new BrowserLiveError(RESTART_NEEDED, 409, "restart_needed") : new BrowserLiveError(otherwise, 409, reason);
}
/** Done on a sign-in card, from any window or device: whoever holds this browser hands it back. */
diff --git a/server/browser-steps.test.ts b/server/browser-steps.test.ts
index 2aaad6cf61..21082bdff0 100644
--- a/server/browser-steps.test.ts
+++ b/server/browser-steps.test.ts
@@ -7,7 +7,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { addHeldSecretScrubber } from "../shared/redact.ts";
import { BrowserEvidence } from "./browser-evidence.ts";
import { RelayPorts, captureFrame } from "./browser-relay.ts";
-import { BrowserSteps, GEOMETRY_SCRIPT, RefIndex, SHELL_REFUSED, markerFor, stepLabel, type Geometry, type StepCall, type StepContext } from "./browser-steps.ts";
+import { BrowserSteps, GEOMETRY_SCRIPT, RefIndex, SHELL_REFUSED, TYPED_PAGE_SCRIPT, markerFor, stepLabel, type Geometry, type StepCall, type StepContext } from "./browser-steps.ts";
+import { createBrowserInputLog, type BrowserInputLog } from "./browser/input-log.ts";
import { FakeRelay } from "./testing/fake-relay.ts";
const cleanup: Array<() => Promise<void> | void> = [];
@@ -83,9 +84,26 @@ describe("what the geometry script reads from a page", () => {
window.document.body.innerHTML = html;
cleanup.push(() => window.happyDOM.close());
const read = () => JSON.parse(window.eval(GEOMETRY_SCRIPT) as string) as Geometry;
- return { document: window.document, read };
+ const typed = () => (JSON.parse(window.eval(TYPED_PAGE_SCRIPT) as string) as { typed: boolean | null }).typed;
+ return { document: window.document, read, typed };
}
+ it("says whether typed text sits in the focused field: not with nothing focused, an empty or read-only field, and unknown in another site's frame", () => {
+ const { document, typed } = page('<input id="name"><input id="fixed" readonly value="kept"><div id="plain">text</div><iframe id="card"></iframe>');
+ const focus = (id: string) => (document.getElementById(id) as unknown as { focus(): void }).focus();
+ expect(typed()).toBe(false);
+ focus("name");
+ expect(typed()).toBe(false);
+ (document.getElementById("name") as unknown as { value: string }).value = "ada";
+ expect(typed()).toBe(true);
+ focus("fixed");
+ expect(typed()).toBe(false);
+ const frame = document.getElementById("card")!;
+ Object.defineProperty(frame, "contentDocument", { get() { throw new Error("cross-origin"); } });
+ focus("card");
+ expect(typed()).toBeNull();
+ });
+
it("counts a secret field that shows what it holds, never a masked password or an empty field, in the page and its open shadow roots", () => {
const { document, read } = page('<label>Password <input id="shown" type="text"></label><input type="password" value="masked" autocomplete="current-password"><input name="email" value="[email protected]"><div id="host"></div>');
expect(read().unmasked).toBe(0);
@@ -131,13 +149,13 @@ describe("the refs a bot holds", () => {
});
/** `clock`: time moves only when the steps wait, or when a test moves it. */
-async function setup(options: { record?: boolean; stopped?: () => boolean; clock?: boolean; shell?: boolean } = {}) {
+async function setup(options: { record?: boolean; stopped?: () => boolean; clock?: boolean; shell?: boolean; inputLog?: BrowserInputLog } = {}) {
const daemon = await new FakeRelay("bot-steps").start();
const root = join(mkdtempSync(join(tmpdir(), "omb-steps-")), "evidence");
const evidence = new BrowserEvidence({ root, statfs: async () => ({ bavail: 1e9, bsize: 4096 }) });
cleanup.push(() => daemon.close(), () => rmSync(join(root, ".."), { recursive: true, force: true }));
const tick = { time: Date.now() };
- const steps = new BrowserSteps({ ports: new RelayPorts(), evidence, ...(options.clock ? { now: () => tick.time } : {}), sleep: async (ms) => { tick.time += ms; }, shellForWantOfChrome: () => options.shell ?? false });
+ const steps = new BrowserSteps({ ports: new RelayPorts(), evidence, ...(options.clock ? { now: () => tick.time } : {}), sleep: async (ms) => { tick.time += ms; }, shellForWantOfChrome: () => options.shell ?? false, ...(options.inputLog ? { inputLog: options.inputLog } : {}) });
const resize = vi.fn(async () => {});
const ctx: StepContext = { botId: "bot-1", botName: "Ava", threadId: "thread-1", generation: "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b", turnId: () => "turn-9", record: options.record ?? false };
const call = (tool: string, args: Record<string, unknown> = {}): StepCall => ({
@@ -155,6 +173,25 @@ async function setup(options: { record?: boolean; stopped?: () => boolean; clock
const failure = { requestId: "r1", url: "https://app.example.com/api/signup", method: "POST", status: 500, resourceType: "Fetch", postData: "password=fake-hunter2", timestamp: Date.now() };
describe("around every bot's browser call", () => {
+ it("logs a fill or type the engine called done that left no text in the focused field, for any bot, and nothing it typed", async () => {
+ const lines: string[] = [];
+ const { daemon, run } = await setup({ inputLog: createBrowserInputLog((line) => lines.push(line)) });
+ daemon.geometry.typed = true;
+ await run("fill", { selector: "@e4", text: "[email protected]" });
+ expect(lines).toEqual([]);
+ daemon.geometry.typed = false;
+ await run("click", { selector: "@e1" });
+ await run("fill", { selector: "@e4", text: "" });
+ await run("fill", { selector: "@e4", text: "[email protected]" }, undefined, { isError: true, content: [{ type: "text", text: "Element not found" }] });
+ expect(lines).toEqual([]);
+ await run("fill", { selector: "@e4", text: "[email protected]" });
+ expect(lines).toEqual([`browser input: bot fill dropped reason=typed_not_landed engine=agent-browser transport=tools session=${daemon.session}`]);
+ daemon.geometry.typed = null;
+ await run("type", { text: "[email protected]" });
+ expect(lines).toHaveLength(1);
+ expect(lines.join("\n")).not.toContain("ada");
+ });
+
it("tells every bot what its action made the page report, from the engine's lists, and records nothing", async () => {
const { daemon, run } = await setup();
daemon.console = [{ type: "error", text: "left over from before" }];
diff --git a/server/browser-steps.ts b/server/browser-steps.ts
index 53ece83468..d8e6ec2eab 100644
--- a/server/browser-steps.ts
+++ b/server/browser-steps.ts
@@ -13,6 +13,7 @@ import { RelayPorts, RelayTimeout, relay, relayPorts, relayTarget, type RelayTar
import { attachesToChrome, type BrowserSpawnSpec } from "./browser-runtime.ts";
import { sanitizeUrl, scrubBrowserResult } from "./browser-tool-shape.ts";
import { browserEgress } from "./browser/egress/registry.ts";
+import { browserInputLog, type BrowserInputLog } from "./browser/input-log.ts";
import { chromeLauncher } from "./browser/chrome/launcher.ts";
export interface StepContext {
@@ -147,6 +148,38 @@ export const GEOMETRY_SCRIPT = `(() => {
const PAGE_SCRIPT = "JSON.stringify({ url: location.href, loadedAt: performance.timeOrigin })";
+/** PAGE_SCRIPT with `typed`: whether the focused element is an editable field holding text; null inside a frame of another site. */
+export const TYPED_PAGE_SCRIPT = `(() => {
+ let a = document.activeElement;
+ let typed = false;
+ for (let depth = 0; a && depth < 20; depth++) {
+ if (a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; continue; }
+ const t = String(a.tagName || "").toLowerCase();
+ if (t !== "iframe" && t !== "frame") break;
+ let doc = null;
+ try { doc = a.contentDocument; } catch {}
+ if (!doc) { a = null; typed = null; break; }
+ a = doc.activeElement;
+ }
+ if (a) {
+ const t = String(a.tagName || "").toLowerCase();
+ const editable = a.isContentEditable || ((t === "input" || t === "textarea") && !a.readOnly && !a.disabled);
+ typed = Boolean(editable && (typeof a.value === "string" ? a.value.length : (a.innerText || "").length) > 0);
+ }
+ return JSON.stringify({ url: location.href, loadedAt: performance.timeOrigin, typed });
+})()`;
+
+/** False when a fill or type the engine called done left no text in the focused field; null when that cannot be told. */
+function typedLanded(geometry: Geometry | null, raw: unknown): boolean | null {
+ if (geometry) return geometry.focus?.frame === "cross" ? null : Boolean(geometry.focus?.editable && geometry.focus.valueLength > 0);
+ let parsed: unknown = raw;
+ for (let depth = 0; depth < 2 && typeof parsed === "string"; depth++) {
+ try { parsed = JSON.parse(parsed); } catch { return null; }
+ }
+ const typed = record(parsed)?.typed;
+ return typeof typed === "boolean" ? typed : null;
+}
+
const FRAME_SCRIPT = "new Promise((r) => { const t = setTimeout(() => r(0), 250); requestAnimationFrame(() => requestAnimationFrame(() => { clearTimeout(t); r(1); })); })";
function record(value: unknown): Record<string, unknown> | null {
@@ -319,9 +352,11 @@ export class BrowserSteps {
private now: () => number;
private sleep: (ms: number) => Promise<void>;
private shellForWantOfChrome: () => boolean;
+ private inputLog: BrowserInputLog;
- constructor(options: { ports: RelayPorts; evidence: BrowserEvidence | null; health?: PageHealthReader; now?: () => number; sleep?: (ms: number) => Promise<void>; shellForWantOfChrome?: () => boolean }) {
+ constructor(options: { ports: RelayPorts; evidence: BrowserEvidence | null; health?: PageHealthReader; now?: () => number; sleep?: (ms: number) => Promise<void>; shellForWantOfChrome?: () => boolean; inputLog?: BrowserInputLog }) {
this.ports = options.ports;
+ this.inputLog = options.inputLog ?? browserInputLog;
this.shellForWantOfChrome = options.shellForWantOfChrome ?? (() => chromeLauncher.runsShellForWantOfChrome());
this.evidence = options.evidence;
this.health = options.health ?? new PageHealthReader();
@@ -452,7 +487,12 @@ export class BrowserSteps {
geometry = parseGeometry(answer?.data?.result);
failure = answer?.error;
}
- const page = geometry ?? parseGeometry((await read({ action: "evaluate", script: PAGE_SCRIPT }))?.data?.result);
+ const typing = ok && (tool === "agent_browser_fill" || tool === "agent_browser_type") && typeof call.args.text === "string" && call.args.text !== "";
+ const raw = geometry ? null : (await read({ action: "evaluate", script: typing ? TYPED_PAGE_SCRIPT : PAGE_SCRIPT }))?.data?.result;
+ const page = geometry ?? parseGeometry(raw);
+ if (typing && (geometry || raw !== undefined) && typedLanded(geometry, raw) === false) {
+ this.inputLog.record({ who: "bot", reason: "typed_not_landed", what: tool, engine: "agent-browser", transport: "tools", session: call.session });
+ }
this.health.setPage(call.session, page?.url ?? null, page?.loadedAt ?? null);
const delta = await this.health.read(call.session, read, call.ctx?.threadId ?? null, state.noDaemon);
if (this.ports.takeStarted(call.session)) await this.started(call, steps, true, out);
diff --git a/server/browser/engines.test.ts b/server/browser/engines.test.ts
index 68e7d85c07..1c07a8adfc 100644
--- a/server/browser/engines.test.ts
+++ b/server/browser/engines.test.ts
@@ -12,6 +12,7 @@ import { BrowserEgress, OwnListeners } from "./egress/registry.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { ProcessRegistry } from "./chrome/processes.ts";
import { browserRoot } from "./chrome/profile.ts";
+import { createBrowserInputLog } from "./input-log.ts";
import { CHROME_ENGINE, ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter, type RuntimeRouterOptions } from "./engines.ts";
const AGENT_BROWSER = { command: "/opt/agent-browser", args: ["--session", "s"], env: { AGENT_BROWSER_SESSION: "s" } };
@@ -68,6 +69,29 @@ describe("which engine runs a session", () => {
});
describe("the runtime router", () => {
+ it("logs a page action that failed on either engine by a reason code, and nothing for one that worked or for a read", async () => {
+ const lines: string[] = [];
+ const { old, chrome, runtime } = engines({ inputLog: createBrowserInputLog((line) => lines.push(line)), refusal: (_session, _spec, params) => (params as { name?: string }).name === "agent_browser_press" ? "Browser tools are paused while a person controls this browser." : null });
+ const failure = (text: string) => ({ isError: true, content: [{ type: "text", text }] });
+ old.agentRpc.mockResolvedValueOnce(failure("Element not found: #pay-now. Verify the selector.") as never);
+ await runtime.agentRpc("omb-a", AGENT_BROWSER, "tools/call", { name: "agent_browser_click", arguments: { selector: "#pay-now" } });
+ chrome.service.agentRpc.mockResolvedValueOnce(failure("No element matches #card-number.") as never);
+ await runtime.agentRpc("omb-b", CHROME, "tools/call", { name: "agent_browser_fill", arguments: { selector: "#card-number", text: "4111" } });
+ old.agentRpc.mockRejectedValueOnce(new Error("socket hang up"));
+ await expect(runtime.agentRpc("omb-a", AGENT_BROWSER, "tools/call", { name: "agent_browser_type", arguments: { text: "typed words" } })).rejects.toThrow("socket hang up");
+ await runtime.agentRpc("omb-a", AGENT_BROWSER, "tools/call", { name: "agent_browser_press", arguments: { key: "Enter" } });
+ old.agentRpc.mockResolvedValueOnce(failure("Element not found: #pay-now.") as never);
+ await runtime.agentRpc("omb-a", AGENT_BROWSER, "tools/call", { name: "agent_browser_get_text", arguments: { selector: "#pay-now" } });
+ await runtime.agentRpc("omb-a", AGENT_BROWSER, "tools/call", { name: "agent_browser_click", arguments: { selector: "#ok" } });
+ expect(lines).toEqual([
+ "browser input: bot click dropped reason=target_not_found engine=agent-browser transport=tools session=omb-a",
+ "browser input: bot fill dropped reason=target_not_found engine=chrome transport=tools session=omb-b",
+ "browser input: bot type dropped reason=threw engine=agent-browser transport=tools session=omb-a",
+ "browser input: bot press dropped reason=person_holds_control engine=agent-browser transport=tools session=omb-a",
+ ]);
+ expect(lines.join("\n")).not.toMatch(/pay-now|card-number|4111|typed words/);
+ });
+
it("sends a new-engine session's calls to the browser service and every other to agent-browser", async () => {
const { old, chrome, runtime } = engines();
await expect(runtime.agentRpc("s", CHROME, "tools/call", { name: "agent_browser_open" })).resolves.toBe("chrome");
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index dcd89f1640..4c90ce99d1 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -16,6 +16,7 @@ import { ProcessRegistry, sweep } from "./chrome/processes.ts";
import { browserRoot } from "./chrome/profile.ts";
import { browserLanguage, browserTimeZone, languageList } from "./chrome/wrapper.ts";
import { displayScreen } from "./display.ts";
+import { botReason, browserInputLog, pageAction, type BotReason, type BrowserInputLog } from "./input-log.ts";
import type { Download } from "./cdp/downloads.ts";
import { BrowserService, type BrowserTarget } from "./service.ts";
import { LiveV1 } from "./viewers/live-v1.ts";
@@ -197,8 +198,15 @@ export interface RuntimeRouterOptions {
annotate?(spec: BrowserSpawnSpec, result: unknown): unknown;
/** The annotated answer, last, for what only the session's host knows about it. */
afterCall?(session: string, spec: BrowserSpawnSpec, result: unknown): unknown;
+ /** Where a page action that failed is counted; the server's own log when unset. */
+ inputLog?: BrowserInputLog;
}
+const resultText = (result: unknown): string => {
+ const first = (result as { content?: Array<{ text?: unknown }> } | null)?.content?.[0]?.text;
+ return typeof first === "string" ? first : "";
+};
+
/** afterClaim's refusal, thrown out of the engine's dispatch and answered as the call's result. */
class ClaimRefused extends Error {}
@@ -211,8 +219,10 @@ export class RuntimeRouter {
readonly #afterClaim: RuntimeRouterOptions["afterClaim"];
readonly #annotate: RuntimeRouterOptions["annotate"];
readonly #afterCall: RuntimeRouterOptions["afterCall"];
+ readonly #log: BrowserInputLog;
constructor(old: BrowserRuntime, chrome: ChromeEngine, options: RuntimeRouterOptions = {}) {
+ this.#log = options.inputLog ?? browserInputLog;
this.#old = old;
this.#chrome = chrome;
this.#refusal = options.refusal;
@@ -223,11 +233,19 @@ export class RuntimeRouter {
}
async agentRpc(session: string, spec: BrowserSpawnSpec, method: "tools/list" | "tools/call", params: unknown, beforeDispatch?: () => void, ctx?: StepContext): Promise<unknown> {
- const refusal = method === "tools/call" ? this.#refusal?.(session, spec, params) : null;
- if (refusal) return { isError: true, content: [{ type: "text", text: refusal }] };
const target = chromeTarget(session, spec);
+ const action = method === "tools/call" ? pageAction((params as { name?: unknown } | null)?.name) : null;
+ const failed = (reason: BotReason) => {
+ if (action) this.#log.record({ who: "bot", reason, what: action, engine: target ? "chrome" : "agent-browser", transport: "tools", session });
+ };
+ const refuse = (text: string, reason: BotReason = botReason(text)) => {
+ failed(reason);
+ return { isError: true, content: [{ type: "text", text }] };
+ };
+ const refusal = method === "tools/call" ? this.#refusal?.(session, spec, params) : null;
+ if (refusal) return refuse(refusal);
const full = method === "tools/call" && target ? await this.#room?.(session, spec, params) : null;
- if (full) return { isError: true, content: [{ type: "text", text: full }] };
+ if (full) return refuse(full, "no_room");
const afterClaim = method === "tools/call" ? this.#afterClaim : undefined;
const dispatch = afterClaim ? () => {
beforeDispatch?.();
@@ -238,10 +256,13 @@ export class RuntimeRouter {
try {
result = await (target ? this.#chrome.service.agentRpc(target, method, params, dispatch) : this.#old.agentRpc(session, spec, method, params, dispatch, ctx));
} catch (error) {
- if (error instanceof ClaimRefused) return { isError: true, content: [{ type: "text", text: error.message }] };
+ if (error instanceof ClaimRefused) return refuse(error.message);
+ const reason = botReason(error instanceof Error ? error.message : "");
+ failed(reason === "engine_error" ? "threw" : reason);
throw error;
}
if (method !== "tools/call") return result;
+ if ((result as { isError?: unknown } | null)?.isError === true) failed(botReason(resultText(result)));
const annotated = this.#annotate ? this.#annotate(spec, result) : result;
return this.#afterCall ? this.#afterCall(session, spec, annotated) : annotated;
}
diff --git a/server/browser/input-log.test.ts b/server/browser/input-log.test.ts
new file mode 100644
index 0000000000..53857c1b29
--- /dev/null
+++ b/server/browser/input-log.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+
+import { buildDevsReport } from "../devs-report.ts";
+import { actionKind, botReason, createBrowserInputLog, pageAction } from "./input-log.ts";
+
+describe("the browser input log", () => {
+ it("prints one line a drop with its reason, engine, transport and session, and counts every one", () => {
+ const lines: string[] = [];
+ let now = Date.UTC(2026, 0, 1);
+ const log = createBrowserInputLog((line) => lines.push(line), () => now);
+ log.record({ who: "person", reason: "not_controlling", what: "input_mouse", engine: "agent-browser", transport: "v1", session: "omb-a" });
+ log.record({ who: "bot", reason: "target_not_found", what: "agent_browser_click", engine: "agent-browser", transport: "tools", session: "omb-a" });
+ expect(lines).toEqual([
+ "browser input: person input_mouse dropped reason=not_controlling engine=agent-browser transport=v1 session=omb-a",
+ "browser input: bot click dropped reason=target_not_found engine=agent-browser transport=tools session=omb-a",
+ ]);
+ expect(log.lines()).toEqual([
+ "person not_controlling input_mouse agent-browser v1: 1; last 2026-01-01T00:00:00.000Z",
+ "bot target_not_found click agent-browser tools: 1; last 2026-01-01T00:00:00.000Z",
+ ]);
+ });
+
+ it("holds a burst of one refusal for one browser to a line, then one more saying how many followed", () => {
+ const lines: string[] = [];
+ let now = 0;
+ const log = createBrowserInputLog((line) => lines.push(line), () => now);
+ const drop = (session = "omb-a") => log.record({ who: "person", reason: "not_controlling", what: "input_mouse", engine: "agent-browser", transport: "v1", session });
+ for (let i = 0; i < 40; i++) drop();
+ drop("omb-b");
+ expect(lines).toHaveLength(2);
+ now = 5_000;
+ drop();
+ expect(lines.at(-1)).toBe("browser input: person input_mouse dropped reason=not_controlling engine=agent-browser transport=v1 session=omb-a times=40");
+ expect(log.lines()[0]).toMatch(/^person not_controlling input_mouse agent-browser v1: 42; /);
+ });
+
+ it("never keeps an action kind, a tool or a session it does not know as given", () => {
+ const lines: string[] = [];
+ const log = createBrowserInputLog((line) => lines.push(line), () => 0);
+ log.record({ who: "person", reason: "other", what: "https://example.com/?q=secret", engine: "chrome", transport: "v2", session: "a session\nwith a line" });
+ log.record({ who: "bot", reason: "engine_error", what: "agent_browser_eval", engine: "chrome", transport: "tools", session: "s" });
+ expect(lines).toEqual([
+ "browser input: person other dropped reason=other engine=chrome transport=v2 session=unknown",
+ "browser input: bot other dropped reason=engine_error engine=chrome transport=tools session=s",
+ ]);
+ expect(actionKind("input_batch")).toBe("input_batch");
+ expect(pageAction("agent_browser_fill")).toBe("fill");
+ expect(pageAction("agent_browser_snapshot")).toBeNull();
+ });
+
+ it("names a bot's failure by a fixed code, whatever the engine wrote", () => {
+ expect(botReason("Element not found: #pay-now. Verify the selector, role, or name is correct and the element exists in the DOM.")).toBe("target_not_found");
+ expect(botReason("Unknown ref: e99")).toBe("target_not_found");
+ expect(botReason("No element matches #inner.")).toBe("target_not_found");
+ expect(botReason("Could not locate element with role=button name=Go")).toBe("target_not_found");
+ expect(botReason("Element '#covered' is covered by <div#cover> at its click point, so the input would land on that element instead.")).toBe("target_not_actionable");
+ expect(botReason("Browser tools are paused while a person controls this browser.")).toBe("person_holds_control");
+ expect(botReason("The browser engine is stuck. Press Restart.")).toBe("browser_stuck");
+ expect(botReason("Something nobody expected")).toBe("engine_error");
+ });
+
+ it("reaches the bug report's diagnostics, and only when there is something to say", () => {
+ const input = {
+ installId: "install", appVersion: "0.0.0", platform: "linux", os: "linux", runsOn: "My Cloud", node: "v0", uptimeSeconds: 60, now: 0,
+ threadId: "thread", messageId: "message", where: "a chat", message: "@devs the browser takes no clicks", bots: [], problems: [], log: [], noSummary: "none",
+ } as unknown as Parameters<typeof buildDevsReport>[0];
+ expect(buildDevsReport(input, []).diagnostics).not.toContain("Browser input");
+ const log = createBrowserInputLog(() => {}, () => Date.UTC(2026, 10, 21));
+ log.record({ who: "app", reason: "queue_halted", what: "input", engine: "agent-browser", transport: "v1", session: "omb-a", count: 7 });
+ expect(buildDevsReport({ ...input, browserInput: log.lines() }, []).diagnostics)
+ .toContain("## Browser input that did not reach the page since the server started\napp queue_halted input agent-browser v1: 7; last 2026-11-21T00:00:00.000Z");
+ });
+});
diff --git a/server/browser/input-log.ts b/server/browser/input-log.ts
new file mode 100644
index 0000000000..27b591b95f
--- /dev/null
+++ b/server/browser/input-log.ts
@@ -0,0 +1,119 @@
+/**
+ * Why a person's input to a bot's browser, or a bot's own page action, did not reach the page: one log line each and a
+ * count since the server started, for a bug report. Security: a line carries a reason code, the tool or action kind, the
+ * engine, the transport and the browser session's id; never page content, typed text, a selector or an address.
+ */
+export type InputEngine = "agent-browser" | "chrome";
+export type InputTransport = "v1" | "v2" | "tools";
+
+/** Refusals the server answers a person's action with. */
+export const PERSON_REASONS = [
+ "session_changed", "view_gone", "invalid_action", "held_elsewhere", "restart_needed", "not_controlling", "take_refused",
+ "too_many_pending", "stream_not_connected", "too_many_keys", "unconfirmed", "browser_restarted", "slow", "page_refused",
+ "action_failed", "busy", "not_handled", "other",
+] as const;
+export type PersonReason = typeof PERSON_REASONS[number];
+
+/** Input the app dropped before sending it, as its view reports them. */
+export const CLIENT_REASONS = ["stale_after_wait", "queue_full", "queue_halted", "send_failed", "take_failed", "not_connected", "held_elsewhere"] as const;
+export type ClientReason = typeof CLIENT_REASONS[number];
+
+export const BOT_REASONS = [
+ "person_holds_control", "browser_stuck", "call_lost", "browser_closing", "browser_busy", "no_room", "target_not_found",
+ "target_not_actionable", "timed_out", "typed_not_landed", "engine_error", "threw",
+] as const;
+export type BotReason = typeof BOT_REASONS[number];
+
+/** The page actions a bot's failure is logged for. */
+const PAGE_ACTIONS = new Set(["click", "dblclick", "fill", "type", "press", "check", "uncheck", "select", "hover", "upload"]);
+const ACTION_KINDS = new Set(["mouse", "wheel", "key", "text", "take", "release", "input_mouse", "input_keyboard", "input_batch", "dialog", "navigate", "back", "forward", "reload", "tab-new", "tab-select", "tab-close", "restart"]);
+const QUIET_MS = 5_000;
+const MAX_SESSIONS = 200;
+const SESSION = /^[\w.:-]{1,128}$/;
+
+export interface InputEvent {
+ who: "person" | "app" | "bot";
+ reason: PersonReason | ClientReason | BotReason;
+ /** A person's action kind or a bot's tool, from a fixed list; anything else is "other". */
+ what: string;
+ engine: InputEngine;
+ transport: InputTransport;
+ session: string;
+ count?: number;
+}
+
+/** A bot tool's name without the engine's prefix when it is a page action, else null. */
+export function pageAction(tool: unknown): string | null {
+ const name = typeof tool === "string" ? tool.replace(/^agent_browser_/, "") : "";
+ return PAGE_ACTIONS.has(name) ? name : null;
+}
+
+export function actionKind(type: unknown): string {
+ return typeof type === "string" && ACTION_KINDS.has(type) ? type : "other";
+}
+
+const BOT_TEXT: Array<[RegExp, BotReason]> = [
+ [/paused while a person controls/i, "person_holds_control"],
+ [/browser engine is stuck|press restart/i, "browser_stuck"],
+ [/did not (?:answer|run)|may still be running|timed out; restart/i, "call_lost"],
+ [/browser is closing/i, "browser_closing"],
+ [/browsers are already open|no room/i, "no_room"],
+ [/busy with another|still busy|still running|another (?:thread|conversation)/i, "browser_busy"],
+ [/not found|no element matches|could not locate|unknown ref|no such element|does not exist|stale/i, "target_not_found"],
+ [/not visible|hidden|disabled|not (?:interactable|editable|enabled|clickable)|outside (?:of )?the viewport|covered|intercepts|obscured|cannot be (?:filled|typed|checked)|not an? (?:input|checkbox|select)/i, "target_not_actionable"],
+ [/timed? ?out|timeout/i, "timed_out"],
+];
+
+/** The reason code for a bot's failed call; the text itself is never kept. */
+export function botReason(text: string): BotReason {
+ return BOT_TEXT.find(([pattern]) => pattern.test(text))?.[1] ?? "engine_error";
+}
+
+/** A person's lost input is a warning, which a bug report's recent log keeps; a bot's failed action is routine and is not. */
+const printByWho = (line: string, who: InputEvent["who"]) => (who === "bot" ? console.info(line) : console.warn(line));
+
+export function createBrowserInputLog(print: (line: string, who: InputEvent["who"]) => void = printByWho, now: () => number = Date.now) {
+ const counts = new Map<string, { count: number; lastAt: number }>();
+ const quiet = new Map<string, { until: number; held: number }>();
+
+ function record(event: InputEvent): void {
+ const what = event.who === "bot" ? pageAction(event.what) ?? "other" : event.who === "person" ? actionKind(event.what) : "input";
+ const session = SESSION.test(event.session) ? event.session : "unknown";
+ const times = Math.max(1, Math.min(Math.round(event.count ?? 1) || 1, 10_000));
+ const key = `${event.who} ${event.reason} ${what} ${event.engine} ${event.transport}`;
+ const row = counts.get(key) ?? { count: 0, lastAt: 0 };
+ row.count += times;
+ row.lastAt = now();
+ counts.set(key, row);
+ // A burst of the same refusal for one browser is one line, then one more carrying how many followed.
+ const burst = `${key} ${session}`;
+ const state = quiet.get(burst);
+ if (state && now() < state.until) { state.held += times; return; }
+ if (quiet.size >= MAX_SESSIONS) quiet.delete(quiet.keys().next().value!);
+ quiet.delete(burst);
+ quiet.set(burst, { until: now() + QUIET_MS, held: 0 });
+ const repeats = times + (state?.held ?? 0);
+ print(`browser input: ${event.who} ${what} dropped reason=${event.reason} engine=${event.engine} transport=${event.transport} session=${session}${repeats > 1 ? ` times=${repeats}` : ""}`, event.who);
+ }
+
+ return {
+ record,
+ /** What an app's view says it dropped before sending: only known reasons and whole counts are taken. */
+ fromApp(value: unknown, context: Pick<InputEvent, "engine" | "transport" | "session">): void {
+ if (!value || typeof value !== "object") return;
+ for (const reason of CLIENT_REASONS) {
+ const count = (value as Record<string, unknown>)[reason];
+ if (typeof count === "number" && Number.isSafeInteger(count) && count > 0) record({ who: "app", reason, what: "input", count, ...context });
+ }
+ },
+ /** One line per kind of drop, most recent first. */
+ lines(): string[] {
+ return [...counts].sort(([, a], [, b]) => b.lastAt - a.lastAt).map(([key, row]) => `${key}: ${row.count}; last ${new Date(row.lastAt).toISOString()}`);
+ },
+ clear: () => { counts.clear(); quiet.clear(); },
+ };
+}
+
+export type BrowserInputLog = ReturnType<typeof createBrowserInputLog>;
+
+export const browserInputLog = createBrowserInputLog();
diff --git a/server/browser/viewers/live-v1.test.ts b/server/browser/viewers/live-v1.test.ts
index 8d01328d65..6269637820 100644
--- a/server/browser/viewers/live-v1.test.ts
+++ b/server/browser/viewers/live-v1.test.ts
@@ -159,6 +159,16 @@ describe("the v1 live view on the new browser", () => {
expect(keys).toContainEqual(expect.objectContaining({ type: "keyUp", key: "Enter" }));
});
+ it("applies every input of a batch, in order", async () => {
+ const { open, backend } = setup();
+ const { action } = await open();
+ await action({ type: "take" });
+ const key = (eventType: string, letter: string) => ({ type: "input_keyboard", eventType, key: letter, code: `Key${letter.toUpperCase()}`, windowsVirtualKeyCode: letter.toUpperCase().charCodeAt(0), modifiers: 0, ...(eventType === "keyDown" ? { text: letter } : {}) });
+ await expect(action({ type: "input_batch", events: [key("keyDown", "o"), key("keyUp", "o"), key("keyDown", "k"), key("keyUp", "k")] })).resolves.toEqual({ ok: true });
+ const keys = backend.chrome.sent.filter((sent) => sent.method === "Input.dispatchKeyEvent").map((sent) => `${sent.params.type}:${sent.params.key}`);
+ expect(keys).toEqual(["keyDown:o", "keyUp:o", "keyDown:k", "keyUp:k"]);
+ });
+
it("tells a phone its browser closed unused and ends its view for good, so it does not reconnect and start it again", async () => {
const { open, service, backend } = setup();
const { sse } = await open();
diff --git a/server/browser/viewers/live-v1.ts b/server/browser/viewers/live-v1.ts
index 17180a6f14..6715fd9d30 100644
--- a/server/browser/viewers/live-v1.ts
+++ b/server/browser/viewers/live-v1.ts
@@ -256,10 +256,10 @@ export class LiveV1 {
}
}
- #refusal(viewer: V1Viewer, otherwise: string): BrowserLiveError {
+ #refusal(viewer: V1Viewer, otherwise: string, reason: "not_controlling" | "take_refused" = "not_controlling"): BrowserLiveError {
const holder = this.#service.heldBy(viewer.session);
- if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409);
- return new BrowserLiveError(this.#service.interrupted(viewer.session) ? RESTART_NEEDED : otherwise, 409);
+ if (holder && holder !== viewer.person) return new BrowserLiveError(BROWSER_HELD_ELSEWHERE, 409, "held_elsewhere");
+ return this.#service.interrupted(viewer.session) ? new BrowserLiveError(RESTART_NEEDED, 409, "restart_needed") : new BrowserLiveError(otherwise, 409, reason);
}
async action({ viewerId, botId, owner, body }: { viewerId: string; botId: string; owner: string; body: unknown }): Promise<unknown> {
@@ -302,12 +302,12 @@ export class LiveV1 {
}
if (action.type === "take") {
const before = this.#service.heldBy(viewer.session);
- if (before !== null && before !== viewer.person) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
+ if (before !== null && before !== viewer.person) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.", "take_refused");
const busy = this.#service.profiles().find((profile) => profile.session === viewer.session)?.control.agents ?? 0;
await core.input({ type: "takeControl" });
this.#controlAll(viewer.session);
- if (!core.controlState().controlling) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.");
- if (!this.#current(viewer)) { this.#close(viewer); throw new BrowserLiveError("This browser view closed.", 409); }
+ if (!core.controlState().controlling) throw this.#refusal(viewer, "Another browser view or bot action is using this browser. Try again shortly.", "take_refused");
+ if (!this.#current(viewer)) { this.#close(viewer); throw new BrowserLiveError("This browser view closed.", 409, "view_gone"); }
return { ok: true, waited: busy > 0 };
}
if (!core.controlState().controlling) throw this.#refusal(viewer, "Browser control changed. Try again.");
@@ -316,6 +316,7 @@ export class LiveV1 {
try {
if (action.type === "command") await core.input(commandMessage(action.args));
else if (action.type === "input") await core.input(inputMessage(action.message));
+ else if (action.type === "inputs") { for (const message of action.messages) await core.input(inputMessage(message)); }
if (!core.controlState().controlling) throw this.#refusal(viewer, "Browser control changed. Try again.");
core.pushTabs();
return { ok: true };
diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.ts
index 60e47a18ae..b166f0bc7a 100644
--- a/server/browser/viewers/stream-v2.ts
+++ b/server/browser/viewers/stream-v2.ts
@@ -12,6 +12,7 @@ import type { Socket } from "node:net";
import { WebSocketServer, type RawData, type WebSocket } from "ws";
import { hostSetupOf } from "../chrome/host-setup.ts";
+import { browserInputLog } from "../input-log.ts";
import type { BrowserService, BrowserTarget } from "../service.ts";
import { FRAME_CAP_LIMITS, type Viewer, type ViewerOptions, type ViewerOutput } from "./core.ts";
import { requestedSize } from "./viewport.ts";
@@ -177,6 +178,7 @@ class StreamSession {
}
if (!this.viewer) {
if (this.#early.length < EARLY_INPUT_LIMIT) this.#early.push(message);
+ else browserInputLog.record({ who: "person", reason: "too_many_pending", what: String((message as { type?: unknown } | null)?.type), engine: "chrome", transport: "v2", session: this.request.target.session });
return;
}
this.#input(message, service);
diff --git a/server/devs-report.ts b/server/devs-report.ts
index 72a7d4e12c..890d69eb9d 100644
--- a/server/devs-report.ts
+++ b/server/devs-report.ts
@@ -70,6 +70,8 @@ export interface DevsReportInput {
log: string[];
/** One line per cloud computer used since the server started: its opaque id and counts, nothing it ran. */
cloudComputers?: string[];
+ /** One line per kind of browser input that did not reach a page since the server started: reason codes and counts. */
+ browserInput?: string[];
contactEmail?: string;
}
@@ -156,6 +158,7 @@ function diagnose(input: DevsReportInput, redact: (text: string) => string): str
const problems = input.problems.slice(-DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars));
lines.push(...(problems.length ? problems : ["(none)"]));
if (input.cloudComputers?.length) lines.push("", "## Cloud computers since the server started", ...input.cloudComputers.slice(0, DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars)));
+ if (input.browserInput?.length) lines.push("", "## Browser input that did not reach the page since the server started", ...input.browserInput.slice(0, DEVS_REPORT_LIMITS.problems).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.problemChars)));
if (input.performance?.length) lines.push("", ...input.performance.slice(0, DEVS_REPORT_LIMITS.performanceLines).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.performanceChars)));
lines.push("", "## Server warnings and errors, newest last");
const log = input.log.slice(-DEVS_REPORT_LIMITS.logLines).map((line) => oneLine(redact(line), DEVS_REPORT_LIMITS.logLineChars));
diff --git a/server/host/devs-reports.ts b/server/host/devs-reports.ts
index 13c36bd08e..eba2a53159 100644
--- a/server/host/devs-reports.ts
+++ b/server/host/devs-reports.ts
@@ -33,6 +33,7 @@ import { personKey } from "../person-key.ts";
import type { RecentLog } from "../recent-log.ts";
import { PASS } from "../routes/table.ts";
import { serverLine, type LineLanguage } from "../server-lines.ts";
+import { browserInputLog } from "../browser/input-log.ts";
import { cloudComputerCounters } from "../cloud-computer-counters.ts";
import type { PublicSession } from "../sessions.ts";
import type { BotRecord, Message, Store, StoreChange } from "../store.ts";
@@ -355,7 +356,7 @@ export function createDevsReports(deps: DevsReportsDeps) {
threadId: entry.threadId, messageId: entry.messageId, ...(groupId ? { groupId } : {}), where, message: entry.text, words: entry.words,
bots: bots.map((bot) => reported(bot, entry.threadId)),
...("bot" in author ? { summary: { by: author.bot.name, text: author.summary } } : { noSummary: author.why }),
- problems: conversationProblems(store.activePath(entry.threadId)), log: deps.recentLog(), cloudComputers: cloudComputerCounters.lines(), contactEmail: contact,
+ problems: conversationProblems(store.activePath(entry.threadId)), log: deps.recentLog(), cloudComputers: cloudComputerCounters.lines(), browserInput: browserInputLog.lines(), contactEmail: contact,
...(deps.performance ? { performance: performanceLines(deps.performance, entry.threadId, bots.map((bot) => bot.id)) } : {}),
}, secrets());
return { payload, ...(contact ? { contact } : {}) };
diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.ts
index 91113864be..67d143909f 100644
--- a/server/routes/browser-viewers.test.ts
+++ b/server/routes/browser-viewers.test.ts
@@ -9,6 +9,8 @@ import { basename, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BrowserHostError } from "../browser/chrome/host-setup.ts";
+import { createBrowserInputLog, type BrowserInputLog } from "../browser/input-log.ts";
+import { BrowserLiveError } from "../browser-live.ts";
import type { Audience } from "../audience.ts";
import type { Download } from "../browser/cdp/downloads.ts";
import type { BrowserService } from "../browser/service.ts";
@@ -72,11 +74,13 @@ afterEach(async () => {
for (const folder of folders.splice(0)) await removeTempDir(folder);
});
-async function serve({ attach, current = () => true, download, audience = () => "team" }: {
+async function serve({ attach, current = () => true, download, audience = () => "team", action = async () => ({ ok: true }), inputLog }: {
attach?: (options: ViewerOptions, push: (output: ViewerOutput) => void) => Promise<Viewer>;
current?: () => boolean;
download?: (id: string) => Download | undefined;
audience?: (threadId: string | null) => Audience | null;
+ action?: (body: unknown) => Promise<unknown>;
+ inputLog?: BrowserInputLog;
} = {}): Promise<Fixture> {
const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], people: [], sizes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;
folders.push(fixture.dataDir);
@@ -103,7 +107,7 @@ async function serve({ attach, current = () => true, download, audience = () =>
fixture.isCurrent = options.isCurrent;
options.res.writeHead(204).end();
},
- action: async () => ({ ok: true }),
+ action: async ({ body }) => action(body),
stream: ({ session, spec: _spec, ...request }) => {
stream.open({ ...request, target: { session, key: "bot:pepper" } });
return true;
@@ -126,11 +130,16 @@ async function serve({ attach, current = () => true, download, audience = () =>
authorize: async () => null,
current: (_botId, _session, _auth, checked) => { fixture.checked.push(checked); return current(); },
restartRefusal: () => null,
+ ...(inputLog ? { inputLog } : {}),
};
const route = createBrowserViewerRoutes(deps);
const handle = async (req: IncomingMessage, res: ServerResponse) => {
const url = new URL(req.url ?? "/", "http://localhost");
- if (!await dispatchRoutes([route], { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: LOOPBACK, json, readBody })) json(res, 404, { error: "no route" });
+ try {
+ if (!await dispatchRoutes([route], { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: LOOPBACK, json, readBody })) json(res, 404, { error: "no route" });
+ } catch (error) {
+ json(res, (error as { status?: number }).status ?? 500, { error: error instanceof Error ? error.message : "failed" });
+ }
};
const server = createServer((req, res) => void handle(req, res));
upgrades.attach(server, handle);
@@ -321,6 +330,58 @@ describe("the v2 stream", () => {
});
describe("the v1 live view", () => {
+ const act = (fixture: Fixture, body: Record<string, unknown>) => fetch(`http://${fixture.origin}/api/bots/pepper/browser/action`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+
+ it("logs one line with a reason code for each action it refuses, and none for one it took", async () => {
+ const lines: string[] = [];
+ const inputLog = createBrowserInputLog((line) => lines.push(line));
+ let current = true;
+ const fixture = await serve({ inputLog, current: () => current, action: async (body) => {
+ const { type, text } = body as { type: string; text?: string };
+ if (type === "take") throw new BrowserLiveError("Another browser view or bot action is using this browser. Try again shortly.", 409, "take_refused");
+ if (type === "input_keyboard" && text === "secret typed text") throw new BrowserLiveError("Too many browser actions are pending. Try again shortly.", 429);
+ if (type === "input_mouse") return { ok: true, notice: "The page did not take some of your input." };
+ if (type === "ack") throw new BrowserLiveError("This browser view is no longer available. Reopen the browser panel.", 404, "view_gone");
+ return { ok: true };
+ } });
+ expect((await act(fixture, { type: "take", viewerId: "v1" })).status).toBe(409);
+ expect((await act(fixture, { type: "input_keyboard", eventType: "char", text: "secret typed text", viewerId: "v1" })).status).toBe(429);
+ expect((await act(fixture, { type: "input_mouse", eventType: "mousePressed", x: 1, y: 2, viewerId: "v1" })).status).toBe(200);
+ expect((await act(fixture, { type: "ack", seq: 3, viewerId: "v1" })).status).toBe(404);
+ expect((await act(fixture, { type: "navigate", url: "https://example.com/?token=abc", viewerId: "v1" })).status).toBe(200);
+ current = false;
+ expect((await act(fixture, { type: "navigate", url: "https://example.com/?token=abc", viewerId: "v1" })).status).toBe(409);
+ expect(lines).toEqual([
+ "browser input: person take dropped reason=take_refused engine=chrome transport=v1 session=bot-pepper",
+ "browser input: person input_keyboard dropped reason=too_many_pending engine=chrome transport=v1 session=bot-pepper",
+ "browser input: person input_mouse dropped reason=page_refused engine=chrome transport=v1 session=bot-pepper",
+ "browser input: person navigate dropped reason=session_changed engine=chrome transport=v1 session=bot-pepper",
+ ]);
+ expect(lines.join("\n")).not.toMatch(/secret|token|example/);
+ });
+
+ it("counts what the app's view says it dropped before sending, by known reason only, without reaching the browser", async () => {
+ const lines: string[] = [];
+ const inputLog = createBrowserInputLog((line) => lines.push(line));
+ const actions: unknown[] = [];
+ const fixture = await serve({ inputLog, action: async (body) => { actions.push(body); return { ok: true }; } });
+ const answer = await act(fixture, { type: "client_drops", counts: { stale_after_wait: 2, queue_halted: 1, "made up": 9, send_failed: "many", queue_full: -1 }, viewerId: "v1" });
+ expect(answer.status).toBe(200);
+ expect(actions).toEqual([]);
+ expect(lines).toEqual([
+ "browser input: app input dropped reason=stale_after_wait engine=chrome transport=v1 session=bot-pepper times=2",
+ "browser input: app input dropped reason=queue_halted engine=chrome transport=v1 session=bot-pepper",
+ ]);
+ });
+
+ it("says when the own-driver v1 view answered a page question's answer it does not apply", async () => {
+ const lines: string[] = [];
+ const fixture = await serve({ inputLog: createBrowserInputLog((line) => lines.push(line)) });
+ expect((await act(fixture, { type: "dialog", accept: true, viewerId: "v1" })).status).toBe(200);
+ expect((await act(fixture, { type: "input_batch", events: [], viewerId: "v1" })).status).toBe(200);
+ expect(lines).toEqual(["browser input: person dialog dropped reason=not_handled engine=chrome transport=v1 session=bot-pepper"]);
+ });
+
it("passes on the view a reconnecting panel had, and the person watching, whose hold every view of theirs shares", async () => {
const fixture = await serve();
expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/live?resume=old-viewer`)).status).toBe(204);
diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.ts
index 9521e866db..3324356e24 100644
--- a/server/routes/browser-viewers.ts
+++ b/server/routes/browser-viewers.ts
@@ -12,7 +12,8 @@ import { BROWSER_UPLOAD_MAX_BYTES as UPLOAD_MAX_BYTES } from "../../shared/uploa
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 { chromeTarget, type LiveRouter } from "../browser/engines.ts";
+import { browserInputLog, type BrowserInputLog, type PersonReason } from "../browser/input-log.ts";
import { requestedSize } from "../browser/viewers/viewport.ts";
import { messageFileDisposition } from "../message-file.ts";
import { isSameOrigin, type RequestAuth } from "../request-auth.ts";
@@ -47,8 +48,14 @@ export interface BrowserViewerRouteDeps {
/** Why a person may not restart this browser now, or null. */
restartRefusal(session: string): string | null;
dataDir: string;
+ /** Where a person's refused input is counted; the server's own log when unset. */
+ inputLog?: BrowserInputLog;
}
+/** What the app's view sends, beside its actions, to say which input it dropped before sending. */
+const APP_DROPS = "client_drops";
+const STATUS_REASONS: Record<number, PersonReason> = { 400: "invalid_action", 404: "view_gone", 429: "too_many_pending" };
+
const ownerOf = (auth: RequestAuth) => (auth.kind === "session" ? auth.session.id : "local-owner");
class UploadError extends Error {
@@ -136,11 +143,31 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHa
}
if (method === "POST" && live[2] === "action") {
const body = await readBody(req, 32_768);
- if (!isCurrent()) return json(res, 409, { error: "This browser session changed. Reopen the browser panel." });
+ const log = deps.inputLog ?? browserInputLog;
+ const seen = { engine: chromeTarget(browser.session, browser.spec) ? "chrome" : "agent-browser", transport: "v1", session: browser.session } as const;
+ const dropped = (reason: PersonReason) => { if (body?.type !== "ack" && body?.type !== "resize") log.record({ who: "person", reason, what: String(body?.type), ...seen }); };
+ if (body?.type === APP_DROPS) {
+ log.fromApp(body.counts, seen);
+ return json(res, 200, { ok: true });
+ }
+ if (!isCurrent()) {
+ dropped("session_changed");
+ return json(res, 409, { error: "This browser session changed. Reopen the browser panel." });
+ }
if (typeof body?.viewerId !== "string") return json(res, 400, { error: "A live browser connection is required." });
const refused = body.type === "restart" && deps.restartRefusal(browser.session);
if (refused) return json(res, 409, { error: refused });
- return json(res, 200, await deps.viewers.action({ viewerId: body.viewerId, botId: browser.botId, owner, body }));
+ let answer: unknown;
+ try { answer = await deps.viewers.action({ viewerId: body.viewerId, botId: browser.botId, owner, body }); }
+ catch (error) {
+ const known = error as { reason?: PersonReason; status?: number } | null;
+ dropped(known?.reason ?? STATUS_REASONS[known?.status ?? 0] ?? "other");
+ throw error;
+ }
+ if (typeof (answer as { notice?: unknown } | null)?.notice === "string") dropped("page_refused");
+ // Its v1 view shows no page question, so an answer to one is answered and not applied.
+ else if (seen.engine === "chrome" && body.type === "dialog") dropped("not_handled");
+ return json(res, 200, answer);
}
return json(res, 405, { error: "method not allowed" });
}
diff --git a/server/testing/fake-relay.ts b/server/testing/fake-relay.ts
index 9d2d5de5a3..3cf66770e8 100644
--- a/server/testing/fake-relay.ts
+++ b/server/testing/fake-relay.ts
@@ -9,6 +9,8 @@ export interface FakeGeometry {
url: string; title: string; vw: number; vh: number; dpr: number; sx: number; sy: number;
focus: null | { role: string; name: string; editable: boolean; valueLength: number; secret: boolean; rect: { x: number; y: number; w: number; h: number }; frame?: "same" | "cross" | null };
unmasked: number;
+ /** What the typed-text read answers: whether the focused field holds text. */
+ typed?: boolean | null;
}
export class FakeRelay {
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 4cc907fb55..a629168789 100644
--- a/src/components/BrowserPanel.tsx
+++ b/src/components/BrowserPanel.tsx
@@ -10,7 +10,7 @@ import { ExtensionsMenu, extensionsOf, type BrowserExtension } from "./browser/E
import { MoreMenu } from "./browser/MoreMenu";
import { PasskeyNotice } from "./browser/PasskeyNotice";
import { StreamSurface, type StreamSurfaceHandle, type SurfaceConnect } from "./browser/StreamSurface";
-import { createBrowserControl, streamTransport, type BrowserControl, type BrowserTakeStatus } from "@/lib/browser-control";
+import { createBrowserControl, startsInteraction, streamTransport, type BrowserControl, type BrowserTakeStatus } from "@/lib/browser-control";
import { resolveAddressBarInput } from "@/lib/browser-address";
import { closeBrowserPictureInPicture, openBrowserPictureInPicture, supportsBrowserPictureInPicture, useBrowserPictureInPicture } from "@/lib/browser-pip";
import { browserStreamAccess, createPreviewStreamClient, type PreviewStreamClient, type PreviewStreamControl, type PreviewStreamInput, type PreviewViewportSetting } from "@/lib/browser-stream-client";
@@ -122,7 +122,11 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
}, [bot.id, bot.browserProfile, scopedThread, stream]);
const interact = useCallback((input: PreviewStreamInput) => {
- if (controlRef.current?.controller === "another-viewer") { setError(BROWSER_HELD_ELSEWHERE); return; }
+ if (controlRef.current?.controller === "another-viewer") {
+ if (startsInteraction(input)) (clientRef.current as Partial<LiveStreamClient> | null)?.transport?.dropped?.("held_elsewhere");
+ setError(BROWSER_HELD_ELSEWHERE);
+ return;
+ }
browserControl.current?.interact(input);
}, []);
diff --git a/src/lib/browser-control.ts b/src/lib/browser-control.ts
index 260de7317c..aa89a4a7a5 100644
--- a/src/lib/browser-control.ts
+++ b/src/lib/browser-control.ts
@@ -1,3 +1,4 @@
+import type { InputDropReason } from "./browser-input-drops";
import type { PreviewStreamClient, PreviewStreamControl, PreviewStreamInput } from "./browser-stream-client";
import { t } from "./i18n";
@@ -15,6 +16,8 @@ export interface ControlTransport {
/** Resolves once this viewer holds the browser; `waited` when bot work was running then. */
take(): Promise<{ waited: boolean } | void>;
release(): Promise<void>;
+ /** Counts input this control dropped, where the transport reports drops. */
+ dropped?(reason: InputDropReason): void;
}
export const BROWSER_HAND_BACK_MS = 8_000;
@@ -28,7 +31,8 @@ const DISCRETE_KEYS = new Set(["Backspace", "Enter", "Tab", "Escape", "Delete",
const COMMANDS = new Set<PreviewStreamInput["type"]>(["navigate", "history", "reload", "tabSelect", "tabNew", "tabClose"]);
const ABSOLUTE_COMMANDS = new Set<PreviewStreamInput["type"]>(["navigate", "tabNew"]);
-function startsInteraction(input: PreviewStreamInput): boolean {
+/** Whether an input begins something a person means: a press, a typed key, text, a scroll or a toolbar action. */
+export function startsInteraction(input: PreviewStreamInput): boolean {
if (COMMANDS.has(input.type)) return true;
if (input.type === "mouse") return input.action === "down";
if (input.type === "key") return input.action === "down" && !MODIFIER_KEYS.has(input.key);
@@ -135,9 +139,14 @@ export function createBrowserControl(options: {
if (closed) return;
if (grant) {
state = "held";
- report(grant.reply?.waited === true && dropStale() ? "stale" : "");
+ const stale = grant.reply?.waited === true && dropStale();
+ if (stale) transport.dropped?.("stale_after_wait");
+ report(stale ? "stale" : "");
await flush();
- } else { report(""); state = "bot"; buffer = []; held.clear(); }
+ } else {
+ if (buffer.length) transport.dropped?.("take_failed");
+ report(""); state = "bot"; buffer = []; held.clear();
+ }
arm();
}).catch(() => {});
};
@@ -151,7 +160,7 @@ export function createBrowserControl(options: {
const waiting = state === "taking" || flushing;
if (state !== "held" && !waiting) {
if (!startsInteraction(input)) return;
- if (transport.stopped() && !COMMANDS.has(input.type)) { options.onHalted(); return; }
+ if (transport.stopped() && !COMMANDS.has(input.type)) { transport.dropped?.("queue_halted"); options.onHalted(); return; }
}
if (COMMANDS.has(input.type) && waiting && buffer.some((queued) => COMMANDS.has(queued.type))) return;
if (startsInteraction(input)) {
diff --git a/src/lib/browser-input-drops.test.ts b/src/lib/browser-input-drops.test.ts
new file mode 100644
index 0000000000..7c0c23ee3a
--- /dev/null
+++ b/src/lib/browser-input-drops.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createInputDropReport } from "./browser-input-drops";
+
+describe("the report of dropped browser input", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("sends the drops of a moment as one request of reason codes and counts", () => {
+ const sent: unknown[] = [];
+ const report = createInputDropReport(async (counts) => { sent.push(counts); }, () => true, 2_000);
+ report.count("queue_halted");
+ report.count("queue_halted");
+ report.count("stale_after_wait");
+ expect(sent).toEqual([]);
+ vi.advanceTimersByTime(2_000);
+ expect(sent).toEqual([{ queue_halted: 2, stale_after_wait: 1 }]);
+ vi.advanceTimersByTime(10_000);
+ expect(sent).toHaveLength(1);
+ });
+
+ it("keeps counts while the view is not connected and sends them once it is", () => {
+ const sent: unknown[] = [];
+ let ready = false;
+ const report = createInputDropReport(async (counts) => { sent.push(counts); }, () => ready, 2_000);
+ report.count("not_connected");
+ vi.advanceTimersByTime(2_000);
+ expect(sent).toEqual([]);
+ ready = true;
+ report.kick();
+ vi.advanceTimersByTime(2_000);
+ expect(sent).toEqual([{ not_connected: 1 }]);
+ });
+
+ it("does not retry a failed send, and sends nothing once closed", async () => {
+ let calls = 0;
+ const report = createInputDropReport(async () => { calls += 1; throw new Error("offline"); }, () => true, 2_000);
+ report.count("send_failed");
+ await vi.advanceTimersByTimeAsync(2_000);
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(calls).toBe(1);
+ report.count("send_failed");
+ report.close();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(calls).toBe(1);
+ });
+});
diff --git a/src/lib/browser-input-drops.ts b/src/lib/browser-input-drops.ts
new file mode 100644
index 0000000000..7b6e6370db
--- /dev/null
+++ b/src/lib/browser-input-drops.ts
@@ -0,0 +1,31 @@
+/** Why the app dropped a person's browser input before sending it. The server counts these for a bug report. */
+export type InputDropReason = "stale_after_wait" | "queue_full" | "queue_halted" | "send_failed" | "take_failed" | "not_connected" | "held_elsewhere";
+
+/**
+ * Counts dropped input and hands the counts to `send` a little later, several drops in one request. Counts wait while
+ * `ready` is false and go with the next ones; a failed send is not retried. Security: only reason codes and counts leave
+ * the app, never what was typed or where.
+ */
+export function createInputDropReport(send: (counts: Partial<Record<InputDropReason, number>>) => Promise<unknown>, ready: () => boolean, delayMs = 2_000) {
+ let counts: Partial<Record<InputDropReason, number>> = {};
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let closed = false;
+ const flush = () => {
+ timer = undefined;
+ if (closed || !ready() || !Object.keys(counts).length) return;
+ const batch = counts;
+ counts = {};
+ void send(batch).catch(() => undefined);
+ };
+ const arm = () => { if (!closed && timer === undefined && Object.keys(counts).length) timer = setTimeout(flush, delayMs); };
+ return {
+ count(reason: InputDropReason) {
+ if (closed) return;
+ counts[reason] = (counts[reason] ?? 0) + 1;
+ arm();
+ },
+ /** The view connected: counts kept meanwhile may go. */
+ kick: arm,
+ close() { closed = true; clearTimeout(timer); timer = undefined; },
+ };
+}
diff --git a/src/lib/browser-live-action.ts b/src/lib/browser-live-action.ts
new file mode 100644
index 0000000000..c4b30e839b
--- /dev/null
+++ b/src/lib/browser-live-action.ts
@@ -0,0 +1,43 @@
+// What the v1 live view posts for each kind of input: the frozen action shapes, with no reach into the rest of the app.
+import type { PreviewStreamInput } from "./browser-stream-client";
+
+export type LiveActionBody = Record<string, unknown>;
+
+const CHAR_LIMIT = 4_096;
+const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, Number.isFinite(value) ? value : 0));
+export const delta = (value: number) => clamp(value, -10_000, 10_000);
+
+/** A v2 message as the v1 action it stands for; null for what v1 has no action for. */
+export function liveAction(input: PreviewStreamInput): LiveActionBody | LiveActionBody[] | null {
+ switch (input.type) {
+ case "mouse":
+ return {
+ type: "input_mouse", eventType: input.action === "down" ? "mousePressed" : input.action === "up" ? "mouseReleased" : "mouseMoved",
+ x: clamp(input.x, 0, 8192), y: clamp(input.y, 0, 8192), button: input.button,
+ clickCount: Math.round(clamp(input.clickCount, 0, 3)), modifiers: input.modifiers,
+ };
+ case "wheel":
+ return { type: "input_mouse", eventType: "mouseWheel", x: clamp(input.x, 0, 8192), y: clamp(input.y, 0, 8192), button: "none", deltaX: delta(input.deltaX), deltaY: delta(input.deltaY), modifiers: input.modifiers };
+ case "key":
+ if (!input.key) return null;
+ return {
+ type: "input_keyboard", eventType: input.action === "up" ? "keyUp" : "keyDown", key: input.key.slice(0, 64), code: input.code.slice(0, 64),
+ windowsVirtualKeyCode: Math.round(clamp(input.keyCode ?? 0, 0, 255)), modifiers: input.modifiers,
+ ...(input.text !== undefined ? { text: input.text } : {}),
+ };
+ case "text": {
+ const chunks: LiveActionBody[] = [];
+ for (let at = 0; at < input.text.length; at += CHAR_LIMIT) chunks.push({ type: "input_keyboard", eventType: "char", text: input.text.slice(at, at + CHAR_LIMIT) });
+ return chunks;
+ }
+ case "navigate": return { type: "navigate", url: input.url };
+ case "history": return { type: input.delta < 0 ? "back" : "forward" };
+ case "reload": return { type: "reload" };
+ case "tabSelect": return { type: "tab-select", tabId: input.tabId };
+ case "tabClose": return { type: "tab-close", tabId: input.tabId };
+ case "tabNew": return input.url ? { type: "tab-new", url: input.url } : { type: "tab-new" };
+ case "restart": return { type: "restart" };
+ case "dialog": return { type: "dialog", accept: input.accept, ...(input.promptText !== undefined ? { promptText: input.promptText.slice(0, 4_096) } : {}) };
+ default: return null;
+ }
+}
diff --git a/src/lib/browser-stream-v1.test.ts b/src/lib/browser-stream-v1.test.ts
index cd98f90dde..2fe3691965 100644
--- a/src/lib/browser-stream-v1.test.ts
+++ b/src/lib/browser-stream-v1.test.ts
@@ -173,6 +173,30 @@ describe("the v1 live client", () => {
expect(post).toHaveBeenLastCalledWith({ type: "release" }, "v1");
});
+ it("stops sending presses after one refused request until it reconnects, and tells the server how many it dropped", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ try {
+ const { client, post, handlers, source } = open();
+ source.emit("ready", { viewerId: "v1" });
+ source.emit("control", { held: true, owned: true, controlling: true });
+ const press = { type: "mouse", action: "down", x: 1, y: 2, button: "left", buttons: 1, clickCount: 1, modifiers: 0 } as const;
+ post.mockRejectedValueOnce(Object.assign(new Error("Browser control changed. Try again."), { status: 409 }));
+ client.transport.send(press);
+ await client.transport.settle();
+ expect(client.transport.stopped()).toBe(true);
+ expect(handlers.onMessage).toHaveBeenCalledWith({ type: "notice", message: "Browser control changed. Try again." });
+ post.mockClear();
+ client.transport.send(press);
+ client.transport.send({ type: "text", text: "typed words" });
+ client.transport.send({ type: "mouse", action: "move", x: 3, y: 4, button: "none", buttons: 0, clickCount: 0, modifiers: 0 });
+ await client.transport.settle();
+ expect(post).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(post.mock.calls).toEqual([[{ type: "client_drops", counts: { send_failed: 1, queue_halted: 2 } }, "v1"]]);
+ client.stop();
+ } finally { vi.useRealTimers(); }
+ });
+
it("batches the input queued behind a request only for a server that said it takes batches", async () => {
for (const [ready, batched] of [[{ viewerId: "v1", inputBatch: 64 }, true], [{ viewerId: "v1" }, false]] as const) {
const { client, post, source } = open();
diff --git a/src/lib/browser-stream-v1.ts b/src/lib/browser-stream-v1.ts
index 11c71e4f19..0fab16499d 100644
--- a/src/lib/browser-stream-v1.ts
+++ b/src/lib/browser-stream-v1.ts
@@ -1,11 +1,14 @@
// The v1 live view (server-sent events, one POST per action) behind the v2 stream client's interface, so one panel
// speaks both: v1 is what agent-browser serves, and what an older server or companion still offers.
import type { ControlTransport } from "./browser-control";
+import { createInputDropReport, type InputDropReason } from "./browser-input-drops";
+import { delta, liveAction } from "./browser-live-action";
import { t } from "./i18n";
import { withBrowserScope } from "./team-browser";
import type { PreviewStreamClient, PreviewStreamControl, PreviewStreamEvents, PreviewStreamInput } from "./browser-stream-client";
type Body = Record<string, unknown>;
+export { liveAction };
export type LivePost = (body: Body, viewerId: string) => Promise<unknown>;
export interface LiveStreamClient extends PreviewStreamClient {
@@ -20,11 +23,8 @@ const RECONNECT_DELAYS = [1_000, 2_000, 4_000, 8_000, 15_000];
const SILENT_MS = 25_000;
const SILENCE_CHECK_MS = 5_000;
const QUEUE_LIMIT = 32;
-const CHAR_LIMIT = 4_096;
/** Under the 32 KB the server reads of one action's body. */
const BATCH_BYTES = 24_000;
-const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, Number.isFinite(value) ? value : 0));
-const delta = (value: number) => clamp(value, -10_000, 10_000);
/** Frame metadata can describe the window, not the page: headless Chrome reports 1280×720 for a 1280×577 page. */
export function browserFrameSize(imageWidth: number, imageHeight: number, width: number, height: number) {
@@ -43,41 +43,6 @@ export function jpegSize(bytes: Uint8Array): { width: number; height: number } |
return null;
}
-/** A v2 message as the v1 action it stands for; null for what v1 has no action for. */
-export function liveAction(input: PreviewStreamInput): Body | Body[] | null {
- switch (input.type) {
- case "mouse":
- return {
- type: "input_mouse", eventType: input.action === "down" ? "mousePressed" : input.action === "up" ? "mouseReleased" : "mouseMoved",
- x: clamp(input.x, 0, 8192), y: clamp(input.y, 0, 8192), button: input.button,
- clickCount: Math.round(clamp(input.clickCount, 0, 3)), modifiers: input.modifiers,
- };
- case "wheel":
- return { type: "input_mouse", eventType: "mouseWheel", x: clamp(input.x, 0, 8192), y: clamp(input.y, 0, 8192), button: "none", deltaX: delta(input.deltaX), deltaY: delta(input.deltaY), modifiers: input.modifiers };
- case "key":
- if (!input.key) return null;
- return {
- type: "input_keyboard", eventType: input.action === "up" ? "keyUp" : "keyDown", key: input.key.slice(0, 64), code: input.code.slice(0, 64),
- windowsVirtualKeyCode: Math.round(clamp(input.keyCode ?? 0, 0, 255)), modifiers: input.modifiers,
- ...(input.text !== undefined ? { text: input.text } : {}),
- };
- case "text": {
- const chunks: Body[] = [];
- for (let at = 0; at < input.text.length; at += CHAR_LIMIT) chunks.push({ type: "input_keyboard", eventType: "char", text: input.text.slice(at, at + CHAR_LIMIT) });
- return chunks;
- }
- case "navigate": return { type: "navigate", url: input.url };
- case "history": return { type: input.delta < 0 ? "back" : "forward" };
- case "reload": return { type: "reload" };
- case "tabSelect": return { type: "tab-select", tabId: input.tabId };
- case "tabClose": return { type: "tab-close", tabId: input.tabId };
- case "tabNew": return input.url ? { type: "tab-new", url: input.url } : { type: "tab-new" };
- case "restart": return { type: "restart" };
- case "dialog": return { type: "dialog", accept: input.accept, ...(input.promptText !== undefined ? { promptText: input.promptText.slice(0, 4_096) } : {}) };
- default: return null;
- }
-}
-
const movement = (body: Body) => body.type === "input_mouse" && (body.eventType === "mouseMoved" || body.eventType === "mouseWheel");
const batchable = (body: Body) => body.type === "input_mouse" || body.type === "input_keyboard";
const releases = (body: Body) => (body.type === "input_mouse" && body.eventType === "mouseReleased") || (body.type === "input_keyboard" && body.eventType === "keyUp");
@@ -86,7 +51,7 @@ const afterHalt = (body: Body) => releases(body) || !batchable(body);
/** One request at a time: key and button order is kept, movement coalesced, and a reconnect never replays old input. Where
* the server takes batches (`batchLimit` above 1), every input queued behind a request goes in the next one. */
-export function createLiveInputQueue(send: (body: Body) => Promise<unknown>, onError: (cause: unknown) => void, batchLimit: () => number = () => 1) {
+export function createLiveInputQueue(send: (body: Body) => Promise<unknown>, onError: (cause: unknown) => void, batchLimit: () => number = () => 1, onDrop: (reason: InputDropReason) => void = () => {}) {
let queue: Body[] = [];
let active: Promise<void> | null = null;
let generation = 0;
@@ -118,6 +83,7 @@ export function createLiveInputQueue(send: (body: Body) => Promise<unknown>, onE
if (current !== generation) continue;
// The server stops a batch at its first failure, so its later releases may never have been sent.
if (taken.length > 1) queue.unshift(...taken.slice(1).filter(releases));
+ onDrop("send_failed");
halt(cause);
}
}
@@ -125,7 +91,10 @@ export function createLiveInputQueue(send: (body: Body) => Promise<unknown>, onE
};
return {
enqueue(body: Body) {
- if (stopped && !afterHalt(body)) return;
+ if (stopped && !afterHalt(body)) {
+ if (!movement(body)) onDrop("queue_halted");
+ return;
+ }
const last = queue.at(-1);
if (last && movement(body) && last.type === body.type && last.eventType === body.eventType && last.modifiers === body.modifiers && last.button === body.button) {
queue[queue.length - 1] = body.eventType === "mouseWheel"
@@ -139,7 +108,10 @@ export function createLiveInputQueue(send: (body: Body) => Promise<unknown>, onE
if (replaceable >= 0) queue.splice(replaceable, 1);
else {
halt(new Error(t("browser.input.tooSlow")));
- if (!afterHalt(body) || queue.length >= QUEUE_LIMIT) return;
+ if (!afterHalt(body) || queue.length >= QUEUE_LIMIT) {
+ onDrop("queue_full");
+ return;
+ }
}
}
queue.push({ ...body });
@@ -223,9 +195,10 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEvent
const message = (reply as { notice?: unknown } | null)?.notice;
if (typeof message === "string" && message) notice(message);
};
+ const drops = createInputDropReport((counts) => post({ type: "client_drops", counts }, viewerId), () => viewerId !== "");
const queue = createLiveInputQueue((body) => (viewerId ? postTo(body, viewerId).then(noticed) : Promise.reject(new Error(t("browser.panel.connectionFirst")))), (cause) => {
notice(cause instanceof Error ? cause.message : String(cause));
- }, () => inputBatch);
+ }, () => inputBatch, drops.count);
/** One resize request at a time, the newest size last; a refusal changes nothing. */
const sendSize = () => {
@@ -264,6 +237,7 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEvent
inputBatch = Number.isSafeInteger(data.inputBatch) ? Math.max(1, Math.min(Number(data.inputBatch), 64)) : 1;
resume.viewer = "";
events.onConnectedChange(true);
+ drops.kick();
if (size !== opening) sendSize();
});
listen("heartbeat", () => { attempts = 0; });
@@ -366,12 +340,15 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEvent
if (viewerId) resume.viewer = viewerId;
viewerId = "";
queue.clear();
+ drops.close();
},
transport: {
send: (input) => {
const action = viewerId ? liveAction(input) : null;
if (action) for (const body of Array.isArray(action) ? action : [action]) queue.enqueue(body);
+ else if (!viewerId && input.type !== "resize" && !(input.type === "mouse" && input.action === "move")) drops.count("not_connected");
},
+ dropped: drops.count,
drain: () => queue.drain(),
settle: () => queue.settle(),
size: () => queue.size(),