Merge remote-tracking branch 'origin/persisted-browser' into browser-site-import

# Conflicts:
#	packages/gui-plugins/src/browser/chromium.ts
This commit is contained in:
Luke Parker 2026-11-17 11:06:10 +10:00
commit bdbc048fe6
143 changed files with 3433 additions and 547 deletions

View file

@ -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")
},
)

View file

@ -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())

View file

@ -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)

View file

@ -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<void>
readonly ask: (input: AssertInput) => Effect.Effect<AskResult, SessionErrors.NotFoundError>
@ -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<Request, "action" | "resources">, rules: Permission.Ruleset) {

View file

@ -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,

View file

@ -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,

View file

@ -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<RegistrationError>()("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<Data, Editor>({
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()

View file

@ -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

View file

@ -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<string, string> = {}) =>
Effect.gen(function* () {
const dir = yield* tmpdirScoped()
for (const [name, text] of Object.entries(files))
yield* Effect.promise(() => Bun.write(path.join(dir.path, name), text))
yield* Effect.promise(() => Bun.write(path.join(dir.path, "opencode.json"), JSON.stringify(config)))
const ref = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
const locations = yield* LocationServiceMap.Service
@ -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"), "<p>page</p>"))
// 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<ReturnType<typeof rule>>
readonly agent?: ReadonlyArray<ReturnType<typeof rule>>
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<ReturnType<typeof setup>>,
operation: string,
agent: string,
sessionID: Session.ID,
) => settle(browser, sessionID, browser.run(operation, {}, agent, sessionID))
// What `call` comes to: it reaches its end or the desktop, prompts, or is refused as denied or disconnected. A call
// that prompts is interrupted, which withdraws the prompt. Any other failure is returned as its message, so the
// comparison shows it.
const settle = Effect.fnUntraced(function* (
browser: Effect.Success<ReturnType<typeof setup>>,
sessionID: Session.ID,
call: Effect.Effect<unknown, { readonly message: string; readonly error?: unknown }>,
) {
const permissions = Context.get(browser.context, Permission.Service)
const before = browser.commands.count
const reached = () => browser.commands.count > before
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<Outcome | string>("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<ReturnType<typeof setup>>, agent: string, sessionID = browser.session.id) =>
Effect.gen(function* () {
const read = (yield* Context.get(browser.context, Tool.Service).list()).find((tool) => tool.name === "read")
if (!read) return yield* Effect.die(new Error("read is not registered"))
return yield* settle(
browser,
sessionID,
read.execute(
{ path: "skill://browser/SKILL.md" },
{
sessionID,
agent: Agent.ID.make(agent),
messageID: SessionMessage.ID.create(),
id: Tool.CallID.make(`call_${crypto.randomUUID()}`),
progress: () => Effect.void,
},
),
)
})
const reads = rule("*", "allow", "read")
it.live("the attachment's grant does not override a configured skill deny or ask for the browser skill", () =>
Effect.gen(function* () {
const denied = yield* setup({ permissions: [reads, rule("*", "deny", "skill")] })
const listed = yield* denied.listing()
expect(listed.catalog).toContain("browser.tabs.list")
expect(listed.skill).toBe(false)
expect(yield* readSkill(denied, "build")).toBe("deny")
const asked = yield* setup({ permissions: [reads, rule("browser", "ask", "skill")] })
expect((yield* asked.listing()).skill).toBe(true)
expect(yield* readSkill(asked, "build")).toBe("ask")
const allowed = yield* setup({
permissions: [reads],
agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } },
})
expect(yield* readSkill(allowed, "build")).toBe("allow")
// The skill tool refuses an agent denied the browser, as its listing does.
expect(yield* readSkill(allowed, "reviewer")).toBe("deny")
}),
)
it.live("a person's own skill named browser follows their rules, not the built-in's", () =>
Effect.gen(function* () {
const browser = yield* setup(
{ permissions: [reads, rule("*", "deny"), rule("browser", "allow", "skill")] },
{
".opencode/skills/browser/SKILL.md":
"---\nname: browser\ndescription: Drive Playwright against the staging site.\n---\n# Playwright\n",
},
)
const sessions = yield* Session.Service
const detached = yield* sessions.create({ location: browser.ref })
for (const sessionID of [browser.session.id, detached.id]) {
const listed = yield* browser.listing(sessionID)
expect(listed.catalog).toEqual([])
expect(listed.skill).toBe(true)
}
}),
)
it.live("a scheduled check runs the browser for an allowed agent and refuses one denied the browser", () =>
Effect.gen(function* () {
const browser = yield* setup({ agents: { reviewer: { mode: "primary", permissions: [rule("*", "deny")] } } })
const sessions = yield* Session.Service
const check = {
mode: "if" as const,
condition: { type: "code" as const, code: "return (await tools.browser.tabs.list({})).tabs.length === 0" },
}
const run = () =>
sessions.get(browser.session.id).pipe(
Effect.flatMap((session) =>
ScheduleCheck.evaluate(session, check, null, { messageID: SessionMessage.ID.create(), now: 0, checks: 0 }),
),
Effect.provideContext(browser.context),
)
expect(yield* run()).toMatchObject({ ok: true, wake: true })
expect(browser.commands.count).toBe(1)
yield* sessions.switchAgent({ sessionID: browser.session.id, agent: Agent.ID.make("reviewer") })
expect(yield* run()).toMatchObject({ ok: false, error: "Permission denied: browser" })
expect(browser.commands.count).toBe(1)
}),
)

View file

@ -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"), "<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"), "<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]")
}),
)

