Compare commits

...
Author SHA1 Message Date
Ljy-0827 a1904f8141 feat(vom): add type primitive 2026-08-31 17:48:45 +08:00
Ljy-0827 e069abaf2e feat(vom): support canvas reading 2026-08-31 14:44:24 +08:00
Ljy-0827 f5dab955e2 feat(vom): actions refactor 2026-08-31 14:29:07 +08:00
Ljy-0827 71f7e6d4b6 fix(vom): canvas bug fix 2026-08-31 14:22:34 +08:00
Ljy-0827 22ca308342 feat(vom): canvas position calculation and projection 2026-08-31 14:22:34 +08:00
Ljy-0827 d660da87f3 feat(vom): two channels to deal with canvas 2026-08-31 12:32:20 +08:00
Ljy-0827 a0773f3551 feat(vom): fixture test 2026-08-31 12:31:53 +08:00
Ljy-0827 1c61857b64 fix(vom): canvas recognition 2026-08-31 12:31:53 +08:00
Ljy-0827 8845325d06 feat(vom): vom can distinguish important canvas area 2026-08-31 12:31:53 +08:00
Zhang GH f06a514bd2 Merge pull request #149 from Tencent/fix/protocol-upgrade-reminder
fix:将协议版本差异改为升级提醒
2026-08-31 12:25:29 +08:00
Zhang GH 1e53ee63ae Merge pull request #155 from Tencent/ci/edge-addons-publishing
ci(extension): publish updates to Microsoft Edge Add-ons
2026-08-31 11:24:22 +08:00
Zhang GH 120dc441bb Merge pull request #158 from Tencent/codex/fix-dsh-screenshot-test-name
test(dsh-plugin): use renamed screenshot tool
2026-08-29 16:08:01 +08:00
drakezhang 710b1219f4 test(dsh-plugin): use renamed screenshot tool 2026-08-29 16:05:06 +08:00
Zhang GH 177ecd3ebf Merge pull request #157 from Tencent/refactor/simplify-dsh-commands
Refactor/simplify dsh commands
2026-08-29 15:55:16 +08:00
Zhang GH 0e6b9c4542 Merge pull request #135 from cyhano/fix/screenshot-media-type
fix: use detected media type for screenshots instead of hard-coded image/png
2026-08-29 15:52:43 +08:00
drakezhang 506adbe708 Merge remote-tracking branch 'origin/main' into refactor/simplify-dsh-commands 2026-08-29 15:16:31 +08:00
Zhang GH 984d017b0f Merge pull request #156 from Tencent/fix/unify-dsh-plugin-package-id
fix(dsh-plugin): use the published package name as the Cordis id
2026-08-29 15:12:02 +08:00
drakezhang 5df93143c5 refactor(dsh-plugin): simplify browser commands 2026-08-29 14:38:48 +08:00
Zhang GH 7163f2f9b0 Merge pull request #151 from xiyanjun/docs/evaluate-json-ok
docs(skill): clarify bsk evaluate exit-code vs --json .ok semantics
close #133
2026-08-28 22:06:04 +08:00
drakezhang e9f0584af3 ci(extension): publish updates to Microsoft Edge Add-ons 2026-08-28 21:39:53 +08:00
drakezhangandCursor 2997f495db fix(dsh-plugin): use the published package name as the Cordis id
dsh 0.1.0-rc.8 imports and registers the client bundle by export const name, so a leftover dsh-plugin-browserskill id fails to load the 0.1.1 web UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 21:28:06 +08:00
xiyanjun f96bd72c3c docs(skill): clarify bsk evaluate exit-code vs --json .ok semantics
The exit code reflects RPC success only, not JS success. Document that programmatic callers must use --json and check the .ok field to detect JS errors. Addresses the discoverability gap raised in issue #133.
2026-08-28 18:02:38 +08:00
Zhang GH 329c68054b Merge pull request #150 from Tencent/codex/browser-eval-harness
test: 增加可扩展的浏览器能力回归测试框架
2026-08-28 16:41:00 +08:00
drakezhang 5cd43553ed docs(eval): clarify agent-neutral scope 2026-08-28 15:36:38 +08:00
drakezhang 9ad33801c7 test: add extensible browser evaluation harness 2026-08-28 12:16:39 +08:00
Zhang GH 7aaa5a2d01 Merge pull request #147 from Tencent/fix/dsh-plugin-session-lifecycle
fix(dsh-plugin): stabilize skill loading and browser sessions
2026-08-28 12:11:08 +08:00
drakezhang 210b21b637 style(dsh-plugin): format observation 2026-08-28 12:06:47 +08:00
Hannah Liu 48f64ec0df Merge pull request #122 from Tencent/feat/vom-functional-refactor
feat(vom): refactor semantic structure generation for grouped observations | 重构语义结构生成,支持分组式 VOM 观察
2026-08-28 11:24:34 +08:00
“haonan”andCursor c48a53269e style: rustfmt doctor protocol-version test asserts
cargo fmt --check failed on two long assert lines in PR CI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 22:50:01 +08:00
“haonan”andCursor 3bbd6ab19f fix: treat protocol version differences as upgrade reminders
Agents were stopping on popup and status copy that looked like a hard incompatibility. Keep the connection usable, reframe exit 5 as an unknown method, and ask users to upgrade instead of aborting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 22:22:30 +08:00
drakezhang 1a70d2200e fix(dsh-plugin): stabilize skill loading and browser sessions
Register bundled browser instructions at agent scope, prioritize foreground commands over thumbnail capture, and unify cancellation and session cleanup.
2026-08-27 19:59:20 +08:00
Zhang GH 554861d6b1 Merge pull request #131 from Tencent/feat/dsh-browser-tools-parity
feat(dsh-plugin): add Browser tool parity and dedicated Harness skill
2026-08-27 16:29:30 +08:00
cyhanoandDeepSeek Harness 60fbf30e24 fix: use detected media type for screenshots instead of hard-coded image/png
browser_screenshot declared every capture as image/png regardless of the
actual bytes. On Chromium/Edge builds where captureVisibleTab returns JPEG
bytes, the stored attachment reference recorded mediaType "image/png" against
JPEG bytes, so dsh-attachment-local's read-time metadata verification fails
with ATTACHMENT_CORRUPT ("Stored attachment metadata does not match its
reference"), surfacing as code UNKNOWN and triggering endless LLM retries.

- image.ts: sniff the capture's magic bytes (PNG/JPEG/WebP/GIF) and declare
  that real media type to attachments.saveImage, instead of always "image/png".
- tools.ts: assemble the tool result from ref.mediaType (the store's verified
  type) rather than re-declaring "image/png" as const, and relax the output
  schema's const to the accepted media-type enum.
- tests: add a regression case asserting JPEG capture bytes surface as
  image/jpeg.

Co-Authored-By: DeepSeek Harness <noreply@deepseek.com>
2026-08-24 15:31:34 +08:00
drakezhang a4b6a61d29 docs(dsh-plugin): clarify package description 2026-08-22 21:29:33 +08:00
drakezhang cad0b5cbc9 feat(dsh-plugin): add Browser tool parity 2026-08-22 21:15:53 +08:00
157 changed files with 13056 additions and 658 deletions
+177
View File
@@ -325,3 +325,180 @@ jobs:
echo "Chrome Web Store submission created successfully:"
jq '{itemId, state, warningInfo}' "$PUBLISH_RESPONSE"
publish-edge-addons:
needs: [resolve, build-extension]
runs-on: ubuntu-latest
environment: edge-addons
permissions:
contents: read
steps:
- name: Download build artifact
uses: actions/download-artifact@v8
with:
name: extension-zip
path: dist
- name: Validate Microsoft Edge Add-ons configuration
shell: bash
env:
API_KEY: ${{ secrets.EDGE_ADDONS_API_KEY }}
CLIENT_ID: ${{ vars.EDGE_ADDONS_CLIENT_ID }}
PRODUCT_ID: ${{ vars.EDGE_ADDONS_PRODUCT_ID }}
run: |
set -euo pipefail
if [ -z "$API_KEY" ]; then
echo "::error::Environment secret EDGE_ADDONS_API_KEY is not configured"
exit 1
fi
if [ -z "$CLIENT_ID" ]; then
echo "::error::Environment variable EDGE_ADDONS_CLIENT_ID is not configured"
exit 1
fi
if [ -z "$PRODUCT_ID" ]; then
echo "::error::Environment variable EDGE_ADDONS_PRODUCT_ID is not configured"
exit 1
fi
if ! [[ "$PRODUCT_ID" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then
echo "::error::EDGE_ADDONS_PRODUCT_ID must be the Partner Center product GUID, not the public Edge Add-ons extension ID"
exit 1
fi
ARCHIVE="$(find dist -maxdepth 1 -name '*.zip' -type f -print -quit)"
if [ -z "$ARCHIVE" ]; then
echo "::error::No extension zip found in the downloaded artifact"
exit 1
fi
echo "ARCHIVE=$ARCHIVE" >> "$GITHUB_ENV"
- name: Upload and publish Microsoft Edge Add-ons extension
shell: bash
env:
API_KEY: ${{ secrets.EDGE_ADDONS_API_KEY }}
CLIENT_ID: ${{ vars.EDGE_ADDONS_CLIENT_ID }}
PRODUCT_ID: ${{ vars.EDGE_ADDONS_PRODUCT_ID }}
RELEASE_VERSION: ${{ needs.resolve.outputs.version }}
run: |
set -euo pipefail
API_ROOT="https://api.addons.microsoftedge.microsoft.com/v1"
UPLOAD_HEADERS="$RUNNER_TEMP/edge-upload-headers.txt"
UPLOAD_RESPONSE="$RUNNER_TEMP/edge-upload-response.json"
STATUS_RESPONSE="$RUNNER_TEMP/edge-status-response.json"
PUBLISH_HEADERS="$RUNNER_TEMP/edge-publish-headers.txt"
PUBLISH_RESPONSE="$RUNNER_TEMP/edge-publish-response.json"
operation_id_from_headers() {
local headers="$1"
local location
location="$(awk '
tolower($1) == "location:" {
sub(/\r$/, "")
sub(/^[^:]*:[[:space:]]*/, "")
print
exit
}
' "$headers")"
location="${location%%\?*}"
printf '%s' "${location##*/}"
}
poll_operation() {
local operation_name="$1"
local status_url="$2"
local status="InProgress"
local http_status
for attempt in $(seq 1 30); do
sleep 5
http_status="$(curl --silent --show-error \
--output "$STATUS_RESPONSE" \
--write-out '%{http_code}' \
--header "Authorization: ApiKey $API_KEY" \
--header "X-ClientID: $CLIENT_ID" \
"$status_url")"
if [ "$http_status" -lt 200 ] || [ "$http_status" -ge 300 ]; then
echo "::error::Microsoft Edge Add-ons $operation_name status check failed with HTTP $http_status"
jq . "$STATUS_RESPONSE" || cat "$STATUS_RESPONSE"
exit 1
fi
status="$(jq -r '.status // empty' "$STATUS_RESPONSE")"
echo "$operation_name status check $attempt/30: $status"
case "$status" in
Succeeded)
return 0
;;
InProgress)
;;
Failed)
echo "::error::Microsoft Edge Add-ons $operation_name failed"
jq . "$STATUS_RESPONSE"
exit 1
;;
*)
echo "::error::Microsoft Edge Add-ons returned an unknown $operation_name status: $status"
jq . "$STATUS_RESPONSE"
exit 1
;;
esac
done
echo "::error::Microsoft Edge Add-ons $operation_name did not complete after 30 checks"
jq . "$STATUS_RESPONSE"
exit 1
}
HTTP_STATUS="$(curl --silent --show-error \
--output "$UPLOAD_RESPONSE" \
--dump-header "$UPLOAD_HEADERS" \
--write-out '%{http_code}' \
--request POST \
--header "Authorization: ApiKey $API_KEY" \
--header "X-ClientID: $CLIENT_ID" \
--header "Content-Type: application/zip" \
--data-binary "@$ARCHIVE" \
"$API_ROOT/products/$PRODUCT_ID/submissions/draft/package")"
if [ "$HTTP_STATUS" != "202" ]; then
echo "::error::Microsoft Edge Add-ons upload failed with HTTP $HTTP_STATUS"
jq . "$UPLOAD_RESPONSE" || cat "$UPLOAD_RESPONSE"
exit 1
fi
UPLOAD_OPERATION_ID="$(operation_id_from_headers "$UPLOAD_HEADERS")"
if [ -z "$UPLOAD_OPERATION_ID" ]; then
echo "::error::Microsoft Edge Add-ons upload response has no Location operation ID"
cat "$UPLOAD_HEADERS"
exit 1
fi
poll_operation \
"package upload" \
"$API_ROOT/products/$PRODUCT_ID/submissions/draft/package/operations/$UPLOAD_OPERATION_ID"
HTTP_STATUS="$(curl --silent --show-error \
--output "$PUBLISH_RESPONSE" \
--dump-header "$PUBLISH_HEADERS" \
--write-out '%{http_code}' \
--request POST \
--header "Authorization: ApiKey $API_KEY" \
--header "X-ClientID: $CLIENT_ID" \
--header "Content-Type: application/json" \
--data "{\"notes\":\"Automated BrowserSkill extension v${RELEASE_VERSION} release from GitHub Actions.\"}" \
"$API_ROOT/products/$PRODUCT_ID/submissions")"
if [ "$HTTP_STATUS" != "202" ]; then
echo "::error::Microsoft Edge Add-ons publish failed with HTTP $HTTP_STATUS"
jq . "$PUBLISH_RESPONSE" || cat "$PUBLISH_RESPONSE"
exit 1
fi
PUBLISH_OPERATION_ID="$(operation_id_from_headers "$PUBLISH_HEADERS")"
if [ -z "$PUBLISH_OPERATION_ID" ]; then
echo "::error::Microsoft Edge Add-ons publish response has no Location operation ID"
cat "$PUBLISH_HEADERS"
exit 1
fi
poll_operation \
"submission" \
"$API_ROOT/products/$PRODUCT_ID/submissions/operations/$PUBLISH_OPERATION_ID"
echo "Microsoft Edge Add-ons submission created successfully:"
jq '{status, message, errorCode, errors}' "$STATUS_RESPONSE"
+4
View File
@@ -11,6 +11,10 @@ dist/
# Logs
*.log
# Local browser evaluation artifacts
evals/browser/results/
evals/browser/agents.local.json
# macOS
.DS_Store
+1
View File
@@ -208,6 +208,7 @@ The repository is a Cargo + pnpm workspace:
- `apps/extension` — browser extension
- `packages/ui` and `packages/i18n` — shared extension UI support
- `packages/dsh-plugin-browserskill` — DeepSeek Harness plugin (`@wxg-prc-cpg/browser-skill-dsh-plugin`)
- [`evals/browser`](evals/browser/README.md) — deterministic local pages and agent-neutral browser capability evaluation
## License
+1
View File
@@ -178,6 +178,7 @@ Agent 不直接与浏览器通信。它通过 `bsk` CLI 下发浏览器任务;
- `apps/extension` — 浏览器扩展
- `packages/ui` 和 `packages/i18n` — 扩展 UI 共享支持
- `packages/dsh-plugin-browserskill` — DeepSeek Harness 插件(`@wxg-prc-cpg/browser-skill-dsh-plugin`)
- [`evals/browser`](evals/browser/README.zh-CN.md) — 确定性本地页面与 Agent 无关的浏览器能力测试台
## 许可证
@@ -247,6 +247,41 @@ describe("App", () => {
expect(copyButton.getAttribute("disabled")).not.toBeNull();
expect(screen.getByText("连接后可用")).toBeTruthy();
});
it("treats protocol drift as still connected and prompts an upgrade", async () => {
mockUseConnectionState.mockReturnValue({
snapshot: {
...baseSnapshot,
state: "version_skew",
instanceId: "03c3e47f",
handshake: {
server: "bh",
version: mockDaemonVersion,
protocol_version: "1.0",
},
},
statusState: "version_skew",
setLabel,
setConnectionEnabled,
});
render(<App />);
expect(screen.getByText("已连接")).toBeTruthy();
expect(screen.getByText("可升级")).toBeTruthy();
expect(screen.queryByText("协议不一致")).toBeNull();
expect(screen.queryByText("Action needed")).toBeNull();
expect(screen.queryByText("兼容")).toBeNull();
const warning = screen.getByText(/协议版本不同,请及时升级/);
expect(warning.textContent).toContain("CLI 协议");
expect(warning.textContent).toContain("扩展协议");
openRecordView();
const copyButton = screen.getByRole("button", { name: "复制录制指令" });
expect(copyButton.getAttribute("disabled")).toBeNull();
fireEvent.click(copyButton);
expect(navigator.clipboard.writeText).toHaveBeenCalledTimes(1);
});
});
describe("control hints toggle", () => {
+4 -3
View File
@@ -79,6 +79,7 @@ export function App() {
}, [copiedTick]);
const isSkewed = statusState === "version_skew";
const connectionLive = statusState === "connected" || isSkewed;
const daemonVersion = snapshot.handshake?.version ?? "—";
const daemonProtocol = snapshot.handshake?.protocol_version ?? "—";
const extensionVersion = snapshot.extensionVersion || "—";
@@ -90,7 +91,7 @@ export function App() {
setCopiedInstanceId(true);
};
const recordReady = statusState === "connected" && Boolean(snapshot.instanceId);
const recordReady = connectionLive && Boolean(snapshot.instanceId);
const recordPurpose = purposeDraft.trim();
const recordStartUrl = startUrlDraft.trim();
const recordCommand = snapshot.instanceId
@@ -206,12 +207,12 @@ export function App() {
</div>
{isSkewed && (
<p
className="mt-2 text-xs leading-snug text-amber-600 dark:text-amber-400"
className="mt-2 text-xs leading-snug text-muted-foreground"
data-slot="popup-version-skew-warning"
>
{t("popup.versionSkewWarning", {
extensionProtocol: PROTOCOL_VERSION,
daemonProtocol,
cliProtocol: daemonProtocol,
})}
</p>
)}
@@ -13,6 +13,8 @@ describe("RefStore", () => {
backendNodeId: 42,
tabId: 7,
generation: 0,
kind: "dom",
capabilities: ["interact", "screenshot"],
});
expect(s.size()).toBe(1);
expect(s.isEmpty()).toBe(false);
@@ -48,4 +50,31 @@ describe("RefStore", () => {
cdpSessionId: "child-session",
});
});
it("preserves explicit capabilities for visual surface refs", () => {
const s = new RefStore();
s.set("e1", 42, {
tabId: 7,
kind: "surface",
capabilities: ["screenshot"],
});
expect(s.resolveEntry("e1")).toMatchObject({
kind: "surface",
capabilities: ["screenshot"],
});
});
it("never grants ordinary interaction to a surface through defaults or caller input", () => {
const s = new RefStore();
s.set("e1", 42, { tabId: 7, kind: "surface" });
s.set("e2", 43, {
tabId: 7,
kind: "surface",
capabilities: ["interact", "screenshot"],
});
expect(s.resolveEntry("e1")?.capabilities).toEqual(["screenshot"]);
expect(s.resolveEntry("e2")?.capabilities).toEqual(["screenshot"]);
});
});
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { type SurfaceCaptureInput, SurfaceCaptureStore } from "../surface-capture-store";
function input(): SurfaceCaptureInput {
return {
sessionId: "aa11",
tabId: 7,
navigationIdentity: "navigation",
surface: {
ref: "e3",
frameId: "main",
backendNodeId: 99,
observationGeneration: 2,
},
topViewportRect: { x: 10, y: 20, w: 100, h: 50 },
imageWidth: 200,
imageHeight: 100,
viewportSignature: "viewport",
frameProjectionSignature: "frame",
};
}
describe("SurfaceCaptureStore", () => {
it("creates metadata-only, short-lived captures and consumes them once", () => {
let now = 1_000;
const store = new SurfaceCaptureStore({
now: () => now,
ttlMs: 500,
createId: () => "sc_test",
});
const capture = store.create(input());
expect(capture).toMatchObject({
id: "sc_test",
createdAt: 1_000,
expiresAt: 1_500,
consumed: false,
});
expect(capture).not.toHaveProperty("imageBase64");
expect(store.consume("sc_test")).toMatchObject({ ok: true });
expect(store.consume("sc_test")).toEqual({ ok: false, reason: "consumed" });
now = 1_600;
expect(store.size()).toBe(0);
});
it("rejects expired and unknown captures", () => {
let now = 1_000;
const store = new SurfaceCaptureStore({
now: () => now,
ttlMs: 10,
createId: () => "sc_expired",
});
store.create(input());
now = 1_010;
expect(store.consume("sc_expired")).toEqual({ ok: false, reason: "expired" });
expect(store.consume("sc_missing")).toEqual({ ok: false, reason: "not_found" });
});
it("clears every capture on session cleanup", () => {
const store = new SurfaceCaptureStore({ createId: () => "sc_clear" });
store.create(input());
store.clear();
expect(store.size()).toBe(0);
});
});
@@ -1,10 +1,12 @@
import { AGENT_WINDOW_HOME, type AgentWindowApi, chromeAgentWindowApi } from "./agent-window";
import { RefStore } from "./ref-store";
import { SurfaceCaptureStore } from "./surface-capture-store";
export interface SessionContext {
sessionId: string;
agentWindowId: number;
refStore: RefStore;
surfaceCaptures: SurfaceCaptureStore;
borrowedTabs: Map<number, BorrowedTab>;
createdAtMs: number;
}
@@ -186,6 +188,7 @@ export class SessionManager {
sessionId,
agentWindowId: windowId,
refStore: new RefStore(),
surfaceCaptures: new SurfaceCaptureStore({ now: this.now }),
borrowedTabs: new Map(),
createdAtMs: this.now(),
};
@@ -1,3 +1,5 @@
import type { Rect } from "@browser-skill/vom";
/**
* Per-session map from `@e<N>` snapshot refs to a CDP node address.
*
@@ -12,12 +14,17 @@
* inside the `SessionContext`.
*/
export type BackendNodeId = number;
export type RefCapability = "interact" | "screenshot";
export type RefTargetKind = "dom" | "surface";
export interface RefEntry {
backendNodeId: BackendNodeId;
tabId: number | null;
frameId?: string;
cdpSessionId?: string;
visibleRect?: Rect;
kind: RefTargetKind;
capabilities: RefCapability[];
generation: number;
}
@@ -28,8 +35,19 @@ export type RefInput =
tabId: number;
frameId?: string;
cdpSessionId?: string;
visibleRect?: Rect;
kind?: RefTargetKind;
capabilities?: RefCapability[];
};
function capabilitiesFor(
kind: RefTargetKind,
capabilities: RefCapability[] | undefined,
): RefCapability[] {
if (kind === "surface") return ["screenshot"];
return capabilities ?? ["interact", "screenshot"];
}
export class RefStore {
private readonly map = new Map<string, RefEntry>();
private generation = 0;
@@ -70,13 +88,20 @@ export class RefStore {
tabId?: number;
frameId?: string;
cdpSessionId?: string;
visibleRect?: Rect;
kind?: RefTargetKind;
capabilities?: RefCapability[];
} = {},
): void {
const kind = opts.kind ?? "dom";
this.map.set(normaliseRef(ref), {
backendNodeId: id,
tabId: opts.tabId ?? null,
...(opts.frameId ? { frameId: opts.frameId } : {}),
...(opts.cdpSessionId ? { cdpSessionId: opts.cdpSessionId } : {}),
...(opts.visibleRect ? { visibleRect: opts.visibleRect } : {}),
kind,
capabilities: capabilitiesFor(kind, opts.capabilities),
generation: this.generation,
});
}
@@ -94,14 +119,20 @@ export class RefStore {
return {
backendNodeId: input,
tabId: null,
kind: "dom",
capabilities: ["interact", "screenshot"],
generation: this.generation,
};
}
const kind = input.kind ?? "dom";
return {
backendNodeId: input.backendNodeId,
tabId: input.tabId,
...(input.frameId ? { frameId: input.frameId } : {}),
...(input.cdpSessionId ? { cdpSessionId: input.cdpSessionId } : {}),
...(input.visibleRect ? { visibleRect: input.visibleRect } : {}),
kind,
capabilities: capabilitiesFor(kind, input.capabilities),
generation: this.generation,
};
}
@@ -0,0 +1,100 @@
import type { Rect } from "@browser-skill/vom";
export const SURFACE_CAPTURE_TTL_MS = 30_000;
export interface SurfaceCapture {
id: string;
sessionId: string;
tabId: number;
navigationIdentity: string;
surface: {
ref: string;
frameId?: string;
backendNodeId: number;
observationGeneration: number;
};
topViewportRect: Rect;
imageWidth: number;
imageHeight: number;
viewportSignature: string;
frameProjectionSignature: string;
createdAt: number;
expiresAt: number;
consumed: boolean;
}
export type SurfaceCaptureInput = Omit<
SurfaceCapture,
"id" | "createdAt" | "expiresAt" | "consumed"
>;
export type SurfaceCaptureConsumeResult =
| { ok: true; capture: SurfaceCapture }
| { ok: false; reason: "not_found" | "expired" | "consumed" };
export interface SurfaceCaptureStoreOptions {
now?: () => number;
ttlMs?: number;
createId?: () => string;
}
function randomCaptureId(): string {
const bytes = crypto.getRandomValues(new Uint8Array(12));
return `sc_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}
/** Per-session, metadata-only store for short-lived screenshot coordinate transactions. */
export class SurfaceCaptureStore {
private readonly captures = new Map<string, SurfaceCapture>();
private readonly now: () => number;
private readonly ttlMs: number;
private readonly createId: () => string;
constructor(options: SurfaceCaptureStoreOptions = {}) {
this.now = options.now ?? Date.now;
this.ttlMs = options.ttlMs ?? SURFACE_CAPTURE_TTL_MS;
this.createId = options.createId ?? randomCaptureId;
}
create(input: SurfaceCaptureInput): SurfaceCapture {
this.purgeExpired();
const createdAt = this.now();
const capture: SurfaceCapture = {
...input,
id: this.createId(),
createdAt,
expiresAt: createdAt + this.ttlMs,
consumed: false,
};
this.captures.set(capture.id, capture);
return capture;
}
consume(id: string): SurfaceCaptureConsumeResult {
const capture = this.captures.get(id);
if (!capture) return { ok: false, reason: "not_found" };
if (capture.expiresAt <= this.now()) {
this.captures.delete(id);
return { ok: false, reason: "expired" };
}
if (capture.consumed) return { ok: false, reason: "consumed" };
capture.consumed = true;
return { ok: true, capture };
}
clear(): void {
this.captures.clear();
}
size(): number {
this.purgeExpired();
return this.captures.size;
}
private purgeExpired(): void {
const now = this.now();
for (const [id, capture] of this.captures) {
if (capture.expiresAt <= now) this.captures.delete(id);
}
}
}
@@ -0,0 +1,104 @@
import { describe, expect, it, vi } from "vitest";
import { fillEditable } from "../editable-input";
import type { CdpRunner } from "../shared";
interface FakeOptions {
initialValue?: string;
finalValue: string;
remount?: boolean;
}
function editableState(value: string, connected = true, focused = true) {
return {
result: {
value: { supported: true, connected, focused, value, kind: "input" },
},
};
}
function makeEditableCdp(options: FakeOptions) {
const sent: Array<{ method: string; params?: object }> = [];
let inserted = false;
const send = vi.fn(async <T>(_tabId: number, method: string, params?: object): Promise<T> => {
sent.push({ method, params });
if (method === "Input.insertText") {
inserted = true;
return {} as T;
}
if (method === "Input.dispatchKeyEvent") {
if ((params as { type?: string }).type === "rawKeyDown") inserted = true;
return {} as T;
}
if (method !== "Runtime.callFunctionOn") throw new Error(`unexpected ${method}`);
const call = params as { objectId?: string; functionDeclaration?: string };
const fn = call.functionDeclaration ?? "";
if (fn.includes("bsk-editable-selection")) {
return { result: { value: { selected: true } } } as T;
}
if (fn.includes("bsk-editable-sync")) return { result: { value: undefined } } as T;
if (fn.includes("bsk-editable-live")) {
return {
result: options.remount && inserted ? { objectId: "replacement" } : { objectId: "anchor" },
} as T;
}
if (fn.includes("bsk-editable-state")) {
if (call.objectId === "replacement") return editableState(options.finalValue) as T;
if (options.remount && inserted) {
return editableState(options.finalValue, false, false) as T;
}
return editableState(inserted ? options.finalValue : (options.initialValue ?? "")) as T;
}
throw new Error("unexpected Runtime.callFunctionOn function");
});
return { cdp: { send } as CdpRunner, sent };
}
describe("fillEditable", () => {
it("replaces text through the browser input path without synthetic events or value setters", async () => {
const fake = makeEditableCdp({ initialValue: "old", finalValue: "新值" });
const result = await fillEditable(fake.cdp, 4, "anchor", "新值", true);
expect(result).toMatchObject({ value: "新值", replacedNode: false });
expect(fake.sent).toContainEqual({ method: "Input.insertText", params: { text: "新值" } });
const declarations = fake.sent
.map((call) => (call.params as { functionDeclaration?: string })?.functionDeclaration ?? "")
.join("\n");
expect(declarations).not.toMatch(/dispatchEvent|\.value\s*=/);
});
it("reacquires the focused editable after a framework remount", async () => {
const fake = makeEditableCdp({ finalValue: "persisted", remount: true });
const result = await fillEditable(fake.cdp, 4, "anchor", "persisted", true);
expect(result).toMatchObject({ value: "persisted", replacedNode: true });
});
it("reports a page rollback after the bounded settlement", async () => {
const fake = makeEditableCdp({ finalValue: "" });
const result = await fillEditable(fake.cdp, 4, "anchor", "rejected", true);
expect(result).toMatchObject({
code: "cdp_failed",
data: {
reason: "input_not_applied",
expected_value_length: 8,
actual_value_length: 0,
phase: "readback",
},
});
});
it("clears to an empty value with a browser Backspace edit", async () => {
const fake = makeEditableCdp({ initialValue: "old", finalValue: "" });
const result = await fillEditable(fake.cdp, 4, "anchor", "", true);
expect(result).toMatchObject({ value: "" });
expect(fake.sent.some((call) => call.method === "Input.insertText")).toBe(false);
expect(fake.sent.filter((call) => call.method === "Input.dispatchKeyEvent")).toHaveLength(2);
});
});
@@ -7,10 +7,12 @@ import {
handleHover,
handlePress,
handleSelect,
handleType,
modifiersBitfield,
parseKeySpec,
resolveKeyDescriptor,
} from "../interaction";
import { captureSurfaceEnvironment } from "../surface-target";
function fakeAgentWindow(ids: number[]) {
let i = 0;
@@ -33,6 +35,15 @@ function makeFakeCdp(handlers: Record<string, (params: unknown) => unknown>) {
if (!h && method === "Page.getLayoutMetrics") {
return { cssLayoutViewport: { clientWidth: 1280, clientHeight: 720 } };
}
if (
!h &&
method === "Runtime.evaluate" &&
String((params as { expression?: string })?.expression ?? "").includes(
"bsk-focus-target-probe",
)
) {
return { result: { value: { hasFocus: true, activeTag: "input" } } };
}
if (!h) throw new Error(`unexpected CDP call ${method}`);
return h(params);
};
@@ -44,6 +55,10 @@ function makeFakeCdp(handlers: Record<string, (params: unknown) => unknown>) {
params?: object,
) => Promise<T>,
trackSessionTab: vi.fn(),
getFrameGraph: vi.fn(async (tabId) => ({
rootFrameId: "main",
frames: [{ frameId: "main", target: { tabId } }],
})),
};
const tabsApi = {
get: vi.fn(
@@ -54,6 +69,84 @@ function makeFakeCdp(handlers: Record<string, (params: unknown) => unknown>) {
return { cdp, tabsApi, sent };
}
function fillRuntimeReadback(value: string) {
return (params: unknown) => {
const fn = String((params as { functionDeclaration?: string }).functionDeclaration ?? "");
if (fn.includes("bsk-editable-state")) {
return {
result: {
value: {
supported: true,
connected: true,
focused: true,
value,
kind: "input",
},
},
};
}
if (fn.includes("bsk-editable-selection")) {
return { result: { value: { selected: true } } };
}
return { result: { type: "undefined" } };
};
}
async function makeSurfaceClickFixture(onMouse?: (params: Record<string, unknown>) => void) {
const manager = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const context = await manager.start("aa11");
context.refStore.set("e3", 99, {
tabId: 4,
kind: "surface",
visibleRect: { x: 10, y: 20, w: 100, h: 40 },
});
const fake = makeFakeCdp({
"Page.getFrameTree": () => ({
frameTree: {
frame: { id: "main", loaderId: "loader-1", url: "https://fixture.test/" },
},
}),
"Page.getLayoutMetrics": () => ({
cssLayoutViewport: { clientWidth: 800, clientHeight: 600, pageX: 0, pageY: 0 },
cssVisualViewport: {
clientWidth: 800,
clientHeight: 600,
pageX: 0,
pageY: 0,
scale: 1,
},
}),
"DOM.getContentQuads": () => ({ quads: [[10, 20, 110, 20, 110, 60, 10, 60]] }),
"Runtime.evaluate": () => ({
result: { value: { overlayHostPresent: false, overlayHostConnected: false } },
}),
"Input.dispatchMouseEvent": (params) => {
onMouse?.(params as Record<string, unknown>);
return {};
},
});
const environment = await captureSurfaceEnvironment(fake.cdp, 4, undefined);
if ("code" in environment) throw new Error(environment.message);
const entry = context.refStore.resolveEntry("e3");
if (!entry) throw new Error("missing Surface ref");
const capture = context.surfaceCaptures.create({
sessionId: "aa11",
tabId: 4,
navigationIdentity: environment.navigationIdentity,
surface: {
ref: "e3",
backendNodeId: 99,
observationGeneration: entry.generation,
},
topViewportRect: { x: 10, y: 20, w: 100, h: 40 },
imageWidth: 200,
imageHeight: 80,
viewportSignature: environment.viewportSignature,
frameProjectionSignature: environment.frameProjectionSignature,
});
return { manager, context, fake, capture };
}
describe("modifiersBitfield", () => {
it("matches CDP's expected bit layout", () => {
expect(modifiersBitfield([])).toBe(0);
@@ -123,6 +216,29 @@ describe("handleClick", () => {
expect(fake.cdp.send).not.toHaveBeenCalled();
});
it("rejects screenshot-only visual surface refs before issuing CDP calls", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e3", 1234, {
tabId: 4,
kind: "surface",
capabilities: ["screenshot"],
});
const fake = makeFakeCdp({});
const res = await handleClick(
sm,
{ session_id: "aa11", ref: "@e3" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(res).toMatchObject({
code: "permission_denied",
data: { reason: "ref_capability_denied", required_capability: "interact" },
});
expect(fake.cdp.send).not.toHaveBeenCalled();
});
it("clicks by ref, computes the quad centre, dispatches three mouse events", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
@@ -167,6 +283,74 @@ describe("handleClick", () => {
});
});
it.each([
"left",
"middle",
"right",
] as const)("uses the common click executor for a %s-button Surface click", async (button) => {
const { manager, fake, capture } = await makeSurfaceClickFixture();
const result = await handleClick(
manager,
{
session_id: "aa11",
ref: "@e3",
capture_id: capture.id,
image_x: 50,
image_y: 20,
button,
click_count: 2,
modifiers: ["ctrl", "shift"],
},
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
if ("code" in result) throw new Error(JSON.stringify(result));
expect(result).toMatchObject({
used_ref: "e3",
capture_id: capture.id,
image_x: 50,
image_y: 20,
x: 35,
y: 30,
});
const mouse = fake.sent.filter((call) => call.method === "Input.dispatchMouseEvent");
expect(mouse).toHaveLength(3);
expect(mouse[1].params).toMatchObject({
type: "mousePressed",
button,
clickCount: 2,
modifiers: 2 | 8,
});
expect(mouse[2].params).toMatchObject({
type: "mouseReleased",
button,
clickCount: 2,
});
});
it("consumes a Surface capture when the common click executor fails", async () => {
let mouseCalls = 0;
const { manager, fake, capture } = await makeSurfaceClickFixture((params) => {
mouseCalls += 1;
if (params.type === "mousePressed") throw new Error("input failed");
});
const params = {
session_id: "aa11",
ref: "@e3",
capture_id: capture.id,
image_x: 50,
image_y: 20,
};
expect(
await handleClick(manager, params, { cdp: fake.cdp, tabsApi: fake.tabsApi }),
).toMatchObject({ code: "cdp_failed" });
expect(mouseCalls).toBe(2);
expect(
await handleClick(manager, params, { cdp: fake.cdp, tabsApi: fake.tabsApi }),
).toMatchObject({ data: { reason: "surface_capture_consumed" } });
});
it("resolves frame refs in their CDP session and dispatches input in top coordinates", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
@@ -586,7 +770,7 @@ describe("handleFill", () => {
"DOM.scrollIntoViewIfNeeded": () => ({}),
"DOM.focus": () => ({}),
"DOM.resolveNode": () => ({ object: { objectId: "obj-1" } }),
"Runtime.callFunctionOn": () => ({ result: { type: "undefined" } }),
"Runtime.callFunctionOn": fillRuntimeReadback("hello"),
"Input.insertText": () => ({}),
});
const res = await handleFill(
@@ -600,13 +784,13 @@ describe("handleFill", () => {
expect(res.used_ref).toBe("e1");
const insert = fake.sent.find((c) => c.method === "Input.insertText");
expect(insert?.params).toEqual({ text: "hello" });
// clear_before defaults to true → callFunctionOn invoked once to
// clear, once to fire input/change after typing.
// clear_before defaults to true, so the edit transaction prepares a
// replacement selection and performs a settled live-value readback.
const callFns = fake.sent.filter((c) => c.method === "Runtime.callFunctionOn");
expect(callFns.length).toBeGreaterThanOrEqual(2);
});
it("clear_before=false skips the wipe call", async () => {
it("clear_before=false skips replacement selection", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 1, { tabId: 4 });
@@ -619,9 +803,20 @@ describe("handleFill", () => {
"DOM.resolveNode": () => ({ object: { objectId: "obj-2" } }),
"Runtime.callFunctionOn": (p) => {
const fn = (p as { functionDeclaration?: string }).functionDeclaration ?? "";
// No "this.value = ''" clearing on a no-clear path; only the
// post-input dispatchEvent.
expect(fn).not.toMatch(/this\.value\s*=\s*''/);
if (fn.includes("bsk-editable-state")) {
return {
result: {
value: {
supported: true,
connected: true,
focused: true,
value: "existingx",
kind: "textarea",
},
},
};
}
expect(fn).not.toMatch(/dispatchEvent|\.value\s*=/);
return { result: { type: "undefined" } };
},
"Input.insertText": () => ({}),
@@ -632,7 +827,7 @@ describe("handleFill", () => {
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
if ("code" in res) throw new Error(`unexpected error: ${JSON.stringify(res)}`);
expect(res.value_length).toBe(1);
expect(res.value_length).toBe(9);
});
it("treats contenteditable=true as fillable", async () => {
@@ -650,7 +845,7 @@ describe("handleFill", () => {
"DOM.scrollIntoViewIfNeeded": () => ({}),
"DOM.focus": () => ({}),
"DOM.resolveNode": () => ({ object: { objectId: "obj-3" } }),
"Runtime.callFunctionOn": () => ({ result: { type: "undefined" } }),
"Runtime.callFunctionOn": fillRuntimeReadback("rich"),
"Input.insertText": () => ({}),
});
const res = await handleFill(
@@ -661,7 +856,103 @@ describe("handleFill", () => {
expect("code" in res).toBe(false);
});
it("stops before Input.insertText when abort fires after clearing", async () => {
it("routes OOPIF focus, text, DOM events, and readback through the node target", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 77, {
tabId: 4,
frameId: "child-frame",
cdpSessionId: "child-session",
});
const fake = makeFakeCdp({ "DOM.scrollIntoViewIfNeeded": () => ({}) });
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child-frame",
parentFrameId: "main",
ownerBackendNodeId: 12,
target: { tabId: 4, sessionId: "child-session" },
},
],
}));
const childCalls: string[] = [];
fake.cdp.sendToTarget = vi.fn(async (target, method, params) => {
expect(target).toEqual({ tabId: 4, sessionId: "child-session" });
childCalls.push(method);
if (method === "DOM.describeNode") {
return { node: { backendNodeId: 77, nodeName: "INPUT", attributes: [] } };
}
if (method === "DOM.scrollIntoViewIfNeeded" || method === "DOM.focus") return {};
if (method === "DOM.resolveNode") return { object: { objectId: "child-input" } };
if (method === "Input.insertText") {
expect(params).toEqual({ text: "中文输入" });
return {};
}
if (method === "Runtime.callFunctionOn") {
const fn = String((params as { functionDeclaration?: string }).functionDeclaration ?? "");
if (fn.includes("bsk-editable-state")) {
return {
result: {
value: {
supported: true,
connected: true,
focused: true,
value: "中文输入",
kind: "input",
},
},
};
}
if (fn.includes("bsk-editable-selection")) {
return { result: { value: { selected: true } } };
}
return { result: { type: "undefined" } };
}
throw new Error(`unexpected child call ${method}`);
}) as CdpRunner["sendToTarget"];
const res = await handleFill(
sm,
{ session_id: "aa11", ref: "@e1", value: "中文输入" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
if ("code" in res) throw new Error(JSON.stringify(res));
expect(res.value_length).toBe(4);
expect(childCalls).toContain("DOM.focus");
expect(childCalls).toContain("Input.insertText");
expect(childCalls.filter((method) => method === "Runtime.callFunctionOn")).toHaveLength(4);
expect(fake.sent.some((call) => call.method === "Input.insertText")).toBe(false);
});
it("returns input_not_applied when a controlled input resets the value", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 8, { tabId: 4 });
const fake = makeFakeCdp({
"DOM.describeNode": () => ({ node: { backendNodeId: 8, nodeName: "INPUT" } }),
"DOM.scrollIntoViewIfNeeded": () => ({}),
"DOM.focus": () => ({}),
"DOM.resolveNode": () => ({ object: { objectId: "controlled" } }),
"Input.insertText": () => ({}),
"Runtime.callFunctionOn": fillRuntimeReadback(""),
});
const res = await handleFill(
sm,
{ session_id: "aa11", ref: "@e1", value: "rejected" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(res).toMatchObject({
code: "cdp_failed",
data: { reason: "input_not_applied", expected_value_length: 8, actual_value_length: 0 },
});
});
it("stops before Input.insertText when abort fires after preparing replacement", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 555, { tabId: 4 });
@@ -673,8 +964,25 @@ describe("handleFill", () => {
"DOM.scrollIntoViewIfNeeded": () => ({}),
"DOM.focus": () => ({}),
"DOM.resolveNode": () => ({ object: { objectId: "obj-1" } }),
"Runtime.callFunctionOn": () => {
abort.abort();
"Runtime.callFunctionOn": (params) => {
const fn = String((params as { functionDeclaration?: string }).functionDeclaration ?? "");
if (fn.includes("bsk-editable-state")) {
return {
result: {
value: {
supported: true,
connected: true,
focused: true,
value: "",
kind: "input",
},
},
};
}
if (fn.includes("bsk-editable-selection")) {
abort.abort();
return { result: { value: { selected: true } } };
}
return { result: { type: "undefined" } };
},
"Input.insertText": () => ({}),
@@ -717,6 +1025,204 @@ describe("handleFill", () => {
});
});
describe("handleType", () => {
it("requires an explicit target mode instead of silently using focus", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
const fake = makeFakeCdp({});
const missing = await handleType(
sm,
{ session_id: "aa11", text: "x" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(missing).toMatchObject({
code: "invalid_params",
message: expect.stringContaining("focused=true"),
});
const mixed = await handleType(
sm,
{ session_id: "aa11", ref: "@e1", focused: true, text: "x" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(mixed).toMatchObject({
code: "invalid_params",
message: expect.stringContaining("not both"),
});
expect(fake.sent).toHaveLength(0);
});
it("routes committed IME text through the explicit OOPIF target without DOM readback", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 77, {
tabId: 4,
frameId: "child-frame",
cdpSessionId: "child-session",
});
const fake = makeFakeCdp({ "DOM.scrollIntoViewIfNeeded": () => ({}) });
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child-frame",
parentFrameId: "main",
ownerBackendNodeId: 12,
target: { tabId: 4, sessionId: "child-session" },
},
],
}));
const childCalls: Array<{ method: string; params?: object }> = [];
fake.cdp.sendToTarget = vi.fn(async (_target, method, params) => {
childCalls.push({ method, params });
if (method === "DOM.describeNode") {
return { node: { backendNodeId: 77, nodeName: "TEXTAREA", attributes: [] } };
}
return {};
}) as CdpRunner["sendToTarget"];
const result = await handleType(
sm,
{ session_id: "aa11", ref: "@e1", text: "测试" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
if ("code" in result) throw new Error(JSON.stringify(result));
expect(result).toMatchObject({
tab_id: 4,
used_ref: "e1",
text_length: 2,
verification: "dispatched",
});
expect(childCalls.map((call) => call.method)).toEqual([
"DOM.describeNode",
"DOM.scrollIntoViewIfNeeded",
"DOM.focus",
"Input.dispatchKeyEvent",
"Input.insertText",
"Input.dispatchKeyEvent",
]);
expect(fake.sent.some((call) => call.method.startsWith("Input."))).toBe(false);
expect(childCalls.some((call) => call.method === "Runtime.callFunctionOn")).toBe(false);
});
it("uses the focused OOPIF only when focused mode resolves a text-entry target", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
const fake = makeFakeCdp({
"Runtime.evaluate": () => ({
result: { value: { hasFocus: true, activeTag: "iframe", textEntry: false } },
}),
});
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child-frame",
parentFrameId: "main",
target: { tabId: 4, sessionId: "child-session" },
},
],
}));
const childCalls: string[] = [];
fake.cdp.sendToTarget = vi.fn(async (_target, method) => {
childCalls.push(method);
if (method === "Runtime.evaluate") {
return {
result: { value: { hasFocus: true, activeTag: "textarea", textEntry: true } },
};
}
return {};
}) as CdpRunner["sendToTarget"];
const result = await handleType(
sm,
{ session_id: "aa11", focused: true, text: "A" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
if ("code" in result) throw new Error(JSON.stringify(result));
expect(result).toMatchObject({ text_length: 1, verification: "dispatched" });
expect(childCalls).toEqual([
"Runtime.evaluate",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
]);
expect(fake.sent.some((call) => call.method.startsWith("Input."))).toBe(false);
});
it("refuses focused mode when focus is not owned by a text-entry target", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
const fake = makeFakeCdp({
"Runtime.evaluate": () => ({
result: { value: { hasFocus: true, activeTag: "button", textEntry: false } },
}),
});
const result = await handleType(
sm,
{ session_id: "aa11", focused: true, text: "x" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(result).toMatchObject({
code: "cdp_failed",
data: { reason: "focus_target_unresolved", candidate_count: 0 },
});
expect(fake.sent.some((call) => call.method.startsWith("Input."))).toBe(false);
});
it("rejects explicit non-text input controls", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 77, { tabId: 4 });
const fake = makeFakeCdp({
"DOM.describeNode": () => ({
node: { backendNodeId: 77, nodeName: "INPUT", attributes: ["type", "checkbox"] },
}),
});
const result = await handleType(
sm,
{ session_id: "aa11", ref: "@e1", text: "x" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(result).toMatchObject({
code: "invalid_params",
data: { reason: "target_not_fillable" },
});
expect(fake.sent.some((call) => call.method.startsWith("Input."))).toBe(false);
});
it("rejects a Surface ref instead of treating it as a text target", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 77, {
tabId: 4,
kind: "surface",
capabilities: ["screenshot"],
});
const fake = makeFakeCdp({});
const result = await handleType(
sm,
{ session_id: "aa11", ref: "@e1", text: "x" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(result).toMatchObject({
code: "permission_denied",
data: { reason: "ref_capability_denied", required_capability: "interact" },
});
});
});
describe("parseKeySpec", () => {
it("splits compound expressions into modifiers + base key", () => {
expect(parseKeySpec("Ctrl+A")).toEqual({ key: "A", modifiers: ["ctrl"] });
@@ -855,6 +1361,125 @@ describe("handlePress", () => {
expect(res.key).toBe("Enter");
});
it("routes ref-targeted key events through the OOPIF session", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e1", 555, {
tabId: 4,
frameId: "child-frame",
cdpSessionId: "child-session",
});
const fake = makeFakeCdp({ "DOM.scrollIntoViewIfNeeded": () => ({}) });
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child-frame",
parentFrameId: "main",
ownerBackendNodeId: 12,
target: { tabId: 4, sessionId: "child-session" },
},
],
}));
const childCalls: string[] = [];
fake.cdp.sendToTarget = vi.fn(async (_target, method) => {
childCalls.push(method);
return {};
}) as CdpRunner["sendToTarget"];
const res = await handlePress(
sm,
{ session_id: "aa11", key: "Enter", ref: "@e1" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expectPressOk(res);
expect(childCalls).toEqual([
"DOM.scrollIntoViewIfNeeded",
"DOM.focus",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
]);
expect(fake.sent.some((call) => call.method === "Input.dispatchKeyEvent")).toBe(false);
});
it("routes an untargeted press to the uniquely focused OOPIF session", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
const fake = makeFakeCdp({
"Runtime.evaluate": () => ({
result: { value: { hasFocus: true, activeTag: "iframe" } },
}),
});
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child-frame",
parentFrameId: "main",
target: { tabId: 4, sessionId: "child-session" },
},
],
}));
const childCalls: string[] = [];
fake.cdp.sendToTarget = vi.fn(async (_target, method) => {
childCalls.push(method);
if (method === "Runtime.evaluate") {
return { result: { value: { hasFocus: true, activeTag: "textarea" } } };
}
return {};
}) as CdpRunner["sendToTarget"];
const res = await handlePress(
sm,
{ session_id: "aa11", key: "a" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expectPressOk(res);
expect(childCalls).toEqual([
"Runtime.evaluate",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
]);
});
it("refuses an untargeted press when focus ownership is ambiguous", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
const fake = makeFakeCdp({
"Runtime.evaluate": () => ({
result: { value: { hasFocus: true, activeTag: "input" } },
}),
});
fake.cdp.getFrameGraph = vi.fn(async () => ({
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{ frameId: "child", target: { tabId: 4, sessionId: "child-session" } },
],
}));
fake.cdp.sendToTarget = vi.fn(async () => ({
result: { value: { hasFocus: true, activeTag: "textarea" } },
})) as CdpRunner["sendToTarget"];
const res = await handlePress(
sm,
{ session_id: "aa11", key: "Enter" },
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
);
expect(res).toMatchObject({
code: "cdp_failed",
data: { reason: "focus_target_unresolved", candidate_count: 2 },
});
expect(fake.sent.some((call) => call.method === "Input.dispatchKeyEvent")).toBe(false);
});
it("stops before focus when abort fires after press scroll", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
@@ -0,0 +1,119 @@
import { describe, expect, it, vi } from "vitest";
import { dispatchMouseClick } from "../mouse-input";
import type { CdpRunner } from "../shared";
function fakeCdp(onSend?: (method: string, params: Record<string, unknown>) => void): {
cdp: CdpRunner;
events: Record<string, unknown>[];
} {
const events: Record<string, unknown>[] = [];
return {
events,
cdp: {
send: vi.fn(async (_tabId, method, params) => {
const event = params as Record<string, unknown>;
events.push(event);
onSend?.(method, event);
return {} as never;
}),
},
};
}
describe("dispatchMouseClick", () => {
it("emits one move, press, and release sequence", async () => {
const { cdp, events } = fakeCdp();
expect(
await dispatchMouseClick(
cdp,
4,
{ x: 12, y: 34 },
{
button: "left",
clickCount: 1,
modifiers: 0,
moveSettleMs: 0,
},
),
).toBe("completed");
expect(events).toEqual([
{
type: "mouseMoved",
x: 12,
y: 34,
modifiers: 0,
},
{
type: "mousePressed",
x: 12,
y: 34,
button: "left",
clickCount: 1,
modifiers: 0,
},
{
type: "mouseReleased",
x: 12,
y: 34,
button: "left",
clickCount: 1,
modifiers: 0,
},
]);
});
it("releases a pressed button when cancellation arrives", async () => {
const controller = new AbortController();
const { cdp, events } = fakeCdp((_method, event) => {
if (event.type === "mousePressed") controller.abort();
});
expect(
await dispatchMouseClick(
cdp,
4,
{ x: 1, y: 2 },
{
button: "left",
clickCount: 1,
modifiers: 0,
signal: controller.signal,
moveSettleMs: 0,
},
),
).toBe("cancelled");
expect(events.at(-1)).toMatchObject({ type: "mouseReleased" });
});
it("settles pointer-move hit testing before pressing", async () => {
vi.useFakeTimers();
try {
const { cdp, events } = fakeCdp();
const click = dispatchMouseClick(
cdp,
4,
{ x: 1, y: 2 },
{
button: "left",
clickCount: 1,
modifiers: 0,
moveSettleMs: 32,
},
);
await vi.advanceTimersByTimeAsync(31);
expect(events.map((event) => event.type)).toEqual(["mouseMoved"]);
await vi.advanceTimersByTimeAsync(1);
await click;
expect(events.map((event) => event.type)).toEqual([
"mouseMoved",
"mousePressed",
"mouseReleased",
]);
} finally {
vi.useRealTimers();
}
});
});
@@ -67,6 +67,9 @@ function makeFakeCdp(handlers: Record<string, (params?: object) => unknown>) {
if (!handler && method === "Page.getLayoutMetrics") {
return { cssLayoutViewport: { clientWidth: 1280, clientHeight: 720 } };
}
if (!handler && method === "Page.getFrameTree") {
return { frameTree: { frame: { id: "main", loaderId: "loader-1", url: "https://test/" } } };
}
if (!handler) throw new Error(`unexpected CDP call ${method}`);
return handler(params);
});
@@ -300,6 +303,82 @@ describe("handleScreenshot", () => {
expect(clip).toMatchObject({ x: 10, y: 20, width: 100, height: 40 });
});
it("captures a bounded visible crop for a visual surface without scrolling it", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e5", 999, {
tabId: 7,
kind: "surface",
capabilities: ["screenshot"],
});
const { cdp, sent } = makeFakeCdp({
"Page.getLayoutMetrics": () => ({
cssLayoutViewport: { clientWidth: 4096, clientHeight: 4096 },
}),
"DOM.getContentQuads": () => ({ quads: [[0, 0, 4096, 0, 4096, 4096, 0, 4096]] }),
"Page.captureScreenshot": () => ({ data: TINY_PNG }),
});
const res = await handleScreenshot(
sm,
{ session_id: "aa11", ref: "@e5", tab_id: 7 },
makeScreenshotDeps({
cdp,
get: vi.fn(async () => ({ id: 7, windowId: 100, active: false }) as chrome.tabs.Tab),
query: vi.fn(),
captureVisibleTab: vi.fn(),
}),
);
if ("code" in res) throw new Error(`unexpected error: ${JSON.stringify(res)}`);
expect(sent.some((call) => call.method === "DOM.scrollIntoViewIfNeeded")).toBe(false);
const clip = sent.find((call) => call.method === "Page.captureScreenshot")?.params as {
clip?: { width: number; height: number; scale: number };
};
expect(clip.clip).toMatchObject({ width: 4096, height: 4096 });
expect(clip.clip?.scale).toBeCloseTo(Math.sqrt(4_000_000 / (4096 * 4096)));
expect(res.capture).toMatchObject({
surface_ref: "@e5",
coordinate_space: "capture-image-pixel",
});
expect(ctx.surfaceCaptures.size()).toBe(1);
});
it("crops a visual surface screenshot to its observation-time visible region", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e5", 999, {
tabId: 7,
kind: "surface",
visibleRect: { x: 25, y: 30, w: 50, h: 40 },
});
const { cdp, sent } = makeFakeCdp({
"Page.getLayoutMetrics": () => ({
cssLayoutViewport: { clientWidth: 800, clientHeight: 600 },
}),
"DOM.getContentQuads": () => ({ quads: [[0, 0, 200, 0, 200, 100, 0, 100]] }),
"Page.captureScreenshot": () => ({ data: TINY_PNG }),
});
const res = await handleScreenshot(
sm,
{ session_id: "aa11", ref: "@e5", tab_id: 7 },
makeScreenshotDeps({
cdp,
get: vi.fn(async () => ({ id: 7, windowId: 100, active: false }) as chrome.tabs.Tab),
query: vi.fn(),
captureVisibleTab: vi.fn(),
}),
);
if ("code" in res) throw new Error(`unexpected error: ${JSON.stringify(res)}`);
const clip = sent.find((call) => call.method === "Page.captureScreenshot")?.params as {
clip?: { x: number; y: number; width: number; height: number };
};
expect(clip.clip).toMatchObject({ x: 25, y: 30, width: 50, height: 40 });
expect(res.capture?.id).toMatch(/^sc_/);
});
it("returns not_found for unknown ref", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
@@ -2693,6 +2772,85 @@ describe("handleSnapshot", () => {
);
});
it("discovers rendered canvases only in observe and stores a screenshot-only ref", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
const root: CdpAxNode = {
nodeId: "1",
role: { type: "role", value: "RootWebArea" },
name: { type: "computedString", value: "Canvas app" },
backendDOMNodeId: 100,
};
const strings = ["body", "canvas", "static", "auto"];
const i = (value: string) => strings.indexOf(value);
const send = vi.fn(async (_tabId: number, method: string) => {
if (method === "Accessibility.enable" || method === "DOMSnapshot.enable") return {};
if (method === "Accessibility.getFullAXTree") return { nodes: [root] };
if (method === "Page.getLayoutMetrics") {
return { cssLayoutViewport: { clientWidth: 1000, clientHeight: 800, pageX: 0, pageY: 0 } };
}
if (method === "DOMSnapshot.captureSnapshot") {
return {
strings,
documents: [
{
nodes: {
parentIndex: [-1, 0],
nodeName: [i("body"), i("canvas")],
backendNodeId: [100, 200],
attributes: [[], []],
},
layout: {
nodeIndex: [0, 1],
styles: [
[i("static"), i("auto"), i("auto")],
[i("static"), i("auto"), i("auto")],
],
bounds: [
[0, 0, 1000, 800],
[20, 30, 800, 500],
],
paintOrders: [0, 1],
},
},
],
};
}
throw new Error(`unexpected CDP method ${method}`);
});
const deps = {
cdp: {
send: send as unknown as <T = unknown>(
tabId: number,
method: string,
params?: object,
) => Promise<T>,
trackSessionTab: vi.fn(),
},
tabsApi: {
get: vi.fn(
async (tabId: number) => ({ id: tabId, windowId: 100, active: true }) as chrome.tabs.Tab,
),
query: vi.fn(async () => [{ id: 4, windowId: 100, active: true } as chrome.tabs.Tab]),
},
conditionalSurfaceProbe: false,
};
const observed = await handleObserve(sm, { session_id: "aa11" }, deps);
if ("code" in observed) throw new Error(`unexpected error: ${JSON.stringify(observed)}`);
expect(observed.text).toContain('@e1 surface "canvas visual surface"');
expect(ctx.refStore.resolveEntry("e1")).toMatchObject({
backendNodeId: 200,
kind: "surface",
capabilities: ["screenshot"],
});
const snapshot = await handleSnapshot(sm, { session_id: "aa11" }, deps);
if ("code" in snapshot) throw new Error(`unexpected error: ${JSON.stringify(snapshot)}`);
expect(snapshot.text).not.toContain("visual surface");
expect(snapshot.ref_count).toBe(0);
});
it("allows passive snapshots of explicit user-window tabs", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
await sm.start("aa11");
@@ -252,12 +252,23 @@ describe("handleSessionStop with auto-return", () => {
expect(aw.remove).not.toHaveBeenCalled();
});
it("clears the RefStore before window teardown", async () => {
it("clears refs and Surface captures before window teardown", async () => {
const aw = fakeAgentWindow([100]);
const sm = new SessionManager({ agentWindow: aw });
const ctx = await sm.start("aa11");
// Insert a fake ref so we can verify clear() ran.
ctx.refStore.set("e1", 123, { tabId: 7 });
ctx.surfaceCaptures.create({
sessionId: "aa11",
tabId: 7,
navigationIdentity: "navigation",
surface: { ref: "e1", backendNodeId: 123, observationGeneration: 0 },
topViewportRect: { x: 0, y: 0, w: 100, h: 50 },
imageWidth: 100,
imageHeight: 50,
viewportSignature: "viewport",
frameProjectionSignature: "frame",
});
const state: FakeState = {
tabs: new Map(),
windowsClosed: new Set(),
@@ -266,5 +277,6 @@ describe("handleSessionStop with auto-return", () => {
const { tabs, windows } = makeApis(state);
await handleSessionStop(sm, { session_id: "aa11" }, { tabManagement: { tabs, windows } });
expect(ctx.refStore.isEmpty()).toBe(true);
expect(ctx.surfaceCaptures.size()).toBe(0);
});
});
@@ -24,10 +24,16 @@ describe("lookupSnapshotRef", () => {
expect(lookupSnapshotRef(ctx, "@e3", 4)).toEqual({
backendNodeId: 1234,
refKey: "e3",
kind: "dom",
capabilities: ["interact", "screenshot"],
generation: 0,
});
expect(lookupSnapshotRef(ctx, "e3", 4)).toEqual({
backendNodeId: 1234,
refKey: "e3",
kind: "dom",
capabilities: ["interact", "screenshot"],
generation: 0,
});
});
@@ -53,6 +59,8 @@ describe("resolveSnapshotRef", () => {
tabId: 4,
frameId: "child-frame",
cdpSessionId: "child-session",
kind: "dom",
capabilities: ["interact", "screenshot"],
});
const expected = {
@@ -60,6 +68,9 @@ describe("resolveSnapshotRef", () => {
refKey: "e3",
frameId: "child-frame",
cdpSessionId: "child-session",
kind: "dom" as const,
capabilities: ["interact", "screenshot"] as const,
generation: 0,
};
expect(lookupSnapshotRef(ctx, "@e3", 4)).toEqual(expected);
expect(resolveSnapshotRef(ctx, "@e3", 4)).toEqual(expected);
@@ -105,6 +116,29 @@ describe("resolveSnapshotRef", () => {
expect(resolveSnapshotRef(ctx, "@e3", 4)).toEqual({
backendNodeId: 1234,
refKey: "e3",
kind: "dom",
capabilities: ["interact", "screenshot"],
generation: 0,
});
});
it("rejects an operation outside the ref's declared capabilities", async () => {
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
const ctx = await sm.start("aa11");
ctx.refStore.set("e3", 1234, {
tabId: 4,
kind: "surface",
capabilities: ["screenshot"],
});
expect(resolveSnapshotRef(ctx, "@e3", 4, "interact")).toMatchObject({
code: "permission_denied",
message: "ref @e3 does not support interact",
data: {
reason: "ref_capability_denied",
required_capability: "interact",
kind: "surface",
},
});
});
});
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import {
mapImagePointToViewport,
pointInRegion,
sameRect,
surfaceVisibleRect,
} from "../surface-coordinate";
describe("surface coordinate mapping", () => {
it("maps capture image pixels through the actual screenshot dimensions", () => {
expect(mapImagePointToViewport({ x: 100, y: 50, w: 400, h: 200 }, 800, 400, 200, 100)).toEqual({
x: 200,
y: 100,
});
});
it("rejects invalid image coordinates and dimensions", () => {
const rect = { x: 0, y: 0, w: 100, h: 50 };
expect(mapImagePointToViewport(rect, 100, 50, -1, 0)).toBeNull();
expect(mapImagePointToViewport(rect, 100, 50, 100, 0)).toBeNull();
expect(mapImagePointToViewport(rect, 100, 50, 0, 50)).toBeNull();
expect(mapImagePointToViewport(rect, 100, 50, Number.NaN, 0)).toBeNull();
expect(mapImagePointToViewport(rect, 100, 50, Number.POSITIVE_INFINITY, 0)).toBeNull();
expect(mapImagePointToViewport(rect, 0, 50, 0, 0)).toBeNull();
});
it("intersects live and observed visible regions and compares them strictly", () => {
const clipped = surfaceVisibleRect(
{ x: 0, y: 0, width: 200, height: 100 },
{ x: 25, y: 30, w: 50, h: 40 },
);
expect(clipped).toEqual({ x: 25, y: 30, w: 50, h: 40 });
expect(sameRect(clipped as NonNullable<typeof clipped>, { x: 25, y: 30, w: 50, h: 40 })).toBe(
true,
);
expect(sameRect(clipped as NonNullable<typeof clipped>, { x: 26, y: 30, w: 50, h: 40 })).toBe(
false,
);
});
it("checks the projected visible region rather than only its bounding box", () => {
const triangle = [
[
{ x: 0, y: 0 },
{ x: 100, y: 0 },
{ x: 0, y: 100 },
],
];
expect(pointInRegion({ x: 20, y: 20 }, triangle)).toBe(true);
expect(pointInRegion({ x: 90, y: 90 }, triangle)).toBe(false);
});
});
@@ -0,0 +1,306 @@
import { describe, expect, it, vi } from "vitest";
import { SessionManager } from "@/session-manager/manager";
import type { CdpRunner } from "../shared";
import {
captureSurfaceEnvironment,
resolveSurfacePointerTarget,
SURFACE_POINTER_MOVE_SETTLE_MS,
} from "../surface-target";
function fakeAgentWindow() {
return {
create: vi.fn(async () => 100),
remove: vi.fn(async () => {}),
ensureActiveTab: vi.fn(async () => {}),
};
}
function fakeBrowser() {
let loaderId = "loader-1";
let pageY = 0;
let quad = [10, 20, 110, 20, 110, 60, 10, 60];
const sent: Array<{ method: string; params?: object }> = [];
const cdp: CdpRunner = {
send: vi.fn(async (_tabId: number, method: string, params?: object) => {
sent.push({ method, params });
if (method === "Page.getFrameTree") {
return {
frameTree: { frame: { id: "main", loaderId, url: "https://fixture.test/" } },
} as never;
}
if (method === "Page.getLayoutMetrics") {
return {
cssLayoutViewport: { clientWidth: 800, clientHeight: 600, pageX: 0, pageY },
cssVisualViewport: {
clientWidth: 800,
clientHeight: 600,
pageX: 0,
pageY,
scale: 1,
},
} as never;
}
if (method === "DOM.getContentQuads") return { quads: [quad] } as never;
throw new Error(`unexpected CDP call ${method}`);
}) as CdpRunner["send"],
trackSessionTab: vi.fn(),
};
return {
cdp,
sent,
setLoaderId: (value: string) => {
loaderId = value;
},
setPageY: (value: number) => {
pageY = value;
},
setQuad: (value: number[]) => {
quad = value;
},
};
}
async function setupCapture() {
const manager = new SessionManager({ agentWindow: fakeAgentWindow() });
const context = await manager.start("aa11");
context.refStore.set("e3", 99, {
tabId: 4,
kind: "surface",
visibleRect: { x: 10, y: 20, w: 100, h: 40 },
});
const browser = fakeBrowser();
const environment = await captureSurfaceEnvironment(browser.cdp, 4, undefined);
if ("code" in environment) throw new Error(environment.message);
const entry = context.refStore.resolveEntry("e3");
if (!entry) throw new Error("missing ref");
const capture = context.surfaceCaptures.create({
sessionId: "aa11",
tabId: 4,
navigationIdentity: environment.navigationIdentity,
surface: {
ref: "e3",
backendNodeId: 99,
observationGeneration: entry.generation,
},
topViewportRect: { x: 10, y: 20, w: 100, h: 40 },
imageWidth: 200,
imageHeight: 80,
viewportSignature: environment.viewportSignature,
frameProjectionSignature: environment.frameProjectionSignature,
});
return { manager, context, browser, capture };
}
function pointParams(captureId: string) {
return {
ref: "@e3",
captureId,
imageX: 50,
imageY: 20,
};
}
describe("Surface screenshot-bound pointer target", () => {
it("maps one fresh capture coordinate without executing an action", async () => {
const { context, browser, capture } = await setupCapture();
const result = await resolveSurfacePointerTarget(
context,
{ tabId: 4 },
pointParams(capture.id),
{ cdp: browser.cdp },
);
if ("code" in result) throw new Error(JSON.stringify(result));
expect(result).toMatchObject({
usedRef: "e3",
point: { x: 35, y: 30 },
moveSettleMs: SURFACE_POINTER_MOVE_SETTLE_MS,
capture: { id: capture.id, imageX: 50, imageY: 20 },
});
expect(browser.sent.some((call) => call.method === "Input.dispatchMouseEvent")).toBe(false);
const repeated = await resolveSurfacePointerTarget(
context,
{ tabId: 4 },
pointParams(capture.id),
{ cdp: browser.cdp },
);
expect(repeated).toMatchObject({
code: "permission_denied",
data: { reason: "surface_capture_consumed" },
});
});
it("rejects a new observation generation before sending input", async () => {
const { context, browser, capture } = await setupCapture();
context.refStore.replace([
[
"e3",
{
backendNodeId: 99,
tabId: 4,
kind: "surface" as const,
visibleRect: { x: 10, y: 20, w: 100, h: 40 },
},
],
]);
const result = await resolveSurfacePointerTarget(
context,
{ tabId: 4 },
pointParams(capture.id),
{ cdp: browser.cdp },
);
expect(result).toMatchObject({
code: "permission_denied",
data: { reason: "surface_capture_stale" },
});
expect(browser.sent.some((call) => call.method === "Input.dispatchMouseEvent")).toBe(false);
});
it("rejects navigation, scroll, and visible geometry changes", async () => {
for (const mutate of [
(browser: ReturnType<typeof fakeBrowser>) => browser.setLoaderId("loader-2"),
(browser: ReturnType<typeof fakeBrowser>) => browser.setPageY(20),
(browser: ReturnType<typeof fakeBrowser>) =>
browser.setQuad([11, 20, 111, 20, 111, 60, 11, 60]),
]) {
const { context, browser, capture } = await setupCapture();
mutate(browser);
const result = await resolveSurfacePointerTarget(
context,
{ tabId: 4 },
pointParams(capture.id),
{ cdp: browser.cdp },
);
expect(result).toMatchObject({
code: "permission_denied",
data: { reason: "surface_capture_stale" },
});
expect(browser.sent.some((call) => call.method === "Input.dispatchMouseEvent")).toBe(false);
}
});
it("consumes the capture when coordinate validation fails", async () => {
const invalid = await setupCapture();
const outside = await resolveSurfacePointerTarget(
invalid.context,
{ tabId: 4 },
{ ...pointParams(invalid.capture.id), imageX: 200 },
{ cdp: invalid.browser.cdp },
);
expect(outside).toMatchObject({
code: "invalid_params",
data: { reason: "surface_coordinate_invalid" },
});
expect(
await resolveSurfacePointerTarget(
invalid.context,
{ tabId: 4 },
pointParams(invalid.capture.id),
{ cdp: invalid.browser.cdp },
),
).toMatchObject({ data: { reason: "surface_capture_consumed" } });
});
it("maps image coordinates through an OOPIF frame projection", async () => {
const manager = new SessionManager({ agentWindow: fakeAgentWindow() });
const context = await manager.start("aa11");
context.refStore.set("e3", 99, {
tabId: 4,
frameId: "child",
cdpSessionId: "child-session",
kind: "surface",
visibleRect: { x: 120, y: 110, w: 100, h: 40 },
});
const graph = {
rootFrameId: "main",
frames: [
{ frameId: "main", target: { tabId: 4 } },
{
frameId: "child",
parentFrameId: "main",
ownerBackendNodeId: 77,
target: { tabId: 4, sessionId: "child-session" },
},
],
};
const sent: Array<{ method: string; params?: object }> = [];
const cdp: CdpRunner = {
send: vi.fn(async (_tabId: number, method: string, params?: object) => {
sent.push({ method, params });
if (method === "Page.getFrameTree") {
return {
frameTree: {
frame: { id: "main", loaderId: "loader-1", url: "https://fixture.test/" },
},
} as never;
}
if (method === "Page.getLayoutMetrics") {
return {
cssLayoutViewport: { clientWidth: 800, clientHeight: 600, pageX: 0, pageY: 0 },
cssVisualViewport: {
clientWidth: 800,
clientHeight: 600,
pageX: 0,
pageY: 0,
scale: 1,
},
} as never;
}
if (method === "DOM.getBoxModel") {
return { model: { content: [100, 100, 300, 100, 300, 200, 100, 200] } } as never;
}
if (method === "Input.dispatchMouseEvent") return {} as never;
throw new Error(`unexpected root CDP call ${method}`);
}) as CdpRunner["send"],
sendToTarget: vi.fn(async (_target, method) => {
if (method === "DOM.getContentQuads") {
return { quads: [[20, 10, 120, 10, 120, 50, 20, 50]] } as never;
}
if (method === "Page.getLayoutMetrics") {
return { cssLayoutViewport: { clientWidth: 200, clientHeight: 100 } } as never;
}
throw new Error(`unexpected child CDP call ${method}`);
}) as CdpRunner["sendToTarget"],
getFrameGraph: vi.fn(async () => graph),
trackSessionTab: vi.fn(),
};
const environment = await captureSurfaceEnvironment(cdp, 4, "child");
if ("code" in environment) throw new Error(environment.message);
const entry = context.refStore.resolveEntry("e3");
if (!entry) throw new Error("missing ref");
const capture = context.surfaceCaptures.create({
sessionId: "aa11",
tabId: 4,
navigationIdentity: environment.navigationIdentity,
surface: {
ref: "e3",
frameId: "child",
backendNodeId: 99,
observationGeneration: entry.generation,
},
topViewportRect: { x: 120, y: 110, w: 100, h: 40 },
imageWidth: 200,
imageHeight: 80,
viewportSignature: environment.viewportSignature,
frameProjectionSignature: environment.frameProjectionSignature,
});
const result = await resolveSurfacePointerTarget(
context,
{ tabId: 4 },
{
ref: "@e3",
captureId: capture.id,
imageX: 100,
imageY: 40,
},
{ cdp },
);
if ("code" in result) throw new Error(JSON.stringify(result));
expect(result).toMatchObject({ point: { x: 170, y: 130 } });
expect(sent.some((call) => call.method === "Input.dispatchMouseEvent")).toBe(false);
});
});
@@ -0,0 +1,128 @@
import { describe, expect, it, vi } from "vitest";
import type { CdpRunner } from "../shared";
import { dispatchTextInput } from "../text-input";
function makeCdp(onSend?: (method: string, params?: object) => void) {
const sent: Array<{ method: string; params?: object }> = [];
const send = vi.fn(async <T>(_tabId: number, method: string, params?: object): Promise<T> => {
sent.push({ method, params });
onSend?.(method, params);
return {} as T;
});
return { cdp: { send } as CdpRunner, sent };
}
describe("dispatchTextInput", () => {
it("types ASCII through complete keydown, char, and keyup sequences", async () => {
const fake = makeCdp();
const result = await dispatchTextInput(fake.cdp, 4, "Ab");
expect(result).toBeNull();
expect(
fake.sent.map((call) => `${call.method}:${(call.params as { type?: string }).type}`),
).toEqual([
"Input.dispatchKeyEvent:rawKeyDown",
"Input.dispatchKeyEvent:char",
"Input.dispatchKeyEvent:keyUp",
"Input.dispatchKeyEvent:rawKeyDown",
"Input.dispatchKeyEvent:char",
"Input.dispatchKeyEvent:keyUp",
]);
expect(fake.sent[0].params).toMatchObject({ key: "A", code: "KeyA", modifiers: 8 });
expect(fake.sent[1].params).toMatchObject({ text: "A" });
});
it("types non-ASCII through the committed IME insertion path", async () => {
const fake = makeCdp();
const result = await dispatchTextInput(fake.cdp, 4, "测试");
expect(result).toBeNull();
expect(fake.sent).toEqual([
{
method: "Input.dispatchKeyEvent",
params: {
type: "rawKeyDown",
key: "Process",
code: "",
windowsVirtualKeyCode: 229,
nativeVirtualKeyCode: 229,
modifiers: 0,
},
},
{ method: "Input.insertText", params: { text: "测试" } },
{
method: "Input.dispatchKeyEvent",
params: {
type: "keyUp",
key: "Process",
code: "",
windowsVirtualKeyCode: 229,
nativeVirtualKeyCode: 229,
modifiers: 0,
},
},
]);
});
it("preserves text order across keyboard and IME segments", async () => {
const fake = makeCdp();
const result = await dispatchTextInput(fake.cdp, 4, "A测试1");
expect(result).toBeNull();
const meaningful = fake.sent.flatMap((call) => {
if (call.method === "Input.insertText") {
return [`ime:${(call.params as { text: string }).text}`];
}
if (
call.method === "Input.dispatchKeyEvent" &&
(call.params as { type?: string }).type === "char"
) {
return [`key:${(call.params as { text: string }).text}`];
}
return [];
});
expect(meaningful).toEqual(["key:A", "ime:测试", "key:1"]);
});
it("reports cancellation observed after an accepted IME insertion", async () => {
const abort = new AbortController();
const fake = makeCdp((method) => {
if (method === "Input.insertText") abort.abort();
});
const result = await dispatchTextInput(fake.cdp, 4, "测试", abort.signal);
expect(result).toMatchObject({ code: "cancelled" });
expect(fake.sent.map((call) => call.method)).toEqual([
"Input.dispatchKeyEvent",
"Input.insertText",
"Input.dispatchKeyEvent",
]);
expect(fake.sent.at(-1)?.params).toMatchObject({ type: "keyUp", key: "Process" });
});
it("releases the IME process key without committing when cancellation follows keydown", async () => {
const abort = new AbortController();
const fake = makeCdp((method, params) => {
if (
method === "Input.dispatchKeyEvent" &&
(params as { type?: string }).type === "rawKeyDown"
) {
abort.abort();
}
});
const result = await dispatchTextInput(fake.cdp, 4, "测试", abort.signal);
expect(result).toMatchObject({ code: "cancelled" });
expect(fake.sent.map((call) => call.method)).toEqual([
"Input.dispatchKeyEvent",
"Input.dispatchKeyEvent",
]);
expect(fake.sent[0].params).toMatchObject({ type: "rawKeyDown", key: "Process" });
expect(fake.sent[1].params).toMatchObject({ type: "keyUp", key: "Process" });
});
});
+21 -1
View File
@@ -28,6 +28,7 @@ import type {
ScreenshotParams,
SelectParams,
SnapshotParams,
TypeParams,
WaitForNavigationParams,
} from "@/transport/types";
import { isRequestFrame } from "@/transport/types";
@@ -35,7 +36,14 @@ import { handleConsole } from "./console";
import { type EmulateCdpRunner, handleEmulate } from "./emulate";
import { handleEvaluate } from "./evaluate";
import { handleRequestHelp } from "./human-loop";
import { handleClick, handleFill, handleHover, handlePress, handleSelect } from "./interaction";
import {
handleClick,
handleFill,
handleHover,
handlePress,
handleSelect,
handleType,
} from "./interaction";
import {
handleNavigate,
handleNavigateBack,
@@ -491,6 +499,17 @@ export class ToolDispatcher {
),
signal,
);
case "tool.type":
return this.withHoverReleaseForRequest(
req.params as TypeParams,
() =>
handleType(
this.sessions,
req.params as TypeParams,
this.cdp ? { cdp: this.cdp, tabsApi: chromeTabsApi, signal } : undefined,
),
signal,
);
case "tool.press":
return this.withHoverReleaseForRequest(
req.params as PressParams,
@@ -717,6 +736,7 @@ function sessionIdForBrowserControlMethod(req: RequestFrame): string | null {
case "tool.click":
case "tool.hover":
case "tool.fill":
case "tool.type":
case "tool.press":
case "tool.select":
case "tool.evaluate":
+282
View File
@@ -0,0 +1,282 @@
// Browser-native editing transaction for input, textarea, and contenteditable
// targets. The CDP target/session is selected by interaction.ts; this module
// owns the shorter-lived editable identity inside that target.
import type { RpcError } from "@/transport/types";
import { rpcError } from "./errors";
import type { CdpRunner } from "./shared";
interface EditableState {
supported: boolean;
connected: boolean;
focused: boolean;
value: string;
kind: "input" | "textarea" | "contenteditable" | "unsupported";
}
export interface EditableFillResult {
value: string;
replacedNode: boolean;
}
function cancelled(signal: AbortSignal | undefined): RpcError | null {
return signal?.aborted ? { code: "cancelled", message: "fill aborted" } : null;
}
async function inspectEditable(
cdp: CdpRunner,
tabId: number,
objectId: string,
): Promise<EditableState> {
const reply = await cdp.send<{
result?: { value?: EditableState };
}>(tabId, "Runtime.callFunctionOn", {
objectId,
functionDeclaration: `function() {
/* bsk-editable-state */
const doc = this.ownerDocument;
const focused = !!doc && doc.activeElement === this;
if (this instanceof HTMLInputElement) {
return { supported: true, connected: this.isConnected, focused,
value: this.value, kind: 'input' };
}
if (this instanceof HTMLTextAreaElement) {
return { supported: true, connected: this.isConnected, focused,
value: this.value, kind: 'textarea' };
}
if (this.isContentEditable) {
return { supported: true, connected: this.isConnected, focused,
value: this.innerText ?? this.textContent ?? '', kind: 'contenteditable' };
}
return { supported: false, connected: this.isConnected === true, focused,
value: '', kind: 'unsupported' };
}`,
returnByValue: true,
});
const state = reply.result?.value;
if (!state || typeof state.value !== "string") {
throw new Error("editable state probe returned no value");
}
return state;
}
/**
* Return the active editable from the anchor's own document. Using the
* anchor's execution context also works for same-process nested frames, where
* a target-level Runtime.evaluate would otherwise see the top document.
*/
async function focusedEditableFromAnchor(
cdp: CdpRunner,
tabId: number,
anchorObjectId: string,
): Promise<string | null> {
const reply = await cdp.send<{
result?: { objectId?: string; subtype?: string };
}>(tabId, "Runtime.callFunctionOn", {
objectId: anchorObjectId,
functionDeclaration: `function() {
/* bsk-editable-live */
const active = this.ownerDocument?.activeElement;
if (!active) return null;
const editable = active instanceof HTMLInputElement ||
active instanceof HTMLTextAreaElement || active.isContentEditable;
return editable ? active : null;
}`,
returnByValue: false,
});
if (reply.result?.subtype === "null") return null;
return typeof reply.result?.objectId === "string" ? reply.result.objectId : null;
}
async function resolveLiveEditable(
cdp: CdpRunner,
tabId: number,
anchorObjectId: string,
): Promise<{ objectId: string; state: EditableState; replaced: boolean } | RpcError> {
const anchor = await inspectEditable(cdp, tabId, anchorObjectId);
if (anchor.supported && anchor.connected && anchor.focused) {
return { objectId: anchorObjectId, state: anchor, replaced: false };
}
const focusedObjectId = await focusedEditableFromAnchor(cdp, tabId, anchorObjectId);
if (!focusedObjectId) {
return rpcError(
"cdp_failed",
"input_not_applied",
"the target editable lost focus or detached before input",
{ phase: "resolve_live_editable" },
);
}
const focused = await inspectEditable(cdp, tabId, focusedObjectId);
if (!focused.supported || !focused.connected || !focused.focused) {
return rpcError(
"cdp_failed",
"input_not_applied",
"the replacement editable was not live and focused",
{ phase: "resolve_live_editable" },
);
}
return { objectId: focusedObjectId, state: focused, replaced: true };
}
async function selectEditableContents(
cdp: CdpRunner,
tabId: number,
objectId: string,
): Promise<void> {
const reply = await cdp.send<{
result?: { value?: { selected?: boolean } };
}>(tabId, "Runtime.callFunctionOn", {
objectId,
functionDeclaration: `function() {
/* bsk-editable-selection */
if (!this.isConnected || this.ownerDocument?.activeElement !== this) {
return { selected: false };
}
if (this instanceof HTMLInputElement || this instanceof HTMLTextAreaElement) {
try {
this.setSelectionRange(0, this.value.length);
} catch {
if (typeof this.select !== 'function') return { selected: false };
this.select();
}
return { selected: true };
}
if (this.isContentEditable) {
const selection = this.ownerDocument.getSelection();
if (!selection) return { selected: false };
const range = this.ownerDocument.createRange();
range.selectNodeContents(this);
selection.removeAllRanges();
selection.addRange(range);
return { selected: true };
}
return { selected: false };
}`,
returnByValue: true,
});
if (reply.result?.value?.selected !== true) {
throw new Error("could not select the live editable contents");
}
}
async function waitForEditableSettlement(
cdp: CdpRunner,
tabId: number,
anchorObjectId: string,
): Promise<void> {
await cdp.send(tabId, "Runtime.callFunctionOn", {
objectId: anchorObjectId,
functionDeclaration: `function() {
/* bsk-editable-sync */
return new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve();
};
const timer = setTimeout(finish, 100);
const view = this.ownerDocument?.defaultView;
if (!view || typeof view.requestAnimationFrame !== 'function') { finish(); return; }
view.requestAnimationFrame(() => view.requestAnimationFrame(finish));
});
}`,
awaitPromise: true,
returnByValue: true,
});
}
async function deleteSelection(cdp: CdpRunner, tabId: number): Promise<void> {
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "rawKeyDown",
key: "Backspace",
code: "Backspace",
windowsVirtualKeyCode: 8,
});
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "keyUp",
key: "Backspace",
code: "Backspace",
windowsVirtualKeyCode: 8,
});
}
/**
* Replace or append text through Chromium's editing pipeline. No value setter
* or synthetic DOM events are used: controlled components observe the same
* beforeinput/input path as a real browser edit. The live editable is resolved
* again after settlement so a framework may remount it without producing a
* false failure or a stale-object success.
*/
export async function fillEditable(
cdp: CdpRunner,
tabId: number,
anchorObjectId: string,
value: string,
clearBefore: boolean,
signal?: AbortSignal,
): Promise<EditableFillResult | RpcError> {
try {
const abortedBefore = cancelled(signal);
if (abortedBefore) return abortedBefore;
const initial = await resolveLiveEditable(cdp, tabId, anchorObjectId);
if ("code" in initial) return initial;
let replacedNode = initial.replaced;
if (clearBefore) await selectEditableContents(cdp, tabId, initial.objectId);
const abortedAfterSelection = cancelled(signal);
if (abortedAfterSelection) return abortedAfterSelection;
if (value.length > 0) {
await cdp.send(tabId, "Input.insertText", { text: value });
} else if (clearBefore) {
await deleteSelection(cdp, tabId);
}
const abortedAfterInput = cancelled(signal);
if (abortedAfterInput) return abortedAfterInput;
await waitForEditableSettlement(cdp, tabId, initial.objectId);
const abortedAfterSettlement = cancelled(signal);
if (abortedAfterSettlement) return abortedAfterSettlement;
let finalObjectId = initial.objectId;
let finalState = await inspectEditable(cdp, tabId, finalObjectId);
if (!finalState.connected || !finalState.focused) {
const live = await resolveLiveEditable(cdp, tabId, initial.objectId);
if ("code" in live) return live;
finalObjectId = live.objectId;
finalState = live.state;
replacedNode ||= live.replaced || finalObjectId !== initial.objectId;
}
const applied = clearBefore
? finalState.value === value
: value.length === 0 || finalState.value.includes(value);
if (!finalState.supported || !applied) {
return rpcError(
"cdp_failed",
"input_not_applied",
"the page did not retain the requested input value",
{
expected_value_length: value.length,
actual_value_length: finalState.value.length,
phase: "readback",
editable_replaced: replacedNode,
},
);
}
return { value: finalState.value, replacedNode };
} catch (err) {
return rpcError(
"cdp_failed",
"input_not_applied",
err instanceof Error ? err.message : String(err),
{ phase: "edit_transaction" },
);
}
}
+377 -131
View File
@@ -1,5 +1,5 @@
// DOM interaction tools — `tool.click`, `tool.fill`, `tool.press`, and
// `tool.select`.
// DOM interaction tools — `tool.click`, `tool.fill`, `tool.type`,
// `tool.press`, and `tool.select`.
//
// All interaction tools:
// 1. Resolve target tab (sandbox: must be inside Agent Window).
@@ -11,7 +11,7 @@
// commands.
import { ChromiumCdp } from "@/browser-driver/chromium-cdp";
import type { CdpTarget } from "@/browser-driver/frame-graph";
import { type CdpTarget, cdpTargetKey } from "@/browser-driver/frame-graph";
import type { SessionContext, SessionManager } from "@/session-manager/manager";
import type {
ClickParams,
@@ -27,11 +27,15 @@ import type {
RpcError,
SelectParams,
SelectResult,
TypeParams,
TypeResult,
} from "@/transport/types";
import { attachDialogs, markDialogCursor } from "./dialogs";
import { fillEditable } from "./editable-input";
import { backendNodeToObject } from "./element-geometry";
import { rpcError } from "./errors";
import { resolveNodeGeometry, scrollElementAndFramesIntoView } from "./frame-geometry";
import { dispatchMouseClick } from "./mouse-input";
import {
type CdpRunner,
type ChromeTabsApi,
@@ -43,6 +47,8 @@ import {
resolveTargetTab,
} from "./shared";
import { resolveSnapshotRef } from "./snapshot-ref";
import { resolveSurfacePointerTarget } from "./surface-target";
import { dispatchTextInput } from "./text-input";
export interface InteractionDeps {
cdp: CdpRunner;
@@ -159,7 +165,7 @@ async function resolveBackendNode(
};
}
if (hasRef) {
const resolved = resolveSnapshotRef(ctx, params.ref as string, target.tabId);
const resolved = resolveSnapshotRef(ctx, params.ref as string, target.tabId, "interact");
if (isRpcError(resolved)) return resolved;
return {
backendNodeId: resolved.backendNodeId,
@@ -215,15 +221,146 @@ async function resolveBackendNode(
}
}
interface InputDispatchContext {
target: CdpTarget;
cdp: CdpRunner;
backendNodeId?: number;
frameId?: string;
usedRef?: string;
usedSelector?: string;
}
function inputContextForNode(
cdp: CdpRunner,
node: Awaited<ReturnType<typeof resolveBackendNode>>,
): (InputDispatchContext & { backendNodeId: number }) | RpcError {
if (isRpcError(node)) return node;
return {
target: node.cdpTarget,
cdp: cdpRunnerForTarget(cdp, node.cdpTarget),
backendNodeId: node.backendNodeId,
frameId: node.frameId,
usedRef: node.usedRef,
usedSelector: node.usedSelector,
};
}
interface FocusProbe {
hasFocus: boolean;
activeTag: string;
textEntry: boolean;
}
/** Resolve keyboard input to the CDP target that currently owns focus. */
async function resolveFocusedInputContext(
cdp: CdpRunner,
tabId: number,
mode: "press" | "type",
): Promise<InputDispatchContext | RpcError> {
if (!cdp.getFrameGraph) {
return rpcError(
"cdp_failed",
"focus_target_unresolved",
`${mode} cannot determine the focused frame target`,
);
}
let targets: CdpTarget[];
try {
const graph = await cdp.getFrameGraph(tabId);
const unique = new Map<string, CdpTarget>();
unique.set(cdpTargetKey({ tabId }), { tabId });
for (const frame of graph.frames) unique.set(cdpTargetKey(frame.target), frame.target);
targets = [...unique.values()];
} catch (err) {
return rpcError(
"cdp_failed",
"focus_target_unresolved",
err instanceof Error ? err.message : String(err),
);
}
const focused: Array<{ target: CdpTarget; probe: FocusProbe }> = [];
await Promise.all(
targets.map(async (candidate) => {
try {
const reply = await cdpRunnerForTarget(cdp, candidate).send<{
result?: { value?: FocusProbe };
}>(tabId, "Runtime.evaluate", {
expression: `(() => {
/* bsk-focus-target-probe */
const active = document.activeElement;
const inputType = active instanceof HTMLInputElement ? active.type.toLowerCase() : '';
const nonTextInputTypes = new Set([
'button', 'checkbox', 'color', 'date', 'datetime-local', 'file',
'hidden', 'image', 'month', 'radio', 'range', 'reset', 'submit',
'time', 'week'
]);
const role = active instanceof Element ? active.getAttribute('role') : null;
return {
hasFocus: document.hasFocus(),
activeTag: active instanceof Element ? active.tagName.toLowerCase() : '',
textEntry:
(active instanceof HTMLInputElement && !nonTextInputTypes.has(inputType)) ||
active instanceof HTMLTextAreaElement ||
(active instanceof HTMLElement && active.isContentEditable) ||
role === 'textbox' || role === 'searchbox'
};
})()`,
returnByValue: true,
});
const probe = reply.result?.value;
if (probe?.hasFocus) focused.push({ target: candidate, probe });
} catch {
// A target may navigate or detach while the graph is being probed.
}
}),
);
// A top document whose active element is an iframe delegates focus to
// that frame. Removing those delegating targets leaves the deepest OOPIF
// target while same-process frames continue to use the shared root target.
const owners = focused.filter(({ probe }) => {
if (probe.activeTag === "iframe" || probe.activeTag === "frame") return false;
return mode !== "type" || probe.textEntry;
});
if (owners.length !== 1) {
return rpcError(
"cdp_failed",
"focus_target_unresolved",
owners.length === 0
? `${mode} found no unique focused${mode === "type" ? " text-entry" : " frame"} target`
: `${mode} found multiple focused frame targets`,
{ candidate_count: owners.length },
);
}
const target = owners[0].target;
return { target, cdp: cdpRunnerForTarget(cdp, target) };
}
// ---------------------------------------------------------------------------
// tool.click
// ---------------------------------------------------------------------------
interface ResolvedClickPointerTarget {
point: { x: number; y: number };
usedRef?: string;
usedSelector?: string;
moveSettleMs: number;
capture?: {
id: string;
imageX: number;
imageY: number;
};
}
export async function handleClick(
manager: SessionManager,
params: ClickParams,
deps: InteractionDeps = getDefaultDeps(),
): Promise<ClickResult | RpcError> {
const hasSurfacePointParams =
params.capture_id !== undefined || params.image_x !== undefined || params.image_y !== undefined;
const ctxOrErr = lookupSession(manager, params, "click");
if (isRpcError(ctxOrErr)) return ctxOrErr;
const ctx = ctxOrErr;
@@ -235,39 +372,67 @@ export async function handleClick(
if (denied) return denied;
const dialogCursor = markDialogCursor(deps.cdp, target.tabId);
const node = await resolveBackendNode(deps.cdp, ctx, target, params, "click");
if (isRpcError(node)) return node;
const button: MouseButton = params.button ?? "left";
const clickCount = params.click_count ?? 1;
if (!Number.isSafeInteger(clickCount) || clickCount < 1) {
return { code: "invalid_params", message: "click_count must be a positive integer" };
}
const modifiers = modifiersBitfield(params.modifiers);
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "click aborted" };
}
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
const geometry = await resolveNodeGeometry(
deps.cdp,
target.tabId,
{
target: node.cdpTarget,
backendNodeId: node.backendNodeId,
...(node.frameId ? { frameId: node.frameId } : {}),
},
{ scrollIntoView: true },
);
if (isRpcError(geometry)) return geometry;
const centre = geometry.actionPoint;
const pointerTarget: ResolvedClickPointerTarget | RpcError = hasSurfacePointParams
? await resolveSurfacePointerTarget(
ctx,
target,
{
ref: params.ref,
selector: params.selector,
captureId: params.capture_id,
imageX: params.image_x,
imageY: params.image_y,
},
{
cdp: deps.cdp,
signal: deps.signal,
},
)
: await (async () => {
const node = await resolveBackendNode(deps.cdp, ctx, target, params, "click");
if (isRpcError(node)) return node;
const geometry = await resolveNodeGeometry(
deps.cdp,
target.tabId,
{
target: node.cdpTarget,
backendNodeId: node.backendNodeId,
...(node.frameId ? { frameId: node.frameId } : {}),
},
{ scrollIntoView: true },
);
if (isRpcError(geometry)) return geometry;
return {
point: geometry.actionPoint,
usedRef: node.usedRef,
usedSelector: node.usedSelector,
moveSettleMs: 0,
};
})();
if (isRpcError(pointerTarget)) return pointerTarget;
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "click aborted" };
}
const button: MouseButton = params.button ?? "left";
const clickCount = params.click_count ?? 1;
if (clickCount < 1) {
return { code: "invalid_params", message: "click_count must be greater than zero" };
}
const modifiers = modifiersBitfield(params.modifiers);
const overlayBlocking = await checkOverlayAtPoint(deps.cdp, target.tabId, centre.x, centre.y);
const overlayBlocking = await checkOverlayAtPoint(
deps.cdp,
target.tabId,
pointerTarget.point.x,
pointerTarget.point.y,
);
let automationBypassEnabled = false;
if (overlayBlocking && deps.bypassOverlay) {
try {
@@ -279,47 +444,16 @@ export async function handleClick(
}
try {
// Move first so hover state activates, then press → release.
await deps.cdp.send(target.tabId, "Input.dispatchMouseEvent", {
type: "mouseMoved",
x: centre.x,
y: centre.y,
modifiers,
});
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "click aborted" };
}
await deps.cdp.send(target.tabId, "Input.dispatchMouseEvent", {
type: "mousePressed",
x: centre.x,
y: centre.y,
const dispatch = await dispatchMouseClick(deps.cdp, target.tabId, pointerTarget.point, {
button,
clickCount,
modifiers,
signal: deps.signal,
moveSettleMs: pointerTarget.moveSettleMs,
});
if (throwIfAborted(deps.signal)) {
try {
await deps.cdp.send(target.tabId, "Input.dispatchMouseEvent", {
type: "mouseReleased",
x: centre.x,
y: centre.y,
button,
clickCount,
modifiers,
});
} catch (err) {
console.debug("[bsk interaction] best-effort mouseReleased after abort failed", err);
}
if (dispatch === "cancelled") {
return { code: "cancelled", message: "click aborted" };
}
await deps.cdp.send(target.tabId, "Input.dispatchMouseEvent", {
type: "mouseReleased",
x: centre.x,
y: centre.y,
button,
clickCount,
modifiers,
});
} catch (err) {
return {
code: "cdp_failed",
@@ -337,10 +471,17 @@ export async function handleClick(
return attachDialogs(deps.cdp, target.tabId, dialogCursor, {
tab_id: target.tabId,
used_ref: node.usedRef,
used_selector: node.usedSelector,
x: centre.x,
y: centre.y,
used_ref: pointerTarget.usedRef,
used_selector: pointerTarget.usedSelector,
x: pointerTarget.point.x,
y: pointerTarget.point.y,
...(pointerTarget.capture
? {
capture_id: pointerTarget.capture.id,
image_x: pointerTarget.capture.imageX,
image_y: pointerTarget.capture.imageY,
}
: {}),
});
}
@@ -560,6 +701,47 @@ function isFillable(node: DescribedNode): boolean {
return false;
}
/** `type` also supports custom text-entry widgets that expose an ARIA role. */
function isTypeTarget(node: DescribedNode): boolean {
const tag = (node.nodeName ?? "").toUpperCase();
const attrs = node.attributes ?? [];
const attributes = new Map<string, string>();
for (let i = 0; i + 1 < attrs.length; i += 2) {
attributes.set(attrs[i].toLowerCase(), attrs[i + 1].toLowerCase());
}
if (tag === "TEXTAREA") return true;
if (tag === "INPUT") {
const type = attributes.get("type") ?? "text";
return !new Set([
"button",
"checkbox",
"color",
"date",
"datetime-local",
"file",
"hidden",
"image",
"month",
"radio",
"range",
"reset",
"submit",
"time",
"week",
]).has(type);
}
const contentEditable = attributes.get("contenteditable");
if (
contentEditable === "" ||
contentEditable === "true" ||
contentEditable === "plaintext-only"
) {
return true;
}
const role = attributes.get("role");
return role === "textbox" || role === "searchbox";
}
type SelectMutationResult =
| {
ok: true;
@@ -598,8 +780,9 @@ export async function handleFill(
const dialogCursor = markDialogCursor(deps.cdp, target.tabId);
const node = await resolveBackendNode(deps.cdp, ctx, target, params, "fill");
if (isRpcError(node)) return node;
const nodeCdp = cdpRunnerForTarget(deps.cdp, node.cdpTarget);
const input = inputContextForNode(deps.cdp, node);
if (isRpcError(input)) return input;
const nodeCdp = input.cdp;
try {
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
@@ -607,7 +790,7 @@ export async function handleFill(
target.tabId,
"DOM.describeNode",
{
backendNodeId: node.backendNodeId,
backendNodeId: input.backendNodeId,
},
);
if (!described.node || !isFillable(described.node)) {
@@ -620,15 +803,15 @@ export async function handleFill(
const scrollErr = await scrollElementAndFramesIntoView(
deps.cdp,
target.tabId,
node.cdpTarget,
node.backendNodeId,
node.frameId,
input.target,
input.backendNodeId,
input.frameId,
);
if (scrollErr) return scrollErr;
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "fill aborted" };
}
await nodeCdp.send(target.tabId, "DOM.focus", { backendNodeId: node.backendNodeId });
await nodeCdp.send(target.tabId, "DOM.focus", { backendNodeId: input.backendNodeId });
} catch (err) {
return {
code: "cdp_failed",
@@ -640,62 +823,118 @@ export async function handleFill(
return { code: "cancelled", message: "fill aborted" };
}
const objectIdOrErr = await backendNodeToObject(nodeCdp, target.tabId, node.backendNodeId);
const objectIdOrErr = await backendNodeToObject(nodeCdp, target.tabId, input.backendNodeId);
if (isRpcError(objectIdOrErr)) return objectIdOrErr;
const objectId = objectIdOrErr;
const clearBefore = params.clear_before ?? true;
try {
if (clearBefore) {
// Clear input/textarea value or wipe contenteditable innerText,
// then fire `input` so frameworks observe the empty state.
await nodeCdp.send(target.tabId, "Runtime.callFunctionOn", {
objectId,
functionDeclaration: `function() {
if (this.isContentEditable) { this.textContent = ''; }
else {
const proto = this instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const descriptor = Object.getOwnPropertyDescriptor(proto, 'value');
if (descriptor && descriptor.set) descriptor.set.call(this, '');
else this.value = '';
}
this.dispatchEvent(new Event('input', { bubbles: true }));
}`,
returnByValue: true,
});
}
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "fill aborted" };
}
// CDP `Input.insertText` handles IME / multi-byte input out of the
// box, much more reliably than per-key `dispatchKeyEvent`.
await deps.cdp.send(target.tabId, "Input.insertText", { text: params.value });
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "fill aborted" };
}
// Fire `input` + `change` so React / Vue controlled inputs commit.
await nodeCdp.send(target.tabId, "Runtime.callFunctionOn", {
objectId,
functionDeclaration: `function() {
this.dispatchEvent(new Event('input', { bubbles: true }));
this.dispatchEvent(new Event('change', { bubbles: true }));
}`,
returnByValue: true,
});
} catch (err) {
return {
code: "cdp_failed",
message: err instanceof Error ? err.message : String(err),
};
}
const fillResult = await fillEditable(
nodeCdp,
target.tabId,
objectId,
params.value,
clearBefore,
deps.signal,
);
if (isRpcError(fillResult)) return fillResult;
return attachDialogs(deps.cdp, target.tabId, dialogCursor, {
tab_id: target.tabId,
used_ref: node.usedRef,
used_selector: node.usedSelector,
value_length: params.value.length,
used_ref: input.usedRef,
used_selector: input.usedSelector,
value_length: fillResult.value.length,
});
}
// ---------------------------------------------------------------------------
// tool.type
// ---------------------------------------------------------------------------
export async function handleType(
manager: SessionManager,
params: TypeParams,
deps: InteractionDeps = getDefaultDeps(),
): Promise<TypeResult | RpcError> {
if (!params || typeof params.text !== "string") {
return { code: "invalid_params", message: "type requires a text string" };
}
if (params.focused !== undefined && typeof params.focused !== "boolean") {
return { code: "invalid_params", message: "type focused must be a boolean" };
}
const hasExplicitTarget =
(typeof params.ref === "string" && params.ref.length > 0) ||
(typeof params.selector === "string" && params.selector.length > 0);
if (params.focused === true && hasExplicitTarget) {
return {
code: "invalid_params",
message: "type: pass a ref/selector or focused=true, not both",
};
}
if (params.focused !== true && !hasExplicitTarget) {
return {
code: "invalid_params",
message: "type requires a ref/selector or focused=true",
};
}
const ctxOrErr = lookupSession(manager, params, "type");
if (isRpcError(ctxOrErr)) return ctxOrErr;
const ctx = ctxOrErr;
if (throwIfAborted(deps.signal)) return { code: "cancelled", message: "type aborted" };
const target = await resolveTargetTab(manager, ctx, params.tab_id, deps.tabsApi);
if (isRpcError(target)) return target;
const denied = enforceAgentWindow(ctx, target, "type");
if (denied) return denied;
const dialogCursor = markDialogCursor(deps.cdp, target.tabId);
let input: InputDispatchContext | RpcError;
if (hasExplicitTarget) {
const node = await resolveBackendNode(deps.cdp, ctx, target, params, "type");
const explicitInput = inputContextForNode(deps.cdp, node);
if (isRpcError(explicitInput)) return explicitInput;
input = explicitInput;
try {
const described = await explicitInput.cdp.send<{ node?: DescribedNode }>(
target.tabId,
"DOM.describeNode",
{ backendNodeId: explicitInput.backendNodeId },
);
if (!described.node || !isTypeTarget(described.node)) {
return rpcError(
"invalid_params",
"target_not_fillable",
`element ${described.node?.nodeName ?? "?"} not text-editable`,
);
}
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
const scrollErr = await scrollElementAndFramesIntoView(
deps.cdp,
target.tabId,
explicitInput.target,
explicitInput.backendNodeId,
explicitInput.frameId,
);
if (scrollErr) return scrollErr;
if (throwIfAborted(deps.signal)) return { code: "cancelled", message: "type aborted" };
await explicitInput.cdp.send(target.tabId, "DOM.focus", {
backendNodeId: explicitInput.backendNodeId,
});
} catch (err) {
return { code: "cdp_failed", message: err instanceof Error ? err.message : String(err) };
}
} else {
input = await resolveFocusedInputContext(deps.cdp, target.tabId, "type");
if (isRpcError(input)) return input;
}
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
const dispatchError = await dispatchTextInput(input.cdp, target.tabId, params.text, deps.signal);
if (dispatchError) return dispatchError;
return attachDialogs(deps.cdp, target.tabId, dialogCursor, {
tab_id: target.tabId,
used_ref: input.usedRef,
used_selector: input.usedSelector,
text_length: params.text.length,
verification: "dispatched",
});
}
@@ -870,31 +1109,38 @@ export async function handlePress(
};
}
let input: InputDispatchContext | RpcError;
// Optional focus before key dispatch.
if (params.ref || params.selector) {
const node = await resolveBackendNode(deps.cdp, ctx, target, params, "press");
if (isRpcError(node)) return node;
const nodeCdp = cdpRunnerForTarget(deps.cdp, node.cdpTarget);
const explicitInput = inputContextForNode(deps.cdp, node);
if (isRpcError(explicitInput)) return explicitInput;
input = explicitInput;
try {
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
const scrollErr = await scrollElementAndFramesIntoView(
deps.cdp,
target.tabId,
node.cdpTarget,
node.backendNodeId,
node.frameId,
explicitInput.target,
explicitInput.backendNodeId,
explicitInput.frameId,
);
if (scrollErr) return scrollErr;
if (throwIfAborted(deps.signal)) {
return { code: "cancelled", message: "press aborted" };
}
await nodeCdp.send(target.tabId, "DOM.focus", { backendNodeId: node.backendNodeId });
await explicitInput.cdp.send(target.tabId, "DOM.focus", {
backendNodeId: explicitInput.backendNodeId,
});
} catch (err) {
return {
code: "cdp_failed",
message: err instanceof Error ? err.message : String(err),
};
}
} else {
input = await resolveFocusedInputContext(deps.cdp, target.tabId, "press");
if (isRpcError(input)) return input;
}
if (throwIfAborted(deps.signal)) {
@@ -908,7 +1154,7 @@ export async function handlePress(
try {
let cancelled = false;
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
await deps.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
await input.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
type: "rawKeyDown",
key: descriptor.key,
code: descriptor.code,
@@ -922,7 +1168,7 @@ export async function handlePress(
typeof descriptor.text === "string" &&
descriptor.text.length > 0
) {
await deps.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
await input.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
type: "char",
key: descriptor.key,
code: descriptor.code,
@@ -939,7 +1185,7 @@ export async function handlePress(
cancelled = true;
}
}
await deps.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
await input.cdp.send(target.tabId, "Input.dispatchKeyEvent", {
type: "keyUp",
key: descriptor.key,
code: descriptor.code,
+96
View File
@@ -0,0 +1,96 @@
import type { MouseButton } from "@/transport/types";
import type { Point } from "./geometry";
import type { CdpRunner } from "./shared";
interface MouseClickDispatchOptions {
button: MouseButton;
clickCount: number;
modifiers: number;
signal?: AbortSignal;
moveSettleMs?: number;
}
type MouseClickDispatchResult = "completed" | "cancelled";
function waitForSettle(ms: number, signal: AbortSignal | undefined): Promise<boolean> {
if (ms <= 0) return Promise.resolve(signal?.aborted !== true);
if (signal?.aborted) return Promise.resolve(false);
return new Promise((resolve) => {
let settled = false;
const finish = (completed: boolean) => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
resolve(completed);
};
const timer = setTimeout(() => finish(true), ms);
const onAbort = () => finish(false);
signal?.addEventListener("abort", onAbort, { once: true });
});
}
/**
* Dispatch one coherent CDP mouse click in top-viewport CSS coordinates.
*
* Keeping the sequence here prevents DOM and Surface interaction paths from
* duplicating cancellation and best-effort release behavior. Callers that
* target asynchronously hit-tested content may request a settle interval.
*/
export async function dispatchMouseClick(
cdp: CdpRunner,
tabId: number,
point: Point,
options: MouseClickDispatchOptions,
): Promise<MouseClickDispatchResult> {
const { button, clickCount, modifiers, signal, moveSettleMs = 0 } = options;
let pressed = false;
const release = () =>
cdp.send(tabId, "Input.dispatchMouseEvent", {
type: "mouseReleased",
x: point.x,
y: point.y,
button,
clickCount,
modifiers,
});
try {
await cdp.send(tabId, "Input.dispatchMouseEvent", {
type: "mouseMoved",
x: point.x,
y: point.y,
modifiers,
});
if (!(await waitForSettle(moveSettleMs, signal))) return "cancelled";
await cdp.send(tabId, "Input.dispatchMouseEvent", {
type: "mousePressed",
x: point.x,
y: point.y,
button,
clickCount,
modifiers,
});
pressed = true;
if (signal?.aborted) {
await release();
pressed = false;
return "cancelled";
}
await release();
pressed = false;
return "completed";
} catch (error) {
if (pressed) {
try {
await release();
} catch (releaseError) {
console.debug("[bsk mouse-input] best-effort mouse release failed", releaseError);
}
}
throw error;
}
}
+96 -7
View File
@@ -8,6 +8,7 @@ import {
applyVomInteractionRecovery,
type CondSurface,
isVomReferenceNode,
type Rect,
renderVom,
type VomNode,
type VomOptions,
@@ -47,6 +48,8 @@ import {
type ToolEffect,
} from "./shared";
import { resolveSnapshotRef } from "./snapshot-ref";
import { surfaceVisibleRect } from "./surface-coordinate";
import { captureSurfaceEnvironment } from "./surface-target";
import {
type CapturedNode,
type CapturedViewModel,
@@ -59,6 +62,11 @@ import {
type CaptureVomObservationResult,
projectRecordSafeObservation,
} from "./vom/record-safe-observation";
import {
clusterRenderedSurfaces,
discoverRenderedSurfaces,
projectRenderedSurfaces,
} from "./vom/rendered-surfaces";
import {
buildSemanticGraph,
buildSemanticVomScene,
@@ -90,6 +98,9 @@ export const normaliseRef = sharedNormaliseRef;
// screenshot — `tool.screenshot`
// ---------------------------------------------------------------------------
const VISUAL_SURFACE_SCREENSHOT_MAX_EDGE = 2_048;
const VISUAL_SURFACE_SCREENSHOT_MAX_PIXELS = 4_000_000;
/**
* Strip the `data:image/...;base64,` prefix from a Chrome
* `captureVisibleTab` dataURL and return the raw base64 payload.
@@ -182,18 +193,42 @@ async function captureElementScreenshot(
target: CdpTarget,
backendNodeId: number,
frameId?: string,
visualSurface = false,
observedVisibleRect?: Rect,
signal?: AbortSignal,
): Promise<{ image_base64: string; width: number; height: number } | RpcError> {
): Promise<
{ image_base64: string; width: number; height: number; topViewportRect: Rect } | RpcError
> {
if (signal?.aborted) return cancelled("screenshot");
const geometry = await resolveNodeGeometry(
cdp,
tabId,
{ target, backendNodeId, ...(frameId ? { frameId } : {}) },
{ scrollIntoView: true },
{ scrollIntoView: !visualSurface },
);
if (isRpcError(geometry)) return geometry;
if (signal?.aborted) return cancelled("screenshot");
const rect = geometry.topBounds;
const topViewportRect = surfaceVisibleRect(
geometry.topBounds,
visualSurface ? observedVisibleRect : undefined,
);
if (!topViewportRect) {
return { code: "permission_denied", message: "surface is no longer visible" };
}
const rect = {
x: topViewportRect.x,
y: topViewportRect.y,
width: topViewportRect.w,
height: topViewportRect.h,
};
const scale = visualSurface
? Math.min(
1,
VISUAL_SURFACE_SCREENSHOT_MAX_EDGE / rect.width,
VISUAL_SURFACE_SCREENSHOT_MAX_EDGE / rect.height,
Math.sqrt(VISUAL_SURFACE_SCREENSHOT_MAX_PIXELS / (rect.width * rect.height)),
)
: 1;
try {
const shot = await cdp.send<{ data?: string }>(tabId, "Page.captureScreenshot", {
@@ -203,7 +238,7 @@ async function captureElementScreenshot(
y: rect.y,
width: rect.width,
height: rect.height,
scale: 1,
scale,
},
});
if (signal?.aborted) return cancelled("screenshot");
@@ -215,7 +250,7 @@ async function captureElementScreenshot(
width: Math.round(rect.width),
height: Math.round(rect.height),
};
return { image_base64, width: dims.width, height: dims.height };
return { image_base64, width: dims.width, height: dims.height, topViewportRect };
} catch (err) {
return {
code: "cdp_failed",
@@ -310,7 +345,7 @@ export async function handleScreenshot(
if (!deps.cdp) {
return { code: "cdp_failed", message: "screenshot ref capture requires CDP" };
}
const node = resolveSnapshotRef(ctx, ref, target.tabId);
const node = resolveSnapshotRef(ctx, ref, target.tabId, "screenshot");
if (isRpcError(node)) return node;
if (signal?.aborted) return cancelled("screenshot");
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
@@ -330,18 +365,54 @@ export async function handleScreenshot(
nodeTarget,
node.backendNodeId,
node.frameId,
node.kind === "surface",
node.visibleRect,
signal,
),
deps.sendToTab,
);
if (isRpcError(captured)) return captured;
if (signal?.aborted) return cancelled("screenshot");
const capture =
node.kind === "surface"
? await (async () => {
const environment = await captureSurfaceEnvironment(cdp, target.tabId, node.frameId);
if (isRpcError(environment)) return environment;
return ctx.surfaceCaptures.create({
sessionId: ctx.sessionId,
tabId: target.tabId,
navigationIdentity: environment.navigationIdentity,
surface: {
ref: node.refKey,
...(node.frameId ? { frameId: node.frameId } : {}),
backendNodeId: node.backendNodeId,
observationGeneration: node.generation,
},
topViewportRect: captured.topViewportRect,
imageWidth: captured.width,
imageHeight: captured.height,
viewportSignature: environment.viewportSignature,
frameProjectionSignature: environment.frameProjectionSignature,
});
})()
: null;
if (capture && isRpcError(capture)) return capture;
return withShotDialogs({
image_base64: captured.image_base64,
width: captured.width,
height: captured.height,
format: "png",
tab_id: target.tabId,
...(capture
? {
capture: {
id: capture.id,
surface_ref: `@${capture.surface.ref}`,
coordinate_space: "capture-image-pixel" as const,
expires_at: capture.expiresAt,
},
}
: {}),
});
}
@@ -1023,6 +1094,7 @@ async function captureForVom(
export interface CaptureVomObservationOptions extends VomOptions {
conditionalSurfaceProbe?: boolean;
renderedSurfaceDiscovery?: boolean;
hoverProbeBypassOverlay?: (tabId: number, enabled: boolean) => Promise<void>;
signal?: AbortSignal;
}
@@ -1064,7 +1136,20 @@ export async function captureVomObservation(
),
);
const decoratedScene = attachCapturedSceneAnnotations(scene, normalizedDocuments, captured);
const rendered = renderVom(decoratedScene, {
const observedScene = options.renderedSurfaceDiscovery
? projectRenderedSurfaces(
decoratedScene,
normalizedDocuments,
clusterRenderedSurfaces(
discoverRenderedSurfaces(
normalizedDocuments,
captured.viewport,
captured.excludedBackendNodeIds,
),
),
)
: decoratedScene;
const rendered = renderVom(observedScene, {
maxDepth: options.maxDepth,
maxTokens: options.maxTokens,
redactValues: options.redactValues,
@@ -1115,6 +1200,7 @@ async function handleVomObservation(
maxTokens: params.max_tokens,
activeRegionPolicy: true,
conditionalSurfaceProbe: effectiveConditionalSurfaceProbe,
renderedSurfaceDiscovery: toolName === "observe",
hoverProbeBypassOverlay: deps.hoverProbeBypassOverlay,
signal,
});
@@ -1132,6 +1218,9 @@ async function handleVomObservation(
tabId: target.tabId,
...(ref.frameId ? { frameId: ref.frameId } : {}),
...(refTarget?.sessionId ? { cdpSessionId: refTarget.sessionId } : {}),
...(ref.visibleRect ? { visibleRect: ref.visibleRect } : {}),
...(ref.kind ? { kind: ref.kind } : {}),
...(ref.capabilities ? { capabilities: ref.capabilities } : {}),
},
] as const;
}),
+1
View File
@@ -243,6 +243,7 @@ export async function handleSessionStop(
// Step 2: clear the per-session RefStore (review M6/M7 parity).
ctx.refStore.clear();
ctx.surfaceCaptures.clear();
clearRecordingForSession(params.session_id);
+19 -1
View File
@@ -2,8 +2,9 @@
// compound CDP node identity via the session RefStore, and build stable
// `ref_not_found` errors for hard-failure tool paths.
import type { Rect } from "@browser-skill/vom";
import type { SessionContext } from "@/session-manager/manager";
import { normaliseRef } from "@/session-manager/ref-store";
import { normaliseRef, type RefCapability, type RefTargetKind } from "@/session-manager/ref-store";
import type { RpcError } from "@/transport/types";
import { rpcError } from "./errors";
@@ -12,6 +13,10 @@ export interface SnapshotRefLookup {
refKey: string;
frameId?: string;
cdpSessionId?: string;
visibleRect?: Rect;
kind: RefTargetKind;
capabilities: RefCapability[];
generation: number;
}
function refEntryForTab(ctx: SessionContext, refKey: string, tabId: number) {
@@ -37,6 +42,10 @@ export function lookupSnapshotRef(
refKey,
...(entry.frameId ? { frameId: entry.frameId } : {}),
...(entry.cdpSessionId ? { cdpSessionId: entry.cdpSessionId } : {}),
...(entry.visibleRect ? { visibleRect: entry.visibleRect } : {}),
kind: entry.kind,
capabilities: entry.capabilities,
generation: entry.generation,
};
}
@@ -49,6 +58,7 @@ export function resolveSnapshotRef(
ctx: SessionContext,
ref: string,
tabId: number,
requiredCapability?: RefCapability,
): SnapshotRefLookup | RpcError {
const looked = lookupSnapshotRef(ctx, ref, tabId);
if (looked === null) {
@@ -58,5 +68,13 @@ export function resolveSnapshotRef(
`ref ${ref} unknown for tab ${tabId} in session ${ctx.sessionId}`,
);
}
if (requiredCapability && !looked.capabilities.includes(requiredCapability)) {
return rpcError(
"permission_denied",
"ref_capability_denied",
`ref ${ref} does not support ${requiredCapability}`,
{ ref: looked.refKey, required_capability: requiredCapability, kind: looked.kind },
);
}
return looked;
}
@@ -0,0 +1,88 @@
import type { Rect } from "@browser-skill/vom";
import type { Point, Region, ViewportRect } from "./geometry";
const RECT_EPSILON = 0.01;
export function surfaceVisibleRect(
liveRect: ViewportRect,
observedRect: Rect | undefined,
): Rect | null {
const observed = observedRect ?? {
x: liveRect.x,
y: liveRect.y,
w: liveRect.width,
h: liveRect.height,
};
const x = Math.max(liveRect.x, observed.x);
const y = Math.max(liveRect.y, observed.y);
const right = Math.min(liveRect.x + liveRect.width, observed.x + observed.w);
const bottom = Math.min(liveRect.y + liveRect.height, observed.y + observed.h);
return right > x && bottom > y ? { x, y, w: right - x, h: bottom - y } : null;
}
export function sameRect(a: Rect, b: Rect): boolean {
return (
Math.abs(a.x - b.x) <= RECT_EPSILON &&
Math.abs(a.y - b.y) <= RECT_EPSILON &&
Math.abs(a.w - b.w) <= RECT_EPSILON &&
Math.abs(a.h - b.h) <= RECT_EPSILON
);
}
export function mapImagePointToViewport(
rect: Rect,
imageWidth: number,
imageHeight: number,
imageX: number,
imageY: number,
): Point | null {
if (
!Number.isFinite(imageX) ||
!Number.isFinite(imageY) ||
!Number.isSafeInteger(imageWidth) ||
!Number.isSafeInteger(imageHeight) ||
imageWidth <= 0 ||
imageHeight <= 0 ||
imageX < 0 ||
imageY < 0 ||
imageX >= imageWidth ||
imageY >= imageHeight ||
!Number.isFinite(rect.x) ||
!Number.isFinite(rect.y) ||
!Number.isFinite(rect.w) ||
!Number.isFinite(rect.h) ||
rect.w <= 0 ||
rect.h <= 0
) {
return null;
}
return {
x: rect.x + (imageX / imageWidth) * rect.w,
y: rect.y + (imageY / imageHeight) * rect.h,
};
}
function pointInPolygon(point: Point, polygon: Point[]): boolean {
for (let index = 0; index < polygon.length; index += 1) {
const a = polygon[index];
const b = polygon[(index + 1) % polygon.length];
const cross = (point.x - a.x) * (b.y - a.y) - (point.y - a.y) * (b.x - a.x);
const withinX = point.x >= Math.min(a.x, b.x) - 1e-9 && point.x <= Math.max(a.x, b.x) + 1e-9;
const withinY = point.y >= Math.min(a.y, b.y) - 1e-9 && point.y <= Math.max(a.y, b.y) + 1e-9;
if (Math.abs(cross) <= 1e-9 && withinX && withinY) return true;
}
let inside = false;
for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index++) {
const a = polygon[index];
const b = polygon[previous];
const intersects =
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x;
if (intersects) inside = !inside;
}
return inside;
}
export function pointInRegion(point: Point, region: Region): boolean {
return region.some((polygon) => polygon.length >= 3 && pointInPolygon(point, polygon));
}
+260
View File
@@ -0,0 +1,260 @@
import type { CdpFrameGraph } from "@/browser-driver/frame-graph";
import type { SessionContext } from "@/session-manager/manager";
import type { RpcError } from "@/transport/types";
import { rpcError } from "./errors";
import { resolveNodeGeometry } from "./frame-geometry";
import { type CdpRunner, isRpcError, normaliseRef } from "./shared";
import { resolveSnapshotRef } from "./snapshot-ref";
import {
mapImagePointToViewport,
pointInRegion,
sameRect,
surfaceVisibleRect,
} from "./surface-coordinate";
export interface SurfaceCaptureEnvironment {
navigationIdentity: string;
viewportSignature: string;
frameProjectionSignature: string;
}
export interface SurfaceTargetResolverDeps {
cdp: CdpRunner;
signal?: AbortSignal;
}
export interface SurfacePointerTargetInput {
ref?: string;
selector?: string;
captureId?: string;
imageX?: number;
imageY?: number;
}
export interface ResolvedSurfacePointerTarget {
point: { x: number; y: number };
usedRef: string;
moveSettleMs: number;
capture: {
id: string;
imageX: number;
imageY: number;
};
}
// Canvas-style controls commonly update their pointer hit-test on the next
// animation frame. Leave a scheduling boundary after moving and before pressing.
export const SURFACE_POINTER_MOVE_SETTLE_MS = 32;
function stale(message: string): RpcError {
return rpcError("permission_denied", "surface_capture_stale", message);
}
function finiteObject(value: unknown): unknown {
if (Array.isArray(value)) return value.map(finiteObject);
if (typeof value !== "object" || value === null) return value;
return Object.fromEntries(
Object.entries(value)
.filter(
([, entry]) => entry !== undefined && (typeof entry !== "number" || Number.isFinite(entry)),
)
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, entry]) => [key, finiteObject(entry)]),
);
}
function framePathSignature(graph: CdpFrameGraph, frameId: string | undefined): string | null {
if (!frameId) return "top";
const frames = new Map(graph.frames.map((frame) => [frame.frameId, frame]));
const path: Array<{
frameId: string;
parentFrameId?: string;
ownerBackendNodeId?: number;
targetSessionId?: string;
}> = [];
const seen = new Set<string>();
let current = frames.get(frameId);
while (current) {
if (seen.has(current.frameId)) return null;
seen.add(current.frameId);
path.push({
frameId: current.frameId,
...(current.parentFrameId ? { parentFrameId: current.parentFrameId } : {}),
...(current.ownerBackendNodeId !== undefined
? { ownerBackendNodeId: current.ownerBackendNodeId }
: {}),
...(current.target.sessionId ? { targetSessionId: current.target.sessionId } : {}),
});
if (!current.parentFrameId) return JSON.stringify(path);
const parent = frames.get(current.parentFrameId);
if (!parent) return null;
current = parent;
}
return null;
}
export async function captureSurfaceEnvironment(
cdp: CdpRunner,
tabId: number,
frameId: string | undefined,
): Promise<SurfaceCaptureEnvironment | RpcError> {
try {
const [tree, metrics, graph] = await Promise.all([
cdp.send<{
frameTree?: { frame?: { id?: string; loaderId?: string; url?: string } };
}>(tabId, "Page.getFrameTree", {}),
cdp.send<Record<string, unknown>>(tabId, "Page.getLayoutMetrics", {}),
frameId && cdp.getFrameGraph ? cdp.getFrameGraph(tabId) : Promise.resolve(null),
]);
const root = tree.frameTree?.frame;
if (!root?.id || !root.loaderId) {
return { code: "cdp_failed", message: "could not identify the current navigation" };
}
const frameProjectionSignature = frameId
? graph
? framePathSignature(graph, frameId)
: null
: "top";
if (!frameProjectionSignature) {
return { code: "cdp_failed", message: `could not identify frame projection for ${frameId}` };
}
return {
navigationIdentity: JSON.stringify({ id: root.id, loaderId: root.loaderId, url: root.url }),
viewportSignature: JSON.stringify(
finiteObject({
cssLayoutViewport: metrics.cssLayoutViewport,
cssVisualViewport: metrics.cssVisualViewport,
}),
),
frameProjectionSignature,
};
} catch (error) {
return { code: "cdp_failed", message: error instanceof Error ? error.message : String(error) };
}
}
function validatePointParams(input: SurfacePointerTargetInput): RpcError | null {
if (!input.captureId || typeof input.captureId !== "string") {
return { code: "invalid_params", message: "surface point click requires capture_id" };
}
if (typeof input.imageX !== "number" || !Number.isFinite(input.imageX)) {
return { code: "invalid_params", message: "image_x must be a finite number" };
}
if (typeof input.imageY !== "number" || !Number.isFinite(input.imageY)) {
return { code: "invalid_params", message: "image_y must be a finite number" };
}
if (!input.ref || input.selector) {
return {
code: "invalid_params",
message: "surface point click requires one Surface ref and does not accept a selector",
};
}
return null;
}
function captureConsumeError(reason: "not_found" | "expired" | "consumed"): RpcError {
const code = reason === "not_found" ? "not_found" : "permission_denied";
return rpcError(code, `surface_capture_${reason}`, `surface capture is ${reason}`);
}
function aborted(signal: AbortSignal | undefined): RpcError | null {
return signal?.aborted
? { code: "cancelled", message: "surface target resolution aborted" }
: null;
}
/** Resolve one fresh Surface capture coordinate into a validated top-viewport pointer target. */
export async function resolveSurfacePointerTarget(
ctx: SessionContext,
target: { tabId: number; url?: string },
input: SurfacePointerTargetInput,
deps: SurfaceTargetResolverDeps,
): Promise<ResolvedSurfacePointerTarget | RpcError> {
const invalid = validatePointParams(input);
if (invalid) return invalid;
const earlyAbort = aborted(deps.signal);
if (earlyAbort) return earlyAbort;
const consumed = ctx.surfaceCaptures.consume(input.captureId as string);
if (!consumed.ok) return captureConsumeError(consumed.reason);
const capture = consumed.capture;
const postConsumeAbort = aborted(deps.signal);
if (postConsumeAbort) return postConsumeAbort;
if (capture.sessionId !== ctx.sessionId || capture.tabId !== target.tabId) {
return stale("surface capture belongs to a different session or tab");
}
if (normaliseRef(input.ref as string) !== capture.surface.ref) {
return stale("surface ref does not match the capture");
}
const node = resolveSnapshotRef(ctx, input.ref as string, target.tabId, "screenshot");
if (isRpcError(node)) return stale(node.message);
if (
node.kind !== "surface" ||
node.backendNodeId !== capture.surface.backendNodeId ||
node.frameId !== capture.surface.frameId ||
node.generation !== capture.surface.observationGeneration
) {
return stale("surface observation generation or node identity changed");
}
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
try {
await deps.cdp.ensureAttachedToUrl?.(target.tabId, target.url);
} catch (error) {
return { code: "cdp_failed", message: error instanceof Error ? error.message : String(error) };
}
const environment = await captureSurfaceEnvironment(deps.cdp, target.tabId, node.frameId);
if (isRpcError(environment)) return environment;
if (
environment.navigationIdentity !== capture.navigationIdentity ||
environment.viewportSignature !== capture.viewportSignature ||
environment.frameProjectionSignature !== capture.frameProjectionSignature
) {
return stale("navigation, viewport, zoom, scroll, or frame projection changed");
}
const geometry = await resolveNodeGeometry(
deps.cdp,
target.tabId,
{
target: {
tabId: target.tabId,
...(node.cdpSessionId ? { sessionId: node.cdpSessionId } : {}),
},
backendNodeId: node.backendNodeId,
...(node.frameId ? { frameId: node.frameId } : {}),
},
{ scrollIntoView: false },
);
if (isRpcError(geometry)) return stale(geometry.message);
const currentRect = surfaceVisibleRect(geometry.topBounds, node.visibleRect);
if (!currentRect || !sameRect(currentRect, capture.topViewportRect)) {
return stale("surface visible region changed");
}
const point = mapImagePointToViewport(
capture.topViewportRect,
capture.imageWidth,
capture.imageHeight,
input.imageX as number,
input.imageY as number,
);
if (!point || !pointInRegion(point, geometry.topVisibleRegions)) {
return rpcError(
"invalid_params",
"surface_coordinate_invalid",
"image coordinate is outside the captured Surface",
);
}
return {
point,
usedRef: capture.surface.ref,
moveSettleMs: SURFACE_POINTER_MOVE_SETTLE_MS,
capture: {
id: capture.id,
imageX: input.imageX as number,
imageY: input.imageY as number,
},
};
}
+194
View File
@@ -0,0 +1,194 @@
// Browser-native text entry for live editing sessions. Unlike fill, this
// module does not assume that the focused editable retains a DOM value: a
// Canvas editor may use an input/textarea only as a transient keyboard/IME
// sink and clear it after consuming each event.
import type { RpcError } from "@/transport/types";
import type { CdpRunner } from "./shared";
function cancelled(signal: AbortSignal | undefined): RpcError | null {
return signal?.aborted ? { code: "cancelled", message: "type aborted" } : null;
}
interface KeyDescriptor {
key: string;
code: string;
windowsVirtualKeyCode: number;
nativeVirtualKeyCode?: number;
modifiers: number;
}
function asciiKeyDescriptor(character: string): KeyDescriptor {
if (/^[a-z]$/.test(character)) {
return {
key: character,
code: `Key${character.toUpperCase()}`,
windowsVirtualKeyCode: character.toUpperCase().charCodeAt(0),
modifiers: 0,
};
}
if (/^[A-Z]$/.test(character)) {
return {
key: character,
code: `Key${character}`,
windowsVirtualKeyCode: character.charCodeAt(0),
modifiers: 8,
};
}
if (/^[0-9]$/.test(character)) {
return {
key: character,
code: `Digit${character}`,
windowsVirtualKeyCode: character.charCodeAt(0),
modifiers: 0,
};
}
if (character === " ") {
return { key: " ", code: "Space", windowsVirtualKeyCode: 32, modifiers: 0 };
}
return {
key: character,
code: "",
windowsVirtualKeyCode: character.charCodeAt(0),
modifiers: 0,
};
}
/**
* Run one complete browser key transaction and always release the key. The
* commit callback owns the text-producing phase: a `char` event for a
* keyboard character, or `Input.insertText` for committed IME text.
*/
async function dispatchKeyTransaction(
cdp: CdpRunner,
tabId: number,
descriptor: KeyDescriptor,
commit: () => Promise<void>,
signal?: AbortSignal,
): Promise<RpcError | null> {
let keyDown = false;
try {
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "rawKeyDown",
...descriptor,
});
keyDown = true;
const abortedAfterDown = cancelled(signal);
if (!abortedAfterDown) await commit();
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "keyUp",
...descriptor,
});
keyDown = false;
return abortedAfterDown ?? cancelled(signal);
} catch (err) {
if (keyDown) {
try {
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "keyUp",
...descriptor,
});
} catch {
// Best-effort cleanup keeps the page from observing a stuck key.
}
}
throw err;
}
}
async function typeAsciiCharacter(
cdp: CdpRunner,
tabId: number,
character: string,
signal?: AbortSignal,
): Promise<RpcError | null> {
const descriptor = asciiKeyDescriptor(character);
return dispatchKeyTransaction(
cdp,
tabId,
descriptor,
async () => {
await cdp.send(tabId, "Input.dispatchKeyEvent", {
type: "char",
...descriptor,
text: character,
unmodifiedText: character,
});
},
signal,
);
}
async function typeImeSegment(
cdp: CdpRunner,
tabId: number,
text: string,
signal?: AbortSignal,
): Promise<RpcError | null> {
const abortedBefore = cancelled(signal);
if (abortedBefore) return abortedBefore;
// A committed IME value is still part of a keyboard transaction. The
// Process key (VK_PROCESSKEY / 229) is the platform-neutral signal that an
// IME owns the keystroke. It lets selection-based editors enter text mode
// before insertText commits the Unicode value, without inventing a visible
// ASCII prefix or leaving a composition transaction open.
const processKey: KeyDescriptor = {
key: "Process",
code: "",
windowsVirtualKeyCode: 229,
nativeVirtualKeyCode: 229,
modifiers: 0,
};
return dispatchKeyTransaction(
cdp,
tabId,
processKey,
() => cdp.send(tabId, "Input.insertText", { text }).then(() => undefined),
signal,
);
}
/**
* Dispatch text through the browser's keyboard/IME pipelines. ASCII runs are
* delivered as physical-key-shaped events; non-ASCII runs use CDP's committed
* IME/software-keyboard insertion path. Successful return means the browser
* accepted the input commands, not that a DOM value retained the text.
*/
export async function dispatchTextInput(
cdp: CdpRunner,
tabId: number,
text: string,
signal?: AbortSignal,
): Promise<RpcError | null> {
const abortedBefore = cancelled(signal);
if (abortedBefore) return abortedBefore;
const segments: Array<{ ime: boolean; text: string }> = [];
for (const character of text) {
const ime = character.codePointAt(0)! > 0x7f;
const previous = segments.at(-1);
if (previous?.ime === ime) previous.text += character;
else segments.push({ ime, text: character });
}
try {
for (const segment of segments) {
if (segment.ime) {
const error = await typeImeSegment(cdp, tabId, segment.text, signal);
if (error) return error;
continue;
}
for (const character of segment.text) {
const error = await typeAsciiCharacter(cdp, tabId, character, signal);
if (error) return error;
}
}
return null;
} catch (err) {
return {
code: "cdp_failed",
message: err instanceof Error ? err.message : String(err),
};
}
}
@@ -722,6 +722,44 @@ describe("captureViewModel", () => {
expect(nodes.find((node) => node.backendNodeId === 14)?.rendered).toBe(false);
});
it("propagates fully transparent ancestor suppression to painted descendants", async () => {
const S = ["html", "body", "div", "canvas", "static", "auto", "visible", "1", "0"];
const i = (value: string) => S.indexOf(value);
const snapshot = {
strings: S,
documents: [
{
nodes: {
parentIndex: [-1, 0, 1, 2],
nodeName: [i("html"), i("body"), i("div"), i("canvas")],
backendNodeId: [10, 11, 12, 13],
attributes: [[], [], [], []],
},
layout: {
nodeIndex: [1, 2, 3],
styles: [
[i("static"), i("auto"), i("auto"), i("visible"), i("1")],
[i("static"), i("auto"), i("auto"), i("visible"), i("0")],
[i("static"), i("auto"), i("auto"), i("visible"), i("1")],
],
bounds: [
[0, 0, 1000, 800],
[10, 10, 200, 100],
[10, 10, 200, 100],
],
paintOrders: [0, 1, 2],
},
},
],
};
const { nodes } = await captureViewModel(makeCdp(snapshot), 4);
const canvas = nodes.find((node) => node.backendNodeId === 13);
expect(canvas?.rendered).toBe(true);
expect(canvas?.visuallySuppressed).toBe(true);
});
it("subtracts scroll offset to make rects viewport-relative", async () => {
const cdp = {
send: vi.fn(async (_t: number, method: string) => {
@@ -0,0 +1,256 @@
import type { VomScene } from "@browser-skill/vom";
import { describe, expect, it } from "vitest";
import type { CapturedNode } from "../capture";
import type { CapturedFrameDocument } from "../frame-capture";
import {
clusterRenderedSurfaces,
discoverRenderedSurfaces,
projectRenderedSurfaces,
} from "../rendered-surfaces";
import type { SemanticAxNode } from "../semantic-graph";
function domNode(backendNodeId: number, overrides: Partial<CapturedNode> = {}): CapturedNode {
return {
backendNodeId,
parentBackendNodeId: null,
frameId: "main",
ownerFrameBackendNodeId: null,
tag: "canvas",
attrs: {},
rect: { x: 10, y: 20, w: 800, h: 500 },
localRect: { x: 10, y: 20, w: 800, h: 500 },
paintOrder: 1,
position: "static",
pointerEvents: "auto",
rendered: true,
...overrides,
};
}
function document(
domNodes: CapturedNode[],
axNodes: SemanticAxNode[] = [],
): CapturedFrameDocument<SemanticAxNode> {
return {
frameId: domNodes[0]?.frameId ?? "main",
contextScopeId: domNodes[0]?.frameId ?? "main",
target: { tabId: 4 },
domNodes,
axNodes,
};
}
describe("rendered surface discovery", () => {
it("finds prominent rendered canvases and excludes hidden descendants", () => {
const visible = domNode(2, { parentBackendNodeId: 1 });
const hidden = domNode(3, { parentBackendNodeId: 4 });
const surfaces = discoverRenderedSurfaces(
[
document([
domNode(1, { tag: "main", rect: null, localRect: null }),
visible,
domNode(4, { tag: "section", attrs: { "aria-hidden": "true" }, rect: null }),
hidden,
]),
],
{ width: 1280, height: 720 },
);
expect(surfaces).toHaveLength(1);
expect(surfaces[0]).toMatchObject({ backendNodeId: 2 });
});
it("keeps tiny canvases as individually addressable exact discoveries", () => {
const surfaces = discoverRenderedSurfaces(
[document([domNode(2, { rect: { x: 1, y: 1, w: 8, h: 8 } })])],
{ width: 1280, height: 720 },
);
expect(surfaces).toEqual([expect.objectContaining({ backendNodeId: 2 })]);
});
it("keeps a surface when the canvas only has partial native accessibility content", () => {
const axNodes = [
{
nodeId: "canvas",
backendDOMNodeId: 2,
role: { type: "role", value: "presentation" },
childIds: ["button"],
frameId: "main",
},
{
nodeId: "button",
backendDOMNodeId: 3,
role: { type: "role", value: "button" },
frameId: "main",
},
] as SemanticAxNode[];
expect(
discoverRenderedSurfaces([document([domNode(2)], axNodes)], { width: 1280, height: 720 }),
).toEqual([expect.objectContaining({ backendNodeId: 2 })]);
});
it("discovers unnamed canvases without guessing labels from engineering attributes", () => {
const canvas = domNode(2, {
attrs: {
id: "must-not-be-a-label",
class: "must-not-be-a-label",
"data-testid": "must-not-be-a-label",
},
});
expect(discoverRenderedSurfaces([document([canvas])], { width: 1280, height: 720 })).toEqual([
expect.not.objectContaining({
label: expect.anything(),
}),
]);
});
it("treats blank explicit Canvas names as unnamed", () => {
expect(
discoverRenderedSurfaces(
[document([domNode(2, { attrs: { "aria-label": " ", title: "\n\t" } })])],
{ width: 1280, height: 720 },
),
).toEqual([expect.not.objectContaining({ label: expect.anything() })]);
});
it("excludes canvases inside BrowserSkill-owned DOM subtrees", () => {
const owner = domNode(1, { tag: "div", rect: null, localRect: null });
const canvas = domNode(2, { parentBackendNodeId: 1 });
expect(
discoverRenderedSurfaces(
[document([owner, canvas])],
{ width: 1280, height: 720 },
new Set([1]),
),
).toEqual([]);
});
it("excludes canvases suppressed by a fully transparent ancestor", () => {
const owner = domNode(1, {
tag: "div",
rect: { x: 0, y: 0, w: 900, h: 600 },
visuallySuppressed: true,
});
const canvas = domNode(2, { parentBackendNodeId: 1 });
expect(
discoverRenderedSurfaces([document([owner, canvas])], { width: 1280, height: 720 }),
).toEqual([]);
});
it("clips canvases to overflow ancestors and drops fully clipped canvases", () => {
const owner = domNode(1, {
tag: "div",
rect: { x: 10, y: 20, w: 100, h: 70 },
overflowX: "hidden",
overflowY: "hidden",
});
const partial = domNode(2, {
parentBackendNodeId: 1,
rect: { x: 55, y: 30, w: 140, h: 60 },
});
const fullyClipped = domNode(3, {
parentBackendNodeId: 1,
rect: { x: 140, y: 30, w: 80, h: 50 },
});
expect(
discoverRenderedSurfaces([document([owner, partial, fullyClipped])], {
width: 1280,
height: 720,
}),
).toEqual([
expect.objectContaining({
backendNodeId: 2,
visibleRect: { x: 55, y: 30, w: 55, h: 60 },
}),
]);
});
});
describe("rendered surface clustering and projection", () => {
it("collapses overlapping canvas layers and attaches them to the nearest retained parent", () => {
const body = domNode(1, { tag: "body", rect: null, localRect: null });
const surfaces = discoverRenderedSurfaces(
[
document([
body,
domNode(2, { parentBackendNodeId: 1, paintOrder: 1 }),
domNode(3, { parentBackendNodeId: 1, paintOrder: 2 }),
]),
],
{ width: 1280, height: 720 },
);
const groups = clusterRenderedSurfaces(surfaces);
const scene: VomScene = {
viewport: { width: 1280, height: 720 },
nodes: [
{
id: 10,
parentId: null,
backendNodeId: 1,
frameId: "main",
tag: "body",
role: "RootWebArea",
rect: null,
paintOrder: 0,
position: "static",
pointerEvents: "auto",
},
],
};
expect(groups).toHaveLength(1);
expect(groups[0]?.members).toHaveLength(2);
expect(groups[0]?.label).toBeUndefined();
expect(
projectRenderedSurfaces(
scene,
[document([body, ...surfaces.map((s) => domNode(s.backendNodeId))])],
groups,
),
).toMatchObject({
visualSurfaces: [expect.objectContaining({ parentId: 10, backendNodeId: 3, memberCount: 2 })],
});
});
it("does not merge a contained canvas with a larger independent canvas", () => {
const groups = clusterRenderedSurfaces([
...discoverRenderedSurfaces(
[
document([
domNode(1, { tag: "main", rect: null, localRect: null }),
domNode(2, { parentBackendNodeId: 1 }),
domNode(3, {
parentBackendNodeId: 1,
rect: { x: 30, y: 40, w: 200, h: 100 },
}),
]),
],
{ width: 1280, height: 720 },
),
]);
expect(groups).toHaveLength(2);
});
it("does not merge coincident canvases owned by different containers", () => {
const groups = clusterRenderedSurfaces(
discoverRenderedSurfaces(
[
document([
domNode(1, { tag: "section", rect: null, localRect: null }),
domNode(2, { tag: "section", rect: null, localRect: null }),
domNode(3, { parentBackendNodeId: 1 }),
domNode(4, { parentBackendNodeId: 2 }),
]),
],
{ width: 1280, height: 720 },
),
);
expect(groups).toHaveLength(2);
});
});
+30 -1
View File
@@ -11,7 +11,15 @@ import { childFrameProjection, type GeometryProjection, projectRectToViewport }
import type { CdpRunner } from "../shared";
import { clearHover, waitForHover } from "./hover-perception";
const REQUESTED_STYLES = ["position", "pointer-events", "cursor", "visibility", "opacity"] as const;
const REQUESTED_STYLES = [
"position",
"pointer-events",
"cursor",
"visibility",
"opacity",
"overflow-x",
"overflow-y",
] as const;
const STYLE_COL = Object.fromEntries(
REQUESTED_STYLES.map((name, index) => [name, index]),
) as Record<(typeof REQUESTED_STYLES)[number], number>;
@@ -39,6 +47,10 @@ export interface CapturedNode {
* `textContent`: the live parser always sets it, hand-built fixtures may not.
*/
cursor?: string;
overflowX?: string;
overflowY?: string;
/** True when this node or one of its DOM ancestors makes the subtree fully transparent/hidden. */
visuallySuppressed?: boolean;
/**
* Whether the live DOM snapshot provides a painted, non-hidden box for this
* node. Semantic resolution uses this only for DOM fallback nodes; AX-backed
@@ -796,6 +808,8 @@ function parseDocumentNodes(
const cursorCol = STYLE_COL.cursor;
const visibilityCol = STYLE_COL.visibility;
const opacityCol = STYLE_COL.opacity;
const overflowXCol = STYLE_COL["overflow-x"];
const overflowYCol = STYLE_COL["overflow-y"];
const inputValues = sparseIndexMap(dn.inputValue);
const textValues = sparseIndexMap(dn.textValue);
const checkedInputs = new Set(dn.inputChecked?.index ?? []);
@@ -821,6 +835,7 @@ function parseDocumentNodes(
// Build CapturedNodes.
const nodes: CapturedNode[] = [];
const visuallySuppressedByNodeIndex = new Array<boolean>(count).fill(false);
for (let n = 0; n < count; n++) {
if (excluded[n]) continue;
const backendNodeId = dn.backendNodeId[n];
@@ -840,7 +855,11 @@ function parseDocumentNodes(
let position = "static";
let pointerEvents = "auto";
let cursor = "auto";
let overflowX = "visible";
let overflowY = "visible";
let rendered = false;
let visuallySuppressed =
parentIdx >= 0 ? visuallySuppressedByNodeIndex[parentIdx] === true : false;
const li = layoutByNode.get(n);
if (li !== undefined) {
const b = dl?.bounds?.[li];
@@ -863,12 +882,19 @@ function parseDocumentNodes(
cursor = str(strings, styleRow[cursorCol]) || "auto";
const visibility = str(strings, styleRow[visibilityCol]) || "visible";
const opacity = str(strings, styleRow[opacityCol]) || "1";
overflowX = str(strings, styleRow[overflowXCol]) || "visible";
overflowY = str(strings, styleRow[overflowYCol]) || "visible";
visuallySuppressed ||=
visibility === "hidden" ||
visibility === "collapse" ||
(Number.parseFloat(opacity) || 0) <= 0;
rendered =
localRect !== null &&
visibility !== "hidden" &&
visibility !== "collapse" &&
(Number.parseFloat(opacity) || 0) > 0;
}
visuallySuppressedByNodeIndex[n] = visuallySuppressed;
// Skip non-element nodes (#text, #cdata-section, etc.) — they carry no
// geometry and are never queried by callers.
@@ -903,6 +929,9 @@ function parseDocumentNodes(
position,
pointerEvents,
cursor,
overflowX,
overflowY,
visuallySuppressed,
rendered,
textContent,
...(formValue !== undefined ? { formValue } : {}),
@@ -0,0 +1,65 @@
import type { Rect } from "@browser-skill/vom";
import type { RenderedSurface, RenderedSurfaceGroup } from "./types";
const STACK_IOU_RATIO = 0.9;
const STACK_SIZE_RATIO = 0.9;
function area(rect: Rect): number {
return Math.max(0, rect.w) * Math.max(0, rect.h);
}
function intersectionArea(a: Rect, b: Rect): number {
const width = Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x));
const height = Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y));
return width * height;
}
function sameVisualStack(a: RenderedSurface, b: RenderedSurface): boolean {
if (a.frameId !== b.frameId) return false;
if (a.parentBackendNodeId !== b.parentBackendNodeId) return false;
const aArea = area(a.visibleRect);
const bArea = area(b.visibleRect);
const intersection = intersectionArea(a.visibleRect, b.visibleRect);
const union = aArea + bArea - intersection;
const widthRatio =
Math.min(a.visibleRect.w, b.visibleRect.w) / Math.max(a.visibleRect.w, b.visibleRect.w);
const heightRatio =
Math.min(a.visibleRect.h, b.visibleRect.h) / Math.max(a.visibleRect.h, b.visibleRect.h);
return (
union > 0 &&
intersection / union >= STACK_IOU_RATIO &&
widthRatio >= STACK_SIZE_RATIO &&
heightRatio >= STACK_SIZE_RATIO
);
}
function toGroup(members: RenderedSurface[]): RenderedSurfaceGroup {
const representative = [...members].sort(
(a, b) => area(b.visibleRect) - area(a.visibleRect) || b.paintOrder - a.paintOrder,
)[0];
return {
frameId: representative.frameId,
members,
representative,
label: members.map((surface) => surface.label).find((label) => label !== undefined),
};
}
export function clusterRenderedSurfaces(surfaces: RenderedSurface[]): RenderedSurfaceGroup[] {
const groups: RenderedSurface[][] = [];
for (const surface of surfaces) {
const matching = groups.find((group) =>
group.some((member) => sameVisualStack(member, surface)),
);
if (matching) matching.push(surface);
else groups.push([surface]);
}
return groups
.map(toGroup)
.sort(
(a, b) =>
a.frameId.localeCompare(b.frameId) ||
a.representative.visibleRect.y - b.representative.visibleRect.y ||
a.representative.visibleRect.x - b.representative.visibleRect.x,
);
}
@@ -0,0 +1,113 @@
import type { Rect, Viewport } from "@browser-skill/vom";
import type { CapturedNode } from "../capture";
import type { CapturedFrameDocument } from "../frame-capture";
import type { SemanticAxNode } from "../semantic-graph";
import type { RenderedSurface } from "./types";
function clean(value: string | undefined): string | undefined {
const normalized = value?.replace(/\s+/g, " ").trim();
return normalized || undefined;
}
function intersectViewport(rect: Rect, viewport: Viewport): Rect | null {
return intersectRect(rect, { x: 0, y: 0, w: viewport.width, h: viewport.height });
}
function intersectRect(a: Rect, b: Rect): Rect | null {
const x = Math.max(a.x, b.x);
const y = Math.max(a.y, b.y);
const right = Math.min(a.x + a.w, b.x + b.w);
const bottom = Math.min(a.y + a.h, b.y + b.h);
if (right <= x || bottom <= y) return null;
return { x, y, w: right - x, h: bottom - y };
}
const CLIPPING_OVERFLOW = new Set(["auto", "clip", "hidden", "scroll"]);
function clipToOverflowAncestors(
node: CapturedNode,
rect: Rect,
nodesByBackend: ReadonlyMap<number, CapturedNode>,
): Rect | null {
let clipped: Rect | null = rect;
let parentBackendNodeId = node.parentBackendNodeId;
let guard = 0;
while (clipped && parentBackendNodeId !== null && guard <= nodesByBackend.size) {
const parent = nodesByBackend.get(parentBackendNodeId);
if (!parent) break;
if (parent.rect) {
const clipX = CLIPPING_OVERFLOW.has(parent.overflowX ?? "visible");
const clipY = CLIPPING_OVERFLOW.has(parent.overflowY ?? "visible");
if (clipX || clipY) {
const clipRect = {
x: clipX ? parent.rect.x : clipped.x,
y: clipY ? parent.rect.y : clipped.y,
w: clipX ? parent.rect.w : clipped.w,
h: clipY ? parent.rect.h : clipped.h,
};
clipped = intersectRect(clipped, clipRect);
}
}
parentBackendNodeId = parent.parentBackendNodeId;
guard += 1;
}
return clipped;
}
function excludedByDomPolicy(
node: CapturedNode,
nodesByBackend: Map<number, CapturedNode>,
excludedBackendNodeIds: ReadonlySet<number>,
): boolean {
let current: CapturedNode | undefined = node;
let guard = 0;
while (current && guard <= nodesByBackend.size) {
if (excludedBackendNodeIds.has(current.backendNodeId)) return true;
if (current.visuallySuppressed === true) return true;
const attrs = current.attrs;
if (
Object.prototype.hasOwnProperty.call(attrs, "hidden") ||
Object.prototype.hasOwnProperty.call(attrs, "inert") ||
(attrs["aria-hidden"] ?? "").toLowerCase() === "true"
) {
return true;
}
current =
current.parentBackendNodeId === null
? undefined
: nodesByBackend.get(current.parentBackendNodeId);
guard += 1;
}
return false;
}
export function discoverRenderedSurfaces(
documents: CapturedFrameDocument<SemanticAxNode>[],
viewport: Viewport,
excludedBackendNodeIds: ReadonlySet<number> = new Set(),
): RenderedSurface[] {
const surfaces: RenderedSurface[] = [];
for (const document of documents) {
const nodesByBackend = new Map(document.domNodes.map((node) => [node.backendNodeId, node]));
for (const node of document.domNodes) {
if (node.tag.toLowerCase() !== "canvas" || node.rendered !== true || !node.rect) continue;
if (excludedByDomPolicy(node, nodesByBackend, excludedBackendNodeIds)) continue;
const viewportRect = intersectViewport(node.rect, viewport);
const visibleRect = viewportRect
? clipToOverflowAncestors(node, viewportRect, nodesByBackend)
: null;
if (!visibleRect) continue;
const label = clean(node.attrs["aria-label"] ?? node.attrs.title);
surfaces.push({
renderingKind: "canvas",
frameId: document.frameId,
backendNodeId: node.backendNodeId,
parentBackendNodeId: node.parentBackendNodeId,
visibleRect,
paintOrder: node.paintOrder,
...(label ? { label } : {}),
});
}
}
return surfaces;
}
@@ -0,0 +1,4 @@
export { clusterRenderedSurfaces } from "./cluster";
export { discoverRenderedSurfaces } from "./discovery";
export { projectRenderedSurfaces } from "./project";
export type { RenderedSurface, RenderedSurfaceGroup } from "./types";
@@ -0,0 +1,100 @@
import type { VomScene, VomVisualSurface } from "@browser-skill/vom";
import type { CapturedFrameDocument } from "../frame-capture";
import type { SemanticAxNode } from "../semantic-graph";
import type { RenderedSurfaceGroup } from "./types";
function frameBackendKey(frameId: string, backendNodeId: number): string {
return `${frameId}\u0000${backendNodeId}`;
}
interface ProjectionIndex {
sceneByBackend: ReadonlyMap<string, number>;
documentByFrame: ReadonlyMap<string, CapturedFrameDocument<SemanticAxNode>>;
domByFrame: ReadonlyMap<
string,
ReadonlyMap<number, CapturedFrameDocument<SemanticAxNode>["domNodes"][number]>
>;
rootSceneIdByFrame: ReadonlyMap<string, number>;
}
function nearestSceneParent(index: ProjectionIndex, group: RenderedSurfaceGroup): number | null {
const document = index.documentByFrame.get(group.frameId);
const domByBackend = index.domByFrame.get(group.frameId) ?? new Map();
let parentBackendNodeId = group.representative.parentBackendNodeId;
let guard = 0;
while (parentBackendNodeId !== null && guard <= domByBackend.size) {
const sceneId = index.sceneByBackend.get(frameBackendKey(group.frameId, parentBackendNodeId));
if (sceneId !== undefined) return sceneId;
parentBackendNodeId = domByBackend.get(parentBackendNodeId)?.parentBackendNodeId ?? null;
guard += 1;
}
if (document?.parentFrameId && document.ownerBackendNodeId !== undefined) {
const owner = index.sceneByBackend.get(
frameBackendKey(document.parentFrameId, document.ownerBackendNodeId),
);
if (owner !== undefined) return owner;
}
return index.rootSceneIdByFrame.get(group.frameId) ?? null;
}
function buildProjectionIndex(
scene: VomScene,
documents: CapturedFrameDocument<SemanticAxNode>[],
): ProjectionIndex {
const rootSceneIdByFrame = new Map<string, number>();
for (const node of scene.nodes) {
if (
node.frameId &&
!rootSceneIdByFrame.has(node.frameId) &&
["rootwebarea", "webarea"].includes(node.role?.toLowerCase() ?? "")
) {
rootSceneIdByFrame.set(node.frameId, node.id);
}
}
return {
sceneByBackend: new Map(
scene.nodes.flatMap((node) =>
node.backendNodeId === undefined
? []
: [[frameBackendKey(node.frameId ?? "", node.backendNodeId), node.id] as const],
),
),
documentByFrame: new Map(documents.map((document) => [document.frameId, document])),
domByFrame: new Map(
documents.map((document) => [
document.frameId,
new Map(document.domNodes.map((node) => [node.backendNodeId, node])),
]),
),
rootSceneIdByFrame,
};
}
export function projectRenderedSurfaces(
scene: VomScene,
documents: CapturedFrameDocument<SemanticAxNode>[],
groups: RenderedSurfaceGroup[],
): VomScene {
const index = buildProjectionIndex(scene, documents);
const visualSurfaces: VomVisualSurface[] = [];
for (const group of groups) {
const parentId = nearestSceneParent(index, group);
visualSurfaces.push({
parentId,
backendNodeId: group.representative.backendNodeId,
frameId: group.frameId,
renderingKind: "canvas",
visibleRect: group.representative.visibleRect,
...(group.label ? { label: group.label } : {}),
memberCount: group.members.length,
});
}
return {
...scene,
...(visualSurfaces.length > 0 ? { visualSurfaces } : {}),
};
}
@@ -0,0 +1,18 @@
import type { Rect } from "@browser-skill/vom";
export interface RenderedSurface {
renderingKind: "canvas";
frameId: string;
backendNodeId: number;
parentBackendNodeId: number | null;
visibleRect: Rect;
paintOrder: number;
label?: string;
}
export interface RenderedSurfaceGroup {
frameId: string;
members: RenderedSurface[];
representative: RenderedSurface;
label?: string;
}
+42
View File
@@ -23,9 +23,12 @@ export type ErrorCode =
export type RpcErrorReason =
| "agent_window_scope"
| "element_not_visible"
| "ref_capability_denied"
| "ref_not_found"
| "selector_not_found"
| "target_not_fillable"
| "focus_target_unresolved"
| "input_not_applied"
| "target_not_select"
| "option_not_found"
| "single_select_value_count"
@@ -33,6 +36,11 @@ export type RpcErrorReason =
| "restricted_tab_url"
| "borrow_conflict"
| "screenshot_capture_failed"
| "surface_capture_not_found"
| "surface_capture_expired"
| "surface_capture_consumed"
| "surface_capture_stale"
| "surface_coordinate_invalid"
| "cleanup_failed";
export interface RpcErrorData {
@@ -298,9 +306,17 @@ export interface ScreenshotResult {
height: number;
format: string;
tab_id: number;
capture?: SurfaceCaptureInfo;
dialogs?: JavaScriptDialogInfo[];
}
export interface SurfaceCaptureInfo {
id: string;
surface_ref: string;
coordinate_space: "capture-image-pixel";
expires_at: number;
}
export interface SnapshotParams {
session_id: string;
tab_id?: number;
@@ -414,6 +430,9 @@ export interface ClickParams {
click_count?: number;
modifiers?: KeyModifier[];
timeout_ms?: number;
capture_id?: string;
image_x?: number;
image_y?: number;
}
export interface ClickResult {
@@ -422,6 +441,9 @@ export interface ClickResult {
used_selector?: string;
x: number;
y: number;
capture_id?: string;
image_x?: number;
image_y?: number;
dialogs?: JavaScriptDialogInfo[];
}
@@ -462,6 +484,26 @@ export interface FillResult {
dialogs?: JavaScriptDialogInfo[];
}
export interface TypeParams {
session_id: string;
text: string;
ref?: string;
selector?: string;
/** Explicitly dispatch to the unique focused text-entry target. */
focused?: boolean;
tab_id?: number;
timeout_ms?: number;
}
export interface TypeResult {
tab_id: number;
used_ref?: string;
used_selector?: string;
text_length: number;
verification: "dispatched";
dialogs?: JavaScriptDialogInfo[];
}
export interface PressParams {
session_id: string;
key: string;
@@ -0,0 +1,147 @@
# Rendered Surface browser fixtures
These pages exercise Canvas discovery through a real browser DOMSnapshot and AX tree. They are deliberately framework- and site-independent.
## Serve
From the repository root:
```bash
python3 -m http.server 4173 --bind 127.0.0.1 \
--directory apps/extension/test-fixtures/rendered-surfaces
```
Use an Agent Window large enough to keep the primary matrix visible:
```bash
bsk session start --width 1440 --height 1100
bsk navigate http://127.0.0.1:4173/index.html --session <id>
bsk observe --session <id>
```
Always stop the session after the run.
## Pages
### `index.html`
Expected individual Surface labels:
- `fixture-basic-large`
- `fixture-tiny-8px`
- `fixture-pointer-events-none`
- `fixture-partial-ax`
- `fixture-contained-outer`
- `fixture-contained-inner`
- `fixture-different-parent-a`
- `fixture-different-parent-b`
Expected one grouped Surface:
- `fixture-layered-group`, with `layers=2`
Expected absent:
- `fixture-display-none`
- `fixture-visibility-hidden`
- `fixture-opacity-zero`
- `fixture-parent-opacity-zero`
- `fixture-hidden-attribute`
- `fixture-inert-parent`
- `fixture-aria-hidden-parent`
- `fixture-zero-size`
- `fixture-offscreen-right`
- `fixture-fully-overflow-clipped`
`fixture-partially-overflow-clipped` must remain present because part of it is visible. Its screenshot must contain only the browser's final composited view.
### `unlabeled.html`
This page contains eight Canvas elements but must render seven generic Surface markers because
the two coincident layers form one group.
- Every marker uses the stable fallback label `canvas visual surface`.
- Exactly one marker has `layers=2`.
- The two contained canvases remain separate markers.
- `id`, `class`, `data-testid`, nearby prose, and fallback AX content never become a Surface label.
- Blank `aria-label` and `title` values behave as no label.
- Fallback AX content does not suppress the corresponding Surface.
### `frames.html`
Expected Surface labels:
- `fixture-same-origin-frame`
- `fixture-cross-origin-frame`
- `fixture-nested-frame`
The cross-origin frame uses `http://localhost:4173` while the parent uses `http://127.0.0.1:4173`. With Chromium site isolation this exercises the OOPIF path without an external service.
Each frame Canvas also exposes a `pointer status` live region. A successful
screenshot-bound point click must report
`down button=0 buttons=1 hoverReady=true; click received` and turn the Canvas
yellow. The hover flag is set on the animation frame after `pointermove`, so the
fixture verifies both child-document delivery and the scheduling boundary
required before `pointerdown`, rather than merely validating projected
coordinates or a successful CDP response.
### `viewport.html`
Run with a `900x700` Agent Window.
- `fixture-partial-viewport` is partly visible and must be represented.
- `fixture-below-fold` is absent initially.
- After scrolling it into view and observing again, `fixture-below-fold` must be represented with a fresh ref.
### `input-frames.html`
This page exercises generic frame-aware input routing. It contains a top-level
input plus same-origin, cross-origin (OOPIF), and nested frame inputs. Each
frame includes an input, textarea, contenteditable editor, an input that
replaces its DOM node after accepted input, an input that rejects synthetic
DOM events, a transient keyboard/IME input proxy that consumes and clears its
DOM value, and a controlled input that resets its value on the next animation
frame.
- `fill` must route focus, text insertion, DOM events, and readback through the
ref's owning CDP target.
- `press --ref` must focus and dispatch every key event through that same target.
- Untargeted `press` must follow the actual focused target or refuse when focus
ownership cannot be determined uniquely.
- The remounting input must retain the value through its replacement node.
- The trusted input must be filled without synthetic `input` / `change` events.
- `type` must deliver ASCII key events and committed non-ASCII IME/software
keyboard insertion to the input proxy. Its DOM value remains empty while
`proxy output` retains the consumed text; the result reports
`verification=dispatched`, not a retained DOM value.
- `type` must reject an omitted target unless `focused=true` is explicit, and
focused mode must reject focus that is not owned by a text-entry target.
- The rejecting input must return `input_not_applied`, never a successful
requested-value length.
### `canvas-input.html`
This is the PR3 end-to-end fixture. Its cross-origin frame contains a
visual-only three-row Canvas. A screenshot-bound click on row 3 exposes and
focuses a standard textbox; ordinary `fill` must then write and read back its
real value through the textbox's owning target. The fixture deliberately does
not provide a Canvas-specific fill action.
### `dynamic.html`
Use the normal DOM buttons and re-observe after each action:
- Initial state: `fixture-dynamic` absent.
- After **Insert canvas**: present.
- After **Resize to zero**: absent.
- After **Restore size**: present with a fresh ref.
- After **Remove canvas**: absent.
## Invariants
- `snapshot` must not emit any of these Surface markers.
- `observe` must emit only currently visible Canvas surfaces.
- Existing DOM/AX controls remain readable alongside Surface markers.
- Missing labels never prevent discovery; naming and discovery are independent.
- A Surface ref allows `screenshot --ref` and rejects ordinary click/fill/hover/select.
- No fixture URL, id, label, or layout constant may appear in production discovery code.
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Canvas to standard input fixture</title>
<style>
body { padding: 16px; font: 14px system-ui, sans-serif; }
iframe { width: 300px; height: 220px; border: 2px solid #5d6d7e; }
</style>
</head>
<body>
<h1>Canvas to standard input fixture</h1>
<p>Select row 3 in the visual-only Canvas, then fill the exposed standard textbox.</p>
<iframe
title="cross-origin Canvas editor"
src="http://localhost:4173/frame.html?label=canvas-input-grid&interactive=1&editor=1"
></iframe>
</body>
</html>
@@ -0,0 +1,46 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rendered Surface dynamic matrix</title>
<style>
html, body { margin: 0; font: 14px system-ui, sans-serif; }
body { padding: 16px; }
.controls { display: flex; gap: 8px; margin-bottom: 16px; }
button { padding: 8px 12px; }
canvas { display: block; width: 260px; height: 120px; background: #e8daef; border: 2px solid #7d3c98; }
</style>
</head>
<body>
<h1>Dynamic Canvas lifecycle</h1>
<div class="controls">
<button id="insert" type="button">Insert canvas</button>
<button id="zero" type="button">Resize to zero</button>
<button id="restore" type="button">Restore size</button>
<button id="remove" type="button">Remove canvas</button>
</div>
<div id="mount"></div>
<script>
const mount = document.querySelector("#mount");
const getCanvas = () => mount.querySelector("canvas");
document.querySelector("#insert").addEventListener("click", () => {
if (getCanvas()) return;
const canvas = document.createElement("canvas");
canvas.width = 260;
canvas.height = 120;
canvas.setAttribute("aria-label", "fixture-dynamic");
mount.append(canvas);
});
document.querySelector("#zero").addEventListener("click", () => {
const canvas = getCanvas();
if (canvas) canvas.style.cssText = "width:0;height:0;border:0";
});
document.querySelector("#restore").addEventListener("click", () => {
const canvas = getCanvas();
if (canvas) canvas.removeAttribute("style");
});
document.querySelector("#remove").addEventListener("click", () => getCanvas()?.remove());
</script>
</body>
</html>
@@ -0,0 +1,80 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
html, body { margin: 0; font: 14px system-ui, sans-serif; }
body { padding: 12px; background: #fdfefe; }
canvas { display: block; width: 220px; height: 90px; background: #d5f5e3; border: 2px solid #1e8449; }
iframe { width: 280px; height: 150px; margin-top: 10px; border: 2px solid #85929e; }
#pointer-status { margin: 8px 0 0; min-height: 20px; }
</style>
</head>
<body>
<canvas id="frame-canvas" width="220" height="90"></canvas>
<script>
const params = new URLSearchParams(location.search);
const canvas = document.querySelector("#frame-canvas");
if (params.get("canvas") === "0") canvas.remove();
else {
canvas.setAttribute("aria-label", params.get("label") || "fixture-frame-default");
if (params.get("editor") === "1") {
const context = canvas.getContext("2d");
context.font = "14px system-ui, sans-serif";
context.textBaseline = "middle";
context.strokeStyle = "#1e8449";
context.fillStyle = "#145a32";
for (let row = 0; row < 3; row += 1) {
const top = row * 30;
context.strokeRect(0.5, top + 0.5, 219, 29);
context.fillText(`Row ${row + 1}`, 12, top + 15);
}
}
if (params.get("interactive") === "1") {
const status = document.createElement("p");
status.id = "pointer-status";
status.setAttribute("aria-live", "polite");
status.textContent = "pointer status: idle";
canvas.insertAdjacentElement("afterend", status);
let hoverReady = false;
canvas.addEventListener("pointermove", () => {
hoverReady = false;
requestAnimationFrame(() => {
hoverReady = true;
});
});
canvas.addEventListener("pointerdown", (event) => {
status.textContent = `pointer status: down button=${event.button} buttons=${event.buttons} hoverReady=${hoverReady}`;
if (event.buttons === 1 && hoverReady) canvas.style.background = "#f9e79f";
});
canvas.addEventListener("click", () => {
status.textContent += "; click received";
});
if (params.get("editor") === "1") {
canvas.addEventListener("click", (event) => {
const rect = canvas.getBoundingClientRect();
const canvasY = ((event.clientY - rect.top) / rect.height) * canvas.height;
const row = Math.min(2, Math.max(0, Math.floor(canvasY / 30)));
status.textContent += `; selected row=${row + 1}`;
document.querySelector("#canvas-cell-editor")?.remove();
if (row !== 2) return;
const editor = document.createElement("input");
editor.id = "canvas-cell-editor";
editor.setAttribute("aria-label", "selected canvas cell editor");
editor.placeholder = "Type into selected row 3";
canvas.insertAdjacentElement("afterend", editor);
editor.focus();
});
}
}
}
if (params.get("nested") === "1") {
const iframe = document.createElement("iframe");
iframe.title = "nested fixture frame";
iframe.src = "frame.html?label=fixture-nested-frame&interactive=1";
document.body.append(iframe);
}
</script>
</body>
</html>
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rendered Surface frame matrix</title>
<style>
html, body { margin: 0; font: 14px system-ui, sans-serif; }
body { padding: 16px; }
.frames { display: grid; grid-template-columns: repeat(3, 320px); gap: 16px; }
iframe { width: 300px; height: 300px; border: 2px solid #5d6d7e; }
</style>
</head>
<body>
<h1>Frame matrix</h1>
<div class="frames">
<iframe title="same-origin fixture" src="frame.html?label=fixture-same-origin-frame&interactive=1"></iframe>
<iframe title="cross-origin fixture" src="http://localhost:4173/frame.html?label=fixture-cross-origin-frame&interactive=1"></iframe>
<iframe title="nested fixture" src="frame.html?canvas=0&nested=1"></iframe>
</div>
</body>
</html>
@@ -0,0 +1,118 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rendered Surface discovery matrix</title>
<style>
* { box-sizing: border-box; }
html, body { margin: 0; min-height: 100%; font: 14px/1.4 system-ui, sans-serif; }
body { padding: 16px; background: #f4f6f8; color: #17202a; }
h1 { margin: 0 0 12px; font-size: 20px; }
.matrix { display: grid; grid-template-columns: repeat(4, minmax(220px, 1fr)); gap: 12px; }
.case { min-height: 150px; padding: 10px; overflow: hidden; border: 1px solid #aeb6bf; border-radius: 6px; background: white; }
.case h2 { margin: 0 0 8px; font-size: 13px; }
canvas { display: block; background: #d6eaf8; border: 2px solid #2874a6; }
.stack { position: relative; width: 180px; height: 90px; }
.stack canvas { position: absolute; inset: 0; width: 180px; height: 90px; }
.stack canvas + canvas { background: rgb(244 208 63 / 45%); border-color: #b7950b; }
.contained { position: relative; width: 190px; height: 100px; }
.contained > canvas:first-child { width: 190px; height: 100px; }
.contained > canvas:last-child { position: absolute; left: 55px; top: 30px; width: 70px; height: 40px; background: #fadbd8; border-color: #c0392b; }
.same-place { position: relative; width: 180px; height: 90px; }
.same-place > div { position: absolute; inset: 0; }
.same-place canvas { width: 180px; height: 90px; }
.same-place > div:last-child canvas { border-color: #7d3c98; background: rgb(210 180 222 / 35%); }
.clip-box { width: 100px; height: 70px; overflow: hidden; border: 2px dashed #566573; }
.partially-clipped { width: 140px; height: 60px; transform: translateX(45px); }
.fully-clipped { width: 80px; height: 50px; transform: translateX(130px); }
.tiny { width: 8px; height: 8px; border-width: 1px; }
</style>
</head>
<body>
<h1>Rendered Surface discovery matrix</h1>
<main class="matrix">
<section class="case">
<h2>Visible named canvas</h2>
<canvas aria-label="fixture-basic-large" width="200" height="90"></canvas>
</section>
<section class="case">
<h2>Tiny canvas remains addressable</h2>
<canvas class="tiny" aria-label="fixture-tiny-8px" width="8" height="8"></canvas>
</section>
<section class="case">
<h2>Visible but pointer-events none</h2>
<canvas aria-label="fixture-pointer-events-none" width="180" height="80" style="pointer-events: none"></canvas>
</section>
<section class="case">
<h2>Partial AX/fallback content</h2>
<canvas aria-label="fixture-partial-ax" width="180" height="80">
<button type="button">Fallback button must not suppress the surface</button>
</canvas>
</section>
<section class="case">
<h2>Two real rendering layers</h2>
<div class="stack">
<canvas aria-label="fixture-layered-group" width="180" height="90"></canvas>
<canvas width="180" height="90"></canvas>
</div>
</section>
<section class="case">
<h2>Contained canvases are independent</h2>
<div class="contained">
<canvas aria-label="fixture-contained-outer" width="190" height="100"></canvas>
<canvas aria-label="fixture-contained-inner" width="70" height="40"></canvas>
</div>
</section>
<section class="case">
<h2>Same geometry, different parents</h2>
<div class="same-place">
<div><canvas aria-label="fixture-different-parent-a" width="180" height="90"></canvas></div>
<div><canvas aria-label="fixture-different-parent-b" width="180" height="90"></canvas></div>
</div>
</section>
<section class="case">
<h2>Partially overflow-clipped</h2>
<div class="clip-box">
<canvas class="partially-clipped" aria-label="fixture-partially-overflow-clipped" width="140" height="60"></canvas>
</div>
</section>
<section class="case">
<h2>Fully overflow-clipped</h2>
<div class="clip-box">
<canvas class="fully-clipped" aria-label="fixture-fully-overflow-clipped" width="80" height="50"></canvas>
</div>
</section>
<section class="case">
<h2>CSS-hidden variants</h2>
<canvas aria-label="fixture-display-none" width="80" height="40" style="display: none"></canvas>
<canvas aria-label="fixture-visibility-hidden" width="80" height="40" style="visibility: hidden"></canvas>
<canvas aria-label="fixture-opacity-zero" width="80" height="40" style="opacity: 0"></canvas>
</section>
<section class="case">
<h2>Hidden ancestor variants</h2>
<div style="opacity: 0"><canvas aria-label="fixture-parent-opacity-zero" width="80" height="40"></canvas></div>
<div hidden><canvas aria-label="fixture-hidden-attribute" width="80" height="40"></canvas></div>
<div inert><canvas aria-label="fixture-inert-parent" width="80" height="40"></canvas></div>
<div aria-hidden="true"><canvas aria-label="fixture-aria-hidden-parent" width="80" height="40"></canvas></div>
</section>
<section class="case">
<h2>Zero-size and offscreen</h2>
<canvas aria-label="fixture-zero-size" width="80" height="40" style="width: 0; height: 0; border: 0"></canvas>
<canvas aria-label="fixture-offscreen-right" width="80" height="40" style="position: fixed; left: 5000px; top: 0"></canvas>
</section>
</main>
</body>
</html>
@@ -0,0 +1,59 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body { margin: 0; padding: 12px; font: 14px system-ui, sans-serif; }
label, textarea, input, [contenteditable] { display: block; margin: 8px 0; }
input, textarea, [contenteditable] { width: 240px; padding: 6px; border: 1px solid #85929e; }
iframe { width: 280px; height: 190px; border: 2px solid #85929e; }
</style>
</head>
<body>
<label>Frame input <input aria-label="frame input" /></label>
<label>Frame textarea <textarea aria-label="frame textarea"></textarea></label>
<div contenteditable="true" aria-label="frame editor"></div>
<label>Remounting input <span id="remount-host"><input aria-label="remounting input" /></span></label>
<label>Trusted input <input id="trusted" aria-label="trusted input" /></label>
<label>Input proxy <input id="proxy" aria-label="input proxy" /></label>
<output id="proxy-output" aria-label="proxy output">proxy output: empty</output>
<label>Rejecting input <input id="rejecting" aria-label="rejecting input" /></label>
<script>
const params = new URLSearchParams(location.search);
const remountHost = document.querySelector("#remount-host");
const armRemount = (input) => {
input.addEventListener("input", () => {
const replacement = document.createElement("input");
replacement.setAttribute("aria-label", "remounting input");
replacement.value = input.value;
armRemount(replacement);
input.replaceWith(replacement);
replacement.focus();
}, { once: true });
};
armRemount(remountHost.querySelector("input"));
const trusted = document.querySelector("#trusted");
trusted.addEventListener("input", (event) => {
if (!event.isTrusted) requestAnimationFrame(() => { trusted.value = ""; });
});
const proxy = document.querySelector("#proxy");
const proxyOutput = document.querySelector("#proxy-output");
let proxyValue = "";
proxy.addEventListener("input", (event) => {
if (event.isComposing) return;
proxyValue += event.data ?? proxy.value;
proxy.value = "";
proxyOutput.textContent = `proxy output: ${proxyValue || "empty"}`;
});
const rejecting = document.querySelector("#rejecting");
rejecting.addEventListener("input", () => requestAnimationFrame(() => { rejecting.value = ""; }));
if (params.get("nested") === "1") {
const iframe = document.createElement("iframe");
iframe.title = "nested input frame";
iframe.src = "input-frame.html";
document.body.append(iframe);
}
</script>
</body>
</html>
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Frame input routing matrix</title>
<style>
body { padding: 16px; font: 14px system-ui, sans-serif; }
.frames { display: grid; grid-template-columns: repeat(3, 320px); gap: 16px; }
iframe { width: 300px; height: 430px; border: 2px solid #5d6d7e; }
input { padding: 6px; }
</style>
</head>
<body>
<h1>Frame input routing matrix</h1>
<label>Top input <input aria-label="top input" /></label>
<div class="frames">
<iframe title="same-origin inputs" src="input-frame.html"></iframe>
<iframe title="cross-origin inputs" src="http://localhost:4173/input-frame.html"></iframe>
<iframe title="nested inputs" src="input-frame.html?nested=1"></iframe>
</div>
</body>
</html>
@@ -0,0 +1,68 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Unlabeled Rendered Surface matrix</title>
<style>
* { box-sizing: border-box; }
html, body { margin: 0; min-height: 100%; font: 14px/1.4 system-ui, sans-serif; }
body { padding: 16px; background: #f4f6f8; color: #17202a; }
h1 { margin: 0 0 12px; font-size: 20px; }
.matrix { display: grid; grid-template-columns: repeat(3, minmax(240px, 1fr)); gap: 12px; }
.case { min-height: 150px; padding: 10px; overflow: hidden; border: 1px solid #aeb6bf; border-radius: 6px; background: white; }
.case h2 { margin: 0 0 8px; font-size: 13px; }
.case p { margin: 0 0 8px; }
canvas { display: block; background: #d6eaf8; border: 2px solid #2874a6; }
.stack { position: relative; width: 180px; height: 90px; }
.stack canvas { position: absolute; inset: 0; width: 180px; height: 90px; }
.stack canvas + canvas { background: rgb(244 208 63 / 45%); border-color: #b7950b; }
.contained { position: relative; width: 190px; height: 100px; }
.contained > canvas:first-child { width: 190px; height: 100px; }
.contained > canvas:last-child { position: absolute; left: 55px; top: 30px; width: 70px; height: 40px; background: #fadbd8; border-color: #c0392b; }
</style>
</head>
<body>
<h1>Unlabeled Rendered Surface matrix</h1>
<main class="matrix">
<section class="case">
<h2>Only engineering attributes</h2>
<canvas id="must-not-be-a-label" class="must-not-be-a-label" data-testid="must-not-be-a-label" width="200" height="90"></canvas>
</section>
<section class="case">
<h2>Blank explicit names</h2>
<canvas aria-label=" " title=" " width="180" height="80"></canvas>
</section>
<section class="case">
<h2>Nearby prose is not a Canvas name</h2>
<p>must-not-be-inferred-as-a-surface-label</p>
<canvas width="180" height="80"></canvas>
</section>
<section class="case">
<h2>Fallback AX content does not name or suppress the Canvas</h2>
<canvas width="180" height="80">
<button type="button">Fallback control remains separate</button>
</canvas>
</section>
<section class="case">
<h2>Unnamed rendering layers still cluster</h2>
<div class="stack">
<canvas width="180" height="90"></canvas>
<canvas width="180" height="90"></canvas>
</div>
</section>
<section class="case">
<h2>Unnamed contained canvases stay independent</h2>
<div class="contained">
<canvas width="190" height="100"></canvas>
<canvas width="70" height="40"></canvas>
</div>
</section>
</main>
</body>
</html>
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rendered Surface viewport matrix</title>
<style>
html, body { margin: 0; font: 14px system-ui, sans-serif; }
body { min-height: 1800px; padding: 16px; }
canvas { display: block; background: #fdebd0; border: 2px solid #ca6f1e; }
#partial { position: fixed; left: -70px; top: 120px; width: 180px; height: 100px; }
#below { position: absolute; left: 40px; top: 1350px; width: 240px; height: 120px; }
</style>
</head>
<body>
<h1>Viewport matrix</h1>
<p>The orange canvas on the left is intentionally clipped by the viewport.</p>
<canvas id="partial" aria-label="fixture-partial-viewport" width="180" height="100"></canvas>
<canvas id="below" aria-label="fixture-below-fold" width="240" height="120"></canvas>
</body>
</html>
+1
View File
@@ -44,6 +44,7 @@
"!packages/dsh-plugin-browserskill/src/client/bsk-ui.nomodule.css",
"!packages/dsh-plugin-browserskill/.bsk-ui.raw.css",
"!packages/dsh-plugin-browserskill/.bsk-ui.input.css",
"!evals/browser/results/**",
"!**/target/**",
"!**/.wxt/**",
"!**/.output/**",
+41 -8
View File
@@ -29,7 +29,7 @@ Drive the user's **real Chromium browser** (with their logins and cookies) throu
## Prerequisites
1. `bsk` on `PATH` (Rust CLI from browser-skill)
2. browser-skill **extension** loaded in Chromium and connected (popup shows green)
2. browser-skill **extension** loaded in Chromium and connected (popup shows green, or an upgrade reminder — still connected; continue)
3. Any `bsk` command auto-starts background services as needed; use `bsk doctor` if anything fails
## Mandatory workflow
@@ -70,16 +70,47 @@ bsk navigate <url> --session <id>
bsk observe --session <id> → primary semantic VOM view; reveals hover/focus surfaces
bsk snapshot --session <id> → static aria tree fallback when VOM is insufficient
bsk hover @e3 --session <id> → reveal hover-triggered menus before re-observing/clicking
bsk click @e4 --session <id> → or bsk fill, bsk select, bsk press
bsk click @e4 --session <id> → or bsk fill, bsk type, bsk select, bsk press
bsk observe --session <id> → again after navigation / DOM change
```
### Choosing `fill`, `type`, and `press`
Choose by the intended postcondition, not by whether observation happens to
render `textbox [empty]`:
- `fill` sets a field's retained value. Use it when success means the target
value must equal the requested text; it replaces existing content by default.
- `type` inserts text at the active caret/selection in a live editing session.
Use it when the application must consume keyboard/IME text; it never clears
first and reports dispatch only.
- `press` sends a discrete key or shortcut such as `Enter`, `Tab`, or `Ctrl+A`.
Do not encode special keys inside `type --text`.
`type` requires an explicit targeting mode: pass a ref/selector when one is
available, or pass `--focused` only after an immediately preceding action in
the same tab deliberately established a text-entry focus. Never use `fill`
as a probe and never automatically retry a failed `fill` with `type`: an
application may already have consumed the text before clearing its proxy DOM
value. Re-observe first. After `type`, verify the application output with one
observation or screenshot; `verification=dispatched` is not business success.
**Refs invalidate after navigation** — always re-snapshot before clicking, filling, or selecting on a new page.
Prefer `@eN` refs from the latest snapshot over raw CSS selectors. Use `--ref` / `--selector` when ambiguous (`bsk click --help`).
When VOM renders `[hover first: …]` on an element, the listed items are not currently clickable refs. Run `bsk hover <that-ref> --session <id>`, then immediately run `bsk snapshot` or `bsk observe` again and click the newly visible menu item ref. Do not click the trigger itself unless the user explicitly wants the trigger action.
When `bsk observe` renders `@eN surface ... [visual-only; requires=image-understanding; ...]`, the ref identifies rendered canvas content that is not represented by the text observation, not an interactable DOM control. Keep using any reliable DOM/AX text and controls that appear alongside it. If you lack multimodal or image-reading capability, do not take a screenshot and pretend to know its contents, and never guess coordinates; tell the user that they need to switch to a model with image-understanding capability.
If you can actually inspect image output, use `bsk screenshot --ref @eN --session <id>` to obtain the visible crop and its short-lived, single-use Surface capture id. Only when the task requires a point action and the image provides a clear target, bind that exact screenshot to the same general click command:
```bash
bsk click @eN --capture <capture-id> --image-x <px> --image-y <px> --session <id>
```
Coordinates are pixels in the returned capture image, not viewport CSS coordinates. Re-observing, navigating, scrolling, resizing, zooming, changing Frame projection, expiry, or reusing the capture makes the action fail; take a new Surface screenshot instead of adjusting or retrying coordinates. A point click does not reveal Canvas semantics and must not be followed by an assumed fill/type/press workflow. Re-observe first: if the application exposes a real DOM editable, use its new ref; use `type --focused` only when the observation and immediately preceding click establish a focused text-entry session without a usable ref. Without all three capture arguments, visual Surface refs remain screenshot-only and click/fill/type/hover/select reject them.
## Observation priority
Start with `bsk observe` to understand page structure, text, controls, element refs, and conditional hover/focus surfaces. Use `bsk snapshot` only when you need the stricter static accessibility tree or VOM is insufficient. Only escalate to raw HTML or screenshots when the latest observation cannot answer the question:
@@ -174,7 +205,7 @@ bsk emulate --session <id> --off
| `bsk snapshot` | First-choice static page understanding: accessibility tree with `@eN` element refs |
| `bsk observe` | Semantic VOM observation with bounded perception probes for conditional surfaces |
| `bsk get-html` | Raw HTML dump after snapshot is insufficient (high token cost) |
| `bsk screenshot` | PNG capture after snapshot is insufficient: full visible tab, or `--ref @eN` to crop to one element (`--out` path optional) |
| `bsk screenshot` | PNG capture after snapshot is insufficient: full visible tab, or `--ref @eN` to crop to one element (`--out` path optional); Surface crops return a short-lived capture id |
### Console & network debugging (read-only; require `--session`)
@@ -200,9 +231,11 @@ Both capture from the moment the tab is attached and read a bounded per-tab buff
| Command | Summary |
|---------|---------|
| `bsk click <ref-or-selector>` | Click element (`--button`, `--click-count`, `--modifiers`) |
| `bsk click <ref-or-selector>` | Click a DOM element (`--button`, `--click-count`, `--modifiers`), or perform one screenshot-bound Surface point click with `--capture`, `--image-x`, and `--image-y` |
| `bsk hover <ref-or-selector>` | Move the mouse to an element and wait for hover UI to settle (`--settle`, `--modifiers`) |
| `bsk fill <ref-or-selector> --value <text>` | Clear and type into input |
| `bsk fill <ref-or-selector> --value <text>` | Replace and verify a field's retained value |
| `bsk type <ref-or-selector> --text <text>` | Insert keyboard/IME text into an explicitly targeted editing session; reports dispatch only |
| `bsk type --focused --text <text>` | Insert into the unique focused text-entry session after an intentional focus-producing action |
| `bsk select <ref-or-selector> --value <v>` | Set `<select>` option(s) by `value` (repeat `--value` for multi-select) |
| `bsk press <key>` | Key/combo (`Enter`, `Ctrl+A`, …; optional `--ref` to focus first) |
@@ -210,7 +243,7 @@ Both capture from the moment the tab is attached and read a bounded per-tab buff
| Command | Summary |
|---------|---------|
| `bsk evaluate <expression>` | Run JS in agent tab (see red lines); JS throw → stderr, **exit 0** |
| `bsk evaluate <expression>` | Run JS in agent tab (see red lines). JS throw → stderr, **exit 0** (RPC success); use `--json` and check `.ok` to detect JS errors |
| `bsk wait-for-navigation` | Block until load/DOM idle/etc. (`--wait-until`, `--timeout`) |
| `bsk wait-ms <duration>` | Sleep (`500ms`, `2s`, `1m`; **no** `--session`) |
@@ -294,12 +327,12 @@ bsk record stop [--output trace] # terminal fallback if the browser panel is u
| Code | Meaning | What to do |
|------|---------|------------|
| `0` | Success (including `evaluate` where JS threw but RPC succeeded) | Continue |
| `0` | Success (including `evaluate` where JS threw but RPC succeeded) | Continue; for `evaluate`, check `--json` `.ok` to distinguish JS success from RPC success |
| `1` | User error — bad args, unknown session, tab not in Agent Window, stale ref | Fix args; `bsk session list`; re-snapshot |
| `2` | Protocol / transport — service unreachable, IPC failure | `bsk doctor`; check extension connected; retry the command |
| `3` | Browser / CDP execution failed | Retry; simplify selector; check tab still open |
| `4` | Timeout | Increase `--timeout`; try `--wait-until domcontentloaded` |
| `5` | Version skew (CLI vs extension) | Upgrade/reinstall matching versions |
| `5` | Unknown RPC method | This command is not implemented in the current build. Continue the task with other commands. If a newly added command is missing, suggest `bsk update`. |
Human errors print `error:` + `hint:` on stderr; `--json` includes `code`, `message`, `hint`, `exit_code`.
+18 -11
View File
@@ -351,10 +351,10 @@ fn check_version_compatible(status: Option<&StatusResult>) -> CheckResult {
}
}
/// `bsk doctor` check: every connected browser should use the same
/// protocol version as the daemon. Minor protocol drift is accepted by
/// the daemon but flagged here so the user can see who needs updating
/// (M10.4).
/// `bsk doctor` check: connected browsers should speak a protocol the
/// daemon accepts. A different protocol string is still a live
/// connection — report Ok so agents keep working. The detail is an
/// upgrade reminder, not a blocker.
///
/// Review M2 (round-1 minor): when no browsers are connected, the
/// check has nothing to compare against, so it now reports
@@ -396,13 +396,12 @@ fn check_browsers_protocol_compatible(status: Option<&StatusResult>) -> CheckRes
})
.collect::<Vec<_>>()
.join(", ");
CheckResult::fail(
CheckResult::ok(
name,
format!(
"{} browser(s) have protocol minor drift from the daemon: {stale}",
"{} browser(s) report a different protocol version (still usable — continue, and upgrade soon): {stale}",
status.version_skew_browsers.len()
),
"upgrade the browser-skill extension or bsk CLI so both sides use the same protocol version",
)
}
@@ -581,7 +580,7 @@ mod m2_tests {
}
#[test]
fn browsers_check_reports_fail_when_skew_present() {
fn browsers_check_reports_ok_when_skew_present() {
let status = fake_status(
vec![BrowserStatusEntry {
instance_id: "alpha".into(),
@@ -605,9 +604,17 @@ mod m2_tests {
}],
);
let check = check_browsers_protocol_compatible(Some(&status));
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.status, CheckStatus::Ok);
assert!(check.detail.contains("alpha"));
assert!(check.hint.is_some());
assert!(
check
.detail
.contains("still usable — continue, and upgrade soon")
);
assert!(
check.hint.is_none(),
"a protocol-version note must not hint to stop"
);
}
#[test]
@@ -635,7 +642,7 @@ mod m2_tests {
}],
);
let check = check_browsers_protocol_compatible(Some(&status));
assert_eq!(check.status, CheckStatus::Fail);
assert_eq!(check.status, CheckStatus::Ok);
assert!(
check
.detail
+188 -1
View File
@@ -11,7 +11,7 @@ use anyhow::Context;
use bsk_protocol::Method;
use bsk_protocol::tools::{
ClickParams, ClickResult, FillParams, FillResult, HoverParams, HoverResult, KeyModifier,
MouseButton, PressParams, PressResult, SelectParams, SelectResult,
MouseButton, PressParams, PressResult, SelectParams, SelectResult, TypeParams, TypeResult,
};
use clap::{Args, ValueEnum};
@@ -95,6 +95,27 @@ fn split_target(
}
}
fn split_type_target(
positional: Option<String>,
explicit_ref: Option<String>,
explicit_selector: Option<String>,
focused: bool,
) -> Result<(Option<String>, Option<String>), CliError> {
if focused {
if positional.is_some() || explicit_ref.is_some() || explicit_selector.is_some() {
return Err(CliError::Local(anyhow::anyhow!(
"pass a target or --focused, not both"
)));
}
return Ok((None, None));
}
split_target(positional, explicit_ref, explicit_selector).map_err(|_| {
CliError::Local(anyhow::anyhow!(
"type requires exactly one of: <target>, --ref, --selector, or --focused"
))
})
}
// ---------------------------------------------------------------------------
// bsk click
// ---------------------------------------------------------------------------
@@ -136,6 +157,18 @@ pub struct ClickArgs {
#[arg(long, default_value = "30s", value_parser = parse_timeout_ms)]
pub timeout: u32,
/// Capture id returned by `bsk screenshot --ref <surface>`.
#[arg(long)]
pub capture: Option<String>,
/// X coordinate in capture-image pixels. Requires `--capture` and `--image-y`.
#[arg(long = "image-x", allow_hyphen_values = true)]
pub image_x: Option<f64>,
/// Y coordinate in capture-image pixels. Requires `--capture` and `--image-x`.
#[arg(long = "image-y", allow_hyphen_values = true)]
pub image_y: Option<f64>,
}
pub fn dispatch_click(args: ClickArgs, format: Format) -> Result<(), CliError> {
@@ -147,6 +180,14 @@ pub fn dispatch_click(args: ClickArgs, format: Format) -> Result<(), CliError> {
)?;
let modifiers = parse_modifiers(&args.modifiers)
.map_err(|e| CliError::Local(anyhow::anyhow!("--modifiers: {e}")))?;
let point_arg_count = usize::from(args.capture.is_some())
+ usize::from(args.image_x.is_some())
+ usize::from(args.image_y.is_some());
if point_arg_count != 0 && point_arg_count != 3 {
return Err(CliError::Local(anyhow::anyhow!(
"--capture, --image-x, and --image-y must be given together"
)));
}
let params = ClickParams {
session_id: args.session.clone(),
ref_,
@@ -160,6 +201,9 @@ pub fn dispatch_click(args: ClickArgs, format: Format) -> Result<(), CliError> {
Some(modifiers)
},
timeout_ms: Some(args.timeout),
capture_id: args.capture.clone(),
image_x: args.image_x,
image_y: args.image_y,
};
let reply: ClickResult = call(
info.sock_path,
@@ -183,6 +227,14 @@ pub fn dispatch_click(args: ClickArgs, format: Format) -> Result<(), CliError> {
"click ok tab={} target={target} at=({}, {})",
reply.tab_id, reply.x, reply.y
);
if let Some(capture_id) = &reply.capture_id {
println!(
"capture={} image=({}, {}) coordinate_space=capture-image-pixel",
capture_id,
reply.image_x.unwrap_or_default(),
reply.image_y.unwrap_or_default()
);
}
print_dialog_summaries(&reply.dialogs);
}
}
@@ -352,6 +404,95 @@ pub fn dispatch_fill(args: FillArgs, format: Format) -> Result<(), CliError> {
Ok(())
}
// ---------------------------------------------------------------------------
// bsk type
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Args)]
#[group(id = "type_destination", required = true, multiple = false)]
pub struct TypeDestinationArgs {
/// Snapshot ref (`@e3`, `e3`) or CSS selector to focus before insertion.
#[arg(value_name = "TARGET")]
pub target: Option<String>,
#[arg(long = "ref")]
pub ref_: Option<String>,
#[arg(long = "selector")]
pub selector: Option<String>,
/// Insert into the unique focused text-entry target instead of focusing a target.
#[arg(long)]
pub focused: bool,
}
#[derive(Debug, Clone, Args)]
pub struct TypeArgs {
#[command(flatten)]
pub destination: TypeDestinationArgs,
/// Text to dispatch through the live keyboard/IME editing session.
#[arg(long)]
pub text: String,
#[arg(long)]
pub session: String,
#[arg(long = "tab-id")]
pub tab_id: Option<i64>,
#[arg(long, default_value = "30s", value_parser = parse_timeout_ms)]
pub timeout: u32,
}
pub fn dispatch_type(args: TypeArgs, format: Format) -> Result<(), CliError> {
let (ref_, selector) = split_type_target(
args.destination.target.clone(),
args.destination.ref_.clone(),
args.destination.selector.clone(),
args.destination.focused,
)?;
let info = ensure_daemon().context("ensure daemon is running")?;
let params = TypeParams {
session_id: args.session.clone(),
text: args.text.clone(),
ref_,
selector,
focused: args.destination.focused,
tab_id: args.tab_id,
timeout_ms: Some(args.timeout),
};
let reply: TypeResult = call(
info.sock_path,
Method::ToolType,
params,
"type-1",
args.timeout,
)?;
match format {
Format::Json => {
println!(
"{}",
serde_json::to_string_pretty(&reply)
.map_err(|e| CliError::Local(anyhow::anyhow!(e)))?
);
}
Format::Human => {
let target = if args.destination.focused {
"focused".into()
} else {
format_used_target(reply.used_ref.as_deref(), reply.used_selector.as_deref())
};
println!(
"type dispatched tab={} target={target} length={} verification=dispatched",
reply.tab_id, reply.text_length
);
print_dialog_summaries(&reply.dialogs);
}
}
Ok(())
}
// ---------------------------------------------------------------------------
// bsk press
// ---------------------------------------------------------------------------
@@ -628,6 +769,52 @@ mod tests {
assert_eq!(parsed.args.session, "ohli");
}
#[test]
fn type_clap_accepts_explicit_target_and_text_flag() {
use clap::Parser;
#[derive(Parser)]
#[command(name = "type")]
struct Wrapper {
#[command(flatten)]
args: TypeArgs,
}
let parsed =
Wrapper::try_parse_from(["type", "@e138", "--text", "测试", "--session", "ohli"])
.expect("type args should parse");
assert_eq!(parsed.args.destination.target.as_deref(), Some("@e138"));
assert_eq!(parsed.args.text, "测试");
assert_eq!(parsed.args.session, "ohli");
}
#[test]
fn type_targeting_requires_exactly_one_explicit_mode() {
use clap::Parser;
#[derive(Parser)]
#[command(name = "type")]
struct Wrapper {
#[command(flatten)]
args: TypeArgs,
}
let parsed =
Wrapper::try_parse_from(["type", "--focused", "--text", "测试", "--session", "ohli"])
.expect("focused type args should parse");
assert!(parsed.args.destination.focused);
assert!(parsed.args.destination.target.is_none());
let focused = split_type_target(None, None, None, true).unwrap();
assert_eq!(focused, (None, None));
let missing = split_type_target(None, None, None, false).unwrap_err();
assert!(missing.to_string().contains("--focused"));
let mixed = split_type_target(Some("@e1".into()), None, None, true).unwrap_err();
assert!(mixed.to_string().contains("not both"));
}
#[test]
fn select_clap_accepts_target_positional_with_repeated_value_flags() {
use clap::Parser;
+4 -1
View File
@@ -43,7 +43,7 @@ use crate::cli::evaluate::EvaluateArgs;
use crate::cli::get_html::GetHtmlArgs;
use crate::cli::human_loop::RequestHelpArgs;
use crate::cli::install_skill::InstallSkillArgs;
use crate::cli::interaction::{ClickArgs, FillArgs, HoverArgs, PressArgs, SelectArgs};
use crate::cli::interaction::{ClickArgs, FillArgs, HoverArgs, PressArgs, SelectArgs, TypeArgs};
use crate::cli::navigate::{NavigateCommand, NavigateHistoryArgs, ReloadArgs};
use crate::cli::network::NetworkArgs;
use crate::cli::observe::ObserveArgs;
@@ -171,6 +171,9 @@ pub enum Command {
/// Fill an input / textarea / contenteditable.
Fill(FillArgs),
/// Insert text into an explicit target or focused keyboard/IME editing session.
Type(TypeArgs),
/// Dispatch a keyboard key combo.
Press(PressArgs),
+111
View File
@@ -40,15 +40,23 @@ use bsk_protocol::ErrorCode;
pub mod reason {
pub const AGENT_WINDOW_SCOPE: &str = "agent_window_scope";
pub const ELEMENT_NOT_VISIBLE: &str = "element_not_visible";
pub const REF_CAPABILITY_DENIED: &str = "ref_capability_denied";
pub const REF_NOT_FOUND: &str = "ref_not_found";
pub const SELECTOR_NOT_FOUND: &str = "selector_not_found";
pub const TARGET_NOT_FILLABLE: &str = "target_not_fillable";
pub const FOCUS_TARGET_UNRESOLVED: &str = "focus_target_unresolved";
pub const INPUT_NOT_APPLIED: &str = "input_not_applied";
pub const TARGET_NOT_SELECT: &str = "target_not_select";
pub const OPTION_NOT_FOUND: &str = "option_not_found";
pub const SINGLE_SELECT_VALUE_COUNT: &str = "single_select_value_count";
pub const TAB_NOT_ACTIVE: &str = "tab_not_active";
pub const BORROW_CONFLICT: &str = "borrow_conflict";
pub const SCREENSHOT_CAPTURE_FAILED: &str = "screenshot_capture_failed";
pub const SURFACE_CAPTURE_NOT_FOUND: &str = "surface_capture_not_found";
pub const SURFACE_CAPTURE_EXPIRED: &str = "surface_capture_expired";
pub const SURFACE_CAPTURE_CONSUMED: &str = "surface_capture_consumed";
pub const SURFACE_CAPTURE_STALE: &str = "surface_capture_stale";
pub const SURFACE_COORDINATE_INVALID: &str = "surface_coordinate_invalid";
pub const SESSION_BUSY: &str = crate::rpc_reason::SESSION_BUSY;
pub const RECORD_START_PAGE_UNREACHABLE: &str = "record_start_page_unreachable";
}
@@ -228,6 +236,27 @@ pub fn info_for_error(code: ErrorCode, data: Option<&serde_json::Value>) -> Rend
),
exit_code: base.exit_code,
},
(ErrorCode::CdpFailed, reason::FOCUS_TARGET_UNRESOLVED) => RenderInfo {
summary: "focused frame target could not be determined",
hint: Some(
"pass an explicit --ref or --selector so the key event can be routed safely",
),
exit_code: base.exit_code,
},
(ErrorCode::CdpFailed, reason::INPUT_NOT_APPLIED) => RenderInfo {
summary: "the page did not retain the requested input",
hint: Some(
"refresh the snapshot and retry; the page may be rejecting or resetting controlled input",
),
exit_code: base.exit_code,
},
(ErrorCode::PermissionDenied, reason::REF_CAPABILITY_DENIED) => RenderInfo {
summary: "snapshot ref does not support this operation",
hint: Some(
"visual Surface refs require image understanding; inspect `bsk screenshot --ref <ref> --session <id>`, then bind its capture id and image coordinates to `bsk click`",
),
exit_code: base.exit_code,
},
(ErrorCode::InvalidParams, reason::TARGET_NOT_SELECT) => RenderInfo {
summary: "target element is not a <select>",
hint: Some(
@@ -270,6 +299,41 @@ pub fn info_for_error(code: ErrorCode, data: Option<&serde_json::Value>) -> Rend
),
exit_code: base.exit_code,
},
(ErrorCode::NotFound, reason::SURFACE_CAPTURE_NOT_FOUND) => RenderInfo {
summary: "surface capture transaction was not found",
hint: Some(
"take a fresh surface screenshot and use its capture id with coordinates from that image",
),
exit_code: base.exit_code,
},
(ErrorCode::PermissionDenied, reason::SURFACE_CAPTURE_EXPIRED) => RenderInfo {
summary: "surface capture transaction has expired",
hint: Some(
"take a fresh surface screenshot, then click promptly with that capture id and image coordinates",
),
exit_code: base.exit_code,
},
(ErrorCode::PermissionDenied, reason::SURFACE_CAPTURE_CONSUMED) => RenderInfo {
summary: "surface capture transaction was already used",
hint: Some(
"each capture id is single-use; take a fresh surface screenshot before another point action",
),
exit_code: base.exit_code,
},
(ErrorCode::PermissionDenied, reason::SURFACE_CAPTURE_STALE) => RenderInfo {
summary: "page state changed since the surface screenshot",
hint: Some(
"take a fresh surface screenshot and choose coordinates from the new image before retrying",
),
exit_code: base.exit_code,
},
(ErrorCode::InvalidParams, reason::SURFACE_COORDINATE_INVALID) => RenderInfo {
summary: "surface image coordinate is invalid",
hint: Some(
"use finite pixel coordinates inside the captured image; its top-left corner is (0, 0)",
),
exit_code: base.exit_code,
},
(
ErrorCode::CdpFailed | ErrorCode::Timeout | ErrorCode::InvalidParams,
reason::RECORD_START_PAGE_UNREACHABLE,
@@ -377,6 +441,18 @@ mod tests {
assert!(!info.summary.contains("sandbox"));
}
#[test]
fn ref_capability_denied_explains_visual_surface_refs() {
let data = serde_json::json!({ "reason": reason::REF_CAPABILITY_DENIED });
let info = info_for_error(ErrorCode::PermissionDenied, Some(&data));
assert_eq!(info.summary, "snapshot ref does not support this operation");
assert!(
info.hint.unwrap().contains("capture id"),
"expected visual-surface-specific hint"
);
assert_eq!(info.exit_code, 1);
}
#[test]
fn session_busy_overrides_timeout_copy() {
let data = serde_json::json!({ "reason": reason::SESSION_BUSY });
@@ -419,6 +495,25 @@ mod tests {
assert_eq!(info.exit_code, 3);
}
#[test]
fn surface_capture_stale_requests_a_fresh_screenshot() {
let data = serde_json::json!({ "reason": reason::SURFACE_CAPTURE_STALE });
let info = info_for_error(ErrorCode::PermissionDenied, Some(&data));
assert_eq!(
info.summary,
"page state changed since the surface screenshot"
);
assert!(info.hint.unwrap().contains("fresh surface screenshot"));
}
#[test]
fn surface_coordinate_invalid_explains_image_pixel_bounds() {
let data = serde_json::json!({ "reason": reason::SURFACE_COORDINATE_INVALID });
let info = info_for_error(ErrorCode::InvalidParams, Some(&data));
assert_eq!(info.summary, "surface image coordinate is invalid");
assert!(info.hint.unwrap().contains("top-left corner is (0, 0)"));
}
#[test]
fn ref_not_found_overrides_not_found_copy() {
let data = serde_json::json!({ "reason": reason::REF_NOT_FOUND });
@@ -453,4 +548,20 @@ mod tests {
);
assert!(info.hint.unwrap().contains("exactly one"));
}
#[test]
fn focus_target_unresolved_overrides_cdp_copy() {
let data = serde_json::json!({ "reason": reason::FOCUS_TARGET_UNRESOLVED });
let info = info_for_error(ErrorCode::CdpFailed, Some(&data));
assert_eq!(info.summary, "focused frame target could not be determined");
assert!(info.hint.unwrap().contains("--ref"));
}
#[test]
fn input_not_applied_overrides_cdp_copy() {
let data = serde_json::json!({ "reason": reason::INPUT_NOT_APPLIED });
let info = info_for_error(ErrorCode::CdpFailed, Some(&data));
assert_eq!(info.summary, "the page did not retain the requested input");
assert!(info.hint.unwrap().contains("rejecting"));
}
}
+11 -1
View File
@@ -59,7 +59,7 @@ fn run(sock: PathBuf, args: ScreenshotArgs, format: Format) -> Result<(), CliErr
.map_err(CliError::Local)?;
match format {
Format::Json => {
let json = serde_json::json!({
let mut json = serde_json::json!({
"tab_id": reply.tab_id,
"width": reply.width,
"height": reply.height,
@@ -67,6 +67,10 @@ fn run(sock: PathBuf, args: ScreenshotArgs, format: Format) -> Result<(), CliErr
"path": out_path.to_string_lossy(),
"byte_size": bytes.len(),
});
if let Some(capture) = &reply.capture {
json["capture"] = serde_json::to_value(capture)
.map_err(|e| CliError::Local(anyhow::anyhow!(e)))?;
}
println!(
"{}",
serde_json::to_string_pretty(&json)
@@ -75,6 +79,12 @@ fn run(sock: PathBuf, args: ScreenshotArgs, format: Format) -> Result<(), CliErr
}
Format::Human => {
println!("{}", out_path.display());
if let Some(capture) = &reply.capture {
println!(
"capture={} surface={} coordinate_space={} expires_at={}",
capture.id, capture.surface_ref, capture.coordinate_space, capture.expires_at
);
}
print_dialog_summaries(&reply.dialogs);
}
}
+2 -2
View File
@@ -65,7 +65,7 @@ fn render_human(s: &StatusResult) {
let bold = "\x1b[1m";
let reset = "\x1b[0m";
eprintln!(
"{bold}{yellow}warning:{reset} {} browser(s) have protocol version drift from the daemon{reset}",
"{bold}{yellow}note:{reset} {} browser(s) report a different protocol version; still usable — continue, and run `bsk update` soon{reset}",
s.version_skew_browsers.len()
);
for skew in &s.version_skew_browsers {
@@ -75,7 +75,7 @@ fn render_human(s: &StatusResult) {
skew.label.clone()
};
eprintln!(
" {} ({}) — protocol ext {} vs daemon {} (app ext v{}, daemon v{}) — please align protocol versions",
" {} ({}) — protocol ext {} vs CLI {} (app ext v{}, CLI v{}) — still usable; please upgrade",
skew.instance_id,
label,
display_protocol(&skew.client_protocol_version),
+1
View File
@@ -244,6 +244,7 @@ pub fn full_handler(status: DaemonStatus, state: Arc<DaemonState>) -> RpcHandler
| Method::ToolClick
| Method::ToolHover
| Method::ToolFill
| Method::ToolType
| Method::ToolPress
| Method::ToolSelect
| Method::ToolEvaluate
+1
View File
@@ -95,6 +95,7 @@ fn dispatch(cli: Cli, format: Format) -> Result<(), CliError> {
Command::Click(args) => cli::interaction::dispatch_click(args, format),
Command::Hover(args) => cli::interaction::dispatch_hover(args, format),
Command::Fill(args) => cli::interaction::dispatch_fill(args, format),
Command::Type(args) => cli::interaction::dispatch_type(args, format),
Command::Press(args) => cli::interaction::dispatch_press(args, format),
Command::Select(args) => cli::interaction::dispatch_select(args, format),
Command::Evaluate(args) => cli::evaluate::dispatch(args, format),
+23
View File
@@ -188,6 +188,29 @@ fn parses_click_count_alias() {
assert_eq!(args.click_count, 2);
}
#[test]
fn parses_surface_capture_image_coordinates() {
let cli = parse(&[
"bsk",
"click",
"@e1",
"--session",
"s1",
"--capture",
"sc_test",
"--image-x",
"160.5",
"--image-y",
"-1",
]);
let Command::Click(args) = cli.command else {
panic!("expected click command");
};
assert_eq!(args.capture.as_deref(), Some("sc_test"));
assert_eq!(args.image_x, Some(160.5));
assert_eq!(args.image_y, Some(-1.0));
}
#[test]
fn parses_hover_with_settle() {
let cli = parse(&[
+2
View File
@@ -238,6 +238,7 @@ async fn screenshot_returns_image_base64_with_dimensions() {
height: 600,
format: "png".into(),
tab_id: 7,
capture: None,
dialogs: vec![],
})
.unwrap(),
@@ -286,6 +287,7 @@ async fn screenshot_forwards_ref_to_extension() {
height: 60,
format: "png".into(),
tab_id: 7,
capture: None,
dialogs: vec![],
})
.unwrap(),
+75 -3
View File
@@ -1,5 +1,4 @@
//! M7 integration: drive the 7 new tool RPCs (navigate /
//! navigate_back / navigate_forward / reload / click / fill / press)
//! M7 integration: drive the navigation and interaction tool RPCs
//! through the IPC + per-session queue + fake extension and assert
//! the wire shapes line up. The extension stub mirrors each method's
//! `*Result` so we exercise the daemon's serialise → forward →
@@ -16,7 +15,8 @@ use bsk_protocol::tools::{
ClickParams, ClickResult, FillParams, FillResult, KeyModifier, MouseButton, NavigateBackParams,
NavigateBackResult, NavigateForwardParams, NavigateForwardResult, NavigateParams,
NavigateResult, PressParams, PressResult, ReloadParams, ReloadResult, SelectParams,
SelectResult, SessionStartParams, SessionStartResult, WaitUntil,
SelectResult, SessionStartParams, SessionStartResult, TypeParams, TypeResult, TypeVerification,
WaitUntil,
};
use bsk_protocol::{
BrowserPeerInfo, ErrorCode, Frame, Method, RequestFrame, ResponseBody, ResponseFrame, RpcError,
@@ -354,6 +354,9 @@ async fn click_round_trips_ref_and_modifiers() {
used_selector: None,
x: 12.5,
y: 34.0,
capture_id: None,
image_x: None,
image_y: None,
dialogs: vec![],
})
.unwrap(),
@@ -373,6 +376,9 @@ async fn click_round_trips_ref_and_modifiers() {
click_count: Some(1),
modifiers: Some(vec![KeyModifier::Ctrl, KeyModifier::Shift]),
timeout_ms: Some(5_000),
capture_id: None,
image_x: None,
image_y: None,
},
)
.await
@@ -427,6 +433,51 @@ async fn fill_round_trips_clear_before_default() {
handle.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn type_round_trips_dispatched_verification() {
let (handle, sock) = spawn_daemon().await;
let mut ws = connect_ext(handle.ws_addr()).await;
let _ = do_handshake(&mut ws).await;
run_extension(ws, |req| {
assert_eq!(req.method, Method::ToolType);
let p: TypeParams = serde_json::from_value(req.params.clone().unwrap()).unwrap();
assert_eq!(p.text, "测试");
assert!(!p.focused);
ResponseBody::Ok(
serde_json::to_value(TypeResult {
tab_id: 12,
used_ref: Some("e3".into()),
used_selector: None,
text_length: 2,
verification: TypeVerification::Dispatched,
dialogs: vec![],
})
.unwrap(),
)
});
let session_id = ipc_session_start(&sock).await;
let result: TypeResult = ipc_tool_call(
&sock,
Method::ToolType,
TypeParams {
session_id,
text: "测试".into(),
ref_: Some("@e3".into()),
selector: None,
focused: false,
tab_id: None,
timeout_ms: Some(5_000),
},
)
.await
.expect("type ok");
assert_eq!(result.text_length, 2);
assert_eq!(result.verification, TypeVerification::Dispatched);
handle.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn press_round_trips_compound_key() {
let (handle, sock) = spawn_daemon().await;
@@ -529,6 +580,7 @@ async fn m7_tools_propagate_extension_errors() {
| Method::ToolReload
| Method::ToolClick
| Method::ToolFill
| Method::ToolType
| Method::ToolPress
| Method::ToolSelect => ResponseBody::Err(RpcError {
code: ErrorCode::CdpFailed,
@@ -610,6 +662,9 @@ async fn m7_tools_propagate_extension_errors() {
click_count: None,
modifiers: None,
timeout_ms: Some(5_000),
capture_id: None,
image_x: None,
image_y: None,
},
)
.await
@@ -633,6 +688,23 @@ async fn m7_tools_propagate_extension_errors() {
.unwrap_err();
assert_eq!(fill.code, ErrorCode::CdpFailed);
let type_result = ipc_tool_call::<_, Value>(
&sock,
Method::ToolType,
TypeParams {
session_id: session_id.clone(),
text: "hello".into(),
ref_: Some("@e1".into()),
selector: None,
focused: false,
tab_id: None,
timeout_ms: Some(5_000),
},
)
.await
.unwrap_err();
assert_eq!(type_result.code, ErrorCode::CdpFailed);
let press = ipc_tool_call::<_, Value>(
&sock,
Method::ToolPress,
@@ -16,6 +16,13 @@
}
]
},
"capture_id": {
"description": "Short-lived capture id returned by a visual Surface screenshot.",
"type": [
"string",
"null"
]
},
"click_count": {
"description": "Number of consecutive mouse presses (double-click = 2).",
"type": [
@@ -25,6 +32,22 @@
"format": "uint32",
"minimum": 1.0
},
"image_x": {
"description": "X coordinate in the capture image's pixel coordinate space.",
"type": [
"number",
"null"
],
"format": "double"
},
"image_y": {
"description": "Y coordinate in the capture image's pixel coordinate space.",
"type": [
"number",
"null"
],
"format": "double"
},
"modifiers": {
"type": [
"array",
@@ -8,6 +8,12 @@
"y"
],
"properties": {
"capture_id": {
"type": [
"string",
"null"
]
},
"dialogs": {
"description": "Native JS dialogs observed and auto-handled during this call.",
"type": "array",
@@ -15,6 +21,20 @@
"$ref": "#/definitions/JavaScriptDialogInfo"
}
},
"image_x": {
"type": [
"number",
"null"
],
"format": "double"
},
"image_y": {
"type": [
"number",
"null"
],
"format": "double"
},
"tab_id": {
"type": "integer",
"format": "int64"
@@ -8,6 +8,16 @@
"tab_id"
],
"properties": {
"capture": {
"anyOf": [
{
"$ref": "#/definitions/SurfaceCaptureInfo"
},
{
"type": "null"
}
]
},
"dialogs": {
"type": "array",
"items": {
@@ -109,6 +119,31 @@
"prompt",
"beforeunload"
]
},
"SurfaceCaptureInfo": {
"type": "object",
"required": [
"coordinate_space",
"expires_at",
"id",
"surface_ref"
],
"properties": {
"coordinate_space": {
"type": "string"
},
"expires_at": {
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"id": {
"type": "string"
},
"surface_ref": {
"type": "string"
}
}
}
}
}
@@ -26,7 +26,7 @@
"format": "int64"
},
"text": {
"description": "Indented aria-snapshot text. Refs are rendered as `@e<N>` so the agent can copy them into subsequent `tool.click` / `tool.fill` selectors.",
"description": "Indented aria-snapshot text. Refs are rendered as `@e<N>` so the agent can copy them into subsequent `tool.click` / `tool.fill` / `tool.type` targets.",
"type": "string"
},
"truncated": {
@@ -0,0 +1,50 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "TypeParams",
"type": "object",
"required": [
"session_id",
"text"
],
"properties": {
"focused": {
"description": "Explicitly dispatch to the unique focused text-entry target instead of focusing a ref or selector.",
"type": "boolean"
},
"ref": {
"description": "Target to focus before dispatching text. Exactly one targeting mode must be selected: `ref` / `selector`, or `focused=true`.",
"type": [
"string",
"null"
]
},
"selector": {
"type": [
"string",
"null"
]
},
"session_id": {
"type": "string"
},
"tab_id": {
"type": [
"integer",
"null"
],
"format": "int64"
},
"text": {
"description": "Text to dispatch to the live editing session. Unlike `fill`, `type` does not require the focused DOM editable to retain this text.",
"type": "string"
},
"timeout_ms": {
"type": [
"integer",
"null"
],
"format": "uint32",
"minimum": 1.0
}
}
}
@@ -0,0 +1,124 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "TypeResult",
"type": "object",
"required": [
"tab_id",
"text_length",
"verification"
],
"properties": {
"dialogs": {
"type": "array",
"items": {
"$ref": "#/definitions/JavaScriptDialogInfo"
}
},
"tab_id": {
"type": "integer",
"format": "int64"
},
"text_length": {
"description": "UTF-16 code-unit length of text accepted for dispatch.",
"type": "integer",
"format": "uint32",
"minimum": 0.0
},
"used_ref": {
"type": [
"string",
"null"
]
},
"used_selector": {
"type": [
"string",
"null"
]
},
"verification": {
"$ref": "#/definitions/TypeVerification"
}
},
"definitions": {
"JavaScriptDialogHandledAction": {
"description": "How the extension resolved the dialog so CDP could continue.",
"type": "string",
"enum": [
"accepted",
"dismissed"
]
},
"JavaScriptDialogInfo": {
"description": "One observed + handled JavaScript dialog during a tool call.",
"type": "object",
"required": [
"handled",
"message",
"sequence",
"tab_id",
"type"
],
"properties": {
"default_prompt": {
"type": [
"string",
"null"
]
},
"handled": {
"$ref": "#/definitions/JavaScriptDialogHandledAction"
},
"has_browser_handler": {
"type": [
"boolean",
"null"
]
},
"message": {
"type": "string"
},
"sequence": {
"description": "Monotonic per-tab sequence for ordering within a session.",
"type": "integer",
"format": "uint64",
"minimum": 0.0
},
"tab_id": {
"type": "integer",
"format": "int64"
},
"type": {
"$ref": "#/definitions/JavaScriptDialogType"
},
"url": {
"type": [
"string",
"null"
]
}
}
},
"JavaScriptDialogType": {
"description": "Native JS dialog kind reported by CDP.",
"type": "string",
"enum": [
"alert",
"confirm",
"prompt",
"beforeunload"
]
},
"TypeVerification": {
"oneOf": [
{
"description": "Chromium accepted the complete keyboard/IME dispatch transaction. The caller must observe the application output to verify business state.",
"type": "string",
"enum": [
"dispatched"
]
}
]
}
}
}
@@ -81,6 +81,8 @@ fn main() {
dump!(HoverResult, "tool_hover_result");
dump!(FillParams, "tool_fill_params");
dump!(FillResult, "tool_fill_result");
dump!(TypeParams, "tool_type_params");
dump!(TypeResult, "tool_type_result");
dump!(PressParams, "tool_press_params");
dump!(PressResult, "tool_press_result");
dump!(SelectParams, "tool_select_params");
+11
View File
@@ -74,6 +74,8 @@ pub enum Method {
ToolHover,
#[serde(rename = "tool.fill")]
ToolFill,
#[serde(rename = "tool.type")]
ToolType,
#[serde(rename = "tool.press")]
ToolPress,
#[serde(rename = "tool.select")]
@@ -154,6 +156,7 @@ impl Method {
| Method::ToolReload
| Method::ToolClick
| Method::ToolFill
| Method::ToolType
| Method::ToolPress
| Method::ToolSelect
| Method::ToolEvaluate
@@ -246,6 +249,13 @@ mod tests {
assert_eq!(serde_json::to_value(method).unwrap(), json!("tool.emulate"));
}
#[test]
fn type_method_round_trips() {
let method: Method = serde_json::from_value(json!("tool.type")).unwrap();
assert_eq!(method, Method::ToolType);
assert_eq!(serde_json::to_value(method).unwrap(), json!("tool.type"));
}
#[test]
fn cancel_params_and_result_round_trip() {
let params: CancelParams = serde_json::from_value(json!({ "rpc_id": "wait-1" })).unwrap();
@@ -284,6 +294,7 @@ mod tests {
assert!(Method::ToolReload.is_mutating());
assert!(Method::ToolClick.is_mutating());
assert!(Method::ToolFill.is_mutating());
assert!(Method::ToolType.is_mutating());
assert!(Method::ToolPress.is_mutating());
assert!(Method::ToolSelect.is_mutating());
assert!(Method::ToolEvaluate.is_mutating());
+118 -2
View File
@@ -1,5 +1,5 @@
//! DOM interaction tools (`tool.click`, `tool.fill`, `tool.press`,
//! `tool.select`).
//! DOM interaction tools (`tool.click`, `tool.fill`, `tool.type`,
//! `tool.press`, `tool.select`).
//!
//! Element-targeted tools accept either a snapshot `ref` (`@e<N>` form,
//! normalised against the session's RefStore) **or** a CSS selector
@@ -67,6 +67,15 @@ pub struct ClickParams {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(range(min = 1))]
pub timeout_ms: Option<u32>,
/// Short-lived capture id returned by a visual Surface screenshot.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capture_id: Option<String>,
/// X coordinate in the capture image's pixel coordinate space.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_x: Option<f64>,
/// Y coordinate in the capture image's pixel coordinate space.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_y: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
@@ -80,6 +89,12 @@ pub struct ClickResult {
/// agents can correlate with a follow-up `tool.screenshot`.
pub x: f64,
pub y: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capture_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_x: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_y: Option<f64>,
/// Native JS dialogs observed and auto-handled during this call.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dialogs: Vec<JavaScriptDialogInfo>,
@@ -173,6 +188,60 @@ pub struct FillResult {
pub dialogs: Vec<JavaScriptDialogInfo>,
}
// ---------------------------------------------------------------------------
// type
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TypeParams {
pub session_id: String,
/// Text to dispatch to the live editing session. Unlike `fill`, `type`
/// does not require the focused DOM editable to retain this text.
pub text: String,
/// Target to focus before dispatching text. Exactly one targeting mode
/// must be selected: `ref` / `selector`, or `focused=true`.
#[serde(
rename = "ref",
alias = "ref_",
default,
skip_serializing_if = "Option::is_none"
)]
pub ref_: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub selector: Option<String>,
/// Explicitly dispatch to the unique focused text-entry target instead
/// of focusing a ref or selector.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub focused: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tab_id: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(range(min = 1))]
pub timeout_ms: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TypeVerification {
/// Chromium accepted the complete keyboard/IME dispatch transaction.
/// The caller must observe the application output to verify business state.
Dispatched,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TypeResult {
pub tab_id: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub used_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub used_selector: Option<String>,
/// UTF-16 code-unit length of text accepted for dispatch.
pub text_length: u32,
pub verification: TypeVerification,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dialogs: Vec<JavaScriptDialogInfo>,
}
// ---------------------------------------------------------------------------
// press
// ---------------------------------------------------------------------------
@@ -288,6 +357,9 @@ mod tests {
click_count: Some(1),
modifiers: Some(vec![KeyModifier::Ctrl]),
timeout_ms: Some(5_000),
capture_id: Some("sc_test".into()),
image_x: Some(160.0),
image_y: Some(90.0),
};
let v = serde_json::to_value(&p).unwrap();
assert_eq!(v.get("ref").and_then(|v| v.as_str()), Some("@e3"));
@@ -333,6 +405,50 @@ mod tests {
assert_eq!(v, json!("meta"));
}
#[test]
fn type_payloads_distinguish_dispatch_from_value_verification() {
let params = TypeParams {
session_id: "abcd".into(),
text: "测试".into(),
ref_: Some("@e3".into()),
selector: None,
focused: false,
tab_id: Some(4),
timeout_ms: Some(5_000),
};
let encoded = serde_json::to_value(&params).unwrap();
assert_eq!(encoded["ref"], json!("@e3"));
assert_eq!(encoded["text"], json!("测试"));
assert!(encoded.get("focused").is_none());
let focused = TypeParams {
session_id: "abcd".into(),
text: "hello".into(),
ref_: None,
selector: None,
focused: true,
tab_id: None,
timeout_ms: None,
};
assert_eq!(
serde_json::to_value(focused).unwrap()["focused"],
json!(true)
);
let result = TypeResult {
tab_id: 4,
used_ref: Some("e3".into()),
used_selector: None,
text_length: 2,
verification: TypeVerification::Dispatched,
dialogs: vec![],
};
assert_eq!(
serde_json::to_value(result).unwrap()["verification"],
json!("dispatched")
);
}
#[test]
fn press_result_round_trips() {
let r = PressResult {
+18 -2
View File
@@ -33,8 +33,8 @@ pub struct SnapshotParams {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SnapshotResult {
/// Indented aria-snapshot text. Refs are rendered as `@e<N>` so the
/// agent can copy them into subsequent `tool.click` / `tool.fill`
/// selectors.
/// agent can copy them into subsequent `tool.click` / `tool.fill` /
/// `tool.type` targets.
pub text: String,
/// Number of `@e<N>` refs registered for this session by this
/// snapshot. Equivalent to the size of the new ref-store map.
@@ -208,10 +208,20 @@ pub struct ScreenshotResult {
/// Always `"png"` in v0.1; reserved for future JPEG / WebP support.
pub format: String,
pub tab_id: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capture: Option<SurfaceCaptureInfo>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub dialogs: Vec<JavaScriptDialogInfo>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SurfaceCaptureInfo {
pub id: String,
pub surface_ref: String,
pub coordinate_space: String,
pub expires_at: u64,
}
#[cfg(test)]
mod tests {
use super::*;
@@ -293,6 +303,12 @@ mod tests {
height: 600,
format: "png".into(),
tab_id: 7,
capture: Some(SurfaceCaptureInfo {
id: "sc_test".into(),
surface_ref: "@e3".into(),
coordinate_space: "capture-image-pixel".into(),
expires_at: 1_700_000_030_000,
}),
dialogs: vec![],
};
let v = serde_json::to_value(&r).unwrap();
+259
View File
@@ -0,0 +1,259 @@
# Browser capability evaluation corpus
This directory is a deterministic, local browser evaluation environment for BrowserSkill, DSH,
and other command-line agents. Cases, fixture pages, direct `bsk` workflows, and assertions are
data-driven and discovered automatically. Adding a case does not require editing a central switch.
[中文说明](README.zh-CN.md)
## Design goals
- Agent-neutral: prompts describe observable page goals so the same cases can run through different
agents and adapters.
- Deterministic: pages run locally and use stable markers and run-scoped events.
- Extensible: manifests, fixture modules, and workflows are auto-discovered.
- Reproducible: generated cases record a seed and derive every DOM variation from it.
- Honest verification: page-observable results, response markers, and adapter evidence are reported
separately. Missing adapter evidence is `unverified`, never silently treated as passed.
- Privacy-safe: user badcases must be reduced to synthetic DOM and anonymized data before commit.
The corpus currently has six stable `core` cases and one seeded `matrix` case. The operation
inventory contains 28 browser operations; that count is capability coverage, not the number of
cases. Cases can grow independently and many cases may cover the same operation under different
page conditions.
## Quick start
These commands validate manifests and run unit/integration tests without launching a browser:
```sh
pnpm eval:browser validate
pnpm eval:browser list
pnpm eval:browser coverage
pnpm eval:browser:test
```
Build the repository CLI and exercise the real CLI, daemon, extension, Agent Window, and pages:
```sh
cargo build -p bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite core --bsk ./target/debug/bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite matrix --seed 4,7,14 --bsk ./target/debug/bsk
```
Every smoke case starts a fresh browser session and stops it in a `finally` cleanup path. Reports
and screenshots are written to the ignored `evals/browser/results/` directory.
`pnpm run eval:browser -- coverage` is also supported. The CLI intentionally accepts pnpm's leading
`--` separator.
## Suites and selection
| Suite | Intended use | Default execution |
| --- | --- | --- |
| `core` | Small stable acceptance set for everyday smoke and CI | Yes |
| `matrix` | Seeded DOM, timing, and layout variations | Explicit |
| `regression` | Minimized user badcases tied to an issue or fix | Explicit |
| `stress` | Higher volume or slower boundary testing | Explicit |
| `manual` | Human-dependent capabilities that cannot be deterministic | Explicit |
`smoke` and `run-agent` default to `core`, so adding a stress or regression case cannot silently
slow down existing CI. `list`, `coverage`, and `validate` inspect the full corpus by default.
```sh
pnpm eval:browser list --suite core
pnpm eval:browser list --tag form
pnpm eval:browser smoke --case form-controls
pnpm eval:browser smoke --case form-controls,generated-form
pnpm eval:browser smoke --case all
```
Filters from different dimensions are combined. Repeated/comma-separated suites or case ids are
alternatives; every requested tag must be present. `--task` remains a backward-compatible alias for
`--case`.
## Directory and discovery model
```text
evals/browser/
cases/
core/*.case.json
matrix/*.case.json
regression/<case-id>/
<case-id>.case.json
<case-id>.fixture.mjs
README.md
fixtures/pages/*.fixture.mjs
schemas/case.schema.json
lib/
tests/
```
- Any `cases/**/*.case.json` file is loaded as a case manifest.
- Any `fixtures/**/*.fixture.mjs` or `cases/**/*.fixture.mjs` file is registered as a fixture.
- Manifests are ordered by suite, optional numeric `order`, then id.
- `validate` rejects duplicate case ids, duplicate routes, missing fixture routes, unknown
operations/actions, invalid workflow variables, and adapter assertions with no evidence producer.
## Case manifest
A case owns all information needed by both an agent evaluation and direct CLI smoke:
```json
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "example-case",
"title": "Example browser behavior",
"order": 10,
"suite": "core",
"tags": ["form", "keyboard"],
"seed": 17,
"fixture": { "startPath": "/example" },
"prompts": { "en": "Open {url} ...", "zh-CN": "打开 {url}……" },
"coverage": ["page.navigate", "interact.press"],
"assertions": { "site": [], "response": [], "adapter": [] },
"smoke": { "steps": [{ "action": "navigate" }] }
}
```
Prompt placeholders are `{url}`, `{baseUrl}`, `{runId}`, and `{seed}`. Agent adapter arguments also
support `{prompt}`, `{caseId}` / `{taskId}`, and `{variant}`.
Assertions have three independent sources:
- `site`: events emitted by the local page, such as submitted values or a history navigation.
- `response`: stable text that must appear in the agent or CLI output.
- `adapter`: facts outside page JavaScript, such as a non-empty screenshot or confirmed session
cleanup.
The declarative smoke workflow supports navigation/history, waits, observe/snapshot/HTML,
screenshot/console/network, click/hover/fill/select/press, tabs, resize/emulation, and the manual
ownership/help operations. A step may `saveAs` its JSON result and later reference values such as
`{child.tab_id}`. A step may set `evidence` for an adapter assertion. See existing manifests for
complete examples.
## Adding a normal case
1. Add a `*.fixture.mjs` module exporting `{ id, routes, render(context) }`. It can live in shared
`fixtures/pages/` or beside a self-contained regression case.
2. Add a `*.case.json` manifest with prompts, operation coverage, assertions, and smoke steps.
3. Make all page events run-scoped using the shared `browserEval.send(...)` client helper.
4. Run `pnpm eval:browser validate` and `pnpm eval:browser:test`.
5. Run the new case against the real local build with `smoke --case <id>`.
Prefer one behavior or failure mechanism per case. Stable synthetic markers make failures easier to
diagnose than assertions against incidental prose.
## Turning a user badcase into a regression
Create a self-contained starting point:
```sh
pnpm eval:browser scaffold reported-timeout \
--title "Navigation settles after a late frame" \
--source "issue-123"
```
The command creates a manifest, fixture, and reproduction notes under
`cases/regression/reported-timeout/`. Then reduce the report to the smallest relevant mechanism:
- Keep DOM structure, timing, redirects, frames, or browser state that triggers the bug.
- Replace names, account data, URLs, tokens, screenshots, and page copy with synthetic values.
- Do not commit HAR files, cookies, credentials, production HTML, or proprietary assets.
- Record the issue/PR reference, seed when relevant, expected result, and the fixing PR.
- Confirm the new case fails on the known-bad build and passes on the fixed build when practical.
## Seeded matrix cases
`generated-form` varies label association, nesting depth, hydration delay, decoy controls, field
order, and element ids while keeping the task and oracle stable. Inspect a seed without a browser:
```sh
pnpm eval:browser generate --seed user-badcase-42
pnpm eval:browser prompt generated-form --seed user-badcase-42 --run-id manual-42
pnpm eval:browser smoke --case generated-form --seed user-badcase-42
pnpm eval:browser smoke --case generated-form --seed 4,7,14
```
Repeated/comma-separated seeds run as independent results. Reports store every normalized seed, so
a failure can be replayed exactly and promoted into a named regression case if it represents a
distinct bug.
## Run any command-line agent
Copy `agents.example.json` to the ignored `agents.local.json` and adapt its command. Arguments are
passed directly to the executable without a shell.
```sh
pnpm eval:browser run-agent \
--config evals/browser/agents.local.json \
--agent dsh-local \
--suite core \
--repeat 3
```
An adapter may define `command`, `args`, `cwd`, `env`, `timeoutMs`, `variant`, free-form `metadata`,
and optional `metrics.errorPattern` / `metrics.toolCallPattern` regular expressions.
To compare 28 granular tools with domain tools, create two isolated adapter entries and run both
against the same selected cases and seeds:
```sh
pnpm eval:browser run-agent \
--config evals/browser/agents.local.json \
--agent dsh-granular,dsh-domain \
--suite core \
--repeat 10
```
Keep browser runs sequential to avoid session contention. Use fresh profiles and alternate adapter
order in larger experiments to reduce warm-cache bias.
## Reading results
```sh
pnpm eval:browser summarize evals/browser/results/*.json
```
The summary groups by adapter and variant and reports pass rate, fully verified rate, process
failures, matched error count, average tool calls, and average duration. The raw JSON retains case,
suite, tags, seed, prompt, command output, page event count, and individual oracle checks.
A healthy run has:
- no execution timeout or non-zero exit;
- no `executionError` in direct smoke;
- `verification.status` equal to `passed` (or intentionally `passed-with-unverified` for an agent
adapter that cannot expose external evidence);
- every session cleanup assertion verified;
- no unexpected increase in errors, tool calls, or duration versus the chosen baseline.
## Development baseline
Use these lanes as commit and PR gates:
| Change | Required checks |
| --- | --- |
| Any case, fixture, oracle, or harness change | `pnpm eval:browser:check` |
| CLI, daemon, extension, DSH plugin, or browser-operation change | The check above, `cargo build -p bsk`, then real-browser `smoke --suite core` |
| DOM discovery, form interaction, timing, or waiting change | The checks above, then `smoke --suite matrix --seed 4,7,14` |
| A bug fix with a known reproduction | Add a `regression` case and run that case on the fixed build |
Before committing this harness, the complete acceptance sequence is:
```sh
pnpm eval:browser:check
cargo build -p bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --case all --bsk ./target/debug/bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite matrix --seed 4,7,14 --bsk ./target/debug/bsk
```
All commands must exit zero. The smoke summary must have 100% pass and fully verified rates, zero
execution failures/errors, and `bsk session list --json` must be `[]` afterward. Do not weaken an
oracle or replace a stable marker merely to make a regression pass; behavior changes should update
the case and expected baseline in the same reviewed change.
The direct smoke lane covers 25 of 28 operations. `tabs.borrow`, `tabs.return`, and
`assist.request-help` stay manual because they require a real user tab or human interaction and
would make the default suite destructive or non-deterministic.
+197
View File
@@ -0,0 +1,197 @@
# 浏览器能力测试语料库
这里是一套供 BrowserSkill、DSH 以及其他命令行 Agent 共用的本地确定性浏览器测试环境。
case、测试页面、`bsk` 直连流程和断言都会自动发现;新增 case 不需要修改中央 `switch`。
[English](README.md)
## 核心原则
- 与 Agent 无关:prompt 只描述可观察的页面目标,同一套 case 可以被不同 Agent 和
adapter 使用。
- 本地且确定:页面只依赖本地服务,使用稳定 marker 和按 run 隔离的事件。
- 可扩展:manifest、fixture 和 workflow 都从目录自动发现。
- 可复现:生成式页面的所有变化由 seed 决定,报告会保留 seed。
- 如实验证:页面事件、回答文本和 adapter 外部证据分别统计;拿不到的证据标为
`unverified`,不会冒充通过。
- 隐私安全:用户 badcase 必须先缩减为合成 DOM 和匿名数据,再进入仓库。
当前有 6 个稳定的 `core` case 和 1 个 seed 驱动的 `matrix` case。28 表示浏览器操作能力
清单,并不是 case 数量;同一种操作可以在不同页面结构、时序和浏览器状态下由多个 case
重复覆盖。
## 快速使用
不启动浏览器的校验:
```sh
pnpm eval:browser validate
pnpm eval:browser list
pnpm eval:browser coverage
pnpm eval:browser:test
```
使用仓库当前代码编译 `bsk`,再跑真实 CLI、daemon、扩展、小窗和页面链路:
```sh
cargo build -p bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite core --bsk ./target/debug/bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite matrix --seed 4,7,14 --bsk ./target/debug/bsk
```
每个 smoke case 都会创建独立 session,并在 `finally` 中关闭。JSON 报告和截图输出到已被
Git 忽略的 `evals/browser/results/`。
也可以写成 `pnpm run eval:browser -- coverage`;CLI 已兼容 pnpm 传入的前导 `--`。
## Suite 与筛选
| Suite | 用途 | 默认执行 |
| --- | --- | --- |
| `core` | 日常 smoke 和 CI 使用的小而稳定的验收集 | 是 |
| `matrix` | seed 驱动的 DOM、时序、布局组合 | 显式选择 |
| `regression` | 从用户 badcase 缩减并与 issue/修复关联的回归 | 显式选择 |
| `stress` | 更高次数或更慢的边界测试 | 显式选择 |
| `manual` | 必须依赖真人或真实用户标签页的能力 | 显式选择 |
`smoke` 和 `run-agent` 不带筛选时只跑 `core`,所以以后新增 stress/badcase 不会突然拖慢
已有 CI。`list`、`coverage`、`validate` 默认检查全部语料。
```sh
pnpm eval:browser list --suite core
pnpm eval:browser list --tag form
pnpm eval:browser smoke --case form-controls
pnpm eval:browser smoke --case form-controls,generated-form
pnpm eval:browser smoke --case all
```
不同维度的筛选会叠加;逗号分隔的 suite/case 是“或”,多个 tag 必须全部命中。旧参数
`--task` 仍作为 `--case` 的兼容别名。
## 自动发现结构
```text
evals/browser/
cases/
core/*.case.json
matrix/*.case.json
regression/<case-id>/
<case-id>.case.json
<case-id>.fixture.mjs
README.md
fixtures/pages/*.fixture.mjs
schemas/case.schema.json
lib/
tests/
```
- `cases/**/*.case.json` 都会作为 case manifest 加载。
- `fixtures/**/*.fixture.mjs` 和 `cases/**/*.fixture.mjs` 都会注册为页面 fixture。
- 顺序按 suite、可选的数字 `order`、id 排列。
- `validate` 会阻止重复 case id、重复路由、缺失 fixture、未知操作/action、无效 workflow
变量,以及没有任何步骤产出的 adapter evidence。
一个 manifest 同时描述:中英文 prompt、能力 coverage、页面事件/回答/adapter 三类断言,以及
`bsk` 直连 smoke 的声明式步骤。prompt 可用 `{url}`、`{baseUrl}`、`{runId}`、`{seed}`;
workflow 可以用 `saveAs` 保存 JSON 结果,并用 `{child.tab_id}` 之类的变量引用后续步骤。
完整写法可直接参考 `cases/core/` 和 `cases/matrix/`。
## 新增普通 case
1. 新增导出 `{ id, routes, render(context) }` 的 `*.fixture.mjs`,可放共享 fixture 目录,也可
和 regression case 放在一起。
2. 新增 `*.case.json`,写好 prompt、operation coverage、断言和 smoke steps。
3. 页面使用共享的 `browserEval.send(...)` 上报按 run 隔离的事件。
4. 执行 `pnpm eval:browser validate` 和 `pnpm eval:browser:test`。
5. 用 `smoke --case <id>` 验证真实本地编译链路。
建议一个 case 只表达一种行为或故障机制,并使用稳定的合成 marker,避免断言偶然文案。
## 把用户 badcase 固化成回归
先生成一个自包含模板:
```sh
pnpm eval:browser scaffold reported-timeout \
--title "Navigation settles after a late frame" \
--source "issue-123"
```
它会在 `cases/regression/reported-timeout/` 下生成 manifest、fixture 和复现说明。随后只保留
真正触发问题的 DOM 结构、时序、跳转、frame 或浏览器状态,并遵守:
- 所有姓名、账号、网址、token、截图和文案都替换为合成值。
- 不提交 HAR、cookie、凭据、生产 HTML 或私有素材。
- 记录 issue/PR 来源、相关 seed、期望行为和后续修复 PR。
- 条件允许时,证明新 case 在旧版本失败、修复版本通过。
## Seed 矩阵
`generated-form` 会确定性改变 label 关联方式、DOM 嵌套、hydration 延迟、干扰控件、字段
顺序和 element id,但任务和 oracle 保持不变:
```sh
pnpm eval:browser generate --seed user-badcase-42
pnpm eval:browser prompt generated-form --seed user-badcase-42 --run-id manual-42
pnpm eval:browser smoke --case generated-form --seed user-badcase-42
pnpm eval:browser smoke --case generated-form --seed 4,7,14
```
逗号分隔或重复的 seed 会生成相互独立的结果。任何失败都能按报告中的规范化 seed 精确重放;
若它代表独立 bug,再提升为命名 regression case。
## 测任意 Agent 与比较 28/6 工具
把 `agents.example.json` 复制为已被 Git 忽略的 `agents.local.json`,分别配置两个隔离的 Agent
profile/build。参数以数组直接传给可执行程序,不经过 shell。
```sh
pnpm eval:browser run-agent \
--config evals/browser/agents.local.json \
--agent dsh-granular,dsh-domain \
--suite core \
--repeat 10
```
浏览器任务应串行运行,避免 session 竞争;更大实验中使用干净 profile 并轮换 adapter 顺序,
降低缓存偏差。
## 如何看结果
```sh
pnpm eval:browser summarize evals/browser/results/*.json
```
汇总按 adapter/variant 展示通过率、完全验证率、进程失败、错误数、平均工具调用数和耗时。
原始 JSON 会保留 case、suite、tag、seed、prompt、命令输出、页面事件数和每条 oracle 结果。
健康运行应满足:没有 timeout/非零退出,direct smoke 没有 `executionError`,验证状态为
`passed`(无法暴露外部证据的 Agent adapter 可明确为 `passed-with-unverified`),session cleanup
通过,并且错误数、调用数和耗时没有相对基线异常上涨。
## 开发基准线
后续开发统一按下面的门禁执行:
| 改动范围 | 必跑检查 |
| --- | --- |
| 任意 case、fixture、oracle 或 harness 改动 | `pnpm eval:browser:check` |
| CLI、daemon、扩展、DSH 插件或浏览器操作改动 | 上述检查、`cargo build -p bsk`、真实浏览器 `smoke --suite core` |
| DOM 发现、表单交互、时序或等待逻辑改动 | 上述检查,再跑 `smoke --suite matrix --seed 4,7,14` |
| 修复已有明确复现的 bug | 新增 `regression` case,并在修复版本单独运行该 case |
提交这套 harness 前,完整验收命令为:
```sh
pnpm eval:browser:check
cargo build -p bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --case all --bsk ./target/debug/bsk
BSK_AUTO_UPDATE=off pnpm eval:browser smoke --suite matrix --seed 4,7,14 --bsk ./target/debug/bsk
```
所有命令必须以 0 退出;smoke 汇总必须达到 100% pass、100% fully verified、0 execution
failure/error,结束后 `bsk session list --json` 必须为 `[]`。不能为了让回归通过而削弱 oracle
或替换稳定 marker;如果产品行为确实改变,case 与预期基线必须在同一个受审查改动中更新。
直连 smoke 自动覆盖 28 项中的 25 项。`tabs.borrow`、`tabs.return`、`assist.request-help` 需要
真实用户标签页或真人交互,因此保留在 manual lane,避免默认测试具有破坏性或不确定性。
+17
View File
@@ -0,0 +1,17 @@
{
"agents": {
"dsh-local": {
"variant": "granular-28",
"command": "dsh",
"args": ["--profile", "headless", "{prompt}"],
"cwd": "../..",
"timeoutMs": 300000,
"metadata": {
"toolCount": 28
},
"metrics": {
"toolCallPattern": "browser[_-][a-z_-]+"
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
# Browser evaluation cases
Cases are discovered recursively from `*.case.json`; colocated `*.fixture.mjs` files are discovered
as fixtures. Use `core` for small deterministic acceptance checks, `matrix` for seeded variations,
and `regression/<case-id>/` for privacy-safe minimized user badcases.
Run `pnpm eval:browser validate` after every case change. See the parent
[`README.md`](../README.md) for the manifest contract, workflow actions, scaffolding, and acceptance
criteria.
@@ -0,0 +1,48 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "diagnostics",
"title": "Console and network inspection",
"order": 50,
"suite": "core",
"tags": ["console", "network", "diagnostics"],
"fixture": { "startPath": "/diagnostics" },
"prompts": {
"en": "Open {url}. Use browser diagnostics to inspect the page console and recent network activity. Report the console marker and the token returned by the ping request, then close the browser session.",
"zh-CN": "打开 {url}。使用浏览器诊断能力检查页面 console 和最近的 network 活动,报告 console marker 以及 ping 请求返回的 token,最后关闭浏览器会话。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"inspect.console",
"inspect.network"
],
"assertions": {
"site": [
{
"label": "diagnostic ping completed",
"type": "network.ping",
"minCount": 1
}
],
"response": [
{ "label": "reported console marker", "includes": "CONSOLE-61" },
{ "label": "reported network token", "includes": "NETWORK-73" }
],
"adapter": [
{ "label": "console inspection was executed", "key": "consoleRead" },
{ "label": "network inspection was executed", "key": "networkRead" },
{ "label": "browser session was closed", "key": "sessionStopped" }
]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{ "action": "wait", "duration": "300ms" },
{ "action": "console", "evidence": "consoleRead" },
{ "action": "network", "evidence": "networkRead" },
{ "action": "observe" }
]
}
}
@@ -0,0 +1,82 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "form-controls",
"title": "Form, select, keyboard, and screenshot",
"order": 20,
"suite": "core",
"tags": ["form", "keyboard", "screenshot", "select"],
"fixture": { "startPath": "/form" },
"prompts": {
"en": "Open {url}. Fill Text input with \"agent-parity\" and Textarea with \"BrowserSkill works\". Select the visible option \"Two\" from Dropdown. Capture a screenshot of the form, focus Submit, and press Enter to submit. Confirm that the result says \"Received!\", then close the browser session.",
"zh-CN": "打开 {url}。把 Text input 填成“agent-parity”,Textarea 填成“BrowserSkill works”,Dropdown 选择可见选项“Two”。截取表单截图,然后聚焦 Submit 并按 Enter 提交。确认结果页出现“Received!”,最后关闭浏览器会话。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"interact.fill",
"interact.select",
"interact.press",
"inspect.screenshot"
],
"assertions": {
"site": [
{
"label": "Enter was pressed on Submit",
"type": "form.enter_pressed",
"minCount": 1
},
{
"label": "form values were submitted",
"type": "form.submitted",
"where": {
"data.text": "agent-parity",
"data.notes": "BrowserSkill works",
"data.choice": "two"
},
"minCount": 1
},
{
"label": "result page was displayed",
"type": "page.shown",
"where": { "data.path": "/result" },
"minCount": 1
}
],
"response": [{ "label": "confirmed result", "includes": "Received!" }],
"adapter": [
{ "label": "screenshot artifact was created", "key": "screenshotCreated" },
{ "label": "browser session was closed", "key": "sessionStopped" }
]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{
"action": "fill",
"selector": "#text-input",
"value": "agent-parity"
},
{
"action": "fill",
"selector": "#notes",
"value": "BrowserSkill works"
},
{ "action": "select", "selector": "#choice", "values": ["two"] },
{
"action": "screenshot",
"artifactName": "form.png",
"evidence": "screenshotCreated"
},
{ "action": "press", "key": "Enter", "selector": "#submit" },
{
"action": "wait-site-event",
"type": "page.shown",
"where": { "path": "/result" }
},
{ "action": "wait", "duration": "200ms" },
{ "action": "observe" }
]
}
}
@@ -0,0 +1,59 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "hover-inspect",
"title": "Hover, local HTML, and screenshot",
"order": 30,
"suite": "core",
"tags": ["hover", "html", "screenshot"],
"fixture": { "startPath": "/hover-inspect" },
"prompts": {
"en": "Open {url}. Hover over Account, then choose Profile beta from the revealed menu. Inspect the local HTML around the Inspection card and capture a screenshot. Report both marker codes you find, then close the browser session.",
"zh-CN": "打开 {url}。把鼠标悬停在“Account”上,然后点击展开菜单中的“Profile beta”。检查 Inspection card 附近的局部 HTML,并截取页面截图。报告找到的两个标记代码,最后关闭浏览器会话。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"interact.hover",
"interact.click",
"inspect.html",
"inspect.screenshot"
],
"assertions": {
"site": [
{
"label": "Account menu was hovered",
"type": "hover.menu_opened",
"minCount": 1
},
{
"label": "Profile beta was selected",
"type": "hover.profile_clicked",
"minCount": 1
}
],
"response": [
{ "label": "reported hover marker", "includes": "HOVER-17" },
{ "label": "reported HTML marker", "includes": "INSPECT-27" }
],
"adapter": [
{ "label": "HTML inspection was executed", "key": "htmlInspected" },
{ "label": "screenshot artifact was created", "key": "screenshotCreated" },
{ "label": "browser session was closed", "key": "sessionStopped" }
]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{ "action": "hover", "selector": "#account-menu" },
{ "action": "click", "selector": "#profile-link" },
{ "action": "html", "evidence": "htmlInspected" },
{
"action": "screenshot",
"artifactName": "hover-inspect.png",
"evidence": "screenshotCreated"
}
]
}
}
@@ -0,0 +1,43 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "mobile-emulation",
"title": "Mobile emulation",
"order": 60,
"suite": "core",
"tags": ["emulation", "mobile", "viewport"],
"fixture": { "startPath": "/responsive" },
"prompts": {
"en": "Open {url}, emulate an iPhone 14, and report the viewport marker shown on the page. Close the browser session when finished.",
"zh-CN": "打开 {url},模拟 iPhone 14,并报告页面显示的 viewport marker。完成后关闭浏览器会话。"
},
"coverage": ["session.start", "session.stop", "page.navigate", "assist.emulate"],
"assertions": {
"site": [
{
"label": "iPhone-sized viewport was observed",
"type": "viewport.sample",
"where": { "data.width": 390, "data.height": 844 },
"minCount": 1
}
],
"response": [{ "label": "reported viewport marker", "includes": "VIEWPORT-84" }],
"adapter": [
{ "label": "device emulation was executed", "key": "emulatedDevice" },
{ "label": "browser session was closed", "key": "sessionStopped" }
]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{ "action": "resize", "width": 900, "height": 700 },
{
"action": "emulate",
"device": "iphone-14",
"evidence": "emulatedDevice"
},
{ "action": "wait", "duration": "300ms" },
{ "action": "html" }
]
}
}
@@ -0,0 +1,67 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "navigation-history",
"title": "Navigation, history, and reload",
"order": 10,
"suite": "core",
"tags": ["navigation", "history", "reload"],
"fixture": { "startPath": "/navigation/start" },
"prompts": {
"en": "Open {url}. Read the main heading, follow the Details link, and report the code shown there. Then go back, go forward, reload the page, and close the browser session. Use only the browser capability for page operations.",
"zh-CN": "打开 {url}。读取页面主标题,点击“详情”,并报告详情页上的代码。然后依次后退、前进、刷新页面,最后关闭浏览器会话。页面操作只使用浏览器能力。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"page.back",
"page.forward",
"page.reload",
"interact.click"
],
"assertions": {
"site": [
{
"label": "details link was clicked",
"type": "navigation.detail.clicked",
"minCount": 1
},
{
"label": "back returned to the start page",
"type": "page.shown",
"where": { "data.path": "/navigation/start" },
"minCount": 2
},
{
"label": "forward returned to the detail page",
"type": "page.shown",
"where": { "data.path": "/navigation/detail" },
"minCount": 2
},
{
"label": "detail page was reloaded",
"type": "page.shown",
"where": {
"data.path": "/navigation/detail",
"data.navigationType": "reload"
},
"minCount": 1
}
],
"response": [{ "label": "reported detail code", "includes": "NAV-42" }],
"adapter": [{ "label": "browser session was closed", "key": "sessionStopped" }]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{ "action": "observe" },
{ "action": "snapshot" },
{ "action": "click", "selector": "#details-link" },
{ "action": "html" },
{ "action": "back" },
{ "action": "forward" },
{ "action": "reload" }
]
}
}
+71
View File
@@ -0,0 +1,71 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "tabs",
"title": "Create, select, and close a tab",
"order": 40,
"suite": "core",
"tags": ["tabs", "ownership", "lifecycle"],
"fixture": { "startPath": "/tabs" },
"prompts": {
"en": "Open {url}. Create a new browser tab at {baseUrl}/tabs/child?run={runId}, read its token, click \"Mark child visited\", close the child tab, return to the original tab, and close the browser session.",
"zh-CN": "打开 {url}。新建一个浏览器标签页并访问 {baseUrl}/tabs/child?run={runId},读取其中的 token,点击“Mark child visited”,关闭子标签页,回到原标签页,最后关闭浏览器会话。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"interact.click",
"tabs.create",
"tabs.select",
"tabs.close"
],
"assertions": {
"site": [
{
"label": "child tab page was displayed",
"type": "page.shown",
"where": { "data.path": "/tabs/child" },
"minCount": 1
},
{
"label": "child tab action ran",
"type": "tabs.child_marked",
"minCount": 1
}
],
"response": [{ "label": "reported child token", "includes": "TAB-29" }],
"adapter": [
{ "label": "child tab was closed", "key": "childTabClosed" },
{ "label": "browser session was closed", "key": "sessionStopped" }
]
},
"smoke": {
"steps": [
{ "action": "navigate", "saveAs": "original" },
{ "action": "tab-list" },
{
"action": "tab-create",
"url": "{baseUrl}/tabs/child?run={runId}",
"saveAs": "child"
},
{
"action": "navigate",
"url": "{baseUrl}/tabs/child?run={runId}",
"tabId": "{child.tab_id}"
},
{
"action": "click",
"selector": "#mark-child",
"tabId": "{child.tab_id}"
},
{ "action": "html", "tabId": "{child.tab_id}" },
{
"action": "tab-close",
"tabId": "{child.tab_id}",
"evidence": "childTabClosed"
},
{ "action": "tab-select", "tabId": "{original.tab_id}" }
]
}
}
+5
View File
@@ -0,0 +1,5 @@
# Seeded matrix cases
Matrix cases vary page structure or timing deterministically from a recorded seed. The task,
assertions, and success marker remain stable so a failed seed can be replayed exactly. A seed that
exposes a distinct product bug should be minimized and promoted to a named regression case.
@@ -0,0 +1,77 @@
{
"$schema": "../../schemas/case.schema.json",
"schemaVersion": 1,
"id": "generated-form",
"title": "Seeded form structure and hydration variants",
"order": 10,
"suite": "matrix",
"tags": ["dynamic-dom", "form", "hydration", "seeded"],
"seed": 20260827,
"fixture": { "startPath": "/matrix/generated-form" },
"prompts": {
"en": "Open {url}. Wait for the seeded form to finish hydrating. Fill Text input with \"seeded-agent\", select the visible option \"Two\", submit with Enter, and report the result marker and seed. Close the browser session.",
"zh-CN": "打开 {url}。等待 seeded form 完成 hydration,把 Text input 填成“seeded-agent”,选择可见选项“Two”,用 Enter 提交,并报告结果 marker 和 seed。最后关闭浏览器会话。"
},
"coverage": [
"session.start",
"session.stop",
"page.navigate",
"page.wait",
"inspect.observe",
"interact.fill",
"interact.select",
"interact.press"
],
"assertions": {
"site": [
{ "label": "generated form hydrated", "type": "matrix.ready", "minCount": 1 },
{
"label": "Enter was pressed on generated form",
"type": "matrix.enter_pressed",
"minCount": 1
},
{
"label": "generated values were submitted",
"type": "matrix.submitted",
"where": { "data.text": "seeded-agent", "data.choice": "two" },
"minCount": 1
},
{
"label": "matrix result page was displayed",
"type": "page.shown",
"where": { "data.path": "/matrix/generated-result" },
"minCount": 1
}
],
"response": [
{ "label": "reported matrix result", "includes": "MATRIX-OK" },
{ "label": "reported selected seed", "includes": "SEED-" }
],
"adapter": [{ "label": "browser session was closed", "key": "sessionStopped" }]
},
"smoke": {
"steps": [
{ "action": "navigate" },
{
"action": "wait-site-event",
"type": "matrix.ready",
"timeoutMs": 5000
},
{ "action": "observe" },
{ "action": "fill", "selector": "[name=text]", "value": "seeded-agent" },
{ "action": "select", "selector": "[name=choice]", "values": ["two"] },
{
"action": "press",
"key": "Enter",
"selector": "button[type=submit]"
},
{
"action": "wait-site-event",
"type": "page.shown",
"where": { "path": "/matrix/generated-result" }
},
{ "action": "wait", "duration": "200ms" },
{ "action": "observe" }
]
}
}
+12
View File
@@ -0,0 +1,12 @@
# Regression cases
Each user-reported badcase should live in its own directory with a manifest, synthetic fixture, and
README describing the symptom, minimal reproduction, expected behavior, source reference, and fix.
Never commit credentials, cookies, HAR files, production HTML, private screenshots, or proprietary
assets.
Create a starting point with:
```sh
pnpm eval:browser scaffold <case-id> --title "..." --source "issue-or-pr"
```
+467
View File
@@ -0,0 +1,467 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { loadAgentConfig, runCommandTask } from "./lib/agent-runner.mjs";
import { runBskSmokeTask } from "./lib/bsk-runner.mjs";
import { buildOperationCoverage } from "./lib/coverage.mjs";
import { loadFixtureRegistry } from "./lib/fixture-registry.mjs";
import { verifyTask } from "./lib/oracle.mjs";
import { resultsDirectory } from "./lib/paths.mjs";
import { repositorySummary, validateRepositoryCases } from "./lib/repository-validation.mjs";
import { scaffoldCase } from "./lib/scaffold-case.mjs";
import { describeSeed, normalizeSeed } from "./lib/seeded-generator.mjs";
import { createEvalServer } from "./lib/server.mjs";
import { printSummary, summarizeReports } from "./lib/summary.mjs";
import { allTasks, getTask, listTasks, renderPrompt } from "./lib/tasks.mjs";
const booleanOptions = new Set(["help", "json"]);
function parseArguments(argv) {
const normalized = argv[0] === "--" ? argv.slice(1) : argv;
let [command, ...rest] = normalized;
const options = new Map();
const positionals = [];
if (command === "--help" || command === "-h") {
command = undefined;
options.set("help", [true]);
}
for (let index = 0; index < rest.length; index += 1) {
const argument = rest[index];
if (!argument.startsWith("--")) {
positionals.push(argument);
continue;
}
const equals = argument.indexOf("=");
const name = argument.slice(2, equals === -1 ? undefined : equals);
let value = equals === -1 ? undefined : argument.slice(equals + 1);
if (value === undefined && !booleanOptions.has(name)) {
const candidate = rest[index + 1];
if (candidate === undefined || candidate.startsWith("--")) {
throw new Error(`--${name} requires a value`);
}
value = candidate;
index += 1;
}
const values = options.get(name) ?? [];
values.push(value ?? true);
options.set(name, values);
}
return { command, options, positionals };
}
function option(parsed, name, fallback) {
return parsed.options.get(name)?.at(-1) ?? fallback;
}
function optionList(parsed, name) {
return (parsed.options.get(name) ?? [])
.flatMap((value) => String(value).split(","))
.map((value) => value.trim())
.filter(Boolean);
}
function numericOption(parsed, name, fallback) {
const value = Number(option(parsed, name, fallback));
if (!Number.isFinite(value) || value < 0) throw new Error(`--${name} must be non-negative`);
return value;
}
function seedOptions(parsed, fallback) {
const requested = optionList(parsed, "seed");
return requested.length > 0 ? unique(requested.map(normalizeSeed)) : [fallback];
}
function seedOption(parsed, fallback) {
const seeds = seedOptions(parsed, fallback);
if (seeds.length > 1) throw new Error("this command accepts only one --seed value");
return seeds[0];
}
function unique(values) {
return [...new Set(values)];
}
function selectCases(cases, parsed, { defaultSuite } = {}) {
const requestedIds = unique([...optionList(parsed, "case"), ...optionList(parsed, "task")]);
const requestedSuites = unique(optionList(parsed, "suite"));
const requestedTags = unique(optionList(parsed, "tag"));
const hasSelector =
requestedIds.length > 0 || requestedSuites.length > 0 || requestedTags.length > 0;
if (requestedIds.includes("all") && requestedIds.length > 1) {
throw new Error("--case all cannot be combined with named cases");
}
if (requestedSuites.includes("all") && requestedSuites.length > 1) {
throw new Error("--suite all cannot be combined with named suites");
}
const caseIds = requestedIds.includes("all") ? [] : requestedIds;
const suites = requestedSuites.includes("all")
? []
: requestedSuites.length > 0
? requestedSuites
: !hasSelector && defaultSuite
? [defaultSuite]
: [];
const knownIds = new Set(cases.map(({ id }) => id));
const missingIds = caseIds.filter((id) => !knownIds.has(id));
if (missingIds.length > 0) throw new Error(`unknown case(s): ${missingIds.join(", ")}`);
const knownSuites = new Set(cases.map(({ suite }) => suite));
const missingSuites = suites.filter((suite) => !knownSuites.has(suite));
if (missingSuites.length > 0) throw new Error(`unknown suite(s): ${missingSuites.join(", ")}`);
const knownTags = new Set(cases.flatMap(({ tags }) => tags));
const missingTags = requestedTags.filter((tag) => !knownTags.has(tag));
if (missingTags.length > 0) throw new Error(`unknown tag(s): ${missingTags.join(", ")}`);
const selected = cases.filter(
(testCase) =>
(caseIds.length === 0 || caseIds.includes(testCase.id)) &&
(suites.length === 0 || suites.includes(testCase.suite)) &&
requestedTags.every((tag) => testCase.tags.includes(tag)),
);
if (selected.length === 0) throw new Error("case selectors matched no cases");
return selected;
}
function reportFilename(mode) {
return `${new Date().toISOString().replaceAll(/[:.]/g, "-")}-${mode}.json`;
}
async function saveReport(report, outputDirectory) {
await mkdir(outputDirectory, { recursive: true });
const path = join(outputDirectory, reportFilename(report.mode));
await writeFile(path, `${JSON.stringify(report, null, 2)}\n`);
return path;
}
async function loadValidatedCorpus() {
const [cases, fixtureRegistry] = await Promise.all([allTasks(), loadFixtureRegistry()]);
const errors = validateRepositoryCases(cases, fixtureRegistry);
if (errors.length > 0) throw new Error(`browser eval validation failed:\n${errors.join("\n")}`);
return { cases, fixtureRegistry };
}
function selectionMetadata(cases) {
return {
cases: cases.map(({ id }) => id),
suites: unique(cases.map(({ suite }) => suite)),
tags: unique(cases.flatMap(({ tags }) => tags)).sort(),
};
}
function usage() {
console.log(`BrowserSkill local browser evaluation
Usage:
node evals/browser/cli.mjs validate [--json]
node evals/browser/cli.mjs list [--suite NAME] [--tag NAME] [--case ID] [--json]
node evals/browser/cli.mjs coverage [--suite NAME] [--tag NAME] [--case ID] [--json]
node evals/browser/cli.mjs serve [--host 127.0.0.1] [--port 4173]
node evals/browser/cli.mjs prompt <case> [--base-url URL] [--run-id ID] [--seed VALUE]
node evals/browser/cli.mjs verify <case> --base-url URL --run-id ID [--response TEXT]
node evals/browser/cli.mjs smoke [--bsk bsk] [--suite core] [--case ID] [--seed VALUE]
node evals/browser/cli.mjs run-agent --config FILE --agent NAME [--suite core] [--case ID]
node evals/browser/cli.mjs generate --seed VALUE [--json]
node evals/browser/cli.mjs scaffold <case-id> [--suite regression] [--title TEXT]
node evals/browser/cli.mjs summarize <report.json> [more reports...]
Selection:
--case ID[,ID] Select case ids; --task is a backward-compatible alias
--suite NAME[,NAME] Select suites
--tag NAME[,NAME] Require every selected tag
--case all Explicitly include every suite (run commands default to core)
--seed VALUE[,VALUE] Run one or more reproducible matrix seeds
run-agent options:
--agent NAME[,NAME] One or more entries from the config file
--variant NAME Override the report label (does not switch plugin code)
--locale en|zh-CN Prompt language (default zh-CN)
--repeat N Repeat every selected case (default 1)
--timeout MS Per-agent timeout (default 300000)
--out DIRECTORY Report/artifact directory
`);
}
async function commandValidate(parsed) {
const { cases, fixtureRegistry } = await loadValidatedCorpus();
const summary = { ok: true, ...repositorySummary(cases, fixtureRegistry) };
if (option(parsed, "json", false)) console.log(JSON.stringify(summary, null, 2));
else {
console.log(`Validated ${summary.cases} cases and ${summary.fixtureRoutes} fixture routes.`);
console.log(
`Suites: ${Object.entries(summary.suites)
.map(([suite, count]) => `${suite}=${count}`)
.join(", ")}`,
);
}
}
async function commandList(parsed) {
const cases = selectCases(await allTasks(), parsed);
const tasks = listTasks(cases);
if (option(parsed, "json", false)) console.log(JSON.stringify(tasks, null, 2));
else {
for (const task of tasks) {
console.log(`${task.id}\t${task.suite}\t${task.tags.join(",")}\t${task.title}`);
}
}
}
async function commandCoverage(parsed) {
const cases = selectCases(await allTasks(), parsed);
const coverage = buildOperationCoverage(cases);
if (option(parsed, "json", false)) {
console.log(JSON.stringify(coverage, null, 2));
} else {
console.table(
coverage.map(({ operation, agentCases, smokeCases, directSmoke, note }) => ({
operation,
agent_cases: agentCases.join(", ") || "-",
smoke_cases: smokeCases.join(", ") || "-",
direct_smoke: directSmoke ? "yes" : "manual",
note: note ?? "",
})),
);
}
}
async function commandServe(parsed) {
const { fixtureRegistry } = await loadValidatedCorpus();
const server = createEvalServer({
host: option(parsed, "host", "127.0.0.1"),
port: numericOption(parsed, "port", 4173),
fixtureRegistry,
});
const info = await server.start();
console.log(`Browser eval server listening at ${info.baseUrl}`);
console.log("Press Ctrl-C to stop.");
await new Promise((resolveSignal) => {
process.once("SIGINT", resolveSignal);
process.once("SIGTERM", resolveSignal);
});
await server.stop();
}
async function commandPrompt(parsed) {
const cases = await allTasks();
const task = getTask(parsed.positionals[0], cases);
const prompt = renderPrompt(task, {
baseUrl: option(parsed, "base-url", "http://127.0.0.1:4173"),
runId: option(parsed, "run-id", randomUUID()),
locale: option(parsed, "locale", "zh-CN"),
seed: seedOption(parsed, task.seed),
});
console.log(prompt);
}
async function commandVerify(parsed) {
const task = getTask(parsed.positionals[0], await allTasks());
const baseUrl = option(parsed, "base-url");
const runId = option(parsed, "run-id");
if (!baseUrl || !runId) throw new Error("verify requires --base-url and --run-id");
let responseText = option(parsed, "response", "");
const responseFile = option(parsed, "response-file");
if (responseFile) responseText = await readFile(resolve(responseFile), "utf8");
const stateResponse = await fetch(`${baseUrl}/api/runs/${encodeURIComponent(runId)}`);
if (!stateResponse.ok) throw new Error(`oracle request failed with ${stateResponse.status}`);
const state = await stateResponse.json();
const verification = verifyTask(task, { events: state.events, responseText });
console.log(JSON.stringify(verification, null, 2));
if (verification.status === "failed") process.exitCode = 1;
}
async function commandRunAgent(parsed) {
const configPath = option(parsed, "config");
const agentNames = optionList(parsed, "agent");
if (!configPath || agentNames.length === 0) {
throw new Error("run-agent requires --config and at least one --agent");
}
const { cases, fixtureRegistry } = await loadValidatedCorpus();
const selected = selectCases(cases, parsed, { defaultSuite: "core" });
const repeat = numericOption(parsed, "repeat", 1);
if (!Number.isInteger(repeat) || repeat < 1) throw new Error("--repeat must be at least 1");
const outputDirectory = resolve(option(parsed, "out", resultsDirectory));
const server = createEvalServer({ fixtureRegistry });
const serverInfo = await server.start();
const results = [];
const startedAt = new Date().toISOString();
try {
for (const agentName of agentNames) {
const { adapter, configDirectory } = await loadAgentConfig(configPath, agentName);
for (let iteration = 1; iteration <= repeat; iteration += 1) {
for (const task of selected) {
for (const seed of seedOptions(parsed, task.seed)) {
const seedLabel = seed === undefined ? "" : ` seed=${seed}`;
console.log(`[run] ${agentName} ${task.id}${seedLabel} (${iteration}/${repeat})`);
const result = await runCommandTask({
server,
serverInfo,
task,
adapter,
adapterName: agentName,
configDirectory,
iteration,
locale: option(parsed, "locale", "zh-CN"),
seed,
timeoutMs: numericOption(parsed, "timeout", 300_000),
variantOverride: option(parsed, "variant"),
});
results.push(result);
console.log(` ${result.verification.status} in ${result.execution.durationMs}ms`);
}
}
}
}
} finally {
await server.stop();
}
const report = {
schemaVersion: 1,
mode: "agent",
startedAt,
finishedAt: new Date().toISOString(),
selection: selectionMetadata(selected),
seeds: unique(results.map(({ seed }) => seed).filter((seed) => seed !== undefined)),
results,
};
const path = await saveReport(report, outputDirectory);
printSummary(summarizeReports([report]));
console.log(`Report: ${path}`);
if (
results.some(
(result) =>
result.verification.status === "failed" ||
result.execution.timedOut ||
result.execution.exitCode !== 0,
)
) {
process.exitCode = 1;
}
}
async function commandSmoke(parsed) {
const { cases, fixtureRegistry } = await loadValidatedCorpus();
const selected = selectCases(cases, parsed, { defaultSuite: "core" });
const outputDirectory = resolve(option(parsed, "out", resultsDirectory));
const server = createEvalServer({ fixtureRegistry });
const serverInfo = await server.start();
const results = [];
const startedAt = new Date().toISOString();
try {
for (const task of selected) {
for (const seed of seedOptions(parsed, task.seed)) {
const runId = `bsk-${task.id}-${randomUUID().slice(0, 8)}`;
const seedLabel = seed === undefined ? "" : ` seed=${seed}`;
console.log(`[smoke] ${task.id}${seedLabel}`);
const result = await runBskSmokeTask({
bskCommand: option(parsed, "bsk", "bsk"),
outputDirectory,
server,
serverInfo,
task,
runId,
seed,
timeoutMs: numericOption(parsed, "timeout", 60_000),
});
results.push(result);
console.log(
` ${result.verification.status}${result.executionError ? `: ${result.executionError}` : ""}`,
);
}
}
} finally {
await server.stop();
}
const report = {
schemaVersion: 1,
mode: "bsk-smoke",
startedAt,
finishedAt: new Date().toISOString(),
selection: selectionMetadata(selected),
seeds: unique(results.map(({ seed }) => seed).filter((seed) => seed !== undefined)),
results,
};
const path = await saveReport(report, outputDirectory);
printSummary(summarizeReports([report]));
console.log(`Report: ${path}`);
if (results.some((result) => result.executionError || result.verification.status === "failed")) {
process.exitCode = 1;
}
}
async function commandGenerate(parsed) {
if (!parsed.options.has("seed")) throw new Error("generate requires --seed");
const dimensions = unique(optionList(parsed, "seed").map(normalizeSeed)).map(describeSeed);
const output = dimensions.length === 1 ? dimensions[0] : dimensions;
if (option(parsed, "json", false)) console.log(JSON.stringify(output, null, 2));
else console.table(dimensions);
}
async function commandScaffold(parsed) {
const id = parsed.positionals[0];
if (!id) throw new Error("scaffold requires a case id");
const result = await scaffoldCase({
id,
title: option(parsed, "title", id),
suite: option(parsed, "suite", "regression"),
source: option(parsed, "source"),
});
if (option(parsed, "json", false)) console.log(JSON.stringify(result, null, 2));
else {
console.log(`Created ${result.directory}`);
console.log(
"Edit the fixture, prompt, workflow, and assertions, then run eval:browser validate.",
);
}
}
async function commandSummarize(parsed) {
const paths = [...parsed.positionals, ...optionList(parsed, "input")];
if (paths.length === 0) throw new Error("summarize requires at least one report path");
const reports = await Promise.all(
paths.map(async (path) => JSON.parse(await readFile(resolve(path), "utf8"))),
);
const rows = summarizeReports(reports);
if (option(parsed, "json", false)) console.log(JSON.stringify(rows, null, 2));
else printSummary(rows);
}
async function main() {
const parsed = parseArguments(process.argv.slice(2));
if (!parsed.command || option(parsed, "help", false)) return usage();
switch (parsed.command) {
case "validate":
return commandValidate(parsed);
case "list":
return commandList(parsed);
case "coverage":
return commandCoverage(parsed);
case "serve":
return commandServe(parsed);
case "prompt":
return commandPrompt(parsed);
case "verify":
return commandVerify(parsed);
case "run-agent":
return commandRunAgent(parsed);
case "smoke":
return commandSmoke(parsed);
case "generate":
return commandGenerate(parsed);
case "scaffold":
return commandScaffold(parsed);
case "summarize":
return commandSummarize(parsed);
default:
throw new Error(`unknown command ${JSON.stringify(parsed.command)}`);
}
}
main().catch((error) => {
console.error(`browser eval: ${error instanceof Error ? error.message : String(error)}`);
process.exitCode = 1;
});
@@ -0,0 +1,18 @@
import { page } from "../../lib/fixtures.mjs";
export default {
id: "diagnostics",
routes: ["/diagnostics"],
render() {
return page({
title: "Diagnostics Lab",
body: `<section class="card"><h1>Diagnostics Lab</h1><p>Inspect console and network buffers.</p><p id="network-status" class="muted">Ping pending</p></section>`,
script: `
console.log("Browser eval console marker: CONSOLE-61");
fetch("/api/ping?run=" + encodeURIComponent(browserEval.runId))
.then((response) => response.json())
.then(({ token }) => { document.querySelector("#network-status").textContent = "Ping completed: " + token; });
`,
});
},
};
@@ -0,0 +1,25 @@
import { escapeHtml, page } from "../../lib/fixtures.mjs";
export default {
id: "form",
routes: ["/form", "/result"],
render({ pathname, runId, query, record }) {
if (pathname === "/form") {
return page({
title: "Browser Eval Form",
body: `<section class="card"><h1>Web form</h1><form action="/result" method="get"><input type="hidden" name="run" value="${escapeHtml(runId)}"><label>Text input<input id="text-input" name="text" autocomplete="off"></label><label>Textarea<textarea id="notes" name="notes"></textarea></label><label>Dropdown<select id="choice" name="choice"><option value="one">One</option><option value="two">Two</option><option value="three">Three</option></select></label><button id="submit" type="submit">Submit</button></form></section>`,
script: `document.querySelector("#submit").addEventListener("keydown", (event) => { if (event.key === "Enter") browserEval.send("form.enter_pressed"); });`,
});
}
const values = {
text: query.get("text") ?? "",
notes: query.get("notes") ?? "",
choice: query.get("choice") ?? "",
};
record("form.submitted", values, { path: pathname });
return page({
title: "Form Result",
body: `<section class="card"><h1>Received!</h1><p id="submitted-values" class="marker">${escapeHtml(values.text)} | ${escapeHtml(values.notes)} | ${escapeHtml(values.choice)}</p></section>`,
});
},
};
@@ -0,0 +1,71 @@
import { escapeHtml, page } from "../../lib/fixtures.mjs";
import { describeSeed } from "../../lib/seeded-generator.mjs";
function nest(content, depth) {
let nested = content;
for (let index = 0; index < depth; index += 1) {
nested = `<div data-depth="${index + 1}">${nested}</div>`;
}
return nested;
}
function textField(dimensions) {
const id = `matrix-text-${dimensions.idSuffix}`;
const input = `<input id="${id}" name="text" autocomplete="off">`;
if (dimensions.labelMode === "wrapped") return `<label>Text input${input}</label>`;
if (dimensions.labelMode === "for") return `<label for="${id}">Text input</label>${input}`;
return `<span id="${id}-label">Text input</span><input id="${id}" name="text" aria-labelledby="${id}-label" autocomplete="off">`;
}
function formMarkup(dimensions, runId) {
const text = textField(dimensions);
const select = `<label>Dropdown<select name="choice"><option value="one">One</option><option value="two">Two</option><option value="three">Three</option></select></label>`;
const fields = dimensions.fieldOrder === "text-first" ? `${text}${select}` : `${select}${text}`;
const decoy =
dimensions.decoy === "disabled-input"
? `<label>Text input<input disabled value="decoy"></label>`
: dimensions.decoy === "duplicate-text"
? `<p class="muted">Text input is intentionally repeated in helper copy.</p>`
: "";
return nest(
`<form action="/matrix/generated-result" method="get"><input type="hidden" name="run" value="${escapeHtml(runId)}"><input type="hidden" name="seed" value="${dimensions.seed}">${decoy}${fields}<button type="submit">Submit matrix form</button></form>`,
dimensions.nestingDepth,
);
}
export default {
id: "generated-form",
routes: ["/matrix/generated-form", "/matrix/generated-result"],
render({ pathname, runId, query, record }) {
const dimensions = describeSeed(query.get("seed") ?? 1);
if (pathname === "/matrix/generated-form") {
const markup = JSON.stringify(formMarkup(dimensions, runId));
const dimensionsJson = JSON.stringify(dimensions);
return page({
title: "Seeded Matrix Form",
body: `<section class="card"><h1>Seeded Matrix Form</h1><p class="marker">SEED-${dimensions.seed}</p><div id="matrix-root">Hydrating…</div></section>`,
script: `
const hydrate = () => {
const root = document.querySelector("#matrix-root");
root.innerHTML = ${markup};
root.querySelector("button[type=submit]").addEventListener("keydown", (event) => {
if (event.key === "Enter") browserEval.send("matrix.enter_pressed");
});
browserEval.send("matrix.ready", ${dimensionsJson});
};
setTimeout(hydrate, ${dimensions.hydrationDelayMs});
`,
});
}
const values = {
seed: dimensions.seed,
text: query.get("text") ?? "",
choice: query.get("choice") ?? "",
};
record("matrix.submitted", values, { path: pathname });
return page({
title: "Matrix Result",
body: `<section class="card"><h1>Matrix Result</h1><p class="marker">MATRIX-OK</p><p>${escapeHtml(values.text)} | ${escapeHtml(values.choice)} | seed ${values.seed}</p></section>`,
});
},
};
@@ -0,0 +1,17 @@
import { page } from "../../lib/fixtures.mjs";
export default {
id: "hover-inspect",
routes: ["/hover-inspect"],
render() {
return page({
title: "Hover and Inspect",
body: `<section class="card"><h1>Hover and Inspect</h1><div id="account-menu" tabindex="0"><button id="account-button" type="button">Account</button><div id="hover-panel"><button id="profile-link" type="button">Profile beta</button></div></div><p id="hover-result" class="marker" hidden>HOVER-17</p><article id="inspect-card" class="card" data-build="2026.08" data-marker="INSPECT-27"><h2>Inspection card</h2><p>Local HTML marker: <code>INSPECT-27</code></p></article></section>`,
script: `
const menu = document.querySelector("#account-menu");
menu.addEventListener("mouseenter", () => { menu.classList.add("open"); browserEval.send("hover.menu_opened"); });
document.querySelector("#profile-link").addEventListener("click", () => { document.querySelector("#hover-result").hidden = false; browserEval.send("hover.profile_clicked"); });
`,
});
},
};
@@ -0,0 +1,12 @@
import { page } from "../../lib/fixtures.mjs";
export default {
id: "fixture-index",
routes: ["/"],
render() {
return page({
title: "Browser Eval Fixtures",
body: `<section class="card"><h1>Browser Eval Fixtures</h1><p class="muted">Deterministic local pages for agent-neutral browser evaluation.</p></section>`,
});
},
};
@@ -0,0 +1,19 @@
import { page, withRun } from "../../lib/fixtures.mjs";
export default {
id: "navigation",
routes: ["/navigation/start", "/navigation/detail"],
render({ pathname, runId }) {
if (pathname === "/navigation/start") {
return page({
title: "Navigation Start",
body: `<section class="card"><h1>Navigation Start</h1><p>Use the link to open the deterministic detail page.</p><a id="details-link" class="button" href="${withRun("/navigation/detail", runId)}">Details</a></section>`,
script: `document.querySelector("#details-link").addEventListener("click", () => browserEval.send("navigation.detail.clicked"));`,
});
}
return page({
title: "Navigation Detail",
body: `<section class="card"><h1>Navigation Detail</h1><p>Stable detail code:</p><p id="navigation-code" class="marker">NAV-42</p></section>`,
});
},
};
@@ -0,0 +1,21 @@
import { page } from "../../lib/fixtures.mjs";
export default {
id: "responsive",
routes: ["/responsive"],
render() {
return page({
title: "Responsive Lab",
body: `<section class="card"><h1>Responsive Lab</h1><p id="viewport-marker" class="marker">VIEWPORT-84</p><p id="viewport-value"></p></section>`,
script: `
const sample = () => {
const data = { width: innerWidth, height: innerHeight, touchPoints: navigator.maxTouchPoints, userAgent: navigator.userAgent };
document.querySelector("#viewport-value").textContent = data.width + "x" + data.height;
browserEval.send("viewport.sample", data);
};
window.addEventListener("resize", sample);
sample();
`,
});
},
};
@@ -0,0 +1,19 @@
import { escapeHtml, page, withRun } from "../../lib/fixtures.mjs";
export default {
id: "tabs",
routes: ["/tabs", "/tabs/child"],
render({ pathname, runId }) {
if (pathname === "/tabs") {
return page({
title: "Tab Lab",
body: `<section class="card"><h1>Tab Lab</h1><p>Keep this original tab open while visiting the child page in a new tab.</p><p class="muted">Child URL: <code>${escapeHtml(withRun("/tabs/child", runId))}</code></p></section>`,
});
}
return page({
title: "Child Tab",
body: `<section class="card"><h1>Child Tab</h1><p id="tab-token" class="marker">TAB-29</p><button id="mark-child" type="button">Mark child visited</button><p id="child-status" hidden>Marked</p></section>`,
script: `document.querySelector("#mark-child").addEventListener("click", () => { document.querySelector("#child-status").hidden = false; browserEval.send("tabs.child_marked"); });`,
});
},
};
+99
View File
@@ -0,0 +1,99 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { verifyTask } from "./oracle.mjs";
import { countPattern, runProcess, substituteArgs } from "./process.mjs";
import { renderPrompt } from "./tasks.mjs";
function safeRunPart(value) {
return value.replaceAll(/[^A-Za-z0-9._-]/g, "-").slice(0, 48);
}
export async function loadAgentConfig(configPath, agentName) {
const absolute = resolve(configPath);
const config = JSON.parse(await readFile(absolute, "utf8"));
const adapter = config.agents?.[agentName];
if (!adapter) {
const names = Object.keys(config.agents ?? {}).join(", ");
throw new Error(`unknown agent ${JSON.stringify(agentName)}; configured agents: ${names}`);
}
if (typeof adapter.command !== "string" || !Array.isArray(adapter.args)) {
throw new Error(`agent ${JSON.stringify(agentName)} must define command and args`);
}
return { adapter, configDirectory: dirname(absolute) };
}
export async function runCommandTask({
server,
serverInfo,
task,
adapter,
adapterName,
configDirectory,
iteration,
locale,
seed = task.seed,
timeoutMs,
variantOverride,
}) {
const variant = variantOverride ?? adapter.variant ?? "unspecified";
const runId = [
safeRunPart(adapterName),
safeRunPart(variant),
safeRunPart(task.id),
iteration,
randomUUID().slice(0, 8),
].join("-");
server.reset(runId);
const prompt = renderPrompt(task, { baseUrl: serverInfo.baseUrl, runId, locale, seed });
const values = {
prompt,
caseId: task.id,
taskId: task.id,
runId,
baseUrl: serverInfo.baseUrl,
seed: seed ?? "",
variant,
};
const args = substituteArgs(adapter.args, values);
const execution = await runProcess(adapter.command, args, {
cwd: adapter.cwd ? resolve(configDirectory, adapter.cwd) : configDirectory,
env: adapter.env,
timeoutMs: adapter.timeoutMs ?? timeoutMs,
});
await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));
const responseText = execution.stdout;
const combinedOutput = `${execution.stdout}\n${execution.stderr}`;
const verification = verifyTask(task, {
events: server.snapshot(runId).events,
responseText,
});
const defaultErrorPattern = "(?:\\bError:|timed out|unfinished command|session already has)";
return {
runId,
caseId: task.id,
taskId: task.id,
suite: task.suite,
tags: task.tags,
seed,
iteration,
adapter: adapterName,
variant,
adapterMetadata: adapter.metadata ?? {},
locale,
prompt,
execution,
metrics: {
errorCount: countPattern(
combinedOutput,
adapter.metrics?.errorPattern ?? defaultErrorPattern,
),
toolCallCount: countPattern(combinedOutput, adapter.metrics?.toolCallPattern),
responseChars: responseText.length,
},
eventCount: server.snapshot(runId).events.length,
verification,
};
}
+309
View File
@@ -0,0 +1,309 @@
import { mkdir, stat } from "node:fs/promises";
import { join } from "node:path";
import { verifyTask } from "./oracle.mjs";
import { runProcess } from "./process.mjs";
import { taskUrl } from "./tasks.mjs";
function parseJsonOutput(step) {
try {
return JSON.parse(step.stdout);
} catch (error) {
throw new Error(`could not parse bsk JSON output: ${error.message}`);
}
}
function renderStepError(step) {
const raw = step.stderr.trim() || step.stdout.trim();
if (!raw) return `exit ${step.exitCode}`;
try {
const parsed = JSON.parse(raw);
return parsed.hint ? `${parsed.message} (hint: ${parsed.hint})` : parsed.message;
} catch {
return raw;
}
}
async function hasNonemptyFile(path) {
try {
return (await stat(path)).size > 0;
} catch {
return false;
}
}
function readPath(value, path) {
return path.split(".").reduce((current, part) => current?.[part], value);
}
function resolveValue(value, variables) {
if (typeof value !== "string") return value;
const exact = value.match(/^\{([^{}]+)}$/);
if (exact) {
const resolved = readPath(variables, exact[1]);
if (resolved === undefined) throw new Error(`unknown workflow variable ${exact[1]}`);
return resolved;
}
return value.replaceAll(/\{([^{}]+)\}/g, (_match, path) => {
const resolved = readPath(variables, path);
if (resolved === undefined) throw new Error(`unknown workflow variable ${path}`);
return String(resolved);
});
}
function targetArgs(step, variables) {
if (step.selector) return ["--selector", String(resolveValue(step.selector, variables))];
if (step.ref) return ["--ref", String(resolveValue(step.ref, variables))];
return [];
}
function tabArgs(step, variables) {
return step.tabId === undefined ? [] : ["--tab-id", String(resolveValue(step.tabId, variables))];
}
function matchesWhere(value, where = {}) {
return Object.entries(where).every(([path, expected]) => readPath(value, path) === expected);
}
export async function runBskSmokeTask({
bskCommand,
outputDirectory,
server,
serverInfo,
task,
runId,
seed = task.seed,
timeoutMs = 60_000,
}) {
const steps = [];
const evidence = {};
const variables = {
baseUrl: serverInfo.baseUrl,
runId,
seed: seed ?? "",
url: taskUrl(task, serverInfo.baseUrl, runId, seed),
};
let sessionId;
let executionError;
await mkdir(outputDirectory, { recursive: true });
async function bsk(args, { timeout = timeoutMs } = {}) {
const execution = await runProcess(bskCommand, [...args, "--json"], { timeoutMs: timeout });
steps.push(execution);
if (execution.exitCode !== 0 || execution.timedOut || execution.error) {
throw new Error(
`bsk ${args.join(" ")} failed: ${execution.error ?? renderStepError(execution)}`,
);
}
return parseJsonOutput(execution);
}
async function waitForSiteEvent(step) {
const timeout = step.timeoutMs ?? 3_000;
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
if (
server
.snapshot(runId)
.events.some(
(event) => event.type === step.type && matchesWhere(event.data ?? {}, step.where ?? {}),
)
) {
return { observed: true };
}
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
}
throw new Error(`local fixture did not report ${step.type} within ${timeout}ms`);
}
async function executeWorkflowStep(step) {
const session = ["--session", sessionId];
let result;
switch (step.action) {
case "navigate":
result = await bsk([
"navigate",
String(resolveValue(step.url ?? "{url}", variables)),
...session,
...tabArgs(step, variables),
]);
break;
case "back":
case "forward":
result = await bsk([`navigate-${step.action}`, ...session, ...tabArgs(step, variables)]);
break;
case "reload":
result = await bsk(["reload", ...session, ...tabArgs(step, variables)]);
break;
case "wait":
result = await bsk(["wait-ms", String(resolveValue(step.duration, variables))]);
break;
case "wait-site-event":
result = await waitForSiteEvent(step);
break;
case "observe":
case "snapshot":
case "html": {
const command = step.action === "html" ? "get-html" : step.action;
result = await bsk([command, ...session, ...tabArgs(step, variables)]);
break;
}
case "screenshot": {
const name = resolveValue(step.artifactName ?? "screenshot.png", variables);
const path = join(outputDirectory, `${runId}-${name}`);
result = await bsk(["screenshot", ...session, ...tabArgs(step, variables), "--out", path]);
if (step.evidence) evidence[step.evidence] = await hasNonemptyFile(path);
break;
}
case "console":
case "network":
result = await bsk([step.action, ...session, ...tabArgs(step, variables)]);
break;
case "click":
case "hover":
result = await bsk([
step.action,
...targetArgs(step, variables),
...session,
...tabArgs(step, variables),
]);
break;
case "fill":
result = await bsk([
"fill",
...targetArgs(step, variables),
"--value",
String(resolveValue(step.value, variables)),
...session,
...tabArgs(step, variables),
]);
break;
case "select":
result = await bsk([
"select",
...targetArgs(step, variables),
...step.values.flatMap((value) => ["--value", String(resolveValue(value, variables))]),
...session,
...tabArgs(step, variables),
]);
break;
case "press":
result = await bsk([
"press",
String(resolveValue(step.key, variables)),
...targetArgs(step, variables),
...session,
...tabArgs(step, variables),
]);
break;
case "tab-list":
result = await bsk(["tab", "list", ...session]);
break;
case "tab-create":
result = await bsk([
"tab",
"create",
...session,
...(step.url ? ["--url", String(resolveValue(step.url, variables))] : []),
]);
break;
case "tab-select":
case "tab-close":
result = await bsk([
"tab",
step.action.slice(4),
String(resolveValue(step.tabId, variables)),
...session,
]);
break;
case "borrow":
case "return":
result = await bsk([
"tab",
step.action,
String(resolveValue(step.tabId, variables)),
...session,
]);
break;
case "resize":
result = await bsk([
"window",
"resize",
...session,
"--width",
String(step.width),
"--height",
String(step.height),
]);
break;
case "emulate":
result = await bsk([
"emulate",
...session,
...tabArgs(step, variables),
"--device",
String(resolveValue(step.device, variables)),
]);
break;
case "request-help":
result = await bsk([
"request-help",
...session,
"--prompt",
String(resolveValue(step.prompt, variables)),
...(step.title ? ["--title", String(resolveValue(step.title, variables))] : []),
...(step.timeout ? ["--timeout", String(step.timeout)] : []),
]);
break;
default:
throw new Error(`unsupported smoke workflow action ${step.action}`);
}
if (step.saveAs) variables[step.saveAs] = result;
if (step.evidence && step.action !== "screenshot") evidence[step.evidence] = true;
}
server.reset(runId);
try {
if (task.smokeSteps.length === 0) throw new Error(`case ${task.id} has no smoke workflow`);
const started = await bsk(["session", "start", "--no-focus"], { timeout: 90_000 });
sessionId = started.session_id;
variables.sessionId = sessionId;
await bsk(["session", "list"]);
for (const step of task.smokeSteps) await executeWorkflowStep(step);
} catch (error) {
executionError = error instanceof Error ? error.message : String(error);
} finally {
if (sessionId) {
try {
const stopped = await bsk(["session", "stop", sessionId], { timeout: 90_000 });
evidence.sessionStopped =
stopped.stopped?.includes(sessionId) === true && (stopped.failed?.length ?? 0) === 0;
if (!evidence.sessionStopped) {
executionError ??= `bsk did not confirm that session ${sessionId} stopped`;
}
} catch (error) {
evidence.sessionStopped = false;
executionError ??= error instanceof Error ? error.message : String(error);
}
}
}
await new Promise((resolveDelay) => setTimeout(resolveDelay, 350));
const responseText = steps.map(({ stdout }) => stdout).join("\n");
const events = server.snapshot(runId).events;
return {
runId,
caseId: task.id,
taskId: task.id,
suite: task.suite,
tags: task.tags,
seed,
adapter: "bsk-direct",
variant: "cli-direct",
executionError,
steps,
evidence,
eventCount: events.length,
verification: verifyTask(task, { events, responseText, adapterEvidence: evidence }),
};
}
+216
View File
@@ -0,0 +1,216 @@
import { readFile } from "node:fs/promises";
import { discoverFiles } from "./discovery.mjs";
import { OPERATION_NAMES, WORKFLOW_ACTIONS } from "./operations.mjs";
import { casesDirectory as defaultCasesDirectory } from "./paths.mjs";
const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const EVIDENCE_PATTERN = /^[A-Za-z][A-Za-z0-9]*$/;
const TOP_LEVEL_KEYS = new Set([
"$schema",
"schemaVersion",
"id",
"title",
"order",
"suite",
"tags",
"seed",
"source",
"fixture",
"prompts",
"coverage",
"assertions",
"smoke",
]);
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function checkString(errors, value, path) {
if (typeof value !== "string" || value.trim() === "") errors.push(`${path} must be a string`);
}
function validateAssertion(errors, assertion, path, kind) {
if (!isObject(assertion)) {
errors.push(`${path} must be an object`);
return;
}
checkString(errors, assertion.label, `${path}.label`);
if (kind === "site") {
checkString(errors, assertion.type, `${path}.type`);
if (!Number.isInteger(assertion.minCount) || assertion.minCount < 1) {
errors.push(`${path}.minCount must be a positive integer`);
}
if (assertion.where !== undefined && !isObject(assertion.where)) {
errors.push(`${path}.where must be an object`);
}
} else if (kind === "response") {
checkString(errors, assertion.includes, `${path}.includes`);
} else {
checkString(errors, assertion.key, `${path}.key`);
}
}
function validateWorkflowStep(errors, step, path) {
if (!isObject(step)) {
errors.push(`${path} must be an object`);
return;
}
if (!WORKFLOW_ACTIONS.has(step.action)) {
errors.push(`${path}.action is unsupported: ${JSON.stringify(step.action)}`);
}
if (step.saveAs !== undefined && !ID_PATTERN.test(step.saveAs)) {
errors.push(`${path}.saveAs must use lowercase kebab-case`);
}
if (step.evidence !== undefined && !EVIDENCE_PATTERN.test(step.evidence)) {
errors.push(`${path}.evidence must be an identifier`);
}
if (["click", "hover", "fill", "select"].includes(step.action) && !step.selector && !step.ref) {
errors.push(`${path} requires selector or ref`);
}
if (step.action === "fill") checkString(errors, step.value, `${path}.value`);
if (step.action === "select") {
if (!Array.isArray(step.values) || step.values.length === 0) {
errors.push(`${path}.values must be a non-empty array`);
} else if (step.values.some((value) => typeof value !== "string")) {
errors.push(`${path}.values must contain only strings`);
}
}
if (step.action === "press") checkString(errors, step.key, `${path}.key`);
if (step.action === "wait") checkString(errors, step.duration, `${path}.duration`);
if (step.action === "wait-site-event") checkString(errors, step.type, `${path}.type`);
if (["tab-select", "tab-close", "borrow", "return"].includes(step.action)) {
checkString(errors, step.tabId, `${path}.tabId`);
}
if (step.action === "resize") {
if (
!Number.isInteger(step.width) ||
step.width < 1 ||
!Number.isInteger(step.height) ||
step.height < 1
) {
errors.push(`${path}.width and height must be positive integers`);
}
}
if (step.action === "emulate") checkString(errors, step.device, `${path}.device`);
if (step.action === "request-help") checkString(errors, step.prompt, `${path}.prompt`);
if (step.timeoutMs !== undefined && (!Number.isInteger(step.timeoutMs) || step.timeoutMs < 1)) {
errors.push(`${path}.timeoutMs must be a positive integer`);
}
}
export function validateCaseManifest(manifest, { source = "case manifest" } = {}) {
const errors = [];
if (!isObject(manifest)) return [`${source} must contain a JSON object`];
for (const key of Object.keys(manifest)) {
if (!TOP_LEVEL_KEYS.has(key)) errors.push(`unknown top-level property ${key}`);
}
if (manifest.schemaVersion !== 1) errors.push("schemaVersion must equal 1");
if (!ID_PATTERN.test(manifest.id ?? "")) errors.push("id must use lowercase kebab-case");
checkString(errors, manifest.title, "title");
if (manifest.order !== undefined && (!Number.isInteger(manifest.order) || manifest.order < 0)) {
errors.push("order must be a non-negative integer");
}
if (!ID_PATTERN.test(manifest.suite ?? "")) errors.push("suite must use lowercase kebab-case");
if (!Array.isArray(manifest.tags) || manifest.tags.some((tag) => !ID_PATTERN.test(tag))) {
errors.push("tags must be an array of lowercase kebab-case strings");
} else if (new Set(manifest.tags).size !== manifest.tags.length) {
errors.push("tags must not contain duplicates");
}
if (!isObject(manifest.fixture)) errors.push("fixture must be an object");
else if (
typeof manifest.fixture.startPath !== "string" ||
!manifest.fixture.startPath.startsWith("/")
) {
errors.push("fixture.startPath must be an absolute URL path");
}
if (!isObject(manifest.prompts)) errors.push("prompts must be an object");
else {
checkString(errors, manifest.prompts.en, "prompts.en");
checkString(errors, manifest.prompts["zh-CN"], "prompts.zh-CN");
}
if (!Array.isArray(manifest.coverage)) errors.push("coverage must be an array");
else {
for (const operation of manifest.coverage) {
if (!OPERATION_NAMES.has(operation))
errors.push(`coverage contains unknown operation ${operation}`);
}
if (new Set(manifest.coverage).size !== manifest.coverage.length) {
errors.push("coverage must not contain duplicates");
}
}
if (!isObject(manifest.assertions)) errors.push("assertions must be an object");
else {
for (const kind of ["site", "response", "adapter"]) {
if (!Array.isArray(manifest.assertions[kind])) {
errors.push(`assertions.${kind} must be an array`);
} else {
manifest.assertions[kind].forEach((assertion, index) =>
validateAssertion(errors, assertion, `assertions.${kind}[${index}]`, kind),
);
}
}
}
if (!isObject(manifest.smoke) || !Array.isArray(manifest.smoke.steps)) {
errors.push("smoke.steps must be an array");
} else {
manifest.smoke.steps.forEach((step, index) =>
validateWorkflowStep(errors, step, `smoke.steps[${index}]`),
);
}
if (manifest.seed !== undefined && !Number.isSafeInteger(manifest.seed)) {
errors.push("seed must be a safe integer");
}
if (manifest.source !== undefined && !isObject(manifest.source)) {
errors.push("source must be an object");
}
return errors.map((error) => `${source}: ${error}`);
}
function normalizeCase(manifest, sourceFile) {
return Object.freeze({
...manifest,
startPath: manifest.fixture.startPath,
siteAssertions: manifest.assertions.site,
responseAssertions: manifest.assertions.response,
adapterAssertions: manifest.assertions.adapter,
smokeSteps: manifest.smoke.steps,
sourceFile,
});
}
export async function loadCaseManifests({ casesDirectory = defaultCasesDirectory } = {}) {
const files = await discoverFiles(casesDirectory, (path) => path.endsWith(".case.json"));
const cases = [];
const ids = new Map();
const errors = [];
for (const file of files) {
let manifest;
try {
manifest = JSON.parse(await readFile(file, "utf8"));
} catch (error) {
errors.push(`${file}: invalid JSON: ${error.message}`);
continue;
}
const manifestErrors = validateCaseManifest(manifest, { source: file });
errors.push(...manifestErrors);
if (typeof manifest?.id === "string") {
if (ids.has(manifest.id)) {
errors.push(`${file}: duplicate id also declared by ${ids.get(manifest.id)}`);
} else {
ids.set(manifest.id, file);
}
}
if (manifestErrors.length === 0) cases.push(normalizeCase(manifest, file));
}
if (files.length === 0) errors.push(`${casesDirectory}: no .case.json files found`);
if (errors.length > 0) throw new Error(`case validation failed:\n${errors.join("\n")}`);
cases.sort(
(left, right) =>
left.suite.localeCompare(right.suite) ||
(left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER) ||
left.id.localeCompare(right.id),
);
return Object.freeze(cases);
}
+26
View File
@@ -0,0 +1,26 @@
import { OPERATION_CATALOG, WORKFLOW_ACTION_OPERATIONS } from "./operations.mjs";
export function buildOperationCoverage(cases) {
return OPERATION_CATALOG.map(({ operation, manualNote }) => {
const agentCases = cases
.filter((testCase) => testCase.coverage.includes(operation))
.map(({ id }) => id);
let smokeCases;
if (["session.start", "session.stop", "session.list"].includes(operation)) {
smokeCases = cases.filter(({ smokeSteps }) => smokeSteps.length > 0).map(({ id }) => id);
} else {
smokeCases = cases
.filter(({ smokeSteps }) =>
smokeSteps.some((step) => WORKFLOW_ACTION_OPERATIONS[step.action] === operation),
)
.map(({ id }) => id);
}
return {
operation,
agentCases,
smokeCases,
directSmoke: smokeCases.length > 0,
note: smokeCases.length === 0 && manualNote ? `manual lane: ${manualNote}` : undefined,
};
});
}
+24
View File
@@ -0,0 +1,24 @@
import { readdir } from "node:fs/promises";
import { join } from "node:path";
export async function discoverFiles(root, predicate) {
const files = [];
async function visit(directory) {
let entries;
try {
entries = await readdir(directory, { withFileTypes: true });
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
const path = join(directory, entry.name);
if (entry.isDirectory()) await visit(path);
else if (entry.isFile() && predicate(path)) files.push(path);
}
}
await visit(root);
return files;
}
+68
View File
@@ -0,0 +1,68 @@
import { pathToFileURL } from "node:url";
import { discoverFiles } from "./discovery.mjs";
import { casesDirectory, fixturesDirectory } from "./paths.mjs";
export async function loadFixtureRegistry({ roots = [fixturesDirectory, casesDirectory] } = {}) {
const files = (
await Promise.all(
roots.map((root) => discoverFiles(root, (path) => path.endsWith(".fixture.mjs"))),
)
).flat();
const routes = new Map();
const definitions = [];
const errors = [];
for (const file of files.sort()) {
let definition;
try {
definition = (await import(pathToFileURL(file).href)).default;
} catch (error) {
errors.push(`${file}: could not import fixture: ${error.message}`);
continue;
}
if (!definition || typeof definition.id !== "string") {
errors.push(`${file}: default export must define id`);
continue;
}
if (!Array.isArray(definition.routes) || definition.routes.length === 0) {
errors.push(`${file}: default export must define non-empty routes`);
continue;
}
if (typeof definition.render !== "function") {
errors.push(`${file}: default export must define render(context)`);
continue;
}
definitions.push({ ...definition, sourceFile: file });
for (const route of definition.routes) {
if (typeof route !== "string" || !route.startsWith("/")) {
errors.push(`${file}: invalid route ${JSON.stringify(route)}`);
} else if (routes.has(route)) {
errors.push(
`${file}: route ${route} is already registered by ${routes.get(route).sourceFile}`,
);
} else {
routes.set(route, { definition, sourceFile: file });
}
}
}
if (errors.length > 0) throw new Error(`fixture validation failed:\n${errors.join("\n")}`);
return Object.freeze({
definitions: Object.freeze(definitions),
routes: Object.freeze([...routes.keys()].sort()),
hasRoute(pathname) {
return routes.has(pathname);
},
render(pathname, context) {
const entry = routes.get(pathname);
return entry ? entry.definition.render({ ...context, pathname }) : null;
},
});
}
export function validateCaseFixtureLinks(cases, fixtureRegistry) {
return cases
.filter(({ startPath }) => !fixtureRegistry.hasRoute(startPath))
.map(({ id, startPath }) => `case ${id} references unregistered fixture route ${startPath}`);
}

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