From ec452dfe59041f682e98ddf102ec0d50cddccc1c Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:53:04 +1000 Subject: [PATCH 01/44] fix(browser): snapshot and search deep accessibility trees --- packages/gui-plugins/src/browser/chromium.ts | 102 +++++----------- .../gui-plugins/src/browser/snapshot.test.ts | 48 ++++++++ packages/gui-plugins/src/browser/snapshot.ts | 115 ++++++++++++++++++ packages/plugin-browser/src/rpc.ts | 4 +- 4 files changed, 195 insertions(+), 74 deletions(-) create mode 100644 packages/gui-plugins/src/browser/snapshot.test.ts create mode 100644 packages/gui-plugins/src/browser/snapshot.ts diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index c6adf802fc4..467d0e710ff 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,5 +1,6 @@ import { homedir } from "node:os" import { navigationTurn } from "./navigation-turn" +import { accessibilitySnapshot } from "./snapshot" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" import electron, { type BrowserWindow, type WebContents } from "electron" @@ -1339,7 +1340,7 @@ export function createBrowserPage( return result({ tab: state(), frames: await frames() }) case "snapshot": case "find": - return result({ tab: state(), ...(await snapshot(action)) }) + return result({ tab: state(), ...(await snapshot(action, signal)) }) case "evaluate": { if (action.ref && action.frameID) throw new Error( @@ -2235,7 +2236,8 @@ export function createBrowserPage( await input("Input.dispatchKeyEvent", { type: "keyUp", ...params }) } - async function snapshot(action: Extract) { + async function snapshot(action: Extract, signal: AbortSignal) { + const generation = documentGeneration(documentState) const tree = await frames() const selected = action.type === "snapshot" && action.ref ? target(action.ref) : undefined const named = selected?.frameID ?? action.frameID @@ -2246,79 +2248,35 @@ export function createBrowserPage( "Frame is unavailable. Call browser.frames({tabID}) and use a current frameID from this tab; omit frameID for the main frame.", ) const sessionID = sessionFor(frameID, tree) - const depth = action.type === "snapshot" ? (action.depth ?? 8) : 8 - const ax = await cdp.send("Accessibility.getFullAXTree", { frameId: frameID, depth }, sessionID) - const nodes = new Map(ax.nodes.map((node) => [node.nodeId, node])) - const root = selected ? ax.nodes.find((node) => node.backendDOMNodeId === selected.backendID) : ax.nodes[0] + const ax = await cdp.send("Accessibility.getFullAXTree", { frameId: frameID }, sessionID) + abortError(signal) - if (!root) - throw new Error( - "Element is absent from this frame's accessibility snapshot. Retry browser.snapshot with the same tabID and no ref to refresh the frame, then choose a returned ref.", - ) + const byNode = (source: Map) => new Map(Array.from(source) + .filter(([, element]) => element.frameID === frameID && element.sessionID === sessionID) + .map(([ref, element]) => [element.backendID, ref])) + + const snapshot = await accessibilitySnapshot(ax.nodes, { + root: selected?.backendID, + depth: action.type === "snapshot" ? action.depth : undefined, + text: action.type === "find" ? action.text : undefined, + previous: byNode(refs), + picked: byNode(picked), + ref: options.shared.ref, + box: action.type === "snapshot" && action.boxes ? async (backendID) => { + abortError(signal) + const box = await rect({ backendID, frameID, sessionID }).catch(() => undefined) + + return box ? ` box=${JSON.stringify(box)}` : "" + } : undefined, + }) + + abortError(signal) + + if (documentGeneration(documentState) !== generation) throw new CodedError(Browser.FailureCode.documentChanged, "Document changed during snapshot; request a fresh snapshot.") refs.clear() - const pinned = new Map(Array.from(picked, ([ref, element]) => [`${element.frameID}:${element.backendID}`, ref])) - const lines: string[] = [] - let truncated = false + snapshot.refs.forEach((backendID, ref) => refs.set(ref, { backendID, frameID, sessionID })) - const walk = async (node: Protocol.Accessibility.AXNode, level: number): Promise => { - if (level > depth || lines.length >= 500) { - truncated = true - - return - } - - const role = String(node.role?.value ?? "node") - .replace(/[^a-zA-Z0-9_-]/g, "") - .slice(0, 40) - - const properties = new Map(node.properties?.map((property) => [property.name, property.value.value]) ?? []) - - if (!node.ignored) { - const actionable = - role !== "RootWebArea" && - (properties.get("focusable") || /^(button|link|textbox|combobox|checkbox|radio|option)$/.test(role)) - - // A picked element keeps the ref its comment names, even when it is not otherwise actionable. - const known = node.backendDOMNodeId ? pinned.get(`${frameID}:${node.backendDOMNodeId}`) : undefined - const ref = known ?? (actionable && node.backendDOMNodeId ? options.shared.ref() : "") - const element = node.backendDOMNodeId ? { backendID: node.backendDOMNodeId, frameID, sessionID } : undefined - - if (ref && element && !known) refs.set(ref, element) - - const flags = (["checked", "disabled", "expanded", "selected"] as const).flatMap((name) => - properties.has(name) ? [`${name}=${properties.get(name)}`] : [], - ) - - const box = - action.type === "snapshot" && action.boxes && ref && element - ? await rect(element).catch(() => undefined) - : undefined - - lines.push( - `${" ".repeat(level)}${ref ? `@${ref} ` : ""}[${role}] ${JSON.stringify( - String(node.name?.value ?? "") - .replace(/\s+/g, " ") - .slice(0, 300), - )} ${flags.join(" ")}${box ? ` box=${JSON.stringify(box)}` : ""}`, - ) - } - - if (["textbox", "searchbox"].includes(role) || properties.get("editable")) return - - for (const childID of node.childIds ?? []) { - const child = nodes.get(childID) - - if (child) await walk(child, level + 1) - } - } - - await walk(root, 0) - - const content = ( - action.type === "find" ? lines.filter((line) => line.toLowerCase().includes(action.text.toLowerCase())) : lines - ).join("\n") - - return { content: content.slice(0, Browser.MAX_TEXT), truncated: truncated || content.length > Browser.MAX_TEXT } + return { content: snapshot.content, truncated: snapshot.truncated } } /** Moves the picker and runs its effects; resolves once they ran, so input waits for the picker to disarm. */ diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts new file mode 100644 index 00000000000..38cfa18c7f9 --- /dev/null +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -0,0 +1,48 @@ +import { expect, test } from "bun:test" +import type { Protocol } from "devtools-protocol" +import { accessibilitySnapshot } from "./snapshot" + +function node(id: number, role: string, name: string, ...children: number[]): Protocol.Accessibility.AXNode { + return { + nodeId: String(id), + backendDOMNodeId: id, + ignored: false, + role: { type: "role", value: role }, + name: { type: "string", value: name }, + childIds: children.map(String), + } +} + +function options() { + let id = 0 + + return { previous: new Map(), picked: new Map(), ref: () => `e${++id}` } +} + +test("empty wrappers cost neither depth nor indentation; named groups and picked elements survive", async () => { + const wrappers = Array.from({ length: 80 }, (_, i) => node(i + 1, "generic", "", i + 2)) + const tree = [...wrappers, node(81, "group", "Toolbar", 82), node(82, "button", "Save")] + const setup = options() + setup.picked.set(72, "e99") + const result = await accessibilitySnapshot(tree, setup) + expect(result.content.split("\n")).toEqual(['@e99 [generic] ""', ' [group] "Toolbar"', ' @e1 [button] "Save"']) + expect(result.truncated).toBe(false) + expect((await accessibilitySnapshot(tree, { ...setup, depth: 1 })).truncated).toBe(true) + expect((await accessibilitySnapshot(tree, { ...setup, root: 82, previous: new Map([[82, "e1"]]) })).content).toBe( + '@e1 [button] "Save"', + ) +}) + +test("budgets whole lines, not traversal: find reaches the last item of a truncated snapshot", async () => { + const buttons = Array.from({ length: 2000 }, (_, i) => node(i + 1, "button", `${"x".repeat(80)} ${i}`)) + const tree = [node(0, "group", "List", ...buttons.map((_, i) => i + 1)), ...buttons] + const setup = options() + const page = await accessibilitySnapshot(tree, setup) + expect(page.truncated).toBe(true) + expect(page.content.length).toBeLessThanOrEqual(100_000) + expect(page.content).toEndWith('"') + expect(page.content).not.toContain(' 1999"') + const match = await accessibilitySnapshot(tree, { ...setup, text: " 1999" }) + expect(match.truncated).toBe(false) + expect([...match.refs.values()]).toEqual([2000]) +}) diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts new file mode 100644 index 00000000000..33d806deba6 --- /dev/null +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -0,0 +1,115 @@ +import type { Protocol } from "devtools-protocol" +import { Browser } from "@opencode/plugin-browser/rpc" + +/** Shape one frame's AX tree. Frame documents have their own target checks and are requested by frameID. */ +export async function accessibilitySnapshot( + nodes: readonly Protocol.Accessibility.AXNode[], + options: { + root?: number + depth?: number + text?: string + previous: ReadonlyMap + picked: ReadonlyMap + ref: () => string + box?: (id: number) => Promise + }, +) { + const root = options.root === undefined ? nodes[0] : nodes.find((node) => node.backendDOMNodeId === options.root) + + if (!root) + throw new Error("Element is absent from this frame's accessibility snapshot. Refresh the snapshot without ref.") + + const index = new Map(nodes.map((node) => [node.nodeId, node])) + const pending = [{ node: root, level: 0 }] + const seen = new Set() + const refs = new Map() + const lines: string[] = [] + const query = options.text?.toLowerCase() + let size = 0 + let truncated = false + + while (pending.length) { + const { node, level } = pending.pop()! + + if (seen.has(node.nodeId)) continue + seen.add(node.nodeId) + + const role = String(node.role?.value ?? "node") + .replace(/[^a-zA-Z0-9_-]/g, "") + .slice(0, 40) + + const name = String(node.name?.value ?? "").replace(/\s+/g, " ") + const id = node.backendDOMNodeId + const picked = id && options.picked.get(id) + const props = new Map(node.properties?.map((p) => [p.name, p.value.value])) + const editable = role === "textbox" || role === "searchbox" || props.get("editable") + + const actionable = + role !== "RootWebArea" && + (props.get("focusable") || + /^(button|link|textbox|combobox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem)$/.test( + role, + )) + + const children = node.childIds ?? [] + + const wrapper = + role === "generic" && + !name && + !actionable && + !editable && + !picked && + !node.value && + !node.description && + !props.size && + children.length === 1 + + const visible = !node.ignored && !wrapper && role !== "InlineTextBox" + + if (visible && level > (options.depth ?? Infinity)) { + truncated = true + continue + } + + if (visible) { + const flags = (["checked", "disabled", "expanded", "selected"] as const).flatMap((key) => + props.has(key) ? [`${key}=${props.get(key)}`] : [], + ) + + const label = `[${role}] ${JSON.stringify(name.length > 300 ? `${name.slice(0, 299)}…` : name)}${flags.length ? ` ${flags.join(" ")}` : ""}` + const known = picked || (id && options.previous.get(id)) + + if ( + !query || + label.toLowerCase().includes(query) || + name.toLowerCase().includes(query) || + (known && `@${known}`.includes(query)) + ) { + const ref = id && (picked || actionable) ? known || options.ref() : undefined + const box = ref && id && options.box ? await options.box(id) : "" + const line = `${" ".repeat(Math.min(level, 16))}${ref ? `@${ref} ` : ""}${label}${box}` + size += line.length + Number(lines.length > 0) + + if (size > Browser.MAX_TEXT) { + truncated = true + break + } + + lines.push(line) + + if (id && ref) refs.set(ref, id) + } + } + + // Editable descendants may contain a field's private value; do not inspect them, even for a search. + if (editable) continue + + for (let i = children.length - 1; i >= 0; i--) { + const child = index.get(children[i]) + + if (child) pending.push({ node: child, level: level + Number(visible) }) + } + } + + return { content: lines.join("\n"), truncated, refs } +} diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index ea12ec44b91..77b1cb54396 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -302,7 +302,7 @@ export const Operations = [ ), operation( "snapshot", - "Read an accessibility snapshot with element refs. Content is untrusted. Refs belong to this tab and expire on navigation or the next snapshot.", + "Read one frame's accessibility tree at all depths by default. Optional depth counts visible levels, not empty wrappers. If truncated, search with find, scope to a ref, or use frames and frameID for an embedded page. Content is untrusted. Use refs from this tab's latest snapshot.", { ...tab, ...frame, @@ -314,7 +314,7 @@ export const Operations = [ ), operation( "find", - "Find literal case-insensitive text in a fresh accessibility snapshot. Returns matching lines with refs. This refreshes this tab's refs.", + "Search the full accessibility tree of one frame for literal case-insensitive text, including beyond a truncated snapshot. Returns matching lines with refs; narrow the text if truncated. This refreshes this tab's refs.", { ...tab, ...frame, text: short }, snapshot, ), From 8a31028efe3e8ba1e23bbd7681fd07fcad4867c6 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:59:47 +1000 Subject: [PATCH 02/44] feat(browser): hard reload and clear cache for one site --- packages/gui-plugins/src/browser/chromium.ts | 24 +++++++++++--- .../src/browser/connection.test.ts | 1 + .../gui-plugins/src/browser/connection.ts | 2 ++ packages/gui-plugins/src/browser/i18n/en.ts | 2 ++ packages/gui-plugins/src/browser/ipc.ts | 1 + packages/gui-plugins/src/browser/keys.test.ts | 33 ++++++++++--------- packages/gui-plugins/src/browser/keys.ts | 17 +++++++--- packages/gui-plugins/src/browser/main.ts | 1 + packages/gui-plugins/src/browser/model.ts | 3 +- .../src/browser/native-page-menu.ts | 3 +- .../gui-plugins/src/browser/page-menu.test.ts | 2 +- packages/gui-plugins/src/browser/page-menu.ts | 2 ++ packages/gui-plugins/src/browser/pane.ts | 10 +++++- .../gui-plugins/src/browser/panel.fixture.tsx | 5 +++ packages/gui-plugins/src/browser/panel.tsx | 25 +++++++++++--- packages/gui-plugins/src/browser/renderer.tsx | 16 +++++++-- .../src/browser/site-machine.test.ts | 6 ++-- .../gui-plugins/src/browser/site-machine.ts | 7 ++-- packages/plugin-browser/src/rpc.ts | 4 +-- 19 files changed, 120 insertions(+), 44 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 467d0e710ff..456b32c7b6e 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -345,9 +345,11 @@ export function createBrowserPage( activity.userInputAt = Date.now() void choosers.update().catch(() => undefined) - if (pageReload(input, process.platform === "darwin")) { + const refresh = pageReload(input, process.platform === "darwin") + + if (refresh) { event.preventDefault() - void reload().catch((error: Error) => publish(error.message)) + void reload(options.signal, refresh === "hard").catch((error: Error) => publish(error.message)) return } @@ -1009,7 +1011,7 @@ export function createBrowserPage( .finally(() => contents.off("did-navigate", commit)) } - const reload = async (signal = options.signal) => { + const reload = async (signal = options.signal, ignoreCache = false) => { const tab = state() if (navigation.interrupt("reload", documentState.status === "restoring" ? documentState.url : undefined)) return @@ -1022,7 +1024,7 @@ export function createBrowserPage( if (address) return void await load(address, true, signal) - return begin(signal)(actual, () => contents.reload()) + return begin(signal)(actual, () => ignoreCache ? contents.reloadIgnoringCache() : contents.reload()) } const ready = navigationDeadline(Promise.all([ @@ -1103,6 +1105,18 @@ export function createBrowserPage( () => undefined, ) }, + async clearCache(address: string) { + const origin = destinationOrigin(address) + + if (closed() || !origin || destinationOrigin(contents.getURL()) !== origin) throw new Error("browser.site.changed") + // Session.clearCache() clears the entire partition; clearData can filter the HTTP cache by origin. + await contents.session.clearData({ + origins: [origin], originMatchingMode: "origin-in-all-contexts", dataTypes: ["cache", "serviceWorkers"], + }) + await contents.session.clearStorageData({ origin, storages: ["cachestorage"] }) + + if (!closed() && destinationOrigin(contents.getURL()) === origin) await reload(options.signal, true) + }, /** Reports the page's icon and zoom when either changed since the last report. */ detail, /** Takes a download this page started; see `guardSession`. */ @@ -1324,7 +1338,7 @@ export function createBrowserPage( if (entry) await begin(signal)(entry.url, () => history.goToIndex(index), () => !closed() && contents.isLoading()) } - if (action.type === "reload" && !saved) await reload(signal) + if (action.type === "reload" && (!saved || action.ignoreCache)) await reload(signal, action.ignoreCache) if (action.type === "stop") { navigation.cancel() diff --git a/packages/gui-plugins/src/browser/connection.test.ts b/packages/gui-plugins/src/browser/connection.test.ts index a5c51194c15..d2dad473b9b 100644 --- a/packages/gui-plugins/src/browser/connection.test.ts +++ b/packages/gui-plugins/src/browser/connection.test.ts @@ -38,6 +38,7 @@ function fixture(reject?: Error) { zoom: async () => undefined, site: async () => ({ cookies: 0 }), clearSite: async () => undefined, + clearCache: async () => undefined, reveal: async () => undefined, close: async (input) => { closed.push(input.binding) diff --git a/packages/gui-plugins/src/browser/connection.ts b/packages/gui-plugins/src/browser/connection.ts index 4e7de530ed5..8fb5a68e9e1 100644 --- a/packages/gui-plugins/src/browser/connection.ts +++ b/packages/gui-plugins/src/browser/connection.ts @@ -25,6 +25,7 @@ export type Registration = { answer(tabID: Browser.TabID, id: number, answer: PromptAnswer): Promise site(tabID: Browser.TabID): Promise<{ cookies: number }> clearSite(tabID: Browser.TabID): Promise + clearCache(tabID: Browser.TabID, address: string): Promise reveal(tabID: Browser.TabID): Promise close(): void } @@ -84,6 +85,7 @@ export function openBinding(input: { }, site: (tabID) => ready.then(() => client.site({ binding, tabID })), clearSite: (tabID) => ready.then(() => client.clearSite({ binding, tabID })), + clearCache: (tabID, address) => ready.then(() => client.clearCache({ binding, tabID, address })), reveal: (tabID) => ready.then(() => client.reveal({ binding, tabID })), close() { if (status.closed) return diff --git a/packages/gui-plugins/src/browser/i18n/en.ts b/packages/gui-plugins/src/browser/i18n/en.ts index 45aaa635c84..d6acb66355d 100644 --- a/packages/gui-plugins/src/browser/i18n/en.ts +++ b/packages/gui-plugins/src/browser/i18n/en.ts @@ -196,6 +196,8 @@ export default { "menu.back": "Back", "menu.forward": "Forward", "menu.reload": "Reload", + "menu.hardReload": "Reload ignoring cache", + "site.clearCache": "Clear cache for this site", "menu.openLink": "Open link in new tab", "menu.external": "Open link in system browser", "menu.copyLink": "Copy link address", diff --git a/packages/gui-plugins/src/browser/ipc.ts b/packages/gui-plugins/src/browser/ipc.ts index 9e8dec85db5..0f5ea3227d6 100644 --- a/packages/gui-plugins/src/browser/ipc.ts +++ b/packages/gui-plugins/src/browser/ipc.ts @@ -245,6 +245,7 @@ export const BrowserPane = Ipc.define({ }, // Deletes the cookies the page's address can read and its origin's stored data, then reloads the page. clearSite: { input: Schema.Struct({ binding, tabID: Browser.TabID }) }, + clearCache: { input: Schema.Struct({ binding, tabID: Browser.TabID, address: text(16_384) }) }, reveal: { input: Schema.Struct({ binding, tabID: Browser.TabID }) }, close: { input: Schema.Struct({ binding }) }, forget: { input: Schema.Struct({server:text(16_384),session:text(256).check(Schema.isStartingWith("ses"))}) }, diff --git a/packages/gui-plugins/src/browser/keys.test.ts b/packages/gui-plugins/src/browser/keys.test.ts index 3ff94fe64f6..de48571d5f8 100644 --- a/packages/gui-plugins/src/browser/keys.test.ts +++ b/packages/gui-plugins/src/browser/keys.test.ts @@ -74,8 +74,8 @@ test("forwards browser and shell shortcuts while leaving page editing, reload an ["mod", ",", true, ","], ["mod", "\\", false, "\\"], ["mod+shift", "T", true, "t"], - ["mod+shift", "R", true, "r"], - ["mod+shift", "R", false, "r"], + ["mod+shift", "R", true, undefined], + ["mod+shift", "R", false, undefined], ["mod+shift", "P", true, "p"], ["mod+shift", "L", true, "l"], ["mod+shift", "E", true, "e"], @@ -152,21 +152,22 @@ test("forwards browser and shell shortcuts while leaving page editing, reload an }) test("reloads the focused page on F5 and the platform's reload chord, leaving other R chords to the window", () => { - const cases: [modifiers: string, key: string, mac: boolean, reloads: boolean, code?: string][] = [ - ["", "F5", true, true], - ["", "F5", false, true], - ["mod", "r", true, true], - ["mod", "r", false, true], + const cases: [modifiers: string, key: string, mac: boolean, reloads: ReturnType, code?: string][] = [ + ["", "F5", true, "normal"], + ["", "F5", false, "normal"], + ["mod", "r", true, "normal"], + ["mod", "r", false, "normal"], // Dvorak: R is on the physical O key; the character decides. - ["mod", "r", true, true, "KeyO"], - ["mod", "\u043a", true, true, "KeyR"], - // ⇧⌘R toggles review, and macOS Control+R is the page's own. - ["mod+shift", "R", true, false], - ["mod+shift", "R", false, false], - ["mod+alt", "r", true, false], - ["ctrl", "r", true, false], - ["mod", "F5", true, false], - ["", "r", true, false], + ["mod", "r", true, "normal", "KeyO"], + ["mod", "\u043a", true, "normal", "KeyR"], + ["mod+shift", "R", true, "hard"], + ["mod+shift", "R", false, "hard"], + ["mod", "F5", false, "hard"], + ["mod+alt", "r", true, undefined], + ["ctrl", "r", true, undefined], + ["mod", "F5", true, undefined], + ["ctrl", "F5", true, undefined], + ["", "r", true, undefined], ] const results = cases.map(([modifiers, key, mac, , code]) => [ diff --git a/packages/gui-plugins/src/browser/keys.ts b/packages/gui-plugins/src/browser/keys.ts index 3ef6db73a5e..089f43c72a8 100644 --- a/packages/gui-plugins/src/browser/keys.ts +++ b/packages/gui-plugins/src/browser/keys.ts @@ -35,7 +35,7 @@ const shellKeys = ["t", "w", "l", "f", "g", "n", "1", "2", "3", "4", "5", "6", " // Shifted chords with the platform's modifier that belong to the app shell rather than the page: reopening a tab, // switching side-panel tabs, toggling the side panel, opening the command palette, or running session commands. New Window and Close Window // (⇧⌘N, ⇧⌘W) stay unclaimed: only their menu accelerators handle them, and claiming a chord also blocks the menu. -const shellShiftKeys = ["t", "[", "]", "r", "g", "p", "l", "e", "o", "s"] +const shellShiftKeys = ["t", "[", "]", "g", "p", "l", "e", "o", "s"] // The side panel's launchers: Review, Browser and Open file, with ⌃⌘ on macOS and Ctrl+Alt elsewhere. Only a typed // Latin letter counts, so AltGr (Ctrl+Alt) typing on other layouts stays with the page. @@ -64,11 +64,20 @@ export function pageLetter(input: Pick) { * reloads itself; left to the window, the Reload menu item would reload the whole app. */ export function pageReload(input: PageKey, mac: boolean) { - if (input.alt || input.shift) return false + if (input.alt) return - if (input.key === "F5") return !input.meta && !input.control + if (input.key === "F5") { + if (input.meta || input.shift) return - return (mac ? input.meta && !input.control : input.control && !input.meta) && pageLetter(input) === "r" + if (!input.control) return "normal" + + if (!mac) return "hard" + + return + } + + if ((mac ? input.meta && !input.control : input.control && !input.meta) && pageLetter(input) === "r") + return input.shift ? "hard" : "normal" } /** diff --git a/packages/gui-plugins/src/browser/main.ts b/packages/gui-plugins/src/browser/main.ts index 6ea447d1cc7..b998d119aa6 100644 --- a/packages/gui-plugins/src/browser/main.ts +++ b/packages/gui-plugins/src/browser/main.ts @@ -145,6 +145,7 @@ const setup: Plugin.MainSetup = (ctx) => { zoom: async (input, caller) => (await pane()).zoom(caller.window, input.binding, input.tabID, input.zoom), site: async (input, caller) => (await pane()).site(caller.window, input.binding, input.tabID), clearSite: async (input, caller) => (await pane()).clearSite(caller.window, input.binding, input.tabID), + clearCache: async (input, caller) => (await pane()).clearCache(caller.window, input.binding, input.tabID, input.address), reveal: async (input, caller) => (await pane()).reveal(caller.window, input.binding, input.tabID), close: async (input, caller) => (await pane()).close(caller.window, input.binding), forget: async (input) => (await load()).forget(input.server,input.session), diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index 25de878dca8..c84286099b3 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -74,7 +74,7 @@ type PageDetail = { icon?: string; zoom: number } type PaneHandle = { visible: () => boolean address: () => string - reload: () => void + reload: (ignoreCache?: boolean) => void /** Closes the selected browser tab, including a blank page. */ close: () => void inspectable: () => boolean @@ -671,6 +671,7 @@ export function createModel(ctx: SetupContext) { site: (session: Session, tabID: Browser.TabID) => registration(session)?.site(tabID), /** Deletes the page's cookies and stored data, and reloads it. */ clearSite: (session: Session, tabID: Browser.TabID) => registration(session)?.clearSite(tabID), + clearCache: (session: Session, tabID: Browser.TabID, address: string) => registration(session)?.clearCache(tabID, address), revealFile: (session: Session, tabID: Browser.TabID) => registration(session)?.reveal(tabID), /** Pages the browser showed, newest first. */ visits: () => history.value.visits.filter((visit) => { diff --git a/packages/gui-plugins/src/browser/native-page-menu.ts b/packages/gui-plugins/src/browser/native-page-menu.ts index c4d7375e6f8..e47de63954d 100644 --- a/packages/gui-plugins/src/browser/native-page-menu.ts +++ b/packages/gui-plugins/src/browser/native-page-menu.ts @@ -10,7 +10,7 @@ import { extensionResource } from "./profile/extension-api/resource" export type PageMenuHost = { t: (key: string) => string extensions: (contents: number, params: Electron.ContextMenuParams) => Electron.MenuItemConstructorOptions[] - navigate: (action: "back" | "forward" | "reload") => Promise + navigate: (action: "back" | "forward" | "reload" | "hardReload") => Promise open: (url: string) => Promise } @@ -59,6 +59,7 @@ export function attachPageMenu( case "back": case "forward": case "reload": + case "hardReload": return input.navigate(action.type) case "cut": return contents.cut() diff --git a/packages/gui-plugins/src/browser/page-menu.test.ts b/packages/gui-plugins/src/browser/page-menu.test.ts index 918d25d9da6..3f7ca6bf1b5 100644 --- a/packages/gui-plugins/src/browser/page-menu.test.ts +++ b/packages/gui-plugins/src/browser/page-menu.test.ts @@ -99,7 +99,7 @@ test.each([ expect( template.filter((x) => x.type !== "separator").map((x) => `${x.enabled === false ? "!" : ""}${x.label}`), - ).toEqual(["!back", "forward", "reload", ...items, "Extension"]) + ).toEqual(["!back", "forward", "reload", "hardReload", ...items, "Extension"]) }, ) diff --git a/packages/gui-plugins/src/browser/page-menu.ts b/packages/gui-plugins/src/browser/page-menu.ts index 6bba986c1fc..dac0defd113 100644 --- a/packages/gui-plugins/src/browser/page-menu.ts +++ b/packages/gui-plugins/src/browser/page-menu.ts @@ -39,6 +39,7 @@ export type MenuAction = | "back" | "forward" | "reload" + | "hardReload" | "copyImage" | "cut" | "copy" @@ -79,6 +80,7 @@ export function pageMenu( item("back", { type: "back" }, options.back), item("forward", { type: "forward" }, options.forward), item("reload", { type: "reload" }), + item("hardReload", { type: "hardReload" }), ] const links = link diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 25d490500b6..40c2d8c6fe4 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -410,6 +410,10 @@ export function createBrowserPane(input: { return (await page(binding, tabID)?.site()) ?? { cookies: 0 } }, + async clearCache(window: number, binding: string, tabID: Browser.TabID, address: string) { + owned(window, binding) + await page(binding, tabID)?.clearCache(address) + }, async clearSite(window: number, binding: string, tabID: Browser.TabID) { owned(window, binding) await page(binding, tabID)?.clearSite() @@ -684,7 +688,11 @@ export function createBrowserPane(input: { menu: { t: input.t, extensions: (contents, params) => handle.shared ? input.profile.extensionMenu(contents, params) : [], - navigate: async (type) => { if (current()) await execute(binding, { action: { type, tabID: id }, files: [] }, handle.abort.signal, "user") }, + navigate: async (type) => { + const action = type === "hardReload" ? { type: "reload", tabID: id, ignoreCache: true } as const : { type, tabID: id } + + if (current()) await execute(binding, { action, files: [] }, handle.abort.signal, "user") + }, open: async (url) => { if (current()) await execute(binding, { action: { type: "tabs.open", url }, files: [] }, handle.abort.signal, "user", "new", childActivity(activity)) }, }, embeds: input.embeds, diff --git a/packages/gui-plugins/src/browser/panel.fixture.tsx b/packages/gui-plugins/src/browser/panel.fixture.tsx index 0bab9b25e81..d1f2fb6a3cb 100644 --- a/packages/gui-plugins/src/browser/panel.fixture.tsx +++ b/packages/gui-plugins/src/browser/panel.fixture.tsx @@ -492,6 +492,10 @@ export function browserPaneFixture(input: PaneHost | StoryHost) { setStore({ cookies: 0, generation: store.generation + 1 }) report() }, + clearCache: async () => { + setStore("generation", (value) => value + 1) + report() + }, close: async () => undefined, forget: async () => undefined, state: () => undefined, @@ -1263,6 +1267,7 @@ export function mountBrowserRegion(input: RegionHost) { zoom: async () => undefined, site: async () => ({ cookies: 0 }), clearSite: async () => undefined, + clearCache: async () => undefined, find: async () => undefined, notice: async () => undefined, answer: async () => undefined, diff --git a/packages/gui-plugins/src/browser/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index 70ca9af2bcc..217d07ddbd5 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -430,10 +430,10 @@ export default function SessionBrowserPane(props: { props.model.mount({ visible, address, - reload: () => { + reload: (ignoreCache) => { const tab = state() - if (tab) command({ type: "reload", tabID: tab.id }) + if (tab) command({ type: "reload", tabID: tab.id, ignoreCache }) }, close: () => { const tab = state() @@ -587,10 +587,11 @@ export default function SessionBrowserPane(props: { size="large" disabled={!state()?.loading && !address()} aria-label={plugin.t(state()?.loading ? "action.stop" : "action.reload")} - onClick={() => { + onClick={(event) => { const tab = state() - if (tab) command({ type: tab.loading ? "stop" : "reload", tabID: tab.id }) + if (!tab) return + command(tab.loading ? { type: "stop", tabID: tab.id } : { type: "reload", tabID: tab.id, ignoreCache: event.shiftKey }) }} icon={ }> @@ -659,6 +660,11 @@ export default function SessionBrowserPane(props: { return tab ? props.model.clearSite(props.session, tab.id) : undefined }} + clearCache={() => { + const tab = state() + + return tab ? props.model.clearCache(props.session, tab.id, address()) : undefined + }} /> @@ -1266,6 +1272,7 @@ function SiteInformation(props: { /** The page's cookie count; undefined while the pane cannot answer. */ site: () => Promise<{ cookies: number }> | undefined clear: () => Promise | undefined + clearCache: () => Promise | undefined }) { const plugin = usePlugin() const [siteState, setSiteState] = createSignal(initialSiteState) @@ -1303,7 +1310,7 @@ function SiteInformation(props: { return } - const pending = props.clear() + const pending = effect.type === "clear-cache" ? props.clearCache() : props.clear() if (!pending) return dispatch({ type: "clear.failed", attempt }) void pending.then( @@ -1409,6 +1416,14 @@ function SiteInformation(props: { {plugin.t(view().failed ? "common.retry" : "site.cookies.clear")} + = (ctx) => { bind: "f5", editable: true, enabled: pane.visible() && !!pane.address(), - run: pane.reload, + run: () => pane.reload(), } }) @@ -178,7 +178,19 @@ const setup: Plugin.Setup = (ctx) => { hidden: true, editable: true, enabled: pane.visible(), - run: pane.reload, + run: () => pane.reload(), + } + }) + + ctx.add(Command, (): Command | undefined => { + const pane = model()?.pane() + + if (!pane) return + + return { + id: "hardReload", title: ctx.t("menu.hardReload"), group: ctx.t("command.category.view"), + bind: mac ? "mod+shift+r" : "mod+shift+r,ctrl+f5", scope: "#browser-panel", editable: true, + enabled: pane.visible() && !!pane.address(), run: () => pane.reload(true), } }) diff --git a/packages/gui-plugins/src/browser/site-machine.test.ts b/packages/gui-plugins/src/browser/site-machine.test.ts index 620586e149e..01730697ac7 100644 --- a/packages/gui-plugins/src/browser/site-machine.test.ts +++ b/packages/gui-plugins/src/browser/site-machine.test.ts @@ -71,10 +71,10 @@ describe("a failed read", () => { }) describe("clearing", () => { - test("hides the old count and disables the button until the next read", () => { - const clearing = transitionSite(ready(), { type: "clear.clicked" }) + test.each([["clear.clicked", "clear"], ["clear-cache.clicked", "clear-cache"]] as const)("%s disables both actions and clears only the requested data", (type, effect) => { + const clearing = transitionSite(ready(), { type }) - expect(clearing.effects).toEqual([{ type: "clear", attempt: 2 }]) + expect(clearing.effects).toEqual([{ type: effect, attempt: 2 }]) expect(siteView(clearing.state)).toMatchObject({ open: true, cookies: undefined, actionDisabled: true }) expect(transitionSite(clearing.state, { type: "clear.clicked" }).state).toBe(clearing.state) diff --git a/packages/gui-plugins/src/browser/site-machine.ts b/packages/gui-plugins/src/browser/site-machine.ts index daa5fba52d7..edf9c363d5e 100644 --- a/packages/gui-plugins/src/browser/site-machine.ts +++ b/packages/gui-plugins/src/browser/site-machine.ts @@ -22,7 +22,7 @@ export type SiteEvent = | { readonly type: "retry" } | { readonly type: "load.succeeded"; readonly attempt: number; readonly cookies: number } | { readonly type: "load.failed"; readonly attempt: number } - | { readonly type: "clear.clicked" } + | { readonly type: "clear.clicked" | "clear-cache.clicked" } | { readonly type: "clear.succeeded"; readonly attempt: number } | { readonly type: "clear.failed"; readonly attempt: number } | { readonly type: "timeout"; readonly phase: "loading" | "clearing"; readonly attempt: number } @@ -31,7 +31,7 @@ export type SiteEvent = export type SiteEffect = | { readonly type: "load"; readonly attempt: number } - | { readonly type: "clear"; readonly attempt: number } + | { readonly type: "clear" | "clear-cache"; readonly attempt: number } | { readonly type: "notify-clear-failed" } export type SiteTransition = { readonly state: SiteState; readonly effects: readonly SiteEffect[] } @@ -61,11 +61,12 @@ export function transitionSite(state: SiteState, event: SiteEvent): SiteTransiti return { state: { status: "failed", attempt: state.attempt }, effects: [] } case "clear.clicked": + case "clear-cache.clicked": if (state.status !== "ready") return unchanged(state) return { state: { status: "clearing", attempt: state.attempt + 1, open: true }, - effects: [{ type: "clear", attempt: state.attempt + 1 }], + effects: [{ type: event.type === "clear-cache.clicked" ? "clear-cache" : "clear", attempt: state.attempt + 1 }], } case "clear.succeeded": return cleared(state, event.attempt, []) diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 77b1cb54396..43dafc982d7 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -286,8 +286,8 @@ export const Operations = [ operation("forward", "Go forward in this tab and wait for loading to finish.", tab, Tab), operation( "reload", - "Reload this tab and wait for loading to finish. Use after starting a performance capture.", - tab, + "Reload this tab and wait for loading to finish. Set ignoreCache to bypass cached resources for this reload. Use after starting a performance capture.", + { ...tab, ignoreCache: optional(Schema.Boolean) }, Tab, ), operation("stop", "Stop loading this tab. This does not stop a trace or CPU recording.", tab, Tab), From 292141ac447bbe6f87ef8b03e529f973a15a3b31 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:11:12 +1000 Subject: [PATCH 03/44] fix(browser): report unattached sessions without failing tool calls --- packages/core/test/browser-permission.test.ts | 17 +++----- packages/core/test/browser-tools.test.ts | 8 +--- packages/plugin-browser/src/connection.ts | 2 +- packages/plugin-browser/src/machine.ts | 4 +- packages/plugin-browser/src/tools.ts | 39 ++++++------------- 5 files changed, 22 insertions(+), 48 deletions(-) diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index f872042b67b..ca7e6518591 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -186,7 +186,7 @@ it.live("a subagent's session loses the inherited grant before its first prompt yield* sessions.prompt({ sessionID: child.id, text: "Take a screenshot", resume: false }) expect(yield* browser.permissions(child.id)).toEqual([]) expect(yield* browser.permissions()).toEqual([...grant]) - expect((yield* browser.call("general", child.id).pipe(Effect.flip)).message).toStartWith("[browser.disconnected]") + expect((yield* browser.call("general", child.id)).output).toMatchObject({ connected: false }) expect((yield* browser.call()).output).toEqual({ tabs: [], focusedTabID: null }) }), ) @@ -424,16 +424,11 @@ it.live("without a deny, a session with no desktop hears that it is disconnected const detached = yield* sessions.create({ location: browser.ref }) yield* Effect.promise(() => Bun.write(path.join(browser.ref.directory, "page.html"), "

page

")) // Whether the file exists is not said: without a desktop no permission check, policies included, can run. - for (const file of ["page.html", "missing.html"]) - expect(yield* refusal(browser, "preview", { path: file }, detached.id)).toStartWith( - `[browser.disconnected] ${path.join(browser.ref.directory, file)} was not shown`, - ) - expect(yield* refusal(browser, "wait", { tabID: tab.id, selector: "#done" }, detached.id)).toStartWith( - "[browser.disconnected]", - ) - expect(yield* refusal(browser, "snapshot", { tabID: missingTab }, detached.id)).toStartWith( - "[browser.disconnected]", - ) + const status = (yield* browser.call("build", detached.id)).output + expect(status).toMatchObject({ connected: false, message: expect.stringContaining("retry only after it attaches") }) + for (const [op, input] of [["preview", { path: "page.html" }], ["preview", { path: "missing.html" }], ["wait", { tabID: tab.id, selector: "#done" }], ["snapshot", { tabID: missingTab }]] as const) + expect((yield* browser.run(op, input, "build", detached.id)).output).toEqual(status) + expect(browser.commands.count).toBe(0) }), ) diff --git a/packages/core/test/browser-tools.test.ts b/packages/core/test/browser-tools.test.ts index fb0080d2df6..34719072df9 100644 --- a/packages/core/test/browser-tools.test.ts +++ b/packages/core/test/browser-tools.test.ts @@ -293,7 +293,7 @@ it.live("HTML preview passes the checked relative path and requires a usable tab }), ) -it.live("preview fails for a missing file, and without a desktop names the file to tell the user", () => +it.live("preview fails for a missing file, and returns attachment status without a desktop", () => Effect.gen(function* () { const browser = yield* setup((action) => success(action.type === "preview" ? { path: action.path } : tab)) yield* Effect.promise(() => Bun.write(join(browser.directory, "chart.svg"), "")) @@ -307,10 +307,6 @@ it.live("preview fails for a missing file, and without a desktop names the file const detached = yield* setup(() => success(tab), { attach: false }) yield* Effect.promise(() => Bun.write(join(detached.directory, "chart.svg"), "")) - expect( - yield* detached.run(`return await tools.browser.preview({ path: "chart.svg" }).catch((error) => error.message)`), - ).toContain( - `[browser.disconnected] ${join(detached.directory, "chart.svg")} was not shown: no OpenCode desktop app is connected to this session`, - ) + expect(JSON.parse(yield* detached.run(`return await tools.browser.preview({ path: "chart.svg" })`))).toMatchObject({ connected: false }) }), ) diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index 347fcd738cc..fca3ef1f802 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -414,7 +414,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( */ authorize: Effect.fn("BrowserConnection.authorize")(function* (tool: Tool.Context, action: Browser.Action | Extract, paths?: readonly string[]) { const connection = BrowserMachine.selectConnection(machine.state, tool.sessionID) - if (!connection.ok) return yield* connection.error + if (!connection.ok) return { connected: false as const, message: connection.error.message } const tab = "tabID" in action ? connection.tabs.find((tab) => tab.id === action.tabID) : undefined const origin = site(tab?.url) const destination = action.type === "tabs.open" ? action.url ?? "about:blank" : action.type === "navigate" ? action.url : undefined diff --git a/packages/plugin-browser/src/machine.ts b/packages/plugin-browser/src/machine.ts index 8f5089f28e9..1984cdfb1f7 100644 --- a/packages/plugin-browser/src/machine.ts +++ b/packages/plugin-browser/src/machine.ts @@ -649,7 +649,7 @@ export function selectConnection( ok: false, error: new Tool.Error({ message: - "[browser.disconnected] No OpenCode desktop app is connected to this session, so no browser action ran. The browser runs inside the desktop app and works only while the user has this session open there. Tell the user, and continue without the browser until they open it; calling again before then fails the same way.", + "No browser is attached to this session. It attaches when the session is open in the OpenCode desktop app. No action ran. Continue without the browser; retry only after it attaches.", }), } @@ -658,7 +658,7 @@ export function selectConnection( ok: false, error: new Tool.Error({ message: - "[browser.disconnected] The desktop browser is still connecting to this session; no action ran. Call browser.tabs.list({}) once it finishes connecting.", + "The desktop browser is still connecting to this session. No action ran. Retry only after it attaches.", }), } diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index bff9a167a22..b96b20ab912 100644 --- a/packages/plugin-browser/src/tools.ts +++ b/packages/plugin-browser/src/tools.ts @@ -4,7 +4,7 @@ import type { Context } from "@opencode/plugin/effect/plugin" import { Tool } from "@opencode/schema/tool" import { Clock, Duration, Effect, Option, Result, Schema } from "effect" import { Base64 } from "effect/encoding" -import { relative, resolve, sep } from "node:path" +import { relative, sep } from "node:path" import { Script } from "node:vm" import type { BrowserConnection } from "./connection.js" import { BrowserFiles } from "./files.js" @@ -16,7 +16,7 @@ export const register = Effect.fn("BrowserTools.register")(function* ( connection: BrowserConnection.Connection, ) { // Load and text waits run on the desktop; the rest poll from here with actions every desktop already supports. - const wait = Effect.fn("BrowserTools.wait")(function* (tabID: Browser.TabID, plan: WaitPlan, tool: Tool.Context, approved: Effect.Success>) { + const wait = Effect.fn("BrowserTools.wait")(function* (tabID: Browser.TabID, plan: WaitPlan, tool: Tool.Context, approved: Extract>, { connectionID: string }>) { const started = yield* Clock.currentTimeMillis const current = connection .target(tool.sessionID, { type: "tabs.focus", tabID }, approved) @@ -143,23 +143,11 @@ export const register = Effect.fn("BrowserTools.register")(function* ( ) { // Before anything else, so a call the configuration denies reveals nothing but the denial. yield* connection.refuse(tool, input.type) - if (input.type === "wait") { - const plan = yield* parse(() => waitPlan(input)) - const approved = yield* connection.authorize(tool, input) - return yield* wait(input.tabID, plan, tool, approved) - } - const action = yield* parse(() => normalizeAction(input)) - if (action.type === "preview" && !(yield* connection.attached(tool.sessionID))) { - // Said without looking at the path, which no permission check has allowed yet. - const shown = BrowserFiles.address(action.path) - ? action.path - : resolve(ctx.location.directory, action.path.trim()) - return yield* new Tool.Error({ - message: `[browser.disconnected] ${shown} was not shown: no OpenCode desktop app is connected to this session, so nothing can open in its Review pane. Tell the user the file is at ${shown}; do not call browser.preview again until they open this session in the desktop app.`, - }) - } + const action = input.type === "wait" ? { ...input, plan: yield* parse(() => waitPlan(input)) } : yield* parse(() => normalizeAction(input)) const paths = "paths" in action ? action.paths.map((path) => BrowserFiles.uploadPath(ctx.location.directory, path)) : undefined const approved = yield* connection.authorize(tool, action, paths ?? (action.type === "preview" ? [action.path] : undefined)) + if (approved.connected === false) return { output: approved, content: [{ type: "text" as const, text: approved.message }] } + if (action.type === "wait") return yield* wait(action.tabID, action.plan, tool, approved) if (action.type === "preview" && ctx.location.workspaceID) return yield* new Tool.Error({ message: "Browser preview requires a server-local workspace." }) const checked = action.type === "preview" ? { ...action, path: yield* previewable(action.path, tool) } : action const target = yield* connection.target(tool.sessionID, checked, approved) @@ -194,7 +182,7 @@ export const register = Effect.fn("BrowserTools.register")(function* ( name: operation.name.slice(separator + 1), description: operation.description, input: operation.input, - output: operation.output, + output: Schema.Union([operation.output, Schema.Struct({ connected: Schema.Literal(false), message: Schema.String })]), options: { namespace: separator < 0 ? "browser" : `browser.${operation.name.slice(0, separator)}`, permission: "browser", @@ -279,7 +267,7 @@ function modelResult(output: Schema.Schema.Type, fi }) } -export function normalizeAction(action: Exclude): Browser.Action { +export function normalizeAction(action: Exclude): Exclude { if (action.type === "preview" && (!action.path.trim() || (BrowserFiles.address(action.path) && !/^file:/i.test(action.path.trim())))) throw new Tool.Error({ metadata: { code: "invalid_path" }, message: "browser.preview needs a workspace file path, not a web or internal address." }) if (action.type === "evaluate") return evaluateAction(action) @@ -306,14 +294,9 @@ export function normalizeAction(action: Exclude - new Tool.Error({ - message: "The URL is longer than 2048 characters once encoded. Open a shorter address.", - }), - ), - ) + const normalized = { ...action, url: url.href } + if (!Schema.is(Browser.Action)(normalized)) throw new Tool.Error({ message: "The URL is longer than 2048 characters once encoded. Open a shorter address." }) + return normalized } type WaitInput = Extract @@ -491,7 +474,7 @@ const refVisibility = const selectorVisibility = (selector: string) => `(() => { const found = [...document.querySelectorAll(${JSON.stringify(selector)})]; return { count: found.length, visible: found.filter((element) => element.checkVisibility()).length } })()` -function evaluateAction(input: Extract): Browser.Action { +function evaluateAction(input: Extract): Extract { const script = input.script ?? input.expression ?? input.code if (script === undefined) throw new Tool.Error({ From 085dee256b282f92dfcb4ff3eb5c8c527627d691 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:12:24 +1000 Subject: [PATCH 04/44] fix(core): list tools and evaluate calls from one ruleset Before, a step listed tools, skills and MCP servers from merge(agent, session) built in SessionContext.select, while calls were evaluated from the same merge built separately in Permission. A plugin that changed how calls were decided (the browser plugin's evaluate hook) could not change what was listed, so the two disagreed. Now Permission.rules(hooks, { session, agent }) is the only place that builds the ruleset. Permission's evaluation (assert, ask, assertNotDenied, allows), SessionContext.select (tool snapshot, Code Mode catalog and search, skill and MCP instructions) and scheduled code checks all use it. Permission.rules triggers a new experimental plugin hook, permission "experimental.rules". The hook gets the session ID, the agent ID, the session's own rules (read-only), and the merged rules (agent, then session). The hook can append rules, which are evaluated last. Core does not restrict what a hook writes. Hooks are trusted in the same way as permission.evaluate hooks, which can already set any effect. With no hook registered, the result is the same as the old merge. Agent resolution changes from agents.resolve to agents.select. This gives the same agent info, and the hook gets an agent ID even when the default agent is used. An agent that cannot be resolved still gets the deny-all rule. The tool-hiding predicate (the last rule matching the action is a deny on "*") moves to @opencode/schema/permission as deniesAll. Plugins can then apply the same predicate as Tool.snapshot. Tool.snapshot and Tool.check use it with the same matching as before (case-insensitive on Windows). --- packages/core/src/permission.ts | 23 ++++++++++++++++++++--- packages/core/src/schedule/check.ts | 4 +++- packages/core/src/session/context.ts | 7 +++++-- packages/core/src/tool.ts | 7 ++----- packages/plugin/src/effect/permission.ts | 15 +++++++++++++++ packages/plugin/src/promise/permission.ts | 15 +++++++++++++++ packages/schema/src/permission.ts | 10 ++++++++++ 7 files changed, 70 insertions(+), 11 deletions(-) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index d2682097cb6..2bb84cea901 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -16,7 +16,7 @@ import { PluginHooks } from "./plugin/hooks.js" const PermissionEffect = Permission.Effect export { PermissionEffect as Effect } -export { Rule, Ruleset } from "@opencode/schema/permission" +export { Rule, Ruleset, deniesAll } from "@opencode/schema/permission" const missingAgentPermissions: Permission.Ruleset = [{ action: "*", resource: "*", effect: "deny" }] export const ID = Permission.ID @@ -107,6 +107,24 @@ export function merge(...rulesets: Permission.Ruleset[]): Permission.Ruleset { return rulesets.flat() } +/** + * The rules for `agent` in `session`: the agent's, then the Session's, then any that `experimental.rules` hooks append. + * Requests are evaluated against them and steps list tools, skills and MCP servers by them, so what an agent is + * offered and what it may call come from one ruleset. + */ +export const rules = Effect.fn("Permission.rules")(function* ( + hooks: PluginHooks.Interface, + input: { readonly session: SessionSchema.Info; readonly agent: Agent.Selection }, +) { + const event = yield* hooks.trigger("permission", "experimental.rules", { + sessionID: input.session.id, + agent: input.agent.id, + session: input.session.permissions ?? [], + rules: [...(input.agent.info?.permissions ?? missingAgentPermissions), ...(input.session.permissions ?? [])], + }) + return event.rules +}) + export interface Interface { readonly close: Effect.Effect readonly ask: (input: AssertInput) => Effect.Effect @@ -169,8 +187,7 @@ const layer = Layer.effect( const configured = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, agentID?: Agent.ID) { const session = yield* sessions.get(sessionID) if (!session) return yield* new SessionErrors.NotFoundError({ sessionID }) - const agent = yield* agents.resolve(agentID ?? session.agent) - return merge(agent?.permissions ?? missingAgentPermissions, session.permissions ?? []) + return yield* rules(hooks, { session, agent: yield* agents.select(agentID ?? session.agent) }) }) function denied(input: Pick, rules: Permission.Ruleset) { diff --git a/packages/core/src/schedule/check.ts b/packages/core/src/schedule/check.ts index 816422d13de..754eadd4aa4 100644 --- a/packages/core/src/schedule/check.ts +++ b/packages/core/src/schedule/check.ts @@ -13,6 +13,7 @@ import { FileAccess } from "../file-access.js" import { Location } from "../location.js" import { Permission } from "../permission.js" import { Plugin } from "../plugin.js" +import { PluginHooks } from "../plugin/hooks.js" import type { SessionMessage } from "../session/message.js" import type { SessionSchema } from "../session/schema.js" import { ShellParse } from "../shell/parse.js" @@ -255,6 +256,7 @@ const runCode = Effect.fnUntraced(function* ( ) { const permission = yield* Permission.Service const agents = yield* Agent.Service + const hooks = yield* PluginHooks.Service const agent = yield* agents.select(session.agent) if (!agent.info) return { ok: false as const, error: `Agent not found: ${agent.id}` } @@ -298,7 +300,7 @@ const runCode = Effect.fnUntraced(function* ( code: condition.code, tools: paths, bindings, - permissions: Permission.merge(agent.info.permissions, session.permissions ?? []), + permissions: yield* Permission.rules(hooks, { session, agent }), limits: CODE_LIMITS, context: { sessionID: session.id, diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index eea20c76fb2..8f87859ac46 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -14,6 +14,7 @@ import { InstructionBuiltIns } from "../instructions/builtins.js" import { Location } from "../location.js" import { McpInstructions } from "../mcp/instructions.js" import { McpTool } from "../tool/mcp.js" +import { PluginHooks } from "../plugin/hooks.js" import { ReferenceInstructions } from "../reference/instructions.js" import { SkillInstructions } from "../skill/instructions.js" import { Tool } from "../tool.js" @@ -81,6 +82,7 @@ const layer = Layer.effect( const db = (yield* Database.Service).db const discovery = yield* InstructionDiscovery.Service const entries = yield* InstructionEntry.Service + const hooks = yield* PluginHooks.Service const location = yield* Location.Service const mcpInstructions = yield* McpInstructions.Service const mcpTools = yield* McpTool.Service @@ -142,8 +144,8 @@ const layer = Layer.effect( yield* mcpTools.flush const agent = yield* agents.select(session.agent) if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id }) - // Session permissions narrow discovery the same way they narrow the tool snapshot. - const permissions = Permission.merge(agent.info.permissions, session.permissions ?? []) + // The rules this agent's calls are evaluated against also decide which tools, skills and MCP servers it lists. + const permissions = yield* Permission.rules(hooks, { session, agent }) const loaded = yield* Effect.all( { tools: registry.snapshot(permissions), @@ -225,6 +227,7 @@ export const node = makeLocationNode({ Location.node, McpInstructions.node, McpTool.node, + PluginHooks.node, ReferenceInstructions.node, SessionRunnerModel.node, SessionModelRequest.node, diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 30d071beb3c..91ad1246de5 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -17,7 +17,6 @@ import { SessionMessage } from "./session/message.js" import { SessionSchema } from "./session/schema.js" import { State } from "./state.js" import { definition, effectiveName, execute, normalizedName, normalizeContent } from "./tool/runtime.js" -import { Wildcard } from "./util/wildcard.js" export class RegistrationError extends Schema.TaggedError()("Tool.RegistrationError", { name: Schema.String, @@ -382,10 +381,8 @@ function commit(editor: Data, id: string, input: Tool.Info & { readonly id: stri editor.definitions.set(id, registered.success) } -const whollyDisabled = (action: string, rules: Permission.Ruleset) => { - const rule = rules.findLast((rule) => Wildcard.match(action, rule.action)) - return rule?.resource === "*" && rule.effect === "deny" -} +const whollyDisabled = (action: string, rules: Permission.Ruleset) => + Permission.deniesAll(action, rules, process.platform === "win32") const formatSchemaIssue = SchemaIssue.makeFormatterDefault() diff --git a/packages/plugin/src/effect/permission.ts b/packages/plugin/src/effect/permission.ts index 4b7bb71948a..20b13788f62 100644 --- a/packages/plugin/src/effect/permission.ts +++ b/packages/plugin/src/effect/permission.ts @@ -29,8 +29,23 @@ export interface PermissionEvaluation { } } +/** + * The rules for one agent in one Session. They decide its permission requests and what its steps list: a tool whose + * permission they deny outright is not listed, and neither is a skill or MCP server they deny. Rules a hook appends + * are evaluated after the Session's. Experimental: may change without compatibility guarantees. + */ +export interface PermissionRules { + readonly sessionID: Session.ID + readonly agent: Agent.ID + /** The Session's own rules, which follow the agent's in `rules`. */ + readonly session: ReadonlyArray + /** The agent's rules, then the Session's. */ + rules: Array +} + export interface PermissionHooks { readonly evaluate: PermissionEvaluation + readonly "experimental.rules": PermissionRules } export type PermissionDomain = Pick, "list" | "get" | "reply"> & { diff --git a/packages/plugin/src/promise/permission.ts b/packages/plugin/src/promise/permission.ts index a5099b243b0..dcfd4f4d915 100644 --- a/packages/plugin/src/promise/permission.ts +++ b/packages/plugin/src/promise/permission.ts @@ -27,8 +27,23 @@ export interface PermissionEvaluation { } } +/** + * The rules for one agent in one Session. They decide its permission requests and what its steps list: a tool whose + * permission they deny outright is not listed, and neither is a skill or MCP server they deny. Rules a hook appends + * are evaluated after the Session's. Experimental: may change without compatibility guarantees. + */ +export interface PermissionRules { + readonly sessionID: Session.ID + readonly agent: Agent.ID + /** The Session's own rules, which follow the agent's in `rules`. */ + readonly session: ReadonlyArray + /** The agent's rules, then the Session's. */ + rules: Array +} + export interface PermissionHooks { readonly evaluate: PermissionEvaluation + readonly "experimental.rules": PermissionRules } export type PermissionDomain = Pick & { diff --git a/packages/schema/src/permission.ts b/packages/schema/src/permission.ts index 41887ed9ea6..832f2318bc0 100644 --- a/packages/schema/src/permission.ts +++ b/packages/schema/src/permission.ts @@ -6,6 +6,7 @@ import { ephemeral, inventory } from "./event.js" import { ascending } from "./identifier.js" import { SessionID } from "./session-id.js" import { statics } from "./schema.js" +import { Wildcard } from "./wildcard.js" export const ID = Schema.String.check(Schema.isStartingWith("per")).pipe( Schema.brand("Permission.ID"), @@ -65,3 +66,12 @@ export const Rule = Schema.Struct({ export const Ruleset = Schema.Array(Rule).annotate({ identifier: "Permission.Ruleset" }) export type Ruleset = typeof Ruleset.Type + +/** + * Whether `rules` deny `action` whatever the resource: the last rule for the action denies `*`. A tool with this + * permission is not listed. A narrower deny, or an allow after it, leaves the tool listed for its calls to decide. + */ +export function deniesAll(action: string, rules: ReadonlyArray, ignoreCase: boolean) { + const rule = rules.findLast((rule) => Wildcard.match(action, rule.action, ignoreCase)) + return rule?.resource === "*" && rule.effect === "deny" +} From d0fd8fceb8206bf3426f90d568a7f4f15408aad5 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:12:25 +1000 Subject: [PATCH 05/44] fix(browser): do not list the browser to an agent that denies it When a desktop attaches, the plugin appends a session grant (browser "*" allow, skill "browser" allow). The grant is evaluated after every agent rule. The PR's permission.evaluate hook already refused the calls of an agent whose configured rules deny the browser. But Tool.snapshot still saw the grant last and listed about 45 browser tools, plus the browser skill, to that agent. For agents without Code Mode, such as explore, these tools were listed as direct tools. Now an experimental.rules hook appends browser "*" deny and skill "browser" deny after the session rules, but only when deniesAll("browser") holds for the rules the evaluate hook already uses: the agent's configured rules (config and agent definition, before the plugin's default deny) followed by the session's rules without the grant. Calls do not change. If deniesAll holds, every browser operation is already refused: the last rule that matches the action has resource "*", so it is the rule that decides every operation. Core now refuses the call itself, and refuse() still runs first in the tool and keeps the "[browser.denied]" message. The only new refusal is reading the browser skill (skill:// read) for such an agent. Before, the grant allowed it. Listing becomes: - A configured or agent-level browser deny, or "*" deny: not listed. This covers the tools, the Code Mode catalog and search, the skill, and direct tools. - ask, a deny of some operations or a pattern, or a deny followed by an allow of one operation: listed, and decided per call as before. - No desktop attached: not listed (the default deny), as before. - Agent rules override global rules because they come later. Subagents lose the inherited grant at their first prompt. Startup sweeps stale grants. These rules are unchanged. Each step calls SessionContext.select, so an agent switch, a session rule change, a config reload, or an attach or detach updates the listing on the next step. The Code Mode catalog cache is keyed by the set of visible tool names. Tests (browser-permission.test.ts) run the real plugin, permission service and SessionContext: - A 13-row truth table checks listing (catalog, skill, direct tools) against the outcomes of tabs.list and tabs.open. - Code Mode catalog, search and tools for a denied agent. - Agent switch, session rule, config reload, and detach and re-attach between steps. - Subagents, including explore attached directly. With the hook disabled, 7 of these tests fail. --- packages/core/test/browser-permission.test.ts | 219 +++++++++++++++++- packages/plugin-browser/README.md | 4 +- packages/plugin-browser/src/connection.ts | 10 + packages/plugin-browser/src/machine.ts | 7 +- 4 files changed, 237 insertions(+), 3 deletions(-) diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index f872042b67b..cae71e6b1bb 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -1,7 +1,7 @@ import { expect } from "bun:test" import { hostname } from "os" import path from "path" -import { Context, Deferred, Effect, Exit, Fiber, Schedule, Stream } from "effect" +import { Context, Deferred, Effect, Exit, Fiber, Schedule, Schema, Stream } from "effect" import { Browser } from "@opencode/plugin-browser/rpc" import { SessionMessage } from "@opencode/schema/session-message" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" @@ -21,13 +21,20 @@ import { PluginHost } from "@opencode/core/plugin/host" import { Rpc } from "@opencode/core/rpc" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" +import { SessionContext } from "@opencode/core/session/context" import { Tool } from "@opencode/core/tool" +import { Config } from "@opencode/core/config" +import { ConfigIntegration } from "@opencode/core/config/integration" +import { Info } from "@opencode/schema/config" +import { Integration } from "@opencode/schema/integration" +import { isRecord } from "@opencode/util/record" import { BrowserConnection } from "../../plugin-browser/src/connection" import { BrowserFiles } from "../../plugin-browser/src/files" import { tempGlobalLayer } from "./fixture/global" import { offlineModels } from "./fixture/models" import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" +import { codeModeListings } from "./lib/tool" const it = testEffect( AppNodeBuilder.build( @@ -127,9 +134,36 @@ const setup = (config: object) => run, permissions: (sessionID = session.id) => Effect.map(sessions.get(sessionID), (info) => info.permissions ?? []), call: (agent = "build", sessionID = session.id) => run("tabs.list", {}, agent, sessionID), + // What the session's next step offers its agent: the selection every step builds its tools and instructions from. + listing: (sessionID = session.id) => listing(Context.get(context, SessionContext.Service), sessionID), } }) +const listing = Effect.fnUntraced(function* (contexts: SessionContext.Interface, sessionID: Session.ID) { + const selection = yield* contexts.select(sessionID) + const browser = (name: string) => name === "browser" || name.startsWith("browser.") || name.startsWith("browser_") + const skills = selection.instructions.find((source) => source.key === "core/skill-guidance") + const guidance = skills ? yield* skills.read : undefined + const catalog = selection.tools.codeModeCatalog + return { + selection, + catalog: (catalog ? codeModeListings(catalog).map((item) => item.path) : []).filter(browser), + direct: selection.tools.definitions.map((tool) => tool.name).filter(browser), + skill: Array.isArray(guidance) && guidance.some((skill) => isRecord(skill) && skill.id === "browser"), + } +}) + +// Runs `code` through the selection's Code Mode tool, as the model's `execute` call would. +const codeMode = (selection: SessionContext.Selection, code: string) => + selection.tools + .execute({ + sessionID: selection.session.id, + agent: selection.agent.id, + messageID: SessionMessage.ID.create(), + call: { type: "tool-call", id: `call_${crypto.randomUUID()}`, name: "execute", input: { code } }, + }) + .pipe(Effect.map((result) => result.output)) + it.live("without a deny, an attached session's browser calls run with no prompt", () => Effect.gen(function* () { const browser = yield* setup({}) @@ -579,3 +613,186 @@ it.live("a configured deny that matches last refuses the call despite a saved ap expect(browser.commands.count).toBe(1) }), ) + +// Listing and calling, decided by the same rules. `listed` is whether the agent's next step offers the browser tools and +// skill; each operation either reaches the desktop, prompts, or is refused as denied or disconnected. +type Outcome = "allow" | "ask" | "deny" | "disconnected" +const truth: ReadonlyArray<{ + readonly name: string + readonly global?: ReadonlyArray> + readonly agent?: ReadonlyArray> + readonly attached: boolean + readonly listed: boolean + readonly list: Outcome + readonly open: Outcome +}> = [ + { name: "no rules", attached: true, listed: true, list: "allow", open: "allow" }, + { name: "no rules, no desktop", attached: false, listed: false, list: "disconnected", open: "disconnected" }, + { name: "global deny", global: [rule("*", "deny")], attached: true, listed: false, list: "deny", open: "deny" }, + { name: "global deny, no desktop", global: [rule("*", "deny")], attached: false, listed: false, list: "deny", open: "deny" }, + { name: "agent deny", agent: [rule("*", "deny")], attached: true, listed: false, list: "deny", open: "deny" }, + { name: "global allow, agent deny", global: [rule("*", "allow")], agent: [rule("*", "deny")], attached: true, listed: false, list: "deny", open: "deny" }, + { name: "global deny, agent allow", global: [rule("*", "deny")], agent: [rule("*", "allow")], attached: true, listed: true, list: "allow", open: "allow" }, + { name: "agent denies every tool", agent: [rule("*", "deny", "*"), rule("*", "allow", "read")], attached: true, listed: false, list: "deny", open: "deny" }, + { name: "global ask", global: [rule("*", "ask")], attached: true, listed: true, list: "ask", open: "ask" }, + { name: "global deny, agent ask", global: [rule("*", "deny")], agent: [rule("*", "ask")], attached: true, listed: true, list: "ask", open: "ask" }, + { name: "one operation denied", global: [rule("tabs.open", "deny")], attached: true, listed: true, list: "allow", open: "deny" }, + { name: "operation pattern denied", global: [rule("tabs.*", "deny")], attached: true, listed: true, list: "deny", open: "deny" }, + { name: "whole browser denied, one operation allowed after", global: [rule("*", "deny"), rule("tabs.list", "allow")], attached: true, listed: true, list: "allow", open: "deny" }, +] + +// What `operation` comes to for `agent` in `sessionID`. A call that prompts is interrupted, which withdraws the prompt. +const outcome = Effect.fnUntraced(function* ( + browser: Effect.Success>, + operation: string, + agent: string, + sessionID: Session.ID, +) { + const permissions = Context.get(browser.context, Permission.Service) + const before = browser.commands.count + const reached = () => browser.commands.count > before + // Any other failure is returned as its message, so the comparison shows it. + const call = browser.run(operation, {}, agent, sessionID).pipe( + Effect.as("allow"), + Effect.catch((error) => + Effect.succeed( + error.message.startsWith("[browser.denied]") + ? "deny" + : error.message.startsWith("[browser.disconnected]") + ? "disconnected" + : reached() + ? "allow" + : error.message, + ), + ), + ) + const prompted = permissions.forSession(sessionID).pipe( + Effect.flatMap((requests) => (requests[0] ? Effect.succeed(requests[0]) : Effect.fail("not asked yet"))), + Effect.retry(Schedule.spaced("10 millis")), + Effect.as("ask"), + ) + return yield* Effect.raceFirst(call, prompted).pipe(Effect.timeout("5 seconds")) +}) + +for (const row of truth) + it.live(`listing agrees with calling: ${row.name}`, () => + Effect.gen(function* () { + const browser = yield* setup({ + ...(row.global && { permissions: row.global }), + ...(row.agent && { agents: { build: { permissions: row.agent } } }), + }) + const sessions = yield* Session.Service + const sessionID = row.attached ? browser.session.id : (yield* sessions.create({ location: browser.ref })).id + const listed = yield* browser.listing(sessionID) + expect(listed.catalog.length > 0).toBe(row.listed) + expect(listed.skill).toBe(row.listed) + expect(listed.direct).toEqual([]) + expect(yield* outcome(browser, "tabs.list", "build", sessionID)).toBe(row.list) + expect(yield* outcome(browser, "tabs.open", "build", sessionID)).toBe(row.open) + }), + ) + +it.live("an agent denied the browser finds no browser tools through Code Mode's catalog, search or tools", () => + Effect.gen(function* () { + const browser = yield* setup({ agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } } }) + const allowed = yield* browser.listing() + expect(allowed.catalog).toContain("browser.tabs.list") + expect(yield* codeMode(allowed.selection, 'return search({ namespace: "browser" }).items.length > 0')).toMatchObject({ output: "true" }) + expect(yield* codeMode(allowed.selection, "return (await tools.browser.tabs.list({})).tabs.length")).toMatchObject({ output: "0" }) + + const sessions = yield* Session.Service + yield* sessions.switchAgent({ sessionID: browser.session.id, agent: Agent.ID.make("reviewer") }) + const denied = yield* browser.listing() + expect(denied.catalog).toEqual([]) + expect(denied.direct).toEqual([]) + expect(denied.skill).toBe(false) + expect(yield* codeMode(denied.selection, 'return search({ namespace: "browser" }).items.length')).toMatchObject({ output: "0" }) + expect(yield* codeMode(denied.selection, 'return search({ query: "browser tabs screenshot" }).items.filter((item) => item.path.startsWith("tools.browser")).length')).toMatchObject({ output: "0" }) + expect( + yield* codeMode( + denied.selection, + 'try { await tools.browser.tabs.list({}); return "called" } catch (error) { return String(error?.message ?? error) }', + ), + ).toMatchObject({ output: "Unknown tool 'browser.tabs.list'.", toolCalls: [] }) + expect(browser.commands.count).toBe(1) + }), +) + +it.live("the next step's listing follows an agent switch, a session rule, a config reload and the attachment", () => + Effect.gen(function* () { + const browser = yield* setup({ agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } } }) + const sessions = yield* Session.Service + const listed = Effect.map(browser.listing(), (listing) => listing.catalog.length > 0) + expect(yield* listed).toBe(true) + + yield* sessions.switchAgent({ sessionID: browser.session.id, agent: Agent.ID.make("reviewer") }) + expect(yield* listed).toBe(false) + yield* sessions.switchAgent({ sessionID: browser.session.id, agent: Agent.ID.make("build") }) + expect(yield* listed).toBe(true) + + yield* sessions.setPermissions({ sessionID: browser.session.id, permissions: [...grant, rule("*", "deny")] }) + expect(yield* listed).toBe(false) + expect((yield* browser.call().pipe(Effect.flip)).message).toStartWith("[browser.denied]") + yield* sessions.setPermissions({ sessionID: browser.session.id, permissions: [...grant] }) + expect(yield* listed).toBe(true) + + // A config source that changes while the server runs reloads the agents, and with them the rules the grant yields to. + const config = Context.get(browser.context, Config.Service) + const integrationID = Integration.ID.make("browser-permission-test") + yield* config.integration!( + integrationID, + new ConfigIntegration.Document({ + type: "document", + integrationID, + connection: { type: "env", name: "BROWSER_PERMISSION_TEST_KEY" }, + info: Schema.decodeUnknownSync(Info)({ permissions: [rule("*", "deny")] }), + }), + ) + yield* Plugin.awaitActivation.pipe(Effect.provideContext(browser.context)) + expect(yield* listed).toBe(false) + expect((yield* browser.call().pipe(Effect.flip)).message).toStartWith("[browser.denied]") + yield* config.integration!(integrationID, undefined) + yield* Plugin.awaitActivation.pipe(Effect.provideContext(browser.context)) + expect(yield* listed).toBe(true) + + yield* browser.detach + yield* browser.permissions().pipe( + Effect.flatMap((rules) => (rules.length ? Effect.fail("grant not revoked yet") : Effect.void)), + Effect.retry(Schedule.spaced("10 millis")), + Effect.timeout("5 seconds"), + ) + expect(yield* listed).toBe(false) + yield* browser.attach(browser.session.id) + expect(yield* listed).toBe(true) + }), +) + +it.live("a subagent lists no browser tools, whether it lost the inherited grant or its agent denies an attached browser", () => + Effect.gen(function* () { + const browser = yield* setup({ + agents: { reviewer: { mode: "subagent", permissions: [rule("*", "deny")] } }, + }) + const sessions = yield* Session.Service + const general = yield* sessions.create({ parentID: browser.session.id, agent: Agent.ID.make("general") }) + yield* sessions.prompt({ sessionID: general.id, text: "Take a screenshot", resume: false }) + expect((yield* browser.listing(general.id)).catalog).toEqual([]) + expect((yield* browser.listing()).catalog).toContain("browser.tabs.list") + + const reviewer = yield* sessions.create({ parentID: browser.session.id, agent: Agent.ID.make("reviewer") }) + yield* sessions.prompt({ sessionID: reviewer.id, text: "Review the page", resume: false }) + yield* browser.attach(reviewer.id) + expect(yield* browser.permissions(reviewer.id)).toEqual([...grant]) + const denied = yield* browser.listing(reviewer.id) + expect(denied.catalog).toEqual([]) + expect(denied.skill).toBe(false) + + // Explore denies every tool, Code Mode included, so a browser it were offered would be listed as direct tools. + const explore = yield* sessions.create({ parentID: browser.session.id, agent: Agent.ID.make("explore") }) + yield* sessions.prompt({ sessionID: explore.id, text: "Find the page", resume: false }) + yield* browser.attach(explore.id) + const listing = yield* browser.listing(explore.id) + expect(listing.direct).toEqual([]) + expect(listing.skill).toBe(false) + expect(browser.commands.count).toBe(0) + }), +) \ No newline at end of file diff --git a/packages/plugin-browser/README.md b/packages/plugin-browser/README.md index 37f673ae9ae..817e1b9baa8 100644 --- a/packages/plugin-browser/README.md +++ b/packages/plugin-browser/README.md @@ -34,7 +34,9 @@ The built-in `browser` skill (`skill.ts`) teaches the workflow: explicit tab IDs, snapshots and refs, showing results to the user, recipes for debugging, performance and memory, and recovery after failures. It lists every operation from `Browser.Operations`. Like the tools, it is hidden until a desktop browser -attaches to the session. +attaches to the session, and stays hidden from an agent whose configured rules +deny the whole browser (`browser: "deny"`). An `ask`, or a deny for some +operations only, keeps them listed; each call then prompts or is refused. The plugin entrypoint only composes its two owners: `connection.ts` manages desktop attachments and pending RPC requests; `tools.ts` runs the tool workflow. diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index 347fcd738cc..c100f09eb70 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -126,6 +126,16 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( ), ), ) + // The grant comes last, so core would list the browser tools and skill to an agent whose own rules deny the whole + // browser, and only the hook above would refuse their calls. Restating the deny after the grant hides them from that + // agent's steps and Code Mode catalog, and core refuses its calls before any hook runs. An ask or a narrower deny + // keeps them listed, for the hook above to decide each call. + yield* ctx.permission.hook("experimental.rules", (event) => + Effect.sync(() => { + if (!BrowserMachine.deniesBrowser(rulesFor({ permissions: event.session }, event.agent))) return + event.rules.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" as const }))) + }), + ) // Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes. const work = yield* Scope.make() yield* Effect.addFinalizer((exit) => Scope.close(work, exit)) diff --git a/packages/plugin-browser/src/machine.ts b/packages/plugin-browser/src/machine.ts index 8f5089f28e9..1be273c4c6d 100644 --- a/packages/plugin-browser/src/machine.ts +++ b/packages/plugin-browser/src/machine.ts @@ -1,6 +1,6 @@ export * as BrowserMachine from "./machine.js" -import type { Permission } from "@opencode/schema/permission" +import { Permission } from "@opencode/schema/permission" import type { Session } from "@opencode/schema/session" import { Tool } from "@opencode/schema/tool" import { Wildcard } from "@opencode/schema/wildcard" @@ -587,6 +587,11 @@ export function selectBrowserRule(rules: readonly Permission.Rule[], operation: ) } +/** Whether `rules` deny the whole browser, which is when core stops listing the browser tools. */ +export function deniesBrowser(rules: readonly Permission.Rule[]) { + return Permission.deniesAll("browser", rules, process.platform === "win32") +} + export function isConnectionDisposed(state: ConnectionState) { return state.status === "disposed" } From f5decd10c3041fb97d44e64a98b33f78cb9d00fa Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:14:08 +1000 Subject: [PATCH 06/44] feat(browser): capture full pages in background tabs --- .../gui-plugins/src/browser/capture.test.ts | 8 +++++++- packages/gui-plugins/src/browser/capture.ts | 13 +++++++++++++ packages/gui-plugins/src/browser/chromium.ts | 19 +++---------------- packages/plugin-browser/src/rpc.ts | 2 +- packages/plugin-browser/src/skill.ts | 2 +- 5 files changed, 25 insertions(+), 19 deletions(-) diff --git a/packages/gui-plugins/src/browser/capture.test.ts b/packages/gui-plugins/src/browser/capture.test.ts index 6bfc72282ce..391a73bfc70 100644 --- a/packages/gui-plugins/src/browser/capture.test.ts +++ b/packages/gui-plugins/src/browser/capture.test.ts @@ -1,8 +1,14 @@ import { expect, test } from "bun:test" -import { captureCoordinator, cropPixels, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" +import { captureCoordinator, captureScale, cropPixels, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" const shown = { minimized: false, visible: true, appHidden: false } +test("full capture limits include zoom and DPI, after scaling to maxWidth", () => { + expect(captureScale({ width: 1000, height: 4000 }, 2, 1000)).toBe(0.5) + expect(() => captureScale({ width: 1000, height: 4001 }, 2, 2000)).toThrow("16 megapixels") + expect(() => captureScale({ width: 100, height: 16385 }, 1, 1000)).toThrow("16384 pixels") +}) + test("crop uses the returned pixels, including fractional edge overlaps at non-default zoom", () => { // A 200 DIP view rendered at 150% DPI, at page zoom 2: one CSS pixel covers three bitmap pixels. const crop = (x: number, y: number, width: number, height: number) => cropPixels({ x, y, width, height }, { width: 300, height: 240 }, 200, 2) diff --git a/packages/gui-plugins/src/browser/capture.ts b/packages/gui-plugins/src/browser/capture.ts index ee654fdb887..b8fb50c32f1 100644 --- a/packages/gui-plugins/src/browser/capture.ts +++ b/packages/gui-plugins/src/browser/capture.ts @@ -8,6 +8,19 @@ type Size = { width: number; height: number } type Rect = Size & { x: number; y: number } +/** Bound both the decoded bitmap (64 MB of RGBA) and the compositor's longest surface edge. */ +export function captureScale(bounds: Size, pixelRatio: number, maxWidth: number) { + if (bounds.width <= 0 || bounds.height <= 0) throw new Error("Element or page has no visible screenshot area.") + const scale = Math.min(1, maxWidth / (bounds.width * pixelRatio)) + const width = Math.ceil(bounds.width * pixelRatio * scale) + const height = Math.ceil(bounds.height * pixelRatio * scale) + + if (width * height > 16_000_000 || Math.max(width, height) > 16_384) + throw new Error("Screenshot exceeds 16 megapixels or 16384 pixels on one edge. Reduce maxWidth or capture the viewport or an element.") + + return scale +} + /** Intersect in actual bitmap pixels. Round outward so a fractional overlap includes the pixel it touches. */ export function cropPixels(clip: Rect, image: Size, viewWidth: number, zoom: number) { if (viewWidth <= 0 || clip.width <= 0 || clip.height <= 0) return diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 456b32c7b6e..be46dafe4f3 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -7,7 +7,7 @@ import electron, { type BrowserWindow, type WebContents } from "electron" import type { Protocol } from "devtools-protocol" import { Schema } from "effect" import type { Embeds } from "@opencode/plugin/gui/main" -import { captureCoordinator, cropPixels, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" +import { captureCoordinator, captureScale, cropPixels, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" import { createCdp, abortError, waitFor } from "./cdp" import { navigationDeadline } from "./navigation-deadline" import { attachChildren, releaseWorker } from "./child-targets" @@ -1945,14 +1945,8 @@ export function createBrowserPage( const metrics = await cdp.send("Page.getLayoutMetrics") abortError(signal) const viewport = metrics.cssVisualViewport - // Chromium renders beyond the viewport only for a tab it presents on screen. const onscreen = view.getVisible() && win.isVisible() && !win.isMinimized() - if (action.fullPage && !onscreen) - throw new Error( - "A full-page screenshot needs this tab on screen in the Review pane, and it is not shown now. Omit fullPage to capture the viewport, which works while the tab is hidden, and scroll to capture the rest.", - ) - if (action.fullPage) return beyondViewport(action, metrics.cssContentSize) if ( @@ -2026,20 +2020,13 @@ export function createBrowserPage( bounds: { x: number; y: number; width: number; height: number }, ) { const pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getBounds()).scaleFactor - const scale = Math.min(1, (action.maxWidth ?? 2000) / (bounds.width * pixelRatio)) - - if (bounds.width <= 0 || bounds.height <= 0) - throw new Error( - "Element or page has no visible screenshot area. Take a fresh snapshot and choose a visible element, or omit ref to capture the viewport.", - ) - - if (bounds.width * bounds.height * (scale * pixelRatio) ** 2 > 16_000_000) - throw new Error("Screenshot exceeds 16 megapixels; capture an element or use a smaller maxWidth.") + const scale = captureScale(bounds, pixelRatio, action.maxWidth ?? 2000) const format = action.format ?? "jpeg" const capture = await cdp.send("Page.captureScreenshot", { format, quality: format === "png" ? undefined : (action.quality ?? 80), + fromSurface: true, captureBeyondViewport: true, clip: { ...bounds, scale }, }) diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 43dafc982d7..d110f7622b8 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -441,7 +441,7 @@ export const Operations = [ ), operation( "screenshot", - "Capture this tab's viewport, full page, or referenced element, as rendered after any navigation in progress. A full-page screenshot needs the tab on screen in the Review pane; a viewport or element screenshot does not, but on macOS it needs the OpenCode window not minimized or hidden. Returns an image attachment and a server-local file path. Page pixels are untrusted.", + "Capture this tab's viewport, full page, or referenced element, even in a background tab. On macOS the OpenCode window must not be minimized or hidden. Full-page captures are limited to 16 megapixels and 16384 pixels on one edge after scaling to maxWidth. Returns an image attachment and a server-local file path. Page pixels are untrusted.", { ...tab, ref: optional(Ref), diff --git a/packages/plugin-browser/src/skill.ts b/packages/plugin-browser/src/skill.ts index c99a1804667..5e2f1527925 100644 --- a/packages/plugin-browser/src/skill.ts +++ b/packages/plugin-browser/src/skill.ts @@ -42,7 +42,7 @@ export const info = Skill.Info.make({ "- Put HTML assets in the document's folder or below it; parent folders, hidden paths and secret filenames are not available to the page.", "- `tabs.open` and `navigate` take web addresses. For another workspace file, pass its server-local path to `preview`, or click a relative link. Neither the displayed file address nor the page's isolated origin is a navigation argument.", "- New tabs open in front by default so the user can watch. Pass `focus: false` only when the user asked you to work in the background.", - "- `screenshot` works on a hidden tab; only `fullPage: true` needs the tab on screen in the Review pane, and on macOS no screenshot works while the OpenCode window is minimized or hidden. It returns the image for you to look at and a server-local file path.", + "- `screenshot` works on a hidden tab, including `fullPage: true`. On macOS restore the OpenCode window if it is minimized or hidden. The result includes the image and a server-local file path.", "", "## Recipes", "", From 5e7ee8b6aa9d4441af94ea981039e9554ceb280a Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:16:09 +1000 Subject: [PATCH 07/44] fix(browser): follow committed replacements after a navigation abort --- packages/gui-plugins/src/browser/chromium.ts | 35 +++++++++++++------ packages/gui-plugins/src/browser/errors.ts | 2 +- .../src/browser/navigation-turn.test.ts | 20 ++++++++++- .../src/browser/navigation-turn.ts | 17 +++++++++ 4 files changed, 62 insertions(+), 12 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index be46dafe4f3..a7aa02e9ed9 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,5 +1,5 @@ import { homedir } from "node:os" -import { navigationTurn } from "./navigation-turn" +import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" @@ -997,18 +997,33 @@ export function createBrowserPage( } contents.once("did-navigate", commit) + const next = replacementNavigation() + contents.on("did-start-navigation", next.start) + contents.on("did-navigate", next.commit) + contents.on("did-stop-loading", next.stop) + contents.once("destroyed", next.stop) - return navigationDeadline(contents.loadURL(destination)) - .catch((error: Error) => { - if (committedLoad(error, committed)) return + return navigationDeadline(contents.loadURL(destination).catch(async (error: Error) => { + if (committedLoad(error, committed)) return - if (options.previewFailure?.(destination)) throw new FileVerificationError() + if (destinationOrigin(destination) && await next.after(error)) return - if (destination.startsWith(`${previewScheme}://`)) - throw new CodedError(Browser.FailureCode.previewUnavailable, `The preview could not be loaded: ${url}`) - throw error - }) - .finally(() => contents.off("did-navigate", commit)) + if (options.previewFailure?.(destination)) throw new FileVerificationError() + + if (destination.startsWith(`${previewScheme}://`)) + throw new CodedError(Browser.FailureCode.previewUnavailable, `The preview could not be loaded: ${url}`) + + if (!committed && "errno" in error && (error.errno === -2 || error.errno === -3)) + throw new CodedError("navigation_failed", "No page committed. The navigation was cancelled, failed, or became a download. Check the tab and its downloads before navigating again.") + throw error + })).finally(() => { + next.stop() + contents.off("destroyed", next.stop) + contents.off("did-stop-loading", next.stop) + contents.off("did-navigate", next.commit) + contents.off("did-start-navigation", next.start) + contents.off("did-navigate", commit) + }) } const reload = async (signal = options.signal, ignoreCache = false) => { diff --git a/packages/gui-plugins/src/browser/errors.ts b/packages/gui-plugins/src/browser/errors.ts index 2751fca7e2d..aa9a6ae98e6 100644 --- a/packages/gui-plugins/src/browser/errors.ts +++ b/packages/gui-plugins/src/browser/errors.ts @@ -5,7 +5,7 @@ import { FileVerificationError } from "@opencode/util/file-verification" /** A failure the server acts on by its code, such as a wait whose condition never held. */ export class CodedError extends Error { constructor( - readonly code: (typeof Browser.FailureCode)[keyof typeof Browser.FailureCode], + readonly code: (typeof Browser.FailureCode)[keyof typeof Browser.FailureCode] | "navigation_failed", message: string, options?: ErrorOptions, ) { diff --git a/packages/gui-plugins/src/browser/navigation-turn.test.ts b/packages/gui-plugins/src/browser/navigation-turn.test.ts index 7abe633f1a0..15fb05aa536 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.test.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.test.ts @@ -1,7 +1,25 @@ import { expect, test } from "bun:test" -import { navigationTurn } from "./navigation-turn" +import { navigationTurn, replacementNavigation } from "./navigation-turn" import { createDocumentState, transitionDocument } from "./page-machine" +test.each([true, false])("an abort waits for the replacement document, not the original commit: committed=%s", async committed => { + const next = replacementNavigation() + const start = { isMainFrame: true, isSameDocument: false } + const aborted = Object.assign(new Error("aborted"), { errno: -3 }) + next.start(start) + next.commit() + next.start({ ...start, isSameDocument: true }) + next.start({ ...start, isMainFrame: false }) + expect(next.after(aborted)).toBeUndefined() + next.start(start) + const result = next.after(aborted) + + if (committed) next.commit() + next.stop() + expect(await result).toBe(committed) + expect(next.after(new Error("network error"))).toBeUndefined() +}) + test.each(["stop", "oc-preview://private/report", "https://next.test"])('a later %s wins over a deferred web navigation', async next => { const gate = Promise.withResolvers() const issued: string[] = [] diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index 26e78a923ca..f510ec99f29 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -1,5 +1,22 @@ import type { Browser } from "@opencode/plugin-browser/rpc" +/** Electron rejects loadURL as soon as a second main-frame navigation starts, before its document commits. */ +export function replacementNavigation() { + let starts = 0 + let replacement: ReturnType> | undefined + + return { + start(event: { isMainFrame: boolean; isSameDocument: boolean }) { + if (event.isMainFrame && !event.isSameDocument && ++starts === 2) replacement = Promise.withResolvers() + }, + commit: () => replacement?.resolve(true), + stop: () => replacement?.resolve(false), + after(error: Error) { + return "errno" in error && error.errno === -3 ? replacement?.promise : undefined + }, + } +} + /** A page owns at most one not-yet-issued navigation. Once issued, Chromium owns cancellation and history. */ export function navigationTurn( wait: ((url: string, signal: AbortSignal) => Promise | undefined) | undefined, From b72e2b18d439a0e3fc7cee37493884c173043d53 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:20:56 +1000 Subject: [PATCH 08/44] fix(browser): preserve tab addresses when stopping a deferred load --- packages/gui-plugins/src/browser/chromium.ts | 34 ++++++++++++++----- .../src/browser/navigation-turn.ts | 17 +++++++++- .../src/browser/page-machine.test.ts | 22 ++++++++++-- .../gui-plugins/src/browser/page-machine.ts | 12 +++++-- .../src/browser/pane-machine.test.ts | 13 +++++++ 5 files changed, 83 insertions(+), 15 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index c6adf802fc4..5615065b1f7 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -490,12 +490,12 @@ export function createBrowserPage( if (reason === "remove") extensionContexts.delete(frameId) }) - const state = () => + const state = (display = false) => documentTab(documentState, { id: options.id, canGoBack: contents.navigationHistory.canGoBack(), canGoForward: contents.navigationHistory.canGoForward(), - }) + }, display) // Every state report goes through here, so a page that was disposed publishes nothing. // While a user's close asks the page's beforeunload on a blank load, the tab reports nothing: the blank page is not @@ -506,7 +506,10 @@ export function createBrowserPage( if (!closed() && !quiet) options.publish(error) } + let startingBlank = false + const dispatch = (event: DocumentEvent) => { + if (startingBlank && event.type !== "disposed") return const next = transitionDocument(documentState, event) documentState = next.state next.effects.forEach((effect) => { @@ -629,6 +632,9 @@ export function createBrowserPage( const pageTitle = (address = state().url) => { const title = contents.getTitle() + if (documentState.status !== "closed" && documentState.retry && (!title || title === "about:blank")) + return documentState.title || documentState.retry + return /^oc-preview:/i.test(title) ? address : title } @@ -962,12 +968,14 @@ export function createBrowserPage( const navigation = navigationTurn(options.waitForFilters, url => { dispatch({ type: "navigation.started", url, isMainFrame: true, isSameDocument: false }) dispatch({ type: "loading.started" }) - }, () => { if (!closed()) dispatch({ type: "loading.stopped", title: pageTitle() }) }) + }, () => { if (!closed()) dispatch({ type: "loading.stopped", title: pageTitle() }) }, address => { + dispatch({ type: "navigation.held-stopped", address }) + }) - const begin = (signal = options.signal) => navigation.begin(AbortSignal.any([pageLifetime.signal, signal, options.signal])) + const begin = (signal = options.signal, keepAddress = false) => navigation.begin(AbortSignal.any([pageLifetime.signal, signal, options.signal]), keepAddress) - const load = async (url: string, retry = false, commandSignal = options.signal) => { - const visit = begin(commandSignal) + const load = async (url: string, retry = false, commandSignal = options.signal, keepAddress = true) => { + const visit = begin(commandSignal, keepAddress) const destination = url.startsWith("artifact:") ? options.artifacts?.load(url) : localFileURL(url) || url.startsWith("workspace:") ? await options.workspace?.load(url, (guarded) => notices.show({reason: guarded ? "browser.preview.agentRestricted" : "browser.preview.restricted"}), retry ? contents.getURL() : undefined) : url if (!destination) return Promise.reject(new Error("Workspace preview is unavailable.")) @@ -1013,6 +1021,8 @@ export function createBrowserPage( if (navigation.interrupt("reload", documentState.status === "restoring" ? documentState.url : undefined)) return + if (documentState.status !== "closed" && documentState.retry) return load(documentState.retry, true, signal) + if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url, true, signal) const actual = contents.getURL() @@ -1029,7 +1039,13 @@ export function createBrowserPage( ...(initial === undefined ? [] : [ - load(initial).catch((error: Error) => { + load(initial).then(async () => { + // Stop before the first load leaves no renderer to finish CDP setup. Start only the inert document; + // its native events are not a navigation of the saved tab. + if (documentState.status !== "restoring" || !documentState.retry || contents.getURL() || closed()) return + startingBlank = true + await contents.loadURL("about:blank").finally(() => { startingBlank = false }) + }).catch((error: Error) => { if (!options.restore) throw error // A dev server may have stopped while this page was unloaded. Keep its tab available to retry. publish(error.message) @@ -1050,7 +1066,7 @@ export function createBrowserPage( view, contents, nativeID: contents.id, - state, + state: () => state(true), childActivity: () => childActivity(activity), previewUsed: () => !!options.popupOptions || !!options.workspace?.used(), previewIdentity: () => options.workspace?.identity(), @@ -1299,7 +1315,7 @@ export function createBrowserPage( signal.addEventListener("abort", cancel, { once: true }) try { - await load(url, false, signal) + await load(url, false, signal, origin === "user") } finally { signal.removeEventListener("abort", cancel) } diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index 26e78a923ca..d06492a6e27 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -5,13 +5,16 @@ export function navigationTurn( wait: ((url: string, signal: AbortSignal) => Promise | undefined) | undefined, started: (url: string) => void, stopped: () => void, + heldStop?: (address?: string) => void, ) { let pending: AbortController | undefined + let held: string | undefined let spinning = false const cancel = () => { pending?.abort() pending = undefined + held = undefined if (spinning) stopped() spinning = false @@ -28,9 +31,19 @@ export function navigationTurn( // This load hasn't been issued yet. Let it satisfy Reload: cancelling would both lose its URL and leave // initial CDP setup waiting for a renderer that the replacement command cannot start until setup finishes. if (method === "reload" && pending && restoring && /^https?:\/\//i.test(restoring)) return restoring + + if (method === "stop" && held !== undefined && heldStop) { + const address = held + spinning = false + cancel() + heldStop(address || undefined) + + return + } + cancel() }, - begin(signal: AbortSignal) { + begin(signal: AbortSignal, keepAddress = true) { cancel() const mine = new AbortController() pending = mine @@ -42,6 +55,7 @@ export function navigationTurn( const waiting = wait?.(url, lifetime) if (waiting) { + held = keepAddress ? url : "" // Let the pane take ownership before publishing the initial restore's spinner. await Promise.resolve() @@ -60,6 +74,7 @@ export function navigationTurn( if (mine.signal.aborted) return lifetime.throwIfAborted() pending = undefined + held = undefined spinning = false await issue() diff --git a/packages/gui-plugins/src/browser/page-machine.test.ts b/packages/gui-plugins/src/browser/page-machine.test.ts index bc3b9aad62a..1bcc86942da 100644 --- a/packages/gui-plugins/src/browser/page-machine.test.ts +++ b/packages/gui-plugins/src/browser/page-machine.test.ts @@ -62,8 +62,7 @@ test("a redraw against the filter gate's held navigation: rejected while it is h expect(frameStillCurrent(page, cancelled)).toBe(true) expect(frameStillCurrent(page, replay(visit("https://site.test/b"), waiting).state)).toBe(false) - // A restored tab whose held load is stopped shows its blank page; one whose load was never issued stays restoring, - // and no redraw of it is current. + // An actual native stop with no commit is distinct from stopping before Chromium starts the load. const restoring = createDocumentState({ generation: 1, title: "B", url: "https://site.test/b" }) const blank = replay([...held, { type: "loading.stopped", title: "" }], restoring).state expect(blank.status).toBe("blank") @@ -71,6 +70,25 @@ test("a redraw against the filter gate's held navigation: rejected while it is h expect(frameStillCurrent(restoring, blank)).toBe(false) }) +test("Stop before issue publishes the restore address without inventing a committed document or an error", () => { + const address = "https://next.test/report" + const restore = createDocumentState({ url: address, title: "Report", generation: 4 }) + + for (const before of [restore, replay(visit("https://previous.test/")).state]) { + const cancelled = replay([ + { type: "navigation.started", isMainFrame: true, isSameDocument: false, url: address }, + { type: "loading.started" }, + { type: "navigation.held-stopped", address }, + ], before).state + + const saved = documentTab(cancelled, history) + expect(saved).toMatchObject({ id: history.id, url: address, loading: false }) + expect(saved).not.toHaveProperty("loadError") + expect(documentVisible(cancelled)).toBe(documentVisible(before)) + expect(documentTab(cancelled, history, false)).toEqual(documentTab(before, history, false)) + } +}) + // Electron's events for a navigation that commits and finishes loading. const visit = (url: string, title = url): DocumentEvent[] => [ { type: "navigation.started", url, isMainFrame: true, isSameDocument: false }, diff --git a/packages/gui-plugins/src/browser/page-machine.ts b/packages/gui-plugins/src/browser/page-machine.ts index 19cd0a9d323..4ff8533e3de 100644 --- a/packages/gui-plugins/src/browser/page-machine.ts +++ b/packages/gui-plugins/src/browser/page-machine.ts @@ -8,6 +8,8 @@ type Document = { /** Bumped when a navigation replaces the document; refs and operations from an older one are stale. */ readonly generation: number readonly url: string + /** An unissued user navigation. Shown and saved, but never used as the committed document's identity. */ + readonly retry?: string /** * Chromium names a document after its URL until its parses. A navigation on the same site keeps the shown * title until the new document names itself or stops loading, so a page that reloads or redirects to itself does @@ -43,6 +45,7 @@ export type DocumentState = | { readonly status: "closed" } export type DocumentEvent = + | { readonly type: "navigation.held-stopped"; readonly address?: string } | { readonly type: "loading.started" } | { readonly type: "loading.stopped"; readonly title: string } | { @@ -126,6 +129,8 @@ export function transitionDocument(state: DocumentState, event: DocumentEvent): if (state.status === "closed") return unchanged(state) switch (event.type) { + case "navigation.held-stopped": + return settle(state, { ...state, retry: event.address, busy: false, pending: undefined }, [PUBLISH]) case "disposed": return { state: CLOSED, effects: [] } case "loading.started": @@ -135,7 +140,7 @@ export function transitionDocument(state: DocumentState, event: DocumentEvent): case "navigation.started": if (!event.isMainFrame || event.isSameDocument) return unchanged(state) - return settle(state, { ...state, pending: event.url }, [CLEAR, PUBLISH]) + return settle(state, { ...state, retry: undefined, pending: event.url }, [CLEAR, PUBLISH]) case "navigation.committed": return committed(state, event) case "navigation.failed": @@ -210,6 +215,7 @@ export function isDocumentLoading(state: DocumentState) { export function documentTab( state: DocumentState, history: { readonly id: Browser.TabID; readonly canGoBack: boolean; readonly canGoForward: boolean }, + display = true, ): Browser.Tab { if (state.status === "closed") return { ...history, url: "", title: "", loading: false, generation: 0 } @@ -217,7 +223,7 @@ export function documentTab( const tab = { id: history.id, - url: state.url.slice(0, 16_384), + url: ((display && state.retry) || state.url).slice(0, 16_384), title: state.title.slice(0, 2_048), loading, canGoBack: history.canGoBack, @@ -226,7 +232,7 @@ export function documentTab( } // A reload of a failed page shows its progress, and the error again if it stops without a document. - return state.status === "failed" && !loading ? { ...tab, loadError: state.message } : tab + return state.status === "failed" && !loading && !state.retry ? { ...tab, loadError: state.message } : tab } function committed(state: Open, event: Extract<DocumentEvent, { type: "navigation.committed" }>): DocumentTransition { diff --git a/packages/gui-plugins/src/browser/pane-machine.test.ts b/packages/gui-plugins/src/browser/pane-machine.test.ts index 5922b00cd48..b847bb7ea1b 100644 --- a/packages/gui-plugins/src/browser/pane-machine.test.ts +++ b/packages/gui-plugins/src/browser/pane-machine.test.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from "bun:test" import { Browser } from "@opencode/plugin-browser/rpc" +import { createDocumentState, documentTab, transitionDocument } from "./page-machine" import { invalidReply, wireOutcome, wireState } from "./wire" import { SessionNotFoundError } from "@opencode/protocol/errors" import { @@ -73,6 +74,18 @@ function attached(restore?: Browser.State) { return play(createPaneState(), registered(restore), on({ type: "server.attached", fileRoots: [] })).state } +test("the saved-tab record after stopping a deferred restore is the original address", () => { + const prior = tab(tabA, dashboard, "Dashboard", 2) + const start = attached({ tabs: [prior], focusedTabID: tabA }) + const attempt = entry(start).nextAttempt + const held = transitionDocument(createDocumentState(prior), { type: "navigation.started", url: dashboard, isMainFrame: true, isSameDocument: false }).state + const stopped = transitionDocument(held, { type: "navigation.held-stopped", address: dashboard }).state + const value = documentTab(stopped, { id: tabA, canGoBack: false, canGoForward: false }) + const opened = play(start, on({ type: "tab.opened", tabID: tabA, attempt, tab: prior })) + const next = play(opened.state, on({ type: "tab.published", tabID: tabA, attempt, tab: value })) + expect(next.effects).toContainEqual({ type: "save-restore", storageKey: "server\nb1", snapshot: { tabs: [{ id: tabA, url: dashboard }], focusedTabID: tabA } }) +}) + test("a refused restore keeps its saved address, reports the reason once and consumes no page attempt", () => { const url = "file:///old/project/index.html" const start = attached({ tabs: [tab(tabA, url)], focusedTabID: tabA }) From 611cd6be5f8eb5694941948d357c65c39be14699 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:20:58 +1000 Subject: [PATCH 09/44] feat(browser): add permission-checked extension stylesheet APIs --- packages/gui-plugins/src/browser/chromium.ts | 3 + .../browser/profile/extension-api/action.ts | 3 + .../src/browser/profile/extension-api/api.ts | 8 +- .../profile/extension-api/context-menus.ts | 2 + .../profile/extension-api/frame-styles.js | 45 +++++ .../src/browser/profile/extension-api/host.ts | 3 +- .../browser/profile/extension-api/index.ts | 6 +- .../browser/profile/extension-api/preload.js | 30 ++- .../profile/extension-api/styles.test.ts | 59 ++++++ .../browser/profile/extension-api/styles.ts | 177 ++++++++++++++++++ .../src/browser/profile/extension-api/tabs.ts | 5 + 11 files changed, 330 insertions(+), 11 deletions(-) create mode 100644 packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js create mode 100644 packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts create mode 100644 packages/gui-plugins/src/browser/profile/extension-api/styles.ts diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 5615065b1f7..9aab0aa7bc1 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -299,6 +299,8 @@ export function createBrowserPage( webPreferences: { partition: options.partition, nodeIntegration: false, + // Deliver the profile's CSS receiver to child frames. It runs in the isolated sandbox, not the web world. + nodeIntegrationInSubFrames: options.local === true, contextIsolation: true, sandbox: true, webSecurity: true, @@ -767,6 +769,7 @@ export function createBrowserPage( overrideBrowserWindowOptions: { webPreferences: { nodeIntegration: false, + nodeIntegrationInSubFrames: options.local === true, contextIsolation: true, sandbox: true, webSecurity: true, diff --git a/packages/gui-plugins/src/browser/profile/extension-api/action.ts b/packages/gui-plugins/src/browser/profile/extension-api/action.ts index 6943829c4ec..6f6f383eabe 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/action.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/action.ts @@ -86,6 +86,7 @@ const MEMBERS = [ * extension through `onClicked` when it has none. */ export function createActions(input: { + grant: (extension: Extension, tabId: number) => void tabs: ExtensionTabs emit: Emit changed: () => void @@ -250,6 +251,8 @@ export function createActions(input: { const values = actionFor(stateOf(extension), tab?.id) if (values.enabled === false) return true + + if (tab) input.grant(extension, tab.id) const url = extensionPage(extension.id, values.popup) if (url) { diff --git a/packages/gui-plugins/src/browser/profile/extension-api/api.ts b/packages/gui-plugins/src/browser/profile/extension-api/api.ts index 44221e06d28..1b952dec525 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/api.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/api.ts @@ -86,9 +86,11 @@ export type Emit = (event: string, args: readonly Wire[], extension?: string) => /** The namespace a `path.member` name belongs to: the one whose path is everything before the member. */ export function namespaceOf(namespaces: readonly ApiNamespace[], name: string) { - return namespaces.find( - (namespace) => name.startsWith(`${namespace.path}.`) && !name.slice(namespace.path.length + 1).includes("."), - ) + return namespaces.find(namespace => { + const member = name.slice(namespace.path.length + 1) + + return name.startsWith(`${namespace.path}.`) && (namespace.methods.includes(member) || namespace.events?.includes(member)) + }) } /** diff --git a/packages/gui-plugins/src/browser/profile/extension-api/context-menus.ts b/packages/gui-plugins/src/browser/profile/extension-api/context-menus.ts index 482ad4feabe..845bade8a7b 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/context-menus.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/context-menus.ts @@ -183,6 +183,7 @@ export function menuTarget( * it has more than one; the extension API never sees built-in items or a local preview's context. */ export function createContextMenus(input: { + grant: (extension: Extension, tabId: number) => void tabs: ExtensionTabs emit: Emit extensions: () => readonly Extension[] @@ -203,6 +204,7 @@ export function createContextMenus(input: { } const clicked = (extension: Extension, tab: PaneTab, item: MenuItem, params: ContextMenuParams) => { + if (params.pageURL === tab.contents.getURL()) input.grant(extension, tab.contents.id) const target = menuTarget(params) const choice = item.type === "checkbox" || item.type === "radio" // The tab that was right-clicked, with its address only for an extension that may read it. diff --git a/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js b/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js new file mode 100644 index 00000000000..aa0fa450d04 --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js @@ -0,0 +1,45 @@ +// Runs only in a pane document's sandboxed isolated preload world. No function or IPC channel is exposed to +// page JS. The native keys belong to this document (including in an out-of-process child), never to a URL. +if (process.type === "renderer" && process.contextIsolated && process.sandboxed && /^(https?:|about:)/.test(location.protocol)) { + const { ipcRenderer, webFrame } = require("electron") + const sheets = new Map() + const forget = id => { + const keys = sheets.get(id) + keys?.forEach((key, name) => { + // Keep the record for live USER keys until the document goes away (see removal below). + if (name.startsWith("user:")) return + webFrame.removeInsertedCSS(key) + keys.delete(name) + }) + if (!keys?.size) sheets.delete(id) + } + ipcRenderer.on("browser-extension:forget-css", (_, id) => forget(id)) + addEventListener("pagehide", () => sheets.forEach((_, id) => forget(id)), { once: true }) + ipcRenderer.on("browser-extension:css", async (_, channel, at) => { + try { + if (at !== "document_start" && document.readyState === "loading") { + await new Promise(resolve => addEventListener("DOMContentLoaded", resolve, { once: true })) + } + if (at === "document_idle" && document.readyState !== "complete") { + await new Promise(resolve => requestIdleCallback(resolve, { timeout: 200 })) + } + const item = await ipcRenderer.invoke(channel) + if (!item) return ipcRenderer.send(channel, false) + const name = `${item.origin}:${item.css}` + const keys = sheets.get(item.id) ?? new Map() + if (item.remove) { + const key = keys.get(name) + // Electron 44's removal binding always passes Blink's default (author) origin. Do not silently + // report success or discard a live USER key. Destruction of this document drops its native sheets. + if (key !== undefined && item.origin === "user") return ipcRenderer.send(channel, "user-removal") + if (key !== undefined) webFrame.removeInsertedCSS(key) + keys.delete(name) + if (!keys.size) sheets.delete(item.id) + } else if (!keys.has(name)) { + keys.set(name, webFrame.insertCSS(item.css, { cssOrigin: item.origin })) + sheets.set(item.id, keys) + } + ipcRenderer.send(channel, true) + } catch { ipcRenderer.send(channel, false) } + }) +} diff --git a/packages/gui-plugins/src/browser/profile/extension-api/host.ts b/packages/gui-plugins/src/browser/profile/extension-api/host.ts index 33935f338b3..fa1ee3459bb 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/host.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/host.ts @@ -7,6 +7,7 @@ import type { Manifests } from "./manifest" import { sendBackgroundEvent, workerQueue } from "./worker-events" import { eventPage } from "./event-page" import preloadSource from "./preload.js?raw" +import frameStyles from "./frame-styles.js?raw" /** A context that listens to an event: a page frame, or the extension's service worker, which is started to hear it. */ type Subscriber = { readonly kind: "frame"; readonly process: number; readonly routing: number } | { readonly kind: "worker" | "eventPage" } @@ -50,7 +51,7 @@ export async function createExtensionHost(input: { // The modules already listen (to cookies, tabs); a host that cannot start lets them go again. await writeFile( file, - preloadSource.replace('"__NAMESPACES__"', JSON.stringify(JSON.stringify(namespaces))), + frameStyles + "\n" + preloadSource.replace('"__NAMESPACES__"', JSON.stringify(JSON.stringify(namespaces))), "utf8", ).catch((cause: unknown) => { input.modules.forEach((module) => module.dispose?.()) diff --git a/packages/gui-plugins/src/browser/profile/extension-api/index.ts b/packages/gui-plugins/src/browser/profile/extension-api/index.ts index e27d8f86d03..e2567060650 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/index.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/index.ts @@ -11,6 +11,7 @@ import { createNotifications } from "./notifications" import { createPermissions } from "./permissions" import { createPopups } from "./popup" import { createStorageSync } from "./storage-sync" +import { createStyles } from "./styles" import { createStubs } from "./stubs" import { createExtensionTabs } from "./tabs" import { createWebNavigation } from "./web-navigation" @@ -38,10 +39,12 @@ export async function createExtensionApis(input: { const extensions = () => input.session.extensions.getAllExtensions() const manifest = createManifests() const tabs = createExtensionTabs({ emit, extensions, manifest }) - const menus = createContextMenus({ tabs, emit, extensions, manifest, storage: input.storage }) + const styles = createStyles(tabs, manifest) + const menus = createContextMenus({ tabs, emit, extensions, manifest, storage: input.storage, grant: styles.grant }) const popups = createPopups({ partition: input.partition, tabs }) const actions = createActions({ + grant: styles.grant, tabs, emit, changed: input.changed, @@ -60,6 +63,7 @@ export async function createExtensionApis(input: { modules: [ { namespaces: [{ path: "runtime", methods: [], events: ["onInstalled"] }], methods: {} }, tabs.module, + styles.module, actions.module, createWebNavigation({ tabs, emit }), menus.module, diff --git a/packages/gui-plugins/src/browser/profile/extension-api/preload.js b/packages/gui-plugins/src/browser/profile/extension-api/preload.js index c9f8b83f7e8..1decd99b467 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/preload.js +++ b/packages/gui-plugins/src/browser/profile/extension-api/preload.js @@ -45,8 +45,11 @@ if (href.startsWith("chrome-extension://")) { }, } - if (isolated) contextBridge.executeInMainWorld({ func: install, args: [namespaces, bridge] }) - else install(namespaces, bridge) + // Child frames newly receiving the CSS preload get only the guarded stylesheet calls, not the other shims. + const api = process.type === "renderer" && process.isMainFrame === false + ? namespaces.filter(entry => entry.methods.includes("insertCSS")) : namespaces + if (isolated) contextBridge.executeInMainWorld({ func: install, args: [api, bridge] }) + else install(api, bridge) } // Runs in the extension's own world, so it must not use anything from this file's scope. @@ -117,8 +120,10 @@ function install(namespaces, bridge) { return typeof value === "function" ? undefined : value } - const call = (name, sync) => - function (...args) { + const call = (name, sync) => { + const scripting = name === "scripting.insertCSS" || name === "scripting.removeCSS" + const native = scripting && chrome.scripting?.[name.slice("scripting.".length)]?.bind(chrome.scripting) + return function (...args) { const callback = typeof args.at(-1) === "function" ? args.pop() : undefined if (sync && args[0] && typeof args[0] === "object" && args[0].id === undefined) @@ -127,6 +132,10 @@ function install(namespaces, bridge) { const result = bridge.invoke(name, clean(args)).then((reply) => { if (!reply.ok) throw new Error(reply.message) + if (scripting) { + if (!native) throw new Error(`chrome.${name} is unavailable in this runtime.`) + return native({ ...args[0], target: reply.value }) + } return reply.value }) @@ -135,13 +144,22 @@ function install(namespaces, bridge) { result.then( (value) => callback(value), (error) => { - console.error(`chrome.${name}: ${error?.message ?? error}`) - callback() + const last = { message: error?.message ?? String(error) } + const runtime = chrome.runtime + const previous = Object.getOwnPropertyDescriptor(runtime, "lastError") + let read = false + Object.defineProperty(runtime, "lastError", { configurable: true, get() { read = true; return last } }) + try { callback() } finally { + if (previous) Object.defineProperty(runtime, "lastError", previous) + else delete runtime.lastError + if (!read) console.error(`Unchecked runtime.lastError: ${last.message}`) + } }, ) return id } + } /* oxlint-enable anti-slop/no-runtime-typeof */ diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts new file mode 100644 index 00000000000..6106dddf080 --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts @@ -0,0 +1,59 @@ +import { expect, test } from "bun:test" +import { readFile } from "node:fs/promises" +import { runInNewContext } from "node:vm" +import { canStyle } from "./styles" + +test("CSS access requires the frame's host or a gesture for that top origin; private documents never qualify", () => { + const top = "https://page.test/report" + const child = "https://frame.test/embed" + const grants = ["https://frame.test/*"] + const origin = "https://page.test" + const app = "http://localhost:5173/index.html" + + for (const [root, frame, inherited, hosts, gesture, blank, ok] of [ + [top, child, "https://frame.test", grants, undefined, false, true], + [top, child, "https://frame.test", [], origin, false, false], + [top, top, origin, [], origin, false, true], + [top, top, origin, [], undefined, false, false], + [top, "about:blank", origin, [], origin, true, true], + [top, "about:srcdoc", origin, [], origin, false, false], + [top, "about:blank", "null", ["<all_urls>"], origin, true, false], + ["oc-preview://grant/report", child, "https://frame.test", grants, origin, true, false], + ["workspace://session/report", child, "https://frame.test", grants, origin, true, false], + ["artifact://art_x/", child, "https://frame.test", grants, origin, true, false], + [top, "chrome-extension://other/private", "null", ["<all_urls>"], origin, true, false], + [app, child, "https://frame.test", grants, origin, true, false], + [top, app, "http://localhost:5173", ["<all_urls>"], undefined, true, false], + ] as const) expect(canStyle(root, frame, inherited, hosts, gesture, blank, app)).toBe(ok) +}) + +test("a document removes only native sheet keys belonging to the same extension, text and origin", async () => { + const source = await readFile(new URL("./frame-styles.js", import.meta.url), "utf8") + const listeners = new Map<string, (...args: readonly unknown[]) => Promise<void> | void>() + const removed: string[] = [] + let sequence = 0 + const item = { id: "one", css: "body{}", origin: "author", remove: false } + const replies: (boolean | string)[] = [] + const ipcRenderer = { on: listeners.set.bind(listeners), invoke: async () => item, send: (_: string, reply: boolean | string) => replies.push(reply) } + const webFrame = { insertCSS: () => String(++sequence), removeInsertedCSS: (key: string) => removed.push(key) } + runInNewContext(source, { process: { type: "renderer", contextIsolated: true, sandboxed: true }, location: { protocol: "https:" }, document: { readyState: "complete" }, require: () => ({ ipcRenderer, webFrame }), addEventListener: listeners.set.bind(listeners) }) + const style = () => listeners.get("browser-extension:css")?.({}, "request", "document_start") + await style() + await style() + item.id = "two" + await style() + item.origin = "user" + await style() + expect(sequence).toBe(3) + item.remove = true + await style() + expect(replies.at(-1)).toBe("user-removal") + expect(removed).toEqual([]) + item.origin = "author" + await style() + expect(removed).toEqual(["2"]) + listeners.get("browser-extension:forget-css")?.({}, "one") + expect(removed).toEqual(["2", "1"]) + listeners.get("pagehide")?.() + expect(removed).toEqual(["2", "1"]) +}) diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts new file mode 100644 index 00000000000..d64a354d6fa --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts @@ -0,0 +1,177 @@ +import { once } from "node:events" +import type { Extension, WebFrameMain } from "electron" +import { Schema } from "effect" +import { openContained } from "@opencode/util/contained-file" +import { method, type ApiModule, type ExtensionContext } from "./api" +import { matchesHost } from "./match-pattern" +import type { Manifests } from "./manifest" +import type { ExtensionTabs } from "./tabs" + +const Origin = Schema.Literals(["author", "user"]) + +const Details = Schema.Struct({ code: Schema.optional(Schema.String), file: Schema.optional(Schema.String), frameId: Schema.optional(Schema.Int), allFrames: Schema.optional(Schema.Boolean), matchAboutBlank: Schema.optional(Schema.Boolean), cssOrigin: Schema.optional(Origin), runAt: Schema.optional(Schema.Literals(["document_start", "document_end", "document_idle"])) }) + +const Arguments = Schema.Union([Schema.Tuple([Details]), Schema.Tuple([Schema.NullOr(Schema.Int), Details])]) + +const Injection = Schema.Struct({ target: Schema.Struct({ tabId: Schema.Int, allFrames: Schema.optional(Schema.Boolean), frameIds: Schema.optional(Schema.Array(Schema.Int)), documentIds: Schema.optional(Schema.Array(Schema.String)) }) }) + +/** An activeTab gesture lends the top origin, not arbitrary cross-site children. The pane registry is the + * first fence; also check the currently committed top document even for a separately permitted web iframe. */ +export function canStyle(top: string, url: string, origin: string, hosts: readonly string[], grant: string | undefined, blank: boolean, appURL: string) { + const root = URL.parse(top) + + if (!root || !/^https?:$/.test(root.protocol) || root.origin === URL.parse(appURL)?.origin) return false + const inherited = !url || url === "about:blank" || url === "about:srcdoc" + const target = URL.parse(inherited && blank ? origin : url) + + if (!target || !/^https?:$/.test(target.protocol) || target.origin === URL.parse(appURL)?.origin) return false + + return matchesHost(hosts, target.href) || (root.origin === grant && target.origin === grant) +} + +export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { + const grants = new Map<number, Map<string, string>>() + const owners = new Map<string, AbortController>() + + const release = tabs.watch(tab => { + const contents = tab.contents + + const committed = () => { + const origin = URL.parse(contents.getURL())?.origin + grants.get(contents.id)?.forEach((prior, id, entries) => { if (prior !== origin) entries.delete(id) }) + } + + contents.on("did-navigate", committed) + + return () => { + grants.delete(contents.id) + + if (!contents.isDestroyed()) contents.off("did-navigate", committed) + } + }) + + const grant = (extension: Extension, id: number) => { + const tab = tabs.get(id) + + if (!tab || !manifest(extension).permissions.includes("activeTab")) return + const url = URL.parse(tab.contents.getURL()) + + if (!url || !/^https?:$/.test(url.protocol)) return + const entries = grants.get(id) ?? new Map<string, string>() + entries.set(extension.id, url.origin) + grants.set(id, entries) + } + + const forget = (id: string) => { + owners.get(id)?.abort() + owners.delete(id) + grants.forEach(entries => entries.delete(id)) + + for (const tab of tabs.ids()) { + for (const frame of tabs.get(tab)?.contents.mainFrame.framesInSubtree ?? []) { + if (!frame.detached && !frame.isDestroyed()) frame.send("browser-extension:forget-css", id) + } + } + } + + const apply = async (context: ExtensionContext, id: number | null | undefined, details: typeof Details.Type, remove: boolean) => { + const current = id ?? tabs.current(context) + const tab = current === undefined ? undefined : tabs.get(current) + + if (!tab) throw new Error(current === undefined ? "No active tab." : `No tab with id: ${current}.`) + + if ((details.code === undefined) === (details.file === undefined)) throw new Error("Specify exactly one of 'code' and 'file'.") + + if (details.allFrames && details.frameId !== undefined) throw new Error("Cannot specify both 'allFrames' and 'frameId'.") + const extension = context.extension + const owner = owners.get(extension.id) ?? new AbortController() + owners.set(extension.id, owner) + const top = tab.contents.mainFrame + + const allowed = (frame: WebFrameMain) => !owner.signal.aborted && !tab.contents.isDestroyed() && tabs.get(tab.contents.id) === tab && !frame.isDestroyed() && !frame.detached && + tab.contents.mainFrame === top && canStyle(top.url, frame.url, frame.origin, manifest(extension).hosts, grants.get(tab.contents.id)?.get(extension.id), !!details.matchAboutBlank, tab.window.webContents.getURL()) + + const frames = details.allFrames ? top.framesInSubtree : [details.frameId ? top.framesInSubtree.find(f => f !== top && f.frameTreeNodeId === details.frameId) : top] + + if (frames.some(f => !f)) throw new Error(`No frame with id ${details.frameId} in tab ${current}.`) + const targets = frames.filter((f): f is WebFrameMain => !!f && allowed(f)) + + if (!targets.length) throw new Error("Cannot access contents of the page. Extension manifest must request permission to access the respective host.") + const css = details.code ?? await packageCSS(extension, details.file ?? "") + await Promise.all(targets.map(async frame => { + if (!allowed(frame)) throw new Error("The target frame is no longer available.") + const channel = `browser-extension:css:${crypto.randomUUID()}` + const ipc = frame.ipc + const lifetime = new AbortController() + const signal = AbortSignal.any([owner.signal, lifetime.signal, AbortSignal.timeout(15000)]) + // Reauthorize in the receiving document, at the requested runAt, not just when the command was queued. + ipc.handleOnce(channel, event => { + if (event.senderFrame !== frame || !allowed(frame)) return null + + return { id: extension.id, css, origin: details.cssOrigin ?? "author", remove } + }) + + try { + const [reply] = await Promise.all([ + once(ipc, channel, { signal }), + Promise.resolve().then(() => frame.send("browser-extension:css", channel, remove ? "document_start" : details.runAt ?? "document_idle")), + ]) + + if (reply[1] === "user-removal") throw new Error("Electron cannot remove a user-origin stylesheet until the document is reloaded.") + + if (reply[1] !== true) throw new Error("The target frame is no longer available.") + } finally { + lifetime.abort() + ipc.removeHandler(channel) + } + })) + } + + const mv2 = (remove: boolean) => method(Arguments, (context, args) => args.length === 1 ? apply(context, undefined, args[0], remove) : apply(context, args[0], args[1], remove)) + + // MV3 has native CSS APIs. Keep Chromium's package-file resolution, cascade origins and removal; return + // only approved frame IDs, never allFrames (a newly attached child has not been authorized). + const mv3 = method(Schema.Tuple([Injection]), (context, [input]) => { + if (input.target.documentIds) throw new Error("Targeting a document by UUID is not supported in this browser.") + + if (input.target.frameIds && input.target.allFrames) throw new Error("Cannot specify both 'allFrames' and 'frameIds'.") + + const tab = tabs.get(input.target.tabId) + + if (!tab) throw new Error(`No tab with id: ${input.target.tabId}.`) + const top = tab.contents.mainFrame + const ids = input.target.frameIds ?? [0] + const frames = top.framesInSubtree.map(frame => ({ frame, id: frame === top ? 0 : frame.frameTreeNodeId })) + + if (ids.some(id => !frames.some(f => f.id === id))) throw new Error("The target frame is no longer available.") + const requested = frames.filter(f => input.target.allFrames || ids.includes(f.id)) + const allowed = requested.filter(({ frame }) => canStyle(top.url, frame.url, frame.origin, manifest(context.extension).hosts, grants.get(tab.contents.id)?.get(context.extension.id), false, tab.window.webContents.getURL())) + + if (!allowed.length || (!input.target.allFrames && requested.length !== allowed.length)) throw new Error("Cannot access contents of the page.") + + return { tabId: tab.contents.id, frameIds: allowed.map(f => f.id) } + }) + + const module: ApiModule = { + namespaces: [ + { path: "tabs", manifest: 2, methods: ["insertCSS", "removeCSS"], events: [] }, + { path: "scripting", manifest: 3, permissions: ["scripting"], methods: ["insertCSS", "removeCSS"], events: [] }, + ], + methods: { "tabs.insertCSS": mv2(false), "tabs.removeCSS": mv2(true), "scripting.insertCSS": mv3, "scripting.removeCSS": mv3 }, + forget, + dispose() { owners.forEach((_, id) => forget(id)); release() }, + } + + return { module, grant } +} + +async function packageCSS(extension: Extension, resource: string) { + const path = resource.replace(/^\/(?!\/)/, "") + + if (!path || /[\\:%?#]/.test(path)) throw new Error("Invalid extension stylesheet path.") + const opened = await openContained(extension.path, path).catch(() => undefined) + + if (!opened) throw new Error(`Could not load file: '${resource}'.`) + + try { return await opened.file.readFile("utf8") } finally { await opened.file.close() } +} diff --git a/packages/gui-plugins/src/browser/profile/extension-api/tabs.ts b/packages/gui-plugins/src/browser/profile/extension-api/tabs.ts index d8959cf1de9..d94a62e2d9b 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/tabs.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/tabs.ts @@ -437,6 +437,11 @@ export function createExtensionTabs(input: { return { module, + current(context: ExtensionContext) { + const id = currentWindow(context) + + return id === undefined ? undefined : activeOf(id)?.contents.id + }, /** * Hands a pane tab to extensions until the returned release; `tabs.onCreated` hears of it, and of every change * Chrome reports through `tabs.onUpdated`. From 4696694fa1bcc2566e95f1884b26fb4ef5cc212d Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:24:02 +1000 Subject: [PATCH 10/44] fix(browser): keep the keys inside a page prompt from reaching the app behind it macOS Run 9 item 6: Cmd+R with a prompt() field focused reloaded the page and dropped the prompt (the pane's mod+r, scoped to #browser-panel and editable), and Cmd+. cycled the agent behind the open prompt. The command layer already runs no keybind while one of the app's own dialogs is open (dialog.active); it now also runs none for a key whose target is inside an aria-modal dialog, which the pane's tab-modal prompts are. The prompt owns its keys (prompt-keys.ts): Enter, Escape and Tab answer and move within it, typing and the clipboard and undo chords edit its field, the window's own chords (close or new window, quit, hide, full screen) still work, and every other chord is swallowed, so neither the window's reload or zoom nor any other handler behind it sees them. Reload is swallowed rather than cancelling the prompt, as Chrome does with a tab-modal dialog. Typing in a prompt no longer moves to the composer. With the keyboard elsewhere, such as in the composer, the app's shortcuts work and the prompt stays open. The permission bar is not modal and owns only Escape. --- .../app/component-tests/browser-pane.spec.ts | 67 ++++++++++++++++ .../app/src/shell/commands/command.test.ts | 15 ++++ packages/app/src/shell/commands/command.tsx | 11 ++- .../src/browser/prompt-keys.test.ts | 65 ++++++++++++++++ .../gui-plugins/src/browser/prompt-keys.ts | 77 +++++++++++++++++++ packages/gui-plugins/src/browser/prompts.tsx | 22 +++++- 6 files changed, 254 insertions(+), 3 deletions(-) create mode 100644 packages/gui-plugins/src/browser/prompt-keys.test.ts create mode 100644 packages/gui-plugins/src/browser/prompt-keys.ts diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index 8cc78aacca0..b78ce71de94 100644 --- a/packages/app/component-tests/browser-pane.spec.ts +++ b/packages/app/component-tests/browser-pane.spec.ts @@ -1051,6 +1051,73 @@ story("asks for a page's prompt text and sends what the user typed", async ({ pa await expect(dialog).toBeHidden() }) +// What the key test below records in the story's window. +declare global { + interface Window { + keyLog: KeyboardEvent[] + keyBehind: string[] + } +} + +story("keeps the keys inside a page prompt, and leaves them to the window once the keyboard is elsewhere", async ({ page }) => { + const root = page.getByTestId("browser-pane-fixture") + // Each key as the window saw it first, and whether its default was cancelled once every handler had seen it. + await page.evaluate(() => { + const log: KeyboardEvent[] = [] + // Keys the window's own handlers behind the prompt would see, as the composer's and the zoom's do. + const behind: string[] = [] + Object.assign(window, { keyLog: log, keyBehind: behind }) + window.addEventListener("keydown", (event) => log.push(event), { capture: true }) + window.addEventListener("keydown", (event) => behind.push(event.key)) + }) + const behind = () => page.evaluate(() => window.keyBehind.splice(0)) + + const log = () => + page.evaluate(() => + window.keyLog + .splice(0) + .filter((event) => !["Control", "Alt", "Shift", "Meta"].includes(event.key)) + .map((event) => `${event.key}:${event.defaultPrevented ? "prevented" : "default"}`), + ) + + await root.getByRole("button", { name: "Page prompt", exact: true }).evaluate((element: HTMLElement) => element.click()) + const dialog = page.getByRole("alertdialog", { name: "alpha.example says" }) + const field = dialog.getByRole("textbox", { name: "Your answer" }) + await expect(field).toBeFocused() + await field.press("End") + await page.keyboard.type(" two") + await log() + + // Reload, the agent switch, find, address field, close and new tab, zoom and history do nothing here. + for (const chord of ["Control+r", "Control+.", "Control+f", "Control+l", "Control+w", "Control+t", "Control+Equal", "Alt+ArrowLeft", "F5"]) + await page.keyboard.press(chord) + expect(await log()).toEqual(["r", ".", "f", "l", "w", "t", "=", "ArrowLeft", "F5"].map((key) => `${key}:prevented`)) + // Editing keys edit the field as they do anywhere. + await page.keyboard.press("Control+a") + await page.keyboard.press("ArrowRight") + await page.keyboard.press("Backspace") + expect(await log()).toEqual(["a:default", "ArrowRight:default", "Backspace:default"]) + await expect(field).toHaveValue("Draft tw") + await expect(dialog).toBeVisible() + // None of them went past the prompt to the window's handlers. + expect(await behind()).toEqual([]) + + // With the keyboard in the composer, its keys are the app's and the prompt stays open. + await root.getByRole("textbox", { name: "Composer stand-in" }).focus() + await page.keyboard.press("Control+r") + expect(await log()).toEqual(["r:default"]) + expect(await behind()).toEqual(["Control", "r"]) + await expect(dialog).toBeVisible() + + await field.focus() + await expect(async () => { + await field.press("Enter") + await expect(root.getByText('Answers: [{"kind":"dialog","accept":true,"text":"Draft tw","stop":false}]', { exact: true })).toBeVisible({ + timeout: 200, + }) + }).toPass() +}) + story("asks for a site's sign-in with its realm, says the last one failed, and keeps nothing on cancel", async ({ page }) => { const root = page.getByTestId("browser-pane-fixture") await root.getByRole("button", { name: "Sign-in request", exact: true }).evaluate((element: HTMLElement) => element.click()) diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index 72ddf29c6e1..d84450a2a30 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -7,6 +7,7 @@ import { CommandCatalog, commandKeymap, formatKeybind, + insideModalDialog, matchKeybind, parseKeybind, resolveKeybindOption, @@ -141,3 +142,17 @@ describe("command keybinds", () => { expect(formatKeybind("mod+k,mod+p")).not.toContain("P") }) }) + +describe("keys inside a modal dialog", () => { + test("belong to the dialog, which may cover only part of the window; keys elsewhere run commands", () => { + const page = document.createElement("div") + page.innerHTML = `<div id="pane"><div role="alertdialog" aria-modal="true"><input id="field"></div></div><div id="composer" contenteditable="true"></div>` + document.body.append(page) + + expect(insideModalDialog(page.querySelector("#field"))).toBe(true) + expect(insideModalDialog(page.querySelector("#composer"))).toBe(false) + expect(insideModalDialog(page.querySelector("#pane"))).toBe(false) + expect(insideModalDialog(null)).toBe(false) + page.remove() + }) +}) diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 7c916ee63a0..1a5bf764573 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -368,6 +368,15 @@ export function formatKeybind(config: string, t?: (key: KeyLabel) => string): st return IS_MAC ? parts.join("") : parts.join("+") } +/** + * Whether a key's target is inside a modal dialog, which owns the keyboard there: no command keybind runs, as none runs + * while one of the app's own dialogs is open (`dialog.active`). A dialog modal for less than the window, such as a + * page's prompt in the browser pane, owns only the keys pressed inside it. + */ +export function insideModalDialog(target: EventTarget | null) { + return target instanceof Element && !!target.closest('[aria-modal="true"]') +} + function isEditableTarget(target: EventTarget | null) { if (!(target instanceof HTMLElement)) return false @@ -514,7 +523,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const handleKeyDown = (event: KeyboardEvent) => { - if (suspended() || dialog.active) return + if (suspended() || dialog.active || insideModalDialog(event.target)) return const sig = signatureFromEvent(event) const isPalette = palette().has(sig) diff --git a/packages/gui-plugins/src/browser/prompt-keys.test.ts b/packages/gui-plugins/src/browser/prompt-keys.test.ts new file mode 100644 index 00000000000..d694905e8bd --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-keys.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, test } from "bun:test" +import { promptKeyOwner, type PromptKey } from "./prompt-keys" + +// A chord as the platform writes it: "mod" is Command on macOS and Ctrl elsewhere. +const press = (chord: string, mac: boolean): PromptKey => { + const parts = chord.split("+") + const key = parts.at(-1) === "" ? "+" : (parts.at(-1) ?? "") + const has = (name: string) => parts.slice(0, -1).includes(name) + + return { + key, + ctrlKey: has("Ctrl") || (!mac && has("mod")), + metaKey: has("Cmd") || (mac && has("mod")), + altKey: has("Alt"), + shiftKey: has("Shift"), + isComposing: false, + } +} + +const owner = (chord: string, mac: boolean, inside = true) => promptKeyOwner(press(chord, mac), { inside, mac }) + +describe("keys inside an open page prompt", () => { + for (const mac of [false, true]) { + const os = mac ? "macOS" : "Windows and Linux" + + test(`answer and move within the prompt on ${os}`, () => { + for (const chord of ["Enter", "Escape", "Tab", "Shift+Tab"]) expect(owner(chord, mac)).toBe("prompt") + }) + + test(`edit its field as text fields do on ${os}`, () => { + for (const chord of ["a", "Z", " ", "Backspace", "ArrowLeft", "Shift+Home", "mod+a", "mod+c", "mod+x", "mod+v", "mod+z", "Shift+mod+z", "mod+Backspace"]) + expect(owner(chord, mac)).toBe("field") + }) + + test(`never run the app's or the pane's shortcuts behind it on ${os}`, () => { + // Reload, the agent switch, find, address field, close and new tab, zoom, palette, model picker, back. + for (const chord of ["mod+r", "mod+.", "mod+f", "mod+l", "mod+w", "mod+t", "mod+=", "mod++", "mod+-", "mod+0", "Shift+mod+p", "mod+k", "mod+'", "F5", "F3", "F6", "Shift+mod+r"]) + expect(owner(chord, mac), chord).toBe("swallowed") + }) + + test(`leave the window's own keys to the window on ${os}`, () => { + for (const chord of ["Shift+mod+w", "Shift+mod+n"]) expect(owner(chord, mac)).toBe("window") + }) + + test(`leave every key to the app when the keyboard is elsewhere on ${os}`, () => { + for (const chord of ["mod+r", "mod+.", "Escape", "Enter", "a"]) expect(owner(chord, mac, false)).toBe("app") + }) + } + + test("Windows keeps Alt for history and menus, macOS edits text with Option and Control", () => { + expect(owner("Alt+ArrowLeft", false)).toBe("swallowed") + expect(owner("Ctrl+y", false)).toBe("field") + expect(owner("Alt+ArrowLeft", true)).toBe("field") + expect(owner("Ctrl+a", true)).toBe("field") + expect(owner("Ctrl+Tab", true)).toBe("swallowed") + expect(owner("Cmd+ArrowLeft", true)).toBe("field") + expect(owner("Cmd+[", true)).toBe("swallowed") + + for (const chord of ["Cmd+q", "Cmd+h", "Cmd+Alt+h", "Cmd+m", "Ctrl+Cmd+f"]) expect(owner(chord, true)).toBe("window") + }) + + test("a key that composes text is the field's", () => { + expect(promptKeyOwner({ ...press("Enter", false), isComposing: true }, { inside: true, mac: false })).toBe("field") + }) +}) diff --git a/packages/gui-plugins/src/browser/prompt-keys.ts b/packages/gui-plugins/src/browser/prompt-keys.ts new file mode 100644 index 00000000000..5e5fdc0fff0 --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-keys.ts @@ -0,0 +1,77 @@ +// Who a key pressed in the app window belongs to while a page prompt (alert, confirm, prompt, "Leave site?", a +// sign-in) is open in the pane. The prompt is modal for its tab: while the keyboard is inside it, the app's command +// keybinds do not run (the command layer skips a key whose target is inside an `aria-modal` dialog, as it skips every +// key while one of the app's own dialogs is open), and the prompt cancels what the window itself would do behind it. +// Keys outside the prompt are the app's. + +export type PromptKey = { + readonly key: string + readonly ctrlKey: boolean + readonly metaKey: boolean + readonly altKey: boolean + readonly shiftKey: boolean + readonly isComposing: boolean +} + +export type PromptKeyOwner = + /** The prompt answers or moves within itself: Enter accepts, Escape cancels, Tab and Shift+Tab cycle. */ + | "prompt" + /** The focused field or button, as its default does: typing, moving the caret, clipboard, undo. */ + | "field" + /** The window, as Chrome leaves them to a window with a tab-modal dialog: close or new window, quit, hide, full screen. */ + | "window" + /** Nothing: an app or pane shortcut (reload, find, zoom, history, tabs, the address field, the agent, the palette). */ + | "swallowed" + /** The keyboard is elsewhere, such as the chat composer: the app's shortcuts as usual, and the prompt stays open. */ + | "app" + +const modifiers: readonly string[] = ["Alt", "AltGraph", "CapsLock", "Control", "Fn", "Meta", "NumLock", "Shift"] + +const caret: readonly string[] = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "Backspace", "Delete"] + +// Text editing on the command key (Ctrl on Windows and Linux): select all, copy, cut, paste, undo and redo. +const editing: readonly string[] = ["a", "c", "x", "v", "z"] + +/** Who `key` belongs to: `inside` is whether the keyboard is inside the open prompt. */ +export function promptKeyOwner(key: PromptKey, input: { readonly inside: boolean; readonly mac: boolean }): PromptKeyOwner { + if (!input.inside) return "app" + + if (key.isComposing || modifiers.includes(key.key)) return "field" + const name = key.key.length === 1 ? key.key.toLowerCase() : key.key + const command = input.mac ? key.metaKey : key.ctrlKey + const control = input.mac && key.ctrlKey + const plain = !key.ctrlKey && !key.metaKey && !key.altKey + + if (plain && (name === "Enter" || name === "Escape" || name === "Tab")) return "prompt" + + if (plain) return /^F\d{1,2}$/.test(name) ? "swallowed" : "field" + + if (windowChord(name, key, input.mac)) return "window" + + // macOS edits text on Option (words) and Control (Emacs bindings) too; Windows uses Alt for menus and history. + if (input.mac && key.altKey && !key.metaKey && !key.ctrlKey) return "field" + + if (control && !key.metaKey && !key.altKey) return name === "Tab" ? "swallowed" : "field" + + if (command && !key.altKey && !(input.mac ? key.ctrlKey : key.metaKey)) { + if (editing.includes(name) || (!input.mac && name === "y" && !key.shiftKey) || caret.includes(name)) return "field" + } + + return "swallowed" +} + +function windowChord(name: string, key: PromptKey, mac: boolean) { + if (mac) { + if (key.metaKey && key.ctrlKey && !key.altKey && name === "f") return true + + if (!key.metaKey || key.ctrlKey) return false + + if (!key.shiftKey && !key.altKey) return name === "q" || name === "h" || name === "m" || name === "`" + + if (key.altKey && !key.shiftKey) return name === "h" + + return key.shiftKey && !key.altKey && (name === "w" || name === "n") + } + + return key.ctrlKey && key.shiftKey && !key.altKey && !key.metaKey && (name === "w" || name === "n") +} diff --git a/packages/gui-plugins/src/browser/prompts.tsx b/packages/gui-plugins/src/browser/prompts.tsx index b191a25dcf9..113c5a8428f 100644 --- a/packages/gui-plugins/src/browser/prompts.tsx +++ b/packages/gui-plugins/src/browser/prompts.tsx @@ -8,6 +8,7 @@ import { Tooltip } from "@opencode/ui/tooltip" import { createSignal, createUniqueId, Match, onCleanup, onMount, Show, Switch, type JSX } from "solid-js" import { createKeyed, usePlugin } from "@opencode/plugin/gui" import { guardActivation } from "./activation-delay" +import { promptKeyOwner } from "./prompt-keys" import type definition from "./index" import { PROMPT_TEXT_MAX, SIGN_IN_TEXT_MAX, type PromptAnswer, type PromptSite, type PromptView } from "./ipc" @@ -72,6 +73,10 @@ export function PromptDialog(props: { if (!box) return guard = guardActivation(box) onCleanup(guard.dispose) + // A listener on the dialog itself, not Solid's on the document, so the dialog's keys stop here. + const root = box + root.addEventListener("keydown", keyDown) + onCleanup(() => root.removeEventListener("keydown", keyDown)) onCleanup(() => { const active = document.activeElement @@ -85,8 +90,16 @@ export function PromptDialog(props: { target.focus({ preventScroll: true }) }) - // Tab and Shift+Tab cycle inside the dialog; the page behind it is a still. + // The dialog's keys are its own (prompt-keys.ts): the command layer runs no shortcut from inside an aria-modal dialog, + // no other handler of the window sees them, and what the window would do behind it, as its own reload or zoom, is + // cancelled. Tab and Shift+Tab cycle inside the dialog; the page behind it is a still. const keyDown = (event: KeyboardEvent) => { + const owner = promptKeyOwner(event, { inside: true, mac }) + + if (owner !== "window") event.stopPropagation() + + if (owner === "swallowed") return event.preventDefault() + if (cancelKey(event)) { event.preventDefault() event.stopPropagation() @@ -130,6 +143,8 @@ export function PromptDialog(props: { data-component="dialog-v2" data-fit data-browser-prompt={props.view.ask.kind} + // Typing here never moves to the chat composer, and Escape here is the dialog's. + data-prevent-autofocus // The app's dialog, scoped to the page's box instead of the window; the scrim dims the page's still. style={{ position: "absolute", @@ -148,7 +163,6 @@ export function PromptDialog(props: { aria-describedby={described() ? description : undefined} tabIndex={-1} style={{ width: "min(100%, 480px)", "max-height": "100%", outline: "none" }} - onKeyDown={keyDown} > <Switch> <Match when={pageDialog()}> @@ -432,6 +446,8 @@ export function PromptBar(props: { view: PromptView; answer: (answer: PromptAnsw <section ref={bar} data-component="browser-prompt" + // Not modal: the app's shortcuts work here; only Escape, which dismisses the bar, is the bar's alone. + data-prevent-autofocus role={permission() ? "alertdialog" : "status"} aria-label={permission() ? ctx.t("prompt.permission.label") : undefined} aria-describedby={text} @@ -517,6 +533,8 @@ type Plugin = ReturnType<typeof usePlugin<typeof definition>> const cancelKey = (event: KeyboardEvent) => !event.isComposing && event.key === "Escape" +const mac = /(Mac|iPhone|iPad)/.test(navigator.platform) + function siteSays(ctx: Plugin, site: PromptSite) { if (site.kind === "web") return ctx.t(site.embedded ? "prompt.site.embedded" : "prompt.site.web", { host: site.host }) From 9f982342239e22f0232129854c23fd15b88a8dad Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:25:43 +1000 Subject: [PATCH 11/44] fix(browser): throttle idle agent tabs between commands --- .../src/browser/agent-rendering.test.ts | 31 ++++++++++++++ .../src/browser/agent-rendering.ts | 40 +++++++++++++++++++ packages/gui-plugins/src/browser/chromium.ts | 18 ++++----- packages/gui-plugins/src/browser/pane.ts | 1 - 4 files changed, 80 insertions(+), 10 deletions(-) create mode 100644 packages/gui-plugins/src/browser/agent-rendering.test.ts create mode 100644 packages/gui-plugins/src/browser/agent-rendering.ts diff --git a/packages/gui-plugins/src/browser/agent-rendering.test.ts b/packages/gui-plugins/src/browser/agent-rendering.test.ts new file mode 100644 index 00000000000..3bcd9b81912 --- /dev/null +++ b/packages/gui-plugins/src/browser/agent-rendering.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "bun:test" +import { agentRendering } from "./agent-rendering" + +test("only the last command starts the idle clock; wake before the next command and cancel at disposal", () => { + const lifetime = new AbortController() + const timers = new Set<() => void>() + const throttles: boolean[] = [] + + const render = agentRendering(lifetime.signal, value => throttles.push(value), (ms, run) => { + expect(ms).toBe(30_000) + timers.add(run) + + return () => { timers.delete(run) } + }) + + const wait = render.hold() + render.hold()[Symbol.dispose]() + expect(timers.size).toBe(0) + wait[Symbol.dispose]() + expect(timers.size).toBe(1) + const followup = render.hold() + expect(timers.size).toBe(0) + followup[Symbol.dispose]() + timers.forEach(run => run()) + render.committed() + expect(throttles).toEqual([false, true]) + render.hold()[Symbol.dispose]() + expect(throttles).toEqual([false, true, false]) + lifetime.abort() + expect(timers.size).toBe(0) +}) diff --git a/packages/gui-plugins/src/browser/agent-rendering.ts b/packages/gui-plugins/src/browser/agent-rendering.ts new file mode 100644 index 00000000000..e813ca96fcb --- /dev/null +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -0,0 +1,40 @@ +// Long enough to cover thinking between a snapshot and its follow-up; a forgotten tab doesn't animate indefinitely. +const idleMs = 30_000 + +export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) => void, after = scheduleIdle) { + let holds = 0 + let awake = false + let cancel: (() => void) | undefined + signal.addEventListener("abort", () => cancel?.(), { once: true }) + + return { + hold() { + signal.throwIfAborted() + cancel?.() + + if (!awake) throttle(false) + awake = true + holds++ + + return { + [Symbol.dispose]() { + if (--holds || signal.aborted) return + cancel = after(idleMs, () => { + awake = false + throttle(true) + }) + }, + } + }, + // A cross-site commit can replace the renderer while a command or its grace period is active. + committed() { + if (awake && !signal.aborted) throttle(false) + }, + } +} + +function scheduleIdle(ms: number, run: () => void) { + const timer = setTimeout(run, ms) + + return () => clearTimeout(timer) +} diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index a7aa02e9ed9..4d451bc9882 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,6 +1,7 @@ import { homedir } from "node:os" import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" +import { agentRendering } from "./agent-rendering" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" import electron, { type BrowserWindow, type WebContents } from "electron" @@ -316,7 +317,8 @@ export function createBrowserPage( constructing.defer(() => pageLifetime.abort()) constructing.defer(() => { if (!contents.isDestroyed()) contents.close({ waitForBeforeUnload: false }) }) - if (agentDriven(options.activity)) contents.setBackgroundThrottling(false) + const rendering = agentRendering(pageLifetime.signal, enabled => contents.setBackgroundThrottling(enabled)) + const opening = agentDriven(options.activity) ? rendering.hold() : undefined constructing.defer(() => options.workspace?.dispose()) constructing.defer(() => options.artifacts?.dispose()) const preview = (url: string) => options.artifacts?.display(url) ?? options.workspace?.display(url) @@ -649,8 +651,6 @@ export function createBrowserPage( contents.on("did-navigate", (_event, url, status, statusText) => dispatch({ type: "navigation.committed", url: displayURL(url), status, statusText, title: pageTitle(displayURL(url)) }), ) - // Only agent-driven tabs need fresh frames while hidden. A cross-site commit can replace the renderer - // we woke on the first agent command, so wake its replacement too. contents.on("did-navigate", () => { const url = contents.getURL() @@ -658,7 +658,7 @@ export function createBrowserPage( notices.clear() popupReport = undefined - if (agentDriven(activity)) contents.setBackgroundThrottling(false) + rendering.committed() }) contents.on("did-fail-load", (_event, code, description, url, isMainFrame) => dispatch({ type: "navigation.failed", code, description: options.previewFailure?.(url) ?? (options.artifacts?.display(url) ? "browser.artifact.missing" : options.remote?.needsUpdate?.() && preview(url)?.startsWith("workspace:") ? "browser.preview.unsupported" : description), url, preview: preview(url), isMainFrame }), @@ -1060,7 +1060,7 @@ export function createBrowserPage( cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: RESTORE_PROMPT, runImmediately: true }), cdp.send("DOM.enable"), attachFrames(), - ])).then(() => undefined) + ])).then(() => undefined).finally(() => opening?.[Symbol.dispose]()) constructing.move() @@ -1147,6 +1147,9 @@ export function createBrowserPage( * would run with that extension's privileges; every agent operation reaches the page through here. */ async execute(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user"): Promise<Browser.Result> { + using active = new DisposableStack() + + if (origin === "agent") active.use(rendering.hold()) const saved = navigation.interrupt(command.action.type, documentState.status === "restoring" ? documentState.url : undefined) await ready const open = origin === "user" && leavable.includes(command.action.type) ? selectOpenDialog(dialogGate) : undefined @@ -1169,10 +1172,7 @@ export function createBrowserPage( if (origin === "user") activity.userInputAt = Date.now() - if (origin === "agent") { - if (!agentDriven(activity)) contents.setBackgroundThrottling(false) - activity.agentRuns++ - } + if (origin === "agent") activity.agentRuns++ // The user's navigation may stop for "Leave site?"; the agent's stops when the site asks the user to sign in. if (origin === "user" && leavable.includes(command.action.type)) prompts.intend(command.action) diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 40c2d8c6fe4..131a34a7ad0 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -872,7 +872,6 @@ export function createBrowserPane(input: { handle?.activity.set(id, activity) if (changed && current?.previewUsed()) dispatchBinding(binding, {type:"tab.restricted", tabID:id, url:current.state().url}) - else if (changed && current) current.contents.setBackgroundThrottling(false) return load(binding, id, identity) } From 3cbfdd88d409de209632fcceec8f90f8b20ea1fc Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:29:47 +1000 Subject: [PATCH 12/44] feat(browser): accept recorded tool aliases and response-only bodies --- .../gui-plugins/src/browser/diagnostics.ts | 2 +- packages/plugin-browser/src/rpc.ts | 17 +++++++++---- packages/plugin-browser/src/tools.ts | 24 +++++++++++++++++++ packages/plugin-browser/test/tools.test.ts | 19 ++++++++++++++- 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/packages/gui-plugins/src/browser/diagnostics.ts b/packages/gui-plugins/src/browser/diagnostics.ts index 91c8cd63fa4..9ff1fc024ed 100644 --- a/packages/gui-plugins/src/browser/diagnostics.ts +++ b/packages/gui-plugins/src/browser/diagnostics.ts @@ -284,7 +284,7 @@ export function createDiagnostics(cdp: Cdp, displayURL: (url: string) => string, return value.length ? { state: "text", text: value.slice(0, max), truncated: value.length > max } : { state: "empty" } } - const known = responseBody(hop, input.includeBody) + const known = responseBody(hop, input.includeResponseBody ?? input.includeBody) return { request: networkRequest(hop), diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index d110f7622b8..02903483e47 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -187,6 +187,12 @@ export const ConsoleEntry = Schema.Struct({ }).annotate({ identifier: "Browser.ConsoleEntry" }) export interface ConsoleEntry extends Schema.Schema.Type<typeof ConsoleEntry> {} const snapshot = Schema.Struct({ ...page, content: text, truncated: Schema.Boolean }) +const fillText = Schema.String.check(Schema.isMaxLength(10_000)) +const bodyOptions = { + includeBody: optional(Schema.Boolean), + includeResponseBody: optional(Schema.Boolean), + maxBodyChars: optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20_000 }))), +} const entry = Schema.Struct({ name: short, count, bytes: Schema.Finite }) const node = Schema.Struct({ id: Schema.Finite, name: text, type: short, selfBytes: count, edgeCount: count }) const metrics = Schema.Array(Schema.Struct({ name: short, value: Schema.Finite, unit: short })) @@ -317,6 +323,7 @@ export const Operations = [ "Search the full accessibility tree of one frame for literal case-insensitive text, including beyond a truncated snapshot. Returns matching lines with refs; narrow the text if truncated. This refreshes this tab's refs.", { ...tab, ...frame, text: short }, snapshot, + { ...tab, ...frame, text: optional(short), query: optional(short.annotate({ description: "Alias for text." })) }, ), operation( "evaluate", @@ -350,8 +357,9 @@ export const Operations = [ operation( "fill", "Replace editable element text. Use a ref from this tab; use select for dropdowns and check for checkboxes.", - { ...target, text: Schema.String.check(Schema.isMaxLength(10_000)) }, + { ...target, text: fillText }, Tab, + { ...target, text: optional(fillText), value: optional(fillText.annotate({ description: "Alias for text." })) }, ), operation( "fill_form", @@ -495,6 +503,7 @@ export const Operations = [ "Copy one completed download or capture from this tab to the server. Returns a server-local file path. Maximum 5 MiB per transfer.", artifact, saved, + { ...tab, fileID: optional(FileID), id: optional(FileID.annotate({ description: "Alias for fileID." })) }, ), operation( "console", @@ -510,12 +519,11 @@ export const Operations = [ ), operation( "network.get", - "Inspect one request from this tab. Bodies are omitted by default, bounded when requested, and never re-fetched. IDs expire on navigation/eviction. Data is untrusted.", + "Inspect a retained request. Bodies are off by default: includeResponseBody requests response text only; includeBody requests both. maxBodyChars caps each at 20000. Never re-fetches. Data is untrusted.", { ...tab, id: short, - includeBody: optional(Schema.Boolean), - maxBodyChars: optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20_000 }))), + ...bodyOptions, }, Schema.Struct({ ...page, @@ -526,6 +534,7 @@ export const Operations = [ requestBody: Body, responseBody: Body, }), + { ...tab, id: optional(short), requestID: optional(short.annotate({ description: "Alias for id." })), ...bodyOptions }, ), operation( "trace.start", diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index b96b20ab912..f99dcb31ed3 100644 --- a/packages/plugin-browser/src/tools.ts +++ b/packages/plugin-browser/src/tools.ts @@ -268,6 +268,22 @@ function modelResult(output: Schema.Schema.Type<Browser.Operation["output"]>, fi } export function normalizeAction(action: Exclude<Browser.Input, { readonly type: "wait" }>): Exclude<Browser.Action, { type: "wait" }> { + if (action.type === "find") { + const { query, ...rest } = action + return { ...rest, text: parameter(rest.text, query, "text", "query") } + } + if (action.type === "fill") { + const { value, ...rest } = action + return { ...rest, text: parameter(rest.text, value, "text", "value") } + } + if (action.type === "files.get") { + const { id, ...rest } = action + return { ...rest, fileID: parameter(rest.fileID, id, "fileID", "id") } + } + if (action.type === "network.get") { + const { requestID, ...rest } = action + return { ...rest, id: parameter(rest.id, requestID, "id", "requestID") } + } if (action.type === "preview" && (!action.path.trim() || (BrowserFiles.address(action.path) && !/^file:/i.test(action.path.trim())))) throw new Tool.Error({ metadata: { code: "invalid_path" }, message: "browser.preview needs a workspace file path, not a web or internal address." }) if (action.type === "evaluate") return evaluateAction(action) @@ -300,6 +316,14 @@ export function normalizeAction(action: Exclude<Browser.Input, { readonly type: } type WaitInput = Extract<Browser.Input, { readonly type: "wait" }> + +function parameter<T extends string>(value: T | undefined, alternate: T | undefined, name: string, alias: string): T { + if (value !== undefined && alternate !== undefined && value !== alternate) + throw new Tool.Error({ message: `Conflicting ${name} and ${alias}. Pass only ${name}.` }) + const result = value ?? alternate + if (result === undefined) throw new Tool.Error({ message: `Missing ${name}. Pass ${name} or its alias ${alias}.` }) + return result +} type WaitAction = Extract<Browser.Action, { readonly type: "wait" }> export type WaitPlan = { readonly timeoutMs: number; readonly waited: Browser.Waited["waited"] } & ( diff --git a/packages/plugin-browser/test/tools.test.ts b/packages/plugin-browser/test/tools.test.ts index 106e6499824..1decb8e75bc 100644 --- a/packages/plugin-browser/test/tools.test.ts +++ b/packages/plugin-browser/test/tools.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os" import { basename, dirname, join } from "node:path" import { pathToFileURL } from "node:url" import { runInNewContext } from "node:vm" -import { Effect } from "effect" +import { Effect, Schema } from "effect" import { Browser } from "../src/rpc.js" import { BrowserFiles } from "../src/files.js" import { BrowserSkill } from "../src/skill.js" @@ -13,6 +13,23 @@ import { BrowserTools } from "../src/tools.js" const tabID = Browser.TabID.make(`tab_${crypto.randomUUID()}`) const navigate = (url: string) => BrowserTools.normalizeAction({ type: "navigate", tabID, url }) +test("model-written aliases decode to canonical desktop actions; conflicting choices fail before dispatch", () => { + const ref = Browser.Ref.make("e4") + const fileID = Browser.FileID.make(`file_${crypto.randomUUID()}`) + const parse = (input: Exclude<Browser.Input, { type: "wait" }>) => { + const { type, ...fields } = input + const operation = Browser.Operations.find(op => op.name === type)! + Schema.decodeUnknownSync(operation.input)(fields) + return BrowserTools.normalizeAction(input) + } + expect(parse({ type: "find", tabID, query: "Save" })).toEqual({ type: "find", tabID, text: "Save" }) + expect(parse({ type: "fill", tabID, ref, value: "" })).toEqual({ type: "fill", tabID, ref, text: "" }) + expect(parse({ type: "files.get", tabID, id: fileID })).toEqual({ type: "files.get", tabID, fileID }) + expect(parse({ type: "network.get", tabID, requestID: "r1", includeResponseBody: true })).toEqual({ type: "network.get", tabID, id: "r1", includeResponseBody: true }) + expect(() => parse({ type: "fill", tabID, ref, text: "keep", value: "replace" })).toThrow("Conflicting") + expect(() => parse({ type: "find", tabID })).toThrow("Missing text") +}) + test("built-in browser skill uses a virtual skill:// URI", () => { expect(String(BrowserSkill.info.path)).toBe("skill://browser/SKILL.md") }) From 0bb06881e5bc0adfea9776d3cd0cde8eee427622 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:31:57 +1000 Subject: [PATCH 13/44] feat(browser): show interactive controls with bounded snapshot lines --- packages/gui-plugins/src/browser/chromium.ts | 2 + .../gui-plugins/src/browser/snapshot.test.ts | 14 +++++++ packages/gui-plugins/src/browser/snapshot.ts | 38 +++++++++++++++---- packages/plugin-browser/src/rpc.ts | 13 +++++-- 4 files changed, 55 insertions(+), 12 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 4d451bc9882..3c264f1aae3 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -2275,6 +2275,8 @@ export function createBrowserPage( root: selected?.backendID, depth: action.type === "snapshot" ? action.depth : undefined, text: action.type === "find" ? action.text : undefined, + interactive: action.interactive, + maxLines: action.maxLines, previous: byNode(refs), picked: byNode(picked), ref: options.shared.ref, diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts index 38cfa18c7f9..e3e7174da32 100644 --- a/packages/gui-plugins/src/browser/snapshot.test.ts +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -19,6 +19,20 @@ function options() { return { previous: new Map<number, string>(), picked: new Map<number, string>(), ref: () => `e${++id}` } } +test("interactive find keeps controls and their context, not static text or picked decoration", async () => { + const tree = [node(1, "navigation", "Projects", 2, 3, 9), node(2, "StaticText", "intro".repeat(100)), node(3, "row", "", 4, 5), node(4, "cell", "Atlas"), node(5, "button", "Edit"), node(9, "link", "Next")] + const setup = options() + setup.picked.set(2, "e42") + const all = await accessibilitySnapshot(tree, { ...setup, interactive: true, maxLines: 1 }) + expect(all.content).toBe('@e1 [button] "Edit" in navigation "Projects" / row "Atlas"') + expect(all.truncated).toBe(true) + expect([...all.refs.keys()]).toEqual(["e1"]) + const found = await accessibilitySnapshot(tree, { ...setup, interactive: true, text: "NEXT", maxLines: 1 }) + expect(found.content).toBe('@e2 [link] "Next" in navigation "Projects"') + expect(found.truncated).toBe(false) + expect((await accessibilitySnapshot(tree, { ...setup, maxLines: 2 })).content.split("\n")).toHaveLength(2) +}) + test("empty wrappers cost neither depth nor indentation; named groups and picked elements survive", async () => { const wrappers = Array.from({ length: 80 }, (_, i) => node(i + 1, "generic", "", i + 2)) const tree = [...wrappers, node(81, "group", "Toolbar", 82), node(82, "button", "Save")] diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index 33d806deba6..0d2aacd3798 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -8,6 +8,8 @@ export async function accessibilitySnapshot( root?: number depth?: number text?: string + interactive?: boolean + maxLines?: number previous: ReadonlyMap<number, string> picked: ReadonlyMap<number, string> ref: () => string @@ -20,7 +22,8 @@ export async function accessibilitySnapshot( throw new Error("Element is absent from this frame's accessibility snapshot. Refresh the snapshot without ref.") const index = new Map(nodes.map((node) => [node.nodeId, node])) - const pending = [{ node: root, level: 0 }] + const pending = [{ node: root, level: 0, scope: "", item: "", ordinal: 1, parent: "" }] + const headings = new Map<string, string>() const seen = new Set<string>() const refs = new Map<string, number>() const lines: string[] = [] @@ -29,7 +32,8 @@ export async function accessibilitySnapshot( let truncated = false while (pending.length) { - const { node, level } = pending.pop()! + const current = pending.pop()! + const { node, level } = current if (seen.has(node.nodeId)) continue seen.add(node.nodeId) @@ -47,7 +51,7 @@ export async function accessibilitySnapshot( const actionable = role !== "RootWebArea" && (props.get("focusable") || - /^(button|link|textbox|combobox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem)$/.test( + editable || /^(button|link|textbox|searchbox|combobox|listbox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem|scrollbar)$/.test( role, )) @@ -65,18 +69,28 @@ export async function accessibilitySnapshot( children.length === 1 const visible = !node.ignored && !wrapper && role !== "InlineTextBox" + const lean = options.interactive === true + const contextual = lean && visible + const landmark = contextual && name && /^(banner|navigation|main|region|form|search|complementary|dialog|table|grid|list|group|heading)$/.test(role) + const inherited = headings.get(current.parent) ?? current.scope + const scope = landmark ? `${role} ${brief(name)}` : inherited + if (contextual && role === "heading" && name) headings.set(current.parent, scope) + const itemName = contextual && role === "row" && !name ? String(index.get(children[0])?.name?.value ?? "").replace(/\s+/g, " ") : name + const item = contextual && (role === "row" || role === "listitem") + ? `${role} ${itemName ? brief(itemName) : current.ordinal}` : current.item if (visible && level > (options.depth ?? Infinity)) { truncated = true continue } - if (visible) { - const flags = (["checked", "disabled", "expanded", "selected"] as const).flatMap((key) => + if (visible && (!lean || (actionable && id))) { + const flags = (["checked", "disabled", "expanded", "selected", "pressed"] as const).flatMap((key) => props.has(key) ? [`${key}=${props.get(key)}`] : [], ) - const label = `[${role}] ${JSON.stringify(name.length > 300 ? `${name.slice(0, 299)}…` : name)}${flags.length ? ` ${flags.join(" ")}` : ""}` + const context = lean ? [inherited, current.item].filter(Boolean).join(" / ") : "" + const label = `[${role}] ${lean ? brief(name) : JSON.stringify(name.length > 300 ? `${name.slice(0, 299)}…` : name)}${flags.length ? ` ${flags.join(" ")}` : ""}${context ? ` in ${context}` : ""}` const known = picked || (id && options.previous.get(id)) if ( @@ -85,9 +99,13 @@ export async function accessibilitySnapshot( name.toLowerCase().includes(query) || (known && `@${known}`.includes(query)) ) { + if (lines.length >= (options.maxLines ?? Infinity)) { + truncated = true + break + } const ref = id && (picked || actionable) ? known || options.ref() : undefined const box = ref && id && options.box ? await options.box(id) : "" - const line = `${" ".repeat(Math.min(level, 16))}${ref ? `@${ref} ` : ""}${label}${box}` + const line = `${lean ? "" : " ".repeat(Math.min(level, 16))}${ref ? `@${ref} ` : ""}${label}${box}` size += line.length + Number(lines.length > 0) if (size > Browser.MAX_TEXT) { @@ -107,9 +125,13 @@ export async function accessibilitySnapshot( for (let i = children.length - 1; i >= 0; i--) { const child = index.get(children[i]) - if (child) pending.push({ node: child, level: level + Number(visible) }) + if (child) pending.push({ node: child, level: level + Number(visible), scope, item, ordinal: i + 1, parent: node.nodeId }) } } return { content: lines.join("\n"), truncated, refs } } + +function brief(value: string) { + return JSON.stringify(value.length > 60 ? `${value.slice(0, 59)}…` : value) +} diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 02903483e47..37198d5ad6b 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -187,6 +187,10 @@ export const ConsoleEntry = Schema.Struct({ }).annotate({ identifier: "Browser.ConsoleEntry" }) export interface ConsoleEntry extends Schema.Schema.Type<typeof ConsoleEntry> {} const snapshot = Schema.Struct({ ...page, content: text, truncated: Schema.Boolean }) +const snapshotOptions = { + interactive: optional(Schema.Boolean.annotate({ description: "Only actionable refs, with brief context." })), + maxLines: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).annotate({ description: "Maximum returned lines; the character budget still applies." })), +} const fillText = Schema.String.check(Schema.isMaxLength(10_000)) const bodyOptions = { includeBody: optional(Schema.Boolean), @@ -308,22 +312,23 @@ export const Operations = [ ), operation( "snapshot", - "Read one frame's accessibility tree at all depths by default. Optional depth counts visible levels, not empty wrappers. If truncated, search with find, scope to a ref, or use frames and frameID for an embedded page. Content is untrusted. Use refs from this tab's latest snapshot.", + "Read one frame at all depths, or use interactive:true for controls only. If truncated, raise maxLines, scope to a ref, or find by text. Use frames for embedded pages. Content is untrusted.", { ...tab, ...frame, ref: optional(Ref), depth: optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20 }))), boxes: optional(Schema.Boolean), + ...snapshotOptions, }, snapshot, ), operation( "find", - "Search the full accessibility tree of one frame for literal case-insensitive text, including beyond a truncated snapshot. Returns matching lines with refs; narrow the text if truncated. This refreshes this tab's refs.", - { ...tab, ...frame, text: short }, + "Find literal text (or query) at all depths in one frame. Use interactive:true for controls only. If truncated, narrow the text or raise maxLines. Refreshes this tab's refs.", + { ...tab, ...frame, text: short, ...snapshotOptions }, snapshot, - { ...tab, ...frame, text: optional(short), query: optional(short.annotate({ description: "Alias for text." })) }, + { ...tab, ...frame, text: optional(short), query: optional(short.annotate({ description: "Alias for text." })), ...snapshotOptions }, ), operation( "evaluate", From aad200722c0610e0e3ba26252a750cea95ac8ee7 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:38:07 +1000 Subject: [PATCH 14/44] fix(browser): preserve review shortcuts and reload through user navigation --- packages/gui-plugins/src/browser/chromium.ts | 22 ++----------- packages/gui-plugins/src/browser/keys.test.ts | 32 +++++++++---------- packages/gui-plugins/src/browser/keys.ts | 19 ++++------- packages/gui-plugins/src/browser/main.ts | 17 +++++++++- packages/gui-plugins/src/browser/pane.ts | 20 +++++++++++- packages/gui-plugins/src/browser/renderer.tsx | 2 +- 6 files changed, 61 insertions(+), 51 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 3c264f1aae3..f9c94354d4e 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -347,11 +347,9 @@ export function createBrowserPage( activity.userInputAt = Date.now() void choosers.update().catch(() => undefined) - const refresh = pageReload(input, process.platform === "darwin") - - if (refresh) { + if (pageReload(input, process.platform === "darwin")) { event.preventDefault() - void reload(options.signal, refresh === "hard").catch((error: Error) => publish(error.message)) + void options.menu.navigate("reload").catch((error: Error) => publish(error.message)) return } @@ -1029,8 +1027,6 @@ export function createBrowserPage( const reload = async (signal = options.signal, ignoreCache = false) => { const tab = state() - if (navigation.interrupt("reload", documentState.status === "restoring" ? documentState.url : undefined)) return - if (tab.loadError && /^(?:file|workspace|artifact):/.test(tab.url)) return void await load(tab.url, true, signal) const actual = contents.getURL() @@ -1114,24 +1110,12 @@ export function createBrowserPage( await contents.session.clearAuthCache() if (closed()) return - await reload() + await options.menu.navigate("reload") // A slow page still cleared; the count then reads what it set so far. await waitFor(() => closed() || !contents.isLoading(), new AbortController().signal, 30_000).catch( () => undefined, ) }, - async clearCache(address: string) { - const origin = destinationOrigin(address) - - if (closed() || !origin || destinationOrigin(contents.getURL()) !== origin) throw new Error("browser.site.changed") - // Session.clearCache() clears the entire partition; clearData can filter the HTTP cache by origin. - await contents.session.clearData({ - origins: [origin], originMatchingMode: "origin-in-all-contexts", dataTypes: ["cache", "serviceWorkers"], - }) - await contents.session.clearStorageData({ origin, storages: ["cachestorage"] }) - - if (!closed() && destinationOrigin(contents.getURL()) === origin) await reload(options.signal, true) - }, /** Reports the page's icon and zoom when either changed since the last report. */ detail, /** Takes a download this page started; see `guardSession`. */ diff --git a/packages/gui-plugins/src/browser/keys.test.ts b/packages/gui-plugins/src/browser/keys.test.ts index de48571d5f8..56b0e65ee14 100644 --- a/packages/gui-plugins/src/browser/keys.test.ts +++ b/packages/gui-plugins/src/browser/keys.test.ts @@ -74,8 +74,8 @@ test("forwards browser and shell shortcuts while leaving page editing, reload an ["mod", ",", true, ","], ["mod", "\\", false, "\\"], ["mod+shift", "T", true, "t"], - ["mod+shift", "R", true, undefined], - ["mod+shift", "R", false, undefined], + ["mod+shift", "R", true, "r"], + ["mod+shift", "R", false, "r"], ["mod", "F5", false, "F5"], ["mod+alt", "r", true, "r"], ["mod+shift", "P", true, "p"], ["mod+shift", "L", true, "l"], ["mod+shift", "E", true, "e"], @@ -153,21 +153,21 @@ test("forwards browser and shell shortcuts while leaving page editing, reload an test("reloads the focused page on F5 and the platform's reload chord, leaving other R chords to the window", () => { const cases: [modifiers: string, key: string, mac: boolean, reloads: ReturnType<typeof pageReload>, code?: string][] = [ - ["", "F5", true, "normal"], - ["", "F5", false, "normal"], - ["mod", "r", true, "normal"], - ["mod", "r", false, "normal"], + ["", "F5", true, true], + ["", "F5", false, true], + ["mod", "r", true, true], + ["mod", "r", false, true], // Dvorak: R is on the physical O key; the character decides. - ["mod", "r", true, "normal", "KeyO"], - ["mod", "\u043a", true, "normal", "KeyR"], - ["mod+shift", "R", true, "hard"], - ["mod+shift", "R", false, "hard"], - ["mod", "F5", false, "hard"], - ["mod+alt", "r", true, undefined], - ["ctrl", "r", true, undefined], - ["mod", "F5", true, undefined], - ["ctrl", "F5", true, undefined], - ["", "r", true, undefined], + ["mod", "r", true, true, "KeyO"], + ["mod", "\u043a", true, true, "KeyR"], + ["mod+shift", "R", true, false], + ["mod+shift", "R", false, false], + ["mod", "F5", false, false], + ["mod+alt", "r", true, false], + ["ctrl", "r", true, false], + ["mod", "F5", true, false], + ["ctrl", "F5", true, false], + ["", "r", true, false], ] const results = cases.map(([modifiers, key, mac, , code]) => [ diff --git a/packages/gui-plugins/src/browser/keys.ts b/packages/gui-plugins/src/browser/keys.ts index 089f43c72a8..cb3790775ef 100644 --- a/packages/gui-plugins/src/browser/keys.ts +++ b/packages/gui-plugins/src/browser/keys.ts @@ -35,7 +35,7 @@ const shellKeys = ["t", "w", "l", "f", "g", "n", "1", "2", "3", "4", "5", "6", " // Shifted chords with the platform's modifier that belong to the app shell rather than the page: reopening a tab, // switching side-panel tabs, toggling the side panel, opening the command palette, or running session commands. New Window and Close Window // (⇧⌘N, ⇧⌘W) stay unclaimed: only their menu accelerators handle them, and claiming a chord also blocks the menu. -const shellShiftKeys = ["t", "[", "]", "g", "p", "l", "e", "o", "s"] +const shellShiftKeys = ["t", "[", "]", "r", "g", "p", "l", "e", "o", "s"] // The side panel's launchers: Review, Browser and Open file, with ⌃⌘ on macOS and Ctrl+Alt elsewhere. Only a typed // Latin letter counts, so AltGr (Ctrl+Alt) typing on other layouts stays with the page. @@ -64,20 +64,11 @@ export function pageLetter(input: Pick<Electron.Input, "key" | "code">) { * reloads itself; left to the window, the Reload menu item would reload the whole app. */ export function pageReload(input: PageKey, mac: boolean) { - if (input.alt) return + if (input.alt || input.shift) return false - if (input.key === "F5") { - if (input.meta || input.shift) return + if (input.key === "F5") return !input.meta && !input.control - if (!input.control) return "normal" - - if (!mac) return "hard" - - return - } - - if ((mac ? input.meta && !input.control : input.control && !input.meta) && pageLetter(input) === "r") - return input.shift ? "hard" : "normal" + return (mac ? input.meta && !input.control : input.control && !input.meta) && pageLetter(input) === "r" } /** @@ -91,6 +82,8 @@ export function pageShortcut(input: PageKey, mac: boolean): PageShortcut | undef const launcher = mac ? input.meta && input.control && !input.alt : input.control && input.alt && !input.meta const matched = + (!mac && mod && !input.alt && !input.shift && key === "f5") || + (mac && mod && input.alt && !input.shift && key === "r") || (!mac && key === "f3" && !input.control && !input.meta && !input.alt) || (input.control && !input.meta && !input.alt && (key === "tab" || (key === "`" && !input.shift))) || (launcher && !input.shift && launcherKeys.includes(input.key.toLowerCase())) || diff --git a/packages/gui-plugins/src/browser/main.ts b/packages/gui-plugins/src/browser/main.ts index b998d119aa6..63a187412c4 100644 --- a/packages/gui-plugins/src/browser/main.ts +++ b/packages/gui-plugins/src/browser/main.ts @@ -1,5 +1,5 @@ import { builtinMainContext } from "@opencode/plugin/gui/builtin" -import type { Plugin } from "@opencode/plugin/gui/main" +import { MenubarItem, type Plugin } from "@opencode/plugin/gui/main" import type { Pane } from "./pane" import type { Profile } from "./profile" import { RefsStore } from "./refs" @@ -132,6 +132,21 @@ const setup: Plugin.MainSetup = (ctx) => { return pane() } + if (process.platform === "darwin") { + const reload = (window?: number) => { + const current = selectPane(paneState) + + return current.kind === "ready" ? current.pane.menuReload(window) : undefined + } + + ctx.add(MenubarItem, { + menu: "view", id: "hardReload", after: "view.reload", + get label() { return ctx.t("menu.hardReload") }, + enabled: () => !!reload(ctx.windows.focused()?.id), + run: window => { void reload(window?.id)?.().catch((error: Error) => ctx.log.write("warn", error.message)) }, + }) + } + const provider = ctx.provide(BrowserPane, { register: async (input, caller) => (await load()).register(caller.window, input.binding, input), load: async (input, caller) => (await pane()).load(caller.window, input.binding, input.tabID), diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 131a34a7ad0..3abb6a9b2ec 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -123,6 +123,15 @@ export function createBrowserPane(input: { const warned = new Set<string>() return { + menuReload(window: number | undefined) { + for (const [binding, handle] of handles) { + if (handle.window !== window) continue + const tab = inventory(binding).focusedTabID + + if (tab && page(binding, tab)?.view.getVisible()) + return () => execute(binding, { action: { type: "reload", tabID: tab, ignoreCache: true }, files: [] }, handle.abort.signal, "user") + } + }, async register(window: number, binding: string, target: Target) { const server = input.serverEndpoints.get(target.server) @@ -412,7 +421,16 @@ export function createBrowserPane(input: { }, async clearCache(window: number, binding: string, tabID: Browser.TabID, address: string) { owned(window, binding) - await page(binding, tabID)?.clearCache(address) + const handle = handles.get(binding) + const origin = destinationOrigin(address) + const current = () => page(binding, tabID)?.contents.getURL() ?? selectTabSlot(machine.state, binding, tabID)?.tab.url + + if (!handle || !origin || destinationOrigin(current() ?? "") !== origin) throw new Error("browser.site.changed") + const session = electron.session.fromPartition(handle.partition) + await session.clearData({ origins: [origin], originMatchingMode: "origin-in-all-contexts", dataTypes: ["cache", "serviceWorkers"] }) + + if (handle.abort.signal.aborted || destinationOrigin(current() ?? "") !== origin) return + await execute(binding, { action: { type: "reload", tabID, ignoreCache: true }, files: [] }, handle.abort.signal, "user") }, async clearSite(window: number, binding: string, tabID: Browser.TabID) { owned(window, binding) diff --git a/packages/gui-plugins/src/browser/renderer.tsx b/packages/gui-plugins/src/browser/renderer.tsx index 87ec7f0b6ec..f840a783d31 100644 --- a/packages/gui-plugins/src/browser/renderer.tsx +++ b/packages/gui-plugins/src/browser/renderer.tsx @@ -189,7 +189,7 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => { return { id: "hardReload", title: ctx.t("menu.hardReload"), group: ctx.t("command.category.view"), - bind: mac ? "mod+shift+r" : "mod+shift+r,ctrl+f5", scope: "#browser-panel", editable: true, + bind: mac ? "mod+alt+r" : "ctrl+f5", scope: "#browser-panel", editable: true, enabled: pane.visible() && !!pane.address(), run: () => pane.reload(true), } }) From bbb8ac1e8da429c8a1ecdea8cdf8ad9222a5e275 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:50:42 +1000 Subject: [PATCH 15/44] fix(browser): budget snapshots by landmark and preserve document refs --- packages/gui-plugins/src/browser/chromium.ts | 18 +- packages/gui-plugins/src/browser/refs.ts | 26 ++ .../gui-plugins/src/browser/snapshot.test.ts | 94 ++++- packages/gui-plugins/src/browser/snapshot.ts | 345 +++++++++++++----- packages/plugin-browser/src/rpc.ts | 3 +- packages/plugin-browser/src/skill.ts | 2 +- 6 files changed, 388 insertions(+), 100 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index f9c94354d4e..83a5914b889 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,6 +1,7 @@ import { homedir } from "node:os" import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" +import { documentRefs } from "./refs" import { agentRendering } from "./agent-rendering" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" @@ -433,7 +434,7 @@ export function createBrowserPage( Array.from(contexts.values()).some((context) => context.id === id && context.sessionID === sessionID)) const profiling = createProfiling(contents, cdp, files, sourceURLs, options.shared) - const refs = new Map<string, Element>() + const refs = documentRefs() // Elements the user picked. Their refs outlive later snapshots, so a comment keeps pointing at // the element until the document changes. const picked = new Map<string, Element>() @@ -1760,7 +1761,7 @@ export function createBrowserPage( if (!value) throw new CodedError( Browser.FailureCode.staleRef, - "Element ref is stale or belongs to another tab. Call browser.snapshot({tabID}) and use a ref from that tab's newest snapshot. Do not reuse refs after navigation or a newer snapshot.", + "Element ref is stale or belongs to another tab. Call browser.snapshot({tabID}) and use a ref from the current document.", ) return value @@ -1864,7 +1865,7 @@ export function createBrowserPage( return object.object.objectId } - async function rect(element: Element, scroll = false) { + async function rect(element: Element, scroll = false, knownTree?: Awaited<ReturnType<typeof frames>>) { if (scroll) { await cdp.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: element.backendID }, element.sessionID) // Input is routed by the last rendered frame, so let one render at the new scroll position. @@ -1882,7 +1883,7 @@ export function createBrowserPage( ), } - const tree = await frames() + const tree = knownTree ?? await frames() let frame = tree.find((frame) => frame.id === element.frameID) while (frame?.parentID) { @@ -2261,12 +2262,14 @@ export function createBrowserPage( text: action.type === "find" ? action.text : undefined, interactive: action.interactive, maxLines: action.maxLines, - previous: byNode(refs), + maxChars: action.maxChars, + signal, + previous: refs.previous(frameID, sessionID), picked: byNode(picked), ref: options.shared.ref, box: action.type === "snapshot" && action.boxes ? async (backendID) => { abortError(signal) - const box = await rect({ backendID, frameID, sessionID }).catch(() => undefined) + const box = await rect({ backendID, frameID, sessionID }, false, tree).catch(() => undefined) return box ? ` box=${JSON.stringify(box)}` : "" } : undefined, @@ -2275,8 +2278,7 @@ export function createBrowserPage( abortError(signal) if (documentGeneration(documentState) !== generation) throw new CodedError(Browser.FailureCode.documentChanged, "Document changed during snapshot; request a fresh snapshot.") - refs.clear() - snapshot.refs.forEach((backendID, ref) => refs.set(ref, { backendID, frameID, sessionID })) + refs.add(frameID, sessionID, snapshot.refs) return { content: snapshot.content, truncated: snapshot.truncated } } diff --git a/packages/gui-plugins/src/browser/refs.ts b/packages/gui-plugins/src/browser/refs.ts index 066d1b67e13..752542b42e3 100644 --- a/packages/gui-plugins/src/browser/refs.ts +++ b/packages/gui-plugins/src/browser/refs.ts @@ -4,6 +4,32 @@ import type { Persisted } from "@opencode/plugin/gui/main" /** Main storage's `refs` store: the end of the last block of refs main reserved, so refs stay unique across reloads. */ export const RefsStore = { schema: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), initial: 0 } +/** Scoped reads add to this document's refs; a navigation discards both directions together. */ +export function documentRefs() { + const elements = new Map<string, { backendID: number; frameID: string; sessionID?: string }>() + const frames = new Map<string, Map<number, string>>() + const frame = (frameID: string, sessionID?: string) => `${sessionID ?? ""}:${frameID}` + + return { + get: (ref: string) => elements.get(ref), + previous: (frameID: string, sessionID?: string) => + frames.get(frame(frameID, sessionID)) ?? new Map<number, string>(), + add(frameID: string, sessionID: string | undefined, refs: ReadonlyMap<string, number>) { + const key = frame(frameID, sessionID) + const previous = frames.get(key) ?? new Map<number, string>() + frames.set(key, previous) + refs.forEach((backendID, ref) => { + elements.set(ref, { frameID, sessionID, backendID }) + previous.set(backendID, ref) + }) + }, + clear() { + elements.clear() + frames.clear() + }, + } +} + // Reserving in blocks keeps storage writes rare while refs stay short. const block = 10_000 diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts index e3e7174da32..58cdd42a0e1 100644 --- a/packages/gui-plugins/src/browser/snapshot.test.ts +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -1,6 +1,7 @@ import { expect, test } from "bun:test" import type { Protocol } from "devtools-protocol" import { accessibilitySnapshot } from "./snapshot" +import { documentRefs } from "./refs" function node(id: number, role: string, name: string, ...children: number[]): Protocol.Accessibility.AXNode { return { @@ -20,15 +21,25 @@ function options() { } test("interactive find keeps controls and their context, not static text or picked decoration", async () => { - const tree = [node(1, "navigation", "Projects", 2, 3, 9), node(2, "StaticText", "intro".repeat(100)), node(3, "row", "", 4, 5), node(4, "cell", "Atlas"), node(5, "button", "Edit"), node(9, "link", "Next")] + const tree = [ + node(1, "navigation", "Projects", 2, 3, 9), + node(2, "StaticText", "intro".repeat(100)), + node(3, "row", "", 4, 5), + node(4, "cell", "Atlas"), + node(5, "button", "Edit"), + node(9, "link", "Next"), + ] + const setup = options() setup.picked.set(2, "e42") const all = await accessibilitySnapshot(tree, { ...setup, interactive: true, maxLines: 1 }) - expect(all.content).toBe('@e1 [button] "Edit" in navigation "Projects" / row "Atlas"') + expect(all.content).toStartWith('@e1 [button] "Edit" in navigation "Projects" / row "Atlas"') + expect(all.content).toContain("1 interactive") + expect(all.content).not.toContain("intro") expect(all.truncated).toBe(true) - expect([...all.refs.keys()]).toEqual(["e1"]) + expect(all.refs.get("e2")).toBe(1) const found = await accessibilitySnapshot(tree, { ...setup, interactive: true, text: "NEXT", maxLines: 1 }) - expect(found.content).toBe('@e2 [link] "Next" in navigation "Projects"') + expect(found.content).toBe('@e3 [link] "Next" in navigation "Projects"') expect(found.truncated).toBe(false) expect((await accessibilitySnapshot(tree, { ...setup, maxLines: 2 })).content.split("\n")).toHaveLength(2) }) @@ -53,10 +64,81 @@ test("budgets whole lines, not traversal: find reaches the last item of a trunca const setup = options() const page = await accessibilitySnapshot(tree, setup) expect(page.truncated).toBe(true) - expect(page.content.length).toBeLessThanOrEqual(100_000) - expect(page.content).toEndWith('"') + expect(page.content.length).toBeLessThanOrEqual(20_000) + expect(page.content).toEndWith("maxChars/maxLines.") expect(page.content).not.toContain(' 1999"') const match = await accessibilitySnapshot(tree, { ...setup, text: " 1999" }) expect(match.truncated).toBe(false) expect([...match.refs.values()]).toEqual([2000]) }) + +test("orders landmarks across empty branching wrappers, follows aria-owns cycles once, and never enters an editor", async () => { + const tree = [ + node(1, "generic", "", 2, 3, 4), + node(2, "navigation", "Menu", 5), + node(3, "main", "Body", 1, 6), + node(4, "dialog", "Confirm"), + node(5, "textbox", "Password", 7), + node(6, "StaticText", "Body"), + node(7, "StaticText", "secret"), + ] + + const result = await accessibilitySnapshot(tree, options()) + expect(result.content.split("\n").map((s) => s.trim().split(" ")[1])).toEqual([ + "[dialog]", + "[main]", + "[navigation]", + "[textbox]", + ]) + expect(result.content).not.toContain("secret") + expect((await accessibilitySnapshot(tree, { ...options(), text: "secret" })).content).toBe("") +}) + +test("summarizes collections, preserves late selections, and expands a scoped collection", async () => { + const items = Array.from({ length: 30 }, (_, i) => node(i + 2, "option", `City ${i}`)) + items[29].properties = [{ name: "selected", value: { type: "boolean", value: true } }] + const tree = [node(1, "listbox", "Cities", ...items.map((_, i) => i + 2)), ...items] + const result = await accessibilitySnapshot(tree, options()) + expect(result.content).toContain('"City 29" selected=true') + expect(result.content).not.toContain('"City 27"') + expect(result.content).toContain("+4 more in @e1 [listbox]") + expect(result.content).toContain("4 nodes omitted (4 interactive)") + const scoped = await accessibilitySnapshot(tree, { ...options(), root: 1 }) + expect(scoped.truncated).toBe(false) + expect(scoped.content).toContain('"City 27"') +}) + +test("prefers a nonignored root and can find a known ref after its role changes", async () => { + const first = { ...node(1, "generic", ""), ignored: true, nodeId: "ignored" } + + const result = await accessibilitySnapshot([first, node(1, "group", "Renamed")], { + ...options(), + root: 1, + text: "@e9", + previous: new Map([[1, "e9"]]), + }) + + expect(result.content).toBe('@e9 [group] "Renamed"') +}) + +test("snapshot, find, then scope by the first ref without invalidating the second", async () => { + const live = documentRefs() + const tree = [node(1, "generic", "", 2, 3), node(2, "button", "First"), node(3, "button", "Second")] + const setup = options() + + const read = async (extra: { maxLines?: number; text?: string; root?: number }) => { + const result = await accessibilitySnapshot(tree, { ...setup, ...extra, previous: live.previous("main") }) + live.add("main", undefined, result.refs) + + return result.content + } + + await read({ maxLines: 1 }) + await read({ text: "Second" }) + expect(await read({ root: live.get("e1")?.backendID })).toBe('@e1 [button] "First"') + expect(live.get("e2")?.backendID).toBe(3) + expect(await read({})).toContain('@e2 [button] "Second"') + live.clear() + expect(live.get("e1")).toBeUndefined() + expect(live.previous("main").size).toBe(0) +}) diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index 0d2aacd3798..004063c52e5 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -1,43 +1,92 @@ import type { Protocol } from "devtools-protocol" -import { Browser } from "@opencode/plugin-browser/rpc" +import { setImmediate } from "node:timers/promises" -/** Shape one frame's AX tree. Frame documents have their own target checks and are requested by frameID. */ -export async function accessibilitySnapshot( - nodes: readonly Protocol.Accessibility.AXNode[], - options: { - root?: number - depth?: number - text?: string - interactive?: boolean - maxLines?: number - previous: ReadonlyMap<number, string> - picked: ReadonlyMap<number, string> - ref: () => string - box?: (id: number) => Promise<string> - }, -) { - const root = options.root === undefined ? nodes[0] : nodes.find((node) => node.backendDOMNodeId === options.root) +type Options = { + root?: number + depth?: number + text?: string + interactive?: boolean + maxLines?: number + maxChars?: number + previous: ReadonlyMap<number, string> + picked: ReadonlyMap<number, string> + ref: () => string + box?: (id: number) => Promise<string> + signal?: AbortSignal +} + +type Area = { id: number; role: string; count: number; skipped: number } + +type Overflow = { area: Area; keep: boolean; parent?: Overflow } + +type Branch = { + node: Protocol.Accessibility.AXNode + level: number + parent: string + parentName: string + scope: string + item: string + ordinal: number + priority?: number + area?: Area + collection?: Area + overflow?: Overflow +} + +type Line = { label: string; id?: number; interactive: boolean; area?: Area; overflow?: Overflow; deep: boolean } + +const controls = + /^(button|link|textbox|searchbox|combobox|listbox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem|scrollbar)$/ + +const collections = /^(table|grid|treegrid|list|listbox|combobox|menu|tree)$/ + +const landmarks = /^(dialog|alertdialog|main|form|search|region|navigation|contentinfo|banner|complementary)$/ + +function excerpt(name: string, limit: number) { + return name.length <= limit ? name : `${name.slice(0, limit)}… [+${name.length - limit} chars]` +} + +function rank(role: string) { + if (role === "alertdialog" || role === "dialog") return 1 + + if (role === "main") return 2 + + if (role === "form" || role === "search") return 3 + + if (landmarks.test(role)) return 4 +} + +/** One frame per walk. Never inspect editable descendants, even to count omitted nodes or search text. */ +export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibility.AXNode[], options: Options) { + const index = new Map<string, Protocol.Accessibility.AXNode>() + let root = options.root === undefined ? nodes[0] : undefined + + for (const node of nodes) { + index.set(node.nodeId, node) + + if (options.root !== undefined && node.backendDOMNodeId === options.root && (!root || root.ignored)) root = node + + if (index.size % 2048 === 0) await setImmediate(undefined, { signal: options.signal }) + } if (!root) throw new Error("Element is absent from this frame's accessibility snapshot. Refresh the snapshot without ref.") - - const index = new Map(nodes.map((node) => [node.nodeId, node])) - const pending = [{ node: root, level: 0, scope: "", item: "", ordinal: 1, parent: "" }] - const headings = new Map<string, string>() + const pending: Branch[] = [{ node: root, level: 0, parent: "", parentName: "", scope: "", item: "", ordinal: 1 }] + const buckets = Array.from({ length: 6 }, (): Line[] => []) const seen = new Set<string>() - const refs = new Map<string, number>() - const lines: string[] = [] + const headings = new Map<string, string>() + const overflowItems: Overflow[] = [] const query = options.text?.toLowerCase() - let size = 0 - let truncated = false while (pending.length) { - const current = pending.pop()! - const { node, level } = current + const branch = pending.pop() - if (seen.has(node.nodeId)) continue + if (!branch || seen.has(branch.node.nodeId)) continue + const node = branch.node seen.add(node.nodeId) + if (seen.size % 2048 === 0) await setImmediate(undefined, { signal: options.signal }) + const role = String(node.role?.value ?? "node") .replace(/[^a-zA-Z0-9_-]/g, "") .slice(0, 40) @@ -45,53 +94,77 @@ export async function accessibilitySnapshot( const name = String(node.name?.value ?? "").replace(/\s+/g, " ") const id = node.backendDOMNodeId const picked = id && options.picked.get(id) + const known = picked || (id && options.previous.get(id)) const props = new Map(node.properties?.map((p) => [p.name, p.value.value])) - const editable = role === "textbox" || role === "searchbox" || props.get("editable") - - const actionable = - role !== "RootWebArea" && - (props.get("focusable") || - editable || /^(button|link|textbox|searchbox|combobox|listbox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem|scrollbar)$/.test( - role, - )) - - const children = node.childIds ?? [] + const editable = role === "textbox" || role === "searchbox" || !!props.get("editable") + const interactive = !!id && role !== "RootWebArea" && (editable || !!props.get("focusable") || controls.test(role)) const wrapper = - role === "generic" && + /^(generic|none|presentation)$/.test(role) && !name && - !actionable && - !editable && - !picked && + !interactive && + !known && !node.value && !node.description && - !props.size && - children.length === 1 + !props.size - const visible = !node.ignored && !wrapper && role !== "InlineTextBox" - const lean = options.interactive === true - const contextual = lean && visible - const landmark = contextual && name && /^(banner|navigation|main|region|form|search|complementary|dialog|table|grid|list|group|heading)$/.test(role) - const inherited = headings.get(current.parent) ?? current.scope - const scope = landmark ? `${role} ${brief(name)}` : inherited - if (contextual && role === "heading" && name) headings.set(current.parent, scope) - const itemName = contextual && role === "row" && !name ? String(index.get(children[0])?.name?.value ?? "").replace(/\s+/g, " ") : name - const item = contextual && (role === "row" || role === "listitem") - ? `${role} ${itemName ? brief(itemName) : current.ordinal}` : current.item + const visible = + !node.ignored && + !wrapper && + role !== "InlineTextBox" && + !(role === "StaticText" && name === branch.parentName && !known) - if (visible && level > (options.depth ?? Infinity)) { - truncated = true - continue + const area = + visible && id && (landmarks.test(role) || collections.test(role)) + ? { id, role, count: 0, skipped: 0 } + : branch.area + + const collection = area && collections.test(area.role) ? area : branch.collection + const priority = branch.priority ?? (visible ? rank(role) : undefined) + const inherited = headings.get(branch.parent) ?? branch.scope + + const scope = + options.interactive && visible && name && (landmarks.test(role) || collections.test(role) || role === "heading") + ? `${role} ${JSON.stringify(excerpt(name, 60))}` + : inherited + + if (options.interactive && visible && role === "heading" && name) headings.set(branch.parent, scope) + const children = node.childIds ?? [] + const isItem = visible && /^(row|listitem|option)$/.test(role) + + const itemName = + options.interactive && role === "row" && !name + ? String(index.get(children[0])?.name?.value ?? "").replace(/\s+/g, " ") + : name + + const item = + options.interactive && isItem + ? `${role} ${itemName ? JSON.stringify(excerpt(itemName, 60)) : branch.ordinal}` + : branch.item + + const overflow = + isItem && collection && options.text === undefined && collection.id !== options.root && ++collection.count > 25 + ? { area: collection, keep: false, parent: branch.overflow } + : branch.overflow + + if (overflow && overflow !== branch.overflow) overflowItems.push(overflow) + + if ( + overflow && + ["focused", "selected", "checked"].some((key) => + node.properties?.some((p) => p.name === key && [true, "true", "mixed"].includes(p.value.value)), + ) + ) { + for (let group: Overflow | undefined = overflow; group; group = group.parent) group.keep = true } - if (visible && (!lean || (actionable && id))) { - const flags = (["checked", "disabled", "expanded", "selected", "pressed"] as const).flatMap((key) => + if (visible && (!options.interactive || interactive)) { + const flags = (["checked", "disabled", "expanded", "selected", "pressed", "focused"] as const).flatMap((key) => props.has(key) ? [`${key}=${props.get(key)}`] : [], ) - const context = lean ? [inherited, current.item].filter(Boolean).join(" / ") : "" - const label = `[${role}] ${lean ? brief(name) : JSON.stringify(name.length > 300 ? `${name.slice(0, 299)}…` : name)}${flags.length ? ` ${flags.join(" ")}` : ""}${context ? ` in ${context}` : ""}` - const known = picked || (id && options.previous.get(id)) + const context = options.interactive ? [inherited, branch.item].filter(Boolean).join(" / ") : "" + const label = `[${role}] ${JSON.stringify(excerpt(name, interactive ? 300 : 160))}${flags.length ? ` ${flags.join(" ")}` : ""}${context ? ` in ${context}` : ""}` if ( !query || @@ -99,39 +172,143 @@ export async function accessibilitySnapshot( name.toLowerCase().includes(query) || (known && `@${known}`.includes(query)) ) { - if (lines.length >= (options.maxLines ?? Infinity)) { - truncated = true - break - } - const ref = id && (picked || actionable) ? known || options.ref() : undefined - const box = ref && id && options.box ? await options.box(id) : "" - const line = `${lean ? "" : " ".repeat(Math.min(level, 16))}${ref ? `@${ref} ` : ""}${label}${box}` - size += line.length + Number(lines.length > 0) - - if (size > Browser.MAX_TEXT) { - truncated = true - break - } - - lines.push(line) - - if (id && ref) refs.set(ref, id) + const pad = options.interactive ? "" : " ".repeat(Math.min(12, branch.level)) + buckets[role === "RootWebArea" ? 0 : (priority ?? 5)].push({ + label: pad + label, + id: interactive || known || area?.id === id ? id : undefined, + interactive, + area, + overflow, + deep: branch.level > (options.depth ?? Infinity), + }) } } - // Editable descendants may contain a field's private value; do not inspect them, even for a search. if (editable) continue for (let i = children.length - 1; i >= 0; i--) { const child = index.get(children[i]) - if (child) pending.push({ node: child, level: level + Number(visible), scope, item, ordinal: i + 1, parent: node.nodeId }) + if (child) + pending.push({ + node: child, + level: branch.level + Number(visible), + parent: node.nodeId, + parentName: visible ? name : branch.parentName, + scope, + item, + priority, + area, + collection, + overflow, + ordinal: i + 1, + }) } } - return { content: lines.join("\n"), truncated, refs } + for (const group of overflowItems) if (!group.keep) group.area.skipped++ + + return printSnapshot(buckets, options) } -function brief(value: string) { - return JSON.stringify(value.length > 60 ? `${value.slice(0, 59)}…` : value) +async function printSnapshot(buckets: Line[][], options: Options) { + const refs = new Map<string, number>() + const issued = new Map<number, string>() + + const ref = (id: number) => { + const value = options.picked.get(id) ?? options.previous.get(id) ?? issued.get(id) ?? options.ref() + issued.set(id, value) + + return value + } + + const maxChars = options.maxChars ?? 20_000 + const maxLines = options.maxLines ?? Infinity + const output: { line: Line; text: string }[] = [] + const areas = new Map<Area | undefined, number>() + let omitted = 0 + let interactive = 0 + let size = 0 + let full = false + let visited = 0 + + const omit = (line: Line) => { + omitted++ + interactive += Number(line.interactive) + areas.set(line.area, (areas.get(line.area) ?? 0) + 1) + } + + for (const bucket of buckets) { + for (let i = 0; i < bucket.length; i += 32) { + const batch = bucket.slice(i, i + 32) + + const boxes = + options.box && !full && output.length < maxLines + ? await Promise.all( + batch.map((line) => + !line.deep && (!line.overflow || line.overflow.keep) && line.id ? options.box?.(line.id) : undefined, + ), + ) + : [] + + for (const [j, line] of batch.entries()) { + if (++visited % 2048 === 0) await setImmediate(undefined, { signal: options.signal }) + + if ((line.overflow && !line.overflow.keep) || line.deep || full || output.length >= maxLines) { + omit(line) + continue + } + + const key = line.id ? ref(line.id) : undefined + const text = (key ? line.label.replace(/^\s*/, (pad) => `${pad}@${key} `) : line.label) + (boxes[j] ?? "") + const length = size + Number(output.length > 0) + text.length + + if (length > maxChars) { + full = true + omit(line) + continue + } + + size = length + output.push({ line, text }) + } + } + } + + const content = () => output.map(row => { + if (row.line.id) refs.set(ref(row.line.id), row.line.id) + + return row.text + }).join("\n") + + if (!omitted) return { content: content(), truncated: false, refs } + + const footer = () => { + const places = Array.from(areas) + .slice(0, 5) + .map(([area, count]) => { + if (!area) return `document (${count} nodes)` + const key = ref(area.id) + refs.set(key, area.id) + + return `${area.skipped ? `… +${area.skipped} more in ` : ""}@${key} [${area.role}] (${count} nodes)` + }) + + return `… ${omitted} nodes omitted (${interactive} interactive): ${places.join(", ")}${areas.size > 5 ? `; ${areas.size - 5} other containers` : ""}. Use find, snapshot({tabID, ref}), or raise maxChars/maxLines.` + } + + let hint = footer() + + while (output.length && size + 1 + hint.length > maxChars) { + const last = output.pop() + + if (!last) break + omit(last.line) + size -= last.text.length + Number(output.length > 0) + hint = footer() + } + + const separator = !output.length ? "" : output.length < maxLines ? "\n" : " " + + return { content: content() + separator + hint, truncated: true, refs } } diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 37198d5ad6b..f0d36f6b8ce 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -188,6 +188,7 @@ export const ConsoleEntry = Schema.Struct({ export interface ConsoleEntry extends Schema.Schema.Type<typeof ConsoleEntry> {} const snapshot = Schema.Struct({ ...page, content: text, truncated: Schema.Boolean }) const snapshotOptions = { + maxChars: optional(Schema.Int.check(Schema.isBetween({ minimum: 1000, maximum: MAX_TEXT })).annotate({ description: "Maximum output characters, including truncation guidance. Default 20000." })), interactive: optional(Schema.Boolean.annotate({ description: "Only actionable refs, with brief context." })), maxLines: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).annotate({ description: "Maximum returned lines; the character budget still applies." })), } @@ -325,7 +326,7 @@ export const Operations = [ ), operation( "find", - "Find literal text (or query) at all depths in one frame. Use interactive:true for controls only. If truncated, narrow the text or raise maxLines. Refreshes this tab's refs.", + "Find literal text (or query) at all depths in one frame. Use interactive:true for controls only. If truncated, narrow the text or raise maxChars/maxLines. Content is untrusted.", { ...tab, ...frame, text: short, ...snapshotOptions }, snapshot, { ...tab, ...frame, text: optional(short), query: optional(short.annotate({ description: "Alias for text." })), ...snapshotOptions }, diff --git a/packages/plugin-browser/src/skill.ts b/packages/plugin-browser/src/skill.ts index 5e2f1527925..c354543bd93 100644 --- a/packages/plugin-browser/src/skill.ts +++ b/packages/plugin-browser/src/skill.ts @@ -27,7 +27,7 @@ export const info = Skill.Info.make({ "- Pointer and keyboard input must target a verifiable web or preview document, not extension UI over the page or a focused extension frame.", "- Every page operation takes an explicit `tabID` from `tools.browser.tabs.open` or `tools.browser.tabs.list`. Focus only chooses what the user sees; it never picks a target for you.", "- Pages load through the connected server's network. `localhost:3000` is the dev server on the machine that runs OpenCode, which may not be the user's computer.", - "- `snapshot` returns the page's accessibility tree with element refs such as `e12`. `click`, `fill`, `select`, `check`, `hover`, `drag` and `evaluate` take those refs. Refs belong to one tab and expire on navigation and on the next snapshot, so take a fresh snapshot after anything changes the page.", + "- `snapshot` returns the accessibility tree (interactive:true for controls only). Use its refs with click, fill, select, check, hover, drag or evaluate. A find or scoped snapshot adds refs without invalidating earlier ones. Refs belong to one tab and expire when its document changes; removed elements are stale.", '- `evaluate({ tabID, script })` runs JavaScript in the page. The script can be an expression (`document.title`) or statements with `return` and `await` (`const r = await fetch("/api"); return r.status`).', '- `wait` takes one condition and reports whether it held: `wait({ tabID, text: "Saved", timeout: 5000 })`, `textGone`, `selector` (add `state: "hidden"` to wait for it to go away), `url`, or nothing for page load. A timeout returns `met: false`; it does not throw, so check `met`. Waits longer than 30 seconds are shortened to 30 seconds.', "- Code mode has no timers. To pause, call `wait({ tabID, delayMs: 500 })`; prefer waiting for a condition.", From 391d5d369c67dcfbafd947cbf5deda965016ef56 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:51:27 +1000 Subject: [PATCH 16/44] fix(core): make the experimental.rules hook deny-only Review finding M1. An experimental.rules hook could rewrite the whole ruleset, so one appended allow outranked every configured deny for calls and listing. Agents and sessions showed nothing. The rule objects were also the agent state's own, so an edit in place changed the agent for every session. The new shape is { sessionID, agent, rules, session, deny }. - rules (agent then session) and session are fresh copies of each rule. Core ignores them after the hooks run. - Core reads only event.deny and decodes it with Schema.Array(Struct({ action: String, resource: String })). Other fields of an entry, such as effect, are dropped, so each entry is a deny. - Core returns [...agent, ...session, ...denies], in the order the hooks pushed them. Nothing a hook writes can allow, remove or reorder a rule. Before this, a configured deny was final: evaluateInput returned deny before any hook ran. That holds again. A hook can only add denies, and they are checked in the same place. A deny entry that is not two strings dies with 'A permission "experimental.rules" hook added an invalid deny: ...'. The request or step fails closed instead of running without the hook's denies. L2: the TSDoc says that the hook runs for every permission check and every step, must be quick, and must not request permissions itself. A request would run the hook again without end. The evaluate hook next to it has no re-entrancy guard, so this hook documents the constraint in the same way. Tests (permission.test.ts): - A hook pushes an allow, edits rules in place, changes the arrays and adds an entry with effect "allow". None of this reaches the rules or the agent state, and configured denies and asks still decide. - Two hooks' denies are appended in order. - A hook's deny refuses a request before any evaluate hook runs. - A malformed entry fails closed and names the hook. --- packages/core/src/permission.ts | 24 +++++-- packages/core/test/permission.test.ts | 87 +++++++++++++++++++++++ packages/plugin/src/effect/permission.ts | 19 +++-- packages/plugin/src/promise/permission.ts | 19 +++-- 4 files changed, 133 insertions(+), 16 deletions(-) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 2bb84cea901..0ceefec7ad6 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -107,22 +107,34 @@ export function merge(...rulesets: Permission.Ruleset[]): Permission.Ruleset { return rulesets.flat() } +const Denies = Schema.Array(Schema.Struct({ action: Schema.String, resource: Schema.String })) + /** - * The rules for `agent` in `session`: the agent's, then the Session's, then any that `experimental.rules` hooks append. - * Requests are evaluated against them and steps list tools, skills and MCP servers by them, so what an agent is - * offered and what it may call come from one ruleset. + * The rules for `agent` in `session`: the agent's, then the Session's, then a deny for each entry `experimental.rules` + * hooks add. Requests are evaluated against them and steps list tools, skills and MCP servers by them, so what an + * agent is offered and what it may call come from one ruleset. Hooks see copies and can only add denies, so a + * configured deny stays final and no hook can allow, remove or reorder a rule. */ export const rules = Effect.fn("Permission.rules")(function* ( hooks: PluginHooks.Interface, input: { readonly session: SessionSchema.Info; readonly agent: Agent.Selection }, ) { + const base = [...(input.agent.info?.permissions ?? missingAgentPermissions), ...(input.session.permissions ?? [])] const event = yield* hooks.trigger("permission", "experimental.rules", { sessionID: input.session.id, agent: input.agent.id, - session: input.session.permissions ?? [], - rules: [...(input.agent.info?.permissions ?? missingAgentPermissions), ...(input.session.permissions ?? [])], + rules: base.map((rule) => ({ ...rule })), + session: (input.session.permissions ?? []).map((rule) => ({ ...rule })), + deny: [], }) - return event.rules + // A hook that cannot say what it denies must not leave the request decided without it. + const denies = yield* Schema.decodeUnknownEffect(Denies)(event.deny).pipe( + Effect.mapError( + (error) => new Error(`A permission "experimental.rules" hook added an invalid deny: ${error.message}`), + ), + Effect.orDie, + ) + return [...base, ...denies.map((rule) => ({ action: rule.action, resource: rule.resource, effect: "deny" as const }))] }) export interface Interface { diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 80fe7c5dadf..bb65a2abaef 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -881,3 +881,90 @@ describe("shell scanner permission impact", () => { ) } }) + +describe("Permission experimental.rules", () => { + const rulesFor = Effect.gen(function* () { + const store = yield* SessionStore.Service + const agents = yield* Agent.Service + const session = yield* store.get(Session.ID.make("ses_test")) + if (!session) return yield* Effect.die(new Error("no session")) + return yield* Permission.rules(yield* PluginHooks.Service, { session, agent: yield* agents.select(session.agent) }) + }) + + it.effect("appends each hook's denies in order, and nothing a hook writes elsewhere", () => + Effect.gen(function* () { + const configured: Permission.Ruleset = [ + { action: "shell", resource: "*", effect: "deny" }, + { action: "read", resource: "*.env", effect: "ask" }, + ] + yield* setup(configured) + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.sync(() => { + // Every way a hook could try to allow: push to the rules, edit them in place, swap the arrays, allow in deny. + ;(event.rules as Permission.Rule[]).push({ action: "*", resource: "*", effect: "allow" }) + ;(event.rules as Permission.Rule[]).forEach((rule) => Object.assign(rule, { effect: "allow" })) + ;(event.session as Permission.Rule[]).push({ action: "*", resource: "*", effect: "allow" }) + Object.assign(event, { rules: [], session: [] }) + event.deny.push({ action: "edit", resource: "*" }) + event.deny.push(Object.assign({ action: "webfetch", resource: "*" }, { effect: "allow" })) + }), + ) + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.sync(() => event.deny.push({ action: "shell", resource: "git *" })), + ) + expect(yield* rulesFor).toEqual([ + ...configured, + { action: "edit", resource: "*", effect: "deny" }, + { action: "webfetch", resource: "*", effect: "deny" }, + { action: "shell", resource: "git *", effect: "deny" }, + ]) + const agents = yield* Agent.Service + expect((yield* agents.get(Agent.ID.make("test")))?.permissions).toEqual(configured) + + const service = yield* Permission.Service + expect(yield* service.ask(assertion({ action: "shell", resources: ["ls"] }))).toMatchObject({ effect: "deny" }) + expect(yield* service.ask(assertion({ action: "edit", resources: ["a.ts"] }))).toMatchObject({ effect: "deny" }) + expect( + yield* service.ask(assertion({ id: Permission.ID.create("per_env"), action: "read", resources: [".env"] })), + ).toMatchObject({ effect: "ask" }) + }), + ) + + it.effect("a hook's deny refuses the request before any evaluate hook runs", () => + Effect.gen(function* () { + yield* setup([{ action: "*", resource: "*", effect: "allow" }]) + const hooks = yield* PluginHooks.Service + const evaluated: string[] = [] + yield* hooks.register("permission", "evaluate", (event) => + Effect.sync(() => { + evaluated.push(event.action) + event.effect = "allow" + }), + ) + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.sync(() => event.deny.push({ action: "shell", resource: "*" })), + ) + const service = yield* Permission.Service + const error = yield* service.assert(assertion({ action: "shell", resources: ["ls"] })).pipe(Effect.flip) + expect(error).toBeInstanceOf(Permission.BlockedError) + expect(yield* service.ask(assertion({ action: "read" }))).toMatchObject({ effect: "allow" }) + expect(evaluated).toEqual(["read"]) + }), + ) + + it.effect("a deny that is not two strings fails the check closed and names the hook", () => + Effect.gen(function* () { + yield* setup([{ action: "*", resource: "*", effect: "allow" }]) + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.sync(() => event.deny.push({ action: 1, resource: "*" } as unknown as (typeof event.deny)[number])), + ) + const service = yield* Permission.Service + const exit = yield* service.ask(assertion()).pipe(Effect.exit) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") + expect(Cause.pretty(exit.cause)).toContain('A permission "experimental.rules" hook added an invalid deny') + }), + ) +}) \ No newline at end of file diff --git a/packages/plugin/src/effect/permission.ts b/packages/plugin/src/effect/permission.ts index 20b13788f62..30cae1ae6cc 100644 --- a/packages/plugin/src/effect/permission.ts +++ b/packages/plugin/src/effect/permission.ts @@ -30,17 +30,26 @@ export interface PermissionEvaluation { } /** - * The rules for one agent in one Session. They decide its permission requests and what its steps list: a tool whose - * permission they deny outright is not listed, and neither is a skill or MCP server they deny. Rules a hook appends - * are evaluated after the Session's. Experimental: may change without compatibility guarantees. + * Runs whenever core builds the rules for one agent in one Session: for every permission check and every step. The + * rules decide the agent's permission requests and what its steps list: a tool whose permission they deny outright is + * not listed, and neither is a skill or MCP server they deny. + * + * A hook can only narrow them. Each entry it adds to `deny` becomes `{ action, resource, effect: "deny" }` after every + * other rule, so it outranks every allow and ask; other fields of an entry are ignored. `rules` and `session` are + * copies: changing them changes nothing. An entry that is not two strings fails the check or step that built the + * rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which + * would build the rules again and run the hook again without end. Experimental: may change without compatibility + * guarantees. */ export interface PermissionRules { readonly sessionID: Session.ID readonly agent: Agent.ID + /** The agent's rules, then the Session's, as evaluated before any `deny` entry. */ + readonly rules: ReadonlyArray<Permission.Rule> /** The Session's own rules, which follow the agent's in `rules`. */ readonly session: ReadonlyArray<Permission.Rule> - /** The agent's rules, then the Session's. */ - rules: Array<Permission.Rule> + /** Denies to add after `rules`, in the order the hooks add them. */ + readonly deny: Array<{ readonly action: string; readonly resource: string }> } export interface PermissionHooks { diff --git a/packages/plugin/src/promise/permission.ts b/packages/plugin/src/promise/permission.ts index dcfd4f4d915..d258d78c6a7 100644 --- a/packages/plugin/src/promise/permission.ts +++ b/packages/plugin/src/promise/permission.ts @@ -28,17 +28,26 @@ export interface PermissionEvaluation { } /** - * The rules for one agent in one Session. They decide its permission requests and what its steps list: a tool whose - * permission they deny outright is not listed, and neither is a skill or MCP server they deny. Rules a hook appends - * are evaluated after the Session's. Experimental: may change without compatibility guarantees. + * Runs whenever core builds the rules for one agent in one Session: for every permission check and every step. The + * rules decide the agent's permission requests and what its steps list: a tool whose permission they deny outright is + * not listed, and neither is a skill or MCP server they deny. + * + * A hook can only narrow them. Each entry it adds to `deny` becomes `{ action, resource, effect: "deny" }` after every + * other rule, so it outranks every allow and ask; other fields of an entry are ignored. `rules` and `session` are + * copies: changing them changes nothing. An entry that is not two strings fails the check or step that built the + * rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which + * would build the rules again and run the hook again without end. Experimental: may change without compatibility + * guarantees. */ export interface PermissionRules { readonly sessionID: Session.ID readonly agent: Agent.ID + /** The agent's rules, then the Session's, as evaluated before any `deny` entry. */ + readonly rules: ReadonlyArray<Permission.Rule> /** The Session's own rules, which follow the agent's in `rules`. */ readonly session: ReadonlyArray<Permission.Rule> - /** The agent's rules, then the Session's. */ - rules: Array<Permission.Rule> + /** Denies to add after `rules`, in the order the hooks add them. */ + readonly deny: Array<{ readonly action: string; readonly resource: string }> } export interface PermissionHooks { From 545a330056b23db046d2e3df028975c3b89f0ad2 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:51:28 +1000 Subject: [PATCH 17/44] fix(browser): keep the grant from overriding a configured skill rule Review finding L1, and the browser plugin moves to the deny-only hook. The attachment's grant includes skill "browser" allow. It is the last rule, so with skill "*": deny or ask and a desktop attached, the built-in browser skill was listed and loaded without a prompt. This was already the case at 9e20e99a4f. A person's own skill named browser replaces the built-in (ConfigSkill loads later). Before, it was hidden whenever no desktop was attached, because of the agent-level default deny. It was also hidden whenever the agent was denied the browser, even with an explicit skill allow. Now: - The agent-level default deny covers only browser "*". The skill deny moves to the experimental.rules hook. - The hook pushes a skill "browser" deny in two cases: - the configured rules (agent, then session without the grant) deny that skill; - the registered browser skill is the built-in one (its path is skill://browser/SKILL.md) and the session has no grant, or the agent is denied the whole browser. A person's own skill is denied only by their own rules. - If the skill list cannot be read, the hook treats the skill as the built-in one, so it hides the skill rather than shows it. - The evaluate hook gets a branch for skill "browser": a configured ask prompts despite the grant, unless the same save key was saved before. This works as the ask for browser operations does. - The browser deny is now event.deny.push({ action: "browser", resource: "*" }) under the same condition as before. Call outcomes for browser operations do not change. For an agent denied the browser, a scheduled check's preflight now fails with core's "Permission denied: browser" message instead of the plugin's "[browser.denied] ...". Tests (browser-permission.test.ts), review finding L3: - A row pins the tool.use policy gap as it is today: listed, and calls refused with "Blocked by configuration policy". - With the plugin removed by "-opencode.browser" and a grant left in the session, nothing is registered or listed. - skill "*": deny hides the skill and the read tool refuses it. skill browser: ask lists it and prompts. - The read tool refuses the skill to an agent denied the browser. - A person's own browser skill with an explicit allow stays listed while the agent is denied the browser, attached or not. - A scheduled code check runs the browser for an allowed agent and refuses one denied the browser. With the plugin's experimental.rules hook skipped, 12 of the 45 tests in the file fail: - the 7 that failed before; - 2 no-desktop rows, whose skill hiding is now in the hook; - the 3 new skill and scheduled-check tests. --- packages/core/test/browser-permission.test.ts | 141 ++++++++++++++++-- packages/plugin-browser/README.md | 5 +- packages/plugin-browser/src/connection.ts | 110 ++++++++------ packages/plugin-browser/src/machine.ts | 12 +- 4 files changed, 211 insertions(+), 57 deletions(-) diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index cae71e6b1bb..5709f55e4c2 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -22,6 +22,7 @@ import { Rpc } from "@opencode/core/rpc" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" import { SessionContext } from "@opencode/core/session/context" +import { ScheduleCheck } from "@opencode/core/schedule/check" import { Tool } from "@opencode/core/tool" import { Config } from "@opencode/core/config" import { ConfigIntegration } from "@opencode/core/config/integration" @@ -63,11 +64,13 @@ const tab = { generation: 1, } -// A location with `config` as its opencode.json and one session, plus a stand-in desktop that attaches to that +// A location with `config` as its opencode.json, `files` beside it and one session, plus a stand-in desktop that attaches to that // session and answers every browser command with an empty tab list. -const setup = (config: object) => +const setup = (config: object, files: Record<string, string> = {}) => Effect.gen(function* () { const dir = yield* tmpdirScoped() + for (const [name, text] of Object.entries(files)) + yield* Effect.promise(() => Bun.write(path.join(dir.path, name), text)) yield* Effect.promise(() => Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify(config))) const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) const locations = yield* LocationServiceMap.Service @@ -641,22 +644,30 @@ const truth: ReadonlyArray<{ { name: "whole browser denied, one operation allowed after", global: [rule("*", "deny"), rule("tabs.list", "allow")], attached: true, listed: true, list: "allow", open: "deny" }, ] -// What `operation` comes to for `agent` in `sessionID`. A call that prompts is interrupted, which withdraws the prompt. -const outcome = Effect.fnUntraced(function* ( +// What `operation` comes to for `agent` in `sessionID`. +const outcome = ( browser: Effect.Success<ReturnType<typeof setup>>, operation: string, agent: string, sessionID: Session.ID, +) => settle(browser, sessionID, browser.run(operation, {}, agent, sessionID)) + +// What `call` comes to: it reaches its end or the desktop, prompts, or is refused as denied or disconnected. A call +// that prompts is interrupted, which withdraws the prompt. Any other failure is returned as its message, so the +// comparison shows it. +const settle = Effect.fnUntraced(function* ( + browser: Effect.Success<ReturnType<typeof setup>>, + sessionID: Session.ID, + call: Effect.Effect<unknown, { readonly message: string; readonly error?: unknown }>, ) { const permissions = Context.get(browser.context, Permission.Service) const before = browser.commands.count const reached = () => browser.commands.count > before - // Any other failure is returned as its message, so the comparison shows it. - const call = browser.run(operation, {}, agent, sessionID).pipe( + const settled = call.pipe( Effect.as<Outcome | string>("allow"), Effect.catch((error) => Effect.succeed( - error.message.startsWith("[browser.denied]") + error.message.startsWith("[browser.denied]") || error.message.startsWith("Permission denied") || error.error instanceof Permission.BlockedError ? "deny" : error.message.startsWith("[browser.disconnected]") ? "disconnected" @@ -671,9 +682,8 @@ const outcome = Effect.fnUntraced(function* ( Effect.retry(Schedule.spaced("10 millis")), Effect.as<Outcome | string>("ask"), ) - return yield* Effect.raceFirst(call, prompted).pipe(Effect.timeout("5 seconds")) + return yield* Effect.raceFirst(settled, prompted).pipe(Effect.timeout("5 seconds")) }) - for (const row of truth) it.live(`listing agrees with calling: ${row.name}`, () => Effect.gen(function* () { @@ -795,4 +805,117 @@ it.live("a subagent lists no browser tools, whether it lost the inherited grant expect(listing.skill).toBe(false) expect(browser.commands.count).toBe(0) }), +) +it.live("a tool.use policy on the browser refuses its calls but still lists its tools, as today", () => + Effect.gen(function* () { + const browser = yield* setup({ policies: [{ action: "tool.use", resource: "browser:*", effect: "deny" }] }) + // Listing does not ask policies yet; closing that changes this test on purpose. + expect((yield* browser.listing()).catalog).toContain("browser.tabs.list") + expect((yield* browser.call().pipe(Effect.flip)).message).toBe("Blocked by configuration policy") + }), +) + +it.live("with the browser plugin removed, a grant left in a session lists and registers nothing", () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify({ plugins: ["-opencode.browser"] }))) + const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const locations = yield* LocationServiceMap.Service + const context = yield* locations.contextEffect(ref).pipe(Effect.scoped) + yield* Plugin.awaitActivation.pipe(Effect.provideContext(context)) + const sessions = yield* Session.Service + const session = yield* sessions.create({ location: ref, permissions: [...grant] }) + const tools = yield* Context.get(context, Tool.Service).list() + expect(tools.filter((tool) => tool.options?.namespace?.startsWith("browser"))).toEqual([]) + const listed = yield* listing(Context.get(context, SessionContext.Service), session.id) + expect(listed.catalog).toEqual([]) + expect(listed.skill).toBe(false) + }), +) + +// Loads the browser skill as the model would, through the read tool. +const readSkill = (browser: Effect.Success<ReturnType<typeof setup>>, agent: string, sessionID = browser.session.id) => + Effect.gen(function* () { + const read = (yield* Context.get(browser.context, Tool.Service).list()).find((tool) => tool.name === "read") + if (!read) return yield* Effect.die(new Error("read is not registered")) + return yield* settle( + browser, + sessionID, + read.execute( + { path: "skill://browser/SKILL.md" }, + { + sessionID, + agent: Agent.ID.make(agent), + messageID: SessionMessage.ID.create(), + id: Tool.CallID.make(`call_${crypto.randomUUID()}`), + progress: () => Effect.void, + }, + ), + ) + }) + +const reads = rule("*", "allow", "read") + +it.live("the attachment's grant does not override a configured skill deny or ask for the browser skill", () => + Effect.gen(function* () { + const denied = yield* setup({ permissions: [reads, rule("*", "deny", "skill")] }) + const listed = yield* denied.listing() + expect(listed.catalog).toContain("browser.tabs.list") + expect(listed.skill).toBe(false) + expect(yield* readSkill(denied, "build")).toBe("deny") + + const asked = yield* setup({ permissions: [reads, rule("browser", "ask", "skill")] }) + expect((yield* asked.listing()).skill).toBe(true) + expect(yield* readSkill(asked, "build")).toBe("ask") + + const allowed = yield* setup({ + permissions: [reads], + agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } }, + }) + expect(yield* readSkill(allowed, "build")).toBe("allow") + // The skill tool refuses an agent denied the browser, as its listing does. + expect(yield* readSkill(allowed, "reviewer")).toBe("deny") + }), +) + +it.live("a person's own skill named browser follows their rules, not the built-in's", () => + Effect.gen(function* () { + const browser = yield* setup( + { permissions: [reads, rule("*", "deny"), rule("browser", "allow", "skill")] }, + { + ".opencode/skills/browser/SKILL.md": + "---\nname: browser\ndescription: Drive Playwright against the staging site.\n---\n# Playwright\n", + }, + ) + const sessions = yield* Session.Service + const detached = yield* sessions.create({ location: browser.ref }) + for (const sessionID of [browser.session.id, detached.id]) { + const listed = yield* browser.listing(sessionID) + expect(listed.catalog).toEqual([]) + expect(listed.skill).toBe(true) + } + }), +) + +it.live("a scheduled check runs the browser for an allowed agent and refuses one denied the browser", () => + Effect.gen(function* () { + const browser = yield* setup({ agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } } }) + const sessions = yield* Session.Service + const check = { + mode: "if" as const, + condition: { type: "code" as const, code: "return (await tools.browser.tabs.list({})).tabs.length === 0" }, + } + const run = () => + sessions.get(browser.session.id).pipe( + Effect.flatMap((session) => + ScheduleCheck.evaluate(session, check, null, { messageID: SessionMessage.ID.create(), now: 0, checks: 0 }), + ), + Effect.provideContext(browser.context), + ) + expect(yield* run()).toMatchObject({ ok: true, wake: true }) + expect(browser.commands.count).toBe(1) + yield* sessions.switchAgent({ sessionID: browser.session.id, agent: Agent.ID.make("reviewer") }) + expect(yield* run()).toMatchObject({ ok: false, error: "Permission denied: browser" }) + expect(browser.commands.count).toBe(1) + }), ) \ No newline at end of file diff --git a/packages/plugin-browser/README.md b/packages/plugin-browser/README.md index 817e1b9baa8..45fa5028b06 100644 --- a/packages/plugin-browser/README.md +++ b/packages/plugin-browser/README.md @@ -36,7 +36,10 @@ performance and memory, and recovery after failures. It lists every operation from `Browser.Operations`. Like the tools, it is hidden until a desktop browser attaches to the session, and stays hidden from an agent whose configured rules deny the whole browser (`browser: "deny"`). An `ask`, or a deny for some -operations only, keeps them listed; each call then prompts or is refused. +operations only, keeps them listed; each call then prompts or is refused. The +attachment never overrides a configured `skill` deny or ask for the skill, and a +person's own skill named `browser` replaces the built-in one and follows only +their rules. The plugin entrypoint only composes its two owners: `connection.ts` manages desktop attachments and pending RPC requests; `tools.ts` runs the tool workflow. diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index c100f09eb70..896f69c51b1 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -12,6 +12,7 @@ import { Session } from "@opencode/schema/session" import { Tool } from "@opencode/schema/tool" import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect" import { BrowserMachine } from "./machine.js" +import { BrowserSkill } from "./skill.js" import { Browser } from "./rpc.js" import { BrowserTunnel } from "./tunnel.js" @@ -74,16 +75,17 @@ export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleG }) export const make = Effect.fn("BrowserConnection.make")(function* ( - ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event" | "permission" | "storage">, + ctx: Pick<Context, "agent" | "rpc" | "session" | "location" | "event" | "permission" | "storage" | "skill">, ) { // Each agent's rules from config and its definition, which an attachment's grant must not override. const configured = new Map<string, readonly Permission.Rule[]>() - // Appended after config, so every agent hides the browser until an attachment allows it. + // Appended after config, so every agent hides the browser tools until an attachment allows them. The skill is hidden + // by the `experimental.rules` hook below, which can tell the built-in skill from a person's own skill of that name. yield* ctx.agent.transform((editor) => { configured.clear() editor.list().forEach((agent) => { configured.set(agent.id, [...agent.permissions]) - agent.permissions.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" as const }))) + agent.permissions.push({ action: "browser", resource: "*", effect: "deny" }) }) }) const rulesFor = (session: Pick<Session.Info, "agent" | "permissions">, agent: string | undefined) => [ @@ -91,50 +93,72 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( ...(configured.get(agent ?? session.agent ?? "") ?? [{ action: "*", resource: "*", effect: "deny" as const }]), ...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)), ] - // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call to - // allow. The rules from config, the agent's definition and the session itself decide instead: a deny refuses the - // call, and an ask makes the permission check prompt as it would without the grant, unless the user already saved - // "always" for it. No matching rule leaves it allowed. - yield* ctx.permission.hook("evaluate", (event) => - event.action !== "browser" || event.effect === "deny" - ? Effect.void - : ctx.session.get({ sessionID: event.sessionID }).pipe( - Effect.map((session) => { - const rules = rulesFor(session, event.agent) - const denied = denial(rules, event.resources) - if (denied) { + // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call and + // every load of the `browser` skill to allow. The rules from config, the agent's definition and the session itself + // decide instead: a deny refuses the call, and an ask makes the permission check prompt as it would without the + // grant, unless the user already saved "always" for it. No matching rule leaves it allowed. The skill's denies come + // from the `experimental.rules` hook below, so core refuses those before this hook runs. + yield* ctx.permission.hook("evaluate", (event) => { + const skill = event.action === "skill" && event.resources.includes(BrowserSkill.id) + if ((event.action !== "browser" && !skill) || event.effect === "deny") return Effect.void + return ctx.session.get({ sessionID: event.sessionID }).pipe( + Effect.map((session) => { + const rules = rulesFor(session, event.agent) + if (skill) { + if ( + !event.experimental?.approvedSave && + BrowserMachine.selectRule(rules, "skill", BrowserSkill.id)?.effect === "ask" + ) + event.effect = "ask" + return + } + const denied = denial(rules, event.resources) + if (denied) { + event.effect = "deny" + event.message = denied + return + } + if ( + !event.experimental?.approvedSave && + event.resources.some((operation) => BrowserMachine.selectBrowserRule(rules, operation)?.effect === "ask") + ) + event.effect = "ask" + }), + // Without the rules, the grant must not decide alone. + Effect.catchCause((cause) => + Effect.logWarning("Browser permission evaluation failed", cause).pipe( + Effect.andThen( + Effect.sync(() => { event.effect = "deny" - event.message = denied - return - } - if ( - !event.experimental?.approvedSave && - event.resources.some((operation) => BrowserMachine.selectBrowserRule(rules, operation)?.effect === "ask") - ) - event.effect = "ask" - }), - // Without the rules, the grant must not decide alone. - Effect.catchCause((cause) => - Effect.logWarning("Browser permission evaluation failed", cause).pipe( - Effect.andThen( - Effect.sync(() => { - event.effect = "deny" - event.message = "Browser permissions could not be read; no action ran." - }), - ), - ), + event.message = "Browser permissions could not be read; no action ran." + }), ), ), - ) - // The grant comes last, so core would list the browser tools and skill to an agent whose own rules deny the whole - // browser, and only the hook above would refuse their calls. Restating the deny after the grant hides them from that - // agent's steps and Code Mode catalog, and core refuses its calls before any hook runs. An ask or a narrower deny - // keeps them listed, for the hook above to decide each call. + ), + ) + }) + // The grant comes last, so without these denies core would list the browser tools and skill to an agent whose own + // rules deny them, and only the hook above would refuse their calls. A deny added here is evaluated after the grant: + // it hides them from that agent's steps and Code Mode catalog, and core refuses their calls before any hook runs. An + // ask or a narrower deny keeps them listed, for the hook above to decide each call. The skill is denied while no + // desktop is attached, or when the agent is denied the whole browser, only while the registered `browser` skill is + // the built-in one: a person's own skill of that name follows their rules alone. yield* ctx.permission.hook("experimental.rules", (event) => - Effect.sync(() => { - if (!BrowserMachine.deniesBrowser(rulesFor({ permissions: event.session }, event.agent))) return - event.rules.push(...BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "deny" as const }))) - }), + ctx.skill.list().pipe( + Effect.map((skills) => skills.data.some((skill) => skill.id === BrowserSkill.id && skill.path === BrowserSkill.info.path)), + // When the skills cannot be read, treat the skill as the built-in one, which hides it rather than shows it. + Effect.orElseSucceed(() => true), + Effect.map((builtin) => { + const rules = rulesFor({ permissions: event.session }, event.agent) + const browser = BrowserMachine.deniesBrowser(rules) + if (browser) event.deny.push({ action: "browser", resource: "*" }) + if ( + BrowserMachine.selectRule(rules, "skill", BrowserSkill.id)?.effect === "deny" || + (builtin && (browser || !event.session.some(BrowserMachine.isGrant))) + ) + event.deny.push({ action: "skill", resource: BrowserSkill.id }) + }), + ), ) // Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes. const work = yield* Scope.make() diff --git a/packages/plugin-browser/src/machine.ts b/packages/plugin-browser/src/machine.ts index 1be273c4c6d..42798d374fe 100644 --- a/packages/plugin-browser/src/machine.ts +++ b/packages/plugin-browser/src/machine.ts @@ -576,17 +576,21 @@ export function isGrant(rule: Permission.Rule) { } /** - * The rule that decides `browser` on `operation`, picked as core's `Permission.evaluate` picks it: the last rule whose + * The rule that decides `action` on `resource`, picked as core's `Permission.evaluate` picks it: the last rule whose * action and resource patterns both match. Undefined when none matches. */ -export function selectBrowserRule(rules: readonly Permission.Rule[], operation: string) { +export function selectRule(rules: readonly Permission.Rule[], action: string, resource: string) { const ignoreCase = process.platform === "win32" return rules.findLast( - (rule) => - Wildcard.match("browser", rule.action, ignoreCase) && Wildcard.match(operation, rule.resource, ignoreCase), + (rule) => Wildcard.match(action, rule.action, ignoreCase) && Wildcard.match(resource, rule.resource, ignoreCase), ) } +/** The rule that decides `browser` on `operation`. */ +export function selectBrowserRule(rules: readonly Permission.Rule[], operation: string) { + return selectRule(rules, "browser", operation) +} + /** Whether `rules` deny the whole browser, which is when core stops listing the browser tools. */ export function deniesBrowser(rules: readonly Permission.Rule[]) { return Permission.deniesAll("browser", rules, process.platform === "win32") From 08273592834f8544cbfaeaa819dea981b6cb67e0 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:51:29 +1000 Subject: [PATCH 18/44] fix(core): keep one Code Mode catalog per visible tool set Tool.snapshot cached one Code Mode catalog, keyed by the registry revision and the visible tool names. Two sessions whose agents see different tool sets alternate steps, for example an agent denied the browser and one that is not, or an attached parent and its children. Each such step rebuilt the inventory, catalog, Code Mode definition and search index. Measured on Windows with 3,000 tools in one namespace plus the 45 browser tools, median of 20 alternating steps: snapshot went from 92.7 ms to 1.3 ms. A step that hits the cache costs 0.8 ms either way. Rendering costs about 1 ms and the first search about 2.5 ms, in both versions. The cache is now a map keyed by the visible names. It holds at most 8 entries, removes the least recently used first, and is cleared when the registry changes, as the single entry was. An entry built from an older registry revision is never served: the stored data must be the current one. Test: alternating two visible sets returns the same catalog object for each, and a registry change rebuilds it. --- packages/core/src/tool.ts | 39 +++++++++++++++--------- packages/core/test/tool-registry.test.ts | 22 +++++++++++++ 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 91ad1246de5..e88aa73b0af 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -183,15 +183,17 @@ const layer = Layer.effect( const run = (tool: Tool.Info, name: string, input: unknown, context: Tool.Context) => beforeExecute(name, input, context).pipe(Effect.flatMap((event) => executeTool(tool, name, event.input, context))) - let catalog: - | { - data: Data - names: string - inventory: CodeModeTool.Inventory - value: CodeModeCatalog.Inventory - definition: ToolDefinition - } - | undefined + // Keyed by the visible tool names. Sessions whose agents see different tool sets, such as one denied the browser + // and one not, alternate steps; with one entry each step rebuilt a large catalog (about 90 ms for 3,000 tools). + const catalogs = new Map< + string, + { + data: Data + inventory: CodeModeTool.Inventory + value: CodeModeCatalog.Inventory + definition: ToolDefinition + } + >() const state = State.create<Data, Editor>({ name: "tool", initial: () => ({ @@ -232,7 +234,7 @@ const layer = Layer.effect( }, }), notify: (value) => { - catalog = undefined + catalogs.clear() return Effect.forEach( value.errors, ({ kind, name, namespace, error }) => @@ -269,7 +271,8 @@ const layer = Layer.effect( // Discovery is immutable for a registry revision and visible tool set. Keep executors // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog // are cached by identity, and the execute tool's definition across steps. - const cached = catalog?.data === data && catalog.names === names ? catalog : undefined + const entry = catalogs.get(names) + const cached = entry?.data === data ? entry : undefined const codeModeInventory = cached?.inventory ?? { tools: codeModeTools, namespaces: data.namespaces } const codeModeTool = codeModeEnabled ? CodeModeTool.create( @@ -282,14 +285,17 @@ const layer = Layer.effect( ? undefined : (cached?.value ?? CodeModeTool.catalog(codeModeInventory)) const codeModeDefinition = codeModeTool && (cached?.definition ?? definition(codeModeTool)) - if (codeModeCatalog && codeModeDefinition) - catalog = { + if (codeModeCatalog && codeModeDefinition) { + // Least recently used goes first: a hit moves its entry to the end. + catalogs.delete(names) + catalogs.set(names, { data, - names, inventory: codeModeInventory, value: codeModeCatalog, definition: codeModeDefinition, - } + }) + if (catalogs.size > CATALOG_CACHE_SIZE) catalogs.delete(catalogs.keys().next().value!) + } return { ...(codeModeCatalog === undefined ? {} : { codeModeCatalog }), definitions: [ @@ -381,6 +387,9 @@ function commit(editor: Data, id: string, input: Tool.Info & { readonly id: stri editor.definitions.set(id, registered.success) } +/** Visible tool sets whose Code Mode catalog stays prepared. */ +const CATALOG_CACHE_SIZE = 8 + const whollyDisabled = (action: string, rules: Permission.Ruleset) => Permission.deniesAll(action, rules, process.platform === "win32") diff --git a/packages/core/test/tool-registry.test.ts b/packages/core/test/tool-registry.test.ts index 2a62821caa4..7439d0fbfe9 100644 --- a/packages/core/test/tool-registry.test.ts +++ b/packages/core/test/tool-registry.test.ts @@ -529,6 +529,28 @@ describe("Tool", () => { }), ) + it.effect("keeps the catalog of each visible tool set while sessions alternate, until the registry changes", () => + Effect.gen(function* () { + const service = yield* Tool.Service + yield* service.transform((editor) => { + editor.add({ ...make(), options: { namespace: "acme" } }) + editor.add({ ...constant("page"), options: { namespace: "web", permission: "web" } }) + }) + const denied: Permission.Ruleset = [{ action: "web", resource: "*", effect: "deny" }] + const all = yield* service.snapshot() + const narrowed = yield* service.snapshot(denied) + expect(codeModeListings(narrowed.codeModeCatalog!).map((tool) => tool.path)).toEqual(["acme.echo"]) + // Each set's prepared catalog is reused, not rebuilt, when the other set's session ran in between. + expect((yield* service.snapshot()).codeModeCatalog).toBe(all.codeModeCatalog!) + expect((yield* service.snapshot(denied)).codeModeCatalog).toBe(narrowed.codeModeCatalog!) + + yield* service.transform((editor) => editor.add({ ...constant("other"), options: { namespace: "acme" } })) + const changed = yield* service.snapshot() + expect(changed.codeModeCatalog).not.toBe(all.codeModeCatalog) + expect(codeModeListings(changed.codeModeCatalog!).map((tool) => tool.path)).toContain("acme.constant") + }), + ) + it.effect("retains namespace descriptions in executable snapshots after appended transforms", () => Effect.gen(function* () { const service = yield* Tool.Service From 0a61901570b67470a0883fa385b999ab04389acf Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:51:30 +1000 Subject: [PATCH 19/44] fix(browser): say in the site popover that permissions decide agent access The site popover always said "Agent can use this page". That is false when the session's current agent is denied the browser. The pane cannot know the true state without a new server call: - The attach exchange and the synced session data carry the session's rules, grant included. - agent.list returns each agent's rules after the browser plugin appends its default deny, so every agent looks denied there. - No endpoint returns a session's listed tools. The text is now true in both cases. Title: "Agents allowed the browser can use this page". Description: "They can read the page, run scripts, and fill in forms. Your browser permission decides which agents can." The 62 translations of the old claim are removed, so those locales show the English text until they are translated, instead of a stale statement. --- packages/gui-plugins/src/browser/i18n/am.ts | 2 -- packages/gui-plugins/src/browser/i18n/ar.ts | 2 -- packages/gui-plugins/src/browser/i18n/az.ts | 2 -- packages/gui-plugins/src/browser/i18n/bg.ts | 2 -- packages/gui-plugins/src/browser/i18n/bn.ts | 2 -- packages/gui-plugins/src/browser/i18n/br.ts | 2 -- packages/gui-plugins/src/browser/i18n/bs.ts | 2 -- packages/gui-plugins/src/browser/i18n/ca.ts | 2 -- packages/gui-plugins/src/browser/i18n/cs.ts | 2 -- packages/gui-plugins/src/browser/i18n/da.ts | 2 -- packages/gui-plugins/src/browser/i18n/de.ts | 2 -- packages/gui-plugins/src/browser/i18n/dv.ts | 2 -- packages/gui-plugins/src/browser/i18n/dz.ts | 2 -- packages/gui-plugins/src/browser/i18n/el.ts | 2 -- packages/gui-plugins/src/browser/i18n/en.ts | 5 +++-- packages/gui-plugins/src/browser/i18n/es.ts | 2 -- packages/gui-plugins/src/browser/i18n/et.ts | 2 -- packages/gui-plugins/src/browser/i18n/fa.ts | 2 -- packages/gui-plugins/src/browser/i18n/fi.ts | 2 -- packages/gui-plugins/src/browser/i18n/fo.ts | 2 -- packages/gui-plugins/src/browser/i18n/fr.ts | 2 -- packages/gui-plugins/src/browser/i18n/he.ts | 2 -- packages/gui-plugins/src/browser/i18n/hi.ts | 2 -- packages/gui-plugins/src/browser/i18n/hr.ts | 2 -- packages/gui-plugins/src/browser/i18n/hu.ts | 2 -- packages/gui-plugins/src/browser/i18n/hy.ts | 2 -- packages/gui-plugins/src/browser/i18n/id.ts | 2 -- packages/gui-plugins/src/browser/i18n/is.ts | 2 -- packages/gui-plugins/src/browser/i18n/it.ts | 2 -- packages/gui-plugins/src/browser/i18n/ja.ts | 2 -- packages/gui-plugins/src/browser/i18n/ka.ts | 2 -- packages/gui-plugins/src/browser/i18n/km.ts | 2 -- packages/gui-plugins/src/browser/i18n/ko.ts | 2 -- packages/gui-plugins/src/browser/i18n/lo.ts | 2 -- packages/gui-plugins/src/browser/i18n/lt.ts | 2 -- packages/gui-plugins/src/browser/i18n/lv.ts | 2 -- packages/gui-plugins/src/browser/i18n/mk.ts | 2 -- packages/gui-plugins/src/browser/i18n/mn.ts | 2 -- packages/gui-plugins/src/browser/i18n/ms.ts | 2 -- packages/gui-plugins/src/browser/i18n/my.ts | 3 --- packages/gui-plugins/src/browser/i18n/ne.ts | 2 -- packages/gui-plugins/src/browser/i18n/nl.ts | 2 -- packages/gui-plugins/src/browser/i18n/no.ts | 2 -- packages/gui-plugins/src/browser/i18n/pa.ts | 2 -- packages/gui-plugins/src/browser/i18n/pl.ts | 2 -- packages/gui-plugins/src/browser/i18n/ro.ts | 2 -- packages/gui-plugins/src/browser/i18n/ru.ts | 2 -- packages/gui-plugins/src/browser/i18n/si.ts | 2 -- packages/gui-plugins/src/browser/i18n/sk.ts | 2 -- packages/gui-plugins/src/browser/i18n/sl.ts | 2 -- packages/gui-plugins/src/browser/i18n/sq.ts | 2 -- packages/gui-plugins/src/browser/i18n/sr.ts | 2 -- packages/gui-plugins/src/browser/i18n/sv.ts | 2 -- packages/gui-plugins/src/browser/i18n/tg.ts | 2 -- packages/gui-plugins/src/browser/i18n/th.ts | 2 -- packages/gui-plugins/src/browser/i18n/tk.ts | 2 -- packages/gui-plugins/src/browser/i18n/tr.ts | 2 -- packages/gui-plugins/src/browser/i18n/uk.ts | 2 -- packages/gui-plugins/src/browser/i18n/ur.ts | 2 -- packages/gui-plugins/src/browser/i18n/uz.ts | 2 -- packages/gui-plugins/src/browser/i18n/vi.ts | 2 -- packages/gui-plugins/src/browser/i18n/zh.ts | 2 -- packages/gui-plugins/src/browser/i18n/zht.ts | 2 -- 63 files changed, 3 insertions(+), 127 deletions(-) diff --git a/packages/gui-plugins/src/browser/i18n/am.ts b/packages/gui-plugins/src/browser/i18n/am.ts index b0c340e1041..128652dd5ab 100644 --- a/packages/gui-plugins/src/browser/i18n/am.ts +++ b/packages/gui-plugins/src/browser/i18n/am.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "አጽዳ", "site.permissions": "ፍቃዶች ታግደዋል", "site.permissions.description": "ካሜራ፣ ማይክሮፎን፣ አካባቢ እና ማሳወቂያዎች በዚህ አሳሽ ውስጥ አይሰሩም።", - "site.agent": "ወኪሉ ይህን ገጽ መጠቀም ይችላል", - "site.agent.description": "ገጹን ማንበብ፣ ስክሪፕቶችን ማሄድ እና ቅጾችን መሙላት ይችላል።", "page.add": "ገጹን ወደ ክፍለ ጊዜ አክል", "page.placeholder": "ስለዚህ ገጽ አውድ ያክሉ", "external.open": "በስርዓቱ አሳሽ ውስጥ ክፈት", diff --git a/packages/gui-plugins/src/browser/i18n/ar.ts b/packages/gui-plugins/src/browser/i18n/ar.ts index f1c4e822859..5b346a538c7 100644 --- a/packages/gui-plugins/src/browser/i18n/ar.ts +++ b/packages/gui-plugins/src/browser/i18n/ar.ts @@ -51,8 +51,6 @@ export default { "site.cookies.clear": "مسح", "site.permissions": "الأذونات محظورة", "site.permissions.description": "لا تعمل الكاميرا والميكروفون والموقع والإشعارات في هذا المتصفح.", - "site.agent": "يمكن للوكيل استخدام هذه الصفحة", - "site.agent.description": "يمكنه قراءة الصفحة وتشغيل البرامج النصية وملء النماذج.", "page.add": "إضافة الصفحة إلى الجلسة", "page.placeholder": "أضف سياقًا عن هذه الصفحة", "external.open": "فتح في متصفح النظام", diff --git a/packages/gui-plugins/src/browser/i18n/az.ts b/packages/gui-plugins/src/browser/i18n/az.ts index a07ac3964a4..24c7aa9fdc2 100644 --- a/packages/gui-plugins/src/browser/i18n/az.ts +++ b/packages/gui-plugins/src/browser/i18n/az.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Təmizlə", "site.permissions": "İcazələr bloklanıb", "site.permissions.description": "Kamera, mikrofon, məkan və bildirişlər bu brauzerdə işləmir.", - "site.agent": "Agent bu səhifədən istifadə edə bilər", - "site.agent.description": "O, səhifəni oxuya, skriptlər işlədə və formaları doldura bilər.", "page.add": "Səhifəni sessiyaya əlavə et", "page.placeholder": "Bu səhifə haqqında kontekst əlavə edin", "external.open": "Sistem brauzerində aç", diff --git a/packages/gui-plugins/src/browser/i18n/bg.ts b/packages/gui-plugins/src/browser/i18n/bg.ts index 5e3643fe619..269d48f35fb 100644 --- a/packages/gui-plugins/src/browser/i18n/bg.ts +++ b/packages/gui-plugins/src/browser/i18n/bg.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Изчистване", "site.permissions": "Разрешенията са блокирани", "site.permissions.description": "Камерата, микрофонът, местоположението и известията не работят в този браузър.", - "site.agent": "Агентът може да използва тази страница", - "site.agent.description": "Може да чете страницата, да изпълнява скриптове и да попълва формуляри.", "page.add": "Добавяне на страницата към сесията", "page.placeholder": "Добавете контекст за тази страница", "external.open": "Отваряне в системния браузър", diff --git a/packages/gui-plugins/src/browser/i18n/bn.ts b/packages/gui-plugins/src/browser/i18n/bn.ts index d940c633186..6e5b9ede9f4 100644 --- a/packages/gui-plugins/src/browser/i18n/bn.ts +++ b/packages/gui-plugins/src/browser/i18n/bn.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "পরিষ্কার করুন", "site.permissions": "অনুমতিগুলো ব্লক করা আছে", "site.permissions.description": "এই ব্রাউজারে ক্যামেরা, মাইক্রোফোন, অবস্থান এবং বিজ্ঞপ্তি কাজ করে না।", - "site.agent": "এজেন্ট এই পৃষ্ঠা ব্যবহার করতে পারে", - "site.agent.description": "এটি পৃষ্ঠা পড়তে, স্ক্রিপ্ট চালাতে এবং ফর্ম পূরণ করতে পারে।", "page.add": "সেশনে পৃষ্ঠা যোগ করুন", "page.placeholder": "এই পৃষ্ঠা সম্পর্কে প্রসঙ্গ যোগ করুন", "external.open": "সিস্টেম ব্রাউজারে খুলুন", diff --git a/packages/gui-plugins/src/browser/i18n/br.ts b/packages/gui-plugins/src/browser/i18n/br.ts index 746224d3414..abc20656ef8 100644 --- a/packages/gui-plugins/src/browser/i18n/br.ts +++ b/packages/gui-plugins/src/browser/i18n/br.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Limpar", "site.permissions": "As permissões estão bloqueadas", "site.permissions.description": "Câmera, microfone, localização e notificações não funcionam neste navegador.", - "site.agent": "O agente pode usar esta página", - "site.agent.description": "Ele pode ler a página, executar scripts e preencher formulários.", "page.add": "Adicionar página à sessão", "page.placeholder": "Adicione contexto sobre esta página", "external.open": "Abrir no navegador do sistema", diff --git a/packages/gui-plugins/src/browser/i18n/bs.ts b/packages/gui-plugins/src/browser/i18n/bs.ts index 0ff3721f49b..cd1f3f5298e 100644 --- a/packages/gui-plugins/src/browser/i18n/bs.ts +++ b/packages/gui-plugins/src/browser/i18n/bs.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Obriši", "site.permissions": "Dozvole su blokirane", "site.permissions.description": "Kamera, mikrofon, lokacija i obavještenja ne rade u ovom pregledniku.", - "site.agent": "Agent može koristiti ovu stranicu", - "site.agent.description": "Može čitati stranicu, pokretati skripte i popunjavati obrasce.", "page.add": "Dodaj stranicu u sesiju", "page.placeholder": "Dodajte kontekst o ovoj stranici", "external.open": "Otvori u sistemskom pregledniku", diff --git a/packages/gui-plugins/src/browser/i18n/ca.ts b/packages/gui-plugins/src/browser/i18n/ca.ts index cfb0ddc548b..0226e4c4d3a 100644 --- a/packages/gui-plugins/src/browser/i18n/ca.ts +++ b/packages/gui-plugins/src/browser/i18n/ca.ts @@ -48,8 +48,6 @@ export default { "site.permissions": "Els permisos estan bloquejats", "site.permissions.description": "La càmera, el micròfon, la ubicació i les notificacions no funcionen en aquest navegador.", - "site.agent": "L'agent pot utilitzar aquesta pàgina", - "site.agent.description": "Pot llegir la pàgina, executar scripts i emplenar formularis.", "page.add": "Afegeix la pàgina a la sessió", "page.placeholder": "Afegeix context sobre aquesta pàgina", "external.open": "Obre al navegador del sistema", diff --git a/packages/gui-plugins/src/browser/i18n/cs.ts b/packages/gui-plugins/src/browser/i18n/cs.ts index db709922ea5..4ee3b2b1ae5 100644 --- a/packages/gui-plugins/src/browser/i18n/cs.ts +++ b/packages/gui-plugins/src/browser/i18n/cs.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Vymazat", "site.permissions": "Oprávnění jsou blokována", "site.permissions.description": "Kamera, mikrofon, poloha a oznámení v tomto prohlížeči nefungují.", - "site.agent": "Agent může tuto stránku používat", - "site.agent.description": "Může číst stránku, spouštět skripty a vyplňovat formuláře.", "page.add": "Přidat stránku do relace", "page.placeholder": "Přidejte kontext k této stránce", "external.open": "Otevřít v systémovém prohlížeči", diff --git a/packages/gui-plugins/src/browser/i18n/da.ts b/packages/gui-plugins/src/browser/i18n/da.ts index 3129c196f80..9ccc3759d8f 100644 --- a/packages/gui-plugins/src/browser/i18n/da.ts +++ b/packages/gui-plugins/src/browser/i18n/da.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Ryd", "site.permissions": "Tilladelser er blokeret", "site.permissions.description": "Kamera, mikrofon, placering og notifikationer virker ikke i denne browser.", - "site.agent": "Agenten kan bruge denne side", - "site.agent.description": "Den kan læse siden, køre scripts og udfylde formularer.", "page.add": "Føj side til session", "page.placeholder": "Tilføj kontekst om denne side", "external.open": "Åbn i systembrowser", diff --git a/packages/gui-plugins/src/browser/i18n/de.ts b/packages/gui-plugins/src/browser/i18n/de.ts index c46a220726b..0928d63392e 100644 --- a/packages/gui-plugins/src/browser/i18n/de.ts +++ b/packages/gui-plugins/src/browser/i18n/de.ts @@ -49,8 +49,6 @@ export default { "site.permissions": "Berechtigungen sind blockiert", "site.permissions.description": "Kamera, Mikrofon, Standort und Benachrichtigungen funktionieren in diesem Browser nicht.", - "site.agent": "Agent kann diese Seite verwenden", - "site.agent.description": "Er kann die Seite lesen, Skripte ausführen und Formulare ausfüllen.", "page.add": "Seite zur Sitzung hinzufügen", "page.placeholder": "Kontext zu dieser Seite hinzufügen", "external.open": "Im Systembrowser öffnen", diff --git a/packages/gui-plugins/src/browser/i18n/dv.ts b/packages/gui-plugins/src/browser/i18n/dv.ts index 59330f80118..e59e82f530c 100644 --- a/packages/gui-plugins/src/browser/i18n/dv.ts +++ b/packages/gui-plugins/src/browser/i18n/dv.ts @@ -48,8 +48,6 @@ export default { "site.permissions": "ހުއްދަތައް ބްލޮކްކޮށްފައި", "site.permissions.description": "މި ބްރައުޒަރުގައި ކެމެރާ، މައިކްރޮފޯން، ލޮކޭޝަން އަދި ނޮޓިފިކޭޝަންތައް މަސައްކަތެއް ނުކުރެއެވެ.", - "site.agent": "އޭޖެންޓަށް މި ޕޭޖް ބޭނުންކުރެވޭނެ", - "site.agent.description": "އެއަށް ޕޭޖް ކިޔުމާއި، ސްކްރިޕްޓް ހިންގުމާއި، ފޯމު ފުރުން ކުރެވޭނެއެވެ.", "page.add": "ޕޭޖް ސެޝަނަށް އިތުރުކުރާ", "page.placeholder": "މި ޕޭޖާ ބެހޭ ކޮންޓެކްސްޓް އިތުރުކުރާ", "external.open": "ސިސްޓަމް ބްރައުޒަރުގައި ހުޅުވާ", diff --git a/packages/gui-plugins/src/browser/i18n/dz.ts b/packages/gui-plugins/src/browser/i18n/dz.ts index 32284417055..ed3cd3f986e 100644 --- a/packages/gui-plugins/src/browser/i18n/dz.ts +++ b/packages/gui-plugins/src/browser/i18n/dz.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "བསལ།", "site.permissions": "གནང་བ་ཚུ་ བཀག་ཡོདཔ།", "site.permissions.description": "པར་ཆས་དང་ སྒྲ་དུང་ ས་གནས་ བརྡ་བསྐུལ་ཚུ་ བརའུ་ཟར་འདི་ནང་ ལཱ་མི་འབད།", - "site.agent": "ལས་ཚབ་ཀྱིས་ ཤོག་ལེབ་འདི་ལག་ལེན་འཐབ་ཚུགས།", - "site.agent.description": "དེ་གིས་ ཤོག་ལེབ་ལྷག་ནི་དང་ ཡིག་ཚུགས་གཡོག་བཀོལ་ནི་ འབྲི་ཤོག་བཀང་ནི་ཚུ་ འབད་ཚུགས།", "page.add": "ཤོག་ལེབ་འདི་ ལཱ་ཡུན་ལུ་ཁ་སྐོང་།", "page.placeholder": "ཤོག་ལེབ་འདི་གི་སྐོར་ལས་ སྐབས་དོན་ཁ་སྐོང་རྐྱབས།", "external.open": "རིམ་ལུགས་བརའུ་ཟར་ནང་ཁ་ཕྱེ།", diff --git a/packages/gui-plugins/src/browser/i18n/el.ts b/packages/gui-plugins/src/browser/i18n/el.ts index 2b571c0e981..f1916588d93 100644 --- a/packages/gui-plugins/src/browser/i18n/el.ts +++ b/packages/gui-plugins/src/browser/i18n/el.ts @@ -49,8 +49,6 @@ export default { "site.permissions": "Τα δικαιώματα είναι αποκλεισμένα", "site.permissions.description": "Η κάμερα, το μικρόφωνο, η τοποθεσία και οι ειδοποιήσεις δεν λειτουργούν σε αυτό το πρόγραμμα περιήγησης.", - "site.agent": "Ο πράκτορας μπορεί να χρησιμοποιήσει αυτήν τη σελίδα", - "site.agent.description": "Μπορεί να διαβάσει τη σελίδα, να εκτελέσει σενάρια και να συμπληρώσει φόρμες.", "page.add": "Προσθήκη σελίδας στη συνεδρία", "page.placeholder": "Προσθέστε περιβάλλον για αυτήν τη σελίδα", "external.open": "Άνοιγμα στο πρόγραμμα περιήγησης του συστήματος", diff --git a/packages/gui-plugins/src/browser/i18n/en.ts b/packages/gui-plugins/src/browser/i18n/en.ts index 45aaa635c84..14fc716bf54 100644 --- a/packages/gui-plugins/src/browser/i18n/en.ts +++ b/packages/gui-plugins/src/browser/i18n/en.ts @@ -59,8 +59,9 @@ export default { "site.permissions": "Permissions", "site.permissions.description": "Sites ask before they use your camera, microphone, location, notifications, or clipboard. Change saved answers in Browser settings.", - "site.agent": "Agent can use this page", - "site.agent.description": "It can read the page, run scripts, and fill in forms.", + "site.agent": "Agents allowed the browser can use this page", + "site.agent.description": + "They can read the page, run scripts, and fill in forms. Your browser permission decides which agents can.", "page.add": "Add page to session", "page.placeholder": "Add context about this page", "external.open": "Open in system browser", diff --git a/packages/gui-plugins/src/browser/i18n/es.ts b/packages/gui-plugins/src/browser/i18n/es.ts index 543ca9cabfc..e49a6a20243 100644 --- a/packages/gui-plugins/src/browser/i18n/es.ts +++ b/packages/gui-plugins/src/browser/i18n/es.ts @@ -48,8 +48,6 @@ export default { "site.permissions": "Los permisos están bloqueados", "site.permissions.description": "La cámara, el micrófono, la ubicación y las notificaciones no funcionan en este navegador.", - "site.agent": "El agente puede usar esta página", - "site.agent.description": "Puede leer la página, ejecutar scripts y rellenar formularios.", "page.add": "Añadir página a la sesión", "page.placeholder": "Añade contexto sobre esta página", "external.open": "Abrir en el navegador del sistema", diff --git a/packages/gui-plugins/src/browser/i18n/et.ts b/packages/gui-plugins/src/browser/i18n/et.ts index ee367d06066..c7e6feb3a36 100644 --- a/packages/gui-plugins/src/browser/i18n/et.ts +++ b/packages/gui-plugins/src/browser/i18n/et.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Tühjenda", "site.permissions": "Load on blokeeritud", "site.permissions.description": "Kaamera, mikrofon, asukoht ja teavitused selles brauseris ei tööta.", - "site.agent": "Agent saab seda lehte kasutada", - "site.agent.description": "See saab lehte lugeda, skripte käivitada ja vorme täita.", "page.add": "Lisa leht seansile", "page.placeholder": "Lisa selle lehe kohta konteksti", "external.open": "Ava süsteemi brauseris", diff --git a/packages/gui-plugins/src/browser/i18n/fa.ts b/packages/gui-plugins/src/browser/i18n/fa.ts index 7272eaab10e..a5779fc66b7 100644 --- a/packages/gui-plugins/src/browser/i18n/fa.ts +++ b/packages/gui-plugins/src/browser/i18n/fa.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "پاک کردن", "site.permissions": "مجوزها مسدود هستند", "site.permissions.description": "دوربین، میکروفون، موقعیت مکانی و اعلان‌ها در این مرورگر کار نمی‌کنند.", - "site.agent": "عامل می‌تواند از این صفحه استفاده کند", - "site.agent.description": "می‌تواند صفحه را بخواند، اسکریپت اجرا کند و فرم‌ها را پر کند.", "page.add": "افزودن صفحه به جلسه", "page.placeholder": "زمینه‌ای درباره این صفحه اضافه کنید", "external.open": "باز کردن در مرورگر سیستم", diff --git a/packages/gui-plugins/src/browser/i18n/fi.ts b/packages/gui-plugins/src/browser/i18n/fi.ts index 7518e459c8f..c050900ad31 100644 --- a/packages/gui-plugins/src/browser/i18n/fi.ts +++ b/packages/gui-plugins/src/browser/i18n/fi.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Tyhjennä", "site.permissions": "Käyttöoikeudet on estetty", "site.permissions.description": "Kamera, mikrofoni, sijainti ja ilmoitukset eivät toimi tässä selaimessa.", - "site.agent": "Agentti voi käyttää tätä sivua", - "site.agent.description": "Se voi lukea sivua, suorittaa skriptejä ja täyttää lomakkeita.", "page.add": "Lisää sivu istuntoon", "page.placeholder": "Lisää kontekstia tästä sivusta", "external.open": "Avaa järjestelmän selaimessa", diff --git a/packages/gui-plugins/src/browser/i18n/fo.ts b/packages/gui-plugins/src/browser/i18n/fo.ts index caebdbec627..651d9384d60 100644 --- a/packages/gui-plugins/src/browser/i18n/fo.ts +++ b/packages/gui-plugins/src/browser/i18n/fo.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Rudda", "site.permissions": "Loyvi eru forðað", "site.permissions.description": "Myndatól, mikrofon, staðseting og fráboðanir virka ikki í hesum kaganum.", - "site.agent": "Agenturin kann brúka hesa síðuna", - "site.agent.description": "Hann kann lesa síðuna, koyra skript og fylla út formularar.", "page.add": "Legg síðu afturat setuni", "page.placeholder": "Legg samanhang um hesa síðuna afturat", "external.open": "Lat upp í skipanarkaganum", diff --git a/packages/gui-plugins/src/browser/i18n/fr.ts b/packages/gui-plugins/src/browser/i18n/fr.ts index 2dd51d2c62c..453ea080408 100644 --- a/packages/gui-plugins/src/browser/i18n/fr.ts +++ b/packages/gui-plugins/src/browser/i18n/fr.ts @@ -50,8 +50,6 @@ export default { "site.permissions": "Les permissions sont bloquées", "site.permissions.description": "La caméra, le microphone, la localisation et les notifications ne fonctionnent pas dans ce navigateur.", - "site.agent": "L’agent peut utiliser cette page", - "site.agent.description": "Il peut lire la page, exécuter des scripts et remplir des formulaires.", "page.add": "Ajouter la page à la session", "page.placeholder": "Ajouter du contexte sur cette page", "external.open": "Ouvrir dans le navigateur du système", diff --git a/packages/gui-plugins/src/browser/i18n/he.ts b/packages/gui-plugins/src/browser/i18n/he.ts index ece8f13649b..6b4324a36d7 100644 --- a/packages/gui-plugins/src/browser/i18n/he.ts +++ b/packages/gui-plugins/src/browser/i18n/he.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "נקה", "site.permissions": "ההרשאות חסומות", "site.permissions.description": "מצלמה, מיקרופון, מיקום והתראות אינם פועלים בדפדפן זה.", - "site.agent": "הסוכן יכול להשתמש בדף זה", - "site.agent.description": "הוא יכול לקרוא את הדף, להריץ סקריפטים ולמלא טפסים.", "page.add": "הוסף דף להפעלה", "page.placeholder": "הוסף הקשר על דף זה", "external.open": "פתח בדפדפן המערכת", diff --git a/packages/gui-plugins/src/browser/i18n/hi.ts b/packages/gui-plugins/src/browser/i18n/hi.ts index b0293dab430..0922b854748 100644 --- a/packages/gui-plugins/src/browser/i18n/hi.ts +++ b/packages/gui-plugins/src/browser/i18n/hi.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "साफ़ करें", "site.permissions": "अनुमतियाँ अवरुद्ध हैं", "site.permissions.description": "इस ब्राउज़र में कैमरा, माइक्रोफ़ोन, लोकेशन और सूचनाएँ काम नहीं करतीं।", - "site.agent": "एजेंट इस पेज का उपयोग कर सकता है", - "site.agent.description": "यह पेज पढ़ सकता है, स्क्रिप्ट चला सकता है और फ़ॉर्म भर सकता है।", "page.add": "पेज को सेशन में जोड़ें", "page.placeholder": "इस पेज के बारे में कॉन्टेक्स्ट जोड़ें", "external.open": "सिस्टम ब्राउज़र में खोलें", diff --git a/packages/gui-plugins/src/browser/i18n/hr.ts b/packages/gui-plugins/src/browser/i18n/hr.ts index 28fba4311f1..af5fe3e95a7 100644 --- a/packages/gui-plugins/src/browser/i18n/hr.ts +++ b/packages/gui-plugins/src/browser/i18n/hr.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Očisti", "site.permissions": "Dopuštenja su blokirana", "site.permissions.description": "Kamera, mikrofon, lokacija i obavijesti ne rade u ovom pregledniku.", - "site.agent": "Agent može koristiti ovu stranicu", - "site.agent.description": "Može čitati stranicu, pokretati skripte i ispunjavati obrasce.", "page.add": "Dodaj stranicu u sesiju", "page.placeholder": "Dodajte kontekst o ovoj stranici", "external.open": "Otvori u pregledniku sustava", diff --git a/packages/gui-plugins/src/browser/i18n/hu.ts b/packages/gui-plugins/src/browser/i18n/hu.ts index d5a3cf45752..3838502c542 100644 --- a/packages/gui-plugins/src/browser/i18n/hu.ts +++ b/packages/gui-plugins/src/browser/i18n/hu.ts @@ -49,8 +49,6 @@ export default { "site.permissions": "Az engedélyek le vannak tiltva", "site.permissions.description": "A kamera, a mikrofon, a helymeghatározás és az értesítések nem működnek ebben a böngészőben.", - "site.agent": "Az ügynök használhatja ezt az oldalt", - "site.agent.description": "Elolvashatja az oldalt, szkripteket futtathat és kitölthet űrlapokat.", "page.add": "Oldal hozzáadása a munkamenethez", "page.placeholder": "Kontextus hozzáadása ehhez az oldalhoz", "external.open": "Megnyitás a rendszer böngészőjében", diff --git a/packages/gui-plugins/src/browser/i18n/hy.ts b/packages/gui-plugins/src/browser/i18n/hy.ts index 8527fa0ebdd..2556e37287e 100644 --- a/packages/gui-plugins/src/browser/i18n/hy.ts +++ b/packages/gui-plugins/src/browser/i18n/hy.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Մաքրել", "site.permissions": "Թույլտվություններն արգելափակված են", "site.permissions.description": "Տեսախցիկը, խոսափողը, տեղադրությունը և ծանուցումներն այս դիտարկչում չեն աշխատում։", - "site.agent": "Գործակալը կարող է օգտագործել այս էջը", - "site.agent.description": "Այն կարող է կարդալ էջը, գործարկել սկրիպտներ և լրացնել ձևեր։", "page.add": "Ավելացնել էջը նիստին", "page.placeholder": "Ավելացրեք համատեքստ այս էջի մասին", "external.open": "Բացել համակարգի դիտարկչում", diff --git a/packages/gui-plugins/src/browser/i18n/id.ts b/packages/gui-plugins/src/browser/i18n/id.ts index d79ca87d422..1a0f745005d 100644 --- a/packages/gui-plugins/src/browser/i18n/id.ts +++ b/packages/gui-plugins/src/browser/i18n/id.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Hapus", "site.permissions": "Izin diblokir", "site.permissions.description": "Kamera, mikrofon, lokasi, dan notifikasi tidak berfungsi di peramban ini.", - "site.agent": "Agen dapat menggunakan halaman ini", - "site.agent.description": "Agen dapat membaca halaman, menjalankan skrip, dan mengisi formulir.", "page.add": "Tambahkan halaman ke sesi", "page.placeholder": "Tambahkan konteks tentang halaman ini", "external.open": "Buka di peramban sistem", diff --git a/packages/gui-plugins/src/browser/i18n/is.ts b/packages/gui-plugins/src/browser/i18n/is.ts index de3d285ba66..d24e04cadf9 100644 --- a/packages/gui-plugins/src/browser/i18n/is.ts +++ b/packages/gui-plugins/src/browser/i18n/is.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Hreinsa", "site.permissions": "Heimildir eru lokaðar", "site.permissions.description": "Myndavél, hljóðnemi, staðsetning og tilkynningar virka ekki í þessum vafra.", - "site.agent": "Fulltrúinn getur notað þessa síðu", - "site.agent.description": "Hann getur lesið síðuna, keyrt skriftur og fyllt út eyðublöð.", "page.add": "Bæta síðu við setu", "page.placeholder": "Bættu við samhengi um þessa síðu", "external.open": "Opna í kerfisvafra", diff --git a/packages/gui-plugins/src/browser/i18n/it.ts b/packages/gui-plugins/src/browser/i18n/it.ts index cef21ecbbe5..72110b05375 100644 --- a/packages/gui-plugins/src/browser/i18n/it.ts +++ b/packages/gui-plugins/src/browser/i18n/it.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Cancella", "site.permissions": "Le autorizzazioni sono bloccate", "site.permissions.description": "Fotocamera, microfono, posizione e notifiche non funzionano in questo browser.", - "site.agent": "L'agente può usare questa pagina", - "site.agent.description": "Può leggere la pagina, eseguire script e compilare moduli.", "page.add": "Aggiungi pagina alla sessione", "page.placeholder": "Aggiungi contesto su questa pagina", "external.open": "Apri nel browser di sistema", diff --git a/packages/gui-plugins/src/browser/i18n/ja.ts b/packages/gui-plugins/src/browser/i18n/ja.ts index f742031a9f3..9ff48df3a5e 100644 --- a/packages/gui-plugins/src/browser/i18n/ja.ts +++ b/packages/gui-plugins/src/browser/i18n/ja.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "消去", "site.permissions": "権限はブロックされています", "site.permissions.description": "このブラウザーでは、カメラ、マイク、位置情報、通知は機能しません。", - "site.agent": "エージェントはこのページを使用できます", - "site.agent.description": "ページの読み取り、スクリプトの実行、フォームへの入力ができます。", "page.add": "ページをセッションに追加", "page.placeholder": "このページに関するコンテキストを追加", "external.open": "システムのブラウザーで開く", diff --git a/packages/gui-plugins/src/browser/i18n/ka.ts b/packages/gui-plugins/src/browser/i18n/ka.ts index a3290083b70..b410acf9745 100644 --- a/packages/gui-plugins/src/browser/i18n/ka.ts +++ b/packages/gui-plugins/src/browser/i18n/ka.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "გასუფთავება", "site.permissions": "ნებართვები დაბლოკილია", "site.permissions.description": "კამერა, მიკროფონი, მდებარეობა და შეტყობინებები ამ ბრაუზერში არ მუშაობს.", - "site.agent": "აგენტს შეუძლია ამ გვერდის გამოყენება", - "site.agent.description": "მას შეუძლია გვერდის წაკითხვა, სკრიპტების გაშვება და ფორმების შევსება.", "page.add": "გვერდის სესიაში დამატება", "page.placeholder": "დაამატეთ კონტექსტი ამ გვერდის შესახებ", "external.open": "სისტემის ბრაუზერში გახსნა", diff --git a/packages/gui-plugins/src/browser/i18n/km.ts b/packages/gui-plugins/src/browser/i18n/km.ts index e75028d3829..d699143e250 100644 --- a/packages/gui-plugins/src/browser/i18n/km.ts +++ b/packages/gui-plugins/src/browser/i18n/km.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "សម្អាត", "site.permissions": "ការអនុញ្ញាតត្រូវបានរារាំង", "site.permissions.description": "កាមេរ៉ា មីក្រូហ្វូន ទីតាំង និងការជូនដំណឹង មិនដំណើរការក្នុងកម្មវិធីរុករកនេះទេ។", - "site.agent": "ភ្នាក់ងារអាចប្រើទំព័រនេះ", - "site.agent.description": "វាអាចអានទំព័រ ដំណើរការស្គ្រីប និងបំពេញទម្រង់។", "page.add": "បន្ថែមទំព័រទៅសម័យ", "page.placeholder": "បន្ថែមបរិបទអំពីទំព័រនេះ", "external.open": "បើកក្នុងកម្មវិធីរុករកប្រព័ន្ធ", diff --git a/packages/gui-plugins/src/browser/i18n/ko.ts b/packages/gui-plugins/src/browser/i18n/ko.ts index 46334a8e732..6e3762dc0e8 100644 --- a/packages/gui-plugins/src/browser/i18n/ko.ts +++ b/packages/gui-plugins/src/browser/i18n/ko.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "지우기", "site.permissions": "권한이 차단됨", "site.permissions.description": "이 브라우저에서는 카메라, 마이크, 위치, 알림이 작동하지 않습니다.", - "site.agent": "에이전트가 이 페이지를 사용할 수 있음", - "site.agent.description": "페이지를 읽고, 스크립트를 실행하고, 양식을 작성할 수 있습니다.", "page.add": "세션에 페이지 추가", "page.placeholder": "이 페이지에 대한 컨텍스트 추가", "external.open": "시스템 브라우저에서 열기", diff --git a/packages/gui-plugins/src/browser/i18n/lo.ts b/packages/gui-plugins/src/browser/i18n/lo.ts index 706bd0cf2fa..16b92411eda 100644 --- a/packages/gui-plugins/src/browser/i18n/lo.ts +++ b/packages/gui-plugins/src/browser/i18n/lo.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "ລ້າງ", "site.permissions": "ການອະນຸຍາດຖືກບລັອກ", "site.permissions.description": "ກ້ອງ, ໄມໂຄຣໂຟນ, ຕຳແໜ່ງ ແລະການແຈ້ງເຕືອນບໍ່ເຮັດວຽກໃນເບຣາວເຊີນີ້.", - "site.agent": "ຕົວແທນສາມາດໃຊ້ໜ້ານີ້ໄດ້", - "site.agent.description": "ມັນສາມາດອ່ານໜ້າ, ແລ່ນສະຄຣິບ ແລະກອກແບບຟອມໄດ້.", "page.add": "ເພີ່ມໜ້າໃສ່ເຊດຊັນ", "page.placeholder": "ເພີ່ມບໍລິບົດກ່ຽວກັບໜ້ານີ້", "external.open": "ເປີດໃນເບຣາວເຊີຂອງລະບົບ", diff --git a/packages/gui-plugins/src/browser/i18n/lt.ts b/packages/gui-plugins/src/browser/i18n/lt.ts index de30a5932cd..8a34bf05e9e 100644 --- a/packages/gui-plugins/src/browser/i18n/lt.ts +++ b/packages/gui-plugins/src/browser/i18n/lt.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Išvalyti", "site.permissions": "Leidimai užblokuoti", "site.permissions.description": "Kamera, mikrofonas, vietovė ir pranešimai šioje naršyklėje neveikia.", - "site.agent": "Agentas gali naudoti šį puslapį", - "site.agent.description": "Jis gali skaityti puslapį, vykdyti scenarijus ir pildyti formas.", "page.add": "Pridėti puslapį prie seanso", "page.placeholder": "Pridėkite kontekstą apie šį puslapį", "external.open": "Atverti sistemos naršyklėje", diff --git a/packages/gui-plugins/src/browser/i18n/lv.ts b/packages/gui-plugins/src/browser/i18n/lv.ts index e8fdc25bbec..047bde2e337 100644 --- a/packages/gui-plugins/src/browser/i18n/lv.ts +++ b/packages/gui-plugins/src/browser/i18n/lv.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Notīrīt", "site.permissions": "Atļaujas ir bloķētas", "site.permissions.description": "Kamera, mikrofons, atrašanās vieta un paziņojumi šajā pārlūkprogrammā nedarbojas.", - "site.agent": "Aģents var izmantot šo lapu", - "site.agent.description": "Tas var lasīt lapu, izpildīt skriptus un aizpildīt veidlapas.", "page.add": "Pievienot lapu sesijai", "page.placeholder": "Pievienojiet kontekstu par šo lapu", "external.open": "Atvērt sistēmas pārlūkprogrammā", diff --git a/packages/gui-plugins/src/browser/i18n/mk.ts b/packages/gui-plugins/src/browser/i18n/mk.ts index ce006f16ccd..fbadbd7d21a 100644 --- a/packages/gui-plugins/src/browser/i18n/mk.ts +++ b/packages/gui-plugins/src/browser/i18n/mk.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Избриши", "site.permissions": "Дозволите се блокирани", "site.permissions.description": "Камерата, микрофонот, локацијата и известувањата не работат во овој прелистувач.", - "site.agent": "Агентот може да ја користи оваа страница", - "site.agent.description": "Може да ја чита страницата, да извршува скрипти и да пополнува формулари.", "page.add": "Додај ја страницата во сесијата", "page.placeholder": "Додајте контекст за оваа страница", "external.open": "Отвори во системскиот прелистувач", diff --git a/packages/gui-plugins/src/browser/i18n/mn.ts b/packages/gui-plugins/src/browser/i18n/mn.ts index 23e851708ca..32c736669ec 100644 --- a/packages/gui-plugins/src/browser/i18n/mn.ts +++ b/packages/gui-plugins/src/browser/i18n/mn.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Цэвэрлэх", "site.permissions": "Зөвшөөрлүүд хаагдсан", "site.permissions.description": "Камер, микрофон, байршил болон мэдэгдлүүд энэ хөтөч дээр ажиллахгүй.", - "site.agent": "Агент энэ хуудсыг ашиглаж болно", - "site.agent.description": "Хуудсыг уншиж, скрипт ажиллуулж, маягт бөглөж чадна.", "page.add": "Хуудсыг сесст нэмэх", "page.placeholder": "Энэ хуудасны талаар контекст нэмэх", "external.open": "Системийн хөтөч дээр нээх", diff --git a/packages/gui-plugins/src/browser/i18n/ms.ts b/packages/gui-plugins/src/browser/i18n/ms.ts index 6aed84da075..3e872465d5e 100644 --- a/packages/gui-plugins/src/browser/i18n/ms.ts +++ b/packages/gui-plugins/src/browser/i18n/ms.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Kosongkan", "site.permissions": "Kebenaran disekat", "site.permissions.description": "Kamera, mikrofon, lokasi dan pemberitahuan tidak berfungsi dalam pelayar ini.", - "site.agent": "Ejen boleh menggunakan halaman ini", - "site.agent.description": "Ia boleh membaca halaman, menjalankan skrip dan mengisi borang.", "page.add": "Tambah halaman ke sesi", "page.placeholder": "Tambah konteks tentang halaman ini", "external.open": "Buka dalam pelayar sistem", diff --git a/packages/gui-plugins/src/browser/i18n/my.ts b/packages/gui-plugins/src/browser/i18n/my.ts index 17b4d52b117..ad4cd5ded2c 100644 --- a/packages/gui-plugins/src/browser/i18n/my.ts +++ b/packages/gui-plugins/src/browser/i18n/my.ts @@ -48,9 +48,6 @@ export default { "site.permissions": "ခွင့်ပြုချက်များကို ပိတ်ထားသည်", "site.permissions.description": "ဤဘရောက်ဇာတွင် ကင်မရာ၊ မိုက်ခရိုဖုန်း၊ တည်နေရာနှင့် အကြောင်းကြားချက်များ အလုပ်မလုပ်ပါ။", - "site.agent": "အေးဂျင့်သည် ဤစာမျက်နှာကို အသုံးပြုနိုင်သည်", - "site.agent.description": - "၎င်းသည် စာမျက်နှာကို ဖတ်ခြင်း၊ script များ လုပ်ဆောင်ခြင်းနှင့် ဖောင်များ ဖြည့်ခြင်းတို့ ပြုလုပ်နိုင်သည်။", "page.add": "စာမျက်နှာကို စက်ရှင်သို့ ထည့်ရန်", "page.placeholder": "ဤစာမျက်နှာအကြောင်း ဆက်စပ်အချက်အလက် ထည့်ပါ", "external.open": "စနစ်ဘရောက်ဇာတွင် ဖွင့်ရန်", diff --git a/packages/gui-plugins/src/browser/i18n/ne.ts b/packages/gui-plugins/src/browser/i18n/ne.ts index bb2d784024d..f74fd926d5e 100644 --- a/packages/gui-plugins/src/browser/i18n/ne.ts +++ b/packages/gui-plugins/src/browser/i18n/ne.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "खाली गर्नुहोस्", "site.permissions": "अनुमतिहरू अवरुद्ध छन्", "site.permissions.description": "यो ब्राउजरमा क्यामेरा, माइक्रोफोन, स्थान र सूचनाहरू काम गर्दैनन्।", - "site.agent": "एजेन्टले यो पृष्ठ प्रयोग गर्न सक्छ", - "site.agent.description": "यसले पृष्ठ पढ्न, स्क्रिप्ट चलाउन र फारम भर्न सक्छ।", "page.add": "पृष्ठलाई सत्रमा थप्नुहोस्", "page.placeholder": "यो पृष्ठबारे सन्दर्भ थप्नुहोस्", "external.open": "प्रणाली ब्राउजरमा खोल्नुहोस्", diff --git a/packages/gui-plugins/src/browser/i18n/nl.ts b/packages/gui-plugins/src/browser/i18n/nl.ts index fc82dfda060..45f89924033 100644 --- a/packages/gui-plugins/src/browser/i18n/nl.ts +++ b/packages/gui-plugins/src/browser/i18n/nl.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Wissen", "site.permissions": "Machtigingen zijn geblokkeerd", "site.permissions.description": "Camera, microfoon, locatie en meldingen werken niet in deze browser.", - "site.agent": "Agent kan deze pagina gebruiken", - "site.agent.description": "De agent kan de pagina lezen, scripts uitvoeren en formulieren invullen.", "page.add": "Pagina aan sessie toevoegen", "page.placeholder": "Voeg context over deze pagina toe", "external.open": "Openen in systeembrowser", diff --git a/packages/gui-plugins/src/browser/i18n/no.ts b/packages/gui-plugins/src/browser/i18n/no.ts index f3d9cab821e..5e7cbf0b20a 100644 --- a/packages/gui-plugins/src/browser/i18n/no.ts +++ b/packages/gui-plugins/src/browser/i18n/no.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Fjern", "site.permissions": "Tillatelser er blokkert", "site.permissions.description": "Kamera, mikrofon, posisjon og varsler fungerer ikke i denne nettleseren.", - "site.agent": "Agenten kan bruke denne siden", - "site.agent.description": "Den kan lese siden, kjøre skript og fylle ut skjemaer.", "page.add": "Legg til side i økten", "page.placeholder": "Legg til kontekst om denne siden", "external.open": "Åpne i systemets nettleser", diff --git a/packages/gui-plugins/src/browser/i18n/pa.ts b/packages/gui-plugins/src/browser/i18n/pa.ts index e6bd0a7924a..d6254771966 100644 --- a/packages/gui-plugins/src/browser/i18n/pa.ts +++ b/packages/gui-plugins/src/browser/i18n/pa.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "صاف کرو", "site.permissions": "اجازتاں بلاک نیں", "site.permissions.description": "ایس براؤزر وچ کیمرہ، مائیکروفون، مقام تے نوٹیفکیشن کم نئیں کردے۔", - "site.agent": "ایجنٹ ایہہ صفحہ ورت سکدا اے", - "site.agent.description": "ایہہ صفحہ پڑھ سکدا اے، سکرپٹ چلا سکدا اے تے فارم بھر سکدا اے۔", "page.add": "صفحہ سیشن وچ شامل کرو", "page.placeholder": "ایس صفحے بارے تناظر شامل کرو", "external.open": "سسٹم براؤزر وچ کھولو", diff --git a/packages/gui-plugins/src/browser/i18n/pl.ts b/packages/gui-plugins/src/browser/i18n/pl.ts index 47ce85dce42..620484a9e47 100644 --- a/packages/gui-plugins/src/browser/i18n/pl.ts +++ b/packages/gui-plugins/src/browser/i18n/pl.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Wyczyść", "site.permissions": "Uprawnienia są zablokowane", "site.permissions.description": "Kamera, mikrofon, lokalizacja i powiadomienia nie działają w tej przeglądarce.", - "site.agent": "Agent może używać tej strony", - "site.agent.description": "Może czytać stronę, uruchamiać skrypty i wypełniać formularze.", "page.add": "Dodaj stronę do sesji", "page.placeholder": "Dodaj kontekst dotyczący tej strony", "external.open": "Otwórz w przeglądarce systemowej", diff --git a/packages/gui-plugins/src/browser/i18n/ro.ts b/packages/gui-plugins/src/browser/i18n/ro.ts index 2e6d3a4e7d9..7f74f81a33e 100644 --- a/packages/gui-plugins/src/browser/i18n/ro.ts +++ b/packages/gui-plugins/src/browser/i18n/ro.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Șterge", "site.permissions": "Permisiunile sunt blocate", "site.permissions.description": "Camera, microfonul, locația și notificările nu funcționează în acest browser.", - "site.agent": "Agentul poate folosi această pagină", - "site.agent.description": "Poate citi pagina, rula scripturi și completa formulare.", "page.add": "Adaugă pagina în sesiune", "page.placeholder": "Adaugă context despre această pagină", "external.open": "Deschide în browserul sistemului", diff --git a/packages/gui-plugins/src/browser/i18n/ru.ts b/packages/gui-plugins/src/browser/i18n/ru.ts index 08dababe376..ae370a8b327 100644 --- a/packages/gui-plugins/src/browser/i18n/ru.ts +++ b/packages/gui-plugins/src/browser/i18n/ru.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Очистить", "site.permissions": "Разрешения заблокированы", "site.permissions.description": "Камера, микрофон, геолокация и уведомления в этом браузере не работают.", - "site.agent": "Агент может использовать эту страницу", - "site.agent.description": "Он может читать страницу, запускать скрипты и заполнять формы.", "page.add": "Добавить страницу в сессию", "page.placeholder": "Добавьте контекст об этой странице", "external.open": "Открыть в системном браузере", diff --git a/packages/gui-plugins/src/browser/i18n/si.ts b/packages/gui-plugins/src/browser/i18n/si.ts index 21a4701df84..339d443c92e 100644 --- a/packages/gui-plugins/src/browser/i18n/si.ts +++ b/packages/gui-plugins/src/browser/i18n/si.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "ඉවත් කරන්න", "site.permissions": "අවසර අවහිර කර ඇත", "site.permissions.description": "කැමරාව, මයික්‍රෆෝනය, ස්ථානය සහ දැනුම්දීම් මෙම බ්‍රවුසරයේ ක්‍රියා නොකරයි.", - "site.agent": "නියෝජිතයාට මෙම පිටුව භාවිතා කළ හැක", - "site.agent.description": "එයට පිටුව කියවීමට, ස්ක්‍රිප්ට් ධාවනය කිරීමට සහ පෝරම පිරවීමට හැක.", "page.add": "සැසියට පිටුව එක් කරන්න", "page.placeholder": "මෙම පිටුව ගැන සන්දර්භය එක් කරන්න", "external.open": "පද්ධති බ්‍රවුසරයේ විවෘත කරන්න", diff --git a/packages/gui-plugins/src/browser/i18n/sk.ts b/packages/gui-plugins/src/browser/i18n/sk.ts index e9034caf2e5..47b1d85d0e6 100644 --- a/packages/gui-plugins/src/browser/i18n/sk.ts +++ b/packages/gui-plugins/src/browser/i18n/sk.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Vymazať", "site.permissions": "Povolenia sú blokované", "site.permissions.description": "Kamera, mikrofón, poloha a upozornenia v tomto prehliadači nefungujú.", - "site.agent": "Agent môže používať túto stránku", - "site.agent.description": "Môže čítať stránku, spúšťať skripty a vypĺňať formuláre.", "page.add": "Pridať stránku do relácie", "page.placeholder": "Pridajte kontext k tejto stránke", "external.open": "Otvoriť v systémovom prehliadači", diff --git a/packages/gui-plugins/src/browser/i18n/sl.ts b/packages/gui-plugins/src/browser/i18n/sl.ts index 9b09ed62ccd..d5582575a18 100644 --- a/packages/gui-plugins/src/browser/i18n/sl.ts +++ b/packages/gui-plugins/src/browser/i18n/sl.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Počisti", "site.permissions": "Dovoljenja so blokirana", "site.permissions.description": "Kamera, mikrofon, lokacija in obvestila v tem brskalniku ne delujejo.", - "site.agent": "Agent lahko uporablja to stran", - "site.agent.description": "Lahko bere stran, izvaja skripte in izpolnjuje obrazce.", "page.add": "Dodaj stran v sejo", "page.placeholder": "Dodajte kontekst o tej strani", "external.open": "Odpri v sistemskem brskalniku", diff --git a/packages/gui-plugins/src/browser/i18n/sq.ts b/packages/gui-plugins/src/browser/i18n/sq.ts index da53302206b..28f79c05441 100644 --- a/packages/gui-plugins/src/browser/i18n/sq.ts +++ b/packages/gui-plugins/src/browser/i18n/sq.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Pastro", "site.permissions": "Lejet janë bllokuar", "site.permissions.description": "Kamera, mikrofoni, vendndodhja dhe njoftimet nuk funksionojnë në këtë shfletues.", - "site.agent": "Agjenti mund ta përdorë këtë faqe", - "site.agent.description": "Mund ta lexojë faqen, të ekzekutojë skripte dhe të plotësojë formularë.", "page.add": "Shto faqen në sesion", "page.placeholder": "Shtoni kontekst për këtë faqe", "external.open": "Hap në shfletuesin e sistemit", diff --git a/packages/gui-plugins/src/browser/i18n/sr.ts b/packages/gui-plugins/src/browser/i18n/sr.ts index 6e8b7ca6cc8..1de65b9ef5f 100644 --- a/packages/gui-plugins/src/browser/i18n/sr.ts +++ b/packages/gui-plugins/src/browser/i18n/sr.ts @@ -48,8 +48,6 @@ export default { "site.cookies.clear": "Обриши", "site.permissions": "Дозволе су блокиране", "site.permissions.description": "Камера, микрофон, локација и обавештења не раде у овом прегледачу.", - "site.agent": "Агент може да користи ову страницу", - "site.agent.description": "Може да чита страницу, покреће скрипте и попуњава обрасце.", "page.add": "Додај страницу у сесију", "page.placeholder": "Додајте контекст о овој страници", "external.open": "Отвори у системском прегледачу", diff --git a/packages/gui-plugins/src/browser/i18n/sv.ts b/packages/gui-plugins/src/browser/i18n/sv.ts index c4656fb443d..64ef35cdf1e 100644 --- a/packages/gui-plugins/src/browser/i18n/sv.ts +++ b/packages/gui-plugins/src/browser/i18n/sv.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Rensa", "site.permissions": "Behörigheter är blockerade", "site.permissions.description": "Kamera, mikrofon, plats och aviseringar fungerar inte i den här webbläsaren.", - "site.agent": "Agenten kan använda den här sidan", - "site.agent.description": "Den kan läsa sidan, köra skript och fylla i formulär.", "page.add": "Lägg till sidan i sessionen", "page.placeholder": "Lägg till kontext om den här sidan", "external.open": "Öppna i systemets webbläsare", diff --git a/packages/gui-plugins/src/browser/i18n/tg.ts b/packages/gui-plugins/src/browser/i18n/tg.ts index f0d80942fef..a698e2841cf 100644 --- a/packages/gui-plugins/src/browser/i18n/tg.ts +++ b/packages/gui-plugins/src/browser/i18n/tg.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Тоза кардан", "site.permissions": "Иҷозатҳо баста шудаанд", "site.permissions.description": "Камера, микрофон, ҷойгиршавӣ ва огоҳиҳо дар ин браузер кор намекунанд.", - "site.agent": "Агент метавонад ин саҳифаро истифода барад", - "site.agent.description": "Он метавонад саҳифаро хонад, скриптҳо иҷро кунад ва шаклҳоро пур кунад.", "page.add": "Илова кардани саҳифа ба сессия", "page.placeholder": "Дар бораи ин саҳифа контекст илова кунед", "external.open": "Кушодан дар браузери система", diff --git a/packages/gui-plugins/src/browser/i18n/th.ts b/packages/gui-plugins/src/browser/i18n/th.ts index 716f4ff9dff..2e4770e3135 100644 --- a/packages/gui-plugins/src/browser/i18n/th.ts +++ b/packages/gui-plugins/src/browser/i18n/th.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "ล้าง", "site.permissions": "สิทธิ์ถูกบล็อก", "site.permissions.description": "กล้อง ไมโครโฟน ตำแหน่ง และการแจ้งเตือนไม่ทำงานในเบราว์เซอร์นี้", - "site.agent": "เอเจนต์ใช้หน้านี้ได้", - "site.agent.description": "เอเจนต์สามารถอ่านหน้า เรียกใช้สคริปต์ และกรอกฟอร์มได้", "page.add": "เพิ่มหน้าไปยังเซสชัน", "page.placeholder": "เพิ่มบริบทเกี่ยวกับหน้านี้", "external.open": "เปิดในเบราว์เซอร์ของระบบ", diff --git a/packages/gui-plugins/src/browser/i18n/tk.ts b/packages/gui-plugins/src/browser/i18n/tk.ts index f9f6cfb9f86..5c1a4702b72 100644 --- a/packages/gui-plugins/src/browser/i18n/tk.ts +++ b/packages/gui-plugins/src/browser/i18n/tk.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Arassala", "site.permissions": "Rugsatlar petiklenen", "site.permissions.description": "Kamera, mikrofon, ýerleşiş we habarnamalar bu brauzerde işlemeýär.", - "site.agent": "Agent bu sahypany ulanyp biler", - "site.agent.description": "Ol sahypany okap, skriptleri işledip we formalary doldurup biler.", "page.add": "Sahypany sessiýa goşuň", "page.placeholder": "Bu sahypa barada kontekst goşuň", "external.open": "Ulgam brauzerinde açyň", diff --git a/packages/gui-plugins/src/browser/i18n/tr.ts b/packages/gui-plugins/src/browser/i18n/tr.ts index d390654cb30..90b8585f581 100644 --- a/packages/gui-plugins/src/browser/i18n/tr.ts +++ b/packages/gui-plugins/src/browser/i18n/tr.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Temizle", "site.permissions": "İzinler engellendi", "site.permissions.description": "Kamera, mikrofon, konum ve bildirimler bu tarayıcıda çalışmaz.", - "site.agent": "Ajan bu sayfayı kullanabilir", - "site.agent.description": "Sayfayı okuyabilir, betik çalıştırabilir ve formları doldurabilir.", "page.add": "Sayfayı oturuma ekle", "page.placeholder": "Bu sayfa hakkında bağlam ekleyin", "external.open": "Sistem tarayıcısında aç", diff --git a/packages/gui-plugins/src/browser/i18n/uk.ts b/packages/gui-plugins/src/browser/i18n/uk.ts index 3f005294fd3..a953f2d5551 100644 --- a/packages/gui-plugins/src/browser/i18n/uk.ts +++ b/packages/gui-plugins/src/browser/i18n/uk.ts @@ -49,8 +49,6 @@ export default { "site.cookies.clear": "Очистити", "site.permissions": "Дозволи заблоковано", "site.permissions.description": "Камера, мікрофон, геолокація та сповіщення не працюють у цьому браузері.", - "site.agent": "Агент може використовувати цю сторінку", - "site.agent.description": "Він може читати сторінку, запускати скрипти й заповнювати форми.", "page.add": "Додати сторінку до сесії", "page.placeholder": "Додайте контекст про цю сторінку", "external.open": "Відкрити в системному браузері", diff --git a/packages/gui-plugins/src/browser/i18n/ur.ts b/packages/gui-plugins/src/browser/i18n/ur.ts index b8ff2813481..be35d901ea7 100644 --- a/packages/gui-plugins/src/browser/i18n/ur.ts +++ b/packages/gui-plugins/src/browser/i18n/ur.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "صاف کریں", "site.permissions": "اجازتیں مسدود ہیں", "site.permissions.description": "اس براؤزر میں کیمرہ، مائیکروفون، مقام اور اطلاعات کام نہیں کرتے۔", - "site.agent": "ایجنٹ یہ صفحہ استعمال کر سکتا ہے", - "site.agent.description": "یہ صفحہ پڑھ سکتا ہے، اسکرپٹس چلا سکتا ہے اور فارم بھر سکتا ہے۔", "page.add": "صفحہ سیشن میں شامل کریں", "page.placeholder": "اس صفحے کے بارے میں سیاق و سباق شامل کریں", "external.open": "سسٹم براؤزر میں کھولیں", diff --git a/packages/gui-plugins/src/browser/i18n/uz.ts b/packages/gui-plugins/src/browser/i18n/uz.ts index 95437eac660..30ac33c67e0 100644 --- a/packages/gui-plugins/src/browser/i18n/uz.ts +++ b/packages/gui-plugins/src/browser/i18n/uz.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Tozalash", "site.permissions": "Ruxsatlar bloklangan", "site.permissions.description": "Bu brauzerda kamera, mikrofon, joylashuv va bildirishnomalar ishlamaydi.", - "site.agent": "Agent bu sahifadan foydalanishi mumkin", - "site.agent.description": "U sahifani o‘qishi, skriptlarni ishga tushirishi va shakllarni to‘ldirishi mumkin.", "page.add": "Sahifani sessiyaga qo‘shish", "page.placeholder": "Bu sahifa haqida kontekst qo‘shing", "external.open": "Tizim brauzerida ochish", diff --git a/packages/gui-plugins/src/browser/i18n/vi.ts b/packages/gui-plugins/src/browser/i18n/vi.ts index 47f50db3b66..4cd9fb29776 100644 --- a/packages/gui-plugins/src/browser/i18n/vi.ts +++ b/packages/gui-plugins/src/browser/i18n/vi.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "Xóa", "site.permissions": "Các quyền bị chặn", "site.permissions.description": "Camera, micrô, vị trí và thông báo không hoạt động trong trình duyệt này.", - "site.agent": "Tác nhân có thể dùng trang này", - "site.agent.description": "Tác nhân có thể đọc trang, chạy script và điền biểu mẫu.", "page.add": "Thêm trang vào phiên", "page.placeholder": "Thêm ngữ cảnh về trang này", "external.open": "Mở trong trình duyệt hệ thống", diff --git a/packages/gui-plugins/src/browser/i18n/zh.ts b/packages/gui-plugins/src/browser/i18n/zh.ts index 4d5c8f55f9d..58ec0296003 100644 --- a/packages/gui-plugins/src/browser/i18n/zh.ts +++ b/packages/gui-plugins/src/browser/i18n/zh.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "清除", "site.permissions": "权限已被阻止", "site.permissions.description": "摄像头、麦克风、位置和通知在此浏览器中不可用。", - "site.agent": "智能体可以使用此页面", - "site.agent.description": "它可以读取页面、运行脚本和填写表单。", "page.add": "将页面添加到会话", "page.placeholder": "添加关于此页面的上下文", "external.open": "在系统浏览器中打开", diff --git a/packages/gui-plugins/src/browser/i18n/zht.ts b/packages/gui-plugins/src/browser/i18n/zht.ts index 5d51f9c9fed..27288e63cc3 100644 --- a/packages/gui-plugins/src/browser/i18n/zht.ts +++ b/packages/gui-plugins/src/browser/i18n/zht.ts @@ -47,8 +47,6 @@ export default { "site.cookies.clear": "清除", "site.permissions": "權限已封鎖", "site.permissions.description": "攝影機、麥克風、位置和通知在此瀏覽器中無法使用。", - "site.agent": "代理程式可以使用此頁面", - "site.agent.description": "它可以讀取頁面、執行指令碼和填寫表單。", "page.add": "將頁面加入工作階段", "page.placeholder": "新增此頁面的相關上下文", "external.open": "在系統瀏覽器中開啟", From fc06dbf1b47083ff7c8ffd6ac33eb4e290ef46d1 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:05:07 +1000 Subject: [PATCH 20/44] fix(browser): keep stopped navigation aligned with the visible document --- .../gui-plugins/src/browser/navigation-turn.test.ts | 13 +++++++++++++ packages/gui-plugins/src/browser/navigation-turn.ts | 3 ++- .../gui-plugins/src/browser/page-machine.test.ts | 4 ++-- packages/gui-plugins/src/browser/page-machine.ts | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/gui-plugins/src/browser/navigation-turn.test.ts b/packages/gui-plugins/src/browser/navigation-turn.test.ts index 7abe633f1a0..b5c714fb130 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.test.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.test.ts @@ -30,6 +30,19 @@ test("only a cross-document main-frame navigation supersedes a gated load", asyn } }) +test("interrupting an unissued restore preserves its address; stopping an agent navigation does not propose one", async () => { + for (const [method, restoring, keep, expected] of [["back", "https://saved.test", true, "https://saved.test"], ["forward", "https://saved.test", true, "https://saved.test"], ["stop", undefined, true, "https://saved.test"], ["stop", undefined, false, undefined]] as const) { + const gate = Promise.withResolvers<void>() + const stopped: (string | undefined)[] = [] + const navigation = navigationTurn(() => gate.promise, () => {}, () => {}, address => stopped.push(address)) + const visit = navigation.begin(new AbortController().signal, keep)("https://saved.test", () => { throw Error("load was issued") }) + navigation.interrupt(method, restoring) + gate.resolve() + await visit + expect(stopped).toEqual([expected]) + } +}) + test("a gated history traversal settles the spinner when Chromium has no load to stop", async () => { const gate = Promise.withResolvers<void>() const events: string[] = [] diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index d06492a6e27..623f5d6053d 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -32,7 +32,8 @@ export function navigationTurn( // initial CDP setup waiting for a renderer that the replacement command cannot start until setup finishes. if (method === "reload" && pending && restoring && /^https?:\/\//i.test(restoring)) return restoring - if (method === "stop" && held !== undefined && heldStop) { + // A not-yet-issued initial restore has no committed history entry to traverse. + if ((method === "stop" || (restoring && (method === "back" || method === "forward"))) && held !== undefined && heldStop) { const address = held spinning = false cancel() diff --git a/packages/gui-plugins/src/browser/page-machine.test.ts b/packages/gui-plugins/src/browser/page-machine.test.ts index 1bcc86942da..80d3e1ab729 100644 --- a/packages/gui-plugins/src/browser/page-machine.test.ts +++ b/packages/gui-plugins/src/browser/page-machine.test.ts @@ -74,7 +74,7 @@ test("Stop before issue publishes the restore address without inventing a commit const address = "https://next.test/report" const restore = createDocumentState({ url: address, title: "Report", generation: 4 }) - for (const before of [restore, replay(visit("https://previous.test/")).state]) { + for (const before of [restore, replay(visit("https://previous.test/")).state, replay(visit("file:///workspace/report.html")).state]) { const cancelled = replay([ { type: "navigation.started", isMainFrame: true, isSameDocument: false, url: address }, { type: "loading.started" }, @@ -82,7 +82,7 @@ test("Stop before issue publishes the restore address without inventing a commit ], before).state const saved = documentTab(cancelled, history) - expect(saved).toMatchObject({ id: history.id, url: address, loading: false }) + expect(saved).toMatchObject({ id: history.id, url: before.status === "loaded" ? before.url : address, loading: false }) expect(saved).not.toHaveProperty("loadError") expect(documentVisible(cancelled)).toBe(documentVisible(before)) expect(documentTab(cancelled, history, false)).toEqual(documentTab(before, history, false)) diff --git a/packages/gui-plugins/src/browser/page-machine.ts b/packages/gui-plugins/src/browser/page-machine.ts index 4ff8533e3de..073550c6a27 100644 --- a/packages/gui-plugins/src/browser/page-machine.ts +++ b/packages/gui-plugins/src/browser/page-machine.ts @@ -130,7 +130,7 @@ export function transitionDocument(state: DocumentState, event: DocumentEvent): switch (event.type) { case "navigation.held-stopped": - return settle(state, { ...state, retry: event.address, busy: false, pending: undefined }, [PUBLISH]) + return settle(state, { ...state, retry: state.status === "loaded" ? undefined : event.address, busy: false, pending: undefined }, [PUBLISH]) case "disposed": return { state: CLOSED, effects: [] } case "loading.started": From fe79e7eaa263e0bfb161d3b21a4a578e4ecd03b7 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:05:08 +1000 Subject: [PATCH 21/44] fix(browser): scope extension gestures and stylesheet targets to the pane --- .../gui-plugins/src/browser/connection.ts | 2 + packages/gui-plugins/src/browser/main.ts | 6 +- packages/gui-plugins/src/browser/model.ts | 1 + packages/gui-plugins/src/browser/pane.ts | 10 ++ packages/gui-plugins/src/browser/panel.tsx | 7 +- .../browser/profile/extension-api/action.ts | 4 +- .../profile/extension-api/frame-styles.js | 3 +- .../browser/profile/extension-api/index.ts | 6 +- .../profile/extension-api/styles.test.ts | 125 +++++++++++++++++- .../browser/profile/extension-api/styles.ts | 64 +++++++-- .../gui-plugins/src/browser/profile/ipc.ts | 3 + 11 files changed, 211 insertions(+), 20 deletions(-) diff --git a/packages/gui-plugins/src/browser/connection.ts b/packages/gui-plugins/src/browser/connection.ts index 4e7de530ed5..5e5bc1ba38e 100644 --- a/packages/gui-plugins/src/browser/connection.ts +++ b/packages/gui-plugins/src/browser/connection.ts @@ -14,6 +14,7 @@ export type ShortcutEvent = Extract<PaneEvent, { type: "shortcut" }> export type Zoom = "in" | "out" | "reset" export type Registration = { + readonly binding: string /** Creates a restored tab's page, which then reports its embed. */ load(tabID: Browser.TabID): void command(command: Browser.Action): Promise<void> @@ -60,6 +61,7 @@ export function openBinding(input: { ) return { + binding, load(tabID) { if (status.closed) return void ready.then(() => client.load({ binding, tabID })).catch(() => undefined) diff --git a/packages/gui-plugins/src/browser/main.ts b/packages/gui-plugins/src/browser/main.ts index 6ea447d1cc7..9ea05a00ccd 100644 --- a/packages/gui-plugins/src/browser/main.ts +++ b/packages/gui-plugins/src/browser/main.ts @@ -183,8 +183,12 @@ const setup: Plugin.MainSetup = (ctx) => { // The window lays out in CSS pixels; its content is in device-independent ones. const zoom = win.webContents.getZoomFactor() const anchor = input.anchor + const current = await profile() + const tab = (await pane()).toolbarTab(caller.window, input.binding, input.tabID) - return (await profile()).clickExtension(win, input.id, { + if (tab === undefined) return false + + return current.clickExtension(win, input.id, tab, { x: Math.round(anchor.x * zoom), y: Math.round(anchor.y * zoom), width: Math.round(anchor.width * zoom), diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index 25de878dca8..ad6889d3e56 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -669,6 +669,7 @@ export function createModel(ctx: SetupContext<typeof definition>) { }, /** The page's cookie count; undefined while the pane cannot answer. */ site: (session: Session, tabID: Browser.TabID) => registration(session)?.site(tabID), + binding: (session: Session) => registration(session)?.binding, /** Deletes the page's cookies and stored data, and reloads it. */ clearSite: (session: Session, tabID: Browser.TabID) => registration(session)?.clearSite(tabID), revealFile: (session: Session, tabID: Browser.TabID) => registration(session)?.reveal(tabID), diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 25d490500b6..26494cd82b1 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -377,6 +377,16 @@ export function createBrowserPane(input: { owned(window, binding) load(binding, tabID) }, + toolbarTab(window: number, binding: string, tabID: Browser.TabID) { + owned(window, binding) + const target = page(binding, tabID) + + // The visible toolbar's menu temporarily covers its native view. Resolve the clicked binding and + // selection, not view visibility or the window's last activation (which can be in another session). + if (!handles.get(binding)?.shared || inventory(binding).focusedTabID !== tabID) return + + return target?.nativeID + }, notice(window: number, binding: string, tabID: Browser.TabID, token: string, dismiss: boolean) { owned(window, binding) diff --git a/packages/gui-plugins/src/browser/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index 70ca9af2bcc..bfdec221ae8 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -149,8 +149,11 @@ export default function SessionBrowserPane(props: { // An extension's button opens its popup or tells it of the click; one without a button opens its options page. const chooseExtension = (extension: ProfileExtension) => { + if (!visible()) return const current = profile() const rect = extensionsButton.element?.getBoundingClientRect() + const binding = props.model.binding(props.session) + const tab = state() const fallback = () => { const page = extension.options ?? extension.popup @@ -158,9 +161,9 @@ export default function SessionBrowserPane(props: { if (page) props.model.openURL(props.session, page) } - if (current.status !== "active" || !rect) return fallback() + if (current.status !== "active" || !rect || !binding || !tab) return fallback() const anchor = { x: rect.x, y: rect.y, width: rect.width, height: rect.height } - void current.value.click({ id: extension.id, anchor }).then((handled) => { + void current.value.click({ id: extension.id, binding, tabID: tab.id, anchor }).then((handled) => { if (!handled) fallback() }, fallback) } diff --git a/packages/gui-plugins/src/browser/profile/extension-api/action.ts b/packages/gui-plugins/src/browser/profile/extension-api/action.ts index 6f6f383eabe..77a41143243 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/action.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/action.ts @@ -245,9 +245,9 @@ export function createActions(input: { * The user chose the extension in `window`'s menu: its popup opens over the window, or the extension hears the * click. Returns whether it had a button to click. */ - click(window: BrowserWindow, extension: Extension) { + click(window: BrowserWindow, extension: Extension, tabId: number) { if (!defaults(extension)) return false - const tab = input.tabs.activeTab(window) + const tab = input.tabs.snapshot(tabId) const values = actionFor(stateOf(extension), tab?.id) if (values.enabled === false) return true diff --git a/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js b/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js index aa0fa450d04..9370f6f31ac 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js +++ b/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js @@ -15,8 +15,9 @@ if (process.type === "renderer" && process.contextIsolated && process.sandboxed } ipcRenderer.on("browser-extension:forget-css", (_, id) => forget(id)) addEventListener("pagehide", () => sheets.forEach((_, id) => forget(id)), { once: true }) - ipcRenderer.on("browser-extension:css", async (_, channel, at) => { + ipcRenderer.on("browser-extension:css", async (_, channel, at, acknowledge) => { try { + if (acknowledge) ipcRenderer.send(`${channel}:received`) if (at !== "document_start" && document.readyState === "loading") { await new Promise(resolve => addEventListener("DOMContentLoaded", resolve, { once: true })) } diff --git a/packages/gui-plugins/src/browser/profile/extension-api/index.ts b/packages/gui-plugins/src/browser/profile/extension-api/index.ts index e2567060650..f273764c51a 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/index.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/index.ts @@ -89,13 +89,15 @@ export async function createExtensionApis(input: { * The user chose an extension in `window`'s extensions menu, whose button is at `anchor`: its popup opens there, * or the extension hears the click. Returns false when it has no button. */ - click(window: BrowserWindow, id: string, anchor: Rectangle) { + click(window: BrowserWindow, id: string, tabId: number, anchor: Rectangle) { const extension = input.session.extensions.getExtension(id) if (!extension) return false popups.anchor(window, anchor) - return actions.click(window, extension) + tabs.activated(tabId) + + return actions.click(window, extension, tabId) }, forget(id: string) { host.forget(id) diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts index 6106dddf080..ec9de839a7f 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts @@ -1,7 +1,13 @@ import { expect, test } from "bun:test" -import { readFile } from "node:fs/promises" +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import path from "node:path" +import { EventEmitter } from "node:events" +import type { Extension } from "electron" import { runInNewContext } from "node:vm" -import { canStyle } from "./styles" +import { canStyle, createStyles } from "./styles" +import { apiManifest } from "./manifest" +import type { ExtensionTabs } from "./tabs" test("CSS access requires the frame's host or a gesture for that top origin; private documents never qualify", () => { const top = "https://page.test/report" @@ -18,6 +24,8 @@ test("CSS access requires the frame's host or a gesture for that top origin; pri [top, "about:blank", origin, [], origin, true, true], [top, "about:srcdoc", origin, [], origin, false, false], [top, "about:blank", "null", ["<all_urls>"], origin, true, false], + [top, "data:text/html,hi", "null", ["<all_urls>"], origin, true, false], + [top, "blob:https://page.test/id", origin, ["<all_urls>"], origin, true, false], ["oc-preview://grant/report", child, "https://frame.test", grants, origin, true, false], ["workspace://session/report", child, "https://frame.test", grants, origin, true, false], ["artifact://art_x/", child, "https://frame.test", grants, origin, true, false], @@ -27,6 +35,119 @@ test("CSS access requires the frame's host or a gesture for that top origin; pri ] as const) expect(canStyle(root, frame, inherited, hosts, gesture, blank, app)).toBe(ok) }) +// A tab-scoped transport: the receiver asks main again at delivery, then acknowledges the sheet. This drives +// the actual API argument decoder, permission checks, tab watcher and unload broadcast, not copies of them. +function fixture() { + const root = "https://site.test/" + const forgotten: string[] = [] + const css: string[] = [] + + function frame(id: number, url: string) { + const ipc = Object.assign(new EventEmitter(), { + handleOnce(name: string, handler: () => void) { ipc.once(`request:${name}`, handler) }, + removeHandler(name: string) { ipc.removeAllListeners(`request:${name}`) }, + }) + + const f = { + url, origin: new URL(url).origin, frameTreeNodeId: id, detached: false, isDestroyed: () => false, ipc, + send(name: string, channel: string) { + if (name === "browser-extension:forget-css") { forgotten.push(channel); + + return } + + const [ask] = ipc.rawListeners(`request:${channel}`) + const item = ask?.({ senderFrame: f }) + + if (item) css.push(item.css) + ipc.emit(channel, {}, !!item && id !== 8) + }, + } + + return f + } + + const main = frame(4, root) + const child = frame(8, root) + const top = Object.assign(main, { framesInSubtree: [main, child] }) + const contents = Object.assign(new EventEmitter(), { id: 3, getURL: () => top.url, mainFrame: top, isDestroyed: () => false }) + const tab = { contents, window: { webContents: { getURL: () => "app://desktop/" } } } + let release = () => {} + + const registry = { get: (id: number) => id === 3 ? tab : undefined, ids: () => [3], current: () => 3, + watch(callback: (value: typeof tab) => () => void) { release = callback(tab); + + return () => release() }, + } + + // SAFETY: this fixture implements the registry and Electron frame operations used by createStyles above. + // oxlint-disable-next-line anti-slop/no-chained-type-assertions -- see SAFETY above + const styles = createStyles(registry as unknown as ExtensionTabs, apiManifest) + const extension: Extension = { id: "fixture", name: "Fixture", path: "", version: "1", url: "chrome-extension://fixture/", manifest: { permissions: ["activeTab"] } } + const mv2 = (args: Parameters<(typeof styles.module.methods)[string]>[1]) => Promise.resolve().then(() => styles.module.methods["tabs.insertCSS"]!({ extension }, args)) + const mv3 = (target: { tabId: number; frameIds?: number[]; allFrames?: boolean }) => styles.module.methods["scripting.insertCSS"]!({ extension }, [{ target }]) + const navigate = (url: string) => { main.url = url; main.origin = new URL(url).origin; contents.emit("did-navigate") } + + return { root, styles, extension, mv2, mv3, navigate, close: () => release(), forgotten, css } +} + +test("a toolbar grant covers only this tab and origin until cross-origin navigation, release or forget", async () => { + const f = fixture() + const style = () => f.mv2([{ code: "p{}" }]) // omitted tab ID resolves in the caller's window + await expect(style()).rejects.toThrow("Cannot access") + f.styles.grant(f.extension, 3) + await style() + f.navigate(f.root + "other") + await style() + f.navigate("https://other.test/") + f.navigate(f.root) + await expect(style()).rejects.toThrow("Cannot access") + f.styles.grant(f.extension, 3) + f.close() + await expect(style()).rejects.toThrow("Cannot access") + f.styles.grant(f.extension, 3) + f.styles.module.forget?.(f.extension.id) + expect(f.forgotten).toEqual(["fixture", "fixture"]) + await expect(style()).rejects.toThrow("Cannot access") +}) + +test("private tops deny before frame selection on both paths; a lost child does not veto allFrames", async () => { + const f = fixture() + f.styles.grant(f.extension, 3) + await f.mv2([{ allFrames: true, code: "p{}" }]) + await expect(f.mv2([{ frameId: 8, code: "p{}" }])).rejects.toThrow("no longer available") + expect(f.mv3({ tabId: 3, allFrames: true })).toEqual({ tabId: 3, frameIds: [0, 8] }) + f.navigate("oc-preview://private/report") + + for (const frameId of [0, 8, 9]) { + await expect(f.mv2([{ frameId, code: "p{}" }])).rejects.toThrow(/^Cannot access contents of the page\.$/) + expect(() => f.mv3({ tabId: 3, frameIds: [frameId] })).toThrow(/^Cannot access contents of the page\.$/) + } + + await expect(f.mv2([undefined, { code: "p{}" }])).rejects.toThrow() +}) + +test("file CSS stays in the physical package and has a bounded read", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "css-package-")) + + try { + const f = fixture() + const pkg = path.join(dir, "package") + await mkdir(pkg) + await writeFile(path.join(dir, "outside.css"), "outside") + await writeFile(path.join(pkg, "style.css"), "inside") + await writeFile(path.join(pkg, "large.css"), Buffer.alloc(4 * 1024 * 1024 + 1)) + Object.assign(f.extension, { path: pkg }) + f.styles.grant(f.extension, 3) + await f.mv2([{ file: "style.css" }]) + + for (const file of ["../outside.css", "%2e%2e/outside.css", "//host/outside.css", "large.css"]) { + await expect(f.mv2([{ file }])).rejects.toThrow() + } + + expect(f.css).toEqual(["inside"]) + } finally { await rm(dir, { recursive: true, force: true }) } +}) + test("a document removes only native sheet keys belonging to the same extension, text and origin", async () => { const source = await readFile(new URL("./frame-styles.js", import.meta.url), "utf8") const listeners = new Map<string, (...args: readonly unknown[]) => Promise<void> | void>() diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts index d64a354d6fa..495a58bf0bf 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/styles.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts @@ -1,4 +1,5 @@ import { once } from "node:events" +import { realpath } from "node:fs/promises" import type { Extension, WebFrameMain } from "electron" import { Schema } from "effect" import { openContained } from "@opencode/util/contained-file" @@ -18,15 +19,19 @@ const Injection = Schema.Struct({ target: Schema.Struct({ tabId: Schema.Int, all /** An activeTab gesture lends the top origin, not arbitrary cross-site children. The pane registry is the * first fence; also check the currently committed top document even for a separately permitted web iframe. */ export function canStyle(top: string, url: string, origin: string, hosts: readonly string[], grant: string | undefined, blank: boolean, appURL: string) { - const root = URL.parse(top) - - if (!root || !/^https?:$/.test(root.protocol) || root.origin === URL.parse(appURL)?.origin) return false + if (!publicTop(top, appURL)) return false const inherited = !url || url === "about:blank" || url === "about:srcdoc" const target = URL.parse(inherited && blank ? origin : url) if (!target || !/^https?:$/.test(target.protocol) || target.origin === URL.parse(appURL)?.origin) return false - return matchesHost(hosts, target.href) || (root.origin === grant && target.origin === grant) + return matchesHost(hosts, target.href) || (URL.parse(top)?.origin === grant && target.origin === grant) +} + +function publicTop(top: string, appURL: string) { + const url = URL.parse(top) + + return url && /^https?:$/.test(url.protocol) && url.origin !== URL.parse(appURL)?.origin } export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { @@ -88,6 +93,8 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { owners.set(extension.id, owner) const top = tab.contents.mainFrame + if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error("Cannot access contents of the page.") + const allowed = (frame: WebFrameMain) => !owner.signal.aborted && !tab.contents.isDestroyed() && tabs.get(tab.contents.id) === tab && !frame.isDestroyed() && !frame.detached && tab.contents.mainFrame === top && canStyle(top.url, frame.url, frame.origin, manifest(extension).hosts, grants.get(tab.contents.id)?.get(extension.id), !!details.matchAboutBlank, tab.window.webContents.getURL()) @@ -98,12 +105,21 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { if (!targets.length) throw new Error("Cannot access contents of the page. Extension manifest must request permission to access the respective host.") const css = details.code ?? await packageCSS(extension, details.file ?? "") - await Promise.all(targets.map(async frame => { + + const results = await Promise.allSettled(targets.map(async frame => { if (!allowed(frame)) throw new Error("The target frame is no longer available.") const channel = `browser-extension:css:${crypto.randomUUID()}` const ipc = frame.ipc const lifetime = new AbortController() const signal = AbortSignal.any([owner.signal, lifetime.signal, AbortSignal.timeout(15000)]) + // An initial empty document may never receive a sandbox preload. Distinguish no receiver from a live + // receiver waiting for document_end/idle. Never send CSS via a parent on the child's behalf. + const blank = !frame.url || frame.url === "about:blank" + const absent = new Error("The blank frame has no stylesheet receiver.") + const timer = blank ? setTimeout(() => lifetime.abort(absent), 250) : undefined + const heard = () => clearTimeout(timer) + + if (blank) ipc.once(`${channel}:received`, heard) // Reauthorize in the receiving document, at the requested runAt, not just when the command was queued. ipc.handleOnce(channel, event => { if (event.senderFrame !== frame || !allowed(frame)) return null @@ -114,23 +130,33 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { try { const [reply] = await Promise.all([ once(ipc, channel, { signal }), - Promise.resolve().then(() => frame.send("browser-extension:css", channel, remove ? "document_start" : details.runAt ?? "document_idle")), - ]) + Promise.resolve().then(() => frame.send("browser-extension:css", channel, remove ? "document_start" : details.runAt ?? "document_idle", blank)), + ]).catch(cause => { throw lifetime.signal.reason === absent ? absent : cause }) if (reply[1] === "user-removal") throw new Error("Electron cannot remove a user-origin stylesheet until the document is reloaded.") if (reply[1] !== true) throw new Error("The target frame is no longer available.") } finally { + clearTimeout(timer) + + if (blank) ipc.off(`${channel}:received`, heard) lifetime.abort() ipc.removeHandler(channel) } })) + + if (!results.some(result => result.status === "fulfilled")) { + const failure = results.find(result => result.status === "rejected") + + if (failure) throw failure.reason + } } const mv2 = (remove: boolean) => method(Arguments, (context, args) => args.length === 1 ? apply(context, undefined, args[0], remove) : apply(context, args[0], args[1], remove)) // MV3 has native CSS APIs. Keep Chromium's package-file resolution, cascade origins and removal; return - // only approved frame IDs, never allFrames (a newly attached child has not been authorized). + // only approved frame IDs, never allFrames (a newly attached child has not been authorized). This guards + // calls through our preload, not Chromium's native injection APIs in contexts without that preload. const mv3 = method(Schema.Tuple([Injection]), (context, [input]) => { if (input.target.documentIds) throw new Error("Targeting a document by UUID is not supported in this browser.") @@ -140,6 +166,8 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { if (!tab) throw new Error(`No tab with id: ${input.target.tabId}.`) const top = tab.contents.mainFrame + + if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error("Cannot access contents of the page.") const ids = input.target.frameIds ?? [0] const frames = top.framesInSubtree.map(frame => ({ frame, id: frame === top ? 0 : frame.frameTreeNodeId })) @@ -169,9 +197,25 @@ async function packageCSS(extension: Extension, resource: string) { const path = resource.replace(/^\/(?!\/)/, "") if (!path || /[\\:%?#]/.test(path)) throw new Error("Invalid extension stylesheet path.") - const opened = await openContained(extension.path, path).catch(() => undefined) + const opened = await realpath(extension.path).then(root => openContained(root, path)).catch(() => undefined) if (!opened) throw new Error(`Could not load file: '${resource}'.`) - try { return await opened.file.readFile("utf8") } finally { await opened.file.close() } + try { + if (opened.size > 4 * 1024 * 1024) throw new Error("Extension stylesheet exceeds 4 MiB.") + // Bound the actual read as well as the stat, even if the file grows while open. + const bytes = Buffer.alloc(opened.size + 1) + let length = 0 + + while (length < bytes.length) { + const read = await opened.file.read(bytes, length, bytes.length - length, length) + + if (!read.bytesRead) break + length += read.bytesRead + } + + if (length > opened.size) throw new Error("Extension stylesheet changed while reading.") + + return bytes.toString("utf8", 0, length) + } finally { await opened.file.close() } } diff --git a/packages/gui-plugins/src/browser/profile/ipc.ts b/packages/gui-plugins/src/browser/profile/ipc.ts index 744d916b48f..00f115b930c 100644 --- a/packages/gui-plugins/src/browser/profile/ipc.ts +++ b/packages/gui-plugins/src/browser/profile/ipc.ts @@ -1,5 +1,6 @@ import { Schema } from "effect" import { Ipc } from "@opencode/plugin/gui" +import { Browser } from "@opencode/plugin-browser/rpc" const Count = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) @@ -245,6 +246,8 @@ export const BrowserProfile = Ipc.define({ */ click: { input: Schema.Struct({ + binding: text(256), + tabID: Browser.TabID, id: text(64), anchor: Schema.Struct({ x: Schema.Number, y: Schema.Number, width: Schema.Number, height: Schema.Number }), }), From 83eeecbe1d6b0ea8d56272e8481dc04983bf26c7 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:06:56 +1000 Subject: [PATCH 22/44] fix(core): keep each experimental.rules hook's denies out of other hooks' reach Confirmation review, low finding. All hooks shared one event.deny array, so a later hook could drop an earlier hook's denies, for example with event.deny.length = 0, or replace the array. Now event.deny is a function that appends to a list owned by core. The event object is frozen, so a hook cannot swap deny, rules or session. No hook can read, clear or reorder the list. Core decodes the list as before, and a malformed entry still fails closed with a message that names the hook. Denies still apply in the order the hooks add them. Tests: a later hook that tries to replace deny fails to and cannot undo the earlier deny. The first test now checks that swapping rules and session fails. --- packages/core/src/permission.ts | 24 ++++++++----- packages/core/test/permission.test.ts | 44 ++++++++++++++++++----- packages/plugin/src/effect/permission.ts | 12 +++---- packages/plugin/src/promise/permission.ts | 12 +++---- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index 0ceefec7ad6..80547e04f74 100644 --- a/packages/core/src/permission.ts +++ b/packages/core/src/permission.ts @@ -120,15 +120,23 @@ export const rules = Effect.fn("Permission.rules")(function* ( input: { readonly session: SessionSchema.Info; readonly agent: Agent.Selection }, ) { const base = [...(input.agent.info?.permissions ?? missingAgentPermissions), ...(input.session.permissions ?? [])] - const event = yield* hooks.trigger("permission", "experimental.rules", { - sessionID: input.session.id, - agent: input.agent.id, - rules: base.map((rule) => ({ ...rule })), - session: (input.session.permissions ?? []).map((rule) => ({ ...rule })), - deny: [], - }) + // Core owns the list and the event is frozen, so a hook can add a deny but cannot remove or replace another's. + const added: unknown[] = [] + yield* hooks.trigger( + "permission", + "experimental.rules", + Object.freeze({ + sessionID: input.session.id, + agent: input.agent.id, + rules: base.map((rule) => ({ ...rule })), + session: (input.session.permissions ?? []).map((rule) => ({ ...rule })), + deny: (rule: unknown) => { + added.push(rule) + }, + }), + ) // A hook that cannot say what it denies must not leave the request decided without it. - const denies = yield* Schema.decodeUnknownEffect(Denies)(event.deny).pipe( + const denies = yield* Schema.decodeUnknownEffect(Denies)(added).pipe( Effect.mapError( (error) => new Error(`A permission "experimental.rules" hook added an invalid deny: ${error.message}`), ), diff --git a/packages/core/test/permission.test.ts b/packages/core/test/permission.test.ts index bb65a2abaef..b2d2fdf744f 100644 --- a/packages/core/test/permission.test.ts +++ b/packages/core/test/permission.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { Cause, Deferred, Effect, Fiber, Layer, Schema } from "effect" +import { Cause, Deferred, Effect, Exit, Fiber, Layer, Schema } from "effect" import { Agent } from "@opencode/core/agent" import { Database } from "@opencode/core/database/database" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" @@ -883,6 +883,8 @@ describe("shell scanner permission impact", () => { }) describe("Permission experimental.rules", () => { + // Writes `value` into `target` and says whether that failed, as a write to a frozen object does. + const assign = (target: object, value: object) => Effect.exit(Effect.try(() => Object.assign(target, value))) const rulesFor = Effect.gen(function* () { const store = yield* SessionStore.Service const agents = yield* Agent.Service @@ -900,18 +902,18 @@ describe("Permission experimental.rules", () => { yield* setup(configured) const hooks = yield* PluginHooks.Service yield* hooks.register("permission", "experimental.rules", (event) => - Effect.sync(() => { + Effect.gen(function* () { // Every way a hook could try to allow: push to the rules, edit them in place, swap the arrays, allow in deny. ;(event.rules as Permission.Rule[]).push({ action: "*", resource: "*", effect: "allow" }) ;(event.rules as Permission.Rule[]).forEach((rule) => Object.assign(rule, { effect: "allow" })) ;(event.session as Permission.Rule[]).push({ action: "*", resource: "*", effect: "allow" }) - Object.assign(event, { rules: [], session: [] }) - event.deny.push({ action: "edit", resource: "*" }) - event.deny.push(Object.assign({ action: "webfetch", resource: "*" }, { effect: "allow" })) + expect(Exit.isFailure(yield* assign(event, { rules: [], session: [] }))).toBe(true) + event.deny({ action: "edit", resource: "*" }) + event.deny(Object.assign({ action: "webfetch", resource: "*" }, { effect: "allow" })) }), ) yield* hooks.register("permission", "experimental.rules", (event) => - Effect.sync(() => event.deny.push({ action: "shell", resource: "git *" })), + Effect.sync(() => event.deny({ action: "shell", resource: "git *" })), ) expect(yield* rulesFor).toEqual([ ...configured, @@ -931,6 +933,32 @@ describe("Permission experimental.rules", () => { }), ) + it.effect("a later hook cannot remove or replace an earlier hook's deny", () => + Effect.gen(function* () { + yield* setup([{ action: "*", resource: "*", effect: "allow" }]) + const hooks = yield* PluginHooks.Service + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.sync(() => event.deny({ action: "edit", resource: "*" })), + ) + const attempts: boolean[] = [] + yield* hooks.register("permission", "experimental.rules", (event) => + Effect.gen(function* () { + // The event is frozen, so the swap fails; the list behind `deny` is core's, so there is nothing to clear. + attempts.push(Exit.isFailure(yield* assign(event, { deny: () => {} }))) + event.deny({ action: "shell", resource: "*" }) + }), + ) + expect(yield* rulesFor).toEqual([ + { action: "*", resource: "*", effect: "allow" }, + { action: "edit", resource: "*", effect: "deny" }, + { action: "shell", resource: "*", effect: "deny" }, + ]) + expect(attempts).toEqual([true]) + const service = yield* Permission.Service + expect(yield* service.ask(assertion({ action: "edit", resources: ["a.ts"] }))).toMatchObject({ effect: "deny" }) + }), + ) + it.effect("a hook's deny refuses the request before any evaluate hook runs", () => Effect.gen(function* () { yield* setup([{ action: "*", resource: "*", effect: "allow" }]) @@ -943,7 +971,7 @@ describe("Permission experimental.rules", () => { }), ) yield* hooks.register("permission", "experimental.rules", (event) => - Effect.sync(() => event.deny.push({ action: "shell", resource: "*" })), + Effect.sync(() => event.deny({ action: "shell", resource: "*" })), ) const service = yield* Permission.Service const error = yield* service.assert(assertion({ action: "shell", resources: ["ls"] })).pipe(Effect.flip) @@ -958,7 +986,7 @@ describe("Permission experimental.rules", () => { yield* setup([{ action: "*", resource: "*", effect: "allow" }]) const hooks = yield* PluginHooks.Service yield* hooks.register("permission", "experimental.rules", (event) => - Effect.sync(() => event.deny.push({ action: 1, resource: "*" } as unknown as (typeof event.deny)[number])), + Effect.sync(() => event.deny({ action: 1, resource: "*" } as unknown as Parameters<typeof event.deny>[0])), ) const service = yield* Permission.Service const exit = yield* service.ask(assertion()).pipe(Effect.exit) diff --git a/packages/plugin/src/effect/permission.ts b/packages/plugin/src/effect/permission.ts index 30cae1ae6cc..fc8db4ac301 100644 --- a/packages/plugin/src/effect/permission.ts +++ b/packages/plugin/src/effect/permission.ts @@ -34,10 +34,10 @@ export interface PermissionEvaluation { * rules decide the agent's permission requests and what its steps list: a tool whose permission they deny outright is * not listed, and neither is a skill or MCP server they deny. * - * A hook can only narrow them. Each entry it adds to `deny` becomes `{ action, resource, effect: "deny" }` after every - * other rule, so it outranks every allow and ask; other fields of an entry are ignored. `rules` and `session` are - * copies: changing them changes nothing. An entry that is not two strings fails the check or step that built the - * rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which + * A hook can only narrow them. Each entry it passes to `deny` becomes `{ action, resource, effect: "deny" }` after + * every other rule, so it outranks every allow and ask; other fields of an entry are ignored. Core keeps each entry + * itself, so no hook can remove another's. The event is frozen, and `rules` and `session` are copies: changing them + * changes nothing. An entry that is not two strings fails the check or step that built the rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which * would build the rules again and run the hook again without end. Experimental: may change without compatibility * guarantees. */ @@ -48,8 +48,8 @@ export interface PermissionRules { readonly rules: ReadonlyArray<Permission.Rule> /** The Session's own rules, which follow the agent's in `rules`. */ readonly session: ReadonlyArray<Permission.Rule> - /** Denies to add after `rules`, in the order the hooks add them. */ - readonly deny: Array<{ readonly action: string; readonly resource: string }> + /** Adds a deny after `rules`. Denies apply in the order the hooks add them. */ + readonly deny: (rule: { readonly action: string; readonly resource: string }) => void } export interface PermissionHooks { diff --git a/packages/plugin/src/promise/permission.ts b/packages/plugin/src/promise/permission.ts index d258d78c6a7..633b0c24d79 100644 --- a/packages/plugin/src/promise/permission.ts +++ b/packages/plugin/src/promise/permission.ts @@ -32,10 +32,10 @@ export interface PermissionEvaluation { * rules decide the agent's permission requests and what its steps list: a tool whose permission they deny outright is * not listed, and neither is a skill or MCP server they deny. * - * A hook can only narrow them. Each entry it adds to `deny` becomes `{ action, resource, effect: "deny" }` after every - * other rule, so it outranks every allow and ask; other fields of an entry are ignored. `rules` and `session` are - * copies: changing them changes nothing. An entry that is not two strings fails the check or step that built the - * rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which + * A hook can only narrow them. Each entry it passes to `deny` becomes `{ action, resource, effect: "deny" }` after + * every other rule, so it outranks every allow and ask; other fields of an entry are ignored. Core keeps each entry + * itself, so no hook can remove another's. The event is frozen, and `rules` and `session` are copies: changing them + * changes nothing. An entry that is not two strings fails the check or step that built the rules. The hook must be quick and must not request permissions itself (for example with `permission.assert`), which * would build the rules again and run the hook again without end. Experimental: may change without compatibility * guarantees. */ @@ -46,8 +46,8 @@ export interface PermissionRules { readonly rules: ReadonlyArray<Permission.Rule> /** The Session's own rules, which follow the agent's in `rules`. */ readonly session: ReadonlyArray<Permission.Rule> - /** Denies to add after `rules`, in the order the hooks add them. */ - readonly deny: Array<{ readonly action: string; readonly resource: string }> + /** Adds a deny after `rules`. Denies apply in the order the hooks add them. */ + readonly deny: (rule: { readonly action: string; readonly resource: string }) => void } export interface PermissionHooks { From 27777efd13a7dfb8ce06230aa260c3dfa0e74419 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:06:57 +1000 Subject: [PATCH 23/44] fix(browser): stop granting the browser skill on attach Confirmation review, the gap I reported. If the browser plugin was removed (plugins: ["-opencode.browser"]) after a crash left a grant, the grant's skill "browser" allow outranked a person's deny or ask on their own skill named browser. Nothing sweeps a grant once the plugin is gone. The skill rule was not needed. The experimental.rules hook already hides the built-in skill while the session holds no browser grant or its agent is denied the browser. Allowed agents get the skill from their own rules: the default agent rules allow "*". Now: - An attachment writes only browser "*" allow (BrowserMachine.GRANT). - isGrant still matches the old skill allow. A revoke, the reconcile on attach and the startup sweep therefore remove grants written by earlier versions. The configured rules the hooks read still leave that allow out. - The hook checks for the browser grant itself (holdsGrant), so a leftover skill allow does not count as attached. - With no skill rule in any grant, the evaluate hook's skill branch and the hook's "configured skill deny" check are removed. Core's own rules decide every skill. A configured skill deny or ask is final again. Tests: - grant fixtures drop the skill rule. The startup-sweep test uses the old two-rule grant and still revokes it. - A machine test: an old grant is revoked in full and replaced with the new one. - The truth table and skill tests pass unchanged: with no skill rule in the grant, the built-in skill is listed and loads for an allowed agent with a desktop, and is hidden otherwise. - New: with the plugin removed, a person's deny on their own browser skill holds against a grant left behind. An old-version grant there still outranks it, and the test pins that as the remaining case. --- packages/core/test/browser-attach.test.ts | 6 +-- packages/core/test/browser-permission.test.ts | 39 ++++++++++++++--- packages/plugin-browser/src/connection.ts | 42 +++++++------------ packages/plugin-browser/src/machine.ts | 42 +++++++++++-------- packages/plugin-browser/test/machine.test.ts | 8 +++- 5 files changed, 83 insertions(+), 54 deletions(-) diff --git a/packages/core/test/browser-attach.test.ts b/packages/core/test/browser-attach.test.ts index f7685ec8684..a7381dee0d8 100644 --- a/packages/core/test/browser-attach.test.ts +++ b/packages/core/test/browser-attach.test.ts @@ -73,10 +73,8 @@ const it = testEffect( ) const user = { action: "bash", resource: "*", effect: "ask" } as const -const allows = [ - { action: "browser", resource: "*", effect: "allow" }, - { action: "skill", resource: "browser", effect: "allow" }, -] as const +const allows = [{ action: "browser", resource: "*", effect: "allow" }] as const + const setup = Effect.gen(function* () { writes.race = undefined diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index 5709f55e4c2..8c32e0d8016 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -49,10 +49,9 @@ const it = testEffect( ), ) -const grant = [ - { action: "browser", resource: "*", effect: "allow" }, - { action: "skill", resource: "browser", effect: "allow" }, -] as const +const grant = [{ action: "browser", resource: "*", effect: "allow" }] as const +// What versions before this one granted; a revoke or the startup sweep must still remove it. +const legacyGrant = [...grant, { action: "skill", resource: "browser", effect: "allow" }] as const const tab = { id: Browser.TabID.make(`tab_${crypto.randomUUID()}`), @@ -259,7 +258,7 @@ it.live("startup revokes a grant whose server no longer runs", () => // What a server killed while attached leaves behind: the grant and the record of the process that wrote it. yield* storage.set(`grant:${sessionID}`, owner(ref.directory, exited)) const sessions = yield* Session.Service - yield* sessions.create({ id: sessionID, location: ref, permissions: [...grant] }) + yield* sessions.create({ id: sessionID, location: ref, permissions: [...legacyGrant] }) const locations = yield* LocationServiceMap.Service yield* Plugin.awaitActivation.pipe(Effect.provideContext(yield* locations.contextEffect(ref).pipe(Effect.scoped))) @@ -833,6 +832,36 @@ it.live("with the browser plugin removed, a grant left in a session lists and re }), ) +it.live("with the browser plugin removed, a person's deny on their own browser skill outranks a grant left behind", () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => + Bun.write( + path.join(dir.path, ".opencode/skills/browser/SKILL.md"), + "---\nname: browser\ndescription: Drive Playwright against the staging site.\n---\n# Playwright\n", + ), + ) + yield* Effect.promise(() => + Bun.write( + path.join(dir.path, "opencode.json"), + JSON.stringify({ plugins: ["-opencode.browser"], permissions: [rule("browser", "deny", "skill")] }), + ), + ) + const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) }) + const locations = yield* LocationServiceMap.Service + const context = yield* locations.contextEffect(ref).pipe(Effect.scoped) + yield* Plugin.awaitActivation.pipe(Effect.provideContext(context)) + const sessions = yield* Session.Service + const contexts = Context.get(context, SessionContext.Service) + // A grant allows no skill, so the person's deny decides. + const current = yield* sessions.create({ location: ref, permissions: [...grant] }) + expect((yield* listing(contexts, current.id)).skill).toBe(false) + // An earlier version's grant also allowed the skill. Nothing sweeps it once the plugin is removed, so it still + // outranks the deny; with the plugin loaded, a revoke or the startup sweep removes it. + const legacy = yield* sessions.create({ location: ref, permissions: [...legacyGrant] }) + expect((yield* listing(contexts, legacy.id)).skill).toBe(true) + }), +) // Loads the browser skill as the model would, through the read tool. const readSkill = (browser: Effect.Success<ReturnType<typeof setup>>, agent: string, sessionID = browser.session.id) => Effect.gen(function* () { diff --git a/packages/plugin-browser/src/connection.ts b/packages/plugin-browser/src/connection.ts index 896f69c51b1..e26a611305d 100644 --- a/packages/plugin-browser/src/connection.ts +++ b/packages/plugin-browser/src/connection.ts @@ -93,25 +93,15 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( ...(configured.get(agent ?? session.agent ?? "") ?? [{ action: "*", resource: "*", effect: "deny" as const }]), ...(session.permissions ?? []).filter((rule) => !BrowserMachine.isGrant(rule)), ] - // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call and - // every load of the `browser` skill to allow. The rules from config, the agent's definition and the session itself - // decide instead: a deny refuses the call, and an ask makes the permission check prompt as it would without the - // grant, unless the user already saved "always" for it. No matching rule leaves it allowed. The skill's denies come - // from the `experimental.rules` hook below, so core refuses those before this hook runs. + // The attachment's grant is a session rule, evaluated after every agent rule, so core resolves every browser call to + // allow. The rules from config, the agent's definition and the session itself decide instead: a deny refuses the + // call, and an ask makes the permission check prompt as it would without the grant, unless the user already saved + // "always" for it. No matching rule leaves it allowed. yield* ctx.permission.hook("evaluate", (event) => { - const skill = event.action === "skill" && event.resources.includes(BrowserSkill.id) - if ((event.action !== "browser" && !skill) || event.effect === "deny") return Effect.void + if (event.action !== "browser" || event.effect === "deny") return Effect.void return ctx.session.get({ sessionID: event.sessionID }).pipe( Effect.map((session) => { const rules = rulesFor(session, event.agent) - if (skill) { - if ( - !event.experimental?.approvedSave && - BrowserMachine.selectRule(rules, "skill", BrowserSkill.id)?.effect === "ask" - ) - event.effect = "ask" - return - } const denied = denial(rules, event.resources) if (denied) { event.effect = "deny" @@ -137,12 +127,13 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( ), ) }) - // The grant comes last, so without these denies core would list the browser tools and skill to an agent whose own - // rules deny them, and only the hook above would refuse their calls. A deny added here is evaluated after the grant: - // it hides them from that agent's steps and Code Mode catalog, and core refuses their calls before any hook runs. An - // ask or a narrower deny keeps them listed, for the hook above to decide each call. The skill is denied while no - // desktop is attached, or when the agent is denied the whole browser, only while the registered `browser` skill is - // the built-in one: a person's own skill of that name follows their rules alone. + // The grant comes last, so without this deny core would list the browser tools to an agent whose own rules deny the + // whole browser, and only the hook above would refuse their calls. A deny added here is evaluated after the grant: it + // hides them from that agent's steps and Code Mode catalog, and core refuses their calls before any hook runs. An ask + // or a narrower deny keeps them listed, for the hook above to decide each call. The grant allows no skill, so the + // person's rules decide every skill; this hook only hides the built-in `browser` skill while the session holds no + // grant or its agent is denied the browser. A person's own skill of that name replaces the built-in one and follows + // their rules alone. yield* ctx.permission.hook("experimental.rules", (event) => ctx.skill.list().pipe( Effect.map((skills) => skills.data.some((skill) => skill.id === BrowserSkill.id && skill.path === BrowserSkill.info.path)), @@ -151,12 +142,9 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( Effect.map((builtin) => { const rules = rulesFor({ permissions: event.session }, event.agent) const browser = BrowserMachine.deniesBrowser(rules) - if (browser) event.deny.push({ action: "browser", resource: "*" }) - if ( - BrowserMachine.selectRule(rules, "skill", BrowserSkill.id)?.effect === "deny" || - (builtin && (browser || !event.session.some(BrowserMachine.isGrant))) - ) - event.deny.push({ action: "skill", resource: BrowserSkill.id }) + if (browser) event.deny({ action: "browser", resource: "*" }) + if (builtin && (browser || !BrowserMachine.holdsGrant(event.session))) + event.deny({ action: "skill", resource: BrowserSkill.id }) }), ), ) diff --git a/packages/plugin-browser/src/machine.ts b/packages/plugin-browser/src/machine.ts index 42798d374fe..83a19912439 100644 --- a/packages/plugin-browser/src/machine.ts +++ b/packages/plugin-browser/src/machine.ts @@ -13,11 +13,15 @@ export const PERMISSION_SYNC_TIMEOUT_MS = 10_000 /** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */ export const REQUEST_TIMEOUT_MS = 60_000 -/** The browser tools and their skill, which an attachment allows together. */ -export const ACCESS = [ - { action: "browser", resource: "*" }, - { action: "skill", resource: BrowserSkill.id }, -] as const +/** + * What an attachment allows: the browser tools. It grants no skill rule. The `experimental.rules` hook shows the + * built-in skill only while the session holds this grant, so the grant cannot outrank a person's own rules for any + * skill, including their own skill named `browser`. + */ +export const GRANT = { action: "browser", resource: "*", effect: "allow" } as const + +/** Every rule an attachment has granted. Earlier versions also allowed the skill; those grants are still recognised. */ +const GRANTED = [GRANT, { action: "skill", resource: BrowserSkill.id }] as const /** The one `session.permissions` sync in flight for a session: grant (`allow`) or revoke the browser rules. */ export type PermissionSync = { readonly attempt: number; readonly allow: boolean } @@ -545,7 +549,7 @@ function syncWarning( } /** - * The session's permissions with exactly one set of browser allows (`allow`) or none, every other rule kept in order. + * The session's permissions with exactly one browser grant (`allow`) or none, every other rule kept in order. * Undefined when they already are, so a replace writes nothing. */ export function reconcileBrowserPermissions( @@ -554,7 +558,7 @@ export function reconcileBrowserPermissions( ): Permission.Rule[] | undefined { const rules = current ?? [] const kept = rules.filter((rule) => !isGrant(rule)) - const next = allow ? [...kept, ...ACCESS.map((rule) => ({ ...rule, effect: "allow" as const }))] : kept + const next = allow ? [...kept, { ...GRANT }] : kept const unchanged = next.length === rules.length && next.every( @@ -567,30 +571,34 @@ export function reconcileBrowserPermissions( return unchanged ? undefined : next } -/** One of the allows an attachment grants. A user rule of the same shape cannot be told apart from it. */ +/** + * One of the allows an attachment grants, or granted in an earlier version, so a revoke or the startup sweep removes + * old grants too. A user rule of the same shape cannot be told apart from it. + */ export function isGrant(rule: Permission.Rule) { return ( rule.effect === "allow" && - ACCESS.some((access) => access.action === rule.action && access.resource === rule.resource) + GRANTED.some((granted) => granted.action === rule.action && granted.resource === rule.resource) ) } +/** Whether `rules` hold an attachment's grant of the browser tools. */ +export function holdsGrant(rules: readonly Permission.Rule[]) { + return rules.some((rule) => rule.effect === "allow" && rule.action === GRANT.action && rule.resource === GRANT.resource) +} + /** - * The rule that decides `action` on `resource`, picked as core's `Permission.evaluate` picks it: the last rule whose + * The rule that decides `browser` on `operation`, picked as core's `Permission.evaluate` picks it: the last rule whose * action and resource patterns both match. Undefined when none matches. */ -export function selectRule(rules: readonly Permission.Rule[], action: string, resource: string) { +export function selectBrowserRule(rules: readonly Permission.Rule[], operation: string) { const ignoreCase = process.platform === "win32" return rules.findLast( - (rule) => Wildcard.match(action, rule.action, ignoreCase) && Wildcard.match(resource, rule.resource, ignoreCase), + (rule) => + Wildcard.match("browser", rule.action, ignoreCase) && Wildcard.match(operation, rule.resource, ignoreCase), ) } -/** The rule that decides `browser` on `operation`. */ -export function selectBrowserRule(rules: readonly Permission.Rule[], operation: string) { - return selectRule(rules, "browser", operation) -} - /** Whether `rules` deny the whole browser, which is when core stops listing the browser tools. */ export function deniesBrowser(rules: readonly Permission.Rule[]) { return Permission.deniesAll("browser", rules, process.platform === "win32") diff --git a/packages/plugin-browser/test/machine.test.ts b/packages/plugin-browser/test/machine.test.ts index dd1863d3c30..ae2775e5742 100644 --- a/packages/plugin-browser/test/machine.test.ts +++ b/packages/plugin-browser/test/machine.test.ts @@ -256,7 +256,8 @@ describe("permission syncs", () => { describe("reconcileBrowserPermissions", () => { const user = { action: "bash", resource: "*", effect: "ask" } as const - const allows = BrowserMachine.ACCESS.map((rule) => ({ ...rule, effect: "allow" as const })) + const allows = [BrowserMachine.GRANT] + const legacy = [BrowserMachine.GRANT, { action: "skill", resource: "browser", effect: "allow" } as const] test("granting what is already granted writes nothing", () => { expect(BrowserMachine.reconcileBrowserPermissions([user, ...allows], true)).toBeUndefined() @@ -270,6 +271,11 @@ describe("reconcileBrowserPermissions", () => { expect(BrowserMachine.reconcileBrowserPermissions(undefined, true)).toEqual(allows) }) + test("a grant from an earlier version, which also allowed the skill, is revoked and replaced in full", () => { + expect(BrowserMachine.reconcileBrowserPermissions([user, ...legacy], false)).toEqual([user]) + expect(BrowserMachine.reconcileBrowserPermissions([user, ...legacy], true)).toEqual([user, ...allows]) + }) + test("browser denies are not browser allows", () => { const deny = { action: "browser", resource: "*", effect: "deny" } as const expect(BrowserMachine.reconcileBrowserPermissions([deny], false)).toBeUndefined() From 69f065f36e8fd15789fe6834f3db268f9b74644c Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:14:19 +1000 Subject: [PATCH 24/44] fix(browser): let a page prompt take real typing and keep its keyboard after a click Review of 4696694fa1. AltGr characters and dead keys (Ctrl+Alt, or AltGraph) type into the prompt on Windows and Linux instead of being swallowed. Chords on layouts without Latin letters are read by their physical key, so Ctrl+V, Ctrl+A and Ctrl+Z work on Russian, Greek, Hebrew or Arabic layouts. The key that ends an IME composition (keyCode 229) neither submits nor cancels. Alt+F4, Shift+F10, Ctrl+Insert, Shift+Insert, Shift+Delete, Shift+Cmd+` and Ctrl+Cmd+Space are no longer swallowed, and Shift only edits with Z (redo) and V (paste as plain text). On macOS, Ctrl+` and Option+Up/Down off a text field are swallowed, and a native menu key equivalent the page left unhandled runs nothing while the keyboard is in the prompt (main now says whether an accelerator chose the item). A click on the prompt's dimmed page keeps or returns the keyboard to the prompt; the strip, the address field and the chat stay usable and take the keyboard as before. The command layer's gate is narrowed from any aria-modal element to a data-owns-keyboard marker, after the existing data-owns-escape convention, so drawers and other modal surfaces keep their shortcuts. --- .../browser-pane-restore.spec.ts | 63 +++++++++++++ packages/app/src/desktop.ts | 2 +- .../app/src/shell/commands/command.test.ts | 15 ---- packages/app/src/shell/commands/command.tsx | 12 +-- .../desktop/src/main/ipc-transport.test.ts | 12 +-- packages/desktop/src/main/native/menu.ts | 8 +- packages/desktop/src/renderer/api-types.ts | 2 +- packages/desktop/src/renderer/api.ts | 2 +- .../desktop/src/renderer/platform/menu.ts | 13 ++- packages/desktop/src/shared/ipc-rpc/events.ts | 2 + .../gui-plugins/src/browser/panel.fixture.tsx | 64 ++++++++++++- .../src/browser/prompt-keys.test.ts | 81 +++++++++++++---- .../gui-plugins/src/browser/prompt-keys.ts | 90 +++++++++++++------ packages/gui-plugins/src/browser/prompts.tsx | 41 +++++++-- 14 files changed, 313 insertions(+), 94 deletions(-) diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 034e59c2672..2c1b2742dc3 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -698,3 +698,66 @@ story( await expect(tabs).toHaveText(["beta.ts", "Preview"]) }, ) + +story( + "runs no shortcut from a page prompt, even after a click on its dimmed page; the permission bar and a drawer keep theirs", + async ({ page }) => { + const root = page.getByTestId("browser-region-fixture") + const reloads = root.getByTestId("browser-reloads") + const reviews = root.getByTestId("review-toggles") + await expect(root.getByText("Registrations: 1", { exact: true })).toBeVisible() + await root.getByRole("button", { name: "Beta", exact: true }).click() + await expect(root.getByText("Registrations: 2", { exact: true })).toBeVisible() + await root.getByRole("button", { name: "First inventory", exact: true }).click() + + await root.getByRole("button", { name: "Page prompt", exact: true }).click() + const dialog = root.getByRole("alertdialog", { name: "beta.example says" }) + const field = dialog.getByRole("textbox", { name: "Your answer" }) + const dimmed = root.locator("[data-browser-prompt]") + await expect(field).toBeFocused() + // Neither the pane's reload nor the session's review toggle runs from the prompt. + await field.press("ControlOrMeta+r") + await field.press("ControlOrMeta+Shift+r") + // A click on the dimmed page keeps the keyboard in the prompt rather than giving it to the pane behind. + await dimmed.click({ position: { x: 4, y: 4 } }) + await expect(field).toBeFocused() + await page.keyboard.press("ControlOrMeta+r") + await expect(reloads).toHaveText("0") + await expect(reviews).toHaveText("0") + + // The prompt is modal for its tab only: on the address field the pane's shortcuts work and the prompt stays open. + const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + await address.click() + await address.press("ControlOrMeta+r") + await expect(reloads).toHaveText("1") + await expect(dialog).toBeVisible() + // A click on the dimmed page brings the keyboard back, where Escape is the prompt's cancel. + await dimmed.click({ position: { x: 4, y: 4 } }) + await expect(field).toBeFocused() + await page.keyboard.press("Escape") + await expect(dialog).toBeHidden() + + // The permission bar is not modal: the pane's shortcuts work there, and Escape is its "not now". + await root.getByRole("button", { name: "Permission request", exact: true }).click() + const bar = root.locator('[data-component="browser-prompt"]') + const never = bar.getByRole("button", { name: "Never allow", exact: true }) + await expect(never).toBeFocused() + await never.press("ControlOrMeta+r") + await expect(reloads).toHaveText("2") + await never.press("Escape") + await expect(bar).toBeHidden() + + // Another modal surface, as a mobile drawer, keeps the app's shortcuts. + await page.evaluate(() => { + const drawer = document.createElement("div") + drawer.setAttribute("role", "dialog") + drawer.setAttribute("aria-modal", "true") + drawer.append(Object.assign(document.createElement("button"), { textContent: "Drawer action" })) + document.body.append(drawer) + }) + const action = page.getByRole("button", { name: "Drawer action", exact: true }) + await action.focus() + await action.press("ControlOrMeta+Shift+r") + await expect(reviews).toHaveText("1") + }, +) diff --git a/packages/app/src/desktop.ts b/packages/app/src/desktop.ts index 581b737be30..8617aeb7848 100644 --- a/packages/app/src/desktop.ts +++ b/packages/app/src/desktop.ts @@ -1,6 +1,6 @@ export { AppBaseProviders, AppInterface, preloadRoute } from "./app" -export { useCommand } from "./shell/commands/command" +export { keyboardOwned, useCommand } from "./shell/commands/command" export { currentRoute, type LayoutRoute, useCurrentRoute } from "./shell/state/layout" diff --git a/packages/app/src/shell/commands/command.test.ts b/packages/app/src/shell/commands/command.test.ts index d84450a2a30..72ddf29c6e1 100644 --- a/packages/app/src/shell/commands/command.test.ts +++ b/packages/app/src/shell/commands/command.test.ts @@ -7,7 +7,6 @@ import { CommandCatalog, commandKeymap, formatKeybind, - insideModalDialog, matchKeybind, parseKeybind, resolveKeybindOption, @@ -142,17 +141,3 @@ describe("command keybinds", () => { expect(formatKeybind("mod+k,mod+p")).not.toContain("P") }) }) - -describe("keys inside a modal dialog", () => { - test("belong to the dialog, which may cover only part of the window; keys elsewhere run commands", () => { - const page = document.createElement("div") - page.innerHTML = `<div id="pane"><div role="alertdialog" aria-modal="true"><input id="field"></div></div><div id="composer" contenteditable="true"></div>` - document.body.append(page) - - expect(insideModalDialog(page.querySelector("#field"))).toBe(true) - expect(insideModalDialog(page.querySelector("#composer"))).toBe(false) - expect(insideModalDialog(page.querySelector("#pane"))).toBe(false) - expect(insideModalDialog(null)).toBe(false) - page.remove() - }) -}) diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 1a5bf764573..03dd97b04ce 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -369,12 +369,12 @@ export function formatKeybind(config: string, t?: (key: KeyLabel) => string): st } /** - * Whether a key's target is inside a modal dialog, which owns the keyboard there: no command keybind runs, as none runs - * while one of the app's own dialogs is open (`dialog.active`). A dialog modal for less than the window, such as a - * page's prompt in the browser pane, owns only the keys pressed inside it. + * Whether `target` is inside a surface that owns the keyboard (`data-owns-keyboard`), such as a page's prompt in the + * browser pane, which is modal for its tab only: no command keybind or native menu key equivalent runs there, as none + * runs while one of the app's own dialogs is open (`dialog.active`). Keys pressed elsewhere in the window are the app's. */ -export function insideModalDialog(target: EventTarget | null) { - return target instanceof Element && !!target.closest('[aria-modal="true"]') +export function keyboardOwned(target: EventTarget | null) { + return target instanceof Element && !!target.closest("[data-owns-keyboard]") } function isEditableTarget(target: EventTarget | null) { @@ -523,7 +523,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const handleKeyDown = (event: KeyboardEvent) => { - if (suspended() || dialog.active || insideModalDialog(event.target)) return + if (suspended() || dialog.active || keyboardOwned(event.target)) return const sig = signatureFromEvent(event) const isPalette = palette().has(sig) diff --git a/packages/desktop/src/main/ipc-transport.test.ts b/packages/desktop/src/main/ipc-transport.test.ts index 8854a9475a9..4874d055c54 100644 --- a/packages/desktop/src/main/ipc-transport.test.ts +++ b/packages/desktop/src/main/ipc-transport.test.ts @@ -125,15 +125,15 @@ describe("desktop RPC transport", () => { const handoff = await runtime.runPromise(IpcPortHandoff) const win = sender(1) // A window that has not asked for its snapshot has no document to hold events for. - expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early" }))).toBe(false) + expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early", accelerator: false }))).toBe(false) handoff.prepare(win) // On dev these were dropped: the window had no event queue until its port bound. - expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a" }))).toBe(true) - expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b" }))).toBe(true) + expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a", accelerator: false }))).toBe(true) + expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b", accelerator: false }))).toBe(true) const channel = new MessageChannel() handoff.bind(win, serverPort(channel.port1)) - emitIpcEvent(win, new MenuCommandTriggered({ id: "c" })) + emitIpcEvent(win, new MenuCommandTriggered({ id: "c", accelerator: false })) expect(await chunks(channel.port2, 0, "DesktopEvents", 3)).toEqual(["a", "b", "c"].map(menuCommand)) @@ -156,7 +156,7 @@ describe("desktop RPC transport", () => { // The new document's snapshot: the old one stops receiving events but still answers its RPCs. handoff.prepare(win) expect((await firstEvents).chunks).toEqual([]) - emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload" })) + emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload", accelerator: false })) Effect.runSync(Deferred.succeed(flushGate, undefined)) expect((await flush).exit).toEqual(success("flushed")) @@ -187,7 +187,7 @@ const eventsLive = RpcServer.layer(EventRpcs.merge(FlushRpcs)).pipe( ) function menuCommand(id: string) { - return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id })) + return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id, accelerator: false })) } class TestEvent extends Schema.TaggedClass<TestEvent>()("TestEvent", { value: Schema.String }) {} diff --git a/packages/desktop/src/main/native/menu.ts b/packages/desktop/src/main/native/menu.ts index 36feb4eaa49..dbd41f79920 100644 --- a/packages/desktop/src/main/native/menu.ts +++ b/packages/desktop/src/main/native/menu.ts @@ -96,8 +96,8 @@ function build(deps: Deps, provider: MenubarProvider) { Menu.setApplicationMenu(built) } -export function sendMenuCommand(win: BrowserWindow, id: string) { - emitIpcEvent(win.webContents, new MenuCommandTriggered({ id })) +export function sendMenuCommand(win: BrowserWindow, id: string, accelerator: boolean) { + emitIpcEvent(win.webContents, new MenuCommandTriggered({ id, accelerator })) } function nativeMenu(menu: DesktopMenu, extra: readonly MenubarEntry[], deps: Deps): MenuItemConstructorOptions { @@ -145,10 +145,10 @@ function nativeItem(entry: DesktopMenuEntry, deps: Deps): MenuItemConstructorOpt if (entry.command) { const command = entry.command - item.click = () => { + item.click = (_item, _window, event) => { const win = deps.commandWindow() - if (win) sendMenuCommand(win, command) + if (win) sendMenuCommand(win, command, !!event.triggeredByAccelerator) } } diff --git a/packages/desktop/src/renderer/api-types.ts b/packages/desktop/src/renderer/api-types.ts index 41c40ab18a8..b2903de8e2b 100644 --- a/packages/desktop/src/renderer/api-types.ts +++ b/packages/desktop/src/renderer/api-types.ts @@ -39,7 +39,7 @@ export type ElectronAPI = { getWindowID(): string getWindowBootstrap(): WindowBootstrap themeReady(): Promise<void> - onMenuCommand(cb: (id: string) => void): () => void + onMenuCommand(cb: (id: string, accelerator: boolean) => void): () => void onDeepLink(cb: (delivery: { attempt: number; urls: string[] }) => void): () => void openDirectoryPicker(opts?: DirectoryPickerOptions): Promise<string | string[] | null> openFilePicker(opts?: FilePickerOptions): Promise<PickedFiles | null> diff --git a/packages/desktop/src/renderer/api.ts b/packages/desktop/src/renderer/api.ts index 54d5bb67d40..ff1598fd1bb 100644 --- a/packages/desktop/src/renderer/api.ts +++ b/packages/desktop/src/renderer/api.ts @@ -43,7 +43,7 @@ export const api: ElectronAPI = { getWindowID: () => window.electron.windowID, getWindowBootstrap: () => window.electron.bootstrap, themeReady: () => invoke("WindowThemeReady"), - onMenuCommand: (cb) => listen("MenuCommandTriggered", (event) => cb(event.id)), + onMenuCommand: (cb) => listen("MenuCommandTriggered", (event) => cb(event.id, event.accelerator)), onDeepLink: (cb) => listen("DeepLinksOpened", (event) => cb({ attempt: event.attempt, urls: mutable(event.urls) })), openDirectoryPicker: (opts) => invoke("FilesOpenDirectoryPicker", { options: opts }).then(mutable), diff --git a/packages/desktop/src/renderer/platform/menu.ts b/packages/desktop/src/renderer/platform/menu.ts index b7bff2a9759..d855e61ded6 100644 --- a/packages/desktop/src/renderer/platform/menu.ts +++ b/packages/desktop/src/renderer/platform/menu.ts @@ -1,4 +1,4 @@ -import type { Platform } from "@opencode/app/desktop" +import { keyboardOwned, type Platform } from "@opencode/app/desktop" import type { ElectronAPI } from "../api-types" import { resetZoom, zoomIn, zoomOut } from "../window/zoom" import { @@ -23,9 +23,16 @@ function dispatch(event: MenuRouterEvent) { ) } -/** Commands that arrive before the app interface binds run once it does. */ +/** + * Commands that arrive before the app interface binds run once it does. A key equivalent the page left unhandled runs + * nothing while the keyboard is in a surface that owns it, such as a page's prompt: macOS offers the menu every key + * the focused element does not consume, as Control+` or Option+Down on a prompt's button. + */ export function startDesktopMenu(api: ElectronAPI) { - api.onMenuCommand((id) => dispatch({ type: "command.received", id })) + api.onMenuCommand((id, accelerator) => { + if (accelerator && keyboardOwned(document.activeElement)) return + dispatch({ type: "command.received", id }) + }) } /** Routes menu commands to `handler` until the returned function unbinds it. */ diff --git a/packages/desktop/src/shared/ipc-rpc/events.ts b/packages/desktop/src/shared/ipc-rpc/events.ts index 3c436842ffb..f10451fa6e0 100644 --- a/packages/desktop/src/shared/ipc-rpc/events.ts +++ b/packages/desktop/src/shared/ipc-rpc/events.ts @@ -10,6 +10,8 @@ export class DeepLinksOpened extends Schema.TaggedClass<DeepLinksOpened>()("Deep export class MenuCommandTriggered extends Schema.TaggedClass<MenuCommandTriggered>()("MenuCommandTriggered", { id: Schema.String, + /** A key equivalent chose the item, rather than a click on the menu. */ + accelerator: Schema.Boolean, }) {} export class WindowFullscreenChanged extends Schema.TaggedClass<WindowFullscreenChanged>()("WindowFullscreenChanged", { diff --git a/packages/gui-plugins/src/browser/panel.fixture.tsx b/packages/gui-plugins/src/browser/panel.fixture.tsx index 0bab9b25e81..2e2f37d1b2b 100644 --- a/packages/gui-plugins/src/browser/panel.fixture.tsx +++ b/packages/gui-plugins/src/browser/panel.fixture.tsx @@ -51,7 +51,7 @@ import browserEn from "./i18n/en" import type definition from "./index" import { createModel } from "./model" import SessionBrowserPane from "./panel" -import { BrowserPane, type PaneEvent, type PromptAnswer } from "./ipc" +import { BrowserPane, type PaneEvent, type PromptAnswer, type PromptView } from "./ipc" import { pageShortcut } from "./keys" import { normalizeURL, refusal } from "./policy" import { type BuiltinLayout } from "@opencode/plugin/gui/builtin" @@ -1265,7 +1265,8 @@ export function mountBrowserRegion(input: RegionHost) { clearSite: async () => undefined, find: async () => undefined, notice: async () => undefined, - answer: async () => undefined, + // Main answers the page, which then waits on nothing. + answer: async () => ask(null), reveal: async () => undefined, close: async () => undefined, forget: async () => undefined, @@ -1288,7 +1289,15 @@ export function mountBrowserRegion(input: RegionHost) { servers: () => servers, workspaces: () => workspaces, desktop: () => ({ zoom: () => 1 }), - embeds: () => ({ View: () => null, capture: async () => undefined }), + // The page area with what the pane draws over it, as a page's prompt; the page itself is the iframe above. + embeds: () => ({ + View: (props: Parameters<Embeds["View"]>[0]) => ( + <div class={props.class} style={{ "min-height": "240px" }}> + {props.children} + </div> + ), + capture: async () => undefined, + }), system: () => ({ copy: async () => undefined, openExternal() {}, save: async () => false }), sessions: () => ({ list: () => refs, current: view }), screen: () => ({ current: () => screen }), @@ -1315,6 +1324,13 @@ export function mountBrowserRegion(input: RegionHost) { ) } + // As main reports a page's prompt on Beta's tab. + const ask = (prompt: PromptView | null) => { + const binding = latest()?.binding + + if (binding) listeners.forEach((listener) => listener({ binding, event: { type: "prompt", tabID, prompt } })) + } + // Wires an embedded page with the same before-input-event shortcut interception as chromium.ts. const wirePage = (frame: HTMLIFrameElement) => { const win = frame.contentWindow @@ -1499,6 +1515,48 @@ export function mountBrowserRegion(input: RegionHost) { </button> <button onClick={() => setStore("away", true)}>Pane away</button> <button onClick={() => setStore("away", false)}>Pane back</button> + <button + onClick={() => + ask({ + id: 1, + waiting: 0, + focus: true, + asked: 1, + page: false, + ask: { + kind: "dialog", + dialog: "prompt", + site: { kind: "web", host: "beta.example", embedded: false }, + message: "Name the copy", + value: "Draft", + stop: false, + }, + }) + } + > + Page prompt + </button> + <button + onClick={() => + ask({ + id: 2, + waiting: 0, + focus: true, + asked: 1, + page: false, + ask: { + kind: "permission", + site: { kind: "web", host: "beta.example", embedded: false }, + permissions: ["notifications"], + remember: "kept", + agent: false, + system: false, + }, + }) + } + > + Permission request + </button> </nav> <iframe title="Browser page" diff --git a/packages/gui-plugins/src/browser/prompt-keys.test.ts b/packages/gui-plugins/src/browser/prompt-keys.test.ts index d694905e8bd..87de7c6e618 100644 --- a/packages/gui-plugins/src/browser/prompt-keys.test.ts +++ b/packages/gui-plugins/src/browser/prompt-keys.test.ts @@ -1,23 +1,30 @@ import { describe, expect, test } from "bun:test" import { promptKeyOwner, type PromptKey } from "./prompt-keys" -// A chord as the platform writes it: "mod" is Command on macOS and Ctrl elsewhere. -const press = (chord: string, mac: boolean): PromptKey => { +// A chord as the platform writes it: "mod" is Command on macOS and Ctrl elsewhere. `code` is the physical key, which +// a US layout names after its letter; `as` overrides what the layout reports. +const press = (chord: string, mac: boolean, as: Partial<PromptKey> & { altGraph?: boolean } = {}): PromptKey => { const parts = chord.split("+") const key = parts.at(-1) === "" ? "+" : (parts.at(-1) ?? "") const has = (name: string) => parts.slice(0, -1).includes(name) + const code = /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key === "`" ? "Backquote" : key return { key, + code, + keyCode: 0, ctrlKey: has("Ctrl") || (!mac && has("mod")), metaKey: has("Cmd") || (mac && has("mod")), altKey: has("Alt"), shiftKey: has("Shift"), isComposing: false, + getModifierState: (state) => state === "AltGraph" && !!as.altGraph, + ...as, } } -const owner = (chord: string, mac: boolean, inside = true) => promptKeyOwner(press(chord, mac), { inside, mac }) +const owner = (chord: string, mac: boolean, input: { inside?: boolean; text?: boolean; as?: Partial<PromptKey> & { altGraph?: boolean } } = {}) => + promptKeyOwner(press(chord, mac, input.as), { inside: input.inside ?? true, mac, text: input.text ?? true }) describe("keys inside an open page prompt", () => { for (const mac of [false, true]) { @@ -28,13 +35,14 @@ describe("keys inside an open page prompt", () => { }) test(`edit its field as text fields do on ${os}`, () => { - for (const chord of ["a", "Z", " ", "Backspace", "ArrowLeft", "Shift+Home", "mod+a", "mod+c", "mod+x", "mod+v", "mod+z", "Shift+mod+z", "mod+Backspace"]) - expect(owner(chord, mac)).toBe("field") + for (const chord of ["a", "Z", " ", "Backspace", "ArrowLeft", "Shift+Home", "mod+a", "mod+c", "mod+x", "mod+v", "mod+z", "Shift+mod+z", "Shift+mod+v", "mod+Backspace", "Shift+mod+ArrowLeft"]) + expect(owner(chord, mac), chord).toBe("field") }) test(`never run the app's or the pane's shortcuts behind it on ${os}`, () => { - // Reload, the agent switch, find, address field, close and new tab, zoom, palette, model picker, back. - for (const chord of ["mod+r", "mod+.", "mod+f", "mod+l", "mod+w", "mod+t", "mod+=", "mod++", "mod+-", "mod+0", "Shift+mod+p", "mod+k", "mod+'", "F5", "F3", "F6", "Shift+mod+r"]) + // Reload, the agent switch, find, address field, close and new tab, zoom, palette, model picker, back, and the + // editing letters with a Shift that edits nothing (select an element, a new incognito-style window). + for (const chord of ["mod+r", "mod+.", "mod+f", "mod+l", "mod+w", "mod+t", "mod+=", "mod++", "mod+-", "mod+0", "Shift+mod+p", "mod+k", "mod+'", "F5", "F3", "F6", "Shift+mod+r", "Shift+mod+a", "Shift+mod+c", "Shift+mod+x"]) expect(owner(chord, mac), chord).toBe("swallowed") }) @@ -43,23 +51,58 @@ describe("keys inside an open page prompt", () => { }) test(`leave every key to the app when the keyboard is elsewhere on ${os}`, () => { - for (const chord of ["mod+r", "mod+.", "Escape", "Enter", "a"]) expect(owner(chord, mac, false)).toBe("app") + for (const chord of ["mod+r", "mod+.", "Escape", "Enter", "a"]) expect(owner(chord, mac, { inside: false })).toBe("app") + }) + + test(`keep a key that ends an IME composition in the field on ${os}`, () => { + expect(owner("Enter", mac, { as: { isComposing: true } })).toBe("field") + // Chromium already reports isComposing false for the key that commits or cancels the composition. + expect(owner("Enter", mac, { as: { keyCode: 229 } })).toBe("field") + expect(owner("Escape", mac, { as: { keyCode: 229 } })).toBe("field") + }) + + test(`paste, select all and undo on a layout without Latin letters on ${os}`, () => { + // A Russian layout names the V, A, Z and C keys by their Cyrillic letters. + for (const [key, code] of [["м", "KeyV"], ["ф", "KeyA"], ["я", "KeyZ"], ["с", "KeyC"]]) + expect(owner(`mod+${key}`, mac, { as: { code } }), key).toBe("field") + expect(owner("mod+к", mac, { as: { code: "KeyR" } })).toBe("swallowed") }) } - test("Windows keeps Alt for history and menus, macOS edits text with Option and Control", () => { - expect(owner("Alt+ArrowLeft", false)).toBe("swallowed") - expect(owner("Ctrl+y", false)).toBe("field") - expect(owner("Alt+ArrowLeft", true)).toBe("field") - expect(owner("Ctrl+a", true)).toBe("field") - expect(owner("Ctrl+Tab", true)).toBe("swallowed") - expect(owner("Cmd+ArrowLeft", true)).toBe("field") - expect(owner("Cmd+[", true)).toBe("swallowed") + test("AltGr types a layout's characters on Windows and Linux", () => { + // German @ and {, Polish ą, a French dead key: Windows reports Ctrl+Alt, with or without AltGraph. + for (const key of ["@", "{", "[", "\\", "€", "ą", "Dead"]) { + expect(owner(`Ctrl+Alt+${key}`, false, { as: { altGraph: true } }), key).toBe("field") + expect(owner(`Ctrl+Alt+${key}`, false), key).toBe("field") + } - for (const chord of ["Cmd+q", "Cmd+h", "Cmd+Alt+h", "Cmd+m", "Ctrl+Cmd+f"]) expect(owner(chord, true)).toBe("window") + expect(owner("q", false, { as: { key: "@", altGraph: true } })).toBe("field") + // Ctrl+Alt with no character is still a chord. + expect(owner("Ctrl+Alt+ArrowLeft", false)).toBe("swallowed") }) - test("a key that composes text is the field's", () => { - expect(promptKeyOwner({ ...press("Enter", false), isComposing: true }, { inside: true, mac: false })).toBe("field") + test("Windows and Linux keep their system chords", () => { + expect(owner("Alt+F4", false)).toBe("window") + + for (const chord of ["Shift+F10", "Ctrl+Insert", "Shift+Insert", "Shift+Delete", "ContextMenu", "Ctrl+y"]) + expect(owner(chord, false), chord).toBe("field") + expect(owner("Alt+ArrowLeft", false)).toBe("swallowed") + expect(owner("Alt+F", false)).toBe("swallowed") + }) + + test("macOS edits text with Option and Control and keeps its window chords", () => { + for (const chord of ["Alt+ArrowLeft", "Alt+l", "Alt+e", "Ctrl+a", "Ctrl+e", "Ctrl+k", "Ctrl+b", "Ctrl+f", "Ctrl+d", "Ctrl+h", "Cmd+ArrowLeft", "Ctrl+Cmd+ "]) + expect(owner(chord, true), chord).toBe("field") + + for (const chord of ["Cmd+q", "Cmd+h", "Cmd+Alt+h", "Cmd+m", "Cmd+`", "Shift+Cmd+`", "Ctrl+Cmd+f"]) expect(owner(chord, true), chord).toBe("window") + + for (const chord of ["Ctrl+Tab", "Ctrl+`", "Cmd+[", "Cmd+]", "Cmd+n", "Cmd+,", "Shift+Cmd+b", "Alt+Cmd+i"]) expect(owner(chord, true), chord).toBe("swallowed") + }) + + test("macOS Option+Up and Down move the caret in a field and do nothing elsewhere in the prompt", () => { + for (const chord of ["Alt+ArrowUp", "Alt+ArrowDown"]) { + expect(owner(chord, true, { text: true })).toBe("field") + expect(owner(chord, true, { text: false })).toBe("swallowed") + } }) }) diff --git a/packages/gui-plugins/src/browser/prompt-keys.ts b/packages/gui-plugins/src/browser/prompt-keys.ts index 5e5fdc0fff0..bc9eec0d810 100644 --- a/packages/gui-plugins/src/browser/prompt-keys.ts +++ b/packages/gui-plugins/src/browser/prompt-keys.ts @@ -1,24 +1,21 @@ +import { pageLetter } from "./keys" + // Who a key pressed in the app window belongs to while a page prompt (alert, confirm, prompt, "Leave site?", a // sign-in) is open in the pane. The prompt is modal for its tab: while the keyboard is inside it, the app's command -// keybinds do not run (the command layer skips a key whose target is inside an `aria-modal` dialog, as it skips every -// key while one of the app's own dialogs is open), and the prompt cancels what the window itself would do behind it. -// Keys outside the prompt are the app's. +// keybinds and the native menu's key equivalents do not run (the prompt marks itself `data-owns-keyboard`), and the +// prompt cancels what the window itself would do behind it. Keys outside the prompt are the app's. -export type PromptKey = { - readonly key: string - readonly ctrlKey: boolean - readonly metaKey: boolean - readonly altKey: boolean - readonly shiftKey: boolean - readonly isComposing: boolean -} +export type PromptKey = Pick< + KeyboardEvent, + "key" | "code" | "keyCode" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "isComposing" | "getModifierState" +> export type PromptKeyOwner = /** The prompt answers or moves within itself: Enter accepts, Escape cancels, Tab and Shift+Tab cycle. */ | "prompt" - /** The focused field or button, as its default does: typing, moving the caret, clipboard, undo. */ + /** The focused field or button, as its default does: typing, moving the caret, clipboard, undo, the context menu. */ | "field" - /** The window, as Chrome leaves them to a window with a tab-modal dialog: close or new window, quit, hide, full screen. */ + /** The window or the system, as Chrome leaves them with a tab-modal dialog: close or new window, quit, hide, full screen. */ | "window" /** Nothing: an app or pane shortcut (reload, find, zoom, history, tabs, the address field, the agent, the palette). */ | "swallowed" @@ -29,49 +26,86 @@ const modifiers: readonly string[] = ["Alt", "AltGraph", "CapsLock", "Control", const caret: readonly string[] = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "Backspace", "Delete"] -// Text editing on the command key (Ctrl on Windows and Linux): select all, copy, cut, paste, undo and redo. +// Text editing on the command key (Ctrl on Windows and Linux): select all, copy, cut, paste, undo; with Shift only redo +// and paste as plain text. const editing: readonly string[] = ["a", "c", "x", "v", "z"] -/** Who `key` belongs to: `inside` is whether the keyboard is inside the open prompt. */ -export function promptKeyOwner(key: PromptKey, input: { readonly inside: boolean; readonly mac: boolean }): PromptKeyOwner { +const shiftedEditing: readonly string[] = ["z", "v"] + +/** + * Who `key` belongs to: `inside` is whether the keyboard is inside the open prompt, `text` whether it is in one of + * the prompt's text fields. + */ +export function promptKeyOwner( + key: PromptKey, + input: { readonly inside: boolean; readonly mac: boolean; readonly text: boolean }, +): PromptKeyOwner { if (!input.inside) return "app" - if (key.isComposing || modifiers.includes(key.key)) return "field" - const name = key.key.length === 1 ? key.key.toLowerCase() : key.key + // Chromium reports the key that ends an IME composition with keyCode 229 once isComposing is already false. + if (key.isComposing || key.keyCode === 229 || modifiers.includes(key.key)) return "field" + + if (!input.mac && altGraph(key)) return "field" + + // A layout that types no Latin letter names the physical key, so its Ctrl+V still pastes. + const name = key.key.length === 1 ? pageLetter(key) : key.key + const backquote = name === "`" || key.code === "Backquote" const command = input.mac ? key.metaKey : key.ctrlKey - const control = input.mac && key.ctrlKey const plain = !key.ctrlKey && !key.metaKey && !key.altKey if (plain && (name === "Enter" || name === "Escape" || name === "Tab")) return "prompt" - if (plain) return /^F\d{1,2}$/.test(name) ? "swallowed" : "field" + // Shift+F10 opens the field's context menu on Windows and Linux. + if (plain) return /^F\d{1,2}$/.test(name) && !(!input.mac && key.shiftKey && name === "F10") ? "swallowed" : "field" - if (windowChord(name, key, input.mac)) return "window" + if (windowChord(name, backquote, key, input.mac)) return "window" - // macOS edits text on Option (words) and Control (Emacs bindings) too; Windows uses Alt for menus and history. - if (input.mac && key.altKey && !key.metaKey && !key.ctrlKey) return "field" + if (input.mac) { + // The emoji and symbols picker types into the field. + if (key.ctrlKey && key.metaKey && !key.altKey && name === " ") return "field" - if (control && !key.metaKey && !key.altKey) return name === "Tab" ? "swallowed" : "field" + // macOS edits text on Option (words) and Control (Emacs bindings). The menu takes what the field leaves: Option+Up + // and Down off a text field switch the session, Control+` toggles the terminal. + if (key.altKey && !key.metaKey && !key.ctrlKey) + return !input.text && (name === "ArrowUp" || name === "ArrowDown") ? "swallowed" : "field" + + if (key.ctrlKey && !key.metaKey && !key.altKey) return name === "Tab" || backquote ? "swallowed" : "field" + } if (command && !key.altKey && !(input.mac ? key.ctrlKey : key.metaKey)) { - if (editing.includes(name) || (!input.mac && name === "y" && !key.shiftKey) || caret.includes(name)) return "field" + if (caret.includes(name)) return "field" + + if (key.shiftKey && shiftedEditing.includes(name)) return "field" + + // Ctrl+Insert copies on Windows and Linux. + if (!key.shiftKey && (editing.includes(name) || (!input.mac && (name === "y" || name === "Insert")))) return "field" } return "swallowed" } -function windowChord(name: string, key: PromptKey, mac: boolean) { +// AltGr types a layout's @, {, € or ą, and its dead keys. Windows reports it as Ctrl+Alt, as it does Ctrl+Alt pressed +// for it; Linux may report AltGraph alone. +function altGraph(key: PromptKey) { + if (!/^.$/u.test(key.key) && key.key !== "Dead") return false + + return key.getModifierState("AltGraph") || (key.ctrlKey && key.altKey && !key.metaKey) +} + +function windowChord(name: string, backquote: boolean, key: PromptKey, mac: boolean) { if (mac) { if (key.metaKey && key.ctrlKey && !key.altKey && name === "f") return true if (!key.metaKey || key.ctrlKey) return false - if (!key.shiftKey && !key.altKey) return name === "q" || name === "h" || name === "m" || name === "`" + if (!key.shiftKey && !key.altKey) return name === "q" || name === "h" || name === "m" || backquote if (key.altKey && !key.shiftKey) return name === "h" - return key.shiftKey && !key.altKey && (name === "w" || name === "n") + return key.shiftKey && !key.altKey && (name === "w" || name === "n" || backquote) } + if (key.altKey && !key.ctrlKey && !key.metaKey && !key.shiftKey && name === "F4") return true + return key.ctrlKey && key.shiftKey && !key.altKey && !key.metaKey && (name === "w" || name === "n") } diff --git a/packages/gui-plugins/src/browser/prompts.tsx b/packages/gui-plugins/src/browser/prompts.tsx index 113c5a8428f..f50c18bc519 100644 --- a/packages/gui-plugins/src/browser/prompts.tsx +++ b/packages/gui-plugins/src/browser/prompts.tsx @@ -35,6 +35,8 @@ export function PromptDialog(props: { const title = createUniqueId() const description = createUniqueId() let box: HTMLDivElement | undefined + // Where the keyboard last was inside the dialog, which a click on the dimmed page returns it to. + let last: HTMLElement | undefined // A page can open a dialog under a click or key press already in flight: its default answer waits for a new one, // from each dialog it shows on and each time the page asks again. let guard: ReturnType<typeof guardActivation> | undefined @@ -90,11 +92,15 @@ export function PromptDialog(props: { target.focus({ preventScroll: true }) }) - // The dialog's keys are its own (prompt-keys.ts): the command layer runs no shortcut from inside an aria-modal dialog, - // no other handler of the window sees them, and what the window would do behind it, as its own reload or zoom, is - // cancelled. Tab and Shift+Tab cycle inside the dialog; the page behind it is a still. + // The dialog's keys are its own (prompt-keys.ts): the command layer and the native menu run no shortcut while the + // keyboard is inside it (`data-owns-keyboard`), no other handler of the window sees them, and what the window would do + // behind it, as its own reload or zoom, is cancelled. Tab and Shift+Tab cycle inside the dialog; the page behind it is + // a still. const keyDown = (event: KeyboardEvent) => { - const owner = promptKeyOwner(event, { inside: true, mac }) + const text = + event.target instanceof HTMLInputElement && (event.target.type === "text" || event.target.type === "password") + + const owner = promptKeyOwner(event, { inside: true, mac, text }) if (owner !== "window") event.stopPropagation() @@ -108,9 +114,9 @@ export function PromptDialog(props: { } // A click on the dialog's text focuses the dialog, or the page's text, where Enter answers as the main button does. - const text = event.target instanceof HTMLElement && event.target.dataset.pageText !== undefined + const pageText = event.target instanceof HTMLElement && event.target.dataset.pageText !== undefined - if (event.key === "Enter" && !event.isComposing && box && (event.target === box || text)) { + if (event.key === "Enter" && !composing(event) && box && (event.target === box || pageText)) { event.preventDefault() return box.querySelector("form")?.requestSubmit() @@ -153,12 +159,30 @@ export function PromptDialog(props: { "pointer-events": "auto", "background-color": "var(--v2-overlay-simple-overlay-scrim)", }} + // The dimmed page is the dialog's: a click there keeps the keyboard in the dialog, or brings it back, rather than + // giving it to the pane behind. The strip, the address field and the chat stay the user's to click. + onMouseDown={(event) => { + if (event.target !== event.currentTarget || !box) return + event.preventDefault() + + if (box.contains(document.activeElement)) return + + const target = + last?.isConnected && box.contains(last) ? last : (box.querySelector<HTMLElement>("[autofocus]") ?? box) + + target.focus({ preventScroll: true }) + }} > <div ref={box} data-slot="dialog-container" role="alertdialog" aria-modal="true" + // The command layer and the native menu run no shortcut while the keyboard is here. + data-owns-keyboard + onFocusIn={(event) => { + if (event.target instanceof HTMLElement) last = event.target + }} aria-labelledby={title} aria-describedby={described() ? description : undefined} tabIndex={-1} @@ -531,7 +555,10 @@ export function PromptBar(props: { view: PromptView; answer: (answer: PromptAnsw type Plugin = ReturnType<typeof usePlugin<typeof definition>> -const cancelKey = (event: KeyboardEvent) => !event.isComposing && event.key === "Escape" +// Chromium reports the key that ends an IME composition with keyCode 229 once isComposing is already false. +const composing = (event: KeyboardEvent) => event.isComposing || event.keyCode === 229 + +const cancelKey = (event: KeyboardEvent) => !composing(event) && event.key === "Escape" const mac = /(Mac|iPhone|iPad)/.test(navigator.platform) From 1537fa7c9d083383daa684fcdb87e51dbc0ca319 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:17:21 +1000 Subject: [PATCH 25/44] fix(browser): guard retry-only site controls and stylesheet errors --- packages/gui-plugins/src/browser/chromium.ts | 13 +++++++++---- packages/gui-plugins/src/browser/ipc.ts | 5 +++-- packages/gui-plugins/src/browser/model.ts | 4 ++-- .../src/browser/page-machine.test.ts | 13 +++++++++++++ .../gui-plugins/src/browser/page-machine.ts | 9 ++++++++- packages/gui-plugins/src/browser/panel.tsx | 2 +- .../profile/extension-api/styles.test.ts | 5 ++++- .../browser/profile/extension-api/styles.ts | 18 +++++++++++++----- 8 files changed, 53 insertions(+), 16 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 9aab0aa7bc1..ffa89c2c64a 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -25,6 +25,7 @@ import { frameStillCurrent, isDocumentClosed, isNavigationPending, + retryOnly, transitionDocument, type DocumentEvent, } from "./page-machine" @@ -158,7 +159,7 @@ const inspectOff = { mode: "none", highlightConfig: inspectHighlight } const zoomSteps = [0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5] /** A page's icon as a data URL, and its zoom factor, 1 at 100%. */ -export type PageDetail = { icon?: string; zoom: number } +export type PageDetail = { icon?: string; zoom: number; retryOnly?: boolean } /** The zoom a key press asks for: the system browser's zoom keys, with the platform's modifier already checked. */ function zoomKey(input: Electron.Input) { @@ -415,7 +416,9 @@ export function createBrowserPage( const icon = documentIcon(documentState) if (icon) next.icon = icon - const key = `${next.zoom}:${next.icon ?? ""}` + + if (retryOnly(documentState)) next.retryOnly = true + const key = `${next.zoom}:${next.icon ?? ""}:${!!next.retryOnly}` if (key === reported) return reported = key @@ -1090,9 +1093,10 @@ export function createBrowserPage( if (!closed()) zoom(direction) }, async site() { + if (closed() || retryOnly(documentState)) return { cookies: 0 } const url = contents.getURL() - if (closed() || !destinationOrigin(url)) return { cookies: 0 } + if (!destinationOrigin(url)) return { cookies: 0 } return { cookies: (await contents.session.cookies.get({ url })).length } }, @@ -1101,10 +1105,11 @@ export function createBrowserPage( * the page reloaded without them, so a count read next includes what the reload set again. */ async clearSite() { + if (closed() || retryOnly(documentState)) return const url = contents.getURL() const origin = destinationOrigin(url) - if (closed() || !origin) return + if (!origin) return const cookies = await contents.session.cookies.get({ url }) await Promise.all(cookies.map((cookie) => contents.session.cookies.remove(cookieURL(cookie), cookie.name))) await contents.session.clearStorageData({ diff --git a/packages/gui-plugins/src/browser/ipc.ts b/packages/gui-plugins/src/browser/ipc.ts index 9e8dec85db5..99794e03b7b 100644 --- a/packages/gui-plugins/src/browser/ipc.ts +++ b/packages/gui-plugins/src/browser/ipc.ts @@ -163,8 +163,9 @@ export const PaneEvent = Schema.Union([ // Details only this desktop shows, kept out of the server's tab state: the page's icon as a data URL, and its zoom // factor, 1 at 100%. Schema.Struct({ - type: Schema.Literal("page"), - tabID: Browser.TabID, + type: Schema.Literal("page"), + tabID: Browser.TabID, + retryOnly: Schema.optionalKey(Schema.Boolean), icon: Schema.optionalKey(detail(MAX_ICON_URL).check(Schema.isStartingWith("data:image/"))), zoom: Schema.Finite.check(Schema.isBetween({ minimum: 0.25, maximum: 5 })), }), diff --git a/packages/gui-plugins/src/browser/model.ts b/packages/gui-plugins/src/browser/model.ts index ad6889d3e56..56d8a33455d 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -68,7 +68,7 @@ type ModelState = { } /** A page's icon as a data URL, and its zoom factor, 1 at 100%. */ -type PageDetail = { icon?: string; zoom: number } +type PageDetail = { icon?: string; zoom: number; retryOnly?: boolean } /** A mounted pane; the newest one answers the reload and inspect commands. */ type PaneHandle = { @@ -421,7 +421,7 @@ export function createModel(ctx: SetupContext<typeof definition>) { const page = (sessionKey: string, event: PageEvent) => { setState("pages", sessionKey, (pages) => ({ ...pages, - [event.tabID]: event.icon ? { icon: event.icon, zoom: event.zoom } : { zoom: event.zoom }, + [event.tabID]: { icon: event.icon, zoom: event.zoom, retryOnly: event.retryOnly }, })) const url = sessionTab(machine(), sessionKey, event.tabID)?.url const visits = url && event.icon ? withIcon(history.value.visits, url, event.icon) : undefined diff --git a/packages/gui-plugins/src/browser/page-machine.test.ts b/packages/gui-plugins/src/browser/page-machine.test.ts index 80d3e1ab729..f7890bbae61 100644 --- a/packages/gui-plugins/src/browser/page-machine.test.ts +++ b/packages/gui-plugins/src/browser/page-machine.test.ts @@ -8,6 +8,7 @@ import { frameStillCurrent, isDocumentLoading, isNavigationPending, + retryOnly, transitionDocument, type DocumentEvent, type DocumentState, @@ -112,6 +113,18 @@ test("a failed local history entry has no address to open, not the previous HTTP expect(documentTab(replay([event], shown()).state, history)).toMatchObject({ url: "about:blank", loadError: "ERR_FAILED" }) }) +test("site controls are unavailable for a failed page showing a retry address until that address loads", () => { + const url = "https://retry.test/" + const failed = transitionDocument(shown(), { type: "navigation.failed", code: -324, description: "ERR_EMPTY_RESPONSE", url: "https://failed.test/", isMainFrame: true }).state + const stopped = transitionDocument(failed, { type: "navigation.held-stopped", address: url }) + expect(documentTab(stopped.state, history).url).toBe(url) + expect(retryOnly(stopped.state)).toBe(true) + expect(types(stopped.effects)).toContain("detail") + const loaded = replay(visit(url), stopped.state) + expect(retryOnly(loaded.state)).toBe(false) + expect(types(loaded.all)).toContain("detail") +}) + test.each(["workspace://ses_a/report.html", "file:///work/report.html", "artifact://art_a/"])("a failed restore retains its verified retry address %s", (url) => { const event = { type: "navigation.failed", code: -2, description: "ERR_FAILED", url: "oc-preview://grant/report.html", preview: url, isMainFrame: true } as const expect(documentTab(replay([event], createDocumentState({ url, generation: 1, title: "Report" })).state, history)).toMatchObject({ url, loadError: "ERR_FAILED" }) diff --git a/packages/gui-plugins/src/browser/page-machine.ts b/packages/gui-plugins/src/browser/page-machine.ts index 073550c6a27..17afb1834f5 100644 --- a/packages/gui-plugins/src/browser/page-machine.ts +++ b/packages/gui-plugins/src/browser/page-machine.ts @@ -199,6 +199,11 @@ export function documentVisible(state: DocumentState) { return state.status === "loaded" && state.revealed } +/** The address bar offers another load, not a site whose storage can be inspected or cleared. */ +export function retryOnly(state: DocumentState) { + return state.status !== "closed" && state.status !== "loaded" && !!state.retry +} + export function documentIcon(state: DocumentState) { return state.status === "closed" ? undefined : state.icon } @@ -313,7 +318,9 @@ function settle(previous: Open, next: Open, effects: readonly DocumentEffect[]): const shown: readonly DocumentEffect[] = visible === documentVisible(previous) ? [] : [{ type: "show", visible }] const publish = isDocumentLoading(next) !== isDocumentLoading(previous) && !effects.includes(PUBLISH) - return { state: next, effects: [...shown, ...effects, ...(publish ? [PUBLISH] : [])] } + const siteChanged = retryOnly(previous) !== retryOnly(next) && !effects.includes(DETAIL) + + return { state: next, effects: [...shown, ...(siteChanged ? [DETAIL] : []), ...effects, ...(publish ? [PUBLISH] : [])] } } function unchanged(state: DocumentState): DocumentTransition { diff --git a/packages/gui-plugins/src/browser/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index bfdec221ae8..2cedc4f80ac 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -329,7 +329,7 @@ export default function SessionBrowserPane(props: { // The address field always shows the whole URL; at rest it draws the host emphasized. const webParts = createMemo(() => hostDisplay(addressBar().field)) const parts = () => webParts() ?? addressParts(addressBar().field) - const site = () => !!addressBar().field && !addressBar().editing + const site = () => !!addressBar().field && !addressBar().editing && !page()?.retryOnly const recent = () => props.model.visits().slice(0, RECENT) // A loopback address opens on the machine that runs the server; the system browser here reaches it only when the diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts index ec9de839a7f..09dd4745e8f 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts @@ -59,6 +59,8 @@ function fixture() { const item = ask?.({ senderFrame: f }) if (item) css.push(item.css) + + if (item?.remove && item.origin === "user" && id === 8) return void ipc.emit(channel, {}, "user-removal") ipc.emit(channel, {}, !!item && id !== 8) }, } @@ -93,7 +95,7 @@ function fixture() { test("a toolbar grant covers only this tab and origin until cross-origin navigation, release or forget", async () => { const f = fixture() const style = () => f.mv2([{ code: "p{}" }]) // omitted tab ID resolves in the caller's window - await expect(style()).rejects.toThrow("Cannot access") + await expect(style()).rejects.toThrow(/^Cannot access contents of the page\.$/) f.styles.grant(f.extension, 3) await style() f.navigate(f.root + "other") @@ -114,6 +116,7 @@ test("private tops deny before frame selection on both paths; a lost child does const f = fixture() f.styles.grant(f.extension, 3) await f.mv2([{ allFrames: true, code: "p{}" }]) + await expect(Promise.resolve(f.styles.module.methods["tabs.removeCSS"]!({ extension: f.extension }, [{ allFrames: true, code: "p{}", cssOrigin: "user" }]))).rejects.toThrow("cannot remove a user-origin stylesheet") await expect(f.mv2([{ frameId: 8, code: "p{}" }])).rejects.toThrow("no longer available") expect(f.mv3({ tabId: 3, allFrames: true })).toEqual({ tabId: 3, frameIds: [0, 8] }) f.navigate("oc-preview://private/report") diff --git a/packages/gui-plugins/src/browser/profile/extension-api/styles.ts b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts index 495a58bf0bf..19c7bbde6df 100644 --- a/packages/gui-plugins/src/browser/profile/extension-api/styles.ts +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts @@ -10,6 +10,10 @@ import type { ExtensionTabs } from "./tabs" const Origin = Schema.Literals(["author", "user"]) +const denied = "Cannot access contents of the page." + +class UserSheetRemovalError extends Error {} + const Details = Schema.Struct({ code: Schema.optional(Schema.String), file: Schema.optional(Schema.String), frameId: Schema.optional(Schema.Int), allFrames: Schema.optional(Schema.Boolean), matchAboutBlank: Schema.optional(Schema.Boolean), cssOrigin: Schema.optional(Origin), runAt: Schema.optional(Schema.Literals(["document_start", "document_end", "document_idle"])) }) const Arguments = Schema.Union([Schema.Tuple([Details]), Schema.Tuple([Schema.NullOr(Schema.Int), Details])]) @@ -93,7 +97,7 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { owners.set(extension.id, owner) const top = tab.contents.mainFrame - if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error("Cannot access contents of the page.") + if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error(denied) const allowed = (frame: WebFrameMain) => !owner.signal.aborted && !tab.contents.isDestroyed() && tabs.get(tab.contents.id) === tab && !frame.isDestroyed() && !frame.detached && tab.contents.mainFrame === top && canStyle(top.url, frame.url, frame.origin, manifest(extension).hosts, grants.get(tab.contents.id)?.get(extension.id), !!details.matchAboutBlank, tab.window.webContents.getURL()) @@ -103,7 +107,7 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { if (frames.some(f => !f)) throw new Error(`No frame with id ${details.frameId} in tab ${current}.`) const targets = frames.filter((f): f is WebFrameMain => !!f && allowed(f)) - if (!targets.length) throw new Error("Cannot access contents of the page. Extension manifest must request permission to access the respective host.") + if (!targets.length) throw new Error(denied) const css = details.code ?? await packageCSS(extension, details.file ?? "") const results = await Promise.allSettled(targets.map(async frame => { @@ -133,7 +137,7 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { Promise.resolve().then(() => frame.send("browser-extension:css", channel, remove ? "document_start" : details.runAt ?? "document_idle", blank)), ]).catch(cause => { throw lifetime.signal.reason === absent ? absent : cause }) - if (reply[1] === "user-removal") throw new Error("Electron cannot remove a user-origin stylesheet until the document is reloaded.") + if (reply[1] === "user-removal") throw new UserSheetRemovalError("Electron cannot remove a user-origin stylesheet until the document is reloaded.") if (reply[1] !== true) throw new Error("The target frame is no longer available.") } finally { @@ -145,6 +149,10 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { } })) + for (const result of results) { + if (remove && result.status === "rejected" && result.reason instanceof UserSheetRemovalError) throw result.reason + } + if (!results.some(result => result.status === "fulfilled")) { const failure = results.find(result => result.status === "rejected") @@ -167,7 +175,7 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { if (!tab) throw new Error(`No tab with id: ${input.target.tabId}.`) const top = tab.contents.mainFrame - if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error("Cannot access contents of the page.") + if (!publicTop(top.url, tab.window.webContents.getURL())) throw new Error(denied) const ids = input.target.frameIds ?? [0] const frames = top.framesInSubtree.map(frame => ({ frame, id: frame === top ? 0 : frame.frameTreeNodeId })) @@ -175,7 +183,7 @@ export function createStyles(tabs: ExtensionTabs, manifest: Manifests) { const requested = frames.filter(f => input.target.allFrames || ids.includes(f.id)) const allowed = requested.filter(({ frame }) => canStyle(top.url, frame.url, frame.origin, manifest(context.extension).hosts, grants.get(tab.contents.id)?.get(context.extension.id), false, tab.window.webContents.getURL())) - if (!allowed.length || (!input.target.allFrames && requested.length !== allowed.length)) throw new Error("Cannot access contents of the page.") + if (!allowed.length || (!input.target.allFrames && requested.length !== allowed.length)) throw new Error(denied) return { tabId: tab.contents.id, frameIds: allowed.map(f => f.id) } }) From 7fe1f810a2202d52bc63bd7fc83055aa5dade974 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:24:27 +1000 Subject: [PATCH 26/44] fix(browser): distinguish unattached inventory from unexecuted actions --- packages/core/test/browser-permission.test.ts | 2 +- packages/core/test/browser-tools.test.ts | 5 +++-- packages/plugin-browser/src/tools.ts | 7 +++++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index ca7e6518591..121b6cd2709 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -427,7 +427,7 @@ it.live("without a deny, a session with no desktop hears that it is disconnected const status = (yield* browser.call("build", detached.id)).output expect(status).toMatchObject({ connected: false, message: expect.stringContaining("retry only after it attaches") }) for (const [op, input] of [["preview", { path: "page.html" }], ["preview", { path: "missing.html" }], ["wait", { tabID: tab.id, selector: "#done" }], ["snapshot", { tabID: missingTab }]] as const) - expect((yield* browser.run(op, input, "build", detached.id)).output).toEqual(status) + expect((yield* browser.run(op, input, "build", detached.id).pipe(Effect.flip)).message).toStartWith("[browser.not_attached]") expect(browser.commands.count).toBe(0) }), ) diff --git a/packages/core/test/browser-tools.test.ts b/packages/core/test/browser-tools.test.ts index 34719072df9..090ab902868 100644 --- a/packages/core/test/browser-tools.test.ts +++ b/packages/core/test/browser-tools.test.ts @@ -293,7 +293,7 @@ it.live("HTML preview passes the checked relative path and requires a usable tab }), ) -it.live("preview fails for a missing file, and returns attachment status without a desktop", () => +it.live("preview fails for a missing file; an unattached inventory stays iterable and actions do not report success", () => Effect.gen(function* () { const browser = yield* setup((action) => success(action.type === "preview" ? { path: action.path } : tab)) yield* Effect.promise(() => Bun.write(join(browser.directory, "chart.svg"), "<svg/>")) @@ -307,6 +307,7 @@ it.live("preview fails for a missing file, and returns attachment status without const detached = yield* setup(() => success(tab), { attach: false }) yield* Effect.promise(() => Bun.write(join(detached.directory, "chart.svg"), "<svg/>")) - expect(JSON.parse(yield* detached.run(`return await tools.browser.preview({ path: "chart.svg" })`))).toMatchObject({ connected: false }) + expect(JSON.parse(yield* detached.run(`const s = await tools.browser.tabs.list({}); return { ...s, tabs: s.tabs.map(t => t.id) }`))).toMatchObject({ connected: false, tabs: [], focusedTabID: null }) + expect(yield* detached.run(`try { await tools.browser.click({ tabID: "${tabID}", ref: "e1" }); return "Done" } catch (error) { return error.message }`)).toStartWith("[browser.not_attached]") }), ) diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index f99dcb31ed3..cbedd03fed8 100644 --- a/packages/plugin-browser/src/tools.ts +++ b/packages/plugin-browser/src/tools.ts @@ -146,7 +146,10 @@ export const register = Effect.fn("BrowserTools.register")(function* ( const action = input.type === "wait" ? { ...input, plan: yield* parse(() => waitPlan(input)) } : yield* parse(() => normalizeAction(input)) const paths = "paths" in action ? action.paths.map((path) => BrowserFiles.uploadPath(ctx.location.directory, path)) : undefined const approved = yield* connection.authorize(tool, action, paths ?? (action.type === "preview" ? [action.path] : undefined)) - if (approved.connected === false) return { output: approved, content: [{ type: "text" as const, text: approved.message }] } + if (approved.connected === false) { + if (action.type === "tabs.list") return { output: { ...approved, tabs: [], focusedTabID: null }, content: [{ type: "text" as const, text: approved.message }] } + return yield* new Tool.Error({ metadata: { code: "not_attached" }, message: `[browser.not_attached] ${approved.message}` }) + } if (action.type === "wait") return yield* wait(action.tabID, action.plan, tool, approved) if (action.type === "preview" && ctx.location.workspaceID) return yield* new Tool.Error({ message: "Browser preview requires a server-local workspace." }) const checked = action.type === "preview" ? { ...action, path: yield* previewable(action.path, tool) } : action @@ -182,7 +185,7 @@ export const register = Effect.fn("BrowserTools.register")(function* ( name: operation.name.slice(separator + 1), description: operation.description, input: operation.input, - output: Schema.Union([operation.output, Schema.Struct({ connected: Schema.Literal(false), message: Schema.String })]), + output: operation.name === "tabs.list" ? Schema.Struct({ ...Browser.State.fields, connected: Schema.optional(Schema.Literal(false)), message: Schema.optional(Schema.String) }) : operation.output, options: { namespace: separator < 0 ? "browser" : `browser.${operation.name.slice(0, separator)}`, permission: "browser", From 9ce389d03de5df5d168f69c04c09dbc9c7eedea2 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:24:54 +1000 Subject: [PATCH 27/44] fix(desktop): run menu key equivalents in a window without the keyboard After Cmd+M with a page prompt focused, the minimized window stayed the menu's command window and its active element stayed in the prompt, so Cmd+N and Cmd+, were dropped. Only a document that has focus drops an accelerator-chosen command now. --- packages/desktop/src/renderer/platform/menu.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/desktop/src/renderer/platform/menu.ts b/packages/desktop/src/renderer/platform/menu.ts index d855e61ded6..74c04c7756f 100644 --- a/packages/desktop/src/renderer/platform/menu.ts +++ b/packages/desktop/src/renderer/platform/menu.ts @@ -30,7 +30,8 @@ function dispatch(event: MenuRouterEvent) { */ export function startDesktopMenu(api: ElectronAPI) { api.onMenuCommand((id, accelerator) => { - if (accelerator && keyboardOwned(document.activeElement)) return + // A minimized or unfocused window keeps its active element: only a window with the keyboard drops the command. + if (accelerator && document.hasFocus() && keyboardOwned(document.activeElement)) return dispatch({ type: "command.received", id }) }) } From 7579102889708b12d86ec2baf0a149213117ecd5 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:27:09 +1000 Subject: [PATCH 28/44] fix(browser): let F6 and the address shortcut leave a page prompt open Swallowing F6 and Ctrl/Cmd+L left Escape, which cancels, as the only keyboard way out of a prompt. As in Chrome with a tab-modal dialog, F6, Shift+F6 and the address shortcut now move the keyboard to the pane's address field and leave the prompt open; Tab or a click on the dimmed page brings it back. --- .../component-tests/browser-pane-restore.spec.ts | 16 +++++++++++++++- .../app/component-tests/browser-pane.spec.ts | 6 +++--- packages/gui-plugins/src/browser/panel.tsx | 4 +++- .../gui-plugins/src/browser/prompt-keys.test.ts | 8 +++++++- packages/gui-plugins/src/browser/prompt-keys.ts | 11 ++++++++++- packages/gui-plugins/src/browser/prompts.tsx | 8 ++++++++ 6 files changed, 46 insertions(+), 7 deletions(-) diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 2c1b2742dc3..83873967d91 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -725,8 +725,22 @@ story( await expect(reloads).toHaveText("0") await expect(reviews).toHaveText("0") - // The prompt is modal for its tab only: on the address field the pane's shortcuts work and the prompt stays open. + // F6, Shift+F6 and the address shortcut leave the prompt open for the address field, as in Chrome; Tab comes back. const address = root.getByRole("combobox", { name: "Browser address", exact: true }) + + for (const chord of ["F6", "Shift+F6", "ControlOrMeta+l"]) { + await field.focus() + await page.keyboard.press(chord) + await expect(address).toBeFocused() + await expect(dialog).toBeVisible() + } + + await expect(async () => { + await page.keyboard.press("Tab") + await expect(field).toBeFocused({ timeout: 100 }) + }).toPass() + + // The prompt is modal for its tab only: on the address field the pane's shortcuts work and the prompt stays open. await address.click() await address.press("ControlOrMeta+r") await expect(reloads).toHaveText("1") diff --git a/packages/app/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index b78ce71de94..d74006b75a9 100644 --- a/packages/app/component-tests/browser-pane.spec.ts +++ b/packages/app/component-tests/browser-pane.spec.ts @@ -1088,10 +1088,10 @@ story("keeps the keys inside a page prompt, and leaves them to the window once t await page.keyboard.type(" two") await log() - // Reload, the agent switch, find, address field, close and new tab, zoom and history do nothing here. - for (const chord of ["Control+r", "Control+.", "Control+f", "Control+l", "Control+w", "Control+t", "Control+Equal", "Alt+ArrowLeft", "F5"]) + // Reload, the agent switch, find, close and new tab, zoom and history do nothing here. + for (const chord of ["Control+r", "Control+.", "Control+f", "Control+w", "Control+t", "Control+Equal", "Alt+ArrowLeft", "F5"]) await page.keyboard.press(chord) - expect(await log()).toEqual(["r", ".", "f", "l", "w", "t", "=", "ArrowLeft", "F5"].map((key) => `${key}:prevented`)) + expect(await log()).toEqual(["r", ".", "f", "w", "t", "=", "ArrowLeft", "F5"].map((key) => `${key}:prevented`)) // Editing keys edit the field as they do anywhere. await page.keyboard.press("Control+a") await page.keyboard.press("ArrowRight") diff --git a/packages/gui-plugins/src/browser/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index 70ca9af2bcc..91db0e88213 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -977,7 +977,9 @@ export default function SessionBrowserPane(props: { <Show when={promptKey(true)} keyed> {(key) => ( <Show when={key ? prompt() : undefined}> - {(view) => <PromptDialog view={view()} answer={answer} focus={untrack(promptFocus)} />} + {(view) => ( + <PromptDialog view={view()} answer={answer} focus={untrack(promptFocus)} leave={focusAddress} /> + )} </Show> )} </Show> diff --git a/packages/gui-plugins/src/browser/prompt-keys.test.ts b/packages/gui-plugins/src/browser/prompt-keys.test.ts index 87de7c6e618..aac672c6387 100644 --- a/packages/gui-plugins/src/browser/prompt-keys.test.ts +++ b/packages/gui-plugins/src/browser/prompt-keys.test.ts @@ -42,10 +42,15 @@ describe("keys inside an open page prompt", () => { test(`never run the app's or the pane's shortcuts behind it on ${os}`, () => { // Reload, the agent switch, find, address field, close and new tab, zoom, palette, model picker, back, and the // editing letters with a Shift that edits nothing (select an element, a new incognito-style window). - for (const chord of ["mod+r", "mod+.", "mod+f", "mod+l", "mod+w", "mod+t", "mod+=", "mod++", "mod+-", "mod+0", "Shift+mod+p", "mod+k", "mod+'", "F5", "F3", "F6", "Shift+mod+r", "Shift+mod+a", "Shift+mod+c", "Shift+mod+x"]) + for (const chord of ["mod+r", "mod+.", "mod+f", "mod+w", "mod+t", "mod+=", "mod++", "mod+-", "mod+0", "Shift+mod+p", "mod+k", "mod+'", "F5", "F3", "Shift+mod+r", "Shift+mod+a", "Shift+mod+c", "Shift+mod+x", "Shift+mod+l"]) expect(owner(chord, mac), chord).toBe("swallowed") }) + test(`leave the prompt open for the address field on F6 and the address shortcut on ${os}`, () => { + for (const chord of ["F6", "Shift+F6", "mod+l"]) expect(owner(chord, mac), chord).toBe("exit") + expect(owner("mod+д", mac, { as: { code: "KeyL" } })).toBe("exit") + }) + test(`leave the window's own keys to the window on ${os}`, () => { for (const chord of ["Shift+mod+w", "Shift+mod+n"]) expect(owner(chord, mac)).toBe("window") }) @@ -88,6 +93,7 @@ describe("keys inside an open page prompt", () => { expect(owner(chord, false), chord).toBe("field") expect(owner("Alt+ArrowLeft", false)).toBe("swallowed") expect(owner("Alt+F", false)).toBe("swallowed") + expect(owner("Alt+F6", false)).toBe("swallowed") }) test("macOS edits text with Option and Control and keeps its window chords", () => { diff --git a/packages/gui-plugins/src/browser/prompt-keys.ts b/packages/gui-plugins/src/browser/prompt-keys.ts index bc9eec0d810..1512c306103 100644 --- a/packages/gui-plugins/src/browser/prompt-keys.ts +++ b/packages/gui-plugins/src/browser/prompt-keys.ts @@ -17,7 +17,12 @@ export type PromptKeyOwner = | "field" /** The window or the system, as Chrome leaves them with a tab-modal dialog: close or new window, quit, hide, full screen. */ | "window" - /** Nothing: an app or pane shortcut (reload, find, zoom, history, tabs, the address field, the agent, the palette). */ + /** + * The keyboard leaves the prompt for the pane's address field, which stays open: F6, Shift+F6 and the address + * shortcut, as they leave a tab-modal dialog in Chrome. Escape would cancel the prompt. + */ + | "exit" + /** Nothing: an app or pane shortcut (reload, find, zoom, history, tabs, the agent, the palette). */ | "swallowed" /** The keyboard is elsewhere, such as the chat composer: the app's shortcuts as usual, and the prompt stays open. */ | "app" @@ -55,6 +60,10 @@ export function promptKeyOwner( if (plain && (name === "Enter" || name === "Escape" || name === "Tab")) return "prompt" + if (plain && name === "F6") return "exit" + + if (command && !key.shiftKey && !key.altKey && !(input.mac ? key.ctrlKey : key.metaKey) && name === "l") return "exit" + // Shift+F10 opens the field's context menu on Windows and Linux. if (plain) return /^F\d{1,2}$/.test(name) && !(!input.mac && key.shiftKey && name === "F10") ? "swallowed" : "field" diff --git a/packages/gui-plugins/src/browser/prompts.tsx b/packages/gui-plugins/src/browser/prompts.tsx index f50c18bc519..2875bf09752 100644 --- a/packages/gui-plugins/src/browser/prompts.tsx +++ b/packages/gui-plugins/src/browser/prompts.tsx @@ -30,6 +30,8 @@ export function PromptDialog(props: { answer: (answer: PromptAnswer) => void /** Whether to take keyboard focus as it opens; false while the user works elsewhere in the window. */ focus: boolean + /** Moves the keyboard out to the pane's address field, with the dialog left open. */ + leave: () => void }) { const ctx = usePlugin<typeof definition>() const title = createUniqueId() @@ -106,6 +108,12 @@ export function PromptDialog(props: { if (owner === "swallowed") return event.preventDefault() + if (owner === "exit") { + event.preventDefault() + + return props.leave() + } + if (cancelKey(event)) { event.preventDefault() event.stopPropagation() From 8df4933923e443c8ae7d8474ad94ba3a29e0092b Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:25:43 +1000 Subject: [PATCH 29/44] fix(browser): reject conflicting scripts and describe file IDs --- packages/plugin-browser/src/rpc.ts | 8 ++++---- packages/plugin-browser/src/tools.ts | 2 ++ packages/plugin-browser/test/rpc.test.ts | 1 + packages/plugin-browser/test/tools.test.ts | 2 ++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index f0d36f6b8ce..51add066ce7 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -74,9 +74,9 @@ export const Ref = Schema.String.check(Schema.isPattern(/^@?e[1-9][0-9]*$/u)) .pipe(Schema.brand("Browser.Ref")) .annotate({ identifier: "Browser.Ref" }) export type Ref = typeof Ref.Type -export const FileID = Schema.String.check(Schema.isPattern(/^file_[a-f0-9-]{36}$/u)) +const fileID = Schema.String.check(Schema.isPattern(/^file_[a-f0-9-]{36}$/u)) .pipe(Schema.brand("Browser.FileID")) - .annotate({ identifier: "Browser.FileID" }) +export const FileID = fileID.annotate({ identifier: "Browser.FileID" }) export type FileID = typeof FileID.Type const tab = { tabID: TabID.annotate({ @@ -101,7 +101,7 @@ const evaluateRef = optional( ) const artifact = { ...tab, - fileID: FileID.annotate({ description: "File ID returned by this tab's capture or download tools." }), + fileID: fileID.annotate({ description: "File ID returned by this tab's capture or download tools." }), } export interface Tab extends Schema.Schema.Type<typeof Tab> {} @@ -509,7 +509,7 @@ export const Operations = [ "Copy one completed download or capture from this tab to the server. Returns a server-local file path. Maximum 5 MiB per transfer.", artifact, saved, - { ...tab, fileID: optional(FileID), id: optional(FileID.annotate({ description: "Alias for fileID." })) }, + { ...tab, fileID: optional(artifact.fileID), id: optional(FileID.annotate({ description: "Alias for fileID." })) }, ), operation( "console", diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index cbedd03fed8..fc63f759769 100644 --- a/packages/plugin-browser/src/tools.ts +++ b/packages/plugin-browser/src/tools.ts @@ -503,6 +503,8 @@ const selectorVisibility = (selector: string) => function evaluateAction(input: Extract<Browser.Input, { readonly type: "evaluate" }>): Extract<Browser.Action, { type: "evaluate" }> { const script = input.script ?? input.expression ?? input.code + if ([input.expression, input.code].some(value => value !== undefined && value !== script)) + throw new Tool.Error({ message: "Conflicting script, expression or code. Pass one script to evaluate." }) if (script === undefined) throw new Tool.Error({ message: diff --git a/packages/plugin-browser/test/rpc.test.ts b/packages/plugin-browser/test/rpc.test.ts index b2bff8ee4a5..74c2517f760 100644 --- a/packages/plugin-browser/test/rpc.test.ts +++ b/packages/plugin-browser/test/rpc.test.ts @@ -59,6 +59,7 @@ test("optional parameters keep their descriptions in the model's JSON Schema", ( expect(properties("evaluate").expression?.description).toBe("Same as script.") expect(properties("evaluate").frameID?.description).toBe("Frame ID from browser.frames. Omit for the main frame.") expect(properties("wait").timeout?.description).toBe("Same as timeoutMs.") + expect(properties("files.get").fileID?.description).toBe("File ID returned by this tab's capture or download tools.") }) test("browser files are bounded bytes, not remote filesystem paths", () => { diff --git a/packages/plugin-browser/test/tools.test.ts b/packages/plugin-browser/test/tools.test.ts index 1decb8e75bc..44e8137a95e 100644 --- a/packages/plugin-browser/test/tools.test.ts +++ b/packages/plugin-browser/test/tools.test.ts @@ -28,6 +28,8 @@ test("model-written aliases decode to canonical desktop actions; conflicting cho expect(parse({ type: "network.get", tabID, requestID: "r1", includeResponseBody: true })).toEqual({ type: "network.get", tabID, id: "r1", includeResponseBody: true }) expect(() => parse({ type: "fill", tabID, ref, text: "keep", value: "replace" })).toThrow("Conflicting") expect(() => parse({ type: "find", tabID })).toThrow("Missing text") + expect(() => parse({ type: "evaluate", tabID, expression: "1", code: "2" })).toThrow("Conflicting") + expect(parse({ type: "evaluate", tabID, expression: "1", script: "1" })).toEqual({ type: "evaluate", tabID, script: "1" }) }) test("built-in browser skill uses a virtual skill:// URI", () => { From fc81f109603477a794aa3b13c71b6f959d15d47d Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:29:47 +1000 Subject: [PATCH 30/44] fix(app): let only a registered surface claim the keyboard from the command layer A data-owns-keyboard attribute survives into chat markdown, so a focused link carrying it suppressed the app's shortcuts. The page prompt now registers its element in code (ownKeyboard in @opencode/ui/hooks), and the command layer and the desktop menu bridge honour only registered elements; the attribute is gone. --- .../browser-pane-restore.spec.ts | 4 +++- packages/app/src/desktop.ts | 2 +- packages/app/src/shell/commands/command.tsx | 11 ++-------- .../desktop/src/renderer/platform/menu.ts | 3 ++- .../gui-plugins/src/browser/prompt-keys.ts | 2 +- packages/gui-plugins/src/browser/prompts.tsx | 7 ++++--- packages/ui/src/hooks/index.ts | 2 ++ packages/ui/src/hooks/keyboard-owner.ts | 20 +++++++++++++++++++ 8 files changed, 35 insertions(+), 16 deletions(-) create mode 100644 packages/ui/src/hooks/keyboard-owner.ts diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 83873967d91..f353929c52c 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -761,11 +761,13 @@ story( await never.press("Escape") await expect(bar).toBeHidden() - // Another modal surface, as a mobile drawer, keeps the app's shortcuts. + // Another modal surface, as a mobile drawer, keeps the app's shortcuts; markup alone, as a chat message's, cannot + // claim the keyboard. await page.evaluate(() => { const drawer = document.createElement("div") drawer.setAttribute("role", "dialog") drawer.setAttribute("aria-modal", "true") + drawer.setAttribute("data-owns-keyboard", "") drawer.append(Object.assign(document.createElement("button"), { textContent: "Drawer action" })) document.body.append(drawer) }) diff --git a/packages/app/src/desktop.ts b/packages/app/src/desktop.ts index 8617aeb7848..581b737be30 100644 --- a/packages/app/src/desktop.ts +++ b/packages/app/src/desktop.ts @@ -1,6 +1,6 @@ export { AppBaseProviders, AppInterface, preloadRoute } from "./app" -export { keyboardOwned, useCommand } from "./shell/commands/command" +export { useCommand } from "./shell/commands/command" export { currentRoute, type LayoutRoute, useCurrentRoute } from "./shell/state/layout" diff --git a/packages/app/src/shell/commands/command.tsx b/packages/app/src/shell/commands/command.tsx index 03dd97b04ce..105f55b16ee 100644 --- a/packages/app/src/shell/commands/command.tsx +++ b/packages/app/src/shell/commands/command.tsx @@ -1,5 +1,6 @@ import { createSimpleContext } from "@opencode/ui/context" import { useDialog } from "@opencode/ui/context/dialog" +import { keyboardOwned } from "@opencode/ui/hooks" import { type Accessor, batch, createEffect, createMemo, createSignal, onCleanup, onMount, untrack } from "solid-js" import { createStore, produce, reconcile } from "solid-js/store" import { Predicate, Schema } from "effect" @@ -368,15 +369,6 @@ export function formatKeybind(config: string, t?: (key: KeyLabel) => string): st return IS_MAC ? parts.join("") : parts.join("+") } -/** - * Whether `target` is inside a surface that owns the keyboard (`data-owns-keyboard`), such as a page's prompt in the - * browser pane, which is modal for its tab only: no command keybind or native menu key equivalent runs there, as none - * runs while one of the app's own dialogs is open (`dialog.active`). Keys pressed elsewhere in the window are the app's. - */ -export function keyboardOwned(target: EventTarget | null) { - return target instanceof Element && !!target.closest("[data-owns-keyboard]") -} - function isEditableTarget(target: EventTarget | null) { if (!(target instanceof HTMLElement)) return false @@ -523,6 +515,7 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const handleKeyDown = (event: KeyboardEvent) => { + // A surface that owns the keyboard, such as a page's prompt in the browser pane, is modal for less than the window. if (suspended() || dialog.active || keyboardOwned(event.target)) return const sig = signatureFromEvent(event) diff --git a/packages/desktop/src/renderer/platform/menu.ts b/packages/desktop/src/renderer/platform/menu.ts index 74c04c7756f..2b64a2af199 100644 --- a/packages/desktop/src/renderer/platform/menu.ts +++ b/packages/desktop/src/renderer/platform/menu.ts @@ -1,4 +1,5 @@ -import { keyboardOwned, type Platform } from "@opencode/app/desktop" +import type { Platform } from "@opencode/app/desktop" +import { keyboardOwned } from "@opencode/ui/hooks" import type { ElectronAPI } from "../api-types" import { resetZoom, zoomIn, zoomOut } from "../window/zoom" import { diff --git a/packages/gui-plugins/src/browser/prompt-keys.ts b/packages/gui-plugins/src/browser/prompt-keys.ts index 1512c306103..f931a1a59aa 100644 --- a/packages/gui-plugins/src/browser/prompt-keys.ts +++ b/packages/gui-plugins/src/browser/prompt-keys.ts @@ -2,7 +2,7 @@ import { pageLetter } from "./keys" // Who a key pressed in the app window belongs to while a page prompt (alert, confirm, prompt, "Leave site?", a // sign-in) is open in the pane. The prompt is modal for its tab: while the keyboard is inside it, the app's command -// keybinds and the native menu's key equivalents do not run (the prompt marks itself `data-owns-keyboard`), and the +// keybinds and the native menu's key equivalents do not run (the prompt registers itself with `ownKeyboard`), and the // prompt cancels what the window itself would do behind it. Keys outside the prompt are the app's. export type PromptKey = Pick< diff --git a/packages/gui-plugins/src/browser/prompts.tsx b/packages/gui-plugins/src/browser/prompts.tsx index 2875bf09752..6870fe64898 100644 --- a/packages/gui-plugins/src/browser/prompts.tsx +++ b/packages/gui-plugins/src/browser/prompts.tsx @@ -2,6 +2,7 @@ import { Button } from "@opencode/ui/button" import { Checkbox } from "@opencode/ui/checkbox" import { DialogBody, DialogFooter } from "@opencode/ui/dialog" import { Icon } from "@opencode/ui/icon" +import { ownKeyboard } from "@opencode/ui/hooks" import { IconButton } from "@opencode/ui/icon-button" import { TextInput } from "@opencode/ui/text-input" import { Tooltip } from "@opencode/ui/tooltip" @@ -77,6 +78,8 @@ export function PromptDialog(props: { if (!box) return guard = guardActivation(box) onCleanup(guard.dispose) + // The command layer and the native menu run no shortcut while the keyboard is here. + onCleanup(ownKeyboard(box)) // A listener on the dialog itself, not Solid's on the document, so the dialog's keys stop here. const root = box root.addEventListener("keydown", keyDown) @@ -95,7 +98,7 @@ export function PromptDialog(props: { }) // The dialog's keys are its own (prompt-keys.ts): the command layer and the native menu run no shortcut while the - // keyboard is inside it (`data-owns-keyboard`), no other handler of the window sees them, and what the window would do + // keyboard is inside it (`ownKeyboard`), no other handler of the window sees them, and what the window would do // behind it, as its own reload or zoom, is cancelled. Tab and Shift+Tab cycle inside the dialog; the page behind it is // a still. const keyDown = (event: KeyboardEvent) => { @@ -186,8 +189,6 @@ export function PromptDialog(props: { data-slot="dialog-container" role="alertdialog" aria-modal="true" - // The command layer and the native menu run no shortcut while the keyboard is here. - data-owns-keyboard onFocusIn={(event) => { if (event.target instanceof HTMLElement) last = event.target }} diff --git a/packages/ui/src/hooks/index.ts b/packages/ui/src/hooks/index.ts index d41ad2f9729..b13b58bde1d 100644 --- a/packages/ui/src/hooks/index.ts +++ b/packages/ui/src/hooks/index.ts @@ -3,3 +3,5 @@ export * from "./use-filtered-list" export * from "./create-auto-scroll" export * from "./spin-phase" + +export * from "./keyboard-owner" diff --git a/packages/ui/src/hooks/keyboard-owner.ts b/packages/ui/src/hooks/keyboard-owner.ts new file mode 100644 index 00000000000..d41d5794d06 --- /dev/null +++ b/packages/ui/src/hooks/keyboard-owner.ts @@ -0,0 +1,20 @@ +const owners = new WeakSet<Element>() + +/** + * Registers `element` as owning the keyboard while focus is inside it, as a page's prompt in the browser pane does: + * no command keybind or native menu key equivalent runs there, as none runs while one of the app's own dialogs is open. + * Registration happens in code, so markup alone, such as a chat message's, cannot claim the keyboard. Returns the + * release. + */ +export function ownKeyboard(element: Element) { + owners.add(element) + + return () => void owners.delete(element) +} + +/** Whether `target` is inside an element registered with `ownKeyboard`. */ +export function keyboardOwned(target: EventTarget | null): boolean { + if (!(target instanceof Element)) return false + + return owners.has(target) || keyboardOwned(target.parentElement) +} From ccea9a7b936c17faa4edda36abd49803f3b6249b Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:29:52 +1000 Subject: [PATCH 31/44] fix(browser): spend snapshot budgets on labeled controls and form state --- packages/gui-plugins/src/browser/chromium.ts | 5 + .../gui-plugins/src/browser/snapshot.test.ts | 48 +++++- packages/gui-plugins/src/browser/snapshot.ts | 142 ++++++++++++------ 3 files changed, 143 insertions(+), 52 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 83a5914b889..7799d67d8da 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -2267,6 +2267,11 @@ export function createBrowserPage( previous: refs.previous(frameID, sessionID), picked: byNode(picked), ref: options.shared.ref, + // AX does not distinguish password textboxes. Fail closed if the backing input is gone or protected. + readableValue: async backendID => { + abortError(signal) + return (await call({ backendID, frameID, sessionID }, `function() { return this.isConnected && !(this instanceof HTMLInputElement && ['password','file'].includes(this.type)) && getComputedStyle(this).webkitTextSecurity === 'none' }`).catch(() => false)) === true + }, box: action.type === "snapshot" && action.boxes ? async (backendID) => { abortError(signal) const box = await rect({ backendID, frameID, sessionID }, false, tree).catch(() => undefined) diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts index 58cdd42a0e1..dd5efc36ff4 100644 --- a/packages/gui-plugins/src/browser/snapshot.test.ts +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -100,14 +100,56 @@ test("summarizes collections, preserves late selections, and expands a scoped co const tree = [node(1, "listbox", "Cities", ...items.map((_, i) => i + 2)), ...items] const result = await accessibilitySnapshot(tree, options()) expect(result.content).toContain('"City 29" selected=true') - expect(result.content).not.toContain('"City 27"') - expect(result.content).toContain("+4 more in @e1 [listbox]") - expect(result.content).toContain("4 nodes omitted (4 interactive)") + expect(result.content).toContain('"City 27"') + expect(result.truncated).toBe(false) + const short = await accessibilitySnapshot(tree, { ...options(), maxLines: 10 }) + expect(short.content).toContain('"City 29" selected=true') + expect(short.content).toContain("+21 more in @") const scoped = await accessibilitySnapshot(tree, { ...options(), root: 1 }) expect(scoped.truncated).toBe(false) expect(scoped.content).toContain('"City 27"') }) +test("alerts and nested dialogs outrank navigation; invalid fields and safe values survive a tight budget", async () => { + const field = node(4, "textbox", "Email") + field.properties = ["invalid", "readonly", "required"].map((key) => ({ + name: key as "invalid" | "readonly" | "required", + value: { type: "boolean", value: true }, + })) + field.value = { type: "string", value: "bad@" } + const other = { ...node(6, "textbox", "Password"), value: { type: "string" as const, value: "secret" } } + const tree = [ + node(1, "generic", "", 2, 5), + node(2, "navigation", "Routes", 3), + node(3, "dialog", "Submit", 4, 6), + field, + node(5, "alert", "Errors"), + other, + ] + const content = (await accessibilitySnapshot(tree, { ...options(), readableValue: async (id) => id === 4 })).content + expect(content.indexOf("[dialog]")).toBeLessThan(content.indexOf("[navigation]")) + expect(content.indexOf("[alert]")).toBeLessThan(content.indexOf("[navigation]")) + expect(content).toContain('invalid=true required=true readonly=true value="bad@"') + expect(content).not.toContain("secret") +}) + +test("headings inside collapsed card wrappers distinguish identical controls", async () => { + const tree = [ + node(1, "list", "", 2, 6), + node(2, "listitem", "", 3, 5), + node(3, "generic", "", 4), + node(4, "heading", "Alpha"), + node(5, "button", "Edit"), + node(6, "listitem", "", 7, 9), + node(7, "generic", "", 8), + node(8, "heading", "Beta"), + node(9, "button", "Edit"), + ] + const result = await accessibilitySnapshot(tree, { ...options(), interactive: true }) + expect(result.content).toContain('[button] "Edit" in heading "Alpha"') + expect(result.content).toContain('[button] "Edit" in heading "Beta"') +}) + test("prefers a nonignored root and can find a known ref after its role changes", async () => { const first = { ...node(1, "generic", ""), ignored: true, nodeId: "ignored" } diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index 004063c52e5..87aa0b611b7 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -12,12 +12,13 @@ type Options = { picked: ReadonlyMap<number, string> ref: () => string box?: (id: number) => Promise<string> + readableValue?: (id: number) => Promise<boolean> signal?: AbortSignal } -type Area = { id: number; role: string; count: number; skipped: number } +type Area = { id: number; role: string; skipped: number } -type Overflow = { area: Area; keep: boolean; parent?: Overflow } +type Item = { area: Area; keep: boolean; meaningful: boolean; shown: number; parent?: Item } type Branch = { node: Protocol.Accessibility.AXNode @@ -30,24 +31,33 @@ type Branch = { priority?: number area?: Area collection?: Area - overflow?: Overflow + entry?: Item } -type Line = { label: string; id?: number; interactive: boolean; area?: Area; overflow?: Overflow; deep: boolean } +type Line = { + label: string + value?: string + id?: number + interactive: boolean + area?: Area + entry?: Item + important: boolean + deep: boolean +} const controls = /^(button|link|textbox|searchbox|combobox|listbox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem|scrollbar)$/ const collections = /^(table|grid|treegrid|list|listbox|combobox|menu|tree)$/ -const landmarks = /^(dialog|alertdialog|main|form|search|region|navigation|contentinfo|banner|complementary)$/ +const landmarks = /^(alert|dialog|alertdialog|main|form|search|region|navigation|contentinfo|banner|complementary)$/ function excerpt(name: string, limit: number) { return name.length <= limit ? name : `${name.slice(0, limit)}… [+${name.length - limit} chars]` } function rank(role: string) { - if (role === "alertdialog" || role === "dialog") return 1 + if (role === "alert" || role === "alertdialog" || role === "dialog") return 1 if (role === "main") return 2 @@ -75,7 +85,7 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili const buckets = Array.from({ length: 6 }, (): Line[] => []) const seen = new Set<string>() const headings = new Map<string, string>() - const overflowItems: Overflow[] = [] + const items: Item[] = [] const query = options.text?.toLowerCase() while (pending.length) { @@ -115,12 +125,10 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili !(role === "StaticText" && name === branch.parentName && !known) const area = - visible && id && (landmarks.test(role) || collections.test(role)) - ? { id, role, count: 0, skipped: 0 } - : branch.area + visible && id && (landmarks.test(role) || collections.test(role)) ? { id, role, skipped: 0 } : branch.area const collection = area && collections.test(area.role) ? area : branch.collection - const priority = branch.priority ?? (visible ? rank(role) : undefined) + const priority = Math.min(branch.priority ?? 5, (visible && rank(role)) || 5) const inherited = headings.get(branch.parent) ?? branch.scope const scope = @@ -133,7 +141,7 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili const isItem = visible && /^(row|listitem|option)$/.test(role) const itemName = - options.interactive && role === "row" && !name + options.interactive && (role === "row" || role === "listitem") && !name ? String(index.get(children[0])?.name?.value ?? "").replace(/\s+/g, " ") : name @@ -142,25 +150,39 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili ? `${role} ${itemName ? JSON.stringify(excerpt(itemName, 60)) : branch.ordinal}` : branch.item - const overflow = - isItem && collection && options.text === undefined && collection.id !== options.root && ++collection.count > 25 - ? { area: collection, keep: false, parent: branch.overflow } - : branch.overflow - - if (overflow && overflow !== branch.overflow) overflowItems.push(overflow) - - if ( - overflow && - ["focused", "selected", "checked"].some((key) => - node.properties?.some((p) => p.name === key && [true, "true", "mixed"].includes(p.value.value)), - ) - ) { - for (let group: Overflow | undefined = overflow; group; group = group.parent) group.keep = true + const entry = + isItem && collection + ? { area: collection, keep: false, meaningful: false, shown: 0, parent: branch.entry } + : branch.entry + if (entry && entry !== branch.entry) items.push(entry) + const important = !!node.properties?.some( + (p) => + ["focused", "selected", "checked", "invalid"].includes(p.name) && + ![false, "false", undefined].includes(p.value.value), + ) + if (visible && entry && (interactive || name.trim() || important)) { + entry.meaningful = true + if (important) for (let group: Item | undefined = entry; group; group = group.parent) group.keep = true } if (visible && (!options.interactive || interactive)) { - const flags = (["checked", "disabled", "expanded", "selected", "pressed", "focused"] as const).flatMap((key) => - props.has(key) ? [`${key}=${props.get(key)}`] : [], + const flags = ( + [ + "checked", + "disabled", + "expanded", + "selected", + "pressed", + "focused", + "invalid", + "required", + "readonly", + ] as const + ).flatMap((key) => + props.has(key) && + !(["invalid", "required", "readonly"].includes(key) && [false, "false"].includes(props.get(key))) + ? [`${key}=${props.get(key)}`] + : [], ) const context = options.interactive ? [inherited, branch.item].filter(Boolean).join(" / ") : "" @@ -175,10 +197,15 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili const pad = options.interactive ? "" : " ".repeat(Math.min(12, branch.level)) buckets[role === "RootWebArea" ? 0 : (priority ?? 5)].push({ label: pad + label, + value: + interactive && node.value?.value !== undefined + ? JSON.stringify(excerpt(String(node.value.value), 160)) + : undefined, id: interactive || known || area?.id === id ? id : undefined, interactive, area, - overflow, + entry, + important, deep: branch.level > (options.depth ?? Infinity), }) } @@ -193,25 +220,23 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili pending.push({ node: child, level: branch.level + Number(visible), - parent: node.nodeId, + parent: visible ? node.nodeId : branch.parent, parentName: visible ? name : branch.parentName, scope, item, priority, area, collection, - overflow, + entry, ordinal: i + 1, }) } } - for (const group of overflowItems) if (!group.keep) group.area.skipped++ - - return printSnapshot(buckets, options) + return printSnapshot(buckets, items, options) } -async function printSnapshot(buckets: Line[][], options: Options) { +async function printSnapshot(buckets: Line[][], items: Item[], options: Options) { const refs = new Map<string, number>() const issued = new Map<number, string>() @@ -224,7 +249,7 @@ async function printSnapshot(buckets: Line[][], options: Options) { const maxChars = options.maxChars ?? 20_000 const maxLines = options.maxLines ?? Infinity - const output: { line: Line; text: string }[] = [] + const output: { line: Line; text: string; order: number }[] = [] const areas = new Map<Area | undefined, number>() let omitted = 0 let interactive = 0 @@ -238,29 +263,39 @@ async function printSnapshot(buckets: Line[][], options: Options) { areas.set(line.area, (areas.get(line.area) ?? 0) + 1) } - for (const bucket of buckets) { + for (const original of buckets) { + const order = new Map(original.map((line, i) => [line, i + visited])) + // Select within each landmark's budget by usefulness, then restore tree order for reading. + const groups = Array.from({ length: 4 }, (): Line[] => []) + for (const line of original) + groups[ + line.important || line.entry?.keep ? 0 : line.interactive ? 1 : line.area?.id === line.id && line.id ? 2 : 3 + ].push(line) + const bucket = groups.flat() for (let i = 0; i < bucket.length; i += 32) { const batch = bucket.slice(i, i + 32) - const boxes = - options.box && !full && output.length < maxLines + const details = + !full && output.length < maxLines ? await Promise.all( - batch.map((line) => - !line.deep && (!line.overflow || line.overflow.keep) && line.id ? options.box?.(line.id) : undefined, - ), + batch.map(async (line) => { + if (!line.id || line.deep) return "" + const value = line.value && (await options.readableValue?.(line.id)) ? ` value=${line.value}` : "" + return value + ((await options.box?.(line.id)) ?? "") + }), ) : [] for (const [j, line] of batch.entries()) { if (++visited % 2048 === 0) await setImmediate(undefined, { signal: options.signal }) - if ((line.overflow && !line.overflow.keep) || line.deep || full || output.length >= maxLines) { + if (line.deep || full || output.length >= maxLines) { omit(line) continue } const key = line.id ? ref(line.id) : undefined - const text = (key ? line.label.replace(/^\s*/, (pad) => `${pad}@${key} `) : line.label) + (boxes[j] ?? "") + const text = (key ? line.label.replace(/^\s*/, (pad) => `${pad}@${key} `) : line.label) + (details[j] ?? "") const length = size + Number(output.length > 0) + text.length if (length > maxChars) { @@ -270,19 +305,26 @@ async function printSnapshot(buckets: Line[][], options: Options) { } size = length - output.push({ line, text }) + output.push({ line, text, order: order.get(line) ?? 0 }) } } } - const content = () => output.map(row => { - if (row.line.id) refs.set(ref(row.line.id), row.line.id) + const content = () => + output + .sort((a, b) => a.order - b.order) + .map((row) => { + if (row.line.id) refs.set(ref(row.line.id), row.line.id) - return row.text - }).join("\n") + return row.text + }) + .join("\n") if (!omitted) return { content: content(), truncated: false, refs } + for (const row of output) for (let group = row.line.entry; group; group = group.parent) group.shown++ + for (const group of items) if (group.meaningful && !group.shown) group.area.skipped++ + const footer = () => { const places = Array.from(areas) .slice(0, 5) @@ -303,6 +345,8 @@ async function printSnapshot(buckets: Line[][], options: Options) { const last = output.pop() if (!last) break + for (let group = last.line.entry; group; group = group.parent) + if (--group.shown === 0 && group.meaningful) group.area.skipped++ omit(last.line) size -= last.text.length + Number(output.length > 0) hint = footer() From aba3ec42b1560bb81816131295d7279befef16b9 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:31:10 +1000 Subject: [PATCH 32/44] fix(browser): evict old refs and refuse detached targets --- packages/gui-plugins/src/browser/chromium.ts | 21 ++++++++++++------- packages/gui-plugins/src/browser/refs.test.ts | 12 ++++++++++- packages/gui-plugins/src/browser/refs.ts | 10 +++++++++ 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 7799d67d8da..ecb2cfad8fb 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -89,6 +89,15 @@ import type { artifactPages } from "./artifact-preview" type Element = { backendID: number; frameID: string; sessionID?: string } +// A page can retain a removed node. Check in the same renderer call that reads or acts on the ref. +function connectedFunction(fn: string) { + return `function(...args) { if (!this.isConnected) throw new Error('browser.detached_ref'); return (${fn}\n).apply(this,args) }` +} + +function detachedRef() { + return new CodedError(Browser.FailureCode.staleRef, "Element is no longer connected. Take a fresh snapshot and choose a current ref.") +} + const noVisibleArea = "Element has no visible screenshot area. Take a fresh snapshot and choose a visible element, or omit ref to capture the viewport." /** State every page of the pane shares: the element ref allocator and the owner of the app-wide trace. */ @@ -1374,7 +1383,7 @@ export function createBrowserPage( "Runtime.callFunctionOn", { objectId, - functionDeclaration: action.script, + functionDeclaration: connectedFunction(action.script), arguments: [{ objectId }], awaitPromise: true, returnByValue: true, @@ -1393,6 +1402,7 @@ export function createBrowserPage( context?.sessionID, )) + if (element && value.exceptionDetails?.exception?.description?.startsWith("Error: browser.detached_ref\n")) throw detachedRef() if (value.exceptionDetails) throw new Error( `Page JavaScript threw an exception. Check the script and ${action.ref ? "ref" : "frameID"}; inspect the page before repeating code with side effects. Details: ${(value.exceptionDetails.exception?.description ?? value.exceptionDetails.text).slice(0, 800)}`, @@ -1835,7 +1845,7 @@ export function createBrowserPage( "Runtime.callFunctionOn", { objectId, - functionDeclaration, + functionDeclaration: connectedFunction(functionDeclaration), arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise: true, @@ -1843,6 +1853,7 @@ export function createBrowserPage( element.sessionID, ) + if (result.exceptionDetails?.exception?.description?.startsWith("Error: browser.detached_ref\n")) throw detachedRef() if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text) @@ -1856,11 +1867,7 @@ export function createBrowserPage( async function resolve(element: Element) { const object = await cdp.send("DOM.resolveNode", { backendNodeId: element.backendID }, element.sessionID) - if (!object.object.objectId) - throw new CodedError( - Browser.FailureCode.staleRef, - "Element is no longer available. Call browser.snapshot({tabID}) and use a fresh ref; the page may have replaced the element.", - ) + if (!object.object.objectId) throw detachedRef() return object.object.objectId } diff --git a/packages/gui-plugins/src/browser/refs.test.ts b/packages/gui-plugins/src/browser/refs.test.ts index 18a6ef8b0dd..a2bb2e7adf1 100644 --- a/packages/gui-plugins/src/browser/refs.test.ts +++ b/packages/gui-plugins/src/browser/refs.test.ts @@ -1,6 +1,16 @@ import { expect, test } from "bun:test" import { Schema } from "effect" -import { createRefs, RefsStore } from "./refs" +import { createRefs, documentRefs, RefsStore } from "./refs" + +test("a long-lived document evicts its oldest refs from both lookups", () => { + const refs = documentRefs() + refs.add("first", undefined, new Map([["e1", 10]])) + refs.add("second", "session", new Map(Array.from({length:10_000}, (_, i) => [`e${i+2}`, i+1]))) + expect(refs.get("e1")).toBeUndefined() + expect(refs.previous("first").size).toBe(0) + expect(refs.previous("second", "session").size).toBe(10_000) + expect(refs.get("e2")?.backendID).toBe(1) +}) /** Main storage's row for the store, as its schema encodes it. */ type Disk = { stored?: number } diff --git a/packages/gui-plugins/src/browser/refs.ts b/packages/gui-plugins/src/browser/refs.ts index 752542b42e3..4ff1b51c4ba 100644 --- a/packages/gui-plugins/src/browser/refs.ts +++ b/packages/gui-plugins/src/browser/refs.ts @@ -15,6 +15,7 @@ export function documentRefs() { previous: (frameID: string, sessionID?: string) => frames.get(frame(frameID, sessionID)) ?? new Map<number, string>(), add(frameID: string, sessionID: string | undefined, refs: ReadonlyMap<string, number>) { + if (!refs.size) return const key = frame(frameID, sessionID) const previous = frames.get(key) ?? new Map<number, string>() frames.set(key, previous) @@ -22,6 +23,15 @@ export function documentRefs() { elements.set(ref, { frameID, sessionID, backendID }) previous.set(backendID, ref) }) + while (elements.size > 10_000) { + const oldest = elements.entries().next().value + if (!oldest) break + elements.delete(oldest[0]) + const source = frame(oldest[1].frameID, oldest[1].sessionID) + const reverse = frames.get(source) + if (reverse?.get(oldest[1].backendID) === oldest[0]) reverse.delete(oldest[1].backendID) + if (!reverse?.size) frames.delete(source) + } }, clear() { elements.clear() From fd4afe780e65f686384155a025cb6504177a8ec6 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:35:18 +1000 Subject: [PATCH 33/44] fix(browser): hold hidden tabs awake through URL and delay waits --- packages/core/test/browser-tools.test.ts | 5 ++- .../src/browser/agent-rendering.test.ts | 12 +++++ .../src/browser/agent-rendering.ts | 11 ++++- packages/gui-plugins/src/browser/chromium.ts | 23 ++++++++-- packages/plugin-browser/src/rpc.ts | 20 ++++++++- packages/plugin-browser/src/tools.ts | 44 +++---------------- packages/plugin-browser/test/tools.test.ts | 14 +++--- 7 files changed, 77 insertions(+), 52 deletions(-) diff --git a/packages/core/test/browser-tools.test.ts b/packages/core/test/browser-tools.test.ts index 090ab902868..2b2660ce556 100644 --- a/packages/core/test/browser-tools.test.ts +++ b/packages/core/test/browser-tools.test.ts @@ -213,6 +213,8 @@ it.live("wait pauses, and polls for an element or an address", () => Effect.gen(function* () { const seen = { checks: 0 } const browser = yield* setup((action) => { + if (action.type === "wait" && action.condition === "url" && action.url === "**/done") + return failure("Unmet URL wait", Browser.FailureCode.unmet) if (action.type !== "evaluate") return success(tab) seen.checks++ return evaluated(seen.checks < 2 ? { count: 0, visible: 0 } : { count: 1, visible: 1 }) @@ -221,7 +223,8 @@ it.live("wait pauses, and polls for an element or an address", () => expect(JSON.parse(yield* browser.run(waited(`time: 0.02`)))).toMatchObject({ met: true, waited: "delay" }) // A lone timeout is a pause for that long, not a load wait that returns at once on a loaded page. expect(JSON.parse(yield* browser.run(waited(`timeout: 50`)))).toMatchObject({ met: true, waited: "delay" }) - expect(browser.commands).toEqual([]) + expect(browser.commands).toEqual([20,20,50].map(timeoutMs => ({type:"wait",tabID,condition:"delay",timeoutMs}))) + browser.commands.length = 0 expect(JSON.parse(yield* browser.run(`return await tools.browser.wait({ tabID: "${tabID}" })`))).toMatchObject({ met: true, waited: "load", diff --git a/packages/gui-plugins/src/browser/agent-rendering.test.ts b/packages/gui-plugins/src/browser/agent-rendering.test.ts index 3bcd9b81912..465eb785051 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.test.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.test.ts @@ -29,3 +29,15 @@ test("only the last command starts the idle clock; wake before the next command lifetime.abort() expect(timers.size).toBe(0) }) + +test("overlapping commands await the same first frame", async () => { + const render = agentRendering(new AbortController().signal, () => {}, () => () => {}) + const frame = Promise.withResolvers<void>() + const first = render.hold(() => frame.promise) + const second = render.hold(() => { throw new Error("duplicate wake") }) + expect(second.painted).toBe(first.painted) + frame.resolve() + await first.painted + first[Symbol.dispose]() + second[Symbol.dispose]() +}) diff --git a/packages/gui-plugins/src/browser/agent-rendering.ts b/packages/gui-plugins/src/browser/agent-rendering.ts index e813ca96fcb..1f9bc13a4b3 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -4,19 +4,26 @@ const idleMs = 30_000 export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) => void, after = scheduleIdle) { let holds = 0 let awake = false + let paint: Promise<void> | undefined let cancel: (() => void) | undefined signal.addEventListener("abort", () => cancel?.(), { once: true }) return { - hold() { + hold(onWake?: () => Promise<void>) { signal.throwIfAborted() cancel?.() - if (!awake) throttle(false) + if (!awake) { + throttle(false) + paint = onWake?.() + // Later commands may retry a failed wake; overlapping holders await the same frame. + void paint?.finally(() => { paint = undefined }).catch(() => undefined) + } awake = true holds++ return { + painted: paint, [Symbol.dispose]() { if (--holds || signal.aborted) return cancel = after(idleMs, () => { diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index ecb2cfad8fb..1db2b157bb0 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,4 +1,5 @@ import { homedir } from "node:os" +import { scheduler } from "node:timers/promises" import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" import { documentRefs } from "./refs" @@ -1143,9 +1144,19 @@ export function createBrowserPage( async execute(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user"): Promise<Browser.Result> { using active = new DisposableStack() - if (origin === "agent") active.use(rendering.hold()) + const hidden = !view.getVisible() && !undrawable({ platform: process.platform, visible: win.isVisible(), minimized: win.isMinimized(), appHidden: process.platform === "darwin" && electron.app.isHidden() }) + const hold = origin === "agent" ? active.use(rendering.hold(hidden ? async () => { + await ready + if (closed() || agentRefusal(command.action, mainDocument())) return + await withFrames(false, pageLifetime.signal, async stop => { + const frame = (await cdp.send("Page.getFrameTree")).frameTree.frame.id + const world = await cdp.send("Page.createIsolatedWorld", { frameId: frame, worldName: "opencode-browser-paint" }) + abortError(stop) + await cdp.send("Runtime.evaluate", { contextId: world.executionContextId, expression: "new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done())))", awaitPromise: true }) + }) + } : undefined)) : undefined const saved = navigation.interrupt(command.action.type, documentState.status === "restoring" ? documentState.url : undefined) - await ready + await Promise.all([ready, hold?.painted]) const open = origin === "user" && leavable.includes(command.action.type) ? selectOpenDialog(dialogGate) : undefined // The user leaving the page dismisses its dialog, as a browser's address bar does. @@ -1507,7 +1518,12 @@ export function createBrowserPage( } case "wait": { - if (action.condition !== "load" && !action.text) + if (action.condition === "delay") { + await scheduler.wait(action.timeoutMs ?? 0, { signal }) + break + } + if (action.condition === "url" && action.url === undefined) throw new Error("A URL wait requires a URL pattern.") + if ((action.condition === "text" || action.condition === "textGone") && !action.text) throw new Error( 'browser.wait requires non-empty text for condition "text" or "textGone". Use condition "load" without text to wait for loading.', ) @@ -1525,6 +1541,7 @@ export function createBrowserPage( const page = agentRefusal({ type: "wait" }, mainDocument()) if (page) throw new Error(page) + if (action.condition === "url") return Browser.matchesURL(state().url, action.url ?? "") const context = frameID ? contexts.get(frameID) : undefined if (frameID && (!context || extensionFrames().has(frameID))) { diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 51add066ce7..3c9240ee6e8 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -48,6 +48,24 @@ export function loopbackAddress(value: string) { return /^(?:(?:[a-z\d-]+\.)*localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?(?:[/?#]|$)/i.test(value) } +// A glob such as **/dashboard matches the whole address; plain text matches anywhere in it. +export function matchesURL(url: string, pattern: string) { + if (!pattern.includes("*")) return url.includes(pattern) + const parts = pattern.split(/\*+/) + const first = parts.shift() ?? "" + const last = parts.pop() ?? "" + if (!url.startsWith(first) || !url.endsWith(last)) return false + let offset = first.length + for (const part of parts) { + const found = url.indexOf(part, offset) + if (found < 0) return false + offset = found + part.length + } + return offset + last.length <= url.length +} + +/** What one element probe saw; no count while the page navigated or did not answer. */ + export const MAX_FILE_BYTES = 5 * 1024 * 1024 export const TUNNEL_CHUNK_BYTES = 64 * 1024 export const MAX_TEXT = 100_000 @@ -413,7 +431,7 @@ export const Operations = [ operation( "wait", 'Wait until a condition holds in this tab, or pause. Pass one of: text (visible text appears), textGone, selector or ref (a matching element is visible; with state: "hidden", until none is), url (a substring or * glob of the address), delayMs (a plain pause; Code Mode has no timers; time up to 60 counts as seconds, larger as milliseconds), or nothing (the page finishes loading). Only a timeout or timeoutMs, with no condition, pauses that long. For example wait({ tabID, text: "Saved", timeout: 5000 }). A timeout is a result, not an error: it returns met: false with what the page showed; waited says what the call waited for. timeoutMs defaults to 10000; values above 30000 count as 30000.', - { ...tab, ...frame, condition: Schema.Literals(["load", "text", "textGone"]), text: optional(short), timeoutMs }, + { ...tab, ...frame, condition: Schema.Literals(["load", "text", "textGone", "delay", "url"]), text: optional(short), url: optional(short), timeoutMs }, Waited, { ...tab, diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index fc63f759769..a702bbad50a 100644 --- a/packages/plugin-browser/src/tools.ts +++ b/packages/plugin-browser/src/tools.ts @@ -15,7 +15,7 @@ export const register = Effect.fn("BrowserTools.register")(function* ( ctx: Pick<Context, "tool" | "skill" | "location" | "permission">, connection: BrowserConnection.Connection, ) { - // Load and text waits run on the desktop; the rest poll from here with actions every desktop already supports. + // Element waits probe the page on every poll; other waits hold one command on the tab until they settle. const wait = Effect.fn("BrowserTools.wait")(function* (tabID: Browser.TabID, plan: WaitPlan, tool: Tool.Context, approved: Extract<Effect.Success<ReturnType<typeof connection.authorize>>, { connectionID: string }>) { const started = yield* Clock.currentTimeMillis const current = connection @@ -44,33 +44,19 @@ export const register = Effect.fn("BrowserTools.register")(function* ( ) const deadline = started + plan.timeoutMs - if (plan.kind === "delay") { - yield* current - yield* Effect.sleep(Duration.millis(plan.timeoutMs)) - return yield* finish(yield* current, true) - } - - if (plan.kind === "desktop") { - const target = yield* connection.target(tool.sessionID, plan.action, approved) + if (plan.kind !== "element") { + const action: WaitAction = plan.kind === "desktop" ? plan.action : { type: "wait", tabID, condition: plan.kind, ...(plan.kind === "url" ? { url: plan.url } : {}), timeoutMs: Math.max(1, plan.timeoutMs) } + const target = yield* connection.target(tool.sessionID, action, approved) return yield* target.request([]).pipe( Effect.flatMap((response) => Effect.fromResult(decodeResult({ name: "wait", output: Browser.Tab }, response))), Effect.flatMap((tab) => finish(tab, true)), Effect.catchIf( (error) => failureCode(error) === Browser.FailureCode.unmet, - () => Effect.flatMap(current, (tab) => finish(tab, false, unmet(plan.action))), + () => Effect.flatMap(current, (tab) => finish(tab, false, plan.kind === "url" ? `The address was ${tab.url} after ${plan.timeoutMs} ms.` : unmet(action))), ), ) } - if (plan.kind === "url") { - const result = yield* until(current, (tab) => matchesURL(tab.url, plan.url), deadline, current) - return yield* finish( - result.seen, - result.met, - result.met ? undefined : `The address was ${result.seen.url} after ${plan.timeoutMs} ms.`, - ) - } - const probe: Browser.Action = "ref" in plan.element ? { type: "evaluate", tabID, ref: plan.element.ref, script: refVisibility } @@ -473,29 +459,11 @@ function unmet(action: WaitAction) { return `Text "${action.text}" was still on the page after ${after}.` } -// A glob such as **/dashboard matches the whole address; plain text matches anywhere in it. -export function matchesURL(url: string, pattern: string) { - if (!pattern.includes("*")) return url.includes(pattern) - const parts = pattern.split(/\*+/) - const first = parts.shift() ?? "" - const last = parts.pop() ?? "" - if (!url.startsWith(first) || !url.endsWith(last)) return false - let offset = first.length - for (const part of parts) { - const found = url.indexOf(part, offset) - if (found < 0) return false - offset = found + part.length - } - return offset + last.length <= url.length -} - -/** What one element probe saw; no count while the page navigated or did not answer. */ -type Seen = { readonly tab: Browser.Tab; readonly count: number | undefined; readonly visible: number | undefined } - const Visibility = Schema.Struct({ tab: Browser.Tab, value: Schema.Struct({ count: Schema.Number, visible: Schema.Number }), }) +type Seen = { readonly tab: Browser.Tab; readonly count: number | undefined; readonly visible: number | undefined } const refVisibility = "(element) => ({ count: element.isConnected ? 1 : 0, visible: element.isConnected && element.checkVisibility() ? 1 : 0 })" const selectorVisibility = (selector: string) => diff --git a/packages/plugin-browser/test/tools.test.ts b/packages/plugin-browser/test/tools.test.ts index 44e8137a95e..b7919596b55 100644 --- a/packages/plugin-browser/test/tools.test.ts +++ b/packages/plugin-browser/test/tools.test.ts @@ -286,13 +286,13 @@ describe("wait reads the condition from the keys models write", () => { }) test("url matches a substring or a * glob of the whole address", () => { - expect(BrowserTools.matchesURL("https://app.test/dashboard?tab=1", "/dashboard")).toBe(true) - expect(BrowserTools.matchesURL("https://app.test/dashboard", "**/dashboard")).toBe(true) - expect(BrowserTools.matchesURL("https://app.test/dashboard/settings", "**/dashboard")).toBe(false) - expect(BrowserTools.matchesURL("https://app.test/a.b", "*/a.b")).toBe(true) - expect(BrowserTools.matchesURL("https://app.test/axb", "*/a.b")).toBe(false) - expect(BrowserTools.matchesURL("abc", "ab*bc")).toBe(false) - expect(BrowserTools.matchesURL("https://app.test/some/path", "https://*/*/path")).toBe(true) + expect(Browser.matchesURL("https://app.test/dashboard?tab=1", "/dashboard")).toBe(true) + expect(Browser.matchesURL("https://app.test/dashboard", "**/dashboard")).toBe(true) + expect(Browser.matchesURL("https://app.test/dashboard/settings", "**/dashboard")).toBe(false) + expect(Browser.matchesURL("https://app.test/a.b", "*/a.b")).toBe(true) + expect(Browser.matchesURL("https://app.test/axb", "*/a.b")).toBe(false) + expect(Browser.matchesURL("abc", "ab*bc")).toBe(false) + expect(Browser.matchesURL("https://app.test/some/path", "https://*/*/path")).toBe(true) }) }) From bf4c910f948fe143dc0e2f5a543a766e7fbed91e Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:47:31 +1000 Subject: [PATCH 34/44] fix(browser): name list items through collapsed wrappers --- .../gui-plugins/src/browser/snapshot.test.ts | 22 +++++++++- packages/gui-plugins/src/browser/snapshot.ts | 42 ++++++++++++++++++- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts index dd5efc36ff4..ea9ec756782 100644 --- a/packages/gui-plugins/src/browser/snapshot.test.ts +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -112,12 +112,13 @@ test("summarizes collections, preserves late selections, and expands a scoped co test("alerts and nested dialogs outrank navigation; invalid fields and safe values survive a tight budget", async () => { const field = node(4, "textbox", "Email") - field.properties = ["invalid", "readonly", "required"].map((key) => ({ - name: key as "invalid" | "readonly" | "required", + field.properties = (["invalid", "readonly", "required"] as const).map((key) => ({ + name: key, value: { type: "boolean", value: true }, })) field.value = { type: "string", value: "bad@" } const other = { ...node(6, "textbox", "Password"), value: { type: "string" as const, value: "secret" } } + const tree = [ node(1, "generic", "", 2, 5), node(2, "navigation", "Routes", 3), @@ -126,6 +127,7 @@ test("alerts and nested dialogs outrank navigation; invalid fields and safe valu node(5, "alert", "Errors"), other, ] + const content = (await accessibilitySnapshot(tree, { ...options(), readableValue: async (id) => id === 4 })).content expect(content.indexOf("[dialog]")).toBeLessThan(content.indexOf("[navigation]")) expect(content.indexOf("[alert]")).toBeLessThan(content.indexOf("[navigation]")) @@ -145,11 +147,27 @@ test("headings inside collapsed card wrappers distinguish identical controls", a node(8, "heading", "Beta"), node(9, "button", "Edit"), ] + const result = await accessibilitySnapshot(tree, { ...options(), interactive: true }) expect(result.content).toContain('[button] "Edit" in heading "Alpha"') expect(result.content).toContain('[button] "Edit" in heading "Beta"') }) +test("an invalid input in the last table row survives truncation", async () => { + const rows = Array.from({length:40}, (_, i) => node(i+2,"row","",i+42)) + const fields = rows.map((_, i) => node(i+42,"textbox",`Field ${i}`)) + fields[39].properties = [{name:"invalid",value:{type:"token",value:"true"}}] + const root = node(1,"table","Form",...rows.map(row=>Number(row.nodeId))) + const result = await accessibilitySnapshot([root,...rows,...fields],{...options(),interactive:true,maxLines:3}) + expect(result.content).toContain('[textbox] "Field 39" invalid=true') + expect(result.content).not.toContain('"Field 38"') +}) + +test("an unnamed list item uses its text inside a wrapper as context", async () => { + const result = await accessibilitySnapshot([node(1,"listitem","",2,4),node(2,"generic","",3),node(3,"StaticText","Project Fox"),node(4,"button","Edit")],{...options(),interactive:true}) + expect(result.content).toContain('[button] "Edit" in listitem "Project Fox"') +}) + test("prefers a nonignored root and can find a known ref after its role changes", async () => { const first = { ...node(1, "generic", ""), ignored: true, nodeId: "ignored" } diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index 87aa0b611b7..b676cd7e4da 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -66,6 +66,35 @@ function rank(role: string) { if (landmarks.test(role)) return 4 } +function itemLabel(children: readonly string[], index: ReadonlyMap<string, Protocol.Accessibility.AXNode>) { + const pending = children.slice().reverse() + const seen = new Set<string>() + + while (pending.length) { + const id = pending.pop() + + if (!id || seen.has(id)) continue + seen.add(id) + const node = index.get(id) + + if (!node) continue + const role = String(node.role?.value ?? "") + + if (controls.test(role) || collections.test(role) || role === "row" || role === "listitem" || node.properties?.some(p => p.name === "editable")) continue + const name = String(node.name?.value ?? "").replace(/\s+/g," ").trim() + + if (!node.ignored && name) return name + + for (let i=(node.childIds?.length ?? 0)-1; i>=0; i--) { + const child = node.childIds?.[i] + + if (child) pending.push(child) + } + } + + return "" +} + /** One frame per walk. Never inspect editable descendants, even to count omitted nodes or search text. */ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibility.AXNode[], options: Options) { const index = new Map<string, Protocol.Accessibility.AXNode>() @@ -142,7 +171,7 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili const itemName = options.interactive && (role === "row" || role === "listitem") && !name - ? String(index.get(children[0])?.name?.value ?? "").replace(/\s+/g, " ") + ? itemLabel(children, index) : name const item = @@ -154,14 +183,16 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili isItem && collection ? { area: collection, keep: false, meaningful: false, shown: 0, parent: branch.entry } : branch.entry + if (entry && entry !== branch.entry) items.push(entry) + const important = !!node.properties?.some( (p) => ["focused", "selected", "checked", "invalid"].includes(p.name) && ![false, "false", undefined].includes(p.value.value), ) + if (visible && entry && (interactive || name.trim() || important)) { - entry.meaningful = true if (important) for (let group: Item | undefined = entry; group; group = group.parent) group.keep = true } @@ -195,6 +226,8 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili (known && `@${known}`.includes(query)) ) { const pad = options.interactive ? "" : " ".repeat(Math.min(12, branch.level)) + + if (entry && (interactive || name.trim() || important)) entry.meaningful = true buckets[role === "RootWebArea" ? 0 : (priority ?? 5)].push({ label: pad + label, value: @@ -267,11 +300,13 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) const order = new Map(original.map((line, i) => [line, i + visited])) // Select within each landmark's budget by usefulness, then restore tree order for reading. const groups = Array.from({ length: 4 }, (): Line[] => []) + for (const line of original) groups[ line.important || line.entry?.keep ? 0 : line.interactive ? 1 : line.area?.id === line.id && line.id ? 2 : 3 ].push(line) const bucket = groups.flat() + for (let i = 0; i < bucket.length; i += 32) { const batch = bucket.slice(i, i + 32) @@ -281,6 +316,7 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) batch.map(async (line) => { if (!line.id || line.deep) return "" const value = line.value && (await options.readableValue?.(line.id)) ? ` value=${line.value}` : "" + return value + ((await options.box?.(line.id)) ?? "") }), ) @@ -323,6 +359,7 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) if (!omitted) return { content: content(), truncated: false, refs } for (const row of output) for (let group = row.line.entry; group; group = group.parent) group.shown++ + for (const group of items) if (group.meaningful && !group.shown) group.area.skipped++ const footer = () => { @@ -345,6 +382,7 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) const last = output.pop() if (!last) break + for (let group = last.line.entry; group; group = group.parent) if (--group.shown === 0 && group.meaningful) group.area.skipped++ omit(last.line) From 6526cdba93b5d1201a7c93f80635ab3780ba6b0c Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:47:31 +1000 Subject: [PATCH 35/44] fix(browser): allow more time for full-page redraws --- .../gui-plugins/src/browser/agent-rendering.ts | 3 ++- .../gui-plugins/src/browser/capture.test.ts | 10 ++++++++++ packages/gui-plugins/src/browser/capture.ts | 14 ++++++++------ packages/gui-plugins/src/browser/chromium.ts | 17 +++++++++++++---- packages/gui-plugins/src/browser/errors.ts | 4 ++-- packages/plugin-browser/src/rpc.ts | 2 +- 6 files changed, 36 insertions(+), 14 deletions(-) diff --git a/packages/gui-plugins/src/browser/agent-rendering.ts b/packages/gui-plugins/src/browser/agent-rendering.ts index 1f9bc13a4b3..ff1fc3e901a 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -17,8 +17,9 @@ export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) throttle(false) paint = onWake?.() // Later commands may retry a failed wake; overlapping holders await the same frame. - void paint?.finally(() => { paint = undefined }).catch(() => undefined) + void paint?.then(() => { paint = undefined }, () => { awake = false; paint = undefined }) } + awake = true holds++ diff --git a/packages/gui-plugins/src/browser/capture.test.ts b/packages/gui-plugins/src/browser/capture.test.ts index 391a73bfc70..f32dd725621 100644 --- a/packages/gui-plugins/src/browser/capture.test.ts +++ b/packages/gui-plugins/src/browser/capture.test.ts @@ -43,6 +43,16 @@ function coordinator() { return { capture, advance, events, jobs } } +test("a full-page redraw keeps its subscription beyond the viewport deadline", async () => { + const c = coordinator() + const shot = c.capture(false, new AbortController().signal, () => new Promise<void>(() => {}), 6000) + c.advance(2500) + expect(c.events).toEqual(["begin"]) + c.advance(3500) + await expect(shot).rejects.toThrow("6 seconds") + expect(c.events).toEqual(["begin", "end"]) +}) + test("overlapping hidden and stalled visible captures share a subscription until the last release", async () => { const c = coordinator() const one = Promise.withResolvers<void>() diff --git a/packages/gui-plugins/src/browser/capture.ts b/packages/gui-plugins/src/browser/capture.ts index b8fb50c32f1..645109ad0c5 100644 --- a/packages/gui-plugins/src/browser/capture.ts +++ b/packages/gui-plugins/src/browser/capture.ts @@ -4,6 +4,9 @@ export type Undrawable = "minimized" | "hidden" | "stalled" /** How long a viewport or element capture may wait for the tab's frame before it gives up. */ export const CAPTURE_DEADLINE_MS = 2_500 +/** A full document may rasterize and encode up to 16 MP before a fresh frame is delivered. */ +export const FULL_PAGE_DEADLINE_MS = 6_000 + type Size = { width: number; height: number } type Rect = Size & { x: number; y: number } @@ -45,7 +48,7 @@ const schedule: Schedule = (ms, run) => { export function captureCoordinator(begin: () => void, end: () => void, after: Schedule = schedule) { let holders = 0 - return async <T>(presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise<T>) => { + return async <T>(presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise<T>, deadline = CAPTURE_DEADLINE_MS) => { const cancel = () => new Error("Browser capture was cancelled.") if (signal.aborted) throw cancel() @@ -75,7 +78,7 @@ export function captureCoordinator(begin: () => void, end: () => void, after: Sc } }) : undefined - const timeout = after(CAPTURE_DEADLINE_MS, () => interrupt(new Error(undrawableMessage("stalled")))) + const timeout = after(deadline, () => interrupt(new Error(undrawableMessage("stalled", deadline)))) signal.addEventListener("abort", aborted, { once: true }) try { @@ -139,14 +142,13 @@ export function undrawable(window: { return undefined } -const causes: Record<Undrawable, string> = { +const causes: Record<Exclude<Undrawable, "stalled">, string> = { minimized: "The OpenCode window is minimized, so the system does not draw this tab.", hidden: "OpenCode is hidden, so the system does not draw this tab.", - stalled: `No fresh frame of this tab arrived within ${CAPTURE_DEADLINE_MS / 1000} seconds. No cached screenshot was returned.`, } -export function undrawableMessage(reason: Undrawable) { - if (reason === "stalled") return `${causes.stalled} Check that the page has finished navigating and is responsive before retrying.` +export function undrawableMessage(reason: Undrawable, deadline = CAPTURE_DEADLINE_MS) { + if (reason === "stalled") return `No fresh frame of this tab arrived within ${deadline / 1000} seconds. No cached screenshot was returned. Check that the page has finished navigating and is responsive before retrying.` return `${causes[reason]} A screenshot needs the window restored. Ask the user to restore the OpenCode window, then take the screenshot again; do not repeat it before then. Clicks, typing and other browser actions still work.` } diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 1db2b157bb0..e0621f1b5e4 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -10,7 +10,7 @@ import electron, { type BrowserWindow, type WebContents } from "electron" import type { Protocol } from "devtools-protocol" import { Schema } from "effect" import type { Embeds } from "@opencode/plugin/gui/main" -import { captureCoordinator, captureScale, cropPixels, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" +import { captureCoordinator, captureScale, cropPixels, FULL_PAGE_DEADLINE_MS, jpegFits, pngFits, undrawable, undrawableMessage } from "./capture" import { createCdp, abortError, waitFor } from "./cdp" import { navigationDeadline } from "./navigation-deadline" import { attachChildren, releaseWorker } from "./child-targets" @@ -1145,9 +1145,11 @@ export function createBrowserPage( using active = new DisposableStack() const hidden = !view.getVisible() && !undrawable({ platform: process.platform, visible: win.isVisible(), minimized: win.isMinimized(), appHidden: process.platform === "darwin" && electron.app.isHidden() }) + const hold = origin === "agent" ? active.use(rendering.hold(hidden ? async () => { await ready - if (closed() || agentRefusal(command.action, mainDocument())) return + + if (closed() || agentRefusal({ type: "snapshot" }, mainDocument())) return await withFrames(false, pageLifetime.signal, async stop => { const frame = (await cdp.send("Page.getFrameTree")).frameTree.frame.id const world = await cdp.send("Page.createIsolatedWorld", { frameId: frame, worldName: "opencode-browser-paint" }) @@ -1155,6 +1157,7 @@ export function createBrowserPage( await cdp.send("Runtime.evaluate", { contextId: world.executionContextId, expression: "new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done())))", awaitPromise: true }) }) } : undefined)) : undefined + const saved = navigation.interrupt(command.action.type, documentState.status === "restoring" ? documentState.url : undefined) await Promise.all([ready, hold?.painted]) const open = origin === "user" && leavable.includes(command.action.type) ? selectOpenDialog(dialogGate) : undefined @@ -1414,6 +1417,7 @@ export function createBrowserPage( )) if (element && value.exceptionDetails?.exception?.description?.startsWith("Error: browser.detached_ref\n")) throw detachedRef() + if (value.exceptionDetails) throw new Error( `Page JavaScript threw an exception. Check the script and ${action.ref ? "ref" : "frameID"}; inspect the page before repeating code with side effects. Details: ${(value.exceptionDetails.exception?.description ?? value.exceptionDetails.text).slice(0, 800)}`, @@ -1522,7 +1526,9 @@ export function createBrowserPage( await scheduler.wait(action.timeoutMs ?? 0, { signal }) break } + if (action.condition === "url" && action.url === undefined) throw new Error("A URL wait requires a URL pattern.") + if ((action.condition === "text" || action.condition === "textGone") && !action.text) throw new Error( 'browser.wait requires non-empty text for condition "text" or "textGone". Use condition "load" without text to wait for loading.', @@ -1541,6 +1547,7 @@ export function createBrowserPage( const page = agentRefusal({ type: "wait" }, mainDocument()) if (page) throw new Error(page) + if (action.condition === "url") return Browser.matchesURL(state().url, action.url ?? "") const context = frameID ? contexts.get(frameID) : undefined @@ -1871,6 +1878,7 @@ export function createBrowserPage( ) if (result.exceptionDetails?.exception?.description?.startsWith("Error: browser.detached_ref\n")) throw detachedRef() + if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text) @@ -1959,7 +1967,7 @@ export function createBrowserPage( if (!frameStillCurrent(before, documentState)) throw new CodedError(Browser.FailureCode.documentChanged, "The document changed during capture. Check the tab and take a new screenshot.") return frame - }) + }, action.fullPage ? FULL_PAGE_DEADLINE_MS : undefined) } async function screenshot(action: Extract<Browser.Action, { type: "screenshot" }>, signal: AbortSignal) { @@ -2043,7 +2051,7 @@ export function createBrowserPage( action: Extract<Browser.Action, { type: "screenshot" }>, bounds: { x: number; y: number; width: number; height: number }, ) { - const pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getBounds()).scaleFactor + const pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getNormalBounds()).scaleFactor const scale = captureScale(bounds, pixelRatio, action.maxWidth ?? 2000) const format = action.format ?? "jpeg" @@ -2294,6 +2302,7 @@ export function createBrowserPage( // AX does not distinguish password textboxes. Fail closed if the backing input is gone or protected. readableValue: async backendID => { abortError(signal) + return (await call({ backendID, frameID, sessionID }, `function() { return this.isConnected && !(this instanceof HTMLInputElement && ['password','file'].includes(this.type)) && getComputedStyle(this).webkitTextSecurity === 'none' }`).catch(() => false)) === true }, box: action.type === "snapshot" && action.boxes ? async (backendID) => { diff --git a/packages/gui-plugins/src/browser/errors.ts b/packages/gui-plugins/src/browser/errors.ts index aa9a6ae98e6..8122a1f3b07 100644 --- a/packages/gui-plugins/src/browser/errors.ts +++ b/packages/gui-plugins/src/browser/errors.ts @@ -1,5 +1,5 @@ import { Browser } from "@opencode/plugin-browser/rpc" -import { CAPTURE_DEADLINE_MS } from "./capture" +import { CAPTURE_DEADLINE_MS, FULL_PAGE_DEADLINE_MS } from "./capture" import { FileVerificationError } from "@opencode/util/file-verification" /** A failure the server acts on by its code, such as a wait whose condition never held. */ @@ -78,7 +78,7 @@ export function browserFailure(action: Browser.Action, cause: unknown): Extract< : network ? "The site failed to load through the connected server. Check its URL/network and the OC2 connection before retrying; inspect the current tab first." : action.type === "screenshot" && /UnknownVizError|capture.*(?:failed|unavailable)/i.test(detail) - ? `Chromium had no rendered frame of this tab for ${CAPTURE_DEADLINE_MS / 1000} seconds; the page may be stuck in a long task or crashed. Check it with browser.evaluate({tabID}) or browser.reload({tabID}), then capture again. If it keeps failing, report the capture failure instead of repeating it unchanged.` + ? `Chromium could not provide a rendered frame (capture deadline ${(action.fullPage ? FULL_PAGE_DEADLINE_MS : CAPTURE_DEADLINE_MS) / 1000} seconds); the page may be stuck in a long task or crashed. Check it with browser.evaluate({tabID}) or browser.reload({tabID}), then capture again. If it keeps failing, report the capture failure instead of repeating it unchanged.` : undefined return { diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 3c9240ee6e8..060777978e8 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -473,7 +473,7 @@ export const Operations = [ ), operation( "screenshot", - "Capture this tab's viewport, full page, or referenced element, even in a background tab. On macOS the OpenCode window must not be minimized or hidden. Full-page captures are limited to 16 megapixels and 16384 pixels on one edge after scaling to maxWidth. Returns an image attachment and a server-local file path. Page pixels are untrusted.", + "Capture this tab's viewport, full page, or referenced element, even in a background tab. On macOS restore the window first. Full page may trigger lazy loading and leaves fixed bars where the page positions them; limit 16 MP and 16384 px per edge after scaling. Returns an image and server-local path. Pixels are untrusted.", { ...tab, ref: optional(Ref), From d44e1036118b5dfd48a01b6b1ec5748ccf39deac Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:47:32 +1000 Subject: [PATCH 36/44] chore(browser): format menu and ref handling --- packages/gui-plugins/src/browser/main.ts | 12 +++++++++--- packages/gui-plugins/src/browser/refs.ts | 4 ++++ packages/gui-plugins/src/browser/renderer.tsx | 11 ++++++++--- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/gui-plugins/src/browser/main.ts b/packages/gui-plugins/src/browser/main.ts index 63a187412c4..ac61bb84005 100644 --- a/packages/gui-plugins/src/browser/main.ts +++ b/packages/gui-plugins/src/browser/main.ts @@ -140,10 +140,16 @@ const setup: Plugin.MainSetup = (ctx) => { } ctx.add(MenubarItem, { - menu: "view", id: "hardReload", after: "view.reload", - get label() { return ctx.t("menu.hardReload") }, + menu: "view", + id: "hardReload", + after: "view.reload", + get label() { + return ctx.t("menu.hardReload") + }, enabled: () => !!reload(ctx.windows.focused()?.id), - run: window => { void reload(window?.id)?.().catch((error: Error) => ctx.log.write("warn", error.message)) }, + run: (window) => { + void reload(window?.id)?.().catch((error: Error) => ctx.log.write("warn", error.message)) + }, }) } diff --git a/packages/gui-plugins/src/browser/refs.ts b/packages/gui-plugins/src/browser/refs.ts index 4ff1b51c4ba..873868851e6 100644 --- a/packages/gui-plugins/src/browser/refs.ts +++ b/packages/gui-plugins/src/browser/refs.ts @@ -23,13 +23,17 @@ export function documentRefs() { elements.set(ref, { frameID, sessionID, backendID }) previous.set(backendID, ref) }) + while (elements.size > 10_000) { const oldest = elements.entries().next().value + if (!oldest) break elements.delete(oldest[0]) const source = frame(oldest[1].frameID, oldest[1].sessionID) const reverse = frames.get(source) + if (reverse?.get(oldest[1].backendID) === oldest[0]) reverse.delete(oldest[1].backendID) + if (!reverse?.size) frames.delete(source) } }, diff --git a/packages/gui-plugins/src/browser/renderer.tsx b/packages/gui-plugins/src/browser/renderer.tsx index f840a783d31..227b594cf2a 100644 --- a/packages/gui-plugins/src/browser/renderer.tsx +++ b/packages/gui-plugins/src/browser/renderer.tsx @@ -188,9 +188,14 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => { if (!pane) return return { - id: "hardReload", title: ctx.t("menu.hardReload"), group: ctx.t("command.category.view"), - bind: mac ? "mod+alt+r" : "ctrl+f5", scope: "#browser-panel", editable: true, - enabled: pane.visible() && !!pane.address(), run: () => pane.reload(true), + id: "hardReload", + title: ctx.t("menu.hardReload"), + group: ctx.t("command.category.view"), + bind: mac ? "mod+alt+r" : "ctrl+f5", + scope: "#browser-panel", + editable: true, + enabled: pane.visible() && !!pane.address(), + run: () => pane.reload(true), } }) From bd46fe5006e10295f83c8f13589d94efedbcc015 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:07:28 +1000 Subject: [PATCH 37/44] fix(browser): never gate recovery commands on a wake frame --- .../src/browser/agent-rendering.test.ts | 16 +++++++++++++++- .../gui-plugins/src/browser/agent-rendering.ts | 14 ++++++++++---- packages/gui-plugins/src/browser/chromium.ts | 9 +++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/packages/gui-plugins/src/browser/agent-rendering.test.ts b/packages/gui-plugins/src/browser/agent-rendering.test.ts index 465eb785051..2e7c6763e52 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.test.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test" -import { agentRendering } from "./agent-rendering" +import { agentRendering, needsWakeFrame } from "./agent-rendering" test("only the last command starts the idle clock; wake before the next command and cancel at disposal", () => { const lifetime = new AbortController() @@ -41,3 +41,17 @@ test("overlapping commands await the same first frame", async () => { first[Symbol.dispose]() second[Symbol.dispose]() }) + +test("a missing frame never prevents acting; dialog and navigation bypass even a pending wake", async () => { + const render = agentRendering(new AbortController().signal, () => {}, () => () => {}) + const frame = Promise.withResolvers<void>() + const shot = render.hold(() => frame.promise) + expect(needsWakeFrame("dialog", true, true)).toBe(false) + expect(needsWakeFrame("navigate", true, false)).toBe(false) + expect(needsWakeFrame("click", true, true)).toBe(false) + expect(needsWakeFrame("snapshot", false, false)).toBe(false) + expect(needsWakeFrame("evaluate", true, false)).toBe(true) + expect(render.hold().painted).toBeUndefined() + frame.reject(new Error("no frame")) + await expect(shot.painted).resolves.toBeUndefined() +}) diff --git a/packages/gui-plugins/src/browser/agent-rendering.ts b/packages/gui-plugins/src/browser/agent-rendering.ts index ff1fc3e901a..2654e527dec 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -1,3 +1,10 @@ +import type { Browser } from "@opencode/plugin-browser/rpc" + +/** A paused page cannot paint the frame that its dialog or a recovery navigation would unblock. */ +export function needsWakeFrame(method: Browser.Method, loaded: boolean, dialog: boolean) { + return loaded && !dialog && ["snapshot", "find", "wait", "evaluate", "click", "check", "fill", "fill_form", "select", "press", "type", "hover", "drag", "scroll", "screenshot"].includes(method) +} + // Long enough to cover thinking between a snapshot and its follow-up; a forgotten tab doesn't animate indefinitely. const idleMs = 30_000 @@ -15,16 +22,15 @@ export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) if (!awake) { throttle(false) - paint = onWake?.() - // Later commands may retry a failed wake; overlapping holders await the same frame. - void paint?.then(() => { paint = undefined }, () => { awake = false; paint = undefined }) + paint = onWake?.().catch(() => undefined) + void paint?.then(() => { paint = undefined }) } awake = true holds++ return { - painted: paint, + painted: onWake ? paint : undefined, [Symbol.dispose]() { if (--holds || signal.aborted) return cancel = after(idleMs, () => { diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index e0621f1b5e4..e3316e23e2c 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -3,7 +3,7 @@ import { scheduler } from "node:timers/promises" import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" import { documentRefs } from "./refs" -import { agentRendering } from "./agent-rendering" +import { agentRendering, needsWakeFrame } from "./agent-rendering" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" import electron, { type BrowserWindow, type WebContents } from "electron" @@ -1144,12 +1144,13 @@ export function createBrowserPage( async execute(command: Browser.Command, signal: AbortSignal, origin: "agent" | "user"): Promise<Browser.Result> { using active = new DisposableStack() - const hidden = !view.getVisible() && !undrawable({ platform: process.platform, visible: win.isVisible(), minimized: win.isMinimized(), appHidden: process.platform === "darwin" && electron.app.isHidden() }) + const hidden = !view.getVisible() && win.isVisible() && !win.isMinimized() && !(process.platform === "darwin" && electron.app.isHidden()) + const shouldPaint = () => needsWakeFrame(command.action.type, documentState.status === "loaded" && !documentState.busy && !documentState.pending, !!selectOpenDialog(dialogGate)) - const hold = origin === "agent" ? active.use(rendering.hold(hidden ? async () => { + const hold = origin === "agent" ? active.use(rendering.hold(hidden && shouldPaint() ? async () => { await ready - if (closed() || agentRefusal({ type: "snapshot" }, mainDocument())) return + if (!shouldPaint() || agentRefusal({ type: "snapshot" }, mainDocument())) return await withFrames(false, pageLifetime.signal, async stop => { const frame = (await cdp.send("Page.getFrameTree")).frameTree.frame.id const world = await cdp.send("Page.createIsolatedWorld", { frameId: frame, worldName: "opencode-browser-paint" }) From eaa844d9bb1795dfb22efa11bbcdb55ee9cffeab Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:20:52 +1000 Subject: [PATCH 38/44] test(browser): prove dialogs and navigation never wait for a wake frame --- .../src/browser/agent-rendering.test.ts | 38 +++++++++++++++---- .../src/browser/agent-rendering.ts | 4 +- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/packages/gui-plugins/src/browser/agent-rendering.test.ts b/packages/gui-plugins/src/browser/agent-rendering.test.ts index 2e7c6763e52..4deb83329a2 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.test.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.test.ts @@ -42,16 +42,38 @@ test("overlapping commands await the same first frame", async () => { second[Symbol.dispose]() }) -test("a missing frame never prevents acting; dialog and navigation bypass even a pending wake", async () => { +test("idle past the deadline with a dialog open, the dialog command un-throttles without waiting for a frame", () => { + const timers: (() => void)[] = [] + const throttles: boolean[] = [] + + const render = agentRendering(new AbortController().signal, value => throttles.push(value), (_, run) => { + timers.push(run) + + return () => {} + }) + + render.hold()[Symbol.dispose]() + timers.forEach(run => run()) + expect(throttles).toEqual([false, true]) + + // An open alert pauses the page's animation frames, so no command waits for one, including the one that answers it. + for (const method of ["dialog", "snapshot", "click", "navigate"] as const) expect(needsWakeFrame(method, true, true)).toBe(false) + + const answer = render.hold(needsWakeFrame("dialog", true, true) ? () => new Promise(() => {}) : undefined) + expect(answer.painted).toBeUndefined() + expect(throttles).toEqual([false, true, false]) +}) + +test("a renderer that never paints neither blocks navigation nor fails the command that waited for it", async () => { const render = agentRendering(new AbortController().signal, () => {}, () => () => {}) const frame = Promise.withResolvers<void>() - const shot = render.hold(() => frame.promise) - expect(needsWakeFrame("dialog", true, true)).toBe(false) - expect(needsWakeFrame("navigate", true, false)).toBe(false) - expect(needsWakeFrame("click", true, true)).toBe(false) + const snapshot = render.hold(needsWakeFrame("snapshot", true, false) ? () => frame.promise : undefined) + expect(snapshot.painted).toBeDefined() + + for (const method of ["navigate", "reload", "stop", "back", "dialog", "tabs.close"] as const) expect(needsWakeFrame(method, true, false)).toBe(false) expect(needsWakeFrame("snapshot", false, false)).toBe(false) - expect(needsWakeFrame("evaluate", true, false)).toBe(true) - expect(render.hold().painted).toBeUndefined() + expect(render.hold(needsWakeFrame("navigate", true, false) ? () => frame.promise : undefined).painted).toBeUndefined() + // The capture deadline rejects the wake; the snapshot then proceeds as it would without one. frame.reject(new Error("no frame")) - await expect(shot.painted).resolves.toBeUndefined() + await expect(snapshot.painted).resolves.toBeUndefined() }) diff --git a/packages/gui-plugins/src/browser/agent-rendering.ts b/packages/gui-plugins/src/browser/agent-rendering.ts index 2654e527dec..4af49113944 100644 --- a/packages/gui-plugins/src/browser/agent-rendering.ts +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -2,7 +2,9 @@ import type { Browser } from "@opencode/plugin-browser/rpc" /** A paused page cannot paint the frame that its dialog or a recovery navigation would unblock. */ export function needsWakeFrame(method: Browser.Method, loaded: boolean, dialog: boolean) { - return loaded && !dialog && ["snapshot", "find", "wait", "evaluate", "click", "check", "fill", "fill_form", "select", "press", "type", "hover", "drag", "scroll", "screenshot"].includes(method) + const painting: Browser.Method[] = ["snapshot", "find", "wait", "evaluate", "click", "check", "fill", "fill_form", "select", "press", "hover", "drag", "scroll", "screenshot"] + + return loaded && !dialog && painting.includes(method) } // Long enough to cover thinking between a snapshot and its follow-up; a forgotten tab doesn't animate indefinitely. From bb4e02fc0fd651bae8b61830a9fe7d80011656e3 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:30:49 +1000 Subject: [PATCH 39/44] fix(browser): keep headings and opening text when links fill a snapshot --- .../gui-plugins/src/browser/snapshot.test.ts | 33 +++++++++++ packages/gui-plugins/src/browser/snapshot.ts | 59 ++++++++++++++++--- 2 files changed, 83 insertions(+), 9 deletions(-) diff --git a/packages/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts index ea9ec756782..e9af2ec6f0c 100644 --- a/packages/gui-plugins/src/browser/snapshot.test.ts +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -72,6 +72,39 @@ test("budgets whole lines, not traversal: find reaches the last item of a trunca expect([...match.refs.values()]).toEqual([2000]) }) +test("links that fill the budget leave a quarter for headings, opening text and status, which return unused", async () => { + const links = Array.from({ length: 1000 }, (_, i) => node(i + 10, "link", `Sidebar entry ${i}`)) + const rows = Array.from({ length: 200 }, (_, i) => node(i + 2000, "row", `Row ${i}`)) + const prose = Array.from({ length: 400 }, (_, i) => node(i + 3000, "StaticText", `Paragraph ${i} explains one more detail of arrays.`)) + + const article = [ + node(1, "generic", "", ...links.map((_, i) => i + 10), 2, 3, 4, 5, 6, ...prose.map((_, i) => i + 3000)), + node(2, "heading", "Array reference"), + node(3, "StaticText", "The Array object stores a list of values."), + node(4, "table", "Methods", 7, ...rows.map((_, i) => i + 2000)), + node(5, "status", "", 8), + node(6, "StaticText", "Closing remark"), + node(7, "columnheader", "Method"), + node(8, "StaticText", "Saved"), + ...links, + ...rows, + ...prose, + ] + + const page = (await accessibilitySnapshot(article, options())).content + + for (const text of ['[heading] "Array reference"', "The Array object", '[columnheader] "Method"', '"Saved"', '"Paragraph 0 ']) expect(page).toContain(text) + + // Cells and rows do not spend the share on a table's first rows. + expect(page).not.toContain('"Row 199"') + const linkChars = page.split("\n").filter((line) => line.includes("[link]")).join("\n").length + expect(linkChars).toBeGreaterThan(14_000) + expect(linkChars).toBeLessThan(15_500) + const controls = (await accessibilitySnapshot([node(1, "generic", "", ...links.map((_, i) => i + 10)), ...links], options())).content + expect(controls.length).toBeGreaterThan(19_500) + expect((await accessibilitySnapshot(article, { ...options(), interactive: true })).content).not.toContain("The Array object") +}) + test("orders landmarks across empty branching wrappers, follows aria-owns cycles once, and never enters an editor", async () => { const tree = [ node(1, "generic", "", 2, 3, 4), diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index b676cd7e4da..7891a8593d0 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -28,6 +28,7 @@ type Branch = { scope: string item: string ordinal: number + emphasis?: boolean priority?: number area?: Area collection?: Area @@ -43,6 +44,7 @@ type Line = { entry?: Item important: boolean deep: boolean + reading?: "heading" | "prose" } const controls = @@ -158,6 +160,8 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili const collection = area && collections.test(area.role) ? area : branch.collection const priority = Math.min(branch.priority ?? 5, (visible && rank(role)) || 5) + // A status or alert rarely has a name of its own; its text is the message. + const emphasis = branch.emphasis || /^(heading|columnheader|rowheader|status|alert|alertdialog)$/.test(role) const inherited = headings.get(branch.parent) ?? branch.scope const scope = @@ -240,6 +244,7 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili entry, important, deep: branch.level > (options.depth ?? Infinity), + reading: interactive || role === "RootWebArea" || !name.trim() ? undefined : emphasis ? "heading" : "prose", }) } } @@ -257,6 +262,7 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili parentName: visible ? name : branch.parentName, scope, item, + emphasis, priority, area, collection, @@ -296,22 +302,43 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) areas.set(line.area, (areas.get(line.area) ?? 0) + 1) } - for (const original of buckets) { - const order = new Map(original.map((line, i) => [line, i + visited])) + const ordered = buckets.flat() + const order = new Map(ordered.map((line, i) => [line, i])) + + // Links alone can fill any budget and leave an article without its title or opening. Headings and text outside rows + // and list items first take up to a quarter, in reading order; controls get what they leave. A larger share measured + // fewer section headings on documentation pages, and cells would spend it on a table's first rows. + const reading = options.interactive + ? [] + : ordered.filter((line) => !line.deep && (line.reading === "heading" || (line.reading === "prose" && !line.entry))) + + const placed = new Set<Line>() + + for (const [pass, original] of [reading, ...buckets].entries()) { + const chars = pass ? maxChars : maxChars / 4 + const lines = pass ? maxLines : maxLines / 4 + let spent = false // Select within each landmark's budget by usefulness, then restore tree order for reading. const groups = Array.from({ length: 4 }, (): Line[] => []) for (const line of original) - groups[ - line.important || line.entry?.keep ? 0 : line.interactive ? 1 : line.area?.id === line.id && line.id ? 2 : 3 - ].push(line) - const bucket = groups.flat() + if (!placed.has(line)) + groups[ + line.important || line.entry?.keep + ? 0 + : line.interactive || line.reading === "heading" + ? 1 + : line.area?.id === line.id && line.id + ? 2 + : 3 + ].push(line) + const bucket = pass ? groups.flat() : original - for (let i = 0; i < bucket.length; i += 32) { + for (let i = 0; i < bucket.length && !spent; i += 32) { const batch = bucket.slice(i, i + 32) const details = - !full && output.length < maxLines + !full && output.length < lines ? await Promise.all( batch.map(async (line) => { if (!line.id || line.deep) return "" @@ -325,6 +352,14 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) for (const [j, line] of batch.entries()) { if (++visited % 2048 === 0) await setImmediate(undefined, { signal: options.signal }) + if (spent) continue + + // A reading line beyond the share keeps its place in its landmark. + if (!pass && output.length >= lines) { + spent = true + continue + } + if (line.deep || full || output.length >= maxLines) { omit(line) continue @@ -334,13 +369,19 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) const text = (key ? line.label.replace(/^\s*/, (pad) => `${pad}@${key} `) : line.label) + (details[j] ?? "") const length = size + Number(output.length > 0) + text.length - if (length > maxChars) { + if (length > chars && !pass) { + spent = true + continue + } + + if (length > chars) { full = true omit(line) continue } size = length + placed.add(line) output.push({ line, text, order: order.get(line) ?? 0 }) } } From 9215f371082043f6f5900894523982c8c406f526 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:33:05 +1000 Subject: [PATCH 40/44] fix(browser): hide sensitive field values and omit empty ones in snapshots --- packages/gui-plugins/src/browser/chromium.ts | 8 ++-- .../src/browser/field-value.test.ts | 47 +++++++++++++++++++ .../gui-plugins/src/browser/field-value.ts | 44 +++++++++++++++++ packages/gui-plugins/src/browser/snapshot.ts | 13 +++-- 4 files changed, 104 insertions(+), 8 deletions(-) create mode 100644 packages/gui-plugins/src/browser/field-value.test.ts create mode 100644 packages/gui-plugins/src/browser/field-value.ts diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index e3316e23e2c..9b1acdb3b23 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -3,6 +3,7 @@ import { scheduler } from "node:timers/promises" import { navigationTurn, replacementNavigation } from "./navigation-turn" import { accessibilitySnapshot } from "./snapshot" import { documentRefs } from "./refs" +import { describeField, Field, readableField } from "./field-value" import { agentRendering, needsWakeFrame } from "./agent-rendering" import { extensionResource } from "./profile/extension-api/resource" import { Browser } from "@opencode/plugin-browser/rpc" @@ -2300,11 +2301,12 @@ export function createBrowserPage( previous: refs.previous(frameID, sessionID), picked: byNode(picked), ref: options.shared.ref, - // AX does not distinguish password textboxes. Fail closed if the backing input is gone or protected. - readableValue: async backendID => { + // AX does not distinguish password textboxes. Fail closed if the backing field is gone or sensitive. + readableValue: async (backendID, name) => { abortError(signal) + const field = await call({ backendID, frameID, sessionID }, describeField).catch(() => undefined) - return (await call({ backendID, frameID, sessionID }, `function() { return this.isConnected && !(this instanceof HTMLInputElement && ['password','file'].includes(this.type)) && getComputedStyle(this).webkitTextSecurity === 'none' }`).catch(() => false)) === true + return Schema.is(Field)(field) && readableField(field, name) }, box: action.type === "snapshot" && action.boxes ? async (backendID) => { abortError(signal) diff --git a/packages/gui-plugins/src/browser/field-value.test.ts b/packages/gui-plugins/src/browser/field-value.test.ts new file mode 100644 index 00000000000..fdbb22ba8b9 --- /dev/null +++ b/packages/gui-plugins/src/browser/field-value.test.ts @@ -0,0 +1,47 @@ +import { expect, test } from "bun:test" +import type { Protocol } from "devtools-protocol" +import { readableField } from "./field-value" +import { accessibilitySnapshot } from "./snapshot" + +const plain = { type: "text", autocomplete: "", labels: [], masked: false } + +const fields = [ + ["email address", "shown", { ...plain, type: "email" }, "Email", "ada@example.com"], + ["search box", "shown", { ...plain, type: "search", labels: ["q", "Search pinned items"] }, "Search", "kittens"], + ["rich text editor", "shown", { ...plain, type: "" }, "Message body", "Dear Ada"], + ["empty field", "omitted", plain, "Notes", ""], + ["empty password", "omitted", { ...plain, type: "password" }, "Password", ""], + ["password", "hidden", { ...plain, type: "password" }, "Password", "hunter2"], + ["revealed current password", "hidden", { ...plain, autocomplete: "current-password" }, "Show it", "hunter2"], + ["revealed new password", "hidden", { ...plain, autocomplete: "section-a new-password" }, "Choose", "hunter2"], + ["revealed password named by its id", "hidden", { ...plain, labels: ["userPassword"] }, "", "hunter2"], + ["one-time code", "hidden", { ...plain, autocomplete: "one-time-code" }, "Code", "123456"], + ["card number by autocomplete", "hidden", { ...plain, autocomplete: "billing cc-number" }, "Number", "4111111111111111"], + ["card number by label", "hidden", plain, "Card number", "4111111111111111"], + ["CVV placeholder", "hidden", { ...plain, labels: ["CVV"] }, "", "987"], + ["PIN", "hidden", { ...plain, labels: ["pin_code"] }, "", "1234"], + ["OTP name", "hidden", { ...plain, labels: ["otp"] }, "", "1234"], + ["passcode", "hidden", plain, "Passcode", "1234"], + ["API token", "hidden", { ...plain, labels: ["api_token"] }, "", "sk-1"], + ["client secret", "hidden", plain, "Client secret", "abc"], + ["SSN", "hidden", plain, "SSN", "123-45-6789"], + ["masked text", "hidden", { ...plain, masked: true }, "Answer", "blue"], + ["file input", "hidden", { ...plain, type: "file" }, "Upload", "C:\\fakepath\\a.txt"], + ["field gone or unreadable", "hidden", undefined, "Name", "Ada"], +] as const + +test.each(fields)("%s: value %s", async (_, expected, field, name, value) => { + const textbox: Protocol.Accessibility.AXNode = { + nodeId: "1", + backendDOMNodeId: 1, + ignored: false, + role: { type: "role", value: "textbox" }, + name: { type: "string", value: name }, + value: { type: "string", value }, + } + + const readableValue = async (_: number, label: string) => !!field && readableField(field, label) + const content = (await accessibilitySnapshot([textbox], { previous: new Map(), picked: new Map(), ref: () => "e1", readableValue })).content + const printed = content.match(/ value=(.*)$/)?.[1] + expect(printed === undefined ? "omitted" : printed === "<hidden>" ? "hidden" : printed === JSON.stringify(value) ? "shown" : printed).toBe(expected) +}) diff --git a/packages/gui-plugins/src/browser/field-value.ts b/packages/gui-plugins/src/browser/field-value.ts new file mode 100644 index 00000000000..84d75d62e06 --- /dev/null +++ b/packages/gui-plugins/src/browser/field-value.ts @@ -0,0 +1,44 @@ +import { Schema } from "effect" + +/** What the page says about a field whose value a snapshot would print. */ +export const Field = Schema.Struct({ + type: Schema.String, + autocomplete: Schema.String, + /** Its id, name, placeholder, `aria-label` and label texts. */ + labels: Schema.Array(Schema.String), + /** Whether the page masks its characters, as `-webkit-text-security` does. */ + masked: Schema.Boolean, +}) + +/** Reads `Field` from the element a CDP function runs on. */ +export const describeField = `function() { + return { + type: this instanceof HTMLInputElement ? this.type : "", + autocomplete: this.getAttribute("autocomplete") ?? "", + labels: [this.id, this.getAttribute("name"), this.getAttribute("placeholder"), this.getAttribute("aria-label"), ...Array.from(this.labels ?? [], (label) => label.textContent)].filter(Boolean), + masked: getComputedStyle(this).webkitTextSecurity !== "none", + } +}` + +const secretTokens = /^(current-password|new-password|one-time-code|cc-.+)$/ + +const secretWords = /passw|passcode|secret|token|card ?(number|num|no)\b|\b(pwd|otp|pin|cvv|cvc|ssn)\b/ + +/** + * Whether a snapshot may print a field's value; `name` is its accessible name. Chromium keeps no type history, so a + * password that a "show password" toggle turned into `type="text"` is recognised by its autocomplete, name or label. + */ +export function readableField(field: typeof Field.Type, name: string) { + if (field.masked || /^(password|file)$/.test(field.type)) return false + + if (field.autocomplete.toLowerCase().split(/\s+/).some((token) => secretTokens.test(token))) return false + + return ![name, ...field.labels].some((label) => + secretWords.test( + label + .replace(/([a-z])([A-Z])/g, "$1 $2") + .replace(/[\W_]+/g, " ") + .toLowerCase(), + ), + ) +} diff --git a/packages/gui-plugins/src/browser/snapshot.ts b/packages/gui-plugins/src/browser/snapshot.ts index 7891a8593d0..55f18319f15 100644 --- a/packages/gui-plugins/src/browser/snapshot.ts +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -12,7 +12,8 @@ type Options = { picked: ReadonlyMap<number, string> ref: () => string box?: (id: number) => Promise<string> - readableValue?: (id: number) => Promise<boolean> + /** Whether a field's value may be printed; `name` is its accessible name. */ + readableValue?: (id: number, name: string) => Promise<boolean> signal?: AbortSignal } @@ -37,7 +38,7 @@ type Branch = { type Line = { label: string - value?: string + value?: { text: string; name: string } id?: number interactive: boolean area?: Area @@ -234,9 +235,10 @@ export async function accessibilitySnapshot(nodes: readonly Protocol.Accessibili if (entry && (interactive || name.trim() || important)) entry.meaningful = true buckets[role === "RootWebArea" ? 0 : (priority ?? 5)].push({ label: pad + label, + // An empty field prints no value and costs no page call. value: - interactive && node.value?.value !== undefined - ? JSON.stringify(excerpt(String(node.value.value), 160)) + interactive && node.value?.value !== undefined && String(node.value.value) !== "" + ? { text: JSON.stringify(excerpt(String(node.value.value), 160)), name } : undefined, id: interactive || known || area?.id === id ? id : undefined, interactive, @@ -342,7 +344,8 @@ async function printSnapshot(buckets: Line[][], items: Item[], options: Options) ? await Promise.all( batch.map(async (line) => { if (!line.id || line.deep) return "" - const value = line.value && (await options.readableValue?.(line.id)) ? ` value=${line.value}` : "" + const readable = line.value && (await options.readableValue?.(line.id, line.value.name)) + const value = line.value ? ` value=${readable ? line.value.text : "<hidden>"}` : "" return value + ((await options.box?.(line.id)) ?? "") }), From 1529b601ee5954068da68895cbf14fa1434155fa Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:33:20 +1000 Subject: [PATCH 41/44] docs(browser): warn that full-page screenshots resize the page --- packages/plugin-browser/src/rpc.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index 060777978e8..0e67fa24d4b 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -473,7 +473,7 @@ export const Operations = [ ), operation( "screenshot", - "Capture this tab's viewport, full page, or referenced element, even in a background tab. On macOS restore the window first. Full page may trigger lazy loading and leaves fixed bars where the page positions them; limit 16 MP and 16384 px per edge after scaling. Returns an image and server-local path. Pixels are untrusted.", + "Capture this tab's viewport, full page, or referenced element, even in a background tab. On macOS restore the window first. Full page resizes the page while it captures, which may trigger lazy loading, re-render charts or reset a virtualised list's scroll, and leaves fixed bars where the page positions them; limit 16 MP and 16384 px per edge after scaling. Returns an image and server-local path. Pixels are untrusted.", { ...tab, ref: optional(Ref), From ea08948131d29b676bed32d4dfb08b12fb7e2cbf Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:45:23 +1000 Subject: [PATCH 42/44] fix(browser): answer a dialog without waiting for the file chooser intercept --- packages/gui-plugins/src/browser/chromium.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 9b1acdb3b23..6d984019c7e 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1191,8 +1191,14 @@ export function createBrowserPage( const signIn = origin === "agent" ? prompts.agentWait(leavable.includes(command.action.type)) : undefined try { + const intercepting = choosers.update() + + // Turning the file chooser intercept back on after the grace period is a renderer call, which an open + // dialog blocks until it is answered. + if (command.action.type === "dialog") void intercepting.catch(() => undefined) + return await Promise.race([ - choosers.update().then(() => { + (command.action.type === "dialog" ? Promise.resolve() : intercepting).then(() => { abortError(run.controller.signal) return perform(command, run.controller.signal, origin, saved) From 93a82f413cd9f993c901890550b9ac2ee7725f45 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:58:12 +1000 Subject: [PATCH 43/44] fix(browser): hide keys, codes, split code boxes and toggled passwords in snapshots --- .../src/browser/field-value.test.ts | 20 +++++++++++++- .../gui-plugins/src/browser/field-value.ts | 26 +++++++++++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/packages/gui-plugins/src/browser/field-value.test.ts b/packages/gui-plugins/src/browser/field-value.test.ts index fdbb22ba8b9..cbf4ece4c9b 100644 --- a/packages/gui-plugins/src/browser/field-value.test.ts +++ b/packages/gui-plugins/src/browser/field-value.test.ts @@ -3,10 +3,28 @@ import type { Protocol } from "devtools-protocol" import { readableField } from "./field-value" import { accessibilitySnapshot } from "./snapshot" -const plain = { type: "text", autocomplete: "", labels: [], masked: false } +const plain = { type: "text", autocomplete: "", labels: [], masked: false, maxLength: -1, toggles: [] } const fields = [ ["email address", "shown", { ...plain, type: "email" }, "Email", "ada@example.com"], + ["max tokens", "shown", { ...plain, type: "number", labels: ["maxTokens"] }, "Max tokens", "4096"], + ["username in a form whose Show password button is not its own", "shown", { ...plain, labels: ["username"] }, "Username", "ada"], + ["API key", "hidden", plain, "API key", "sk-1"], + ["API key by an acronym id", "hidden", { ...plain, labels: ["APIKey"] }, "", "sk-1"], + ["private key", "hidden", plain, "Private key", "-----BEGIN"], + ["access key named api_key", "hidden", { ...plain, labels: ["api_key"] }, "Access key", "AKIA1"], + ["access token", "hidden", { ...plain, labels: ["accessToken"] }, "", "t1"], + ["verification code", "hidden", plain, "Verification code", "123456"], + ["security code", "hidden", plain, "Security code", "123"], + ["recovery code", "hidden", plain, "Recovery code", "abcd-efgh"], + ["backup code", "hidden", plain, "Backup code", "abcd-efgh"], + ["2FA", "hidden", plain, "2FA", "123456"], + ["TOTP", "hidden", { ...plain, labels: ["totp"] }, "", "123456"], + ["MFA", "hidden", plain, "MFA code", "123456"], + ["split one-time code, text box", "hidden", { ...plain, maxLength: 1 }, "Digit 1", "4"], + ["split one-time code, tel box", "hidden", { ...plain, type: "tel", maxLength: 1 }, "", "4"], + ["split one-time code, number box", "hidden", { ...plain, type: "number", maxLength: 1 }, "", "4"], + ["revealed password beside Hide password", "hidden", { ...plain, labels: ["field_2"], toggles: ["Hide password"] }, "", "hunter2"], ["search box", "shown", { ...plain, type: "search", labels: ["q", "Search pinned items"] }, "Search", "kittens"], ["rich text editor", "shown", { ...plain, type: "" }, "Message body", "Dear Ada"], ["empty field", "omitted", plain, "Notes", ""], diff --git a/packages/gui-plugins/src/browser/field-value.ts b/packages/gui-plugins/src/browser/field-value.ts index 84d75d62e06..d28ff0ae831 100644 --- a/packages/gui-plugins/src/browser/field-value.ts +++ b/packages/gui-plugins/src/browser/field-value.ts @@ -8,34 +8,50 @@ export const Field = Schema.Struct({ labels: Schema.Array(Schema.String), /** Whether the page masks its characters, as `-webkit-text-security` does. */ masked: Schema.Boolean, + /** An input's `maxLength`, -1 when it has none. */ + maxLength: Schema.Number, + /** The `aria-label` or text of buttons beside the field, such as "Show password". */ + toggles: Schema.Array(Schema.String), }) -/** Reads `Field` from the element a CDP function runs on. */ +/** + * Reads `Field` from the element a CDP function runs on. Buttons count as the field's own only when it is the only + * field in its parent, so a login form's "Show password" does not hide its username. + */ export const describeField = `function() { + const parent = this.parentElement + const own = parent && parent.querySelectorAll("input, textarea, [contenteditable]").length === 1 return { type: this instanceof HTMLInputElement ? this.type : "", autocomplete: this.getAttribute("autocomplete") ?? "", labels: [this.id, this.getAttribute("name"), this.getAttribute("placeholder"), this.getAttribute("aria-label"), ...Array.from(this.labels ?? [], (label) => label.textContent)].filter(Boolean), masked: getComputedStyle(this).webkitTextSecurity !== "none", + maxLength: this instanceof HTMLInputElement ? this.maxLength : -1, + toggles: own ? Array.from(parent.querySelectorAll('button, [role="button"]'), (button) => button.getAttribute("aria-label") || button.textContent).filter(Boolean) : [], } }` const secretTokens = /^(current-password|new-password|one-time-code|cc-.+)$/ -const secretWords = /passw|passcode|secret|token|card ?(number|num|no)\b|\b(pwd|otp|pin|cvv|cvc|ssn)\b/ +const secretWords = + /passw|passcode|secret|\btoken\b|\b(api|private|access|signing|auth|ssh|webhook|encryption) ?key\b|\b(security|verification|recovery|backup) ?code\b|card ?(number|num|no)\b|\b(pwd|otp|totp|2fa|mfa|pin|cvv|cvc|ssn)\b/ /** - * Whether a snapshot may print a field's value; `name` is its accessible name. Chromium keeps no type history, so a - * password that a "show password" toggle turned into `type="text"` is recognised by its autocomplete, name or label. + * Whether a snapshot may print a field's value; `name` is its accessible name. When unsure, it hides. Chromium keeps + * no type history, so a password that a "show password" toggle turned into `type="text"` is recognised by its + * autocomplete, name, label or that toggle; a split one-time code by its one-character boxes. */ export function readableField(field: typeof Field.Type, name: string) { if (field.masked || /^(password|file)$/.test(field.type)) return false + if (field.maxLength === 1 && /^(text|tel|number)$/.test(field.type)) return false + if (field.autocomplete.toLowerCase().split(/\s+/).some((token) => secretTokens.test(token))) return false - return ![name, ...field.labels].some((label) => + return ![name, ...field.labels, ...field.toggles].some((label) => secretWords.test( label + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/[\W_]+/g, " ") .toLowerCase(), From 6af944faeafa36b5e75d116f2d5315ded15b90a4 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:02:33 +1000 Subject: [PATCH 44/44] test(core): read an unattached browser's answer as disconnected in the listing table browser-deny-listing's table expected [browser.disconnected] from tabs.list and tabs.open without a desktop; browser-deep-snapshot answers tabs.list with connected: false and fails other operations with [browser.not_attached]. Both mean the session has no desktop; the table now classifies them so. --- packages/core/test/browser-permission.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/test/browser-permission.test.ts b/packages/core/test/browser-permission.test.ts index ea09b6e1241..1e90ccaaf4f 100644 --- a/packages/core/test/browser-permission.test.ts +++ b/packages/core/test/browser-permission.test.ts @@ -638,6 +638,8 @@ const truth: ReadonlyArray<{ { name: "whole browser denied, one operation allowed after", global: [rule("*", "deny"), rule("tabs.list", "allow")], attached: true, listed: true, list: "allow", open: "deny" }, ] +const unattached = Schema.is(Schema.Struct({ output: Schema.Struct({ connected: Schema.Literal(false) }) })) + // What `operation` comes to for `agent` in `sessionID`. const outcome = ( browser: Effect.Success<ReturnType<typeof setup>>, @@ -658,12 +660,13 @@ const settle = Effect.fnUntraced(function* ( const before = browser.commands.count const reached = () => browser.commands.count > before const settled = call.pipe( - Effect.as<Outcome | string>("allow"), + // Without a desktop, tabs.list answers that the browser is not attached instead of failing. + Effect.map((result): Outcome | string => (unattached(result) ? "disconnected" : "allow")), Effect.catch((error) => Effect.succeed( error.message.startsWith("[browser.denied]") || error.message.startsWith("Permission denied") || error.error instanceof Permission.BlockedError ? "deny" - : error.message.startsWith("[browser.disconnected]") + : error.message.startsWith("[browser.disconnected]") || error.message.startsWith("[browser.not_attached]") ? "disconnected" : reached() ? "allow"