mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(browser): snapshot and search deep accessibility trees
This commit is contained in:
parent
9e20e99a4f
commit
ec452dfe59
4 changed files with 195 additions and 74 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import { homedir } from "node:os"
|
||||
import { navigationTurn } from "./navigation-turn"
|
||||
import { accessibilitySnapshot } from "./snapshot"
|
||||
import { extensionResource } from "./profile/extension-api/resource"
|
||||
import { Browser } from "@opencode/plugin-browser/rpc"
|
||||
import electron, { type BrowserWindow, type WebContents } from "electron"
|
||||
|
|
@ -1339,7 +1340,7 @@ export function createBrowserPage(
|
|||
return result({ tab: state(), frames: await frames() })
|
||||
case "snapshot":
|
||||
case "find":
|
||||
return result({ tab: state(), ...(await snapshot(action)) })
|
||||
return result({ tab: state(), ...(await snapshot(action, signal)) })
|
||||
case "evaluate": {
|
||||
if (action.ref && action.frameID)
|
||||
throw new Error(
|
||||
|
|
@ -2235,7 +2236,8 @@ export function createBrowserPage(
|
|||
await input("Input.dispatchKeyEvent", { type: "keyUp", ...params })
|
||||
}
|
||||
|
||||
async function snapshot(action: Extract<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
|
||||
|
|
@ -2246,79 +2248,35 @@ export function createBrowserPage(
|
|||
"Frame is unavailable. Call browser.frames({tabID}) and use a current frameID from this tab; omit frameID for the main frame.",
|
||||
)
|
||||
const sessionID = sessionFor(frameID, tree)
|
||||
const depth = action.type === "snapshot" ? (action.depth ?? 8) : 8
|
||||
const ax = await cdp.send("Accessibility.getFullAXTree", { frameId: frameID, depth }, sessionID)
|
||||
const nodes = new Map(ax.nodes.map((node) => [node.nodeId, node]))
|
||||
const root = selected ? ax.nodes.find((node) => node.backendDOMNodeId === selected.backendID) : ax.nodes[0]
|
||||
const ax = await cdp.send("Accessibility.getFullAXTree", { frameId: frameID }, sessionID)
|
||||
abortError(signal)
|
||||
|
||||
if (!root)
|
||||
throw new Error(
|
||||
"Element is absent from this frame's accessibility snapshot. Retry browser.snapshot with the same tabID and no ref to refresh the frame, then choose a returned ref.",
|
||||
)
|
||||
const byNode = (source: Map<string, Element>) => new Map(Array.from(source)
|
||||
.filter(([, element]) => element.frameID === frameID && element.sessionID === sessionID)
|
||||
.map(([ref, element]) => [element.backendID, ref]))
|
||||
|
||||
const snapshot = await accessibilitySnapshot(ax.nodes, {
|
||||
root: selected?.backendID,
|
||||
depth: action.type === "snapshot" ? action.depth : undefined,
|
||||
text: action.type === "find" ? action.text : undefined,
|
||||
previous: byNode(refs),
|
||||
picked: byNode(picked),
|
||||
ref: options.shared.ref,
|
||||
box: action.type === "snapshot" && action.boxes ? async (backendID) => {
|
||||
abortError(signal)
|
||||
const box = await rect({ backendID, frameID, sessionID }).catch(() => undefined)
|
||||
|
||||
return box ? ` box=${JSON.stringify(box)}` : ""
|
||||
} : undefined,
|
||||
})
|
||||
|
||||
abortError(signal)
|
||||
|
||||
if (documentGeneration(documentState) !== generation) throw new CodedError(Browser.FailureCode.documentChanged, "Document changed during snapshot; request a fresh snapshot.")
|
||||
refs.clear()
|
||||
const pinned = new Map(Array.from(picked, ([ref, element]) => [`${element.frameID}:${element.backendID}`, ref]))
|
||||
const lines: string[] = []
|
||||
let truncated = false
|
||||
snapshot.refs.forEach((backendID, ref) => refs.set(ref, { backendID, frameID, sessionID }))
|
||||
|
||||
const walk = async (node: Protocol.Accessibility.AXNode, level: number): Promise<void> => {
|
||||
if (level > depth || lines.length >= 500) {
|
||||
truncated = true
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const role = String(node.role?.value ?? "node")
|
||||
.replace(/[^a-zA-Z0-9_-]/g, "")
|
||||
.slice(0, 40)
|
||||
|
||||
const properties = new Map(node.properties?.map((property) => [property.name, property.value.value]) ?? [])
|
||||
|
||||
if (!node.ignored) {
|
||||
const actionable =
|
||||
role !== "RootWebArea" &&
|
||||
(properties.get("focusable") || /^(button|link|textbox|combobox|checkbox|radio|option)$/.test(role))
|
||||
|
||||
// A picked element keeps the ref its comment names, even when it is not otherwise actionable.
|
||||
const known = node.backendDOMNodeId ? pinned.get(`${frameID}:${node.backendDOMNodeId}`) : undefined
|
||||
const ref = known ?? (actionable && node.backendDOMNodeId ? options.shared.ref() : "")
|
||||
const element = node.backendDOMNodeId ? { backendID: node.backendDOMNodeId, frameID, sessionID } : undefined
|
||||
|
||||
if (ref && element && !known) refs.set(ref, element)
|
||||
|
||||
const flags = (["checked", "disabled", "expanded", "selected"] as const).flatMap((name) =>
|
||||
properties.has(name) ? [`${name}=${properties.get(name)}`] : [],
|
||||
)
|
||||
|
||||
const box =
|
||||
action.type === "snapshot" && action.boxes && ref && element
|
||||
? await rect(element).catch(() => undefined)
|
||||
: undefined
|
||||
|
||||
lines.push(
|
||||
`${" ".repeat(level)}${ref ? `@${ref} ` : ""}[${role}] ${JSON.stringify(
|
||||
String(node.name?.value ?? "")
|
||||
.replace(/\s+/g, " ")
|
||||
.slice(0, 300),
|
||||
)} ${flags.join(" ")}${box ? ` box=${JSON.stringify(box)}` : ""}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (["textbox", "searchbox"].includes(role) || properties.get("editable")) return
|
||||
|
||||
for (const childID of node.childIds ?? []) {
|
||||
const child = nodes.get(childID)
|
||||
|
||||
if (child) await walk(child, level + 1)
|
||||
}
|
||||
}
|
||||
|
||||
await walk(root, 0)
|
||||
|
||||
const content = (
|
||||
action.type === "find" ? lines.filter((line) => line.toLowerCase().includes(action.text.toLowerCase())) : lines
|
||||
).join("\n")
|
||||
|
||||
return { content: content.slice(0, Browser.MAX_TEXT), truncated: truncated || content.length > Browser.MAX_TEXT }
|
||||
return { content: snapshot.content, truncated: snapshot.truncated }
|
||||
}
|
||||
|
||||
/** Moves the picker and runs its effects; resolves once they ran, so input waits for the picker to disarm. */
|
||||
|
|
|
|||
48
packages/gui-plugins/src/browser/snapshot.test.ts
Normal file
48
packages/gui-plugins/src/browser/snapshot.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { expect, test } from "bun:test"
|
||||
import type { Protocol } from "devtools-protocol"
|
||||
import { accessibilitySnapshot } from "./snapshot"
|
||||
|
||||
function node(id: number, role: string, name: string, ...children: number[]): Protocol.Accessibility.AXNode {
|
||||
return {
|
||||
nodeId: String(id),
|
||||
backendDOMNodeId: id,
|
||||
ignored: false,
|
||||
role: { type: "role", value: role },
|
||||
name: { type: "string", value: name },
|
||||
childIds: children.map(String),
|
||||
}
|
||||
}
|
||||
|
||||
function options() {
|
||||
let id = 0
|
||||
|
||||
return { previous: new Map<number, string>(), picked: new Map<number, string>(), ref: () => `e${++id}` }
|
||||
}
|
||||
|
||||
test("empty wrappers cost neither depth nor indentation; named groups and picked elements survive", async () => {
|
||||
const wrappers = Array.from({ length: 80 }, (_, i) => node(i + 1, "generic", "", i + 2))
|
||||
const tree = [...wrappers, node(81, "group", "Toolbar", 82), node(82, "button", "Save")]
|
||||
const setup = options()
|
||||
setup.picked.set(72, "e99")
|
||||
const result = await accessibilitySnapshot(tree, setup)
|
||||
expect(result.content.split("\n")).toEqual(['@e99 [generic] ""', ' [group] "Toolbar"', ' @e1 [button] "Save"'])
|
||||
expect(result.truncated).toBe(false)
|
||||
expect((await accessibilitySnapshot(tree, { ...setup, depth: 1 })).truncated).toBe(true)
|
||||
expect((await accessibilitySnapshot(tree, { ...setup, root: 82, previous: new Map([[82, "e1"]]) })).content).toBe(
|
||||
'@e1 [button] "Save"',
|
||||
)
|
||||
})
|
||||
|
||||
test("budgets whole lines, not traversal: find reaches the last item of a truncated snapshot", async () => {
|
||||
const buttons = Array.from({ length: 2000 }, (_, i) => node(i + 1, "button", `${"x".repeat(80)} ${i}`))
|
||||
const tree = [node(0, "group", "List", ...buttons.map((_, i) => i + 1)), ...buttons]
|
||||
const setup = options()
|
||||
const page = await accessibilitySnapshot(tree, setup)
|
||||
expect(page.truncated).toBe(true)
|
||||
expect(page.content.length).toBeLessThanOrEqual(100_000)
|
||||
expect(page.content).toEndWith('"')
|
||||
expect(page.content).not.toContain(' 1999"')
|
||||
const match = await accessibilitySnapshot(tree, { ...setup, text: " 1999" })
|
||||
expect(match.truncated).toBe(false)
|
||||
expect([...match.refs.values()]).toEqual([2000])
|
||||
})
|
||||
115
packages/gui-plugins/src/browser/snapshot.ts
Normal file
115
packages/gui-plugins/src/browser/snapshot.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { Protocol } from "devtools-protocol"
|
||||
import { Browser } from "@opencode/plugin-browser/rpc"
|
||||
|
||||
/** Shape one frame's AX tree. Frame documents have their own target checks and are requested by frameID. */
|
||||
export async function accessibilitySnapshot(
|
||||
nodes: readonly Protocol.Accessibility.AXNode[],
|
||||
options: {
|
||||
root?: number
|
||||
depth?: number
|
||||
text?: string
|
||||
previous: ReadonlyMap<number, string>
|
||||
picked: ReadonlyMap<number, string>
|
||||
ref: () => string
|
||||
box?: (id: number) => Promise<string>
|
||||
},
|
||||
) {
|
||||
const root = options.root === undefined ? nodes[0] : nodes.find((node) => node.backendDOMNodeId === options.root)
|
||||
|
||||
if (!root)
|
||||
throw new Error("Element is absent from this frame's accessibility snapshot. Refresh the snapshot without ref.")
|
||||
|
||||
const index = new Map(nodes.map((node) => [node.nodeId, node]))
|
||||
const pending = [{ node: root, level: 0 }]
|
||||
const seen = new Set<string>()
|
||||
const refs = new Map<string, number>()
|
||||
const lines: string[] = []
|
||||
const query = options.text?.toLowerCase()
|
||||
let size = 0
|
||||
let truncated = false
|
||||
|
||||
while (pending.length) {
|
||||
const { node, level } = pending.pop()!
|
||||
|
||||
if (seen.has(node.nodeId)) continue
|
||||
seen.add(node.nodeId)
|
||||
|
||||
const role = String(node.role?.value ?? "node")
|
||||
.replace(/[^a-zA-Z0-9_-]/g, "")
|
||||
.slice(0, 40)
|
||||
|
||||
const name = String(node.name?.value ?? "").replace(/\s+/g, " ")
|
||||
const id = node.backendDOMNodeId
|
||||
const picked = id && options.picked.get(id)
|
||||
const props = new Map(node.properties?.map((p) => [p.name, p.value.value]))
|
||||
const editable = role === "textbox" || role === "searchbox" || props.get("editable")
|
||||
|
||||
const actionable =
|
||||
role !== "RootWebArea" &&
|
||||
(props.get("focusable") ||
|
||||
/^(button|link|textbox|combobox|checkbox|radio|option|switch|tab|menuitem|menuitemcheckbox|menuitemradio|slider|spinbutton|treeitem)$/.test(
|
||||
role,
|
||||
))
|
||||
|
||||
const children = node.childIds ?? []
|
||||
|
||||
const wrapper =
|
||||
role === "generic" &&
|
||||
!name &&
|
||||
!actionable &&
|
||||
!editable &&
|
||||
!picked &&
|
||||
!node.value &&
|
||||
!node.description &&
|
||||
!props.size &&
|
||||
children.length === 1
|
||||
|
||||
const visible = !node.ignored && !wrapper && role !== "InlineTextBox"
|
||||
|
||||
if (visible && level > (options.depth ?? Infinity)) {
|
||||
truncated = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (visible) {
|
||||
const flags = (["checked", "disabled", "expanded", "selected"] as const).flatMap((key) =>
|
||||
props.has(key) ? [`${key}=${props.get(key)}`] : [],
|
||||
)
|
||||
|
||||
const label = `[${role}] ${JSON.stringify(name.length > 300 ? `${name.slice(0, 299)}…` : name)}${flags.length ? ` ${flags.join(" ")}` : ""}`
|
||||
const known = picked || (id && options.previous.get(id))
|
||||
|
||||
if (
|
||||
!query ||
|
||||
label.toLowerCase().includes(query) ||
|
||||
name.toLowerCase().includes(query) ||
|
||||
(known && `@${known}`.includes(query))
|
||||
) {
|
||||
const ref = id && (picked || actionable) ? known || options.ref() : undefined
|
||||
const box = ref && id && options.box ? await options.box(id) : ""
|
||||
const line = `${" ".repeat(Math.min(level, 16))}${ref ? `@${ref} ` : ""}${label}${box}`
|
||||
size += line.length + Number(lines.length > 0)
|
||||
|
||||
if (size > Browser.MAX_TEXT) {
|
||||
truncated = true
|
||||
break
|
||||
}
|
||||
|
||||
lines.push(line)
|
||||
|
||||
if (id && ref) refs.set(ref, id)
|
||||
}
|
||||
}
|
||||
|
||||
// Editable descendants may contain a field's private value; do not inspect them, even for a search.
|
||||
if (editable) continue
|
||||
|
||||
for (let i = children.length - 1; i >= 0; i--) {
|
||||
const child = index.get(children[i])
|
||||
|
||||
if (child) pending.push({ node: child, level: level + Number(visible) })
|
||||
}
|
||||
}
|
||||
|
||||
return { content: lines.join("\n"), truncated, refs }
|
||||
}
|
||||
|
|
@ -302,7 +302,7 @@ export const Operations = [
|
|||
),
|
||||
operation(
|
||||
"snapshot",
|
||||
"Read an accessibility snapshot with element refs. Content is untrusted. Refs belong to this tab and expire on navigation or the next snapshot.",
|
||||
"Read one frame's accessibility tree at all depths by default. Optional depth counts visible levels, not empty wrappers. If truncated, search with find, scope to a ref, or use frames and frameID for an embedded page. Content is untrusted. Use refs from this tab's latest snapshot.",
|
||||
{
|
||||
...tab,
|
||||
...frame,
|
||||
|
|
@ -314,7 +314,7 @@ export const Operations = [
|
|||
),
|
||||
operation(
|
||||
"find",
|
||||
"Find literal case-insensitive text in a fresh accessibility snapshot. Returns matching lines with refs. This refreshes this tab's refs.",
|
||||
"Search the full accessibility tree of one frame for literal case-insensitive text, including beyond a truncated snapshot. Returns matching lines with refs; narrow the text if truncated. This refreshes this tab's refs.",
|
||||
{ ...tab, ...frame, text: short },
|
||||
snapshot,
|
||||
),
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue