diff --git a/packages/app/component-tests/browser-pane-restore.spec.ts b/packages/app/component-tests/browser-pane-restore.spec.ts index 034e59c2672..f353929c52c 100644 --- a/packages/app/component-tests/browser-pane-restore.spec.ts +++ b/packages/app/component-tests/browser-pane-restore.spec.ts @@ -698,3 +698,82 @@ 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") + + // 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") + 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; 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) + }) + 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/component-tests/browser-pane.spec.ts b/packages/app/component-tests/browser-pane.spec.ts index 8cc78aacca0..d74006b75a9 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, 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", "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.tsx b/packages/app/src/shell/commands/command.tsx index 7c916ee63a0..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" @@ -514,7 +515,8 @@ export const { use: useCommand, provider: CommandProvider } = createSimpleContex } const handleKeyDown = (event: KeyboardEvent) => { - if (suspended() || dialog.active) return + // 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) const isPalette = palette().has(sig) diff --git a/packages/core/src/permission.ts b/packages/core/src/permission.ts index d2682097cb6..80547e04f74 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,44 @@ 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 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 ?? [])] + // 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)(added).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 { readonly close: Effect.Effect readonly ask: (input: AssertInput) => Effect.Effect @@ -169,8 +207,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..e88aa73b0af 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, @@ -184,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({ name: "tool", initial: () => ({ @@ -233,7 +234,7 @@ const layer = Layer.effect( }, }), notify: (value) => { - catalog = undefined + catalogs.clear() return Effect.forEach( value.errors, ({ kind, name, namespace, error }) => @@ -270,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( @@ -283,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: [ @@ -382,10 +387,11 @@ 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" -} +/** 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") const formatSchemaIssue = SchemaIssue.makeFormatterDefault() 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 f872042b67b..1e90ccaaf4f 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,21 @@ 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 { 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" +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( @@ -41,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()}`), @@ -56,11 +63,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 = {}) => 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 @@ -127,9 +136,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({}) @@ -186,7 +222,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 }) }), ) @@ -222,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))) @@ -424,16 +460,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).pipe(Effect.flip)).message).toStartWith("[browser.not_attached]") + expect(browser.commands.count).toBe(0) }), ) @@ -579,3 +610,339 @@ 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" }, +] + +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>, + 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>, + sessionID: Session.ID, + call: Effect.Effect, +) { + const permissions = Context.get(browser.context, Permission.Service) + const before = browser.commands.count + const reached = () => browser.commands.count > before + const settled = call.pipe( + // 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.not_attached]") + ? "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(settled, 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) + }), +) +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) + }), +) + +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>, 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/core/test/browser-tools.test.ts b/packages/core/test/browser-tools.test.ts index fb0080d2df6..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", @@ -293,7 +296,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; 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"), "")) @@ -307,10 +310,7 @@ 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(`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/core/test/permission.test.ts b/packages/core/test/permission.test.ts index 80fe7c5dadf..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" @@ -881,3 +881,118 @@ 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 + 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.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" }) + 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({ 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 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" }]) + 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({ 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({ action: 1, resource: "*" } as unknown as Parameters[0])), + ) + 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/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 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", { 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 - 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 openFilePicker(opts?: FilePickerOptions): Promise 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..2b64a2af199 100644 --- a/packages/desktop/src/renderer/platform/menu.ts +++ b/packages/desktop/src/renderer/platform/menu.ts @@ -1,4 +1,5 @@ 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 { @@ -23,9 +24,17 @@ 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) => { + // 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 }) + }) } /** 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()("Deep export class MenuCommandTriggered extends Schema.TaggedClass()("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", { 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..4deb83329a2 --- /dev/null +++ b/packages/gui-plugins/src/browser/agent-rendering.test.ts @@ -0,0 +1,79 @@ +import { expect, test } from "bun:test" +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() + 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) +}) + +test("overlapping commands await the same first frame", async () => { + const render = agentRendering(new AbortController().signal, () => {}, () => () => {}) + const frame = Promise.withResolvers() + 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]() +}) + +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() + 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(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(snapshot.painted).resolves.toBeUndefined() +}) 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..4af49113944 --- /dev/null +++ b/packages/gui-plugins/src/browser/agent-rendering.ts @@ -0,0 +1,56 @@ +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) { + 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. +const idleMs = 30_000 + +export function agentRendering(signal: AbortSignal, throttle: (enabled: boolean) => void, after = scheduleIdle) { + let holds = 0 + let awake = false + let paint: Promise | undefined + let cancel: (() => void) | undefined + signal.addEventListener("abort", () => cancel?.(), { once: true }) + + return { + hold(onWake?: () => Promise) { + signal.throwIfAborted() + cancel?.() + + if (!awake) { + throttle(false) + paint = onWake?.().catch(() => undefined) + void paint?.then(() => { paint = undefined }) + } + + awake = true + holds++ + + return { + painted: onWake ? paint : undefined, + [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/capture.test.ts b/packages/gui-plugins/src/browser/capture.test.ts index 6bfc72282ce..f32dd725621 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) @@ -37,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(() => {}), 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() diff --git a/packages/gui-plugins/src/browser/capture.ts b/packages/gui-plugins/src/browser/capture.ts index ee654fdb887..645109ad0c5 100644 --- a/packages/gui-plugins/src/browser/capture.ts +++ b/packages/gui-plugins/src/browser/capture.ts @@ -4,10 +4,26 @@ 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 } +/** 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 @@ -32,7 +48,7 @@ const schedule: Schedule = (ms, run) => { export function captureCoordinator(begin: () => void, end: () => void, after: Schedule = schedule) { let holders = 0 - return async (presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise) => { + return async (presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise, deadline = CAPTURE_DEADLINE_MS) => { const cancel = () => new Error("Browser capture was cancelled.") if (signal.aborted) throw cancel() @@ -62,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 { @@ -126,14 +142,13 @@ export function undrawable(window: { return undefined } -const causes: Record = { +const causes: Record, 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 5526ee23a53..d90a930ec25 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -1,12 +1,17 @@ import { homedir } from "node:os" -import { navigationTurn } from "./navigation-turn" +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" 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, 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" @@ -27,6 +32,7 @@ import { frameStillCurrent, isDocumentClosed, isNavigationPending, + retryOnly, transitionDocument, type DocumentEvent, } from "./page-machine" @@ -88,6 +94,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. */ @@ -160,7 +175,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) { @@ -308,6 +323,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, @@ -324,7 +341,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) @@ -355,7 +373,7 @@ export function createBrowserPage( if (pageReload(input, process.platform === "darwin")) { event.preventDefault() - void reload().catch((error: Error) => publish(error.message)) + void options.menu.navigate("reload").catch((error: Error) => publish(error.message)) return } @@ -422,7 +440,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 @@ -439,7 +459,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() + 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() @@ -499,12 +519,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 @@ -515,7 +535,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) => { @@ -681,6 +704,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 } @@ -698,8 +724,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() @@ -709,7 +733,7 @@ export function createBrowserPage( passkeyPage.interrupted = false 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 }), @@ -815,6 +839,7 @@ export function createBrowserPage( overrideBrowserWindowOptions: { webPreferences: { nodeIntegration: false, + nodeIntegrationInSubFrames: options.local === true, contextIsolation: true, sandbox: true, webSecurity: true, @@ -1016,12 +1041,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.")) @@ -1048,24 +1075,39 @@ 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) => { + const reload = async (signal = options.signal, ignoreCache = false) => { const tab = state() - 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() @@ -1075,7 +1117,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([ @@ -1083,7 +1125,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) @@ -1097,7 +1145,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() @@ -1105,7 +1153,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(), @@ -1128,9 +1176,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 } }, @@ -1139,10 +1188,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({ @@ -1153,7 +1203,7 @@ 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, @@ -1174,8 +1224,25 @@ 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 { + using active = new DisposableStack() + + 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 && shouldPaint() ? async () => { + await ready + + 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" }) + 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. @@ -1196,10 +1263,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) @@ -1208,9 +1272,16 @@ 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([ - // The agent drives the tab from here on: refuse passkeys in the browser process before its action runs. - afterRefusal(origin === "agent" ? restrictPasskeys : undefined, choosers.update(), () => { + // The agent drives the tab from here on: refuse passkeys in the browser process before its action runs. The + // refusal is the browser process's own command, which an open dialog does not block. + afterRefusal(origin === "agent" ? restrictPasskeys : undefined, command.action.type === "dialog" ? Promise.resolve() : intercepting, () => { abortError(run.controller.signal) return perform(command, run.controller.signal, origin, saved) @@ -1358,7 +1429,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) } @@ -1382,7 +1453,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() @@ -1398,7 +1469,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( @@ -1418,7 +1489,7 @@ export function createBrowserPage( "Runtime.callFunctionOn", { objectId, - functionDeclaration: action.script, + functionDeclaration: connectedFunction(action.script), arguments: [{ objectId }], awaitPromise: true, returnByValue: true, @@ -1437,6 +1508,8 @@ 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)}`, @@ -1541,7 +1614,14 @@ 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.', ) @@ -1559,6 +1639,8 @@ 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))) { @@ -1805,7 +1887,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 @@ -1879,7 +1961,7 @@ export function createBrowserPage( "Runtime.callFunctionOn", { objectId, - functionDeclaration, + functionDeclaration: connectedFunction(functionDeclaration), arguments: args.map((value) => ({ value })), returnByValue: true, awaitPromise: true, @@ -1887,6 +1969,8 @@ 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) @@ -1900,16 +1984,12 @@ 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 } - async function rect(element: Element, scroll = false) { + async function rect(element: Element, scroll = false, knownTree?: Awaited>) { 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. @@ -1927,7 +2007,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) { @@ -1979,7 +2059,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, signal: AbortSignal) { @@ -1989,14 +2069,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 ( @@ -2069,21 +2143,14 @@ export function createBrowserPage( action: Extract, 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 pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getNormalBounds()).scaleFactor + 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 }, }) @@ -2294,7 +2361,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 @@ -2305,79 +2373,45 @@ 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.", - ) - refs.clear() - const pinned = new Map(Array.from(picked, ([ref, element]) => [`${element.frameID}:${element.backendID}`, ref])) - const lines: string[] = [] - let truncated = false + const byNode = (source: Map) => new Map(Array.from(source) + .filter(([, element]) => element.frameID === frameID && element.sessionID === sessionID) + .map(([ref, element]) => [element.backendID, ref])) - const walk = async (node: Protocol.Accessibility.AXNode, level: number): Promise => { - if (level > depth || lines.length >= 500) { - truncated = true + const snapshot = await accessibilitySnapshot(ax.nodes, { + root: selected?.backendID, + depth: action.type === "snapshot" ? action.depth : undefined, + text: action.type === "find" ? action.text : undefined, + interactive: action.interactive, + maxLines: action.maxLines, + maxChars: action.maxChars, + signal, + previous: refs.previous(frameID, sessionID), + picked: byNode(picked), + ref: options.shared.ref, + // 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 - } + return Schema.is(Field)(field) && readableField(field, name) + }, + box: action.type === "snapshot" && action.boxes ? async (backendID) => { + abortError(signal) + const box = await rect({ backendID, frameID, sessionID }, false, tree).catch(() => undefined) - const role = String(node.role?.value ?? "node") - .replace(/[^a-zA-Z0-9_-]/g, "") - .slice(0, 40) + return box ? ` box=${JSON.stringify(box)}` : "" + } : undefined, + }) - const properties = new Map(node.properties?.map((property) => [property.name, property.value.value]) ?? []) + abortError(signal) - if (!node.ignored) { - const actionable = - role !== "RootWebArea" && - (properties.get("focusable") || /^(button|link|textbox|combobox|checkbox|radio|option)$/.test(role)) + if (documentGeneration(documentState) !== generation) throw new CodedError(Browser.FailureCode.documentChanged, "Document changed during snapshot; request a fresh snapshot.") + refs.add(frameID, sessionID, snapshot.refs) - // 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/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..7fb4760e22a 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 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 @@ -25,6 +26,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 } @@ -60,6 +62,7 @@ export function openBinding(input: { ) return { + binding, load(tabID) { if (status.closed) return void ready.then(() => client.load({ binding, tabID })).catch(() => undefined) @@ -84,6 +87,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/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/gui-plugins/src/browser/errors.ts b/packages/gui-plugins/src/browser/errors.ts index 2751fca7e2d..8122a1f3b07 100644 --- a/packages/gui-plugins/src/browser/errors.ts +++ b/packages/gui-plugins/src/browser/errors.ts @@ -1,11 +1,11 @@ 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. */ 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, ) { @@ -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/gui-plugins/src/browser/field-value.test.ts b/packages/gui-plugins/src/browser/field-value.test.ts new file mode 100644 index 00000000000..cbf4ece4c9b --- /dev/null +++ b/packages/gui-plugins/src/browser/field-value.test.ts @@ -0,0 +1,65 @@ +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, 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", ""], + ["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" : 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..d28ff0ae831 --- /dev/null +++ b/packages/gui-plugins/src/browser/field-value.ts @@ -0,0 +1,60 @@ +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, + /** 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. 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|\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. 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, ...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(), + ), + ) +} 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 bb7bf47ad52..f46a3fe71f9 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", @@ -217,6 +218,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/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": "在系統瀏覽器中開啟", diff --git a/packages/gui-plugins/src/browser/ipc.ts b/packages/gui-plugins/src/browser/ipc.ts index adcd7752486..80dca7eef19 100644 --- a/packages/gui-plugins/src/browser/ipc.ts +++ b/packages/gui-plugins/src/browser/ipc.ts @@ -170,8 +170,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 })), }), @@ -252,6 +253,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..56b0e65ee14 100644 --- a/packages/gui-plugins/src/browser/keys.test.ts +++ b/packages/gui-plugins/src/browser/keys.test.ts @@ -75,7 +75,7 @@ test("forwards browser and shell shortcuts while leaving page editing, reload an ["mod", "\\", false, "\\"], ["mod+shift", "T", true, "t"], ["mod+shift", "R", true, "r"], - ["mod+shift", "R", false, "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"], @@ -152,7 +152,7 @@ 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][] = [ + const cases: [modifiers: string, key: string, mac: boolean, reloads: ReturnType, code?: string][] = [ ["", "F5", true, true], ["", "F5", false, true], ["mod", "r", true, true], @@ -160,12 +160,13 @@ test("reloads the focused page on F5 and the platform's reload chord, leaving ot // 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", "F5", false, false], ["mod+alt", "r", true, false], ["ctrl", "r", true, false], ["mod", "F5", true, false], + ["ctrl", "F5", true, false], ["", "r", true, false], ] diff --git a/packages/gui-plugins/src/browser/keys.ts b/packages/gui-plugins/src/browser/keys.ts index 3ef6db73a5e..cb3790775ef 100644 --- a/packages/gui-plugins/src/browser/keys.ts +++ b/packages/gui-plugins/src/browser/keys.ts @@ -82,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 75c533a324a..5cebdf39ae4 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,27 @@ 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), @@ -145,6 +166,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), @@ -185,8 +207,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 ce80d1d7659..61cf57e3d32 100644 --- a/packages/gui-plugins/src/browser/model.ts +++ b/packages/gui-plugins/src/browser/model.ts @@ -68,13 +68,13 @@ 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 = { visible: () => boolean address: () => string - reload: () => void + reload: (ignoreCache?: boolean) => void /** Closes the selected browser tab, including a blank page. */ close: () => void inspectable: () => boolean @@ -421,7 +421,7 @@ export function createModel(ctx: SetupContext) { 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 @@ -682,8 +682,10 @@ export function createModel(ctx: SetupContext) { }, /** 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), + 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/navigation-turn.test.ts b/packages/gui-plugins/src/browser/navigation-turn.test.ts index 7abe633f1a0..a974341c1ce 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[] = [] @@ -30,6 +48,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() + 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() const events: string[] = [] diff --git a/packages/gui-plugins/src/browser/navigation-turn.ts b/packages/gui-plugins/src/browser/navigation-turn.ts index 26e78a923ca..51c5fbdde13 100644 --- a/packages/gui-plugins/src/browser/navigation-turn.ts +++ b/packages/gui-plugins/src/browser/navigation-turn.ts @@ -1,17 +1,37 @@ 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, 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 +48,20 @@ 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 + + // 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() + heldStop(address || undefined) + + return + } + cancel() }, - begin(signal: AbortSignal) { + begin(signal: AbortSignal, keepAddress = true) { cancel() const mine = new AbortController() pending = mine @@ -42,6 +73,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 +92,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..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, @@ -62,8 +63,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 +71,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, replay(visit("file:///workspace/report.html")).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: 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)) + } +}) + // 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 }, @@ -94,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 19cd0a9d323..17afb1834f5 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: state.status === "loaded" ? undefined : 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": @@ -194,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 } @@ -210,6 +220,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 +228,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 +237,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 { @@ -307,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/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-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 }) diff --git a/packages/gui-plugins/src/browser/pane.ts b/packages/gui-plugins/src/browser/pane.ts index 031482e5cb3..153acebe5cb 100644 --- a/packages/gui-plugins/src/browser/pane.ts +++ b/packages/gui-plugins/src/browser/pane.ts @@ -130,6 +130,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) @@ -387,6 +396,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) @@ -420,6 +439,19 @@ 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) + 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) await page(binding, tabID)?.clearSite() @@ -720,7 +752,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, @@ -900,7 +936,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) // The agent may only focus the tab, which runs no command on its page: the refusal starts now all the same, and // where it cannot, the page fails. diff --git a/packages/gui-plugins/src/browser/panel.fixture.tsx b/packages/gui-plugins/src/browser/panel.fixture.tsx index 0bab9b25e81..5dbdbc34807 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" @@ -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,9 +1267,11 @@ 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, + // Main answers the page, which then waits on nothing. + answer: async () => ask(null), reveal: async () => undefined, close: async () => undefined, forget: async () => undefined, @@ -1288,7 +1294,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 +1329,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 +1520,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/panel.tsx b/packages/gui-plugins/src/browser/panel.tsx index b13278e8e21..013001b4baa 100644 --- a/packages/gui-plugins/src/browser/panel.tsx +++ b/packages/gui-plugins/src/browser/panel.tsx @@ -150,8 +150,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 @@ -159,9 +162,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) } @@ -327,7 +330,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 @@ -450,10 +453,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() @@ -607,10 +610,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={ <Show when={state()?.loading} fallback={<Icon name="outline-rotate-clockwise" />}> @@ -679,6 +683,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 + }} /> </Show> </Show> @@ -1014,7 +1023,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> @@ -1303,6 +1314,7 @@ function SiteInformation(props: { /** The page's cookie count; undefined while the pane cannot answer. */ site: () => Promise<{ cookies: number }> | undefined clear: () => Promise<void> | undefined + clearCache: () => Promise<void> | undefined }) { const plugin = usePlugin() const [siteState, setSiteState] = createSignal(initialSiteState) @@ -1340,7 +1352,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( @@ -1446,6 +1458,14 @@ function SiteInformation(props: { {plugin.t(view().failed ? "common.retry" : "site.cookies.clear")} </Button> </SiteRow> + <Button + size="small" + variant="neutral" + disabled={view().actionDisabled || view().failed} + onClick={() => dispatch({ type: "clear-cache.clicked" })} + > + {plugin.t("site.clearCache")} + </Button> <SiteRow icon="outline-eye-slash" title={plugin.t("site.permissions")} 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..77a41143243 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 @@ -244,12 +245,14 @@ 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 + + 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..9370f6f31ac --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/frame-styles.js @@ -0,0 +1,46 @@ +// 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, acknowledge) => { + try { + if (acknowledge) ipcRenderer.send(`${channel}:received`) + 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..f273764c51a 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, @@ -85,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/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..09dd4745e8f --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.test.ts @@ -0,0 +1,183 @@ +import { expect, test } from "bun:test" +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, 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" + 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], + [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], + [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) +}) + +// 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) + + if (item?.remove && item.origin === "user" && id === 8) return void ipc.emit(channel, {}, "user-removal") + 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 contents of the page\.$/) + 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(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") + + 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>() + 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..19c7bbde6df --- /dev/null +++ b/packages/gui-plugins/src/browser/profile/extension-api/styles.ts @@ -0,0 +1,229 @@ +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" +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 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])]) + +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) { + 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) || (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) { + 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 + + 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()) + + 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(denied) + const css = details.code ?? await packageCSS(extension, details.file ?? "") + + 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 + + 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", blank)), + ]).catch(cause => { throw lifetime.signal.reason === absent ? absent : cause }) + + 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 { + clearTimeout(timer) + + if (blank) ipc.off(`${channel}:received`, heard) + lifetime.abort() + ipc.removeHandler(channel) + } + })) + + 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") + + 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). 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.") + + 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 + + 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 })) + + 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(denied) + + 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 realpath(extension.path).then(root => openContained(root, path)).catch(() => undefined) + + if (!opened) throw new Error(`Could not load file: '${resource}'.`) + + 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/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`. diff --git a/packages/gui-plugins/src/browser/profile/ipc.ts b/packages/gui-plugins/src/browser/profile/ipc.ts index d17d8b61101..700648644d0 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)) @@ -271,6 +272,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 }), }), 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..aac672c6387 --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-keys.test.ts @@ -0,0 +1,114 @@ +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. `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, 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]) { + 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", "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, 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+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") + }) + + 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, { 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("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") + } + + 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("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") + expect(owner("Alt+F6", 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 new file mode 100644 index 00000000000..f931a1a59aa --- /dev/null +++ b/packages/gui-plugins/src/browser/prompt-keys.ts @@ -0,0 +1,120 @@ +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 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< + 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 context menu. */ + | "field" + /** The window or the system, as Chrome leaves them with a tab-modal dialog: close or new window, quit, hide, full screen. */ + | "window" + /** + * 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" + +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; with Shift only redo +// and paste as plain text. +const editing: readonly string[] = ["a", "c", "x", "v", "z"] + +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" + + // 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 plain = !key.ctrlKey && !key.metaKey && !key.altKey + + 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" + + if (windowChord(name, backquote, key, input.mac)) return "window" + + if (input.mac) { + // The emoji and symbols picker types into the field. + if (key.ctrlKey && key.metaKey && !key.altKey && name === " ") return "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 (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" +} + +// 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" || backquote + + if (key.altKey && !key.shiftKey) return name === "h" + + 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 b191a25dcf9..6870fe64898 100644 --- a/packages/gui-plugins/src/browser/prompts.tsx +++ b/packages/gui-plugins/src/browser/prompts.tsx @@ -2,12 +2,14 @@ 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" 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" @@ -29,11 +31,15 @@ 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() 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 @@ -72,6 +78,12 @@ 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) + onCleanup(() => root.removeEventListener("keydown", keyDown)) onCleanup(() => { const active = document.activeElement @@ -85,8 +97,26 @@ 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 and the native menu run no shortcut while the + // 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) => { + 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() + + if (owner === "swallowed") return event.preventDefault() + + if (owner === "exit") { + event.preventDefault() + + return props.leave() + } + if (cancelKey(event)) { event.preventDefault() event.stopPropagation() @@ -95,9 +125,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() @@ -130,6 +160,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", @@ -138,17 +170,32 @@ 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" + onFocusIn={(event) => { + if (event.target instanceof HTMLElement) last = event.target + }} aria-labelledby={title} 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 +479,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} @@ -515,7 +564,12 @@ 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) function siteSays(ctx: Plugin, site: PromptSite) { if (site.kind === "web") return ctx.t(site.embedded ? "prompt.site.embedded" : "prompt.site.web", { host: site.host }) 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 066d1b67e13..873868851e6 100644 --- a/packages/gui-plugins/src/browser/refs.ts +++ b/packages/gui-plugins/src/browser/refs.ts @@ -4,6 +4,46 @@ 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>) { + if (!refs.size) return + 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) + }) + + 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() + 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/renderer.tsx b/packages/gui-plugins/src/browser/renderer.tsx index a59085728ac..227b594cf2a 100644 --- a/packages/gui-plugins/src/browser/renderer.tsx +++ b/packages/gui-plugins/src/browser/renderer.tsx @@ -158,7 +158,7 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => { bind: "f5", editable: true, enabled: pane.visible() && !!pane.address(), - run: pane.reload, + run: () => pane.reload(), } }) @@ -178,7 +178,24 @@ const setup: Plugin.Setup<typeof definition> = (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+alt+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/gui-plugins/src/browser/snapshot.test.ts b/packages/gui-plugins/src/browser/snapshot.test.ts new file mode 100644 index 00000000000..e9af2ec6f0c --- /dev/null +++ b/packages/gui-plugins/src/browser/snapshot.test.ts @@ -0,0 +1,237 @@ +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 { + 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<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).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.get("e2")).toBe(1) + const found = await accessibilitySnapshot(tree, { ...setup, interactive: true, text: "NEXT", maxLines: 1 }) + 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) +}) + +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(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("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), + 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).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"] 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), + 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("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" } + + 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 new file mode 100644 index 00000000000..55f18319f15 --- /dev/null +++ b/packages/gui-plugins/src/browser/snapshot.ts @@ -0,0 +1,440 @@ +import type { Protocol } from "devtools-protocol" +import { setImmediate } from "node:timers/promises" + +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> + /** Whether a field's value may be printed; `name` is its accessible name. */ + readableValue?: (id: number, name: string) => Promise<boolean> + signal?: AbortSignal +} + +type Area = { id: number; role: string; skipped: number } + +type Item = { area: Area; keep: boolean; meaningful: boolean; shown: number; parent?: Item } + +type Branch = { + node: Protocol.Accessibility.AXNode + level: number + parent: string + parentName: string + scope: string + item: string + ordinal: number + emphasis?: boolean + priority?: number + area?: Area + collection?: Area + entry?: Item +} + +type Line = { + label: string + value?: { text: string; name: string } + id?: number + interactive: boolean + area?: Area + entry?: Item + important: boolean + deep: boolean + reading?: "heading" | "prose" +} + +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 = /^(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 === "alert" || role === "alertdialog" || role === "dialog") return 1 + + if (role === "main") return 2 + + if (role === "form" || role === "search") return 3 + + 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>() + 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 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 headings = new Map<string, string>() + const items: Item[] = [] + const query = options.text?.toLowerCase() + + while (pending.length) { + const branch = pending.pop() + + 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) + + 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 interactive = !!id && role !== "RootWebArea" && (editable || !!props.get("focusable") || controls.test(role)) + + const wrapper = + /^(generic|none|presentation)$/.test(role) && + !name && + !interactive && + !known && + !node.value && + !node.description && + !props.size + + const visible = + !node.ignored && + !wrapper && + role !== "InlineTextBox" && + !(role === "StaticText" && name === branch.parentName && !known) + + const 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 = 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 = + 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" || role === "listitem") && !name + ? itemLabel(children, index) + : name + + const item = + options.interactive && isItem + ? `${role} ${itemName ? JSON.stringify(excerpt(itemName, 60)) : branch.ordinal}` + : branch.item + + 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)) { + 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", + "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(" / ") : "" + const label = `[${role}] ${JSON.stringify(excerpt(name, interactive ? 300 : 160))}${flags.length ? ` ${flags.join(" ")}` : ""}${context ? ` in ${context}` : ""}` + + if ( + !query || + label.toLowerCase().includes(query) || + name.toLowerCase().includes(query) || + (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, + // An empty field prints no value and costs no page call. + value: + 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, + area, + entry, + important, + deep: branch.level > (options.depth ?? Infinity), + reading: interactive || role === "RootWebArea" || !name.trim() ? undefined : emphasis ? "heading" : "prose", + }) + } + } + + 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: branch.level + Number(visible), + parent: visible ? node.nodeId : branch.parent, + parentName: visible ? name : branch.parentName, + scope, + item, + emphasis, + priority, + area, + collection, + entry, + ordinal: i + 1, + }) + } + } + + return printSnapshot(buckets, items, options) +} + +async function printSnapshot(buckets: Line[][], items: Item[], 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; order: number }[] = [] + 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) + } + + 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) + 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 && !spent; i += 32) { + const batch = bucket.slice(i, i + 32) + + const details = + !full && output.length < lines + ? await Promise.all( + batch.map(async (line) => { + if (!line.id || line.deep) return "" + 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)) ?? "") + }), + ) + : [] + + 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 + } + + const key = line.id ? ref(line.id) : undefined + 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 > 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 }) + } + } + } + + 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") + + 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) + .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 + + 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() + } + + const separator = !output.length ? "" : output.length < maxLines ? "\n" : " " + + return { content: content() + separator + hint, truncated: true, refs } +} diff --git a/packages/plugin-browser/README.md b/packages/plugin-browser/README.md index 37f673ae9ae..45fa5028b06 100644 --- a/packages/plugin-browser/README.md +++ b/packages/plugin-browser/README.md @@ -34,7 +34,12 @@ 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 +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 347fcd738cc..867f7cff6fd 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) => [ @@ -95,36 +97,56 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( // 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) { + yield* ctx.permission.hook("evaluate", (event) => { + 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) + 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 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)), + // 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({ action: "browser", resource: "*" }) + if (builtin && (browser || !BrowserMachine.holdsGrant(event.session))) + event.deny({ 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() @@ -414,7 +436,7 @@ export const make = Effect.fn("BrowserConnection.make")(function* ( */ authorize: Effect.fn("BrowserConnection.authorize")(function* (tool: Tool.Context, action: Browser.Action | Extract<Browser.Input, {type: "wait"}>, 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..8012d19c39d 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" @@ -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,14 +571,22 @@ 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 `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. @@ -587,6 +599,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" } @@ -649,7 +666,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 +675,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/rpc.ts b/packages/plugin-browser/src/rpc.ts index ea12ec44b91..0e67fa24d4b 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 @@ -74,9 +92,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 +119,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> {} @@ -187,6 +205,17 @@ 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 = { + 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." })), +} +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 })) @@ -286,8 +315,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), @@ -302,21 +331,23 @@ 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 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", - "Find literal case-insensitive text in a fresh accessibility snapshot. Returns matching lines with refs. 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 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 }, ), operation( "evaluate", @@ -350,8 +381,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", @@ -399,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, @@ -441,7 +473,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 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), @@ -495,6 +527,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(artifact.fileID), id: optional(FileID.annotate({ description: "Alias for fileID." })) }, ), operation( "console", @@ -510,12 +543,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 +558,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/skill.ts b/packages/plugin-browser/src/skill.ts index c99a1804667..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.", @@ -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", "", diff --git a/packages/plugin-browser/src/tools.ts b/packages/plugin-browser/src/tools.ts index bff9a167a22..a702bbad50a 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" @@ -15,8 +15,8 @@ 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. - const wait = Effect.fn("BrowserTools.wait")(function* (tabID: Browser.TabID, plan: WaitPlan, tool: Tool.Context, approved: Effect.Success<ReturnType<typeof connection.authorize>>) { + // 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 .target(tool.sessionID, { type: "tabs.focus", tabID }, approved) @@ -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 } @@ -143,23 +129,14 @@ 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) { + 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 const target = yield* connection.target(tool.sessionID, checked, approved) @@ -194,7 +171,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: 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", @@ -279,7 +256,23 @@ function modelResult(output: Schema.Schema.Type<Browser.Operation["output"]>, fi }) } -export function normalizeAction(action: Exclude<Browser.Input, { readonly type: "wait" }>): Browser.Action { +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) @@ -306,17 +299,20 @@ export function normalizeAction(action: Exclude<Browser.Input, { readonly type: message: `${JSON.stringify(value)} is not a browser URL. Use an http:// or https:// address, or about:blank, without a user name or password. The connected server must be able to reach it; localhost is that server.`, }) // Percent-encoding can grow the URL past the bound the desktop decodes from `command`. - return Schema.decodeUnknownOption(Browser.Action)({ ...action, url: url.href }).pipe( - Option.getOrThrowWith( - () => - 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<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"] } & ( @@ -463,36 +459,20 @@ 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) => `(() => { const found = [...document.querySelectorAll(${JSON.stringify(selector)})]; return { count: found.length, visible: found.filter((element) => element.checkVisibility()).length } })()` -function evaluateAction(input: Extract<Browser.Input, { readonly type: "evaluate" }>): Browser.Action { +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/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() 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 106e6499824..b7919596b55 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,25 @@ 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") + 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", () => { expect(String(BrowserSkill.info.path)).toBe("skill://browser/SKILL.md") }) @@ -267,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) }) }) diff --git a/packages/plugin/src/effect/permission.ts b/packages/plugin/src/effect/permission.ts index 4b7bb71948a..fc8db4ac301 100644 --- a/packages/plugin/src/effect/permission.ts +++ b/packages/plugin/src/effect/permission.ts @@ -29,8 +29,32 @@ export interface PermissionEvaluation { } } +/** + * 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 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. + */ +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> + /** 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 { readonly evaluate: PermissionEvaluation + readonly "experimental.rules": PermissionRules } export type PermissionDomain = Pick<PermissionApi<unknown>, "list" | "get" | "reply"> & { diff --git a/packages/plugin/src/promise/permission.ts b/packages/plugin/src/promise/permission.ts index a5099b243b0..633b0c24d79 100644 --- a/packages/plugin/src/promise/permission.ts +++ b/packages/plugin/src/promise/permission.ts @@ -27,8 +27,32 @@ export interface PermissionEvaluation { } } +/** + * 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 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. + */ +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> + /** 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 { readonly evaluate: PermissionEvaluation + readonly "experimental.rules": PermissionRules } export type PermissionDomain = Pick<PermissionApi, "list" | "get" | "reply"> & { 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<Rule>, ignoreCase: boolean) { + const rule = rules.findLast((rule) => Wildcard.match(action, rule.action, ignoreCase)) + return rule?.resource === "*" && rule.effect === "deny" +} 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) +}