View file

@ -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<typeof event.deny>[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')
}),
)
})

View file

@ -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

View file

@ -125,15 +125,15 @@ describe("desktop RPC transport", () => {
const handoff = await runtime.runPromise(IpcPortHandoff)
const win = sender(1)
// A window that has not asked for its snapshot has no document to hold events for.
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early" }))).toBe(false)
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "early", accelerator: false }))).toBe(false)
handoff.prepare(win)
// On dev these were dropped: the window had no event queue until its port bound.
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a" }))).toBe(true)
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b" }))).toBe(true)
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "a", accelerator: false }))).toBe(true)
expect(emitIpcEvent(win, new MenuCommandTriggered({ id: "b", accelerator: false }))).toBe(true)
const channel = new MessageChannel()
handoff.bind(win, serverPort(channel.port1))
emitIpcEvent(win, new MenuCommandTriggered({ id: "c" }))
emitIpcEvent(win, new MenuCommandTriggered({ id: "c", accelerator: false }))
expect(await chunks(channel.port2, 0, "DesktopEvents", 3)).toEqual(["a", "b", "c"].map(menuCommand))
@ -156,7 +156,7 @@ describe("desktop RPC transport", () => {
// The new document's snapshot: the old one stops receiving events but still answers its RPCs.
handoff.prepare(win)
expect((await firstEvents).chunks).toEqual([])
emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload" }))
emitIpcEvent(win, new MenuCommandTriggered({ id: "during reload", accelerator: false }))
Effect.runSync(Deferred.succeed(flushGate, undefined))
expect((await flush).exit).toEqual(success("flushed"))
@ -187,7 +187,7 @@ const eventsLive = RpcServer.layer(EventRpcs.merge(FlushRpcs)).pipe(
)
function menuCommand(id: string) {
return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id }))
return Schema.encodeSync(MenuCommandTriggered)(new MenuCommandTriggered({ id, accelerator: false }))
}
class TestEvent extends Schema.TaggedClass<TestEvent>()("TestEvent", { value: Schema.String }) {}

View file

@ -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)
}
}

View file

@ -39,7 +39,7 @@ export type ElectronAPI = {
getWindowID(): string
getWindowBootstrap(): WindowBootstrap
themeReady(): Promise<void>
onMenuCommand(cb: (id: string) => void): () => void
onMenuCommand(cb: (id: string, accelerator: boolean) => void): () => void
onDeepLink(cb: (delivery: { attempt: number; urls: string[] }) => void): () => void
openDirectoryPicker(opts?: DirectoryPickerOptions): Promise<string | string[] | null>
openFilePicker(opts?: FilePickerOptions): Promise<PickedFiles | null>

View file

@ -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),

View file

@ -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. */

View file

