Files
loki/scripts/test/screen-browser.ts
CatoandClaude Opus 5.5 29bfe8012a feat(browser): Terminal → Browser — watch a bot's browser live and take it over (#1772)
The browser Loki's agents and Cat Bot already drive (lib/bot-browser) gets
a screen: a third view of a session beside Chat and Terminal, beside the
conversation on a wide screen and in its place on a phone, with the agent
box under it.

- CDP screencast while someone watches (6 fps, newest wins), drawn by the
  existing RobotBrowser, which gains onTap
- one wheel: a person's step takes it; every bot step (a look too) answers
  TAKEN_OVER until hand-back, and the bot's next look carries handedBack
- the password/code/card refusal shows as "<bot> needs you" with Take over
- caption, pointer on the bot's target, "What happened" timeline (never
  typed text); native <select> offered as a picker; dialogs said in words
- memory: every browser's process tree measured (PSS), closed over 700 MB
- doors: /api/browser/live + /input (a signed-in person, own browsers only),
  /api/browser/step (the account's ck_ token, for Terminal agents),
  /api/browser/sessions; cloud-builder accounts only; demo denied
- /screen redirects to /terminal?view=browser
- scripts/test/screen-browser.ts: end to end at 390px and wide

Measured on the laptop: one live browser 229–236 MB PSS.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:11:03 +01:00

320 lines
14 KiB
TypeScript

/**
* The screen of a bot's browser, end to end on a 390px phone and a wide
* screen: lib/bot-browser (the browser Cat Bot and Loki's agents drive) opens
* a little "preview site" for a bot; Loki's real ScreenPane — the Terminal's
* Browser view — watches it live, shows where the bot pressed, raises "needs
* you" at a password, takes over (the bot is then refused, looks included),
* taps and types into the page, uses a native picker, and hands back (the
* bot's next look says where the page was left).
*
* A local server stands in for Loki's two person doors (/api/browser/live and
* /input) with the same library calls; auth is the routes' own and tested
* elsewhere (api-route-auth).
*
* SCREEN_SHOT / SCREEN_SHOT_WIDE=<path> save the PR's pictures.
* Run: npx tsx scripts/test/screen-browser.ts
*/
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { createRequire } from "node:module";
import { build } from "esbuild";
import { chromium, type Browser } from "playwright";
import tailwind from "@tailwindcss/postcss";
// The test site is on 127.0.0.1; on a person's own machine the private
// network is theirs (lib/feedback/page-picture), and so it is here.
process.env.RUNTIME_AVAILABLE = "true";
process.env.LOKI_BOT_BROWSER_DIR = fs.mkdtempSync(path.join(process.cwd(), ".screen-test-"));
const USER = "00000000-0000-4000-8000-000000000001";
const SITE = `<!doctype html><html><head><title>Murmel Bakery</title>
<style>body{font:22px system-ui;margin:0;padding:32px;background:#fdf6ec;color:#3b2a1a}
h1{font-size:44px;margin:0 0 8px}p{margin:0}.f{position:absolute;left:32px;width:520px;height:56px;box-sizing:border-box;font-size:22px}
#name{top:160px}#q{top:240px}#pw{top:320px}#loaf{top:400px}#echo{position:absolute;top:480px;left:32px}</style></head>
<body><h1>Murmel Bakery</h1><p>Fresh bread every morning, Langstrasse 12.</p>
<input class="f" id="name" aria-label="Your name">
<input class="f" id="q" aria-label="Question" oninput="document.getElementById('echo').textContent='You wrote: '+this.value">
<input class="f" id="pw" type="password" aria-label="Password">
<select class="f" id="loaf" aria-label="Loaf"><option value="rye">Rye</option><option value="spelt">Spelt</option></select>
<p id="echo"></p></body></html>`;
async function bundleViewer(): Promise<{ js: string; css: string }> {
const require = createRequire(import.meta.url);
const postcss = createRequire(require.resolve("@tailwindcss/postcss"))("postcss") as (
plugins: unknown[],
) => { process(css: string, options: { from: string }): Promise<{ css: string }> };
const from = path.resolve("src/app/globals.css");
const styles = await postcss([tailwind()]).process(fs.readFileSync(from, "utf8"), { from });
const out = await build({
stdin: {
resolveDir: process.cwd(),
loader: "jsx",
contents: `import React,{useState} from 'react';import{createRoot}from'react-dom/client';
import{ScreenPane}from'./src/components/screen/ScreenPane';
import{TerminalViewSwitch}from'./src/components/terminal/TerminalViewSwitch';
function Session(){
const [view,setView]=useState('browser');
const wide=window.innerWidth>=1024;
return <main className="app-page" style={{height:'100dvh',display:'flex',flexDirection:'column',gap:8}}>
<TerminalViewSwitch view={view} onViewChange={setView} chat browser sessionView="chat"/>
{wide
? <div className="ui-term-split"><div className="ui-term-split-pty ui-callout">The session as chat, beside the browser</div>{view==='browser'&&<div className="ui-term-split-browser"><ScreenPane/></div>}</div>
: view==='browser'?<ScreenPane/>:<p>The session as {view}</p>}
<div className="ui-input min-h-11">Message the agent</div>
</main>;
}
createRoot(document.getElementById('app')).render(<Session/>);`,
},
bundle: true,
write: false,
jsx: "automatic",
format: "iife",
define: { "process.env.NODE_ENV": '"production"' },
// Next.js gives the browser a `process`; a bare esbuild bundle has none.
banner: { js: 'var process = { env: { NODE_ENV: "production" } };' },
});
return { js: out.outputFiles[0].text, css: styles.css };
}
async function main() {
const engine = await import("../../src/lib/bot-browser");
const live = await import("../../src/lib/bot-browser-live");
const { PersonBrowserAction, TAKEN_OVER } = await import("../../src/lib/bot-browser-live-rules");
const { serverChromium } = await import("../../src/lib/feedback/page-picture");
const found = await serverChromium();
if (!found.ok) {
if (process.env.CI) throw new Error(`no server Chromium: ${found.reason}`);
console.log("↷ screen-browser skipped: no Chromium here; CI runs it");
return;
}
let viewerBrowser: Browser;
try {
viewerBrowser = await chromium.launch({ executablePath: found.executablePath });
} catch (error) {
if (process.env.CI) throw error;
console.log("↷ screen-browser skipped: Chromium does not start here; CI runs it");
return;
}
const { js, css } = await bundleViewer();
const streams = new Set<http.ServerResponse>();
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://x");
const json = (v: unknown, status = 200) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(v));
};
if (url.pathname === "/site") {
res.writeHead(200, { "Content-Type": "text/html" });
return res.end(SITE);
}
if (url.pathname === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
return res.end(
`<!doctype html><html class="dark"><head><meta name="viewport" content="width=device-width,initial-scale=1"><style>${css}</style></head><body class="bg-bg text-text"><div id="app"></div><script>${js}</script></body></html>`,
);
}
if (url.pathname === "/api/browser/live") {
// The route's own follow: watch the newest browser, or wait for one.
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
streams.add(res);
let w: { key: string | null; stop: () => void } = { key: null, stop: () => {} };
const onFrame = (f: unknown) => {
if ((f as { state: string }).state === "closed") {
w.stop();
w = { key: null, stop: () => {} };
}
res.write(`event: frame\ndata: ${JSON.stringify(f)}\n\n`);
};
void live.watchBotBrowser(USER, null, onFrame).then((x) => {
w = x;
res.write(`event: ready\ndata: {}\n\n`);
});
const follow = setInterval(() => {
if (w.key || engine.botBrowsersOf(USER).length === 0) return;
void live.watchBotBrowser(USER, null, onFrame).then((x) => (w = x));
}, 300);
req.on("close", () => {
clearInterval(follow);
w.stop();
streams.delete(res);
});
return;
}
if (url.pathname === "/api/browser/input") {
let b = "";
req.on("data", (c) => (b += c));
req.on("end", () => {
const body = JSON.parse(b) as { key?: string; action: unknown };
const action = PersonBrowserAction.parse(body.action);
if (process.env.SCREEN_TRACE) console.log("input", JSON.stringify(action));
void live
.personBrowserStep(USER, body.key ?? null, action)
.then((r) =>
r.ok ? json({ ok: true, key: r.key }) : json({ ok: false, error: r.error }, 409),
);
});
return;
}
json({ error: "not here" }, 404);
});
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
const base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
try {
const page = await viewerBrowser.newPage({
viewport: { width: 390, height: 844 },
isMobile: true,
hasTouch: true,
});
const errors: string[] = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(base);
await page
.getByText("No browser is open")
.waitFor({ timeout: 15_000 })
.catch(async (e: unknown) => {
console.error(
"page errors:",
errors,
"\nbody:",
(await page.innerText("body")).slice(0, 400),
);
throw e;
});
// An agent opens a page while you watch: it appears, live.
const opened = await engine.botBrowserStep(USER, "loki", { do: "open", url: `${base}/site` });
assert.ok(opened.ok, JSON.stringify(opened));
const img = page.getByRole("img", { name: /browser on/ });
await img.waitFor({ timeout: 20_000 });
// It is a view of the session: a second tap on Browser returns to Chat.
await page.getByRole("button", { name: "Browser", exact: true }).click();
await page.getByText("The session as chat").waitFor();
await page.getByRole("button", { name: "Browser", exact: true }).click();
await img.waitFor({ timeout: 10_000 });
// The agent types by number; the caption says so (never what it typed).
const look = await engine.botBrowserStep(USER, "loki", { do: "look" });
assert.ok(look.ok && look.view);
const n = (name: string) => look.view!.elements.find((e) => e.name === name)?.n;
assert.ok(n("Your name") && n("Password") && n("Loaf"), JSON.stringify(look.view!.elements));
const typed = await engine.botBrowserStep(USER, "loki", {
do: "type",
n: n("Your name"),
text: "Ada",
});
assert.ok(typed.ok);
await page.getByText("Your agents: Typed").waitFor({ timeout: 10_000 });
// A password is never the bot's: stopped, and the owner is asked.
const pw = await engine.botBrowserStep(USER, "loki", {
do: "type",
n: n("Password"),
text: "x",
});
assert.ok(!pw.ok && pw.reason === "stopped");
await page.getByText("Your agents needs you.").waitFor({ timeout: 10_000 });
// Take over: the bot is still and blind until the owner hands back.
await page.getByRole("alert").getByRole("button", { name: "Take over" }).click();
await page.getByText("You have control — the agent is paused").waitFor({ timeout: 10_000 });
const refused = await engine.botBrowserStep(USER, "loki", { do: "look" });
assert.ok(!refused.ok && refused.detail === TAKEN_OVER, "a look is refused too");
// Tap the question field on the picture and type into the page.
// The view eases out of its lean once the person drives: measure the
// picture where it is at the moment of each tap.
await page.waitForTimeout(900);
const at = async (x: number, y: number) => {
const box = (await img.boundingBox())!;
return { x: box.x + (x / 1280) * box.width, y: box.y + (y / 800) * box.height };
};
const q = await at(200, 268);
await page.mouse.click(q.x, q.y);
await page.waitForTimeout(300);
await page.getByLabel("Type into the page").fill("Gluten-free?");
await page.getByRole("button", { name: "Type", exact: true }).click();
// A native select has no picture: the viewer offers its options.
const sel = await at(200, 428);
await page.mouse.click(sel.x, sel.y);
const picker = page.getByLabel("Choose an option");
await picker.waitFor({ timeout: 10_000 });
await picker.selectOption("spelt");
await page.waitForTimeout(600);
if (process.env.SCREEN_SHOT) await page.screenshot({ path: process.env.SCREEN_SHOT });
// Hand back: the bot may look again and is told where the page was left.
await page.getByRole("button", { name: "Hand back" }).click();
await page.getByText("You: Handed back").waitFor({ timeout: 10_000 });
const after = await engine.botBrowserStep(USER, "loki", { do: "look" });
assert.ok(after.ok && after.view, JSON.stringify(after));
assert.ok(after.view.handedBack, "the first look after hand-back says so");
assert.match(
after.view.text,
/You wrote: Gluten-free\?/,
"the person's typing reached the page",
);
const again = await engine.botBrowserStep(USER, "loki", { do: "look" });
assert.ok(again.ok && !again.view?.handedBack, "only once");
// Phone-sized: nothing sideways, every control a thumb's size.
const layout = await page.evaluate(() => {
// The zoomed page layer overhangs by design; its box clips it.
const wide = [
...document.querySelectorAll<HTMLElement>(
".ui-screen *:not(.ui-robot-layer, .ui-robot-layer *)",
),
].filter((el) => el.getBoundingClientRect().right > window.innerWidth + 1).length;
const small = [
...document.querySelectorAll<HTMLElement>(
"main button, main input, main select, main summary",
),
]
.map((el) => el.getBoundingClientRect())
.filter((r) => r.height > 0 && r.height < 44).length;
return { wide, small, scroll: document.documentElement.scrollWidth };
});
assert.equal(layout.wide, 0, "nothing past the right edge");
assert.equal(layout.small, 0, "no control under 44px");
assert.ok(layout.scroll <= 390, `no sideways scroll (${layout.scroll})`);
// Measured, and the cap reads the same number.
await live.measureBotBrowsers();
const mb = engine.botBrowsersOf(USER)[0]?.mb;
if (process.platform === "linux") assert.ok(mb && mb > 20, `one browser measured: ${mb} MB`);
console.log(` one live browser: ${mb ?? "?"} MB (PSS, every process)`);
if (process.env.SCREEN_SHOT_WIDE) {
await page.setViewportSize({ width: 1280, height: 860 });
await page.reload();
await page.getByRole("img", { name: /browser on/ }).waitFor({ timeout: 15_000 });
await page.waitForTimeout(600);
await page.screenshot({ path: process.env.SCREEN_SHOT_WIDE });
}
// Closing ends the screen with a sentence, not a frozen picture.
await engine.botBrowserStep(USER, "loki", { do: "close" });
await page.getByText("Closed.").waitFor({ timeout: 10_000 });
assert.deepEqual(errors, []);
console.log("screen-browser: ok");
} finally {
for (const s of engine.botBrowsersOf(USER)) await engine.closeSession(s);
for (const r of streams) r.end();
server.close();
await viewerBrowser.close();
fs.rmSync(process.env.LOKI_BOT_BROWSER_DIR!, { recursive: true, force: true });
}
}
main().catch((e) => {
console.error(e);
process.exit(1);
});