From 8e38374f276d4d72defdfc3b763bdd99f5e9fb77 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:39:55 +0100 Subject: [PATCH 1/7] fix: capture the scrolled part of the page in the card browser [skip ci] On macOS a card's Browser tab is a stream of screenshots from headless Chrome. The capture passed a clip at 0,0, but Chrome reads the clip in page coordinates. Once the page scrolled, the clip pointed above the viewport and those rows came back blank: scroll 300px and the top 300px of the frame was empty, scroll a full screen and nothing was left. Start the clip at the visual viewport's page offset, which is what Playwright does for its own screenshots. Windows shows the live WebView2 surface and doesn't use this capture. Co-Authored-By: Claude Opus 5.5 --- runtime/browser/render.ts | 8 +++- tests/browser-capture.test.ts | 78 +++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/runtime/browser/render.ts b/runtime/browser/render.ts index 41c1b57..cb1637e 100644 --- a/runtime/browser/render.ts +++ b/runtime/browser/render.ts @@ -36,13 +36,17 @@ export class BrowserRendering { // Capture the compositor at its actual density. Playwright's screenshot // helper otherwise rescales using the context's original density after a // display change. CDP also preserves the page's native caret and selection. + // The clip is in page coordinates, so it starts where the page is scrolled. + const { cssVisualViewport: visible } = await session.send( + "Page.getLayoutMetrics", + ); const result = await session.send("Page.captureScreenshot", { format: "png", fromSurface: true, captureBeyondViewport: false, clip: { - x: 0, - y: 0, + x: visible.pageX, + y: visible.pageY, ...viewport, scale: scale === "css" ? 1 / deviceScaleFactor : 1, }, diff --git a/tests/browser-capture.test.ts b/tests/browser-capture.test.ts index db949ee..6bfbd2a 100644 --- a/tests/browser-capture.test.ts +++ b/tests/browser-capture.test.ts @@ -7,6 +7,8 @@ import { join } from "node:path"; import { browserCapture } from "../runtime/browser/capture.ts"; import { AgentBrowserManager } from "../runtime/browser/manager.ts"; import { initialState } from "../src/seed.ts"; +import type { BrowserImage } from "../src/browser.ts"; +import type { Page } from "playwright-core"; test("a missing native capture callback falls back without waiting indefinitely", async () => { const start = Date.now(); @@ -108,3 +110,79 @@ test( } }, ); + +const bandHeight = 1000; +const bands = ["red", "green", "blue"] as const; +const stripedPage = `${bands + .map( + (color) => + `
`, + ) + .join("")}`; + +function selectedPage(manager: AgentBrowserManager, taskId: string): Page { + const session = (manager as any).sessions.get(taskId); + return session.pages.get(session.selected); +} + +/** Decodes a frame in the browser and names the colour at its top and bottom edge. */ +function frameEdgeColors(page: Page, image: BrowserImage) { + return page.evaluate(async ({ mimeType, data }) => { + const bytes = Uint8Array.from(atob(data), (char) => char.charCodeAt(0)); + const bitmap = await createImageBitmap( + new Blob([bytes], { type: mimeType }), + ); + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const context = canvas.getContext("2d")!; + context.drawImage(bitmap, 0, 0); + // Inline callback: tsx renames named functions with a helper the page lacks. + return [4, bitmap.height - 4].map((y) => { + const [red, green, blue] = context.getImageData(10, y, 1, 1).data; + if (red > 200 && green < 60 && blue < 60) return "red"; + if (green > 200 && red < 60 && blue < 60) return "green"; + if (blue > 200 && red < 60 && green < 60) return "blue"; + return "none"; + }); + }, image); +} + +test( + "a frame after the user scrolls shows the part of the page now on screen", + { timeout: 30000 }, + async () => { + const server = createServer((_request, response) => { + response.setHeader("Content-Type", "text/html"); + response.end(stripedPage); + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + const state = initialState(), + task = state.tasks[0]; + const manager = new AgentBrowserManager( + () => state, + await mkdtemp(join(tmpdir(), "memcode-scroll-frame-test-")), + async () => {}, + ); + try { + await manager.execute(task.id, { + action: "open", + url: `http://127.0.0.1:${address.port}`, + }); + await manager.execute(task.id, { + action: "act", + input: { action: "scroll", x: 100, y: 100, deltaY: 1200 }, + }); + const page = selectedPage(manager, task.id); + await page.waitForFunction(() => scrollY === 1200); + const frame = await manager.execute(task.id, { action: "frame" }); + assert.deepEqual(await frameEdgeColors(page, frame.image!), [ + "green", + "green", + ]); + } finally { + await manager.close(); + await new Promise((done) => server.close(() => done())); + } + }, +); From 7dc4c31a3ea623e3b60fa72b097ee564dc28e64e Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:42:11 +0100 Subject: [PATCH 2/7] fix: send the card browser's live frames as JPEG [skip ci] Each live frame was a lossless PNG at Retina density. In the Mac app that took 133ms on average to capture, up to 284ms, and came to about 530KB of base64. Scrolling showed three or four frames a second, each one late. JPEG at quality 85 takes about 40ms and 130KB for the same page, so a scroll now lands at roughly 8 frames a second with nothing queued behind it. Text stays sharp at 2x. Only the live frame changes. Screenshots a worker observes and ones saved to a card's artifacts stay PNG, and the Windows WebView2 capture is untouched. Co-Authored-By: Claude Opus 5.5 --- runtime/browser/manager.ts | 55 +++++++++++++++++++++------------- runtime/browser/render.ts | 9 +++++- tests/agent-browser.test.ts | 7 ++--- tests/support/browser-image.ts | 28 +++++++++++++++++ 4 files changed, 73 insertions(+), 26 deletions(-) create mode 100644 tests/support/browser-image.ts diff --git a/runtime/browser/manager.ts b/runtime/browser/manager.ts index 7811d07..cca1455 100644 --- a/runtime/browser/manager.ts +++ b/runtime/browser/manager.ts @@ -15,7 +15,7 @@ import { BrowserPool, type BrowserSession } from "./pool"; import { NativeBrowserPool } from "./native-pool"; import type { NativeHost } from "../host"; import { inspectPage, interact } from "./inspect"; -import { BrowserRendering } from "./render"; +import { BrowserRendering, type ImageFormat } from "./render"; import { browserDeadline } from "./capture"; interface Session { @@ -459,7 +459,7 @@ export class AgentBrowserManager { return { state: this.view(session), ...(page && page.url() !== "about:blank" - ? { image: await this.image(session, page, "device") } + ? { image: await this.image(session, page, "device", "jpeg") } : {}), }; } else if (request.action === "capture") @@ -467,7 +467,12 @@ export class AgentBrowserManager { session.state.action = undefined; return { state: this.view(session) }; } - private async image(session: Session, page: Page, scale: "css" | "device") { + private async image( + session: Session, + page: Page, + scale: "css" | "device", + format: ImageFormat = "png", + ) { const actual = this.pool.native ? await browserDeadline( page.evaluate(() => ({ @@ -478,29 +483,37 @@ export class AgentBrowserManager { "Browser viewport observation", ) : undefined; - const data = + // The native WebView2 capture is always PNG; only Chrome's frames change. + const encoded = this.pool instanceof NativeBrowserPool - ? await this.pool.capture( - session.state.taskId, - page, - scale, - actual!.viewport, - actual!.density, - ) - : await browserDeadline( - this.rendering.capture( - session.context!, + ? { + format: "png" as const, + data: await this.pool.capture( + session.state.taskId, page, - actual?.viewport ?? session.state.viewport, - actual?.density ?? session.state.deviceScaleFactor, scale, + actual!.viewport, + actual!.density, ), - 10000, - "Browser screenshot", - ); + } + : { + format, + data: await browserDeadline( + this.rendering.capture( + session.context!, + page, + actual?.viewport ?? session.state.viewport, + actual?.density ?? session.state.deviceScaleFactor, + scale, + format, + ), + 10000, + "Browser screenshot", + ), + }; return { - mimeType: "image/png" as const, - data, + mimeType: `image/${encoded.format}` as const, + data: encoded.data, ...(actual?.viewport ?? session.state.viewport), }; } diff --git a/runtime/browser/render.ts b/runtime/browser/render.ts index cb1637e..00e444f 100644 --- a/runtime/browser/render.ts +++ b/runtime/browser/render.ts @@ -1,6 +1,11 @@ import type { CDPSession, Page } from "playwright-core"; import type { BrowserSession } from "./pool"; +export type ImageFormat = "png" | "jpeg"; +// At Retina density Chrome encodes this 2-3x faster than PNG at about a third +// of the size; 90 approaches PNG size on text-heavy pages. +const JPEG_QUALITY = 85; + export class BrowserRendering { private sessions = new WeakMap(); private async session(context: BrowserSession, page: Page) { @@ -31,6 +36,7 @@ export class BrowserRendering { viewport: { width: number; height: number }, deviceScaleFactor: number, scale: "css" | "device", + format: ImageFormat = "png", ): Promise { const session = await this.session(context, page); // Capture the compositor at its actual density. Playwright's screenshot @@ -41,7 +47,8 @@ export class BrowserRendering { "Page.getLayoutMetrics", ); const result = await session.send("Page.captureScreenshot", { - format: "png", + format, + ...(format === "jpeg" ? { quality: JPEG_QUALITY } : {}), fromSurface: true, captureBeyondViewport: false, clip: { diff --git a/tests/agent-browser.test.ts b/tests/agent-browser.test.ts index 7fd1d32..8aa55d6 100644 --- a/tests/agent-browser.test.ts +++ b/tests/agent-browser.test.ts @@ -8,6 +8,7 @@ import { initialState } from "../src/seed"; import { browserURL } from "../src/browser"; import { BrowserPool } from "../runtime/browser/pool"; import { AgentBrowserManager } from "../runtime/browser/manager"; +import { pixelSize } from "./support/browser-image"; test("shared browser addresses permit HTTPS while keeping privileged URLs and remote plaintext out", () => { assert.equal(browserURL("google.com").href, "https://google.com/"); @@ -159,7 +160,7 @@ test( ); assert.match(observed.snapshot!.text, /Late.*\[selected\]/); const frame = await manager.execute(first.id, { action: "frame" }); - assert.equal(frame.image?.mimeType, "image/png"); + assert.equal(frame.image?.mimeType, "image/jpeg"); await manager.execute(first.id, { action: "resize", width: 800, @@ -167,9 +168,7 @@ test( deviceScaleFactor: 2, }); const retina = await manager.execute(first.id, { action: "frame" }); - const pixels = Buffer.from(retina.image!.data, "base64"); - assert.equal(pixels.readUInt32BE(16), 1600); - assert.equal(pixels.readUInt32BE(20), 1200); + assert.deepEqual(pixelSize(retina.image!), { width: 1600, height: 1200 }); const logical = await manager.execute(first.id, { action: "observe", screenshot: true, diff --git a/tests/support/browser-image.ts b/tests/support/browser-image.ts new file mode 100644 index 0000000..2427ec6 --- /dev/null +++ b/tests/support/browser-image.ts @@ -0,0 +1,28 @@ +import type { BrowserImage } from "../../src/browser"; + +const PNG_WIDTH_OFFSET = 16; +const JPEG_FIRST_SEGMENT = 2; +const isJpegFrameHeader = (marker: number) => marker >= 0xc0 && marker <= 0xc3; + +/** The encoded image's size in device pixels, read from its PNG or JPEG header. */ +export function pixelSize(image: BrowserImage): { + width: number; + height: number; +} { + const bytes = Buffer.from(image.data, "base64"); + if (image.mimeType === "image/png") + return { + width: bytes.readUInt32BE(PNG_WIDTH_OFFSET), + height: bytes.readUInt32BE(PNG_WIDTH_OFFSET + 4), + }; + for (let offset = JPEG_FIRST_SEGMENT; offset < bytes.length;) { + const marker = bytes[offset + 1]; + if (isJpegFrameHeader(marker)) + return { + height: bytes.readUInt16BE(offset + 5), + width: bytes.readUInt16BE(offset + 7), + }; + offset += 2 + bytes.readUInt16BE(offset + 2); + } + throw Error("The JPEG has no frame header."); +} From 072912dd3075356f0cce04f8ab0bc4495cb000b2 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:27:26 +0100 Subject: [PATCH 3/7] test: pin the card browser's address policy and popup tabs [skip ci] Two behaviours the browser tests never checked: a card page can't load plaintext from a host other than this machine, and a target=_blank link opens as another tab of the same card. Both pass on the current code and fail when the route or the popup listener is removed. Co-Authored-By: Claude Opus 5.5 --- tests/agent-browser.test.ts | 85 +++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/tests/agent-browser.test.ts b/tests/agent-browser.test.ts index 8aa55d6..ed05f54 100644 --- a/tests/agent-browser.test.ts +++ b/tests/agent-browser.test.ts @@ -273,3 +273,88 @@ test( } }, ); + +async function fixtureServer(page: (port: number) => string) { + const requests: string[] = []; + const server = createServer((request, response) => { + requests.push(request.url ?? ""); + response.setHeader("Content-Type", "text/html"); + response.end(page((server.address() as { port: number }).port)); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}`, + requests, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +test( + "a card page cannot load plaintext from a host outside the local machine", + { timeout: 30000 }, + async () => { + // Chrome sends "localhost." to this machine, but it is not an allowed address. + const fixture = await fixtureServer( + (port) => `Policy`, + ); + const state = initialState(), + task = state.tasks[0]; + const manager = new AgentBrowserManager( + () => state, + await mkdtemp(join(tmpdir(), "memcode-browser-policy-")), + async () => {}, + ); + try { + await manager.execute(task.id, { action: "open", url: fixture.url }); + for (let wait = 0; wait < 50 && !fixture.requests.includes("/allowed.png"); wait++) + await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 300)); + assert.ok(fixture.requests.includes("/allowed.png")); + assert.ok(!fixture.requests.includes("/blocked.png")); + } finally { + await manager.close(); + await fixture.close(); + } + }, +); + +test( + "a link that opens a new window becomes another tab of the same card", + { timeout: 30000 }, + async () => { + const fixture = await fixtureServer( + () => `OpenerOpen second`, + ); + const state = initialState(), + task = state.tasks[0]; + const manager = new AgentBrowserManager( + () => state, + await mkdtemp(join(tmpdir(), "memcode-browser-popup-")), + async () => {}, + ); + manager.attach(task.id, "codex", await mkdtemp(join(tmpdir(), "memcode-browser-popup-log-"))); + try { + await manager.execute(task.id, { action: "open", url: fixture.url }, "worker"); + const observed = await manager.execute(task.id, { action: "observe" }, "worker"); + await manager.execute( + task.id, + { + action: "act", + input: { action: "click", ref: "m1", revision: observed.snapshot!.revision }, + }, + "worker", + ); + let tabs = observed.state.tabs; + for (let wait = 0; wait < 50 && tabs.length < 2; wait++) { + await new Promise((resolve) => setTimeout(resolve, 50)); + tabs = (await manager.execute(task.id, { action: "state" })).state.tabs; + } + assert.equal(tabs.length, 2); + assert.equal(tabs.find((tab) => tab.active)?.url, fixture.url + "/second"); + } finally { + await manager.close(); + await fixture.close(); + } + }, +); From e41fbc611f73037bccad8dd4b95caa7c4a9ab26a Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:27:26 +0100 Subject: [PATCH 4/7] refactor: put card browsers behind a BrowserEngine port [skip ci] The manager now talks to one interface instead of Playwright pages. Headless Chrome and WebView2 sit behind Playwright adapters in playwright-engine.ts; pool.ts and native-pool.ts are unchanged, so the Windows calls happen in the same order as before. The capture tests only change how they reach the manager's internals. This is where the Mac's native WebKit surface plugs in next. Co-Authored-By: Claude Opus 5.5 --- runtime/browser/engine.ts | 63 +++++++ runtime/browser/manager.ts | 160 ++++++------------ runtime/browser/playwright-engine.ts | 237 +++++++++++++++++++++++++++ runtime/browser/render.ts | 2 +- tests/browser-capture.test.ts | 4 +- 5 files changed, 353 insertions(+), 113 deletions(-) create mode 100644 runtime/browser/engine.ts create mode 100644 runtime/browser/playwright-engine.ts diff --git a/runtime/browser/engine.ts b/runtime/browser/engine.ts new file mode 100644 index 0000000..d970330 --- /dev/null +++ b/runtime/browser/engine.ts @@ -0,0 +1,63 @@ +import type { BrowserInteraction, BrowserImage } from "../../src/browser"; + +export type ImageFormat = "png" | "jpeg"; +export type ImageScale = "css" | "device"; +export interface Viewport { + width: number; + height: number; +} +export interface InteractionRequest { + input: BrowserInteraction; + viewport: Viewport; + actor: "user" | "worker"; +} +export interface InteractionFeedback { + cursor?: string; + point?: { x: number; y: number }; +} +export interface CaptureRequest { + scale: ImageScale; + format: ImageFormat; + /** The card's own viewport, for engines that cannot ask the page. */ + viewport: Viewport; + density: number; +} +export interface SurfacePlacement { + visible: boolean; + bounds?: { x: number; y: number; width: number; height: number }; +} + +/** One tab of a card's browser, whichever engine draws it. */ +export interface BrowserPage { + url(): string; + title(): Promise; + isClosed(): boolean; + goto(url: string): Promise; + /** The worker's text view: control refs plus the accessibility tree. */ + inspect(): Promise; + onNavigated(listener: () => void): void; + onLoaded(listener: () => void): void; + onClosed(listener: () => void): void; +} + +/** A card's browser: its own storage, its tabs and the popups they open. */ +export interface BrowserTabs { + newPage(): Promise; + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void): void; + interact(page: BrowserPage, request: InteractionRequest): Promise; + capture(page: BrowserPage, request: CaptureRequest): Promise; + resize(page: BrowserPage, viewport: Viewport, density: number): Promise; + closePage(page: BrowserPage): Promise; + close(): Promise; +} + +/** Where card browsers live: hidden Chrome frames or a native surface over the card. */ +export interface BrowserEngine { + /** True when the human sees a live native surface instead of frames. */ + readonly native: boolean; + connected(): boolean; + open(viewport: Viewport, density: number, taskId: string): Promise; + /** Places, shows or hides the native surface over the card; frame engines ignore it. */ + surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement): Promise; + close(): Promise; +} diff --git a/runtime/browser/manager.ts b/runtime/browser/manager.ts index cca1455..e98124c 100644 --- a/runtime/browser/manager.ts +++ b/runtime/browser/manager.ts @@ -1,7 +1,6 @@ import { randomUUID } from "node:crypto"; import { mkdir, writeFile, appendFile } from "node:fs/promises"; import { join } from "node:path"; -import type { Page } from "playwright-core"; import type { AppState } from "../../src/shared"; import { browserURL, @@ -11,17 +10,21 @@ import { type WorkerBrowserState, } from "../../src/browser"; import { within, now } from "../local"; -import { BrowserPool, type BrowserSession } from "./pool"; import { NativeBrowserPool } from "./native-pool"; import type { NativeHost } from "../host"; -import { inspectPage, interact } from "./inspect"; -import { BrowserRendering, type ImageFormat } from "./render"; import { browserDeadline } from "./capture"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + ImageFormat, +} from "./engine"; +import { HeadlessEngine, WebView2Engine } from "./playwright-engine"; interface Session { state: WorkerBrowserState; - context?: BrowserSession; - pages: Map; + context?: BrowserTabs; + pages: Map; selected?: string; queue: Promise; revision: number; @@ -32,8 +35,7 @@ interface Session { export class AgentBrowserManager { private closing = false; private sessions = new Map(); - private pool: BrowserPool | NativeBrowserPool; - private rendering = new BrowserRendering(); + private engine: BrowserEngine; constructor( private state: () => AppState, private dataDir: string, @@ -41,10 +43,10 @@ export class AgentBrowserManager { private maxContexts = 16, host?: NativeHost, ) { - this.pool = + this.engine = host && process.platform === "win32" - ? new NativeBrowserPool(host) - : new BrowserPool(); + ? new WebView2Engine(new NativeBrowserPool(host)) + : new HeadlessEngine(); } private session(taskId: string): Session { if (!this.state().tasks.some((task) => task.id === taskId)) @@ -61,7 +63,7 @@ export class AgentBrowserManager { activity: [], viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1, - nativeSurface: this.pool.native, + nativeSurface: this.engine.native, }, pages: new Map(), queue: Promise.resolve(), @@ -112,7 +114,11 @@ export class AgentBrowserManager { })); return structuredClone(session.state); } - private register(session: Session, page: Page, replaces?: Page): string { + private register( + session: Session, + page: BrowserPage, + replaces?: BrowserPage, + ): string { const previous = [...session.pages].find( ([, existing]) => existing === page, ); @@ -137,9 +143,9 @@ export class AgentBrowserManager { }) .catch(() => {}); }; - page.on("domcontentloaded", update); - page.on("framenavigated", (frame) => { - if (frame !== page.mainFrame() || session.pages.get(id) !== page) return; + page.onLoaded(update); + page.onNavigated(() => { + if (session.pages.get(id) !== page) return; session.revision++; session.observed = undefined; update(); @@ -147,15 +153,7 @@ export class AgentBrowserManager { () => {}, ); }); - if (!this.pool.native) - page.on("popup", (popup) => this.register(session, popup)); - page.on("dialog", (dialog) => { - void dialog.dismiss(); - }); - page.on("download", (download) => { - void download.cancel(); - }); - page.on("close", () => { + page.onClosed(() => { if (session.pages.get(id) !== page) return; session.pages.delete(id); if (session.selected === id) @@ -171,11 +169,11 @@ export class AgentBrowserManager { update(); return id; } - private async context(session: Session): Promise { - if (session.context && this.pool.connected()) return session.context; + private async context(session: Session): Promise { + if (session.context && this.engine.connected()) return session.context; const occupied = [...this.sessions.values()].filter( (other) => - (other.context && this.pool.connected()) || + (other.context && this.engine.connected()) || other.state.status === "starting", ); if (occupied.length >= this.maxContexts) { @@ -202,27 +200,19 @@ export class AgentBrowserManager { ); } session.state.status = "starting"; - session.context = await this.pool.context( + session.context = await this.engine.open( session.state.viewport, session.state.deviceScaleFactor, session.state.taskId, ); - await session.context.route("**/*", async (route) => { - try { - browserURL(route.request().url()); - await route.continue(); - } catch { - await route.abort("blockedbyclient"); - } - }); - session.context.onPage?.((page, replaces) => + session.context.onPage((page, replaces) => this.register(session, page, replaces), ); session.pages.clear(); session.selected = undefined; return session.context; } - private page(session: Session, tabId?: string): Page { + private page(session: Session, tabId?: string): BrowserPage { const page = session.pages.get(tabId ?? session.selected ?? ""); if (!page || page.isClosed()) throw Error("Open a browser tab in this work item first."); @@ -285,11 +275,11 @@ export class AgentBrowserManager { : "Browser returned to the worker.", ); } else if (request.action === "surface") { - if (this.pool instanceof NativeBrowserPool) { + if (this.engine.native) { const page = request.tabId ? this.page(session, request.tabId) : undefined; - await this.pool.surface(session.state.taskId, page, { + await this.engine.surface(session.state.taskId, page, { visible: request.visible, bounds: request.bounds, }); @@ -321,11 +311,7 @@ export class AgentBrowserManager { : (existing?.[1] ?? (await context.newPage())); const id = request.tabId ?? existing?.[0] ?? this.register(session, page); session.selected = id; - if (!existing) - await page.goto(url.href, { - waitUntil: "domcontentloaded", - timeout: 20000, - }); + if (!existing) await page.goto(url.href); session.state.status = "ready"; this.view(session); session.state.tabs.find((tab) => tab.id === id)!.title = @@ -365,9 +351,7 @@ export class AgentBrowserManager { session.state.pointer = undefined; session.state.cursor = undefined; } else if (command.action === "close") { - if (this.pool instanceof NativeBrowserPool) - await this.pool.closePage(session.state.taskId, page); - else await page.close(); + await session.context!.closePage(page); if (!session.pages.size) { await session.context?.close(); session.context = undefined; @@ -375,17 +359,11 @@ export class AgentBrowserManager { } } else { session.state.action = command.action; - const native = - this.pool instanceof NativeBrowserPool ? this.pool : undefined; - if (native && actor === "worker") - await native.busy(session.state.taskId, page, true); - let feedback; - try { - feedback = await interact(page, command, session.state.viewport); - } finally { - if (native && actor === "worker") - await native.busy(session.state.taskId, page, false); - } + const feedback = await session.context!.interact(page, { + input: command, + viewport: session.state.viewport, + actor, + }); if ( feedback.cursor && page === session.pages.get(session.selected ?? "") @@ -410,9 +388,8 @@ export class AgentBrowserManager { session.state.viewport = { width: request.width, height: request.height }; session.state.deviceScaleFactor = request.deviceScaleFactor ?? session.state.deviceScaleFactor; - for (const page of this.pool.native ? [] : session.pages.values()) - await this.rendering.resize( - session.context!, + for (const page of session.pages.values()) + await session.context!.resize( page, session.state.viewport, session.state.deviceScaleFactor, @@ -425,7 +402,7 @@ export class AgentBrowserManager { if (actor === "worker" && session.state.control === "worker") session.selected = tabId; const text = await browserDeadline( - inspectPage(page), + page.inspect(), 10000, "Browser DOM observation", ); @@ -467,55 +444,18 @@ export class AgentBrowserManager { session.state.action = undefined; return { state: this.view(session) }; } - private async image( + private image( session: Session, - page: Page, + page: BrowserPage, scale: "css" | "device", format: ImageFormat = "png", ) { - const actual = this.pool.native - ? await browserDeadline( - page.evaluate(() => ({ - viewport: { width: innerWidth, height: innerHeight }, - density: devicePixelRatio, - })), - 3000, - "Browser viewport observation", - ) - : undefined; - // The native WebView2 capture is always PNG; only Chrome's frames change. - const encoded = - this.pool instanceof NativeBrowserPool - ? { - format: "png" as const, - data: await this.pool.capture( - session.state.taskId, - page, - scale, - actual!.viewport, - actual!.density, - ), - } - : { - format, - data: await browserDeadline( - this.rendering.capture( - session.context!, - page, - actual?.viewport ?? session.state.viewport, - actual?.density ?? session.state.deviceScaleFactor, - scale, - format, - ), - 10000, - "Browser screenshot", - ), - }; - return { - mimeType: `image/${encoded.format}` as const, - data: encoded.data, - ...(actual?.viewport ?? session.state.viewport), - }; + return session.context!.capture(page, { + scale, + format, + viewport: session.state.viewport, + density: session.state.deviceScaleFactor, + }); } private async capture( session: Session, @@ -551,7 +491,7 @@ export class AgentBrowserManager { async close(): Promise { this.closing = true; // Closing Chromium cancels pending navigation and screenshot operations. - await this.pool.close(); + await this.engine.close(); await Promise.allSettled( [...this.sessions.values()].map((session) => session.queue), ); diff --git a/runtime/browser/playwright-engine.ts b/runtime/browser/playwright-engine.ts new file mode 100644 index 0000000..3b2a781 --- /dev/null +++ b/runtime/browser/playwright-engine.ts @@ -0,0 +1,237 @@ +import type { Page, Route } from "playwright-core"; +import { browserURL, type BrowserImage } from "../../src/browser"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + CaptureRequest, + InteractionFeedback, + InteractionRequest, + SurfacePlacement, + Viewport, +} from "./engine"; +import { BrowserPool, type BrowserSession } from "./pool"; +import type { NativeBrowserPool } from "./native-pool"; +import { inspectPage, interact } from "./inspect"; +import { BrowserRendering } from "./render"; +import { browserDeadline } from "./capture"; + +/** A tab Playwright drives: headless Chrome, or WebView2 over CDP. */ +export class PlaywrightPage implements BrowserPage { + constructor(readonly raw: Page) { + raw.on("dialog", (dialog) => { + void dialog.dismiss(); + }); + raw.on("download", (download) => { + void download.cancel(); + }); + } + url() { + return this.raw.url(); + } + title() { + return this.raw.title(); + } + isClosed() { + return this.raw.isClosed(); + } + async goto(url: string) { + await this.raw.goto(url, { waitUntil: "domcontentloaded", timeout: 20000 }); + } + inspect() { + return inspectPage(this.raw); + } + onNavigated(listener: () => void) { + this.raw.on("framenavigated", (frame) => { + if (frame === this.raw.mainFrame()) listener(); + }); + } + onLoaded(listener: () => void) { + this.raw.on("domcontentloaded", () => listener()); + } + onClosed(listener: () => void) { + this.raw.on("close", () => listener()); + } +} + +function playwrightPage(page: BrowserPage): Page { + return (page as PlaywrightPage).raw; +} + +async function allowBrowserAddresses(route: Route) { + try { + browserURL(route.request().url()); + await route.continue(); + } catch { + await route.abort("blockedbyclient"); + } +} + +abstract class PlaywrightTabs implements BrowserTabs { + private wrapped = new WeakMap(); + private listener?: (page: BrowserPage, replaces?: BrowserPage) => void; + constructor(protected session: BrowserSession) { + session.onPage?.((page, replaces) => + this.listener?.(this.wrap(page), replaces && this.wrap(replaces)), + ); + } + protected wrap(page: Page): PlaywrightPage { + let wrapped = this.wrapped.get(page); + if (!wrapped) { + wrapped = new PlaywrightPage(page); + this.wrapped.set(page, wrapped); + this.adopted(page); + } + return wrapped; + } + /** Called once for every tab, including popups. */ + protected adopted(_page: Page) {} + protected announce(page: Page) { + this.listener?.(this.wrap(page)); + } + allowOnlyBrowserAddresses() { + return this.session.route("**/*", allowBrowserAddresses); + } + async newPage() { + return this.wrap(await this.session.newPage()); + } + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void) { + this.listener = listener; + } + close() { + return this.session.close(); + } + abstract interact( + page: BrowserPage, + request: InteractionRequest, + ): Promise; + abstract capture(page: BrowserPage, request: CaptureRequest): Promise; + abstract resize(page: BrowserPage, viewport: Viewport, density: number): Promise; + abstract closePage(page: BrowserPage): Promise; +} + +class HeadlessTabs extends PlaywrightTabs { + constructor( + session: BrowserSession, + private rendering: BrowserRendering, + ) { + super(session); + } + protected adopted(page: Page) { + page.on("popup", (popup) => this.announce(popup)); + } + interact(page: BrowserPage, request: InteractionRequest) { + return interact(playwrightPage(page), request.input, request.viewport); + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const data = await browserDeadline( + this.rendering.capture( + this.session, + playwrightPage(page), + request.viewport, + request.density, + request.scale, + request.format, + ), + 10000, + "Browser screenshot", + ); + return { mimeType: `image/${request.format}`, data, ...request.viewport }; + } + resize(page: BrowserPage, viewport: Viewport, density: number) { + return this.rendering.resize(this.session, playwrightPage(page), viewport, density); + } + closePage(page: BrowserPage) { + return playwrightPage(page).close(); + } +} + +/** Cards share one hidden Chrome; the human sees its frames. */ +export class HeadlessEngine implements BrowserEngine { + readonly native = false; + private rendering = new BrowserRendering(); + constructor(private pool = new BrowserPool()) {} + connected() { + return this.pool.connected(); + } + async open(viewport: Viewport, density: number, taskId: string) { + const tabs = new HeadlessTabs( + await this.pool.context(viewport, density, taskId), + this.rendering, + ); + await tabs.allowOnlyBrowserAddresses(); + return tabs; + } + async surface(_taskId: string, _page: BrowserPage | undefined, _placement: SurfacePlacement) {} + close() { + return this.pool.close(); + } +} + +class WebView2Tabs extends PlaywrightTabs { + constructor( + session: BrowserSession, + private pool: NativeBrowserPool, + private taskId: string, + ) { + super(session); + } + async interact(page: BrowserPage, request: InteractionRequest) { + const raw = playwrightPage(page), + worker = request.actor === "worker"; + if (worker) await this.pool.busy(this.taskId, raw, true); + try { + return await interact(raw, request.input, request.viewport); + } finally { + if (worker) await this.pool.busy(this.taskId, raw, false); + } + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const raw = playwrightPage(page); + const actual = await browserDeadline( + raw.evaluate(() => ({ + viewport: { width: innerWidth, height: innerHeight }, + density: devicePixelRatio, + })), + 3000, + "Browser viewport observation", + ); + // The native WebView2 capture is always PNG; only Chrome's frames change. + const data = await this.pool.capture( + this.taskId, + raw, + request.scale, + actual.viewport, + actual.density, + ); + return { mimeType: "image/png", data, ...actual.viewport }; + } + async resize() {} + closePage(page: BrowserPage) { + return this.pool.closePage(this.taskId, playwrightPage(page)); + } +} + +/** Windows: each card's tab is a WebView2 over the card that Playwright drives over CDP. */ +export class WebView2Engine implements BrowserEngine { + readonly native = true; + constructor(private pool: NativeBrowserPool) {} + connected() { + return this.pool.connected(); + } + async open(viewport: Viewport, density: number, taskId: string) { + const tabs = new WebView2Tabs( + await this.pool.context(viewport, density, taskId), + this.pool, + taskId, + ); + await tabs.allowOnlyBrowserAddresses(); + return tabs; + } + surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement) { + return this.pool.surface(taskId, page && playwrightPage(page), { ...placement }); + } + close() { + return this.pool.close(); + } +} diff --git a/runtime/browser/render.ts b/runtime/browser/render.ts index 00e444f..2806550 100644 --- a/runtime/browser/render.ts +++ b/runtime/browser/render.ts @@ -1,7 +1,7 @@ import type { CDPSession, Page } from "playwright-core"; import type { BrowserSession } from "./pool"; +import type { ImageFormat } from "./engine"; -export type ImageFormat = "png" | "jpeg"; // At Retina density Chrome encodes this 2-3x faster than PNG at about a third // of the size; 90 approaches PNG size on text-heavy pages. const JPEG_QUALITY = 85; diff --git a/tests/browser-capture.test.ts b/tests/browser-capture.test.ts index 6bfbd2a..a21ebc4 100644 --- a/tests/browser-capture.test.ts +++ b/tests/browser-capture.test.ts @@ -74,7 +74,7 @@ test( await mkdtemp(join(tmpdir(), "memcode-capture-test-")), async () => {}, ); - const rendering = (manager as any).rendering, + const rendering = (manager as any).engine.rendering, original = rendering.capture.bind(rendering); try { await manager.execute(task.id, { @@ -122,7 +122,7 @@ const stripedPage = `${bands function selectedPage(manager: AgentBrowserManager, taskId: string): Page { const session = (manager as any).sessions.get(taskId); - return session.pages.get(session.selected); + return session.pages.get(session.selected).raw; } /** Decodes a frame in the browser and names the colour at its top and bottom edge. */ From aff33eac5e586a950507452953a8b561ce488851 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:43:07 +0100 Subject: [PATCH 5/7] feat: show a real WebKit page in the Mac card's Browser tab [skip ci] On macOS 14 and later a card's Browser tab is now a WKWebView placed over the card, like the WebView2 surface on Windows, instead of JPEG frames from headless Chrome. Google and other sites see an ordinary WebKit browser, and scrolling is native. - One WebKit data store per card, kept between launches. - Guest pages get no bridge; MemCode's scripts run in their own content world. Plaintext only reaches this machine (content rules plus the navigation check). Camera, microphone and downloads are refused. - The human's own clicks, keys and scrolling are seen by an AppKit event monitor, so taking control from a worker needs no timing guess. - Address bar, tabs, back/forward/reload and page-opened windows work. Worker click/type/scroll on the Mac come in the next commit. macOS 13 keeps the headless Chrome frames. Windows is unchanged. Co-Authored-By: Claude Opus 5.5 --- runtime/browser/engine-choice.ts | 20 ++ runtime/browser/engine.ts | 2 + runtime/browser/manager.ts | 13 +- runtime/browser/playwright-engine.ts | 2 + runtime/browser/webkit-driver.ts | 57 ++++ runtime/browser/webkit-engine.ts | 261 ++++++++++++++++ src-tauri/Cargo.lock | 8 + src-tauri/Cargo.toml | 8 + src-tauri/src/browser.rs | 12 +- src-tauri/src/browser/macos/address_policy.rs | 127 ++++++++ src-tauri/src/browser/macos/capture.rs | 74 +++++ src-tauri/src/browser/macos/human_input.rs | 82 +++++ src-tauri/src/browser/macos/input.rs | 164 ++++++++++ src-tauri/src/browser/macos/mod.rs | 38 +++ src-tauri/src/browser/macos/script.rs | 67 ++++ src-tauri/src/browser/macos/surface.rs | 292 ++++++++++++++++++ tests/support/fake-webkit-host.ts | 137 ++++++++ tests/webkit-browser.test.ts | 164 ++++++++++ 18 files changed, 1517 insertions(+), 11 deletions(-) create mode 100644 runtime/browser/engine-choice.ts create mode 100644 runtime/browser/webkit-driver.ts create mode 100644 runtime/browser/webkit-engine.ts create mode 100644 src-tauri/src/browser/macos/address_policy.rs create mode 100644 src-tauri/src/browser/macos/capture.rs create mode 100644 src-tauri/src/browser/macos/human_input.rs create mode 100644 src-tauri/src/browser/macos/input.rs create mode 100644 src-tauri/src/browser/macos/mod.rs create mode 100644 src-tauri/src/browser/macos/script.rs create mode 100644 src-tauri/src/browser/macos/surface.rs create mode 100644 tests/support/fake-webkit-host.ts create mode 100644 tests/webkit-browser.test.ts diff --git a/runtime/browser/engine-choice.ts b/runtime/browser/engine-choice.ts new file mode 100644 index 0000000..6bd8eec --- /dev/null +++ b/runtime/browser/engine-choice.ts @@ -0,0 +1,20 @@ +import { release as osRelease } from "node:os"; +import type { NativeHost } from "../host"; +import type { BrowserEngine } from "./engine"; +import { NativeBrowserPool } from "./native-pool"; +import { HeadlessEngine, WebView2Engine } from "./playwright-engine"; +import { WebKitEngine } from "./webkit-engine"; + +/** Darwin 23 is macOS 14, the first with a WebKit data store per card. */ +const FIRST_NATIVE_DARWIN = 23; + +export function browserEngineFor( + host?: NativeHost, + platform: NodeJS.Platform = process.platform, + release = osRelease(), +): BrowserEngine { + if (host && platform === "win32") return new WebView2Engine(new NativeBrowserPool(host)); + if (host && platform === "darwin" && Number.parseInt(release, 10) >= FIRST_NATIVE_DARWIN) + return new WebKitEngine(host); + return new HeadlessEngine(); +} diff --git a/runtime/browser/engine.ts b/runtime/browser/engine.ts index d970330..40a8053 100644 --- a/runtime/browser/engine.ts +++ b/runtime/browser/engine.ts @@ -42,6 +42,8 @@ export interface BrowserPage { /** A card's browser: its own storage, its tabs and the popups they open. */ export interface BrowserTabs { + /** Brings page state up to date for engines that have to ask for it. */ + sync(): Promise; newPage(): Promise; onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void): void; interact(page: BrowserPage, request: InteractionRequest): Promise; diff --git a/runtime/browser/manager.ts b/runtime/browser/manager.ts index e98124c..9dcac2c 100644 --- a/runtime/browser/manager.ts +++ b/runtime/browser/manager.ts @@ -10,7 +10,6 @@ import { type WorkerBrowserState, } from "../../src/browser"; import { within, now } from "../local"; -import { NativeBrowserPool } from "./native-pool"; import type { NativeHost } from "../host"; import { browserDeadline } from "./capture"; import type { @@ -19,7 +18,7 @@ import type { BrowserTabs, ImageFormat, } from "./engine"; -import { HeadlessEngine, WebView2Engine } from "./playwright-engine"; +import { browserEngineFor } from "./engine-choice"; interface Session { state: WorkerBrowserState; @@ -35,19 +34,14 @@ interface Session { export class AgentBrowserManager { private closing = false; private sessions = new Map(); - private engine: BrowserEngine; constructor( private state: () => AppState, private dataDir: string, private changed: () => Promise, private maxContexts = 16, host?: NativeHost, - ) { - this.engine = - host && process.platform === "win32" - ? new WebView2Engine(new NativeBrowserPool(host)) - : new HeadlessEngine(); - } + private engine: BrowserEngine = browserEngineFor(host), + ) {} private session(taskId: string): Session { if (!this.state().tasks.some((task) => task.id === taskId)) throw Error("Work item not found."); @@ -256,6 +250,7 @@ export class AgentBrowserManager { request: BrowserRequest, actor: "user" | "worker", ): Promise { + await session.context?.sync(); const observing = ["state", "frame", "observe"].includes(request.action); if (actor === "worker" && !observing && session.state.control === "user") throw Error( diff --git a/runtime/browser/playwright-engine.ts b/runtime/browser/playwright-engine.ts index 3b2a781..75e54a6 100644 --- a/runtime/browser/playwright-engine.ts +++ b/runtime/browser/playwright-engine.ts @@ -89,6 +89,8 @@ abstract class PlaywrightTabs implements BrowserTabs { protected announce(page: Page) { this.listener?.(this.wrap(page)); } + /** Playwright reports page changes as events, so there is nothing to fetch. */ + async sync() {} allowOnlyBrowserAddresses() { return this.session.route("**/*", allowBrowserAddresses); } diff --git a/runtime/browser/webkit-driver.ts b/runtime/browser/webkit-driver.ts new file mode 100644 index 0000000..b3f84fa --- /dev/null +++ b/runtime/browser/webkit-driver.ts @@ -0,0 +1,57 @@ +import type { InteractionFeedback, InteractionRequest } from "./engine"; + +export type NativeInput = + | { kind: "click" | "move"; x: number; y: number } + | { kind: "wheel"; x: number; y: number; deltaY: number } + | { kind: "key"; key: string } + | { kind: "text"; text: string }; + +/** What the WebKit driver needs from one native tab. */ +export interface NativeScripts { + url(): string; + title(): Promise; + /** Runs an async function body in MemCode's content world; it returns text. */ + run(script: string): Promise; + input(input: NativeInput): Promise; + travel(action: "back" | "forward" | "reload"): Promise; +} + +const MAX_OBSERVATION = 18000; + +/** Same refs and wording as `inspectPage`, so a worker sees one format everywhere. */ +const TAG_CONTROLS = ` +for (const node of document.querySelectorAll("[data-memcode-ref]")) + node.removeAttribute("data-memcode-ref"); +const nodes = [...document.querySelectorAll( + "a,button,input,textarea,select,[role=button],[contenteditable=true]", +)] + .filter((node) => node.getClientRects().length && getComputedStyle(node).visibility !== "hidden") + .slice(0, 100); +return nodes + .map((node, index) => { + const ref = "m" + (index + 1); + node.setAttribute("data-memcode-ref", ref); + return (ref + ": " + node.tagName.toLowerCase() + " " + (node.getAttribute("aria-label") || node.innerText || node.getAttribute("placeholder") || node.getAttribute("name") || "")).slice(0, 220); + }) + .join("\\n"); +`; + +export async function inspectNativePage(page: NativeScripts): Promise { + const references = await page.run(TAG_CONTROLS); + return `URL: ${page.url()}\nTitle: ${await page.title()}\n\nVisible controls (use ref for actions):\n${references}`.slice( + 0, + MAX_OBSERVATION, + ); +} + +export async function interactNatively( + page: NativeScripts, + request: InteractionRequest, +): Promise { + const action = request.input.action; + if (action === "back" || action === "forward" || action === "reload") { + await page.travel(action); + return {}; + } + throw Error(`The Mac browser cannot ${action} for a worker yet.`); +} diff --git a/runtime/browser/webkit-engine.ts b/runtime/browser/webkit-engine.ts new file mode 100644 index 0000000..1a19715 --- /dev/null +++ b/runtime/browser/webkit-engine.ts @@ -0,0 +1,261 @@ +import { createHash } from "node:crypto"; +import type { BrowserImage } from "../../src/browser"; +import type { NativeHost } from "../host"; +import type { + BrowserEngine, + BrowserPage, + BrowserTabs, + CaptureRequest, + InteractionFeedback, + InteractionRequest, + SurfacePlacement, +} from "./engine"; +import { inspectNativePage, interactNatively, type NativeScripts } from "./webkit-driver"; + +/** What `src-tauri/src/browser/macos` reports for each surface of a card. */ +interface NativePageState { + nativeId: string; + opener: string | null; + url: string; + title: string; + loading: boolean; + loads: number; +} + +/** WebKit tells MemCode nothing on its own, so the runtime asks this often. */ +const REFRESH_MS = 300; +const NAVIGATION_TIMEOUT_MS = 20000; +const NAVIGATION_POLL_MS = 80; +const HISTORY_QUIET_MS = 1500; + +/** A stable WebKit data store per card, unrelated to any other card's. */ +function cardProfile(taskId: string) { + return "worker-" + createHash("sha256").update(taskId).digest("hex"); +} + +class WebKitPage implements BrowserPage { + private current: Omit = { + url: "about:blank", + title: "", + loading: false, + loads: 0, + }; + private closed = false; + private navigated: Array<() => void> = []; + private loaded: Array<() => void> = []; + private closing: Array<() => void> = []; + constructor( + readonly nativeId: string, + private tabs: WebKitTabs, + ) {} + url() { + return this.current.url; + } + async title() { + return this.current.title; + } + isClosed() { + return this.closed; + } + async goto(url: string) { + const before = this.current.loads; + await this.tabs.call("browser_navigate", { nativeId: this.nativeId, url }); + await this.settle(before); + } + /** Back, forward and reload: the page moves on its own once WebKit has it. */ + async travel(action: "back" | "forward" | "reload") { + const before = this.current.loads; + await this.tabs.call("browser_history", { nativeId: this.nativeId, action }); + await this.settle(before, false); + } + inspect() { + return inspectNativePage(this.scripts()); + } + scripts(): NativeScripts { + return { + url: () => this.url(), + title: () => this.title(), + run: (script) => + this.tabs.call("browser_eval", { nativeId: this.nativeId, script }), + input: (input) => this.tabs.call("browser_input", { nativeId: this.nativeId, input }), + travel: (action) => this.travel(action), + }; + } + onNavigated(listener: () => void) { + this.navigated.push(listener); + } + onLoaded(listener: () => void) { + this.loaded.push(listener); + } + onClosed(listener: () => void) { + this.closing.push(listener); + } + update(next: NativePageState) { + const previous = this.current; + this.current = { url: next.url, title: next.title, loading: next.loading, loads: next.loads }; + if (next.loads !== previous.loads || next.url !== previous.url) + for (const listener of this.navigated) listener(); + if (next.title !== previous.title || (previous.loading && !next.loading)) + for (const listener of this.loaded) listener(); + } + markClosed() { + if (this.closed) return; + this.closed = true; + for (const listener of this.closing) listener(); + } + /** + * Waits until a new document has committed and stopped loading. A navigation + * that stops without committing failed (no network, refused address). Back or + * forward with no history does nothing, so those give up quietly. + */ + private async settle(before: number, expectNavigation = true) { + const started = Date.now(); + let loading = false; + for (;;) { + await this.tabs.sync(); + if (this.closed) throw Error("The browser tab closed."); + loading ||= this.current.loading; + const committed = this.current.loads > before, + elapsed = Date.now() - started; + if (committed && !this.current.loading) return; + if (loading && !committed && !this.current.loading) + throw Error("The page could not be opened."); + if (!expectNavigation && !loading && !committed && elapsed > HISTORY_QUIET_MS) return; + if (elapsed > NAVIGATION_TIMEOUT_MS) { + if (committed) return; + throw Error("The page took too long to open."); + } + await new Promise((resolve) => setTimeout(resolve, NAVIGATION_POLL_MS)); + } + } +} + +function webkitPage(page: BrowserPage): WebKitPage { + return page as WebKitPage; +} + +class WebKitTabs implements BrowserTabs { + private pages = new Map(); + private listener?: (page: BrowserPage, replaces?: BrowserPage) => void; + private timer?: NodeJS.Timeout; + private refreshing?: Promise; + private stopped = false; + constructor( + private host: NativeHost, + private taskId: string, + ) {} + call(method: string, input: Record = {}) { + return this.host.call(method, { taskId: this.taskId, ...input }); + } + async newPage() { + const { nativeId } = await this.call<{ nativeId: string }>("browser_create", { + profile: cardProfile(this.taskId), + }); + const page = new WebKitPage(nativeId, this); + this.pages.set(nativeId, page); + this.watch(); + return page; + } + onPage(listener: (page: BrowserPage, replaces?: BrowserPage) => void) { + this.listener = listener; + } + /** One refresh at a time; callers that arrive meanwhile share it. */ + sync() { + this.refreshing ??= this.refresh().finally(() => { + this.refreshing = undefined; + }); + return this.refreshing; + } + async interact(page: BrowserPage, request: InteractionRequest): Promise { + return interactNatively(webkitPage(page).scripts(), request); + } + async capture(page: BrowserPage, request: CaptureRequest): Promise { + const image = await this.call<{ data: string; width: number; height: number }>( + "browser_capture", + { nativeId: webkitPage(page).nativeId, scale: request.scale, format: request.format }, + ); + return { + mimeType: `image/${request.format}`, + data: image.data, + width: Math.round(image.width), + height: Math.round(image.height), + }; + } + async resize() {} + async closePage(page: BrowserPage) { + const native = webkitPage(page); + await this.call("browser_close", { nativeId: native.nativeId }); + this.pages.delete(native.nativeId); + native.markClosed(); + } + async close() { + this.stop(); + await this.call("browser_close_task"); + for (const page of this.pages.values()) page.markClosed(); + this.pages.clear(); + } + stop() { + this.stopped = true; + clearInterval(this.timer); + } + private watch() { + if (this.timer || this.stopped) return; + this.timer = setInterval(() => void this.sync().catch(() => {}), REFRESH_MS); + this.timer.unref?.(); + } + private async refresh() { + if (this.stopped) return; + const states = await this.call("browser_pages"); + const present = new Set(); + for (const state of states) { + present.add(state.nativeId); + this.adopt(state)?.update(state); + } + for (const [nativeId, page] of this.pages) + if (!present.has(nativeId)) { + this.pages.delete(nativeId); + page.markClosed(); + } + } + /** Known tabs, plus windows a page opened; a tab still being created waits. */ + private adopt(state: NativePageState) { + const known = this.pages.get(state.nativeId); + if (known || !state.opener) return known; + const popup = new WebKitPage(state.nativeId, this); + this.pages.set(state.nativeId, popup); + this.listener?.(popup); + return popup; + } +} + +/** macOS: each card's tab is a real WKWebView over the card. */ +export class WebKitEngine implements BrowserEngine { + readonly native = true; + private cards = new Set(); + constructor(private host: NativeHost) {} + connected() { + return true; + } + async open(_viewport: unknown, _density: number, taskId: string) { + const tabs = new WebKitTabs(this.host, taskId); + this.cards.add(tabs); + return tabs; + } + async surface(taskId: string, page: BrowserPage | undefined, placement: SurfacePlacement) { + if (!page) { + await this.host.call("browser_hide_all"); + return; + } + await this.host.call("browser_surface", { + taskId, + nativeId: webkitPage(page).nativeId, + ...placement, + }); + } + async close() { + const allocated = this.cards.size > 0; + for (const card of this.cards) card.stop(); + this.cards.clear(); + if (allocated) await this.host.call("browser_close_all"); + } +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 0917fc0..b271670 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2353,10 +2353,17 @@ name = "memcode" version = "0.4.0-beta.20" dependencies = [ "base64 0.23.1", + "block2", "core-foundation 0.10.1", "dunce", "image", "keyring", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "objc2-web-kit", "portable-pty", "rfd", "security-framework", @@ -2636,6 +2643,7 @@ dependencies = [ "block2", "objc2", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation", "objc2-quartz-core", "objc2-uniform-type-identifiers", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1f45cc5..9fea334 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -38,6 +38,14 @@ windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Grap [target.'cfg(target_os = "macos")'.dependencies] security-framework = "=3.7.0" core-foundation = "=0.10.1" +wry = "=0.57.2" +objc2 = "=0.6.5" +block2 = "=0.6.2" +objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-core-foundation", "NSString", "NSError", "NSData", "NSDictionary", "NSValue", "NSProcessInfo", "NSGeometry", "NSRange", "NSObjCRuntime", "NSURL", "NSArray"] } +objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-core-graphics", "NSEvent", "NSView", "NSResponder", "NSWindow", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSGraphicsContext", "NSScreen", "NSTextInputClient"] } +objc2-web-kit = { version = "=0.3.2", default-features = false, features = ["std", "block2", "objc2-app-kit", "objc2-core-foundation", "WKWebView", "WKWebViewConfiguration", "WKContentWorld", "WKFrameInfo", "WKSnapshotConfiguration", "WKContentRuleList", "WKContentRuleListStore", "WKUserContentController", "WKNavigation"] } +objc2-core-graphics = { version = "=0.3.2", default-features = false, features = ["std", "CGEvent", "CGEventTypes", "CGRemoteOperation"] } +objc2-core-foundation = { version = "=0.3.2", default-features = false, features = ["std", "CFCGTypes"] } [profile.release] codegen-units = 1 diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index c892f05..5946c65 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -1,4 +1,5 @@ //! Native browser surfaces. Guest pages receive no Tauri bridge or application RPC. +//! Windows: WebView2 driven over CDP. macOS: WKWebView driven natively (`browser/macos`). use serde_json::{json, Value}; use tauri::{AppHandle, Emitter, Manager}; @@ -479,14 +480,21 @@ mod windows { .map_err(|_| "Native browser operation closed")? } } +#[cfg(target_os = "macos")] +mod macos; + pub async fn call(app: AppHandle, method: &str, input: Value) -> Result { #[cfg(windows)] { windows::call(app, method.to_owned(), input).await } - #[cfg(not(windows))] + #[cfg(target_os = "macos")] + { + macos::call(app, method.to_owned(), input).await + } + #[cfg(not(any(windows, target_os = "macos")))] { let _ = (app, method, input); - Err("The shared native browser currently requires Windows WebView2".into()) + Err("The shared native browser requires Windows WebView2 or macOS WebKit".into()) } } diff --git a/src-tauri/src/browser/macos/address_policy.rs b/src-tauri/src/browser/macos/address_policy.rs new file mode 100644 index 0000000..8c157cb --- /dev/null +++ b/src-tauri/src/browser/macos/address_policy.rs @@ -0,0 +1,127 @@ +//! Which addresses a card page may reach, and the WebKit storage each card gets. +use std::cell::RefCell; + +use block2::RcBlock; +use objc2::{rc::Retained, MainThreadMarker}; +use objc2_foundation::{NSError, NSString}; +use objc2_web_kit::{WKContentRuleList, WKContentRuleListStore}; + +const RULES_IDENTIFIER: &str = "memcode-card-address-policy-1"; +/// Same rule as `browserURL` and the Playwright route: plaintext only to this machine. +/// WebKit's content-blocker patterns have no alternation, so each local host gets a rule. +const RULES: &str = r#"[ + {"trigger": {"url-filter": "^http:"}, "action": {"type": "block"}}, + {"trigger": {"url-filter": "^http://localhost[:/]"}, "action": {"type": "ignore-previous-rules"}}, + {"trigger": {"url-filter": "^http://127\\.0\\.0\\.1[:/]"}, "action": {"type": "ignore-previous-rules"}}, + {"trigger": {"url-filter": "^http://\\[::1\\][:/]"}, "action": {"type": "ignore-previous-rules"}} +]"#; +const PRIVILEGED_HOSTS: [&str; 3] = ["tauri.localhost", "ipc.localhost", "asset.localhost"]; +const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "[::1]", "::1"]; + +thread_local! { + static COMPILED: RefCell>> = const { RefCell::new(None) }; +} + +/// Every navigation, main frame or subframe. Frames also load `about:` and in-page +/// `blob:`/`data:` documents, which never leave the page's own origin. +pub(super) fn navigable(value: &str) -> bool { + if value.is_empty() + || value.starts_with("about:blank") + || value == "about:srcdoc" + || value.starts_with("blob:") + || value.starts_with("data:") + { + return true; + } + let Ok(url) = tauri::Url::parse(value) else { + return false; + }; + let host = url.host_str().unwrap_or(""); + let local_plaintext = url.scheme() == "http" && LOCAL_HOSTS.contains(&host); + !PRIVILEGED_HOSTS.contains(&host) + && url.username().is_empty() + && url.password().is_none() + && (url.scheme() == "https" || local_plaintext) +} + +/// The runtime names a card's profile `worker-`; WebKit wants 16 bytes. +pub(super) fn store_identifier(profile: &str) -> Result<[u8; 16], String> { + let invalid = || "Invalid browser profile".to_string(); + let hex = profile.strip_prefix("worker-").ok_or_else(invalid)?; + if hex.len() < 32 || hex.len() > 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) { + return Err(invalid()); + } + let mut identifier = [0u8; 16]; + for (index, byte) in identifier.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16).map_err(|_| invalid())?; + } + Ok(identifier) +} + +/// Compiles the content rules once, then hands them to `then` on the main thread. +pub(super) fn with_rules(then: impl FnOnce(Result, String>) + 'static) { + if let Some(rules) = COMPILED.with(|compiled| compiled.borrow().clone()) { + return then(Ok(rules)); + } + let Some(store) = MainThreadMarker::new().and_then(|mtm| unsafe { WKContentRuleListStore::defaultStore(mtm) }) else { + return then(Err("WebKit content rules are unavailable".into())); + }; + let then = RefCell::new(Some(then)); + let compiled = RcBlock::new(move |list: *mut WKContentRuleList, error: *mut NSError| { + let Some(then) = then.borrow_mut().take() else { + return; + }; + if list.is_null() { + let reason = if error.is_null() { + "unknown error".to_string() + } else { + unsafe { &*error }.localizedDescription().to_string() + }; + return then(Err(format!("Could not prepare the browser address policy: {reason}"))); + } + let rules = unsafe { Retained::retain(list) }.expect("compiled rule list"); + COMPILED.with(|compiled| *compiled.borrow_mut() = Some(rules.clone())); + then(Ok(rules)); + }); + unsafe { + store.compileContentRuleListForIdentifier_encodedContentRuleList_completionHandler( + Some(&NSString::from_str(RULES_IDENTIFIER)), + Some(&NSString::from_str(RULES)), + Some(&compiled), + ) + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pages_reach_https_and_this_machine_but_not_remote_plaintext_or_the_app() { + assert!(navigable("https://www.google.com/search?q=x")); + assert!(navigable("http://localhost:5173/")); + assert!(navigable("http://127.0.0.1:8080/x")); + assert!(navigable("http://[::1]:3000/")); + assert!(navigable("about:blank")); + assert!(navigable("about:srcdoc")); + assert!(!navigable("http://example.com/")); + assert!(!navigable("http://localhost.:3000/")); + assert!(!navigable("ftp://example.com/")); + assert!(!navigable("file:///etc/hosts")); + assert!(!navigable("tauri://localhost/index.html")); + assert!(!navigable("https://tauri.localhost/")); + assert!(!navigable("https://user:secret@example.com/")); + } + + #[test] + fn a_card_profile_becomes_a_stable_webkit_store_identifier() { + let profile = "worker-00112233445566778899aabbccddeeff0123456789"; + let identifier = store_identifier(profile).unwrap(); + assert_eq!(identifier[0], 0x00); + assert_eq!(identifier[15], 0xff); + assert_eq!(identifier, store_identifier(profile).unwrap()); + assert!(store_identifier("worker-short").is_err()); + assert!(store_identifier("../worker-00112233445566778899aabbccddeeff").is_err()); + assert!(store_identifier("worker-zz112233445566778899aabbccddeeff").is_err()); + } +} diff --git a/src-tauri/src/browser/macos/capture.rs b/src-tauri/src/browser/macos/capture.rs new file mode 100644 index 0000000..397e63f --- /dev/null +++ b/src-tauri/src/browser/macos/capture.rs @@ -0,0 +1,74 @@ +//! Pictures of a card's page from WebKit itself, visible or hidden. +use std::cell::RefCell; + +use base64::Engine; +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject, MainThreadMarker}; +use objc2_app_kit::{NSBitmapImageFileType, NSBitmapImageRep, NSImage, NSImageCompressionFactor, NSView}; +use objc2_foundation::{NSDictionary, NSError, NSNumber}; +use objc2_web_kit::{WKSnapshotConfiguration, WKWebView}; +use serde_json::{json, Value}; + +use super::{surface::{owned, SURFACES}, Reply}; + +/// At Retina density JPEG keeps text readable at about a tenth of PNG's size. +const JPEG_QUALITY: f64 = 0.85; + +pub(super) fn capture(input: &Value, reply: Reply) { + let wk = SURFACES.with(|surfaces| -> Result, String> { + Ok(owned(&mut surfaces.borrow_mut(), input)?.wk.clone()) + }); + let wk = match wk { + Ok(wk) => wk, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + let jpeg = input["format"] == "jpeg"; + let css = input["scale"] == "css"; + let Some(mtm) = MainThreadMarker::new() else { + let _ = reply.send(Err("Browser capture must run on the main thread".into())); + return; + }; + let view: &NSView = &wk; + let size = view.bounds().size; + let backing = view.window().map(|window| window.backingScaleFactor()).unwrap_or(1.0); + let configuration = unsafe { WKSnapshotConfiguration::new(mtm) }; + if css { + // The snapshot width is in points and WebKit renders it at the screen's density. + let width = NSNumber::new_f64(size.width / backing); + unsafe { configuration.setSnapshotWidth(Some(&width)) }; + } + let reply = RefCell::new(Some(reply)); + let taken = RcBlock::new(move |image: *mut NSImage, error: *mut NSError| { + let Some(reply) = reply.borrow_mut().take() else { + return; + }; + let encoded = encode(image, error, jpeg).map(|data| { + json!({ "data": data, "width": size.width, "height": size.height }) + }); + let _ = reply.send(encoded); + }); + unsafe { wk.takeSnapshotWithConfiguration_completionHandler(Some(&configuration), &taken) }; +} + +fn encode(image: *mut NSImage, error: *mut NSError, jpeg: bool) -> Result { + if image.is_null() { + return Err(if error.is_null() { + "The browser returned no image".into() + } else { + unsafe { &*error }.localizedDescription().to_string() + }); + } + let image = unsafe { &*image }; + let tiff = image.TIFFRepresentation().ok_or("The browser image could not be read")?; + let bitmap = NSBitmapImageRep::imageRepWithData(&tiff).ok_or("The browser image could not be read")?; + let quality = NSNumber::new_f64(JPEG_QUALITY); + let quality: &AnyObject = &quality; + let properties = NSDictionary::from_slices(&[unsafe { NSImageCompressionFactor }], &[quality]); + let kind = if jpeg { NSBitmapImageFileType::JPEG } else { NSBitmapImageFileType::PNG }; + let data = unsafe { bitmap.representationUsingType_properties(kind, &properties) } + .ok_or("The browser image could not be encoded")?; + Ok(base64::engine::general_purpose::STANDARD.encode(data.to_vec())) +} diff --git a/src-tauri/src/browser/macos/human_input.rs b/src-tauri/src/browser/macos/human_input.rs new file mode 100644 index 0000000..c928326 --- /dev/null +++ b/src-tauri/src/browser/macos/human_input.rs @@ -0,0 +1,82 @@ +//! Notices the human's own clicks, keys and scrolling in a card surface. +//! +//! Real input passes through `NSApplication.sendEvent`, where local monitors run. +//! Worker input is handed straight to the WKWebView, so it never shows up here and +//! no time-window guess is needed to tell the two apart. +use std::{cell::RefCell, ptr::NonNull}; + +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject}; +use objc2_app_kit::{NSEvent, NSEventMask, NSEventType, NSView}; +use serde_json::json; +use tauri::{AppHandle, Emitter}; + +use super::surface::{Surface, SURFACES}; + +thread_local! { + static MONITOR: RefCell>> = const { RefCell::new(None) }; +} + +pub(super) fn watch(app: &AppHandle) { + MONITOR.with(|monitor| { + if monitor.borrow().is_some() { + return; + } + let app = app.clone(); + let seen = RcBlock::new(move |event: NonNull| -> *mut NSEvent { + if let Some(owner) = receiving_owner(unsafe { event.as_ref() }) { + let _ = app.emit_to( + tauri::EventTarget::Webview { label: "main".into() }, + "browser:native-input", + json!({ "taskId": owner, "at": millis() }), + ); + } + event.as_ptr() + }); + let mask = NSEventMask::LeftMouseDown + | NSEventMask::RightMouseDown + | NSEventMask::OtherMouseDown + | NSEventMask::KeyDown + | NSEventMask::ScrollWheel; + *monitor.borrow_mut() = + unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(mask, &seen) }; + }); +} + +fn millis() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 +} + +fn receiving_owner(event: &NSEvent) -> Option { + SURFACES.with(|surfaces| { + let surfaces = surfaces.try_borrow().ok()?; + surfaces + .values() + .find(|surface| receives(surface, event)) + .map(|surface| surface.owner.clone()) + }) +} + +fn receives(surface: &Surface, event: &NSEvent) -> bool { + let view: &NSView = &surface.wk; + let Some(window) = view.window() else { + return false; + }; + if view.isHiddenOrHasHiddenAncestor() || event.windowNumber() != window.windowNumber() { + return false; + } + if event.r#type() == NSEventType::KeyDown { + return window.firstResponder().is_some_and(|responder| { + let responder: &AnyObject = &responder; + responder + .downcast_ref::() + .is_some_and(|responder| responder.isDescendantOf(view)) + }); + } + let point = view.convertPoint_fromView(event.locationInWindow(), None); + let bounds = view.bounds(); + point.x >= 0.0 && point.y >= 0.0 && point.x <= bounds.size.width && point.y <= bounds.size.height +} diff --git a/src-tauri/src/browser/macos/input.rs b/src-tauri/src/browser/macos/input.rs new file mode 100644 index 0000000..cb706fb --- /dev/null +++ b/src-tauri/src/browser/macos/input.rs @@ -0,0 +1,164 @@ +//! The worker's mouse, wheel and keyboard input, handed straight to a card's WKWebView. +//! WebKit delivers these to the page as trusted events at the given CSS point. +use objc2::{msg_send, rc::Retained, MainThreadMarker}; +use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType, NSScreen, NSView}; +use objc2_core_foundation::CGPoint; +use objc2_core_graphics::{CGEvent, CGScrollEventUnit}; +use objc2_foundation::{NSNotFound, NSPoint, NSProcessInfo, NSRange, NSString}; +use objc2_web_kit::WKWebView; +use serde_json::Value; + +const MAX_SCROLL: f64 = 4000.0; + +struct Key { + code: u16, + characters: &'static str, + ignoring: &'static str, + flags: NSEventModifierFlags, +} + +pub(super) fn deliver(wk: &WKWebView, input: &Value) -> Result<(), String> { + let point = || -> Result { + let x = input["x"].as_f64().ok_or("Missing x")?; + let y = input["y"].as_f64().ok_or("Missing y")?; + Ok(window_point(wk, x, y)) + }; + match input["kind"].as_str() { + Some("click") => click(wk, point()?)?, + Some("move") => { + let moved = mouse(wk, NSEventType::MouseMoved, point()?, 0)?; + wk.mouseMoved(&moved) + } + Some("wheel") => { + let delta = input["deltaY"].as_f64().unwrap_or(600.0).clamp(-MAX_SCROLL, MAX_SCROLL); + wheel(wk, point()?, delta)? + } + Some("key") => press(wk, input["key"].as_str().ok_or("Missing key")?)?, + Some("text") => insert_text(wk, input["text"].as_str().ok_or("Missing text")?), + _ => return Err("Unknown browser input".into()), + } + Ok(()) +} + +/// A CSS point in the page, as AppKit window coordinates. WKWebView is flipped. +fn window_point(wk: &WKWebView, x: f64, y: f64) -> NSPoint { + let view: &NSView = wk; + let local = if view.isFlipped() { + NSPoint::new(x, y) + } else { + NSPoint::new(x, view.bounds().size.height - y) + }; + view.convertPoint_toView(local, None) +} + +fn window_number(wk: &WKWebView) -> Result { + Ok(wk.window().ok_or("The card browser is not in a window")?.windowNumber()) +} + +fn uptime() -> f64 { + NSProcessInfo::processInfo().systemUptime() +} + +fn mouse(wk: &WKWebView, kind: NSEventType, at: NSPoint, clicks: isize) -> Result, String> { + NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure( + kind, + at, + NSEventModifierFlags::empty(), + uptime(), + window_number(wk)?, + None, + 0, + clicks, + 1.0, + ) + .ok_or_else(|| "Could not create a mouse event".into()) +} + +fn click(wk: &WKWebView, at: NSPoint) -> Result<(), String> { + let (moved, down, up) = ( + mouse(wk, NSEventType::MouseMoved, at, 0)?, + mouse(wk, NSEventType::LeftMouseDown, at, 1)?, + mouse(wk, NSEventType::LeftMouseUp, at, 1)?, + ); + wk.mouseMoved(&moved); + wk.mouseDown(&down); + wk.mouseUp(&up); + Ok(()) +} + +/// With no window attached, NSEvent reports a CG event's flipped location as its +/// window location, which is what WebKit hit-tests against. +fn wheel(wk: &WKWebView, at: NSPoint, delta_y: f64) -> Result<(), String> { + let mtm = MainThreadMarker::new().ok_or("Browser input must run on the main thread")?; + let primary = NSScreen::screens(mtm).firstObject().ok_or("No screen")?.frame(); + let event = CGEvent::new_scroll_wheel_event2(None, CGScrollEventUnit::Pixel, 1, -delta_y.round() as i32, 0, 0) + .ok_or("Could not create a scroll event")?; + CGEvent::set_location(Some(&event), CGPoint { x: at.x, y: primary.size.height - at.y }); + let event = NSEvent::eventWithCGEvent(&event).ok_or("Could not create a scroll event")?; + wk.scrollWheel(&event); + Ok(()) +} + +fn key(name: &str) -> Option { + let plain = NSEventModifierFlags::empty(); + let function = NSEventModifierFlags::Function; + let arrow = NSEventModifierFlags::Function | NSEventModifierFlags::NumericPad; + let key = |code, characters, ignoring, flags| Key { code, characters, ignoring, flags }; + Some(match name { + "Enter" => key(36, "\r", "\r", plain), + "Tab" => key(48, "\t", "\t", plain), + "Shift+Tab" => key(48, "\u{19}", "\u{19}", NSEventModifierFlags::Shift), + "Escape" => key(53, "\u{1b}", "\u{1b}", plain), + "Backspace" => key(51, "\u{7f}", "\u{7f}", plain), + "Delete" => key(117, "\u{f728}", "\u{f728}", function), + "ArrowLeft" => key(123, "\u{f702}", "\u{f702}", arrow), + "ArrowRight" => key(124, "\u{f703}", "\u{f703}", arrow), + "ArrowUp" => key(126, "\u{f700}", "\u{f700}", arrow), + "ArrowDown" => key(125, "\u{f701}", "\u{f701}", arrow), + "Home" => key(115, "\u{f729}", "\u{f729}", function), + "End" => key(119, "\u{f72b}", "\u{f72b}", function), + "PageUp" => key(116, "\u{f72c}", "\u{f72c}", function), + "PageDown" => key(121, "\u{f72d}", "\u{f72d}", function), + "Space" => key(49, " ", " ", plain), + "Control+A" => key(0, "\u{1}", "a", NSEventModifierFlags::Control), + "Meta+A" => key(0, "a", "a", NSEventModifierFlags::Command), + _ => return None, + }) +} + +fn press(wk: &WKWebView, name: &str) -> Result<(), String> { + let key = key(name).ok_or("A supported key is required.")?; + let window = window_number(wk)?; + let event = |kind| { + NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode( + kind, + NSPoint::new(0.0, 0.0), + key.flags, + uptime(), + window, + None, + &NSString::from_str(key.characters), + &NSString::from_str(key.ignoring), + false, + key.code, + ) + .ok_or_else(|| "Could not create a key event".to_string()) + }; + let down = event(NSEventType::KeyDown)?; + // Command shortcuts are key equivalents in AppKit, not ordinary key presses. + if key.flags.contains(NSEventModifierFlags::Command) { + wk.performKeyEquivalent(&down); + } else { + wk.keyDown(&down); + } + let up = event(NSEventType::KeyUp)?; + wk.keyUp(&up); + Ok(()) +} + +/// Text input as the input method would deliver it: one trusted `input` event. +fn insert_text(wk: &WKWebView, text: &str) { + let text = NSString::from_str(text); + let range = NSRange::new(NSNotFound as usize, 0); + let _: () = unsafe { msg_send![wk, insertText: &*text, replacementRange: range] }; +} diff --git a/src-tauri/src/browser/macos/mod.rs b/src-tauri/src/browser/macos/mod.rs new file mode 100644 index 0000000..ef4ac8b --- /dev/null +++ b/src-tauri/src/browser/macos/mod.rs @@ -0,0 +1,38 @@ +//! macOS card browsers: a real WKWebView over the card, one WebKit data store per card. +//! Guest pages get no bridge at all. MemCode's own scripts run in a separate content +//! world, and worker input is delivered to the view directly, never through the app's +//! event queue, so only the human's own input reaches `human_input`. +mod address_policy; +mod capture; +mod human_input; +mod input; +mod script; +mod surface; + +use serde_json::Value; +use tauri::AppHandle; +use tokio::sync::oneshot; + +type Reply = oneshot::Sender>; + +pub async fn call(app: AppHandle, method: String, input: Value) -> Result { + let (reply, answer) = oneshot::channel(); + let main = app.clone(); + app.run_on_main_thread(move || dispatch(&main, &method, input, reply)) + .map_err(|e| e.to_string())?; + tokio::time::timeout(std::time::Duration::from_secs(25), answer) + .await + .map_err(|_| "Native browser operation timed out")? + .map_err(|_| "Native browser operation closed")? +} + +fn dispatch(app: &AppHandle, method: &str, input: Value, reply: Reply) { + match method { + "browser_create" => surface::create(app, input, reply), + "browser_capture" => capture::capture(&input, reply), + "browser_eval" => script::evaluate(&input, reply), + _ => { + let _ = reply.send(surface::operate(method, &input)); + } + } +} diff --git a/src-tauri/src/browser/macos/script.rs b/src-tauri/src/browser/macos/script.rs new file mode 100644 index 0000000..9d25cf1 --- /dev/null +++ b/src-tauri/src/browser/macos/script.rs @@ -0,0 +1,67 @@ +//! MemCode's own page scripts. They run in a separate WebKit content world: they share +//! the page's DOM but none of its JavaScript, so a page can neither see nor patch them. +use std::cell::RefCell; + +use block2::RcBlock; +use objc2::{rc::Retained, runtime::AnyObject, MainThreadMarker}; +use objc2_foundation::{NSError, NSString}; +use objc2_web_kit::{WKContentWorld, WKWebView}; +use serde_json::{json, Value}; + +use super::{surface::{owned, SURFACES}, Reply}; + +const WORLD: &str = "memcode"; +const MAX_SCRIPT: usize = 512 * 1024; + +/// Runs an async function body; it must return a string (the runtime sends JSON). +pub(super) fn evaluate(input: &Value, reply: Reply) { + let prepared = (|| -> Result<(Retained, Retained, String), String> { + let body = input["script"].as_str().ok_or("Missing browser script")?; + if body.len() > MAX_SCRIPT { + return Err("Browser script is too large".into()); + } + let wk = SURFACES.with(|surfaces| -> Result<_, String> { + Ok(owned(&mut surfaces.borrow_mut(), input)?.wk.clone()) + })?; + let mtm = MainThreadMarker::new().ok_or("Browser scripts must run on the main thread")?; + let world = unsafe { WKContentWorld::worldWithName(&NSString::from_str(WORLD), mtm) }; + Ok((wk, world, body.to_owned())) + })(); + let (wk, world, body) = match prepared { + Ok(prepared) => prepared, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + let reply = RefCell::new(Some(reply)); + let finished = RcBlock::new(move |result: *mut AnyObject, error: *mut NSError| { + let Some(reply) = reply.borrow_mut().take() else { + return; + }; + let _ = reply.send(answer(result, error)); + }); + unsafe { + wk.callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler( + &NSString::from_str(&body), + None, + None, + &world, + Some(&finished), + ) + }; +} + +fn answer(result: *mut AnyObject, error: *mut NSError) -> Result { + if !error.is_null() { + return Err(unsafe { &*error }.localizedDescription().to_string()); + } + if result.is_null() { + return Ok(Value::Null); + } + let result = unsafe { &*result }; + result + .downcast_ref::() + .map(|text| json!(text.to_string())) + .ok_or_else(|| "Browser scripts must return text".into()) +} diff --git a/src-tauri/src/browser/macos/surface.rs b/src-tauri/src/browser/macos/surface.rs new file mode 100644 index 0000000..5ee3ea6 --- /dev/null +++ b/src-tauri/src/browser/macos/surface.rs @@ -0,0 +1,292 @@ +//! Card surfaces: create, place, show, hide and close the WKWebViews over cards. +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + rc::Rc, + sync::atomic::{AtomicU64, Ordering}, +}; + +use objc2::rc::Retained; +use objc2_web_kit::{WKContentRuleList, WKWebView, WKWebViewConfiguration}; +use serde_json::{json, Value}; +use tauri::{AppHandle, Manager}; +use wry::{ + BackgroundThrottlingPolicy, NewWindowFeatures, NewWindowResponse, PageLoadEvent, + PermissionResponse, Rect, WebView, WebViewBuilder, WebViewBuilderExtDarwin, + WebViewBuilderExtMacos, WebViewExtMacOS, +}; + +use super::{address_policy, human_input, input, Reply}; +use crate::native::Bounds; + +const INITIAL_BOUNDS: Bounds = Bounds { + x: 0.0, + y: 0.0, + width: 1280.0, + height: 800.0, +}; +const MAX_SIDE: f64 = 10000.0; + +pub(super) struct Surface { + pub owner: String, + pub wk: Retained, + opener: Option, + view: WebView, + bounds: Bounds, + visible: bool, + loads: Rc>, +} + +thread_local! { + pub(super) static SURFACES: RefCell> = RefCell::new(HashMap::new()); +} +static NEXT: AtomicU64 = AtomicU64::new(1); + +enum Configuration { + Card { + store: [u8; 16], + rules: Retained, + }, + /// A page's `window.open`: WebKit requires the opener's configuration. + Popup(Retained), +} + +fn next_id() -> String { + format!("native-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +fn rect(bounds: Bounds) -> Rect { + Rect { + position: wry::dpi::LogicalPosition::new(bounds.x, bounds.y).into(), + size: wry::dpi::LogicalSize::new(bounds.width, bounds.height).into(), + } +} + +pub(super) fn create(app: &AppHandle, input: Value, reply: Reply) { + let request = (|| -> Result<(String, [u8; 16]), String> { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let profile = input["profile"].as_str().ok_or("Missing browser profile")?; + Ok((owner.to_owned(), address_policy::store_identifier(profile)?)) + })(); + let (owner, store) = match request { + Ok(request) => request, + Err(error) => { + let _ = reply.send(Err(error)); + return; + } + }; + human_input::watch(app); + let app = app.clone(); + address_policy::with_rules(move |rules| { + let created = rules.and_then(|rules| { + let id = next_id(); + let surface = build(&app, Configuration::Card { store, rules }, &owner, None, &id)?; + SURFACES.with(|surfaces| surfaces.borrow_mut().insert(id.clone(), surface)); + Ok(json!({ "nativeId": id })) + }); + let _ = reply.send(created); + }); +} + +fn build( + app: &AppHandle, + configuration: Configuration, + owner: &str, + opener: Option, + id: &str, +) -> Result { + let window = app.get_window("main").ok_or("Main window is unavailable")?; + let loads = Rc::new(Cell::new(0u64)); + let committed = loads.clone(); + let popup_app = app.clone(); + let popup_owner = owner.to_owned(); + let popup_opener = id.to_owned(); + let builder = WebViewBuilder::new() + .with_visible(false) + .with_focused(false) + .with_bounds(rect(INITIAL_BOUNDS)) + .with_background_throttling(BackgroundThrottlingPolicy::Disabled) + .with_navigation_handler(|url| address_policy::navigable(&url)) + .with_new_window_req_handler(move |url, features| { + open_popup(&popup_app, &popup_owner, &popup_opener, &url, features) + }) + .with_download_started_handler(|_, _| false) + .with_permission_handler(|_| PermissionResponse::Deny) + .with_on_page_load_handler(move |event, _| { + if matches!(event, PageLoadEvent::Started) { + committed.set(committed.get() + 1); + } + }); + let (builder, rules) = match configuration { + Configuration::Card { store, rules } => { + (builder.with_data_store_identifier(store), Some(rules)) + } + Configuration::Popup(shared) => (builder.with_webview_configuration(shared), None), + }; + let view = builder.build_as_child(&window).map_err(|e| e.to_string())?; + if let Some(rules) = rules { + unsafe { view.manager().addContentRuleList(&rules) }; + } + let wk = Retained::into_super(view.webview()); + Ok(Surface { + owner: owner.to_owned(), + wk, + opener, + view, + bounds: INITIAL_BOUNDS, + visible: false, + loads, + }) +} + +fn open_popup( + app: &AppHandle, + owner: &str, + opener: &str, + url: &str, + features: NewWindowFeatures, +) -> NewWindowResponse { + if !address_policy::navigable(url) { + return NewWindowResponse::Deny; + } + let id = next_id(); + let configuration = Configuration::Popup(features.opener.target_configuration); + let Ok(surface) = build(app, configuration, owner, Some(opener.to_owned()), &id) else { + return NewWindowResponse::Deny; + }; + let webview = surface.wk.clone(); + let adopted = SURFACES.with(|surfaces| { + surfaces + .try_borrow_mut() + .map(|mut surfaces| surfaces.insert(id, surface)) + .is_ok() + }); + if adopted { + NewWindowResponse::Create { webview } + } else { + NewWindowResponse::Deny + } +} + +fn place(surface: &Surface) -> Result<(), String> { + surface.view.set_bounds(rect(surface.bounds)).map_err(|e| e.to_string())?; + surface.view.set_visible(surface.visible).map_err(|e| e.to_string()) +} + +fn page_state(id: &str, surface: &Surface) -> Value { + let url = unsafe { surface.wk.URL() } + .and_then(|url| url.absoluteString()) + .map(|url| url.to_string()) + .unwrap_or_else(|| "about:blank".into()); + let title = unsafe { surface.wk.title() }.map(|title| title.to_string()).unwrap_or_default(); + json!({ + "nativeId": id, + "opener": surface.opener, + "url": url, + "title": title, + "loading": unsafe { surface.wk.isLoading() }, + "loads": surface.loads.get(), + }) +} + +fn valid_bounds(value: &Value) -> Result { + let bounds: Bounds = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; + let finite = [bounds.x, bounds.y, bounds.width, bounds.height].iter().all(|n| n.is_finite()); + if !finite + || bounds.x < 0.0 + || bounds.y < 0.0 + || bounds.width < 1.0 + || bounds.height < 1.0 + || bounds.width > MAX_SIDE + || bounds.height > MAX_SIDE + { + return Err("Invalid native browser bounds".into()); + } + Ok(bounds) +} + +/// Looks up a surface the given work item owns. +pub(super) fn owned<'a>( + surfaces: &'a mut HashMap, + input: &Value, +) -> Result<&'a mut Surface, String> { + let id = input["nativeId"].as_str().ok_or("Missing browser surface")?; + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let surface = surfaces.get_mut(id).ok_or("Browser surface not found")?; + if surface.owner != owner { + return Err("Browser surface belongs to another work item".into()); + } + Ok(surface) +} + +pub(super) fn operate(method: &str, input: &Value) -> Result { + SURFACES.with(|surfaces| { + let mut surfaces = surfaces.borrow_mut(); + match method { + "browser_hide_all" => { + for surface in surfaces.values_mut() { + surface.visible = false; + place(surface)?; + } + } + "browser_close_all" => surfaces.clear(), + "browser_close_task" => { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + surfaces.retain(|_, surface| surface.owner != owner); + } + "browser_pages" => { + let owner = input["taskId"].as_str().ok_or("Missing browser owner")?; + let pages: Vec = surfaces + .iter() + .filter(|(_, surface)| surface.owner == owner) + .map(|(id, surface)| page_state(id, surface)) + .collect(); + return Ok(Value::Array(pages)); + } + "browser_close" => { + owned(&mut surfaces, input)?; + surfaces.remove(input["nativeId"].as_str().unwrap_or_default()); + } + "browser_surface" => show(&mut surfaces, input)?, + "browser_navigate" => { + let url = input["url"].as_str().ok_or("Missing address")?; + if !address_policy::navigable(url) || url.starts_with("data:") || url.starts_with("blob:") { + return Err("Open an HTTPS website or a localhost development server.".into()); + } + owned(&mut surfaces, input)?.view.load_url(url).map_err(|e| e.to_string())?; + } + "browser_history" => { + let surface = owned(&mut surfaces, input)?; + let _ = match input["action"].as_str() { + Some("back") => unsafe { surface.wk.goBack() }, + Some("forward") => unsafe { surface.wk.goForward() }, + Some("reload") => unsafe { surface.wk.reload() }, + _ => return Err("Unknown browser history action".into()), + }; + } + "browser_input" => input::deliver(&owned(&mut surfaces, input)?.wk, &input["input"])?, + _ => return Err("Unknown browser surface operation".into()), + } + Ok(Value::Null) + }) +} + +/// Shows one card's tab and hides every other surface, as on Windows. +fn show(surfaces: &mut HashMap, input: &Value) -> Result<(), String> { + let visible = input["visible"].as_bool().unwrap_or(false); + let bounds = if visible { Some(valid_bounds(&input["bounds"])?) } else { None }; + owned(surfaces, input)?; + let shown = input["nativeId"].as_str().unwrap_or_default(); + for (id, other) in surfaces.iter_mut() { + if id != shown { + other.visible = false; + place(other)?; + } + } + let surface = owned(surfaces, input)?; + if let Some(bounds) = bounds { + surface.bounds = bounds; + } + surface.visible = visible; + place(surface) +} diff --git a/tests/support/fake-webkit-host.ts b/tests/support/fake-webkit-host.ts new file mode 100644 index 0000000..e728802 --- /dev/null +++ b/tests/support/fake-webkit-host.ts @@ -0,0 +1,137 @@ +import type { NativeHost } from "../../runtime/host"; + +export interface FakeSurface { + nativeId: string; + owner: string; + opener: string | null; + profile?: string; + url: string; + title: string; + loading: boolean; + loads: number; + history: string[]; + position: number; + visible: boolean; + bounds?: unknown; +} + +/** Stands in for `src-tauri/src/browser/macos`: same methods, same replies. */ +export class FakeWebKitHost implements NativeHost { + readonly calls: Array<{ method: string; input: any }> = []; + readonly surfaces = new Map(); + titles = new Map(); + private next = 1; + + async call(method: string, input: any = {}): Promise { + this.calls.push({ method, input }); + return this.reply(method, input) as T; + } + + /** A page opened a window, as WebKit's createWebView would. */ + popup(opener: string, url: string) { + const parent = this.surfaces.get(opener)!; + const surface = this.surface(parent.owner, opener); + this.load(surface, url); + return surface; + } + + /** The human clicked a link inside the native surface. */ + follow(nativeId: string, url: string) { + this.load(this.surfaces.get(nativeId)!, url); + } + + private surface(owner: string, opener: string | null) { + const surface: FakeSurface = { + nativeId: `native-${this.next++}`, + owner, + opener, + url: "about:blank", + title: "", + loading: false, + loads: 0, + history: [], + position: -1, + visible: false, + }; + this.surfaces.set(surface.nativeId, surface); + return surface; + } + + private load(surface: FakeSurface, url: string, record = true) { + if (record) { + surface.history.splice(surface.position + 1, Infinity, url); + surface.position = surface.history.length - 1; + } + surface.url = url; + surface.loads++; + surface.title = this.titles.get(url) ?? new URL(url).host; + } + + private owned(input: any) { + const surface = this.surfaces.get(input.nativeId); + if (!surface) throw Error("Browser surface not found"); + if (surface.owner !== input.taskId) + throw Error("Browser surface belongs to another work item"); + return surface; + } + + private reply(method: string, input: any): unknown { + switch (method) { + case "browser_create": { + const surface = this.surface(input.taskId, null); + surface.profile = input.profile; + return { nativeId: surface.nativeId }; + } + case "browser_pages": + return [...this.surfaces.values()] + .filter((surface) => surface.owner === input.taskId) + .map(({ nativeId, opener, url, title, loading, loads }) => ({ + nativeId, + opener, + url, + title, + loading, + loads, + })); + case "browser_navigate": + this.load(this.owned(input), input.url); + return null; + case "browser_history": { + const surface = this.owned(input); + const step = { back: -1, forward: 1, reload: 0 }[input.action as string]!; + const position = surface.position + step; + if (position >= 0 && position < surface.history.length) { + surface.position = position; + this.load(surface, surface.history[position], false); + } + return null; + } + case "browser_surface": { + const shown = this.owned(input); + for (const surface of this.surfaces.values()) surface.visible = false; + shown.visible = input.visible; + if (input.bounds) shown.bounds = input.bounds; + return null; + } + case "browser_hide_all": + for (const surface of this.surfaces.values()) surface.visible = false; + return null; + case "browser_close": + this.owned(input); + this.surfaces.delete(input.nativeId); + return null; + case "browser_close_task": + for (const [id, surface] of this.surfaces) + if (surface.owner === input.taskId) this.surfaces.delete(id); + return null; + case "browser_close_all": + this.surfaces.clear(); + return null; + case "browser_capture": + this.owned(input); + return { data: "iVBORw0KGgo=", width: 1280, height: 800 }; + default: + throw Error(`Unknown browser surface operation ${method}`); + } + } +} diff --git a/tests/webkit-browser.test.ts b/tests/webkit-browser.test.ts new file mode 100644 index 0000000..db39545 --- /dev/null +++ b/tests/webkit-browser.test.ts @@ -0,0 +1,164 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { initialState } from "../src/seed"; +import { AgentBrowserManager } from "../runtime/browser/manager"; +import { browserEngineFor } from "../runtime/browser/engine-choice"; +import { WebKitEngine } from "../runtime/browser/webkit-engine"; +import { FakeWebKitHost } from "./support/fake-webkit-host"; + +const first = "https://example.com/"; +const second = "https://example.org/next"; + +async function webkitCard() { + const host = new FakeWebKitHost(); + const state = initialState(); + const manager = new AgentBrowserManager( + () => state, + await mkdtemp(join(tmpdir(), "memcode-webkit-")), + async () => {}, + 16, + host, + new WebKitEngine(host), + ); + return { host, state, manager, task: state.tasks[0] }; +} + +async function eventually(read: () => Promise, ok: (value: T) => boolean) { + let value = await read(); + for (let attempt = 0; attempt < 60 && !ok(value); attempt++) { + await new Promise((resolve) => setTimeout(resolve, 50)); + value = await read(); + } + return value; +} + +test("macOS 14 and later draw card browsers natively; older Macs keep the frames", () => { + const host = new FakeWebKitHost(); + assert.ok(browserEngineFor(host, "darwin", "23.0.0") instanceof WebKitEngine); + assert.ok(browserEngineFor(host, "darwin", "27.2.0") instanceof WebKitEngine); + assert.equal(browserEngineFor(host, "darwin", "22.6.0").native, false); + assert.equal(browserEngineFor(undefined, "darwin", "27.2.0").native, false); + assert.equal(browserEngineFor(host, "win32", "10.0.26100").native, true); + assert.ok(!(browserEngineFor(host, "win32", "10.0.26100") instanceof WebKitEngine)); +}); + +test("each card's native tab gets its own lasting WebKit storage", async () => { + const { host, state, manager, task } = await webkitCard(); + host.titles.set(first, "Example Domain"); + try { + const opened = await manager.execute(task.id, { action: "open", url: first }); + assert.equal(opened.state.nativeSurface, true); + assert.equal(opened.state.tabs[0].url, first); + assert.equal(opened.state.tabs[0].title, "Example Domain"); + await manager.execute(state.tasks[1].id, { action: "open", url: first }); + const profiles = [...host.surfaces.values()].map((surface) => surface.profile); + assert.match(profiles[0]!, /^worker-[0-9a-f]{64}$/); + assert.notEqual(profiles[0], profiles[1]); + await manager.execute(task.id, { action: "new-tab" }); + assert.equal( + [...host.surfaces.values()].filter((surface) => surface.owner === task.id)[1].profile, + profiles[0], + ); + } finally { + await manager.close(); + } +}); + +test("the address bar, back, forward and reload drive the native page", async () => { + const { host, manager, task } = await webkitCard(); + try { + const opened = await manager.execute(task.id, { action: "open", url: first }); + const tabId = opened.state.tabs[0].id; + await manager.execute(task.id, { action: "open", url: second, tabId }); + const back = await manager.execute(task.id, { action: "act", input: { action: "back" } }); + assert.equal(back.state.tabs[0].url, first); + const forward = await manager.execute(task.id, { + action: "act", + input: { action: "forward" }, + }); + assert.equal(forward.state.tabs[0].url, second); + const surface = [...host.surfaces.values()][0]; + const loads = surface.loads; + await manager.execute(task.id, { action: "act", input: { action: "reload" } }); + assert.equal(surface.loads, loads + 1); + } finally { + await manager.close(); + } +}); + +test("where the human goes inside the native page shows up in the card", async () => { + const { host, manager, task } = await webkitCard(); + try { + await manager.execute(task.id, { action: "open", url: first }); + host.follow([...host.surfaces.keys()][0], second); + const followed = await eventually( + () => manager.execute(task.id, { action: "state" }), + (reply) => reply.state.tabs[0].url === second, + ); + assert.equal(followed.state.tabs[0].url, second); + assert.ok(followed.state.activity.some((event) => event.text === "Navigated to " + second)); + } finally { + await manager.close(); + } +}); + +test("a window the page opens becomes another tab of the same card", async () => { + const { host, manager, task } = await webkitCard(); + try { + await manager.execute(task.id, { action: "open", url: first }); + host.popup([...host.surfaces.keys()][0], second); + const opened = await eventually( + () => manager.execute(task.id, { action: "state" }), + (reply) => reply.state.tabs.length === 2, + ); + assert.equal(opened.state.tabs.length, 2); + assert.equal(opened.state.tabs.find((tab) => tab.active)?.url, second); + } finally { + await manager.close(); + } +}); + +test("the native surface sits over the card and hides with it", async () => { + const { host, manager, task } = await webkitCard(); + try { + const opened = await manager.execute(task.id, { action: "open", url: first }); + const bounds = { x: 320, y: 140, width: 900, height: 640 }; + const placed = await manager.execute(task.id, { + action: "surface", + tabId: opened.state.tabs[0].id, + visible: true, + bounds, + }); + const surface = [...host.surfaces.values()][0]; + assert.equal(surface.visible, true); + assert.deepEqual(surface.bounds, bounds); + assert.deepEqual(placed.state.viewport, { width: 900, height: 640 }); + await manager.execute(task.id, { action: "surface", visible: false }); + assert.equal(surface.visible, false); + assert.equal(host.calls.at(-1)?.method, "browser_hide_all"); + } finally { + await manager.close(); + } +}); + +test("closing a tab or the app releases the native surfaces", async () => { + const { host, manager, task } = await webkitCard(); + try { + await manager.execute(task.id, { action: "open", url: first }); + const blank = await manager.execute(task.id, { action: "new-tab" }); + assert.equal(host.surfaces.size, 2); + await manager.execute(task.id, { + action: "act", + input: { action: "close", tabId: blank.state.tabs.find((tab) => tab.active)!.id }, + }); + assert.equal(host.surfaces.size, 1); + const left = await manager.execute(task.id, { action: "state" }); + assert.equal(left.state.tabs.length, 1); + } finally { + await manager.close(); + } + assert.equal(host.surfaces.size, 0); +}); From 5d87d1bdf5ab533ca7ed5b4a9b2c5b221d59173f Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:53:09 +0100 Subject: [PATCH 6/7] feat: let workers drive the Mac's native card browser [skip ci] Workers can now click, type, press keys, choose options, scroll and hover in the WKWebView over the card, and observe returns the accessibility tree in the same shape as Playwright's aria snapshot. - Each input goes straight to the WKWebView as a trusted event, and the driver waits until the page has seen it (a counter of trusted events in MemCode's own content world) before the next step. Without that wait, WebKit could apply a later insertText before an earlier keyDown. - Clicking a select, file, date, time or color control is refused: WebKit answers those with an AppKit menu or panel on screen. Selects go through choose, as on the other platforms. - If a worker click makes the visible card take the keyboard, it goes back to whatever had it, unless the human clicked meanwhile. - The content world is now kept alive. WebKit dropped its state whenever the API object was released, so the counter reset on every call. The tests run the same driver scripts against real Chrome pages through a host with the Rust module's methods. The scripts were also checked in a WKWebView: counts, refs, tree, and a fresh counter after navigation. Co-Authored-By: Claude Opus 5.5 --- runtime/browser/webkit-accessibility.ts | 174 +++++++++++++ runtime/browser/webkit-driver.ts | 275 ++++++++++++++++++++- src-tauri/src/browser/macos/focus.rs | 77 ++++++ src-tauri/src/browser/macos/human_input.rs | 6 +- src-tauri/src/browser/macos/mod.rs | 2 + src-tauri/src/browser/macos/script.rs | 18 +- src-tauri/src/browser/macos/surface.rs | 8 +- tests/support/chromium-native-host.ts | 145 +++++++++++ tests/webkit-worker.test.ts | 166 +++++++++++++ 9 files changed, 859 insertions(+), 12 deletions(-) create mode 100644 runtime/browser/webkit-accessibility.ts create mode 100644 src-tauri/src/browser/macos/focus.rs create mode 100644 tests/support/chromium-native-host.ts create mode 100644 tests/webkit-worker.test.ts diff --git a/runtime/browser/webkit-accessibility.ts b/runtime/browser/webkit-accessibility.ts new file mode 100644 index 0000000..9d2a40c --- /dev/null +++ b/runtime/browser/webkit-accessibility.ts @@ -0,0 +1,174 @@ +/** + * The page's accessibility tree for a worker, written like Playwright's aria + * snapshot (`- role "name" [state]: value`) so observations read the same on + * every platform. Runs as an async function body in MemCode's content world. + */ +export const ACCESSIBILITY_TREE = ` +const MAX_LINES = 500, MAX_NODES = 6000, MAX_TEXT = 160; +const SKIPPED = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "TEMPLATE", "HEAD", "META", "LINK"]); +const FROM_CONTENT = new Set(["button", "link", "heading", "option", "tab", "menuitem", "cell", "columnheader", "rowheader", "treeitem", "checkbox", "radio", "switch"]); +const TEXT_LEAF = new Set(["listitem", "paragraph", "cell", "columnheader", "rowheader", "status", "caption", "blockquote", "code", "term", "definition"]); +const VALUED = new Set(["textbox", "searchbox", "spinbutton", "slider", "combobox"]); +const lines = []; +let visited = 0; +const clean = (text) => (text || "").replace(/\\s+/g, " ").trim(); +const clip = (text) => (text.length > MAX_TEXT ? text.slice(0, MAX_TEXT - 1) + "…" : text); +const quote = (text) => JSON.stringify(clip(text)); + +function hidden(element) { + if (element.hidden || element.getAttribute("aria-hidden") === "true") return true; + const style = getComputedStyle(element); + return style.display === "none" || style.visibility === "hidden"; +} + +function inputRole(element) { + const type = (element.getAttribute("type") || "text").toLowerCase(); + if (type === "hidden") return ""; + if (["button", "submit", "reset", "image"].includes(type)) return "button"; + if (type === "checkbox") return element.getAttribute("role") === "switch" ? "switch" : "checkbox"; + if (type === "radio") return "radio"; + if (type === "range") return "slider"; + if (type === "number") return "spinbutton"; + if (type === "search") return "searchbox"; + return element.list ? "combobox" : "textbox"; +} + +function role(element) { + const explicit = clean(element.getAttribute("role")).split(" ")[0]; + if (explicit && explicit !== "presentation" && explicit !== "none") return explicit; + if (explicit) return ""; + const tag = element.tagName; + if (/^H[1-6]$/.test(tag)) return "heading"; + switch (tag) { + case "A": return element.hasAttribute("href") ? "link" : ""; + case "BUTTON": case "SUMMARY": return "button"; + case "INPUT": return inputRole(element); + case "TEXTAREA": return "textbox"; + case "SELECT": return element.multiple || element.size > 1 ? "listbox" : "combobox"; + case "OPTION": return "option"; + case "IMG": return element.getAttribute("alt") === "" ? "" : "img"; + case "UL": case "OL": case "MENU": return "list"; + case "LI": return "listitem"; + case "NAV": return "navigation"; + case "MAIN": return "main"; + case "ASIDE": return "complementary"; + case "HEADER": return element.closest("article, section, main") ? "" : "banner"; + case "FOOTER": return element.closest("article, section, main") ? "" : "contentinfo"; + case "FORM": return element.getAttribute("aria-label") || element.getAttribute("name") ? "form" : ""; + case "TABLE": return "table"; + case "TR": return "row"; + case "TH": return "columnheader"; + case "TD": return "cell"; + case "DIALOG": return "dialog"; + case "P": return "paragraph"; + case "OUTPUT": return "status"; + case "PROGRESS": return "progressbar"; + case "IFRAME": return "iframe"; + case "BLOCKQUOTE": return "blockquote"; + case "CODE": return "code"; + case "DT": return "term"; + case "DD": return "definition"; + case "FIGCAPTION": case "CAPTION": return "caption"; + } + return ""; +} + +function visibleText(node) { + if (node.nodeType === Node.TEXT_NODE) return node.textContent; + if (node.nodeType !== Node.ELEMENT_NODE || SKIPPED.has(node.tagName) || hidden(node)) return ""; + if (node.tagName === "IMG") return node.getAttribute("alt") || ""; + return [...node.childNodes].map(visibleText).join(node.tagName === "BR" ? " " : ""); +} + +function labelOf(element) { + if (element.labels && element.labels.length) + return clean([...element.labels].map((label) => + [...label.childNodes].filter((child) => child !== element && !(child.contains && child.contains(element))).map(visibleText).join(" ")).join(" ")); + return ""; +} + +function name(element, kind) { + const labelledBy = clean(element.getAttribute("aria-labelledby")); + if (labelledBy) { + const text = clean(labelledBy.split(" ").map((id) => { const target = document.getElementById(id); return target ? visibleText(target) : ""; }).join(" ")); + if (text) return text; + } + const label = clean(element.getAttribute("aria-label")); + if (label) return label; + if (["INPUT", "TEXTAREA", "SELECT", "METER", "PROGRESS"].includes(element.tagName)) { + const labelled = labelOf(element); + if (labelled) return labelled; + } + if (element.tagName === "IMG") return clean(element.getAttribute("alt") || element.getAttribute("title")); + if (element.tagName === "INPUT" && ["button", "submit", "reset"].includes(element.type)) + return clean(element.value || (element.type === "submit" ? "Submit" : "")); + if (element.tagName === "IFRAME") return clean(element.getAttribute("title")); + if (FROM_CONTENT.has(kind)) { + const text = clean(element.tagName === "OPTION" ? element.label : visibleText(element)); + if (text) return text; + } + return clean(element.getAttribute("title") || element.getAttribute("placeholder")); +} + +function states(element, kind) { + const flags = []; + if (kind === "heading") flags.push("level=" + (element.getAttribute("aria-level") || element.tagName.slice(1))); + const checked = element.getAttribute("aria-checked"); + if (checked === "true" || (checked === null && element.checked)) flags.push("checked"); + if (checked === "mixed" || element.indeterminate) flags.push("checked=mixed"); + if (element.getAttribute("aria-selected") === "true" || (kind === "option" && element.selected)) flags.push("selected"); + if (element.getAttribute("aria-expanded")) flags.push("expanded=" + element.getAttribute("aria-expanded")); + if (element.getAttribute("aria-pressed") === "true") flags.push("pressed"); + if (element.disabled || element.getAttribute("aria-disabled") === "true") flags.push("disabled"); + return flags.map((flag) => " [" + flag + "]").join(""); +} + +function value(element, kind) { + if (!VALUED.has(kind)) return ""; + if (element.tagName === "SELECT") return ""; + if ("value" in element) return clean(element.value); + return clean(element.textContent); +} + +function emit(depth, text) { + if (lines.length < MAX_LINES) lines.push(" ".repeat(depth) + "- " + text); +} + +/** Element and text children as they will be shown, flattening unnamed containers. */ +function walk(node, depth) { + if (lines.length >= MAX_LINES || ++visited > MAX_NODES) return; + if (node.nodeType === Node.TEXT_NODE) { + const text = clean(node.textContent); + if (text) emit(depth, "text: " + clip(text)); + return; + } + if (node.nodeType !== Node.ELEMENT_NODE || SKIPPED.has(node.tagName) || hidden(node)) return; + const kind = role(node); + if (!kind) { + for (const child of node.childNodes) walk(child, depth); + return; + } + const label = name(node, kind); + const head = kind + (label ? " " + quote(label) : "") + states(node, kind); + const shown = value(node, kind); + if (shown) return emit(depth, head + ": " + clip(shown)); + if (FROM_CONTENT.has(kind) && !hasRoles(node)) return emit(depth, head); + if (TEXT_LEAF.has(kind) && !hasRoles(node)) { + const text = clean(visibleText(node)); + return emit(depth, text ? head + ": " + clip(text) : head); + } + const before = lines.length; + emit(depth, head + ":"); + for (const child of node.childNodes) walk(child, depth + 1); + if (lines.length === before + 1) lines[before] = lines[before].slice(0, -1); +} + +function hasRoles(element) { + for (const child of element.querySelectorAll("*")) if (role(child) && !hidden(child)) return true; + return false; +} + +walk(document.body, 0); +if (lines.length >= MAX_LINES || visited > MAX_NODES) lines.push("- …"); +return lines.join("\\n"); +`; diff --git a/runtime/browser/webkit-driver.ts b/runtime/browser/webkit-driver.ts index b3f84fa..d337f91 100644 --- a/runtime/browser/webkit-driver.ts +++ b/runtime/browser/webkit-driver.ts @@ -1,4 +1,6 @@ -import type { InteractionFeedback, InteractionRequest } from "./engine"; +import type { BrowserInteraction } from "../../src/browser"; +import type { InteractionFeedback, InteractionRequest, Viewport } from "./engine"; +import { ACCESSIBILITY_TREE } from "./webkit-accessibility"; export type NativeInput = | { kind: "click" | "move"; x: number; y: number } @@ -16,7 +18,27 @@ export interface NativeScripts { travel(action: "back" | "forward" | "reload"): Promise; } +type Point = { x: number; y: number }; +type Echo = "mouseup" | "mousemove" | "keyup" | "input" | "wheel"; + const MAX_OBSERVATION = 18000; +const ECHO_TIMEOUT_MS = 1500; +const ECHO_POLL_MS = 15; +const SETTLE_TIMEOUT_MS = 8000; +const SETTLE_POLL_MS = 100; +const DEFAULT_SCROLL = 600; +const KNOWN_CURSORS = [ + "default", + "auto", + "pointer", + "text", + "crosshair", + "grab", + "grabbing", + "not-allowed", + "wait", + "progress", +]; /** Same refs and wording as `inspectPage`, so a worker sees one format everywhere. */ const TAG_CONTROLS = ` @@ -36,22 +58,261 @@ return nodes .join("\\n"); `; +/** + * Counts the trusted events the page has received, per type. A fresh document + * starts a fresh count, which tells the driver the page moved on. + */ +const ECHO_COUNTER = ` +const fresh = !globalThis.__memcodeEchoes; +const echoes = (globalThis.__memcodeEchoes ??= (() => { + const seen = { mouseup: 0, mousemove: 0, keyup: 0, input: 0, wheel: 0 }; + for (const type of Object.keys(seen)) + addEventListener(type, (event) => { if (event.isTrusted) seen[type]++; }, { capture: true, passive: true }); + return seen; +})()); +`; + +/** Controls WebKit answers with an AppKit menu or panel instead of the page. */ +const PICKER_CHECK = ` +const pickers = { file: "Choosing files needs the user: ask them to pick the file.", + date: "Set dates with type instead of the picker.", "datetime-local": "Set dates with type instead of the picker.", + month: "Set dates with type instead of the picker.", week: "Set dates with type instead of the picker.", + time: "Set times with type instead of the picker.", color: "Set colors with type instead of the picker." }; +const refusal = (element) => { + const control = element && element.closest ? element.closest("select, input") : null; + if (!control) return undefined; + if (control.tagName === "SELECT") + return "Use choose with a control ref and option value or label for an HTML select."; + return pickers[(control.getAttribute("type") || "").toLowerCase()]; +}; +`; + +function script(body: string, args: Record = {}) { + return `const args = ${JSON.stringify(args)};\n${body}`; +} + +async function runJson(page: NativeScripts, body: string, args: Record = {}) { + return JSON.parse(await page.run(script(body, args))) as T; +} + +function failure(result: { error?: string }) { + if (result.error) throw Error(result.error); +} + export async function inspectNativePage(page: NativeScripts): Promise { const references = await page.run(TAG_CONTROLS); - return `URL: ${page.url()}\nTitle: ${await page.title()}\n\nVisible controls (use ref for actions):\n${references}`.slice( + const accessible = await page + .run(ACCESSIBILITY_TREE) + .catch(() => "Accessibility snapshot unavailable."); + return `URL: ${page.url()}\nTitle: ${await page.title()}\n\nVisible controls (use ref for actions):\n${references}\n\nAccessibility:\n${accessible}`.slice( 0, MAX_OBSERVATION, ); } +/** Delivers one input and waits until the page has seen it, or a new page loaded. */ +async function deliver(page: NativeScripts, input: NativeInput, echo: Echo) { + const before = await runJson<{ count: number }>( + page, + `${ECHO_COUNTER} return JSON.stringify({ count: echoes[args.echo] });`, + { echo }, + ); + await page.input(input); + const deadline = Date.now() + ECHO_TIMEOUT_MS; + while (Date.now() < deadline) { + const after = await runJson<{ count: number; fresh: boolean }>( + page, + `${ECHO_COUNTER} return JSON.stringify({ count: echoes[args.echo], fresh });`, + { echo }, + ).catch(() => ({ count: before.count, fresh: true })); + if (after.fresh || after.count > before.count) return; + await new Promise((resolve) => setTimeout(resolve, ECHO_POLL_MS)); + } +} + +/** Scrolls a control into view and finds a point on it that receives the click. */ +async function target(page: NativeScripts, ref: string): Promise { + const deadline = Date.now() + SETTLE_TIMEOUT_MS; + for (;;) { + const found = await runJson( + page, + `${PICKER_CHECK} + const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + const refused = refusal(element); + if (refused) return JSON.stringify({ error: refused }); + const view = () => element.getBoundingClientRect(); + let rect = view(); + if (rect.top < 0 || rect.left < 0 || rect.bottom > innerHeight || rect.right > innerWidth) { + element.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); + await new Promise((resolve) => setTimeout(resolve, 50)); + rect = view(); + } + if (!rect.width || !rect.height || getComputedStyle(element).visibility === "hidden") + return JSON.stringify({ retry: true, error: "That control is not visible." }); + if (element.disabled) return JSON.stringify({ retry: true, error: "That control is disabled." }); + const x = Math.min(Math.max(rect.left + rect.width / 2, 0), innerWidth - 1); + const y = Math.min(Math.max(rect.top + rect.height / 2, 0), innerHeight - 1); + const hit = document.elementFromPoint(x, y); + const receives = hit && (hit === element || element.contains(hit) || (hit.control === element)); + if (!receives) { + const cover = hit ? hit.tagName.toLowerCase() + (hit.id ? "#" + hit.id : "") : "nothing"; + return JSON.stringify({ retry: true, error: "Another element (" + cover + ") covers that control. Close it or observe again." }); + } + return JSON.stringify({ x, y });`, + { ref }, + ); + if (!found.error) return { x: found.x, y: found.y }; + if (!found.retry || Date.now() > deadline) failure(found); + await new Promise((resolve) => setTimeout(resolve, SETTLE_POLL_MS)); + } +} + +async function refusePickerAt(page: NativeScripts, point: Point) { + failure( + await runJson<{ error?: string }>( + page, + `${PICKER_CHECK} return JSON.stringify({ error: refusal(document.elementFromPoint(args.x, args.y)) });`, + point, + ), + ); +} + +function inside(point: Point | undefined, viewport: Viewport): point is Point { + return !!point && point.x <= viewport.width && point.y <= viewport.height; +} + +function pointOf(input: BrowserInteraction): Point | undefined { + return input.x !== undefined && input.y !== undefined ? { x: input.x, y: input.y } : undefined; +} + +async function click(page: NativeScripts, input: BrowserInteraction, viewport: Viewport) { + let point = pointOf(input); + if (input.ref) point = await target(page, input.ref); + else if (!inside(point, viewport)) + throw Error("Choose a current control ref or a point inside this page."); + else await refusePickerAt(page, point); + await deliver(page, { kind: "click", ...point! }, "mouseup"); + return point; +} + +/** Focuses the field and selects what is in it, so typing replaces it like Playwright's fill. */ +async function type(page: NativeScripts, input: BrowserInteraction) { + if (input.text === undefined) throw Error("Text is required."); + if (!input.ref) { + if (input.text) await deliver(page, { kind: "text", text: input.text }, "input"); + return; + } + const field = await runJson<{ error?: string; set?: boolean; empty?: boolean }>( + page, + `const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + const kind = (element.getAttribute("type") || "").toLowerCase(); + const picked = ["date", "datetime-local", "month", "week", "time", "color", "range"].includes(kind); + if (element.tagName === "INPUT" && picked) { + element.focus(); + element.value = args.text; + element.dispatchEvent(new Event("input", { bubbles: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return JSON.stringify({ set: true }); + } + const editable = element.isContentEditable || ["INPUT", "TEXTAREA"].includes(element.tagName); + if (!editable) return JSON.stringify({ error: "That control does not take text." }); + if (element.disabled || element.readOnly) return JSON.stringify({ error: "That field is read-only." }); + element.scrollIntoView({ block: "center", behavior: "instant" }); + element.focus(); + if (element.isContentEditable) { + const range = document.createRange(); + range.selectNodeContents(element); + getSelection().removeAllRanges(); + getSelection().addRange(range); + return JSON.stringify({ empty: !element.textContent }); + } + try { element.select(); } catch {} + return JSON.stringify({ empty: !element.value });`, + { ref: input.ref, text: input.text }, + ); + failure(field); + if (field.set) return; + if (input.text) await deliver(page, { kind: "text", text: input.text }, "input"); + else if (!field.empty) await deliver(page, { kind: "key", key: "Backspace" }, "keyup"); +} + +/** As Playwright's selectOption: sets the option and fires input and change. */ +async function choose(page: NativeScripts, input: BrowserInteraction) { + if (!input.ref || (input.value === undefined && input.label === undefined)) + throw Error("Choose a current select ref and option value or label."); + failure( + await runJson<{ error?: string }>( + page, + `const element = document.querySelector('[data-memcode-ref="' + args.ref + '"]'); + if (!element) return JSON.stringify({ error: "That control is gone. Observe the page again." }); + if (element.tagName !== "SELECT") return JSON.stringify({ error: "Choose works on an HTML select." }); + const option = [...element.options].find((option) => + args.value !== null ? option.value === args.value : option.label === args.label || option.textContent.trim() === args.label); + if (!option) return JSON.stringify({ error: "That select has no such option." }); + if (option.disabled) return JSON.stringify({ error: "That option is disabled." }); + element.value = option.value; + element.dispatchEvent(new Event("input", { bubbles: true })); + element.dispatchEvent(new Event("change", { bubbles: true })); + return JSON.stringify({});`, + { ref: input.ref, value: input.value ?? null, label: input.label ?? null }, + ), + ); +} + +async function cursorAt(page: NativeScripts, point: Point) { + const cursor = await page + .run( + script( + `const element = document.elementFromPoint(args.x, args.y); + if (!element) return "default"; + if (element.closest("input,textarea,[contenteditable=true]")) return "text"; + return getComputedStyle(element).cursor;`, + point, + ), + ) + .catch(() => "default"); + return KNOWN_CURSORS.includes(cursor) ? cursor : "default"; +} + export async function interactNatively( page: NativeScripts, request: InteractionRequest, ): Promise { - const action = request.input.action; - if (action === "back" || action === "forward" || action === "reload") { - await page.travel(action); - return {}; + const { input, viewport } = request; + let point = pointOf(input); + switch (input.action) { + case "back": + case "forward": + case "reload": + await page.travel(input.action); + return {}; + case "click": + point = await click(page, input, viewport); + break; + case "hover": + if (!inside(point, viewport)) throw Error("Hover inside the current page."); + await deliver(page, { kind: "move", ...point }, "mousemove"); + break; + case "type": + await type(page, input); + break; + case "press": + if (!input.key) throw Error("A supported key is required."); + await deliver(page, { kind: "key", key: input.key }, "keyup"); + break; + case "choose": + await choose(page, input); + break; + case "scroll": { + const at = point ?? { x: viewport.width / 2, y: viewport.height / 2 }; + await deliver(page, { kind: "wheel", ...at, deltaY: input.deltaY ?? DEFAULT_SCROLL }, "wheel"); + break; + } + default: + throw Error(`The browser cannot ${input.action} here.`); } - throw Error(`The Mac browser cannot ${action} for a worker yet.`); + if (!point) return {}; + return { point, cursor: await cursorAt(page, point) }; } diff --git a/src-tauri/src/browser/macos/focus.rs b/src-tauri/src/browser/macos/focus.rs new file mode 100644 index 0000000..0c8b0e6 --- /dev/null +++ b/src-tauri/src/browser/macos/focus.rs @@ -0,0 +1,77 @@ +//! Worker input must not take the human's keyboard. WebKit makes a visible card the +//! window's first responder when a click lands in a text field, a moment after the +//! click. This hands the keyboard back to whatever had it, unless the human has +//! clicked somewhere since. +use std::{ + cell::RefCell, + time::{Duration, Instant}, +}; + +use objc2::{rc::Retained, runtime::AnyObject, Message}; +use objc2_app_kit::{NSResponder, NSView}; +use objc2_web_kit::WKWebView; + +/// WebKit moves focus within a few hundred milliseconds of the click. +const WATCH: Duration = Duration::from_millis(1500); + +struct Borrowed { + card: Retained, + owner: Retained, + since: Instant, +} + +thread_local! { + static BORROWED: RefCell> = const { RefCell::new(None) }; +} + +fn within(responder: &NSResponder, card: &WKWebView) -> bool { + let responder: &AnyObject = responder; + responder + .downcast_ref::() + .is_some_and(|view| view.isDescendantOf(card)) +} + +/// Before worker input: note who has the keyboard if it is not this card. +pub(super) fn remember(card: &WKWebView) { + let Some(owner) = card.window().and_then(|window| window.firstResponder()) else { + return; + }; + if within(&owner, card) { + return; + } + let card = card.retain(); + BORROWED.with(|borrowed| { + *borrowed.borrow_mut() = Some(Borrowed { card, owner, since: Instant::now() }) + }); +} + +/// Runs on every browser call: returns the keyboard if the card took it. +pub(super) fn give_back() { + BORROWED.with(|borrowed| { + let Ok(mut slot) = borrowed.try_borrow_mut() else { + return; + }; + let Some(pending) = slot.as_ref() else { + return; + }; + let Some(window) = pending.card.window() else { + *slot = None; + return; + }; + if window.firstResponder().is_some_and(|now| within(&now, &pending.card)) { + window.makeFirstResponder(Some(&pending.owner)); + *slot = None; + } else if pending.since.elapsed() > WATCH { + *slot = None; + } + }); +} + +/// The human clicked: wherever focus goes now is their choice. +pub(super) fn forget() { + BORROWED.with(|borrowed| { + if let Ok(mut slot) = borrowed.try_borrow_mut() { + *slot = None; + } + }); +} diff --git a/src-tauri/src/browser/macos/human_input.rs b/src-tauri/src/browser/macos/human_input.rs index c928326..d48dfca 100644 --- a/src-tauri/src/browser/macos/human_input.rs +++ b/src-tauri/src/browser/macos/human_input.rs @@ -24,7 +24,11 @@ pub(super) fn watch(app: &AppHandle) { } let app = app.clone(); let seen = RcBlock::new(move |event: NonNull| -> *mut NSEvent { - if let Some(owner) = receiving_owner(unsafe { event.as_ref() }) { + let event_ref = unsafe { event.as_ref() }; + if event_ref.r#type() != NSEventType::KeyDown && event_ref.r#type() != NSEventType::ScrollWheel { + super::focus::forget(); + } + if let Some(owner) = receiving_owner(event_ref) { let _ = app.emit_to( tauri::EventTarget::Webview { label: "main".into() }, "browser:native-input", diff --git a/src-tauri/src/browser/macos/mod.rs b/src-tauri/src/browser/macos/mod.rs index ef4ac8b..5bd2af4 100644 --- a/src-tauri/src/browser/macos/mod.rs +++ b/src-tauri/src/browser/macos/mod.rs @@ -4,6 +4,7 @@ //! event queue, so only the human's own input reaches `human_input`. mod address_policy; mod capture; +mod focus; mod human_input; mod input; mod script; @@ -27,6 +28,7 @@ pub async fn call(app: AppHandle, method: String, input: Value) -> Result surface::create(app, input, reply), "browser_capture" => capture::capture(&input, reply), diff --git a/src-tauri/src/browser/macos/script.rs b/src-tauri/src/browser/macos/script.rs index 9d25cf1..935f823 100644 --- a/src-tauri/src/browser/macos/script.rs +++ b/src-tauri/src/browser/macos/script.rs @@ -13,6 +13,21 @@ use super::{surface::{owned, SURFACES}, Reply}; const WORLD: &str = "memcode"; const MAX_SCRIPT: usize = 512 * 1024; +thread_local! { + /// WebKit drops a content world's JavaScript state once the API object is + /// released, so the driver's per-page state lives only as long as this does. + static MEMCODE_WORLD: RefCell>> = const { RefCell::new(None) }; +} + +fn memcode_world(mtm: MainThreadMarker) -> Retained { + MEMCODE_WORLD.with(|world| { + world + .borrow_mut() + .get_or_insert_with(|| unsafe { WKContentWorld::worldWithName(&NSString::from_str(WORLD), mtm) }) + .clone() + }) +} + /// Runs an async function body; it must return a string (the runtime sends JSON). pub(super) fn evaluate(input: &Value, reply: Reply) { let prepared = (|| -> Result<(Retained, Retained, String), String> { @@ -24,8 +39,7 @@ pub(super) fn evaluate(input: &Value, reply: Reply) { Ok(owned(&mut surfaces.borrow_mut(), input)?.wk.clone()) })?; let mtm = MainThreadMarker::new().ok_or("Browser scripts must run on the main thread")?; - let world = unsafe { WKContentWorld::worldWithName(&NSString::from_str(WORLD), mtm) }; - Ok((wk, world, body.to_owned())) + Ok((wk, memcode_world(mtm), body.to_owned())) })(); let (wk, world, body) = match prepared { Ok(prepared) => prepared, diff --git a/src-tauri/src/browser/macos/surface.rs b/src-tauri/src/browser/macos/surface.rs index 5ee3ea6..4ae1e2f 100644 --- a/src-tauri/src/browser/macos/surface.rs +++ b/src-tauri/src/browser/macos/surface.rs @@ -16,7 +16,7 @@ use wry::{ WebViewBuilderExtMacos, WebViewExtMacOS, }; -use super::{address_policy, human_input, input, Reply}; +use super::{address_policy, focus, human_input, input, Reply}; use crate::native::Bounds; const INITIAL_BOUNDS: Bounds = Bounds { @@ -264,7 +264,11 @@ pub(super) fn operate(method: &str, input: &Value) -> Result { _ => return Err("Unknown browser history action".into()), }; } - "browser_input" => input::deliver(&owned(&mut surfaces, input)?.wk, &input["input"])?, + "browser_input" => { + let card = &owned(&mut surfaces, input)?.wk; + focus::remember(card); + input::deliver(card, &input["input"])? + } _ => return Err("Unknown browser surface operation".into()), } Ok(Value::Null) diff --git a/tests/support/chromium-native-host.ts b/tests/support/chromium-native-host.ts new file mode 100644 index 0000000..f599933 --- /dev/null +++ b/tests/support/chromium-native-host.ts @@ -0,0 +1,145 @@ +import type { Browser, BrowserContext, Page } from "playwright-core"; +import type { NativeHost } from "../../runtime/host"; + +interface Surface { + owner: string; + page: Page; + loads: number; +} + +const KEYS: Record = { + "Shift+Tab": "Shift+Tab", + "Control+A": "Control+A", + "Meta+A": "Meta+A", + Space: " ", +}; + +/** + * Speaks the same methods as `src-tauri/src/browser/macos`, backed by real + * Chrome pages, so the WebKit driver's scripts and input run against a real DOM. + * Scripts run in the page's own world here; the Mac runs them in a separate one. + */ +export class ChromiumNativeHost implements NativeHost { + private browser?: Browser; + private contexts = new Map(); + private surfaces = new Map(); + private next = 1; + readonly inputs: any[] = []; + + async call(method: string, input: any = {}): Promise { + return (await this.reply(method, input)) as T; + } + + async close() { + await this.browser?.close(); + } + + private async context(profile: string) { + if (!this.browser) { + const { chromium } = await import("playwright-core"); + let failure: unknown; + for (const channel of ["msedge", "chrome"]) + try { + this.browser = await chromium.launch({ channel, headless: true }); + break; + } catch (error) { + failure ??= error; + } + if (!this.browser) throw failure; + } + let context = this.contexts.get(profile); + if (!context) { + context = await this.browser.newContext({ viewport: { width: 800, height: 600 } }); + this.contexts.set(profile, context); + } + return context; + } + + private owned(input: any) { + const surface = this.surfaces.get(input.nativeId); + if (!surface || surface.owner !== input.taskId) throw Error("Browser surface not found"); + return surface; + } + + private async reply(method: string, input: any): Promise { + switch (method) { + case "browser_create": { + const page = await (await this.context(input.profile)).newPage(); + const nativeId = `native-${this.next++}`; + const surface = { owner: input.taskId, page, loads: 0 }; + page.on("framenavigated", (frame) => { + if (frame === page.mainFrame()) surface.loads++; + }); + this.surfaces.set(nativeId, surface); + return { nativeId }; + } + case "browser_pages": + return Promise.all( + [...this.surfaces] + .filter(([, surface]) => surface.owner === input.taskId && !surface.page.isClosed()) + .map(async ([nativeId, surface]) => ({ + nativeId, + opener: null, + url: surface.page.url(), + title: await surface.page.title().catch(() => ""), + loading: false, + loads: surface.loads, + })), + ); + case "browser_navigate": + await this.owned(input).page.goto(input.url, { waitUntil: "load" }); + return null; + case "browser_history": { + const page = this.owned(input).page; + if (input.action === "back") await page.goBack(); + else if (input.action === "forward") await page.goForward(); + else await page.reload(); + return null; + } + case "browser_eval": + return this.owned(input).page.evaluate(`(async () => { ${input.script}\n})()`); + case "browser_input": + this.inputs.push(input.input); + await this.deliver(this.owned(input).page, input.input); + return null; + case "browser_capture": { + const page = this.owned(input).page; + const data = await page.screenshot({ type: input.format === "jpeg" ? "jpeg" : "png" }); + return { data: data.toString("base64"), ...page.viewportSize()! }; + } + case "browser_close": + await this.owned(input).page.close(); + this.surfaces.delete(input.nativeId); + return null; + case "browser_close_task": + for (const [id, surface] of this.surfaces) + if (surface.owner === input.taskId) { + await surface.page.close(); + this.surfaces.delete(id); + } + return null; + case "browser_surface": + case "browser_hide_all": + case "browser_close_all": + return null; + default: + throw Error(`Unknown browser surface operation ${method}`); + } + } + + private async deliver(page: Page, input: any) { + switch (input.kind) { + case "click": + return page.mouse.click(input.x, input.y); + case "move": + return page.mouse.move(input.x, input.y); + case "wheel": + await page.mouse.move(input.x, input.y); + return page.mouse.wheel(0, input.deltaY); + case "key": + return page.keyboard.press(KEYS[input.key] ?? input.key); + case "text": + return page.keyboard.insertText(input.text); + } + } +} diff --git a/tests/webkit-worker.test.ts b/tests/webkit-worker.test.ts new file mode 100644 index 0000000..c9c1ba4 --- /dev/null +++ b/tests/webkit-worker.test.ts @@ -0,0 +1,166 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { initialState } from "../src/seed"; +import { AgentBrowserManager } from "../runtime/browser/manager"; +import { WebKitEngine } from "../runtime/browser/webkit-engine"; +import { ChromiumNativeHost } from "./support/chromium-native-host"; + +async function serve(html: string) { + const server = createServer((_request, response) => { + response.setHeader("Content-Type", "text/html"); + response.end(html); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as { port: number }; + return { + url: `http://127.0.0.1:${port}/`, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + +async function workerCard(html: string) { + const site = await serve(html); + const host = new ChromiumNativeHost(); + const state = initialState(), + task = state.tasks[0], + root = await mkdtemp(join(tmpdir(), "memcode-webkit-worker-")); + const manager = new AgentBrowserManager( + () => state, + root, + async () => {}, + 16, + host, + new WebKitEngine(host), + ); + manager.attach(task.id, "codex", root); + const act = async (input: Record) => { + const { snapshot } = await manager.execute(task.id, { action: "observe" }, "worker"); + return manager.execute( + task.id, + { action: "act", input: { ...input, revision: snapshot!.revision } as any }, + "worker", + ); + }; + const observe = async () => + (await manager.execute(task.id, { action: "observe" }, "worker")).snapshot!.text; + const done = async () => { + await manager.close(); + await host.close(); + await site.close(); + }; + await manager.execute(task.id, { action: "open", url: site.url }, "worker"); + return { manager, host, state, task, act, observe, done }; +} + +const form = `Worker browser fixture + + + + +`; + +test( + "a worker types, clicks and chooses in the Mac's native page like anywhere else", + { timeout: 60000 }, + async () => { + const card = await workerCard(form); + try { + const first = await card.observe(); + assert.match(first, /m1: input Name/); + assert.match(first, /textbox "Name"/); + assert.match(first, /Nothing stored/); + await card.act({ action: "type", ref: "m1", text: "Alice" }); + await card.act({ action: "click", ref: "m2" }); + assert.match(await card.observe(), /Alice/); + await card.act({ action: "choose", ref: "m3", value: "late" }); + assert.match(await card.observe(), /Late.*\[selected\]/); + await card.act({ action: "type", ref: "m1", text: "Bob" }); + await card.act({ action: "press", key: "Backspace" }); + await card.act({ action: "click", ref: "m2" }); + assert.match(await card.observe(), /textbox "Name": Bo\b/); + const captured = await card.manager.execute( + card.task.id, + { action: "act", input: { action: "capture" } }, + "worker", + ); + const artifact = card.state.artifacts.find((item) => item.id === captured.artifactId)!; + assert.equal( + (await readFile(artifact.path)).subarray(0, 8).toString("hex"), + "89504e470d0a1a0a", + ); + } finally { + await card.done(); + } + }, +); + +test( + "on the Mac a worker never clicks open a native menu or file picker", + { timeout: 60000 }, + async () => { + const card = await workerCard(form); + try { + await assert.rejects(card.act({ action: "click", ref: "m3" }), /choose/); + await assert.rejects(card.act({ action: "click", ref: "m4" }), /file/i); + assert.equal(card.host.inputs.length, 0); + } finally { + await card.done(); + } + }, +); + +test( + "a worker scrolls and hovers the native page and sees the cursor there", + { timeout: 60000 }, + async () => { + const card = await workerCard( + `Long +

+ `, + ); + try { + await card.act({ action: "scroll", x: 400, y: 300, deltaY: 600 }); + assert.match(await card.observe(), /At 600/); + await card.act({ action: "scroll", x: 400, y: 300, deltaY: -600 }); + const hovered = await card.act({ action: "hover", x: 60, y: 30 }); + assert.equal(hovered.state.cursor, "text"); + assert.deepEqual( + { x: hovered.state.pointer?.x, y: hovered.state.pointer?.y }, + { x: 60, y: 30 }, + ); + } finally { + await card.done(); + } + }, +); + +test( + "the Mac observation includes the page's accessibility tree", + { timeout: 60000 }, + async () => { + const card = await workerCard( + `Tree

Welcome

+ +
  • First point
  • Second point
+
Gone
+ Logo
`, + ); + try { + const text = await card.observe(); + const tree = text.slice(text.indexOf("Accessibility:")); + assert.match(tree, /- heading "Welcome" \[level=1\]/); + assert.match(tree, /- link "Docs"/); + assert.match(tree, /- checkbox "Subscribe" \[checked\]/); + assert.match(tree, /- listitem: First point/); + assert.match(tree, /- img "Logo"/); + assert.doesNotMatch(tree, /Secret|Gone|Ignored/); + } finally { + await card.done(); + } + }, +); From 56c15b27c8bf35d49a5c399b00e39069ece6f047 Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:53:02 +0100 Subject: [PATCH 7/7] fix: close Mac card tabs whose page calls window.close() [skip ci] On the Mac, a popup that closed itself with window.close() stayed open as a tab. wry's UI delegate has no webViewDidClose:, so WebKit's request went unheard. OAuth sign-in popups finished, but left a tab behind. Each card view now has a small delegate in front of wry's. It notes webViewDidClose: and forwards every other message to wry's delegate, so popups, file uploads and the camera and microphone denial work as before. The next browser call drops the closed view, outside WebKit's callback, and the runtime closes its tab when browser_pages no longer lists it. A card's first tab can close itself too when it has one history entry, as in Chrome. Unit tests cover the close and the forwarding. A real WKWebView check confirmed that popups still open through the forwarded delegate and that both kinds of close are heard. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/browser/macos/mod.rs | 2 + src-tauri/src/browser/macos/self_close.rs | 171 ++++++++++++++++++++++ src-tauri/src/browser/macos/surface.rs | 16 +- 3 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 src-tauri/src/browser/macos/self_close.rs diff --git a/src-tauri/src/browser/macos/mod.rs b/src-tauri/src/browser/macos/mod.rs index 5bd2af4..73c1b0e 100644 --- a/src-tauri/src/browser/macos/mod.rs +++ b/src-tauri/src/browser/macos/mod.rs @@ -8,6 +8,7 @@ mod focus; mod human_input; mod input; mod script; +mod self_close; mod surface; use serde_json::Value; @@ -29,6 +30,7 @@ pub async fn call(app: AppHandle, method: String, input: Value) -> Result surface::create(app, input, reply), "browser_capture" => capture::capture(&input, reply), diff --git a/src-tauri/src/browser/macos/self_close.rs b/src-tauri/src/browser/macos/self_close.rs new file mode 100644 index 0000000..681dbe7 --- /dev/null +++ b/src-tauri/src/browser/macos/self_close.rs @@ -0,0 +1,171 @@ +//! A page's `window.close()`. wry's UI delegate has no `webViewDidClose:`, so WebKit's +//! request to close a page went unheard and the page stayed open as a tab. This delegate +//! sits in front of wry's: it notes the request and passes every other UI delegate +//! message to wry's unchanged, so popups, uploads and the camera and microphone denial +//! work as before. +use std::cell::Cell; + +use objc2::{ + define_class, msg_send, + rc::Retained, + runtime::{AnyObject, Bool, NSObject, Sel}, + AllocAnyThread, DefinedClass, +}; +use objc2_web_kit::WKWebView; + +pub(super) struct Ivars { + wry: Option>, + requested: Cell, +} + +define_class!( + #[unsafe(super(NSObject))] + #[name = "MemCodeSelfCloseListener"] + #[ivars = Ivars] + pub(super) struct SelfCloseListener; + + impl SelfCloseListener { + #[unsafe(method(webViewDidClose:))] + fn web_view_did_close(&self, _page: &AnyObject) { + self.ivars().requested.set(true); + } + + /// WebKit asks once, when the delegate is set, which messages it may send. + #[unsafe(method(respondsToSelector:))] + fn responds_to_selector(&self, selector: Sel) -> Bool { + let own: Bool = unsafe { msg_send![super(self), respondsToSelector: selector] }; + Bool::new(own.as_bool() || self.wry_handles(selector)) + } + + #[unsafe(method(forwardingTargetForSelector:))] + fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject { + match &self.ivars().wry { + Some(wry) if self.wry_handles(selector) => Retained::as_ptr(wry).cast_mut(), + _ => std::ptr::null_mut(), + } + } + } +); + +impl SelfCloseListener { + fn wry_handles(&self, selector: Sel) -> bool { + self.ivars().wry.as_deref().is_some_and(|wry| { + let answer: Bool = unsafe { msg_send![wry, respondsToSelector: selector] }; + answer.as_bool() + }) + } + + fn new(wry: Option>) -> Retained { + let listener = Self::alloc().set_ivars(Ivars { wry, requested: Cell::new(false) }); + unsafe { msg_send![super(listener), init] } + } + + /// Puts a listener in front of the view's UI delegate. The caller keeps it alive: + /// WebKit holds UI delegates weakly. + pub(super) fn install(wk: &WKWebView) -> Retained { + let wry: Option> = unsafe { msg_send![wk, UIDelegate] }; + let listener = Self::new(wry); + let _: () = unsafe { msg_send![wk, setUIDelegate: &*listener] }; + listener + } + + /// The page asked to close itself. + pub(super) fn requested(&self) -> bool { + self.ivars().requested.get() + } +} + +#[cfg(test)] +mod tests { + use std::{ffi::CStr, rc::Rc}; + + use block2::{Block, RcBlock}; + use objc2::{sel, ClassType}; + + use super::*; + + const CAMERA: isize = 0; + const DENY: isize = 2; + const MEDIA_PERMISSION: &CStr = + c"webView:requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:"; + + // Stands in for wry's delegate: denies camera and microphone, as MemCode's handler does. + define_class!( + #[unsafe(super(NSObject))] + #[name = "MemCodeTestWryUIDelegate"] + struct FakeWryDelegate; + + impl FakeWryDelegate { + #[unsafe(method(webView:requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:))] + fn request_media_capture_permission( + &self, + _page: &AnyObject, + _origin: &AnyObject, + _frame: &AnyObject, + _kind: isize, + decide: &Block, + ) { + decide.call((DENY,)); + } + } + ); + + fn listener() -> Retained { + let wry: Retained = unsafe { msg_send![FakeWryDelegate::class(), new] }; + SelfCloseListener::new(Some(wry)) + } + + fn answers(delegate: &AnyObject, selector: Sel) -> bool { + let answer: Bool = unsafe { msg_send![delegate, respondsToSelector: selector] }; + answer.as_bool() + } + + /// Sends the request the way WebKit does. objc2's debug check would refuse it, + /// because the listener's own class lacks the method; forwarding is what is tested. + fn ask_for_camera(delegate: &AnyObject, decide: &Block) { + type Send = unsafe extern "C-unwind" fn( + &AnyObject, + Sel, + &AnyObject, + &AnyObject, + &AnyObject, + isize, + &Block, + ); + let send: Send = unsafe { std::mem::transmute(objc2::ffi::objc_msgSend as *const ()) }; + let stand_in = NSObject::new(); + let selector = Sel::register(MEDIA_PERMISSION); + unsafe { send(delegate, selector, &stand_in, &stand_in, &stand_in, CAMERA, decide) }; + } + + #[test] + fn notes_a_page_closing_itself() { + let listener = listener(); + assert!(!listener.requested()); + assert!(answers(&listener, sel!(webViewDidClose:))); + + let page = NSObject::new(); + let _: () = unsafe { msg_send![&*listener, webViewDidClose: &*page] }; + + assert!(listener.requested()); + } + + #[test] + fn camera_requests_still_reach_wrys_handler() { + let listener = listener(); + assert!(answers(&listener, Sel::register(MEDIA_PERMISSION))); + + let decided = Rc::new(Cell::new(None)); + let record = decided.clone(); + let decide = RcBlock::new(move |decision: isize| record.set(Some(decision))); + ask_for_camera(&listener, &decide); + + assert_eq!(decided.get(), Some(DENY)); + } + + #[test] + fn claims_nothing_wry_does_not_handle() { + let alerts = sel!(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:); + assert!(!answers(&listener(), alerts)); + } +} diff --git a/src-tauri/src/browser/macos/surface.rs b/src-tauri/src/browser/macos/surface.rs index 4ae1e2f..880f5ec 100644 --- a/src-tauri/src/browser/macos/surface.rs +++ b/src-tauri/src/browser/macos/surface.rs @@ -16,7 +16,7 @@ use wry::{ WebViewBuilderExtMacos, WebViewExtMacOS, }; -use super::{address_policy, focus, human_input, input, Reply}; +use super::{address_policy, focus, human_input, input, self_close::SelfCloseListener, Reply}; use crate::native::Bounds; const INITIAL_BOUNDS: Bounds = Bounds { @@ -35,6 +35,7 @@ pub(super) struct Surface { bounds: Bounds, visible: bool, loads: Rc>, + self_close: Retained, } thread_local! { @@ -128,6 +129,7 @@ fn build( unsafe { view.manager().addContentRuleList(&rules) }; } let wk = Retained::into_super(view.webview()); + let self_close = SelfCloseListener::install(&wk); Ok(Surface { owner: owner.to_owned(), wk, @@ -136,9 +138,21 @@ fn build( bounds: INITIAL_BOUNDS, visible: false, loads, + self_close, }) } +/// Drops the pages that called `window.close()`. This runs at the start of a browser +/// call, outside WebKit's own callback. The runtime then sees them missing from +/// `browser_pages` and closes their tabs. +pub(super) fn remove_self_closed() { + SURFACES.with(|surfaces| { + if let Ok(mut surfaces) = surfaces.try_borrow_mut() { + surfaces.retain(|_, surface| !surface.self_close.requested()); + } + }); +} + fn open_popup( app: &AppHandle, owner: &str,