@ -10,6 +10,8 @@ export class DeepLinksOpened extends Schema.TaggedClass<DeepLinksOpened>()("Deep
export class MenuCommandTriggered extends Schema.TaggedClass<MenuCommandTriggered>()("MenuCommandTriggered", {
id: Schema.String,
/** A key equivalent chose the item, rather than a click on the menu. */
accelerator: Schema.Boolean,
}) {}
export class WindowFullscreenChanged extends Schema.TaggedClass<WindowFullscreenChanged>()("WindowFullscreenChanged", {

View file

@ -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<void>()
const first = render.hold(() => frame.promise)
const second = render.hold(() => { throw new Error("duplicate wake") })
expect(second.painted).toBe(first.painted)
frame.resolve()
await first.painted
first[Symbol.dispose]()
second[Symbol.dispose]()
})
test("idle past the deadline with a dialog open, the dialog command un-throttles without waiting for a frame", () => {
const timers: (() => void)[] = []
const throttles: boolean[] = []
const render = agentRendering(new AbortController().signal, value => throttles.push(value), (_, run) => {
timers.push(run)
return () => {}
})
render.hold()[Symbol.dispose]()
timers.forEach(run => run())
expect(throttles).toEqual([false, true])
// An open alert pauses the page's animation frames, so no command waits for one, including the one that answers it.
for (const method of ["dialog", "snapshot", "click", "navigate"] as const) expect(needsWakeFrame(method, true, true)).toBe(false)
const answer = render.hold(needsWakeFrame("dialog", true, true) ? () => new Promise(() => {}) : undefined)
expect(answer.painted).toBeUndefined()
expect(throttles).toEqual([false, true, false])
})
test("a renderer that never paints neither blocks navigation nor fails the command that waited for it", async () => {
const render = agentRendering(new AbortController().signal, () => {}, () => () => {})
const frame = Promise.withResolvers<void>()
const 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()
})

View file

@ -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<void> | undefined
let cancel: (() => void) | undefined
signal.addEventListener("abort", () => cancel?.(), { once: true })
return {
hold(onWake?: () => Promise<void>) {
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)
}

View file

@ -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<void>(() => {}), 6000)
c.advance(2500)
expect(c.events).toEqual(["begin"])
c.advance(3500)
await expect(shot).rejects.toThrow("6 seconds")
expect(c.events).toEqual(["begin", "end"])
})
test("overlapping hidden and stalled visible captures share a subscription until the last release", async () => {
const c = coordinator()
const one = Promise.withResolvers<void>()

View file

@ -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 <T>(presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise<T>) => {
return async <T>(presented: boolean, signal: AbortSignal, redraw: (stop: AbortSignal) => Promise<T>, deadline = CAPTURE_DEADLINE_MS) => {
const cancel = () => new Error("Browser capture was cancelled.")
if (signal.aborted) throw cancel()
@ -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<Undrawable, string> = {
const causes: Record<Exclude<Undrawable, "stalled">, string> = {
minimized: "The OpenCode window is minimized, so the system does not draw this tab.",
hidden: "OpenCode is hidden, so the system does not draw this tab.",
stalled: `No fresh frame of this tab arrived within ${CAPTURE_DEADLINE_MS / 1000} seconds. No cached screenshot was returned.`,
}
export function undrawableMessage(reason: Undrawable) {
if (reason === "stalled") return `${causes.stalled} Check that the page has finished navigating and is responsive before retrying.`
export function undrawableMessage(reason: Undrawable, deadline = CAPTURE_DEADLINE_MS) {
if (reason === "stalled") return `No fresh frame of this tab arrived within ${deadline / 1000} seconds. No cached screenshot was returned. Check that the page has finished navigating and is responsive before retrying.`
return `${causes[reason]} A screenshot needs the window restored. Ask the user to restore the OpenCode window, then take the screenshot again; do not repeat it before then. Clicks, typing and other browser actions still work.`
}

View file

@ -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<string, Element>()
const refs = documentRefs()
// Elements the user picked. Their refs outlive later snapshots, so a comment keeps pointing at
// the element until the document changes.
const picked = new Map<string, Element>()
@ -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<Browser.Result> {
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<ReturnType<typeof frames>>) {
if (scroll) {
await cdp.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: element.backendID }, element.sessionID)
// Input is routed by the last rendered frame, so let one render at the new scroll position.
@ -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<Browser.Action, { type: "screenshot" }>, 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<Browser.Action, { type: "screenshot" }>,
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<Browser.Action, { type: "snapshot" | "find" }>) {
async function snapshot(action: Extract<Browser.Action, { type: "snapshot" | "find" }>, 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<string, Element>) => 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<void> => {
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. */

View file

@ -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)

View file

@ -14,6 +14,7 @@ export type ShortcutEvent = Extract<PaneEvent, { type: "shortcut" }>
export type Zoom = "in" | "out" | "reset"
export type Registration = {
readonly binding: string
/** Creates a restored tab's page, which then reports its embed. */
load(tabID: Browser.TabID): void
command(command: Browser.Action): Promise<void>
@ -25,6 +26,7 @@ export type Registration = {
answer(tabID: Browser.TabID, id: number, answer: PromptAnswer): Promise<void>
site(tabID: Browser.TabID): Promise<{ cookies: number }>
clearSite(tabID: Browser.TabID): Promise<void>
clearCache(tabID: Browser.TabID, address: string): Promise<void>
reveal(tabID: Browser.TabID): Promise<void>
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

View file

@ -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),

View file

@ -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 {

View file

@ -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>" ? "hidden" : printed === JSON.stringify(value) ? "shown" : printed).toBe(expected)
})

View file

@ -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(),
),
)
}

View file

@ -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": "በስርዓቱ አሳሽ ውስጥ ክፈት",

View file

@ -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": "فتح في متصفح النظام",

View file

@ -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ç",

View file

@ -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": "Отваряне в системния браузър",

View file

@ -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": "সিস্টেম ব্রাউজারে খুলুন",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -48,8 +48,6 @@ export default {
"site.permissions": "ހުއްދަތައް ބްލޮކްކޮށްފައި",
"site.permissions.description":
"މި ބްރައުޒަރުގައި ކެމެރާ، މައިކްރޮފޯން، ލޮކޭޝަން އަދި ނޮޓިފިކޭޝަންތައް މަސައްކަތެއް ނުކުރެއެވެ.",
"site.agent": "އޭޖެންޓަށް މި ޕޭޖް ބޭނުންކުރެވޭނެ",
"site.agent.description": "އެއަށް ޕޭޖް ކިޔުމާއި، ސްކްރިޕްޓް ހިންގުމާއި، ފޯމު ފުރުން ކުރެވޭނެއެވެ.",
"page.add": "ޕޭޖް ސެޝަނަށް އިތުރުކުރާ",
"page.placeholder": "މި ޕޭޖާ ބެހޭ ކޮންޓެކްސްޓް އިތުރުކުރާ",
"external.open": "ސިސްޓަމް ބްރައުޒަރުގައި ހުޅުވާ",

View file

@ -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": "རིམ་ལུགས་བརའུ་ཟར་ནང་ཁ་ཕྱེ།",

View file

@ -49,8 +49,6 @@ export default {
"site.permissions": "Τα δικαιώματα είναι αποκλεισμένα",
"site.permissions.description":
"Η κάμερα, το μικρόφωνο, η τοποθεσία και οι ειδοποιήσεις δεν λειτουργούν σε αυτό το πρόγραμμα περιήγησης.",
"site.agent": "Ο πράκτορας μπορεί να χρησιμοποιήσει αυτήν τη σελίδα",
"site.agent.description": "Μπορεί να διαβάσει τη σελίδα, να εκτελέσει σενάρια και να συμπληρώσει φόρμες.",
"page.add": "Προσθήκη σελίδας στη συνεδρία",
"page.placeholder": "Προσθέστε περιβάλλον για αυτήν τη σελίδα",
"external.open": "Άνοιγμα στο πρόγραμμα περιήγησης του συστήματος",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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": "باز کردن در مرورگر سیستم",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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": "פתח בדפדפן המערכת",

View file

@ -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": "सिस्टम ब्राउज़र में खोलें",

View file

@ -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",

View file

@ -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",

View file

@ -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": "Բացել համակարգի դիտարկչում",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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": "システムのブラウザーで開く",

View file

@ -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": "სისტემის ბრაუზერში გახსნა",

View file

@ -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": "បើកក្នុងកម្មវិធីរុករកប្រព័ន្ធ",

View file

@ -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": "시스템 브라우저에서 열기",

View file

@ -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": "ເປີດໃນເບຣາວເຊີຂອງລະບົບ",

View file

@ -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",

View file

@ -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ā",

View file

@ -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": "Отвори во системскиот прелистувач",

View file

@ -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": "Системийн хөтөч дээр нээх",

View file

@ -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",

View file

@ -48,9 +48,6 @@ export default {
"site.permissions": "ခွင့်ပြုချက်များကို ပိတ်ထားသည်",
"site.permissions.description":
"ဤဘရောက်ဇာတွင် ကင်မရာ၊ မိုက်ခရိုဖုန်း၊ တည်နေရာနှင့် အကြောင်းကြားချက်များ အလုပ်မလုပ်ပါ။",
"site.agent": "အေးဂျင့်သည် ဤစာမျက်နှာကို အသုံးပြုနိုင်သည်",
"site.agent.description":
"၎င်းသည် စာမျက်နှာကို ဖတ်ခြင်း၊ script များ လုပ်ဆောင်ခြင်းနှင့် ဖောင်များ ဖြည့်ခြင်းတို့ ပြုလုပ်နိုင်သည်။",
"page.add": "စာမျက်နှာကို စက်ရှင်သို့ ထည့်ရန်",
"page.placeholder": "ဤစာမျက်နှာအကြောင်း ဆက်စပ်အချက်အလက် ထည့်ပါ",
"external.open": "စနစ်ဘရောက်ဇာတွင် ဖွင့်ရန်",

View file

@ -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": "प्रणाली ब्राउजरमा खोल्नुहोस्",

View file

@ -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",

View file

@ -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",

View file

@ -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": "سسٹم براؤزر وچ کھولو",

View file

@ -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",

View file

@ -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",

View file

@ -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": "Открыть в системном браузере",

View file

@ -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": "පද්ධති බ්‍රවුසරයේ විවෘත කරන්න",

View file

@ -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",

View file

@ -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",

View file

@ -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",

View file

@ -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": "Отвори у системском прегледачу",

View file

@ -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",

View file

@ -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": "Кушодан дар браузери система",

View file

@ -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": "เปิดในเบราว์เซอร์ของระบบ",

View file

@ -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ň",

View file

@ -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ç",

View file

@ -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": "Відкрити в системному браузері",

View file

@ -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": "سسٹم براؤزر میں کھولیں",

View file

@ -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",

View file

@ -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",

View file

@ -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": "在系统浏览器中打开",

View file

@ -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": "在系統瀏覽器中開啟",

View file

@ -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"))}) },

View file

@ -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<typeof pageReload>, 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],
]

View file

@ -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())) ||

View file

@ -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),

View file

@ -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<typeof definition>) {
const page = (sessionKey: string, event: PageEvent) => {
setState("pages", sessionKey, (pages) => ({
...pages,
[event.tabID]: event.icon ? { icon: event.icon, zoom: event.zoom } : { zoom: event.zoom },
[event.tabID]: { icon: event.icon, zoom: event.zoom, retryOnly: event.retryOnly },
}))
const url = sessionTab(machine(), sessionKey, event.tabID)?.url
const visits = url && event.icon ? withIcon(history.value.visits, url, event.icon) : undefined
@ -682,8 +682,10 @@ export function createModel(ctx: SetupContext<typeof definition>) {
},
/** The page's cookie count; undefined while the pane cannot answer. */
site: (session: Session, tabID: Browser.TabID) => registration(session)?.site(tabID),
binding: (session: Session) => registration(session)?.binding,
/** Deletes the page's cookies and stored data, and reloads it. */
clearSite: (session: Session, tabID: Browser.TabID) => registration(session)?.clearSite(tabID),
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) => {

View file

@ -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<void>
navigate: (action: "back" | "forward" | "reload" | "hardReload") => Promise<void>
open: (url: string) => Promise<void>
}
@ -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()

View file

@ -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<void>()
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<void>()
const stopped: (string | undefined)[] = []
const navigation = navigationTurn(() => gate.promise, () => {}, () => {}, address => stopped.push(address))
const visit = navigation.begin(new AbortController().signal, keep)("https://saved.test", () => { throw Error("load was issued") })
navigation.interrupt(method, restoring)
gate.resolve()
await visit
expect(stopped).toEqual([expected])
}
})
test("a gated history traversal settles the spinner when Chromium has no load to stop", async () => {
const gate = Promise.withResolvers<void>()
const events: string[] = []

View file

@ -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<typeof Promise.withResolvers<boolean>> | undefined
return {
start(event: { isMainFrame: boolean; isSameDocument: boolean }) {
if (event.isMainFrame && !event.isSameDocument && ++starts === 2) replacement = Promise.withResolvers<boolean>()
},
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<void> | 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()

Some files were not shown because too many files have changed in this diff Show more