mirror of
https://github.com/Tencent/BrowserSkill.git
synced 2026-09-10 13:01:23 +08:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
388c1283bc | ||
|
|
b449be1544 | ||
|
|
f06a514bd2 | ||
|
|
1e53ee63ae | ||
|
|
120dc441bb | ||
|
|
710b1219f4 | ||
|
|
177ecd3ebf | ||
|
|
0e6b9c4542 | ||
|
|
506adbe708 | ||
|
|
984d017b0f | ||
|
|
5df93143c5 | ||
|
|
7163f2f9b0 | ||
|
|
e9f0584af3 | ||
|
|
2997f495db | ||
|
|
f96bd72c3c | ||
|
|
329c68054b | ||
|
|
5cd43553ed | ||
|
|
9ad33801c7 | ||
|
|
7aaa5a2d01 | ||
|
|
210b21b637 | ||
|
|
48f64ec0df | ||
|
|
c48a53269e | ||
|
|
3bbd6ab19f | ||
|
|
1a70d2200e | ||
|
|
554861d6b1 | ||
|
|
0d7f976335 | ||
|
|
d1d3eb6a94 | ||
|
|
38fd7d3f4c | ||
|
|
b5062ac19b | ||
|
|
41cb576256 | ||
|
|
f060a7c074 | ||
|
|
60b62d5420 | ||
|
|
70b851a3e8 | ||
|
|
da3534d066 | ||
|
|
a004291848 | ||
|
|
60fbf30e24 | ||
|
|
a4b6a61d29 | ||
|
|
cad0b5cbc9 |
@@ -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"
|
||||
|
||||
@@ -11,6 +11,10 @@ dist/
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Local browser evaluation artifacts
|
||||
evals/browser/results/
|
||||
evals/browser/agents.local.json
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -134,7 +134,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bsk"
|
||||
version = "0.1.10"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bsk-protocol",
|
||||
@@ -168,7 +168,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "bsk-protocol"
|
||||
version = "0.1.10"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"schemars",
|
||||
"semver",
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ members = [
|
||||
default-members = ["crates/bsk-cli"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.10"
|
||||
version = "0.1.11"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MIT"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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 无关的浏览器能力测试台
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@browser-skill/extension",
|
||||
"version": "0.1.6",
|
||||
"version": "0.1.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { i18n } from "@browser-skill/i18n";
|
||||
import { ChromiumCdp } from "@/browser-driver/chromium-cdp";
|
||||
import { ConnectionController } from "@/lib/connection-controller";
|
||||
import { DiagnosticLogger } from "@/lib/diagnostics";
|
||||
import { startHeartbeat } from "@/lib/heartbeat";
|
||||
import {
|
||||
getConnectionEnabled,
|
||||
@@ -46,9 +47,20 @@ import type { Transport } from "@/transport/transport";
|
||||
import { WSTransport } from "@/transport/ws-transport";
|
||||
|
||||
export default defineBackground(() => {
|
||||
const controller = new ConnectionController();
|
||||
const transport = new WSTransport({ url: __BSK_DAEMON_WS_URL__ });
|
||||
const sessions = new SessionManager();
|
||||
const diagnostics = new DiagnosticLogger();
|
||||
diagnostics.record("extension.worker.started", {
|
||||
diagnostic_build: "lumi-session-loss-v2",
|
||||
extension_version: __BSK_EXT_VERSION__,
|
||||
extension_runtime_id: chrome.runtime.id,
|
||||
daemon_ws_url: __BSK_DAEMON_WS_URL__,
|
||||
});
|
||||
const controller = new ConnectionController(diagnostics.sink);
|
||||
const transport = new WSTransport({
|
||||
url: __BSK_DAEMON_WS_URL__,
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
diagnostics.bindTransport((frame) => transport.send(frame));
|
||||
const sessions = new SessionManager({ diagnostics: diagnostics.sink });
|
||||
const cdp = new ChromiumCdp();
|
||||
const sessionsLive = attachSessionsLiveFlag({ manager: sessions });
|
||||
let overlayGeneration = 0;
|
||||
@@ -109,6 +121,9 @@ export default defineBackground(() => {
|
||||
}
|
||||
|
||||
function onOverlaySessionStateChanged(): void {
|
||||
diagnostics.record("background.sessions.changed", {
|
||||
live_session_ids: sessions.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
void sessionsLive.syncFromManager();
|
||||
const liveSessionIds = new Set(sessions.list().map((ctx) => ctx.sessionId));
|
||||
for (const sessionId of controlModes.keys()) {
|
||||
@@ -146,6 +161,7 @@ export default defineBackground(() => {
|
||||
onSessionsChanged: () => {
|
||||
void sessionsLive.syncFromManager();
|
||||
},
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
const recordDeps = {
|
||||
tabsApi: chrome.tabs,
|
||||
@@ -193,6 +209,7 @@ export default defineBackground(() => {
|
||||
title: i18n.t("helpRequest.notificationTitle", { ns: "extension" }),
|
||||
body: "",
|
||||
}),
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
dispatcher.start();
|
||||
if (typeof chrome.notifications?.onClicked?.addListener === "function") {
|
||||
@@ -225,6 +242,7 @@ export default defineBackground(() => {
|
||||
transport,
|
||||
cdp,
|
||||
onSessionsChanged: onOverlaySessionStateChanged,
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
|
||||
// MV3 service worker keepalive + reconnect supervisor (review M4/M5
|
||||
@@ -236,6 +254,7 @@ export default defineBackground(() => {
|
||||
startKeepalive({
|
||||
transport,
|
||||
shouldConnect: () => controller.isConnectionEnabled,
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
|
||||
// Application-level heartbeat (Chrome 116+): while the post-handshake
|
||||
@@ -249,6 +268,19 @@ export default defineBackground(() => {
|
||||
controller.subscribe((snap) =>
|
||||
cb(snap.state === "connected" || snap.state === "version_skew"),
|
||||
),
|
||||
diagnostics: diagnostics.sink,
|
||||
});
|
||||
|
||||
controller.subscribe((snapshot) => {
|
||||
const ready = snapshot.state === "connected" || snapshot.state === "version_skew";
|
||||
diagnostics.setTransportReady(ready);
|
||||
diagnostics.record("background.controller.snapshot", {
|
||||
state: snapshot.state,
|
||||
connection_enabled: snapshot.connectionEnabled,
|
||||
instance_id: snapshot.instanceId,
|
||||
last_error: snapshot.lastError,
|
||||
live_session_ids: sessions.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
});
|
||||
|
||||
// Wake-driven reconnect (best effort). An MV3 service worker is killed
|
||||
@@ -257,7 +289,12 @@ export default defineBackground(() => {
|
||||
// the worker and let us reconnect immediately instead of waiting for
|
||||
// the next 30s alarm tick. They only help when the daemon is actually
|
||||
// running; a cold daemon is (re)spawned by the next `bsk` command.
|
||||
const reconnectIfNeeded = () => {
|
||||
const reconnectIfNeeded = (source: string) => {
|
||||
diagnostics.record("background.wake_reconnect.requested", {
|
||||
source,
|
||||
controller_enabled: controller.isConnectionEnabled,
|
||||
transport_state: transport.state,
|
||||
});
|
||||
if (!controller.isConnectionEnabled) return;
|
||||
if (transport.state === "connected") return;
|
||||
void transport.connect().catch((err) => {
|
||||
@@ -265,13 +302,14 @@ export default defineBackground(() => {
|
||||
});
|
||||
};
|
||||
if (typeof chrome.runtime?.onStartup?.addListener === "function") {
|
||||
chrome.runtime.onStartup.addListener(reconnectIfNeeded);
|
||||
chrome.runtime.onStartup.addListener(() => reconnectIfNeeded("runtime.onStartup"));
|
||||
}
|
||||
if (typeof chrome.idle?.onStateChanged?.addListener === "function") {
|
||||
chrome.idle.onStateChanged.addListener((state) => {
|
||||
diagnostics.record("chrome.idle.state_changed", { state });
|
||||
// "active" fires when the user returns from idle/locked — the most
|
||||
// reliable "machine just woke" signal we get.
|
||||
if (state === "active") reconnectIfNeeded();
|
||||
if (state === "active") reconnectIfNeeded("idle.active");
|
||||
});
|
||||
// Treat >60s of no input as idle so the active transition is timely.
|
||||
chrome.idle.setDetectionInterval?.(60);
|
||||
@@ -279,14 +317,21 @@ export default defineBackground(() => {
|
||||
|
||||
void (async () => {
|
||||
const connectionEnabled = await getConnectionEnabled();
|
||||
diagnostics.record("background.controller.attach_started", { connectionEnabled });
|
||||
await controller.attach(transport, detectBrowserMeta(), connectionEnabled, {
|
||||
beforeDisconnect: async () => {
|
||||
diagnostics.record("background.before_disconnect_cleanup", {
|
||||
live_session_ids: sessions.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
const report = await cleanupAfterDisconnect();
|
||||
if (report.failures.length > 0) {
|
||||
console.warn("[browser-skill] session cleanup before disconnect was incomplete", report);
|
||||
}
|
||||
},
|
||||
onDisconnected: async () => {
|
||||
diagnostics.record("background.after_disconnect_cleanup", {
|
||||
live_session_ids: sessions.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
const report = await cleanupAfterDisconnect();
|
||||
if (report.failures.length > 0) {
|
||||
console.warn("[browser-skill] session cleanup after disconnect was incomplete", report);
|
||||
@@ -294,6 +339,7 @@ export default defineBackground(() => {
|
||||
},
|
||||
});
|
||||
})().catch((err) => {
|
||||
diagnostics.record("background.controller.attach_failed", { error: err });
|
||||
console.error("[browser-skill] controller failed to attach", err);
|
||||
});
|
||||
|
||||
@@ -374,6 +420,15 @@ export default defineBackground(() => {
|
||||
dbg.__bhDispatcher = dispatcher;
|
||||
}
|
||||
|
||||
if (typeof chrome.runtime?.onSuspend?.addListener === "function") {
|
||||
chrome.runtime.onSuspend.addListener(() => {
|
||||
diagnostics.record("extension.worker.suspending", {
|
||||
live_session_ids: sessions.list().map((ctx) => ctx.sessionId),
|
||||
transport_state: transport.state,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
console.info("[browser-skill] background worker initialised");
|
||||
});
|
||||
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DiagnosticLogger } from "../diagnostics";
|
||||
|
||||
class MemoryStorage {
|
||||
value: Record<string, unknown> = {};
|
||||
|
||||
async get(key: string): Promise<Record<string, unknown>> {
|
||||
return { [key]: this.value[key] };
|
||||
}
|
||||
|
||||
async set(items: Record<string, unknown>): Promise<void> {
|
||||
this.value = { ...this.value, ...items };
|
||||
}
|
||||
}
|
||||
|
||||
describe("DiagnosticLogger", () => {
|
||||
it("persists evidence before transport readiness and flushes it after reconnect", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const send = vi.fn();
|
||||
const logger = new DiagnosticLogger(storage);
|
||||
logger.bindTransport(send);
|
||||
|
||||
logger.record("transport.socket.closed", { code: 1006 });
|
||||
await logger.flush();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
|
||||
logger.setTransportReady(true);
|
||||
await logger.flush();
|
||||
|
||||
expect(send).toHaveBeenCalledOnce();
|
||||
expect(send.mock.calls[0]?.[0]).toMatchObject({
|
||||
event: "browser.diagnostic",
|
||||
payload: {
|
||||
schema_version: 1,
|
||||
entries: [
|
||||
{
|
||||
event: "transport.socket.closed",
|
||||
fields: { code: 1006 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(storage.value.bsk_diagnostic_events_v1).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps persisted evidence when the transport rejects the flush", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const logger = new DiagnosticLogger(storage);
|
||||
logger.bindTransport(() => {
|
||||
throw new Error("socket closed");
|
||||
});
|
||||
logger.record("session.stop.requested", { session_id: "abcd" });
|
||||
|
||||
logger.setTransportReady(true);
|
||||
await logger.flush();
|
||||
|
||||
expect(storage.value.bsk_diagnostic_events_v1).toMatchObject([
|
||||
{ event: "session.stop.requested", fields: { session_id: "abcd" } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not resend an acknowledged event when send records a new event", async () => {
|
||||
const storage = new MemoryStorage();
|
||||
const batches: Array<{ payload?: { entries?: Array<{ event: string }> } }> = [];
|
||||
const logger = new DiagnosticLogger(storage);
|
||||
logger.record("dispatcher.rpc.received", { rpc_id: "one" });
|
||||
await logger.flush();
|
||||
logger.bindTransport((frame) => {
|
||||
batches.push(frame as { payload?: { entries?: Array<{ event: string }> } });
|
||||
if (batches.length === 1) {
|
||||
logger.record("dispatcher.rpc.response_sent", { rpc_id: "one" });
|
||||
}
|
||||
});
|
||||
|
||||
logger.setTransportReady(true);
|
||||
await logger.flush();
|
||||
await logger.flush();
|
||||
|
||||
expect(batches.map((batch) => batch.payload?.entries?.map((entry) => entry.event))).toEqual([
|
||||
["dispatcher.rpc.received"],
|
||||
["dispatcher.rpc.response_sent"],
|
||||
]);
|
||||
expect(storage.value.bsk_diagnostic_events_v1).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "../transport/handshake";
|
||||
import type { Transport } from "../transport/transport";
|
||||
import type { ConnectionState, HandshakeResult } from "../transport/types";
|
||||
import type { DiagnosticSink } from "./diagnostics";
|
||||
import { getLabel, getOrCreateInstanceId } from "./instance-id";
|
||||
import { compareProtocol, parseProtocolMajor } from "./semver";
|
||||
|
||||
@@ -51,6 +52,11 @@ export class ConnectionController {
|
||||
private handshakeAbort: AbortController | null = null;
|
||||
private handshakeRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private suppressDisconnectRecovery = false;
|
||||
private readonly diagnostics?: DiagnosticSink;
|
||||
|
||||
constructor(diagnostics?: DiagnosticSink) {
|
||||
this.diagnostics = diagnostics;
|
||||
}
|
||||
|
||||
get isConnectionEnabled(): boolean {
|
||||
return this.connectionEnabled;
|
||||
@@ -89,8 +95,20 @@ export class ConnectionController {
|
||||
this.lifecycleHooks = lifecycleHooks;
|
||||
this.instanceId = await getOrCreateInstanceId();
|
||||
this.label = await getLabel();
|
||||
this.diagnostics?.("controller.attach", {
|
||||
instance_id: this.instanceId,
|
||||
connection_enabled: connectionEnabled,
|
||||
transport_state: transport.state,
|
||||
});
|
||||
|
||||
transport.onConnectionStateChange((s) => {
|
||||
this.diagnostics?.("controller.transport_state", {
|
||||
transport_state: s,
|
||||
controller_state: this.currentState,
|
||||
connection_generation: this.connectionGeneration,
|
||||
suppress_disconnect_recovery: this.suppressDisconnectRecovery,
|
||||
recovery_inflight: this.disconnectRecovery !== null,
|
||||
});
|
||||
if (s === "disconnected") {
|
||||
// An in-flight handshake belongs to the dead connection — cancel it so
|
||||
// a late resolution can never clobber the next attempt.
|
||||
@@ -103,6 +121,9 @@ export class ConnectionController {
|
||||
// handshake bounce); the caller owns the reconnect policy there.
|
||||
this.suppressDisconnectRecovery = false;
|
||||
} else {
|
||||
this.diagnostics?.("controller.disconnect_recovery.requested", {
|
||||
connection_generation: this.connectionGeneration,
|
||||
});
|
||||
void this.recoverFromDisconnect();
|
||||
}
|
||||
}
|
||||
@@ -161,6 +182,12 @@ export class ConnectionController {
|
||||
const generation = ++this.connectionGeneration;
|
||||
const abort = new AbortController();
|
||||
this.handshakeAbort = abort;
|
||||
this.diagnostics?.("controller.handshake.started", {
|
||||
connection_generation: generation,
|
||||
browser_name: browser.name,
|
||||
browser_version: browser.version,
|
||||
instance_id: this.instanceId,
|
||||
});
|
||||
void this.runHandshake(browser, generation, abort.signal);
|
||||
}
|
||||
|
||||
@@ -197,11 +224,21 @@ export class ConnectionController {
|
||||
}
|
||||
this.clearHandshakeRetry();
|
||||
this.lastError = null;
|
||||
this.diagnostics?.("controller.handshake.completed", {
|
||||
connection_generation: generation,
|
||||
verdict: verdict.kind,
|
||||
daemon_version: outcome.result.version,
|
||||
daemon_protocol: outcome.result.protocol_version,
|
||||
});
|
||||
this.setState(verdict.kind);
|
||||
} catch (err) {
|
||||
if (generation !== this.connectionGeneration || signal.aborted || isAbortError(err)) return;
|
||||
this.handshake = null;
|
||||
this.lastError = err instanceof Error ? err.message : String(err);
|
||||
this.diagnostics?.("controller.handshake.failed", {
|
||||
connection_generation: generation,
|
||||
error: err,
|
||||
});
|
||||
// Bounce the half-open socket deliberately; the retry timer below owns
|
||||
// the reconnect, so skip unexpected-loss recovery for this disconnect.
|
||||
this.suppressDisconnectRecovery = true;
|
||||
@@ -228,23 +265,57 @@ export class ConnectionController {
|
||||
}
|
||||
|
||||
private recoverFromDisconnect(): Promise<void> {
|
||||
if (this.disconnectRecovery) return this.disconnectRecovery;
|
||||
if (this.disconnectRecovery) {
|
||||
this.diagnostics?.("controller.disconnect_recovery.coalesced", {
|
||||
connection_generation: this.connectionGeneration,
|
||||
});
|
||||
return this.disconnectRecovery;
|
||||
}
|
||||
const recovery = (async () => {
|
||||
const recoveryGeneration = this.connectionGeneration;
|
||||
this.diagnostics?.("controller.disconnect_recovery.started", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
});
|
||||
// WSTransport schedules its reconnect timer immediately after notifying
|
||||
// state listeners. Yield once, then disconnect explicitly so that timer
|
||||
// is cancelled before local session teardown begins.
|
||||
await Promise.resolve();
|
||||
if (!this.connectionEnabled || !this.transport) return;
|
||||
if (!this.connectionEnabled || !this.transport) {
|
||||
this.diagnostics?.("controller.disconnect_recovery.skipped", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
reason: "disabled_or_missing_transport",
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Another path already reconnected while we yielded — nothing to do.
|
||||
if (this.currentState !== "disconnected") return;
|
||||
if (this.currentState !== "disconnected") {
|
||||
this.diagnostics?.("controller.disconnect_recovery.skipped", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
reason: "state_already_changed",
|
||||
current_state: this.currentState,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.transport.disconnect().catch(() => {});
|
||||
try {
|
||||
this.diagnostics?.("controller.disconnect_cleanup.started", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
current_generation: this.connectionGeneration,
|
||||
});
|
||||
await this.lifecycleHooks.onDisconnected?.();
|
||||
this.diagnostics?.("controller.disconnect_cleanup.completed", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
current_generation: this.connectionGeneration,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn("[browser-skill] session cleanup after disconnect failed", err);
|
||||
}
|
||||
if (!this.connectionEnabled) return;
|
||||
try {
|
||||
this.diagnostics?.("controller.disconnect_reconnect.started", {
|
||||
recovery_generation: recoveryGeneration,
|
||||
current_generation: this.connectionGeneration,
|
||||
});
|
||||
await this.transport.connect();
|
||||
} catch (err) {
|
||||
this.lastError = err instanceof Error ? err.message : String(err);
|
||||
@@ -252,22 +323,39 @@ export class ConnectionController {
|
||||
}
|
||||
})();
|
||||
this.disconnectRecovery = recovery.finally(() => {
|
||||
this.diagnostics?.("controller.disconnect_recovery.completed", {
|
||||
connection_generation: this.connectionGeneration,
|
||||
current_state: this.currentState,
|
||||
});
|
||||
this.disconnectRecovery = null;
|
||||
});
|
||||
return this.disconnectRecovery;
|
||||
}
|
||||
|
||||
private cancelHandshake(): void {
|
||||
const previousGeneration = this.connectionGeneration;
|
||||
this.connectionGeneration += 1;
|
||||
this.diagnostics?.("controller.handshake.cancelled", {
|
||||
previous_generation: previousGeneration,
|
||||
next_generation: this.connectionGeneration,
|
||||
had_abort_controller: this.handshakeAbort !== null,
|
||||
});
|
||||
this.handshakeAbort?.abort();
|
||||
this.handshakeAbort = null;
|
||||
}
|
||||
|
||||
private scheduleHandshakeRetry(browser: { name: string; version: string }): void {
|
||||
if (this.handshakeRetryTimer || !this.connectionEnabled) return;
|
||||
this.diagnostics?.("controller.handshake_retry.scheduled", {
|
||||
delay_ms: HANDSHAKE_RETRY_DELAY_MS,
|
||||
connection_generation: this.connectionGeneration,
|
||||
});
|
||||
this.handshakeRetryTimer = setTimeout(() => {
|
||||
this.handshakeRetryTimer = null;
|
||||
if (!this.connectionEnabled || !this.transport) return;
|
||||
this.diagnostics?.("controller.handshake_retry.timer_fired", {
|
||||
connection_generation: this.connectionGeneration,
|
||||
});
|
||||
void this.transport.connect().catch((err) => {
|
||||
this.lastError = err instanceof Error ? err.message : String(err);
|
||||
this.setState("disconnected");
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import type { ProtocolFrame } from "@/transport/types";
|
||||
|
||||
const STORAGE_KEY = "bsk_diagnostic_events_v1";
|
||||
const MAX_ENTRIES = 500;
|
||||
|
||||
export type DiagnosticFields = Record<string, unknown>;
|
||||
export type DiagnosticSink = (event: string, fields?: DiagnosticFields) => void;
|
||||
|
||||
export interface DiagnosticEntry {
|
||||
id: string;
|
||||
sequence: number;
|
||||
timestamp: string;
|
||||
monotonic_ms: number;
|
||||
worker_boot_id: string;
|
||||
event: string;
|
||||
fields: DiagnosticFields;
|
||||
}
|
||||
|
||||
interface DiagnosticStorage {
|
||||
get(key: string): Promise<Record<string, unknown>>;
|
||||
set(items: Record<string, unknown>): Promise<void>;
|
||||
}
|
||||
|
||||
function defaultStorage(): DiagnosticStorage | null {
|
||||
if (typeof chrome === "undefined" || !chrome.storage?.local) return null;
|
||||
return {
|
||||
get: (key) => chrome.storage.local.get(key),
|
||||
set: (items) => chrome.storage.local.set(items),
|
||||
};
|
||||
}
|
||||
|
||||
function makeBootId(): string {
|
||||
try {
|
||||
return crypto.randomUUID();
|
||||
} catch {
|
||||
return `worker-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
}
|
||||
|
||||
function normalise(value: unknown): unknown {
|
||||
if (value instanceof Error) {
|
||||
return { name: value.name, message: value.message, stack: value.stack };
|
||||
}
|
||||
if (typeof value === "bigint") return value.toString();
|
||||
if (Array.isArray(value)) return value.map(normalise);
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, child]) => [
|
||||
key,
|
||||
normalise(child),
|
||||
]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persistent diagnostics for the MV3 background worker.
|
||||
*
|
||||
* Events are first written to chrome.storage.local so a worker termination or
|
||||
* dead WebSocket does not erase the evidence. Once the post-handshake link is
|
||||
* ready, pending entries are forwarded to the daemon as one
|
||||
* `browser.diagnostic` event and removed from the local queue.
|
||||
*/
|
||||
export class DiagnosticLogger {
|
||||
readonly workerBootId: string;
|
||||
readonly sink: DiagnosticSink;
|
||||
|
||||
private sequence = 0;
|
||||
private storageQueue: Promise<void> = Promise.resolve();
|
||||
private flushPromise: Promise<void> | null = null;
|
||||
private flushRequested = false;
|
||||
private send: ((frame: ProtocolFrame) => void) | null = null;
|
||||
private transportReady = false;
|
||||
private readonly storage: DiagnosticStorage | null;
|
||||
|
||||
constructor(storage: DiagnosticStorage | null = defaultStorage()) {
|
||||
this.workerBootId = makeBootId();
|
||||
this.storage = storage;
|
||||
this.sink = (event, fields = {}) => this.record(event, fields);
|
||||
}
|
||||
|
||||
bindTransport(send: (frame: ProtocolFrame) => void): void {
|
||||
this.send = send;
|
||||
}
|
||||
|
||||
setTransportReady(ready: boolean): void {
|
||||
this.transportReady = ready;
|
||||
if (ready) void this.flush();
|
||||
}
|
||||
|
||||
record(event: string, fields: DiagnosticFields = {}): void {
|
||||
const sequence = ++this.sequence;
|
||||
const entry: DiagnosticEntry = {
|
||||
id: `${this.workerBootId}:${sequence}`,
|
||||
sequence,
|
||||
timestamp: new Date().toISOString(),
|
||||
monotonic_ms: Math.round(performance.now()),
|
||||
worker_boot_id: this.workerBootId,
|
||||
event,
|
||||
fields: normalise(fields) as DiagnosticFields,
|
||||
};
|
||||
console.info("[bsk diagnostic]", entry);
|
||||
this.storageQueue = this.storageQueue
|
||||
.then(async () => {
|
||||
if (!this.storage) return;
|
||||
const stored = await this.storage.get(STORAGE_KEY);
|
||||
const previous = Array.isArray(stored[STORAGE_KEY])
|
||||
? (stored[STORAGE_KEY] as DiagnosticEntry[])
|
||||
: [];
|
||||
await this.storage.set({
|
||||
[STORAGE_KEY]: [...previous, entry].slice(-MAX_ENTRIES),
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[bsk diagnostic] failed to persist event", error);
|
||||
});
|
||||
if (this.transportReady) void this.flush();
|
||||
}
|
||||
|
||||
flush(): Promise<void> {
|
||||
if (this.flushPromise) {
|
||||
this.flushRequested = true;
|
||||
return this.flushPromise;
|
||||
}
|
||||
const running = (async () => {
|
||||
await this.storageQueue;
|
||||
if (!this.transportReady || !this.send || !this.storage) return;
|
||||
const stored = await this.storage.get(STORAGE_KEY);
|
||||
const entries = Array.isArray(stored[STORAGE_KEY])
|
||||
? (stored[STORAGE_KEY] as DiagnosticEntry[])
|
||||
: [];
|
||||
if (entries.length === 0) return;
|
||||
try {
|
||||
this.send({
|
||||
event: "browser.diagnostic",
|
||||
payload: {
|
||||
schema_version: 1,
|
||||
worker_boot_id: this.workerBootId,
|
||||
entries,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("[bsk diagnostic] daemon flush failed", error);
|
||||
return;
|
||||
}
|
||||
const sentIds = new Set(entries.map((entry) => entry.id));
|
||||
// Serialize acknowledgement behind every record write that may have
|
||||
// started while send() was in progress. Without this, a concurrent
|
||||
// record can read the pre-ack queue and write an already-sent entry
|
||||
// back into storage, causing the next batch to duplicate it.
|
||||
this.storageQueue = this.storageQueue
|
||||
.then(async () => {
|
||||
const current = await this.storage?.get(STORAGE_KEY);
|
||||
const currentEntries = Array.isArray(current?.[STORAGE_KEY])
|
||||
? (current[STORAGE_KEY] as DiagnosticEntry[])
|
||||
: [];
|
||||
await this.storage?.set({
|
||||
[STORAGE_KEY]: currentEntries.filter((entry) => !sentIds.has(entry.id)),
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[bsk diagnostic] failed to acknowledge event batch", error);
|
||||
});
|
||||
await this.storageQueue;
|
||||
})().catch((error) => {
|
||||
console.warn("[bsk diagnostic] flush failed", error);
|
||||
});
|
||||
this.flushPromise = running.finally(() => {
|
||||
this.flushPromise = null;
|
||||
if (this.flushRequested && this.transportReady) {
|
||||
this.flushRequested = false;
|
||||
void this.flush();
|
||||
}
|
||||
});
|
||||
return this.flushPromise;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@
|
||||
* after the handshake has landed.
|
||||
*/
|
||||
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import type { ProtocolFrame } from "@/transport/types";
|
||||
|
||||
export const HEARTBEAT_EVENT = "system.heartbeat";
|
||||
@@ -46,6 +47,7 @@ export interface HeartbeatOptions {
|
||||
intervalMs?: number;
|
||||
/** Inject fake timers (tests). */
|
||||
timers?: HeartbeatTimers;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
export interface HeartbeatHandle {
|
||||
@@ -74,7 +76,9 @@ export function startHeartbeat(options: HeartbeatOptions): HeartbeatHandle {
|
||||
const beat = () => {
|
||||
try {
|
||||
options.send({ event: HEARTBEAT_EVENT, payload: {} });
|
||||
options.diagnostics?.("heartbeat.sent");
|
||||
} catch (err) {
|
||||
options.diagnostics?.("heartbeat.send_failed", { error: err });
|
||||
// The socket raced a close between the state change and this
|
||||
// tick. The transport's own reconnect path recovers; swallow so
|
||||
// the interval keeps running (it is cleared on the disconnect
|
||||
@@ -87,12 +91,14 @@ export function startHeartbeat(options: HeartbeatOptions): HeartbeatHandle {
|
||||
if (timer !== null) {
|
||||
timers.clearInterval(timer);
|
||||
timer = null;
|
||||
options.diagnostics?.("heartbeat.timer.stopped");
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
if (timer !== null) return;
|
||||
timer = timers.setInterval(beat, intervalMs);
|
||||
options.diagnostics?.("heartbeat.timer.started", { interval_ms: intervalMs });
|
||||
};
|
||||
|
||||
const unsubscribe = options.onActiveChange((active) => {
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
* SW idle threshold.
|
||||
*/
|
||||
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import type { Transport } from "@/transport/transport";
|
||||
|
||||
export const KEEPALIVE_ALARM_NAME = "bh-keepalive";
|
||||
@@ -59,6 +60,7 @@ export interface KeepaliveOptions {
|
||||
alarmName?: string;
|
||||
/** Override the alarm period (tests). */
|
||||
periodMin?: number;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
export interface KeepaliveHandle {
|
||||
@@ -79,11 +81,24 @@ export function startKeepalive(options: KeepaliveOptions): KeepaliveHandle {
|
||||
const period = options.periodMin ?? KEEPALIVE_PERIOD_MIN;
|
||||
|
||||
const tick = async () => {
|
||||
if (options.shouldConnect && !options.shouldConnect()) return;
|
||||
if (options.transport.state === "connected") return;
|
||||
if (options.shouldConnect && !options.shouldConnect()) {
|
||||
options.diagnostics?.("keepalive.tick.skipped", { reason: "connection_disabled" });
|
||||
return;
|
||||
}
|
||||
if (options.transport.state === "connected") {
|
||||
options.diagnostics?.("keepalive.tick.healthy", { transport_state: "connected" });
|
||||
return;
|
||||
}
|
||||
options.diagnostics?.("keepalive.reconnect.started", {
|
||||
transport_state: options.transport.state,
|
||||
});
|
||||
try {
|
||||
await options.transport.connect();
|
||||
options.diagnostics?.("keepalive.reconnect.completed", {
|
||||
transport_state: options.transport.state,
|
||||
});
|
||||
} catch (err) {
|
||||
options.diagnostics?.("keepalive.reconnect.failed", { error: err });
|
||||
console.debug("[bsk keepalive] connect attempt failed", err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -13,8 +13,6 @@ describe("RefStore", () => {
|
||||
backendNodeId: 42,
|
||||
tabId: 7,
|
||||
generation: 0,
|
||||
kind: "dom",
|
||||
capabilities: ["interact", "screenshot"],
|
||||
});
|
||||
expect(s.size()).toBe(1);
|
||||
expect(s.isEmpty()).toBe(false);
|
||||
@@ -50,31 +48,4 @@ 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"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import { handleSessionStop, type SessionStopDeps } from "@/tools/session";
|
||||
import type { SessionManager } from "./manager";
|
||||
|
||||
@@ -15,6 +16,7 @@ export interface DisconnectCleanupOptions {
|
||||
manager: SessionManager;
|
||||
sessionStopDeps?: SessionStopDeps;
|
||||
onSessionsChanged?: () => void;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -29,7 +31,15 @@ export function createDisconnectCleanup(options: DisconnectCleanupOptions) {
|
||||
let inFlight: Promise<DisconnectCleanupReport> | null = null;
|
||||
|
||||
return (): Promise<DisconnectCleanupReport> => {
|
||||
if (inFlight) return inFlight;
|
||||
if (inFlight) {
|
||||
options.diagnostics?.("disconnect_cleanup.coalesced", {
|
||||
live_session_ids: options.manager.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
options.diagnostics?.("disconnect_cleanup.scheduled", {
|
||||
live_session_ids: options.manager.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
inFlight = cleanupSessions(options).finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
@@ -42,8 +52,17 @@ async function cleanupSessions(
|
||||
): Promise<DisconnectCleanupReport> {
|
||||
const stoppedSessionIds: string[] = [];
|
||||
const failures: DisconnectCleanupFailure[] = [];
|
||||
const capturedSessions = options.manager.list();
|
||||
options.diagnostics?.("disconnect_cleanup.started", {
|
||||
captured_session_ids: capturedSessions.map((ctx) => ctx.sessionId),
|
||||
});
|
||||
|
||||
for (const ctx of options.manager.list()) {
|
||||
for (const ctx of capturedSessions) {
|
||||
options.diagnostics?.("disconnect_cleanup.session_stop.started", {
|
||||
session_id: ctx.sessionId,
|
||||
agent_window_id: ctx.agentWindowId,
|
||||
still_registered: options.manager.has(ctx.sessionId),
|
||||
});
|
||||
try {
|
||||
const result = await handleSessionStop(
|
||||
options.manager,
|
||||
@@ -62,14 +81,26 @@ async function cleanupSessions(
|
||||
continue;
|
||||
}
|
||||
stoppedSessionIds.push(ctx.sessionId);
|
||||
options.diagnostics?.("disconnect_cleanup.session_stop.completed", {
|
||||
session_id: ctx.sessionId,
|
||||
});
|
||||
} catch (err) {
|
||||
failures.push({
|
||||
sessionId: ctx.sessionId,
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
options.diagnostics?.("disconnect_cleanup.session_stop.failed", {
|
||||
session_id: ctx.sessionId,
|
||||
error: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
options.onSessionsChanged?.();
|
||||
options.diagnostics?.("disconnect_cleanup.completed", {
|
||||
stopped_session_ids: stoppedSessionIds,
|
||||
failures,
|
||||
remaining_session_ids: options.manager.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
return { stoppedSessionIds, failures };
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import type { Transport } from "@/transport/transport";
|
||||
import type { EventFrame } from "@/transport/types";
|
||||
import type { SessionManager } from "./manager";
|
||||
@@ -24,6 +25,7 @@ export interface SessionEventHandlerOptions {
|
||||
* `chrome.storage.session` "sessions live" flag (review M4/M5 I3).
|
||||
*/
|
||||
onSessionsChanged?: () => void;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
function chromeWindowEvents(): WindowRemovedListener {
|
||||
@@ -50,6 +52,11 @@ export function attachSessionEventHandler(options: SessionEventHandlerOptions):
|
||||
|
||||
const onRemoved = (windowId: number): void => {
|
||||
const ctx = manager.findByWindowId(windowId);
|
||||
options.diagnostics?.("chrome.window.removed", {
|
||||
window_id: windowId,
|
||||
matched_session_id: ctx?.sessionId ?? null,
|
||||
live_session_ids: manager.list().map((entry) => entry.sessionId),
|
||||
});
|
||||
if (!ctx) return;
|
||||
const returnFailures = Array.from(ctx.borrowedTabs.keys()).map((tabId) => ({
|
||||
tab_id: tabId,
|
||||
@@ -81,7 +88,16 @@ export function attachSessionEventHandler(options: SessionEventHandlerOptions):
|
||||
};
|
||||
try {
|
||||
transport.send(event);
|
||||
options.diagnostics?.("session.window_closed.sent", {
|
||||
session_id: ctx.sessionId,
|
||||
window_id: windowId,
|
||||
});
|
||||
} catch (err) {
|
||||
options.diagnostics?.("session.window_closed.send_failed", {
|
||||
session_id: ctx.sessionId,
|
||||
window_id: windowId,
|
||||
error: err,
|
||||
});
|
||||
console.warn("[bh] could not push session.window_closed event", err);
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import { AGENT_WINDOW_HOME, type AgentWindowApi, chromeAgentWindowApi } from "./agent-window";
|
||||
import { RefStore } from "./ref-store";
|
||||
|
||||
@@ -23,6 +24,7 @@ export interface BorrowReservation {
|
||||
export interface SessionManagerOptions {
|
||||
agentWindow?: AgentWindowApi;
|
||||
now?: () => number;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
/** Options for starting a session's Agent Window. */
|
||||
@@ -83,10 +85,12 @@ export class SessionManager {
|
||||
private readonly borrowReservations = new Map<number, string>();
|
||||
private readonly agentWindow: AgentWindowApi;
|
||||
private readonly now: () => number;
|
||||
private readonly diagnostics?: DiagnosticSink;
|
||||
|
||||
constructor(options: SessionManagerOptions = {}) {
|
||||
this.agentWindow = options.agentWindow ?? chromeAgentWindowApi;
|
||||
this.now = options.now ?? Date.now;
|
||||
this.diagnostics = options.diagnostics;
|
||||
}
|
||||
|
||||
has(sessionId: string): boolean {
|
||||
@@ -169,6 +173,13 @@ export class SessionManager {
|
||||
* daemon in the `tool.session_start` reply.
|
||||
*/
|
||||
async start(sessionId: string, opts: SessionStartOptions = {}): Promise<SessionContext> {
|
||||
this.diagnostics?.("session_manager.start.requested", {
|
||||
session_id: sessionId,
|
||||
existing_session_ids: this.list().map((ctx) => ctx.sessionId),
|
||||
focused: opts.focused ?? null,
|
||||
size: opts.size ?? null,
|
||||
signal_aborted: opts.signal?.aborted ?? false,
|
||||
});
|
||||
if (this.sessions.has(sessionId)) {
|
||||
throw new Error(`[bh] session ${sessionId} already exists`);
|
||||
}
|
||||
@@ -178,6 +189,10 @@ export class SessionManager {
|
||||
try {
|
||||
const { signal: _signal, ...createOptions } = opts;
|
||||
windowId = await this.agentWindow.create(AGENT_WINDOW_HOME, createOptions);
|
||||
this.diagnostics?.("session_manager.window.created", {
|
||||
session_id: sessionId,
|
||||
agent_window_id: windowId,
|
||||
});
|
||||
throwIfSessionStartAborted(opts.signal);
|
||||
await this.agentWindow.ensureActiveTab(windowId, AGENT_WINDOW_HOME);
|
||||
throwIfSessionStartAborted(opts.signal);
|
||||
@@ -191,8 +206,18 @@ export class SessionManager {
|
||||
};
|
||||
this.sessions.set(sessionId, ctx);
|
||||
this.windowIndex.set(windowId, sessionId);
|
||||
this.diagnostics?.("session_manager.start.committed", {
|
||||
session_id: sessionId,
|
||||
agent_window_id: windowId,
|
||||
live_session_ids: this.list().map((entry) => entry.sessionId),
|
||||
});
|
||||
return ctx;
|
||||
} catch (startupError) {
|
||||
this.diagnostics?.("session_manager.start.failed", {
|
||||
session_id: sessionId,
|
||||
agent_window_id: windowId,
|
||||
error: startupError,
|
||||
});
|
||||
if (windowId !== null) {
|
||||
try {
|
||||
await this.agentWindow.remove(windowId);
|
||||
@@ -216,12 +241,28 @@ export class SessionManager {
|
||||
options: { dropOnly?: boolean } = {},
|
||||
): Promise<SessionContext | null> {
|
||||
const ctx = this.sessions.get(sessionId);
|
||||
this.diagnostics?.("session_manager.stop.requested", {
|
||||
session_id: sessionId,
|
||||
drop_only: options.dropOnly ?? false,
|
||||
existed: ctx !== undefined,
|
||||
live_session_ids: this.list().map((entry) => entry.sessionId),
|
||||
});
|
||||
if (!ctx) return null;
|
||||
if (!options.dropOnly) {
|
||||
await this.agentWindow.remove(ctx.agentWindowId);
|
||||
this.diagnostics?.("session_manager.window.removed", {
|
||||
session_id: sessionId,
|
||||
agent_window_id: ctx.agentWindowId,
|
||||
});
|
||||
}
|
||||
this.sessions.delete(sessionId);
|
||||
this.windowIndex.delete(ctx.agentWindowId);
|
||||
this.diagnostics?.("session_manager.stop.committed", {
|
||||
session_id: sessionId,
|
||||
agent_window_id: ctx.agentWindowId,
|
||||
drop_only: options.dropOnly ?? false,
|
||||
live_session_ids: this.list().map((entry) => entry.sessionId),
|
||||
});
|
||||
return ctx;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { Rect } from "@browser-skill/vom";
|
||||
|
||||
/**
|
||||
* Per-session map from `@e<N>` snapshot refs to a CDP node address.
|
||||
*
|
||||
@@ -14,17 +12,12 @@ import type { Rect } from "@browser-skill/vom";
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -35,19 +28,8 @@ 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;
|
||||
@@ -88,20 +70,13 @@ 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,
|
||||
});
|
||||
}
|
||||
@@ -119,20 +94,14 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,29 +123,6 @@ 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");
|
||||
@@ -479,6 +456,30 @@ describe("handleClick", () => {
|
||||
expect(res).toMatchObject({ code: "not_found", data: { reason: "selector_not_found" } });
|
||||
});
|
||||
|
||||
it("returns invalid_selector when Chrome rejects non-CSS selector syntax", async () => {
|
||||
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
|
||||
await sm.start("aa11");
|
||||
const fake = makeFakeCdp({
|
||||
"DOM.getDocument": () => ({ root: { nodeId: 1 } }),
|
||||
"DOM.querySelector": () => {
|
||||
throw new Error('{"code":-32000,"message":"DOM Error while querying"}');
|
||||
},
|
||||
});
|
||||
const res = await handleClick(
|
||||
sm,
|
||||
{ session_id: "aa11", selector: "text=下午 12~18点" },
|
||||
{ cdp: fake.cdp, tabsApi: fake.tabsApi },
|
||||
);
|
||||
expect(res).toMatchObject({
|
||||
code: "invalid_params",
|
||||
message: "selector is not valid CSS: text=下午 12~18点",
|
||||
data: {
|
||||
reason: "invalid_selector",
|
||||
selector: "text=下午 12~18点",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("respects the AbortSignal", async () => {
|
||||
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
|
||||
const ctx = await sm.start("aa11");
|
||||
|
||||
@@ -300,76 +300,6 @@ 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)));
|
||||
});
|
||||
|
||||
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 });
|
||||
});
|
||||
|
||||
it("returns not_found for unknown ref", async () => {
|
||||
const sm = new SessionManager({ agentWindow: fakeAgentWindow([100]) });
|
||||
await sm.start("aa11");
|
||||
@@ -2763,85 +2693,6 @@ 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");
|
||||
|
||||
@@ -24,14 +24,10 @@ describe("lookupSnapshotRef", () => {
|
||||
expect(lookupSnapshotRef(ctx, "@e3", 4)).toEqual({
|
||||
backendNodeId: 1234,
|
||||
refKey: "e3",
|
||||
kind: "dom",
|
||||
capabilities: ["interact", "screenshot"],
|
||||
});
|
||||
expect(lookupSnapshotRef(ctx, "e3", 4)).toEqual({
|
||||
backendNodeId: 1234,
|
||||
refKey: "e3",
|
||||
kind: "dom",
|
||||
capabilities: ["interact", "screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,8 +53,6 @@ describe("resolveSnapshotRef", () => {
|
||||
tabId: 4,
|
||||
frameId: "child-frame",
|
||||
cdpSessionId: "child-session",
|
||||
kind: "dom",
|
||||
capabilities: ["interact", "screenshot"],
|
||||
});
|
||||
|
||||
const expected = {
|
||||
@@ -66,8 +60,6 @@ describe("resolveSnapshotRef", () => {
|
||||
refKey: "e3",
|
||||
frameId: "child-frame",
|
||||
cdpSessionId: "child-session",
|
||||
kind: "dom" as const,
|
||||
capabilities: ["interact", "screenshot"] as const,
|
||||
};
|
||||
expect(lookupSnapshotRef(ctx, "@e3", 4)).toEqual(expected);
|
||||
expect(resolveSnapshotRef(ctx, "@e3", 4)).toEqual(expected);
|
||||
@@ -113,28 +105,6 @@ describe("resolveSnapshotRef", () => {
|
||||
expect(resolveSnapshotRef(ctx, "@e3", 4)).toEqual({
|
||||
backendNodeId: 1234,
|
||||
refKey: "e3",
|
||||
kind: "dom",
|
||||
capabilities: ["interact", "screenshot"],
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import { OVERLAY_AUTOMATION_BYPASS } from "@/lib/overlay-bridge";
|
||||
import type { SessionManager } from "@/session-manager/manager";
|
||||
import type { Transport } from "@/transport/transport";
|
||||
@@ -118,6 +119,7 @@ export interface DispatcherDeps {
|
||||
approveBorrow?: BorrowConfirmationApprover;
|
||||
/** i18n notification copy for `tool.request_help` (resolved per-call). */
|
||||
helpNotificationCopy?: () => { title: string; body: string };
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -145,6 +147,7 @@ export class ToolDispatcher {
|
||||
private readonly onBrowserControlResumed?: (sessionId: string) => void;
|
||||
private readonly approveBorrow?: BorrowConfirmationApprover;
|
||||
private readonly helpNotificationCopy?: () => { title: string; body: string };
|
||||
private readonly diagnostics?: DiagnosticSink;
|
||||
private subscription: { dispose(): void } | null = null;
|
||||
private readonly hoverBypassTabs = new Map<number, string>();
|
||||
private readonly hoverLatches = new Map<number, HoverLatch>();
|
||||
@@ -165,6 +168,7 @@ export class ToolDispatcher {
|
||||
this.onBrowserControlResumed = deps.onBrowserControlResumed;
|
||||
this.approveBorrow = deps.approveBorrow;
|
||||
this.helpNotificationCopy = deps.helpNotificationCopy;
|
||||
this.diagnostics = deps.diagnostics;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
@@ -192,6 +196,16 @@ export class ToolDispatcher {
|
||||
private async dispatch(msg: ProtocolFrame): Promise<void> {
|
||||
if (!isRequestFrame(msg)) return;
|
||||
const req = msg as RequestFrame;
|
||||
const requestSessionId = (req.params as { session_id?: unknown } | undefined)?.session_id;
|
||||
const startedAt = performance.now();
|
||||
this.diagnostics?.("dispatcher.rpc.received", {
|
||||
rpc_id: req.id,
|
||||
method: req.method,
|
||||
session_id: typeof requestSessionId === "string" ? requestSessionId : null,
|
||||
transport_state: this.transport.state,
|
||||
live_session_ids: this.sessions.list().map((ctx) => ctx.sessionId),
|
||||
inflight_rpc_ids: Array.from(this.inflightAbortControllers.keys()),
|
||||
});
|
||||
|
||||
// Cancel frames take a fast path: trip the matching controller
|
||||
// (if any), reply with `{cancelled}` so the daemon can answer
|
||||
@@ -200,6 +214,12 @@ export class ToolDispatcher {
|
||||
const params = (req.params as { rpc_id?: string } | undefined) ?? {};
|
||||
const target = typeof params.rpc_id === "string" ? params.rpc_id : "";
|
||||
const ac = target ? this.inflightAbortControllers.get(target) : undefined;
|
||||
this.diagnostics?.("dispatcher.cancel.received", {
|
||||
rpc_id: req.id,
|
||||
target_rpc_id: target,
|
||||
target_found: ac !== undefined,
|
||||
inflight_rpc_ids: Array.from(this.inflightAbortControllers.keys()),
|
||||
});
|
||||
if (ac) {
|
||||
try {
|
||||
ac.abort();
|
||||
@@ -213,7 +233,17 @@ export class ToolDispatcher {
|
||||
};
|
||||
try {
|
||||
this.transport.send(reply);
|
||||
this.diagnostics?.("dispatcher.cancel.ack_sent", {
|
||||
rpc_id: req.id,
|
||||
target_rpc_id: target,
|
||||
cancelled: ac !== undefined,
|
||||
});
|
||||
} catch (sendErr) {
|
||||
this.diagnostics?.("dispatcher.cancel.ack_failed", {
|
||||
rpc_id: req.id,
|
||||
target_rpc_id: target,
|
||||
error: sendErr,
|
||||
});
|
||||
console.warn("[bsk dispatcher] failed to ack cancel", sendErr);
|
||||
}
|
||||
return;
|
||||
@@ -238,6 +268,13 @@ export class ToolDispatcher {
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.diagnostics?.("dispatcher.rpc.invoke_failed", {
|
||||
rpc_id: req.id,
|
||||
method: req.method,
|
||||
session_id: typeof requestSessionId === "string" ? requestSessionId : null,
|
||||
abort_signal: ac.signal.aborted,
|
||||
error: err,
|
||||
});
|
||||
if (isAbortLikeError(err)) {
|
||||
body = {
|
||||
id: req.id,
|
||||
@@ -258,8 +295,27 @@ export class ToolDispatcher {
|
||||
let sent = true;
|
||||
try {
|
||||
this.transport.send(body);
|
||||
this.diagnostics?.("dispatcher.rpc.response_sent", {
|
||||
rpc_id: req.id,
|
||||
method: req.method,
|
||||
session_id: typeof requestSessionId === "string" ? requestSessionId : null,
|
||||
response_kind: "error" in body ? "error" : "ok",
|
||||
error_code: "error" in body ? body.error.code : null,
|
||||
elapsed_ms: Math.round(performance.now() - startedAt),
|
||||
transport_state: this.transport.state,
|
||||
live_session_ids: this.sessions.list().map((ctx) => ctx.sessionId),
|
||||
});
|
||||
} catch (sendErr) {
|
||||
sent = false;
|
||||
this.diagnostics?.("dispatcher.rpc.response_send_failed", {
|
||||
rpc_id: req.id,
|
||||
method: req.method,
|
||||
session_id: typeof requestSessionId === "string" ? requestSessionId : null,
|
||||
started_session_id: startedSession,
|
||||
elapsed_ms: Math.round(performance.now() - startedAt),
|
||||
transport_state: this.transport.state,
|
||||
error: sendErr,
|
||||
});
|
||||
// Transport is dead by the time we want to reply. Drop the link
|
||||
// proactively so the alarm-driven keepalive reconnects sooner
|
||||
// and the daemon's pending RPC times out cleanly instead of
|
||||
@@ -278,12 +334,23 @@ export class ToolDispatcher {
|
||||
try {
|
||||
const ctx = await this.sessions.stop(startedSession);
|
||||
if (ctx) {
|
||||
this.diagnostics?.("dispatcher.session_start.rolled_back", {
|
||||
rpc_id: req.id,
|
||||
session_id: startedSession,
|
||||
agent_window_id: ctx.agentWindowId,
|
||||
reason: "response_send_failed",
|
||||
});
|
||||
console.warn(
|
||||
"[bsk dispatcher] rolled back orphan session after send failure",
|
||||
startedSession,
|
||||
);
|
||||
}
|
||||
} catch (rollbackErr) {
|
||||
this.diagnostics?.("dispatcher.session_start.rollback_failed", {
|
||||
rpc_id: req.id,
|
||||
session_id: startedSession,
|
||||
error: rollbackErr,
|
||||
});
|
||||
console.warn("[bsk dispatcher] session rollback after send failure failed", rollbackErr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +106,14 @@ function isAbortLikeError(err: unknown): boolean {
|
||||
return err instanceof DOMException && err.name === "AbortError";
|
||||
}
|
||||
|
||||
function isInvalidCssSelectorError(err: unknown): boolean {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return (
|
||||
message.includes("DOM Error while querying") ||
|
||||
/invalid selector|not a valid selector|querySelector.*failed/i.test(message)
|
||||
);
|
||||
}
|
||||
|
||||
async function wait(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted) throw new DOMException("aborted", "AbortError");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -159,7 +167,7 @@ async function resolveBackendNode(
|
||||
};
|
||||
}
|
||||
if (hasRef) {
|
||||
const resolved = resolveSnapshotRef(ctx, params.ref as string, target.tabId, "interact");
|
||||
const resolved = resolveSnapshotRef(ctx, params.ref as string, target.tabId);
|
||||
if (isRpcError(resolved)) return resolved;
|
||||
return {
|
||||
backendNodeId: resolved.backendNodeId,
|
||||
@@ -208,6 +216,14 @@ async function resolveBackendNode(
|
||||
}
|
||||
return { backendNodeId, cdpTarget: { tabId: target.tabId }, usedSelector: params.selector };
|
||||
} catch (err) {
|
||||
if (isInvalidCssSelectorError(err)) {
|
||||
return rpcError(
|
||||
"invalid_params",
|
||||
"invalid_selector",
|
||||
`selector is not valid CSS: ${params.selector}`,
|
||||
{ selector: params.selector },
|
||||
);
|
||||
}
|
||||
return {
|
||||
code: "cdp_failed",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
applyVomInteractionRecovery,
|
||||
type CondSurface,
|
||||
isVomReferenceNode,
|
||||
type Rect,
|
||||
renderVom,
|
||||
type VomNode,
|
||||
type VomOptions,
|
||||
@@ -60,11 +59,6 @@ import {
|
||||
type CaptureVomObservationResult,
|
||||
projectRecordSafeObservation,
|
||||
} from "./vom/record-safe-observation";
|
||||
import {
|
||||
clusterRenderedSurfaces,
|
||||
discoverRenderedSurfaces,
|
||||
projectRenderedSurfaces,
|
||||
} from "./vom/rendered-surfaces";
|
||||
import {
|
||||
buildSemanticGraph,
|
||||
buildSemanticVomScene,
|
||||
@@ -96,9 +90,6 @@ 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.
|
||||
@@ -191,8 +182,6 @@ async function captureElementScreenshot(
|
||||
target: CdpTarget,
|
||||
backendNodeId: number,
|
||||
frameId?: string,
|
||||
visualSurface = false,
|
||||
observedVisibleRect?: Rect,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ image_base64: string; width: number; height: number } | RpcError> {
|
||||
if (signal?.aborted) return cancelled("screenshot");
|
||||
@@ -200,36 +189,11 @@ async function captureElementScreenshot(
|
||||
cdp,
|
||||
tabId,
|
||||
{ target, backendNodeId, ...(frameId ? { frameId } : {}) },
|
||||
{ scrollIntoView: !visualSurface },
|
||||
{ scrollIntoView: true },
|
||||
);
|
||||
if (isRpcError(geometry)) return geometry;
|
||||
if (signal?.aborted) return cancelled("screenshot");
|
||||
const liveRect = geometry.topBounds;
|
||||
const rect =
|
||||
visualSurface && observedVisibleRect
|
||||
? (() => {
|
||||
const x = Math.max(liveRect.x, observedVisibleRect.x);
|
||||
const y = Math.max(liveRect.y, observedVisibleRect.y);
|
||||
const right = Math.min(
|
||||
liveRect.x + liveRect.width,
|
||||
observedVisibleRect.x + observedVisibleRect.w,
|
||||
);
|
||||
const bottom = Math.min(
|
||||
liveRect.y + liveRect.height,
|
||||
observedVisibleRect.y + observedVisibleRect.h,
|
||||
);
|
||||
return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : null;
|
||||
})()
|
||||
: liveRect;
|
||||
if (!rect) return { code: "permission_denied", message: "surface is no longer visible" };
|
||||
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;
|
||||
const rect = geometry.topBounds;
|
||||
|
||||
try {
|
||||
const shot = await cdp.send<{ data?: string }>(tabId, "Page.captureScreenshot", {
|
||||
@@ -239,7 +203,7 @@ async function captureElementScreenshot(
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
scale,
|
||||
scale: 1,
|
||||
},
|
||||
});
|
||||
if (signal?.aborted) return cancelled("screenshot");
|
||||
@@ -346,7 +310,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, "screenshot");
|
||||
const node = resolveSnapshotRef(ctx, ref, target.tabId);
|
||||
if (isRpcError(node)) return node;
|
||||
if (signal?.aborted) return cancelled("screenshot");
|
||||
deps.cdp.trackSessionTab?.(ctx.sessionId, target.tabId);
|
||||
@@ -366,8 +330,6 @@ export async function handleScreenshot(
|
||||
nodeTarget,
|
||||
node.backendNodeId,
|
||||
node.frameId,
|
||||
node.kind === "surface",
|
||||
node.visibleRect,
|
||||
signal,
|
||||
),
|
||||
deps.sendToTab,
|
||||
@@ -1061,7 +1023,6 @@ async function captureForVom(
|
||||
|
||||
export interface CaptureVomObservationOptions extends VomOptions {
|
||||
conditionalSurfaceProbe?: boolean;
|
||||
renderedSurfaceDiscovery?: boolean;
|
||||
hoverProbeBypassOverlay?: (tabId: number, enabled: boolean) => Promise<void>;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
@@ -1103,20 +1064,7 @@ export async function captureVomObservation(
|
||||
),
|
||||
);
|
||||
const decoratedScene = attachCapturedSceneAnnotations(scene, normalizedDocuments, captured);
|
||||
const observedScene = options.renderedSurfaceDiscovery
|
||||
? projectRenderedSurfaces(
|
||||
decoratedScene,
|
||||
normalizedDocuments,
|
||||
clusterRenderedSurfaces(
|
||||
discoverRenderedSurfaces(
|
||||
normalizedDocuments,
|
||||
captured.viewport,
|
||||
captured.excludedBackendNodeIds,
|
||||
),
|
||||
),
|
||||
)
|
||||
: decoratedScene;
|
||||
const rendered = renderVom(observedScene, {
|
||||
const rendered = renderVom(decoratedScene, {
|
||||
maxDepth: options.maxDepth,
|
||||
maxTokens: options.maxTokens,
|
||||
redactValues: options.redactValues,
|
||||
@@ -1167,7 +1115,6 @@ async function handleVomObservation(
|
||||
maxTokens: params.max_tokens,
|
||||
activeRegionPolicy: true,
|
||||
conditionalSurfaceProbe: effectiveConditionalSurfaceProbe,
|
||||
renderedSurfaceDiscovery: toolName === "observe",
|
||||
hoverProbeBypassOverlay: deps.hoverProbeBypassOverlay,
|
||||
signal,
|
||||
});
|
||||
@@ -1185,9 +1132,6 @@ 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;
|
||||
}),
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
// 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, type RefCapability, type RefTargetKind } from "@/session-manager/ref-store";
|
||||
import { normaliseRef } from "@/session-manager/ref-store";
|
||||
import type { RpcError } from "@/transport/types";
|
||||
import { rpcError } from "./errors";
|
||||
|
||||
@@ -13,9 +12,6 @@ export interface SnapshotRefLookup {
|
||||
refKey: string;
|
||||
frameId?: string;
|
||||
cdpSessionId?: string;
|
||||
visibleRect?: Rect;
|
||||
kind: RefTargetKind;
|
||||
capabilities: RefCapability[];
|
||||
}
|
||||
|
||||
function refEntryForTab(ctx: SessionContext, refKey: string, tabId: number) {
|
||||
@@ -41,9 +37,6 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -56,7 +49,6 @@ export function resolveSnapshotRef(
|
||||
ctx: SessionContext,
|
||||
ref: string,
|
||||
tabId: number,
|
||||
requiredCapability?: RefCapability,
|
||||
): SnapshotRefLookup | RpcError {
|
||||
const looked = lookupSnapshotRef(ctx, ref, tabId);
|
||||
if (looked === null) {
|
||||
@@ -66,13 +58,5 @@ 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;
|
||||
}
|
||||
|
||||
@@ -722,44 +722,6 @@ 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) => {
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -11,15 +11,7 @@ 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",
|
||||
"overflow-x",
|
||||
"overflow-y",
|
||||
] as const;
|
||||
const REQUESTED_STYLES = ["position", "pointer-events", "cursor", "visibility", "opacity"] as const;
|
||||
const STYLE_COL = Object.fromEntries(
|
||||
REQUESTED_STYLES.map((name, index) => [name, index]),
|
||||
) as Record<(typeof REQUESTED_STYLES)[number], number>;
|
||||
@@ -47,10 +39,6 @@ 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
|
||||
@@ -808,8 +796,6 @@ 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 ?? []);
|
||||
@@ -835,7 +821,6 @@ 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];
|
||||
@@ -855,11 +840,7 @@ 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];
|
||||
@@ -882,19 +863,12 @@ 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.
|
||||
@@ -929,9 +903,6 @@ function parseDocumentNodes(
|
||||
position,
|
||||
pointerEvents,
|
||||
cursor,
|
||||
overflowX,
|
||||
overflowY,
|
||||
visuallySuppressed,
|
||||
rendered,
|
||||
textContent,
|
||||
...(formValue !== undefined ? { formValue } : {}),
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export { clusterRenderedSurfaces } from "./cluster";
|
||||
export { discoverRenderedSurfaces } from "./discovery";
|
||||
export { projectRenderedSurfaces } from "./project";
|
||||
export type { RenderedSurface, RenderedSurfaceGroup } from "./types";
|
||||
@@ -1,100 +0,0 @@
|
||||
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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -23,8 +23,8 @@ export type ErrorCode =
|
||||
export type RpcErrorReason =
|
||||
| "agent_window_scope"
|
||||
| "element_not_visible"
|
||||
| "ref_capability_denied"
|
||||
| "ref_not_found"
|
||||
| "invalid_selector"
|
||||
| "selector_not_found"
|
||||
| "target_not_fillable"
|
||||
| "target_not_select"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DiagnosticSink } from "@/lib/diagnostics";
|
||||
import type { ConnectionStateHandler, Disposable, FrameHandler, Transport } from "./transport";
|
||||
import type { ConnectionState, ProtocolFrame } from "./types";
|
||||
|
||||
@@ -18,6 +19,7 @@ export interface WSTransportOptions {
|
||||
* Inject a fake WebSocket constructor in tests; defaults to `globalThis.WebSocket`.
|
||||
*/
|
||||
webSocketFactory?: WebSocketFactory;
|
||||
diagnostics?: DiagnosticSink;
|
||||
}
|
||||
|
||||
interface CloseLikeEvent {
|
||||
@@ -44,6 +46,7 @@ export class WSTransport implements Transport {
|
||||
private readonly factory: WebSocketFactory;
|
||||
private readonly initialDelayMs: number;
|
||||
private readonly maxDelayMs: number;
|
||||
private readonly diagnostics?: DiagnosticSink;
|
||||
|
||||
private socket: WebSocket | null = null;
|
||||
private currentState: ConnectionState = "disconnected";
|
||||
@@ -63,6 +66,7 @@ export class WSTransport implements Transport {
|
||||
this.factory = options.webSocketFactory ?? ((url: string) => new WebSocket(url));
|
||||
this.initialDelayMs = options.reconnect?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
|
||||
this.maxDelayMs = options.reconnect?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
||||
this.diagnostics = options.diagnostics;
|
||||
}
|
||||
|
||||
get state(): ConnectionState {
|
||||
@@ -70,6 +74,13 @@ export class WSTransport implements Transport {
|
||||
}
|
||||
|
||||
connect(): Promise<void> {
|
||||
this.diagnostics?.("transport.connect.requested", {
|
||||
state: this.currentState,
|
||||
socket_generation: this.socketGeneration,
|
||||
has_socket: this.socket !== null,
|
||||
has_connecting_promise: this.connectingPromise !== null,
|
||||
has_reconnect_timer: this.reconnectTimer !== null,
|
||||
});
|
||||
if (this.currentState === "connected") return Promise.resolve();
|
||||
|
||||
this.explicitlyClosed = false;
|
||||
@@ -94,6 +105,11 @@ export class WSTransport implements Transport {
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.diagnostics?.("transport.disconnect.requested", {
|
||||
state: this.currentState,
|
||||
socket_generation: this.socketGeneration,
|
||||
has_socket: this.socket !== null,
|
||||
});
|
||||
this.explicitlyClosed = true;
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
@@ -124,6 +140,12 @@ export class WSTransport implements Transport {
|
||||
|
||||
send(msg: ProtocolFrame): void {
|
||||
if (!this.socket || this.socket.readyState !== 1 /* OPEN */) {
|
||||
this.diagnostics?.("transport.send.rejected", {
|
||||
state: this.currentState,
|
||||
socket_generation: this.socketGeneration,
|
||||
socket_ready_state: this.socket?.readyState ?? null,
|
||||
frame_kind: "method" in msg ? msg.method : "event" in msg ? msg.event : "response",
|
||||
});
|
||||
throw new Error("[WSTransport] cannot send while not connected");
|
||||
}
|
||||
this.socket.send(JSON.stringify(msg));
|
||||
@@ -152,10 +174,16 @@ export class WSTransport implements Transport {
|
||||
const generation = ++this.socketGeneration;
|
||||
const socket = this.factory(this.url);
|
||||
this.socket = socket;
|
||||
this.diagnostics?.("transport.socket.created", {
|
||||
socket_generation: generation,
|
||||
reconnect_attempt: this.reconnectAttempt,
|
||||
url: this.url,
|
||||
});
|
||||
|
||||
socket.addEventListener("open", () => {
|
||||
if (!this.isCurrentSocket(socket, generation)) return;
|
||||
this.reconnectAttempt = 0;
|
||||
this.diagnostics?.("transport.socket.open", { socket_generation: generation });
|
||||
this.setState("connected");
|
||||
const resolve = this.resolveConnect;
|
||||
this.resolveConnect = null;
|
||||
@@ -174,6 +202,7 @@ export class WSTransport implements Transport {
|
||||
});
|
||||
|
||||
socket.addEventListener("error", () => {
|
||||
this.diagnostics?.("transport.socket.error", { socket_generation: generation });
|
||||
// The 'close' handler always fires after 'error' in browsers, so we
|
||||
// just record the error and let close drive reconnect logic.
|
||||
});
|
||||
@@ -197,7 +226,16 @@ export class WSTransport implements Transport {
|
||||
}
|
||||
|
||||
private handleClose(socket: WebSocket, generation: number, _ev: CloseLikeEvent): void {
|
||||
if (!this.isCurrentSocket(socket, generation)) return;
|
||||
const isCurrent = this.isCurrentSocket(socket, generation);
|
||||
this.diagnostics?.("transport.socket.close", {
|
||||
socket_generation: generation,
|
||||
current_socket_generation: this.socketGeneration,
|
||||
is_current: isCurrent,
|
||||
explicitly_closed: this.explicitlyClosed,
|
||||
close_code: _ev.code ?? null,
|
||||
close_reason: _ev.reason ?? "",
|
||||
});
|
||||
if (!isCurrent) return;
|
||||
this.socket = null;
|
||||
if (this.explicitlyClosed) {
|
||||
this.setState("disconnected");
|
||||
@@ -211,9 +249,18 @@ export class WSTransport implements Transport {
|
||||
if (this.reconnectTimer) return;
|
||||
const delay = Math.min(this.initialDelayMs * 2 ** this.reconnectAttempt, this.maxDelayMs);
|
||||
this.reconnectAttempt += 1;
|
||||
this.diagnostics?.("transport.reconnect.scheduled", {
|
||||
delay_ms: delay,
|
||||
reconnect_attempt: this.reconnectAttempt,
|
||||
socket_generation: this.socketGeneration,
|
||||
});
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
if (this.explicitlyClosed) return;
|
||||
this.diagnostics?.("transport.reconnect.timer_fired", {
|
||||
reconnect_attempt: this.reconnectAttempt,
|
||||
socket_generation: this.socketGeneration,
|
||||
});
|
||||
void this.connect().catch((err) => {
|
||||
console.debug("[WSTransport] reconnect attempt failed", err);
|
||||
});
|
||||
@@ -226,7 +273,13 @@ export class WSTransport implements Transport {
|
||||
|
||||
private setState(next: ConnectionState): void {
|
||||
if (this.currentState === next) return;
|
||||
const previous = this.currentState;
|
||||
this.currentState = next;
|
||||
this.diagnostics?.("transport.state.changed", {
|
||||
previous,
|
||||
next,
|
||||
socket_generation: this.socketGeneration,
|
||||
});
|
||||
for (const h of this.stateHandlers) {
|
||||
try {
|
||||
h(next);
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
# 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.
|
||||
|
||||
### `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.
|
||||
|
||||
### `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.
|
||||
@@ -1,46 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,28 +0,0 @@
|
||||
<!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; }
|
||||
</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("nested") === "1") {
|
||||
const iframe = document.createElement("iframe");
|
||||
iframe.title = "nested fixture frame";
|
||||
iframe.src = "frame.html?label=fixture-nested-frame";
|
||||
document.body.append(iframe);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,22 +0,0 @@
|
||||
<!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"></iframe>
|
||||
<iframe title="cross-origin fixture" src="http://localhost:4173/frame.html?label=fixture-cross-origin-frame"></iframe>
|
||||
<iframe title="nested fixture" src="frame.html?canvas=0&nested=1"></iframe>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,118 +0,0 @@
|
||||
<!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>
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,22 +0,0 @@
|
||||
<!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>
|
||||
|
||||
@@ -22,7 +22,8 @@ export default defineConfig({
|
||||
outDir: "dist",
|
||||
modules: ["@wxt-dev/module-react"],
|
||||
manifest: {
|
||||
name: "BrowserSkill",
|
||||
name: "BrowserSkill (Lumi Diagnostics)",
|
||||
version_name: `${EXTENSION_VERSION}-lumi-session-loss-v2`,
|
||||
description:
|
||||
"Let AI agents use your logged-in browser in a separate Agent Window—without interrupting your work. Powered by the bsk CLI.",
|
||||
// Flat debugger sessions are required to address out-of-process iframes.
|
||||
@@ -45,7 +46,7 @@ export default defineConfig({
|
||||
128: "icon/logo.png",
|
||||
},
|
||||
action: {
|
||||
default_title: "BrowserSkill",
|
||||
default_title: "BrowserSkill (Lumi Diagnostics)",
|
||||
default_icon: {
|
||||
16: "icon/logo.png",
|
||||
32: "icon/logo.png",
|
||||
|
||||
@@ -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/**",
|
||||
|
||||
@@ -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
|
||||
@@ -80,8 +80,6 @@ Prefer `@eN` refs from the latest snapshot over raw CSS selectors. Use `--ref` /
|
||||
|
||||
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; ...]`, the ref identifies a rendered canvas surface, not an interactable DOM control. Use `bsk screenshot --ref @eN --session <id>` to inspect its visible crop. Do not pass a visual surface ref to click, fill, hover, or select; those commands intentionally reject screenshot-only refs.
|
||||
|
||||
## 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:
|
||||
@@ -212,7 +210,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`) |
|
||||
|
||||
@@ -296,12 +294,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`.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -497,4 +497,21 @@ mod tests {
|
||||
.contains("CSS selector")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_selector_explains_css_contract_in_json() {
|
||||
let cli = CliError::from_rpc(RpcError {
|
||||
code: ErrorCode::InvalidParams,
|
||||
message: "selector is not valid CSS: text=submit".into(),
|
||||
data: Some(serde_json::json!({ "reason": "invalid_selector" })),
|
||||
});
|
||||
let exit = cli.exit_code();
|
||||
let hint = hint_for(&cli, render_info_for(&cli).as_ref());
|
||||
let json = json_error_string(&cli, exit, hint);
|
||||
let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
|
||||
let hint = parsed.get("hint").and_then(|v| v.as_str()).unwrap();
|
||||
assert!(hint.contains("CSS selector"));
|
||||
assert!(hint.contains("text="));
|
||||
assert!(hint.contains("@eN"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,8 +40,8 @@ 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 INVALID_SELECTOR: &str = "invalid_selector";
|
||||
pub const SELECTOR_NOT_FOUND: &str = "selector_not_found";
|
||||
pub const TARGET_NOT_FILLABLE: &str = "target_not_fillable";
|
||||
pub const TARGET_NOT_SELECT: &str = "target_not_select";
|
||||
@@ -222,6 +222,13 @@ pub fn info_for_error(code: ErrorCode, data: Option<&serde_json::Value>) -> Rend
|
||||
hint: Some("verify the CSS selector or wait for the element to appear before retrying"),
|
||||
exit_code: base.exit_code,
|
||||
},
|
||||
(ErrorCode::InvalidParams, reason::INVALID_SELECTOR) => RenderInfo {
|
||||
summary: "selector is not valid CSS",
|
||||
hint: Some(
|
||||
"use a standard CSS selector or a fresh @eN ref; Playwright text= selectors and XPath are not supported",
|
||||
),
|
||||
exit_code: base.exit_code,
|
||||
},
|
||||
(ErrorCode::InvalidParams, reason::TARGET_NOT_FILLABLE) => RenderInfo {
|
||||
summary: "target element is not fillable",
|
||||
hint: Some(
|
||||
@@ -229,13 +236,6 @@ pub fn info_for_error(code: ErrorCode, data: Option<&serde_json::Value>) -> Rend
|
||||
),
|
||||
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 are screenshot-only; run `bsk screenshot --ref <ref> --session <id>`",
|
||||
),
|
||||
exit_code: base.exit_code,
|
||||
},
|
||||
(ErrorCode::InvalidParams, reason::TARGET_NOT_SELECT) => RenderInfo {
|
||||
summary: "target element is not a <select>",
|
||||
hint: Some(
|
||||
@@ -385,18 +385,6 @@ 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("screenshot-only"),
|
||||
"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 });
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -223,6 +223,14 @@ impl BrowserRegistry {
|
||||
"browser reconnect: replacing previous registration"
|
||||
);
|
||||
}
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "browser.registry.insert",
|
||||
id = %client.id,
|
||||
generation = client.generation,
|
||||
previous_generation = guard.get(&client.id).map(|previous| previous.generation),
|
||||
"diagnostic browser registry mutation"
|
||||
);
|
||||
guard.insert(client.id.clone(), client);
|
||||
}
|
||||
|
||||
@@ -239,16 +247,31 @@ impl BrowserRegistry {
|
||||
/// took over the same `id` while the old socket was tearing down
|
||||
/// (review M4/M5 round 2 Important #1). Returns the removed entry
|
||||
/// when a removal actually happened.
|
||||
#[track_caller]
|
||||
pub fn remove_if_generation_matches(
|
||||
&self,
|
||||
id: &BrowserId,
|
||||
generation: u64,
|
||||
) -> Option<std::sync::Arc<BrowserClient>> {
|
||||
let caller = std::panic::Location::caller();
|
||||
let mut guard = self.inner.lock().expect("browser registry poisoned");
|
||||
match guard.get(id) {
|
||||
let current_generation = guard.get(id).map(|current| current.generation);
|
||||
let removed = match guard.get(id) {
|
||||
Some(current) if current.generation == generation => guard.remove(id),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "browser.registry.remove_if_generation_matches",
|
||||
id = %id,
|
||||
requested_generation = generation,
|
||||
?current_generation,
|
||||
removed = removed.is_some(),
|
||||
caller_file = caller.file(),
|
||||
caller_line = caller.line(),
|
||||
"diagnostic browser registry mutation"
|
||||
);
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn get(&self, id: &BrowserId) -> Option<std::sync::Arc<BrowserClient>> {
|
||||
|
||||
@@ -37,7 +37,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::{debug, warn};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::abort::AbortRegistry;
|
||||
use super::queue::{DEFAULT_TOOL_TIMEOUT, DispatchError};
|
||||
@@ -197,7 +197,22 @@ pub fn full_handler(status: DaemonStatus, state: Arc<DaemonState>) -> RpcHandler
|
||||
let status = status.clone();
|
||||
let state = Arc::clone(&state);
|
||||
Box::pin(async move {
|
||||
match method {
|
||||
let method_name = format!("{method:?}");
|
||||
let diagnostic_rpc_id = rpc_id.clone();
|
||||
let session_id = params
|
||||
.get("session_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
let started = Instant::now();
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "ipc.rpc.started",
|
||||
rpc_id = %diagnostic_rpc_id,
|
||||
method = %method_name,
|
||||
session = session_id.as_deref().unwrap_or(""),
|
||||
"diagnostic IPC RPC"
|
||||
);
|
||||
let body = match method {
|
||||
Method::SystemPing => {
|
||||
let result = PingResult { pong: true };
|
||||
ResponseBody::Ok(serde_json::to_value(result).unwrap_or(Value::Null))
|
||||
@@ -261,7 +276,23 @@ pub fn full_handler(status: DaemonStatus, state: Arc<DaemonState>) -> RpcHandler
|
||||
message: format!("method not implemented yet: {other:?}"),
|
||||
data: None,
|
||||
}),
|
||||
}
|
||||
};
|
||||
let (outcome, error_code) = match &body {
|
||||
ResponseBody::Ok(_) => ("ok", String::new()),
|
||||
ResponseBody::Err(error) => ("error", format!("{:?}", error.code)),
|
||||
};
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "ipc.rpc.completed",
|
||||
rpc_id = %diagnostic_rpc_id,
|
||||
method = %method_name,
|
||||
session = session_id.as_deref().unwrap_or(""),
|
||||
outcome,
|
||||
error_code = %error_code,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"diagnostic IPC RPC"
|
||||
);
|
||||
body
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -465,8 +496,14 @@ fn handle_cancel(state: &Arc<DaemonState>, params: Value) -> ResponseBody {
|
||||
};
|
||||
let local = state.abort_registry.cancel(¶ms.rpc_id);
|
||||
let mut cancelled = local;
|
||||
let mut surface = if local { "abort_registry" } else { "none" };
|
||||
if !local && let Some(snap) = state.tool_inflight.cancel(¶ms.rpc_id) {
|
||||
cancelled = true;
|
||||
surface = if snap.ws_rpc_id.is_some() {
|
||||
"tool_inflight_forwarded"
|
||||
} else {
|
||||
"tool_inflight_queued"
|
||||
};
|
||||
// Forward the WS-side cancel only when the worker has
|
||||
// already promoted the entry to "forwarded"; queued entries
|
||||
// short-circuit on their own pre-flight without ever
|
||||
@@ -484,6 +521,14 @@ fn handle_cancel(state: &Arc<DaemonState>, params: Value) -> ResponseBody {
|
||||
);
|
||||
}
|
||||
}
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "ipc.cancel.resolved",
|
||||
target_rpc_id = %params.rpc_id,
|
||||
cancelled,
|
||||
surface,
|
||||
"diagnostic IPC cancellation"
|
||||
);
|
||||
ResponseBody::Ok(serde_json::to_value(CancelResult { cancelled }).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ use bsk_protocol::{ErrorCode, Frame, Method, RequestFrame, ResponseBody, RpcErro
|
||||
use rand::Rng;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{debug, warn};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::abort::AbortToken;
|
||||
use super::browsers::BrowserRegistry;
|
||||
@@ -515,6 +515,16 @@ async fn forward_one(
|
||||
sessions: &Arc<SessionRegistry>,
|
||||
job: &ToolJob,
|
||||
) -> Result<Value, RpcError> {
|
||||
let started = std::time::Instant::now();
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "tool.dispatch.started",
|
||||
session = %sid,
|
||||
method = ?job.method,
|
||||
has_inflight = job.inflight.is_some(),
|
||||
has_lifecycle_cancel = job.lifecycle_cancel.is_some(),
|
||||
"diagnostic tool dispatch"
|
||||
);
|
||||
// Pre-flight: a cancel that landed while this job was still in
|
||||
// the per-session channel must short-circuit before any session
|
||||
// / browser resolution work, and before any WS frame leaves the
|
||||
@@ -535,6 +545,13 @@ async fn forward_one(
|
||||
));
|
||||
}
|
||||
let Some(session) = sessions.get(sid) else {
|
||||
warn!(
|
||||
diagnostic = true,
|
||||
event = "tool.dispatch.session_missing",
|
||||
session = %sid,
|
||||
method = ?job.method,
|
||||
"diagnostic tool dispatch"
|
||||
);
|
||||
return Err(RpcError {
|
||||
code: ErrorCode::NotFound,
|
||||
message: format!("session {sid} no longer exists"),
|
||||
@@ -542,6 +559,14 @@ async fn forward_one(
|
||||
});
|
||||
};
|
||||
let Some(client) = browsers.get(&session.browser_id) else {
|
||||
warn!(
|
||||
diagnostic = true,
|
||||
event = "tool.dispatch.browser_missing",
|
||||
session = %sid,
|
||||
method = ?job.method,
|
||||
browser = %session.browser_id,
|
||||
"diagnostic tool dispatch"
|
||||
);
|
||||
return Err(RpcError {
|
||||
code: ErrorCode::NotFound,
|
||||
message: "owning browser is no longer connected".into(),
|
||||
@@ -558,6 +583,16 @@ async fn forward_one(
|
||||
method: job.method.clone(),
|
||||
params: Some(job.params.clone()),
|
||||
});
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "tool.dispatch.forwarding",
|
||||
session = %sid,
|
||||
method = ?job.method,
|
||||
browser = %session.browser_id,
|
||||
browser_generation = client.generation,
|
||||
ws_rpc_id = %rpc_id,
|
||||
"diagnostic tool dispatch"
|
||||
);
|
||||
// Promote the inflight entry to "forwarded" AND push the WS
|
||||
// request frame to the sink inside the same critical section
|
||||
// (review round 2 C1). The closure runs while the entry's inner
|
||||
@@ -717,6 +752,18 @@ async fn forward_one(
|
||||
});
|
||||
}
|
||||
};
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "tool.dispatch.response",
|
||||
session = %sid,
|
||||
method = ?job.method,
|
||||
browser = %session.browser_id,
|
||||
browser_generation = client.generation,
|
||||
ws_rpc_id = %rpc_id,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
response_is_error = matches!(&response.body, ResponseBody::Err(_)),
|
||||
"diagnostic tool dispatch"
|
||||
);
|
||||
match response.body {
|
||||
ResponseBody::Ok(v) => Ok(v),
|
||||
ResponseBody::Err(err) => Err(err),
|
||||
|
||||
@@ -105,12 +105,22 @@ impl SessionRegistry {
|
||||
|
||||
pub fn insert(&self, session: Session) {
|
||||
let session_id = session.id.clone();
|
||||
let browser_id = session.browser_id.clone();
|
||||
let agent_window_id = session.agent_window_id;
|
||||
let mut sessions = self.inner.lock().expect("session registry poisoned");
|
||||
sessions.insert(session_id.clone(), session);
|
||||
self.last_activity
|
||||
.lock()
|
||||
.expect("session activity registry poisoned")
|
||||
.insert(session_id, Instant::now());
|
||||
.insert(session_id.clone(), Instant::now());
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.insert",
|
||||
session = %session_id,
|
||||
browser = %browser_id,
|
||||
?agent_window_id,
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
}
|
||||
|
||||
/// Reserve a fresh, collision-free [`SessionId`] under the registry
|
||||
@@ -152,6 +162,13 @@ impl SessionRegistry {
|
||||
.lock()
|
||||
.expect("session activity registry poisoned")
|
||||
.insert(candidate.clone(), Instant::now());
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.reserve",
|
||||
session = %candidate,
|
||||
browser = %browser_id,
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
return Some(candidate);
|
||||
}
|
||||
None
|
||||
@@ -169,13 +186,24 @@ impl SessionRegistry {
|
||||
let mut guard = self.inner.lock().expect("session registry poisoned");
|
||||
let session = guard.get_mut(session_id)?;
|
||||
session.agent_window_id = agent_window_id;
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.commit",
|
||||
session = %session_id,
|
||||
browser = %session.browser_id,
|
||||
?agent_window_id,
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
Some(session.clone())
|
||||
}
|
||||
|
||||
/// Drop a placeholder reservation, used on extension error/timeout
|
||||
/// paths so failed reservations do not accumulate.
|
||||
#[track_caller]
|
||||
pub fn cancel_reservation(&self, session_id: &SessionId) {
|
||||
self.inner
|
||||
let caller = std::panic::Location::caller();
|
||||
let removed = self
|
||||
.inner
|
||||
.lock()
|
||||
.expect("session registry poisoned")
|
||||
.remove(session_id);
|
||||
@@ -183,9 +211,20 @@ impl SessionRegistry {
|
||||
.lock()
|
||||
.expect("session activity registry poisoned")
|
||||
.remove(session_id);
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.cancel_reservation",
|
||||
session = %session_id,
|
||||
existed = removed.is_some(),
|
||||
caller_file = caller.file(),
|
||||
caller_line = caller.line(),
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn remove(&self, id: &SessionId) -> Option<Session> {
|
||||
let caller = std::panic::Location::caller();
|
||||
let removed = self
|
||||
.inner
|
||||
.lock()
|
||||
@@ -195,6 +234,17 @@ impl SessionRegistry {
|
||||
.lock()
|
||||
.expect("session activity registry poisoned")
|
||||
.remove(id);
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.remove",
|
||||
session = %id,
|
||||
existed = removed.is_some(),
|
||||
browser = removed.as_ref().map(|session| session.browser_id.0.as_str()),
|
||||
agent_window_id = removed.as_ref().and_then(|session| session.agent_window_id),
|
||||
caller_file = caller.file(),
|
||||
caller_line = caller.line(),
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
removed
|
||||
}
|
||||
|
||||
@@ -243,7 +293,9 @@ impl SessionRegistry {
|
||||
}
|
||||
|
||||
/// Drop all sessions owned by `browser_id` (e.g. on disconnect).
|
||||
#[track_caller]
|
||||
pub fn purge_browser(&self, browser_id: &BrowserId) -> Vec<Session> {
|
||||
let caller = std::panic::Location::caller();
|
||||
let mut guard = self.inner.lock().expect("session registry poisoned");
|
||||
let drained: Vec<Session> = guard
|
||||
.values()
|
||||
@@ -260,6 +312,20 @@ impl SessionRegistry {
|
||||
for session in &drained {
|
||||
activity.remove(&session.id);
|
||||
}
|
||||
let session_ids: Vec<&str> = drained
|
||||
.iter()
|
||||
.map(|session| session.id.0.as_str())
|
||||
.collect();
|
||||
tracing::info!(
|
||||
diagnostic = true,
|
||||
event = "session.registry.purge_browser",
|
||||
browser = %browser_id,
|
||||
sessions = ?session_ids,
|
||||
count = drained.len(),
|
||||
caller_file = caller.file(),
|
||||
caller_line = caller.line(),
|
||||
"diagnostic session registry mutation"
|
||||
);
|
||||
drained
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ pub(crate) const DAEMONIZED_ENV: &str = "BSK_DAEMONIZED";
|
||||
/// daemon lock, IPC socket, and WS port — before taking over.
|
||||
pub(crate) const DAEMON_REPLACEMENT_WAIT_ENV: &str = "BSK_DAEMON_REPLACES_PID";
|
||||
|
||||
const LUMI_DIAGNOSTIC_BUILD: &str = "lumi-session-loss-v2";
|
||||
|
||||
/// Concrete daemon configuration resolved from CLI flags / defaults.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DaemonConfig {
|
||||
@@ -251,6 +253,7 @@ pub fn run_foreground(cfg: DaemonConfig) -> Result<()> {
|
||||
pid = info.pid,
|
||||
ws_port = info.ws_port,
|
||||
sock = %sock_path.display(),
|
||||
diagnostic_build = LUMI_DIAGNOSTIC_BUILD,
|
||||
"daemon ready"
|
||||
);
|
||||
|
||||
@@ -588,7 +591,9 @@ pub(crate) fn spawn_update_check_task(
|
||||
// The session gate is read after the fetch, as late
|
||||
// as possible before the binary gets replaced.
|
||||
let active_sessions = state.sessions.len();
|
||||
let auto_update = update::auto_update_enabled() && exe_path.is_some();
|
||||
// Keep this local diagnostic build in place until a
|
||||
// reproduction has uploaded its extension-side evidence.
|
||||
let auto_update = false;
|
||||
update::auto_update_step(
|
||||
candidate.as_ref(),
|
||||
auto_update,
|
||||
@@ -732,7 +737,11 @@ fn init_tracing() -> Option<tracing_appender::non_blocking::WorkerGuard> {
|
||||
use tracing_subscriber::prelude::*;
|
||||
|
||||
let log_dir = paths::log_dir().ok();
|
||||
let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
let env_filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("info"))
|
||||
// Lumi commonly runs with RUST_LOG=warn. This local build must retain
|
||||
// BrowserSkill's INFO diagnostics even under that host-wide setting.
|
||||
.add_directive("bsk=info".parse().expect("valid diagnostic log directive"));
|
||||
|
||||
let (file_layer, guard) = if let Some(dir) = log_dir {
|
||||
let appender = tracing_appender::rolling::daily(&dir, "daemon.log");
|
||||
|
||||
@@ -233,6 +233,14 @@ async fn drive_connection(
|
||||
.ok_or_else(|| anyhow!("handshake missing params"))?;
|
||||
let params: HandshakeParams = serde_json::from_value(params_raw)
|
||||
.map_err(|err| anyhow!("invalid HandshakeParams: {err}"))?;
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "browser.handshake.received",
|
||||
browser = %params.instance_id,
|
||||
extension_version = %params.version,
|
||||
extension_protocol = %params.protocol_version,
|
||||
"diagnostic browser handshake"
|
||||
);
|
||||
|
||||
// Version compatibility (design §10, M10.4): protocol_version only.
|
||||
let our_app_version: Version = env!("CARGO_PKG_VERSION")
|
||||
@@ -350,7 +358,7 @@ async fn drive_connection(
|
||||
// Pump loop: outbound frames from sink → ws; inbound from ws → resolve.
|
||||
let pump_state = Arc::clone(&state);
|
||||
let pump_browser = Arc::clone(&client);
|
||||
let result_outcome: anyhow::Result<()> = async {
|
||||
let result_outcome: anyhow::Result<String> = async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
outbound = rx.recv() => {
|
||||
@@ -359,7 +367,7 @@ async fn drive_connection(
|
||||
let json = serde_json::to_string(&frame)?;
|
||||
writer.send(Message::Text(json)).await?;
|
||||
}
|
||||
None => break,
|
||||
None => break Ok("outbound_channel_closed".to_string()),
|
||||
}
|
||||
}
|
||||
msg = reader.next() => {
|
||||
@@ -381,18 +389,37 @@ async fn drive_connection(
|
||||
pump_browser.touch();
|
||||
}
|
||||
Some(Ok(Message::Frame(_))) => {}
|
||||
Some(Ok(Message::Close(_))) | None => break,
|
||||
Some(Ok(Message::Close(frame))) => {
|
||||
let reason = frame
|
||||
.map(|frame| format!("peer_close code={:?} reason={}", frame.code, frame.reason))
|
||||
.unwrap_or_else(|| "peer_close_without_frame".to_string());
|
||||
break Ok(reason);
|
||||
}
|
||||
None => break Ok("peer_eof".to_string()),
|
||||
Some(Err(err)) => {
|
||||
warn!(%err, "ws read error");
|
||||
break;
|
||||
break Ok(format!("read_error: {err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
let pump_exit_reason = match &result_outcome {
|
||||
Ok(reason) => reason.clone(),
|
||||
Err(err) => format!("pump_error: {err:#}"),
|
||||
};
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "browser.websocket.pump_exit",
|
||||
id = %browser_id,
|
||||
generation,
|
||||
reason = %pump_exit_reason,
|
||||
last_seen_idle_ms = client.idle_for().as_millis() as u64,
|
||||
session_ids = ?state.sessions.ids_for_browser(&browser_id),
|
||||
"diagnostic browser websocket exit"
|
||||
);
|
||||
|
||||
// Cleanup: drop browser + purge its sessions, but only if the
|
||||
// registry still holds *this* generation. If a reconnect already
|
||||
@@ -416,7 +443,7 @@ async fn drive_connection(
|
||||
"browser disconnected; newer reconnect already owns this id, leaving sessions intact"
|
||||
);
|
||||
}
|
||||
result_outcome
|
||||
result_outcome.map(|_| ())
|
||||
}
|
||||
|
||||
async fn handle_inbound_text(state: &Arc<DaemonState>, client: &Arc<BrowserClient>, text: &str) {
|
||||
@@ -442,6 +469,38 @@ async fn handle_inbound_text(state: &Arc<DaemonState>, client: &Arc<BrowserClien
|
||||
client.mark_heartbeat_seen();
|
||||
debug!(id = %client.id, "heartbeat");
|
||||
}
|
||||
bsk_protocol::EventKind::BrowserDiagnostic => {
|
||||
let entries = ev.payload.get("entries").and_then(|value| value.as_array());
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "extension.diagnostic.batch",
|
||||
browser = %client.id,
|
||||
generation = client.generation,
|
||||
worker_boot_id = ev.payload.get("worker_boot_id").and_then(|value| value.as_str()).unwrap_or("unknown"),
|
||||
count = entries.map_or(0, Vec::len),
|
||||
"received extension diagnostic batch"
|
||||
);
|
||||
if let Some(entries) = entries {
|
||||
for entry in entries {
|
||||
info!(
|
||||
diagnostic = true,
|
||||
event = "extension.diagnostic.entry",
|
||||
browser = %client.id,
|
||||
generation = client.generation,
|
||||
entry = %entry,
|
||||
"extension diagnostic"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
warn!(
|
||||
diagnostic = true,
|
||||
event = "extension.diagnostic.invalid",
|
||||
browser = %client.id,
|
||||
payload = %ev.payload,
|
||||
"extension diagnostic payload missing entries"
|
||||
);
|
||||
}
|
||||
}
|
||||
bsk_protocol::EventKind::SessionWindowClosed => {
|
||||
handle_session_window_closed(state, &client.id, &ev.payload);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,10 @@ pub enum EventKind {
|
||||
BrowserDisconnected,
|
||||
#[serde(rename = "browser.connected")]
|
||||
BrowserConnected,
|
||||
/// Structured diagnostics emitted by locally instrumented extension
|
||||
/// builds. Production peers may ignore this event safely.
|
||||
#[serde(rename = "browser.diagnostic")]
|
||||
BrowserDiagnostic,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -256,6 +260,27 @@ mod tests {
|
||||
assert_eq!(frame.event, EventKind::SystemHeartbeat);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_diagnostic_event_frame_round_trips_from_extension_shape() {
|
||||
let wire = serde_json::json!({
|
||||
"event": "browser.diagnostic",
|
||||
"payload": {
|
||||
"schema_version": 1,
|
||||
"worker_boot_id": "worker-1",
|
||||
"entries": [{ "event": "extension.worker.started" }]
|
||||
}
|
||||
});
|
||||
let frame: EventFrame = serde_json::from_value(wire).unwrap();
|
||||
assert_eq!(frame.event, EventKind::BrowserDiagnostic);
|
||||
assert_eq!(
|
||||
frame
|
||||
.payload
|
||||
.get("worker_boot_id")
|
||||
.and_then(|value| value.as_str()),
|
||||
Some("worker-1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_user_interrupt_serialises_as_snake_case() {
|
||||
let v = serde_json::to_value(EventKind::SessionUserInterrupt).unwrap();
|
||||
|
||||
@@ -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.
|
||||
@@ -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,避免默认测试具有破坏性或不确定性。
|
||||
@@ -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_-]+"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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}" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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" }
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
```
|
||||
@@ -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"); });`,
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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 }),
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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}`);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
const stylesheet = `
|
||||
:root { color-scheme: light; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
|
||||
body { margin: 0; background: #f4f7fb; color: #182033; }
|
||||
main { width: min(760px, calc(100% - 40px)); margin: 48px auto; }
|
||||
.card { background: white; border: 1px solid #d9e1ef; border-radius: 14px; padding: 24px; box-shadow: 0 8px 28px #20304a12; }
|
||||
h1 { margin-top: 0; }
|
||||
a, button { font: inherit; }
|
||||
button, .button { display: inline-block; border: 0; border-radius: 8px; padding: 10px 16px; background: #3157d5; color: white; cursor: pointer; text-decoration: none; }
|
||||
label { display: block; margin: 16px 0; font-weight: 600; }
|
||||
input, textarea, select { display: block; box-sizing: border-box; width: 100%; margin-top: 6px; border: 1px solid #9caac2; border-radius: 7px; padding: 9px; font: inherit; }
|
||||
textarea { min-height: 90px; }
|
||||
.marker { border-left: 4px solid #3157d5; padding: 8px 12px; background: #eef2ff; font-family: ui-monospace, monospace; }
|
||||
.muted { color: #5c667a; }
|
||||
#account-menu { position: relative; display: inline-block; padding-bottom: 12px; }
|
||||
#hover-panel { display: none; position: absolute; z-index: 2; top: 34px; left: 0; width: 190px; padding: 10px; background: white; border: 1px solid #9caac2; border-radius: 8px; box-shadow: 0 8px 24px #20304a22; }
|
||||
#account-menu:hover #hover-panel, #account-menu.open #hover-panel { display: block; }
|
||||
#hover-panel button { width: 100%; }
|
||||
#inspect-card { margin-top: 80px; }
|
||||
code { font-family: ui-monospace, monospace; }
|
||||
`;
|
||||
|
||||
const clientScript = `
|
||||
(() => {
|
||||
const runId = new URLSearchParams(location.search).get("run");
|
||||
const navigation = performance.getEntriesByType("navigation")[0];
|
||||
const send = (type, data = {}) => {
|
||||
if (!runId) return Promise.resolve();
|
||||
return fetch("/api/events", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ runId, type, path: location.pathname, data }),
|
||||
keepalive: true,
|
||||
}).catch(() => undefined);
|
||||
};
|
||||
window.browserEval = { runId, send };
|
||||
window.addEventListener("pageshow", (event) => {
|
||||
send("page.shown", {
|
||||
path: location.pathname,
|
||||
persisted: event.persisted,
|
||||
navigationType: navigation?.type ?? "unknown",
|
||||
});
|
||||
});
|
||||
})();
|
||||
`;
|
||||
|
||||
export function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
export function withRun(path, runId, extra = {}) {
|
||||
const url = new URL(path, "http://browser-eval.local");
|
||||
url.searchParams.set("run", runId);
|
||||
for (const [name, value] of Object.entries(extra)) {
|
||||
if (value !== undefined) url.searchParams.set(name, String(value));
|
||||
}
|
||||
return `${url.pathname}${url.search}`;
|
||||
}
|
||||
|
||||
export function page({ title, body, script = "" }) {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>${escapeHtml(title)}</title>
|
||||
<style>${stylesheet}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>${body}</main>
|
||||
<script>${clientScript}</script>
|
||||
${script ? `<script>${script}</script>` : ""}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export const OPERATION_CATALOG = [
|
||||
{ operation: "session.start" },
|
||||
{ operation: "session.stop" },
|
||||
{ operation: "session.list" },
|
||||
{ operation: "page.navigate" },
|
||||
{ operation: "page.back" },
|
||||
{ operation: "page.forward" },
|
||||
{ operation: "page.reload" },
|
||||
{ operation: "page.wait" },
|
||||
{ operation: "inspect.observe" },
|
||||
{ operation: "inspect.snapshot" },
|
||||
{ operation: "inspect.html" },
|
||||
{ operation: "inspect.screenshot" },
|
||||
{ operation: "inspect.console" },
|
||||
{ operation: "inspect.network" },
|
||||
{ operation: "interact.click" },
|
||||
{ operation: "interact.hover" },
|
||||
{ operation: "interact.fill" },
|
||||
{ operation: "interact.select" },
|
||||
{ operation: "interact.press" },
|
||||
{ operation: "tabs.list" },
|
||||
{ operation: "tabs.create" },
|
||||
{ operation: "tabs.select" },
|
||||
{ operation: "tabs.close" },
|
||||
{
|
||||
operation: "tabs.borrow",
|
||||
manualNote: "requires an existing user tab and ownership confirmation",
|
||||
},
|
||||
{ operation: "tabs.return", manualNote: "paired with borrowing a real user tab" },
|
||||
{ operation: "assist.resize" },
|
||||
{ operation: "assist.emulate" },
|
||||
{ operation: "assist.request-help", manualNote: "intentionally waits for human interaction" },
|
||||
];
|
||||
|
||||
export const WORKFLOW_ACTION_OPERATIONS = {
|
||||
navigate: "page.navigate",
|
||||
back: "page.back",
|
||||
forward: "page.forward",
|
||||
reload: "page.reload",
|
||||
wait: "page.wait",
|
||||
observe: "inspect.observe",
|
||||
snapshot: "inspect.snapshot",
|
||||
html: "inspect.html",
|
||||
screenshot: "inspect.screenshot",
|
||||
console: "inspect.console",
|
||||
network: "inspect.network",
|
||||
click: "interact.click",
|
||||
hover: "interact.hover",
|
||||
fill: "interact.fill",
|
||||
select: "interact.select",
|
||||
press: "interact.press",
|
||||
"tab-list": "tabs.list",
|
||||
"tab-create": "tabs.create",
|
||||
"tab-select": "tabs.select",
|
||||
"tab-close": "tabs.close",
|
||||
borrow: "tabs.borrow",
|
||||
return: "tabs.return",
|
||||
resize: "assist.resize",
|
||||
emulate: "assist.emulate",
|
||||
"request-help": "assist.request-help",
|
||||
};
|
||||
|
||||
export const WORKFLOW_ACTIONS = new Set([
|
||||
...Object.keys(WORKFLOW_ACTION_OPERATIONS),
|
||||
"wait-site-event",
|
||||
]);
|
||||
|
||||
export const OPERATION_NAMES = new Set(OPERATION_CATALOG.map(({ operation }) => operation));
|
||||
@@ -0,0 +1,63 @@
|
||||
function readPath(value, path) {
|
||||
return path.split(".").reduce((current, part) => current?.[part], value);
|
||||
}
|
||||
|
||||
function eventMatches(event, assertion) {
|
||||
if (event.type !== assertion.type) return false;
|
||||
return Object.entries(assertion.where ?? {}).every(
|
||||
([path, expected]) => readPath(event, path) === expected,
|
||||
);
|
||||
}
|
||||
|
||||
export function verifyTask(task, { events = [], responseText = "", adapterEvidence = {} } = {}) {
|
||||
const site = task.siteAssertions.map((assertion) => {
|
||||
const actual = events.filter((event) => eventMatches(event, assertion)).length;
|
||||
return {
|
||||
kind: "site",
|
||||
label: assertion.label,
|
||||
status: actual >= assertion.minCount ? "passed" : "failed",
|
||||
expected: `at least ${assertion.minCount}`,
|
||||
actual,
|
||||
};
|
||||
});
|
||||
|
||||
const response = task.responseAssertions.map((assertion) => ({
|
||||
kind: "response",
|
||||
label: assertion.label,
|
||||
status: responseText.includes(assertion.includes) ? "passed" : "failed",
|
||||
expected: `response includes ${JSON.stringify(assertion.includes)}`,
|
||||
}));
|
||||
|
||||
const adapter = task.adapterAssertions.map((assertion) => {
|
||||
if (!Object.hasOwn(adapterEvidence, assertion.key)) {
|
||||
return {
|
||||
kind: "adapter",
|
||||
label: assertion.label,
|
||||
status: "unverified",
|
||||
expected: assertion.key,
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "adapter",
|
||||
label: assertion.label,
|
||||
status: adapterEvidence[assertion.key] ? "passed" : "failed",
|
||||
expected: assertion.key,
|
||||
actual: adapterEvidence[assertion.key],
|
||||
};
|
||||
});
|
||||
|
||||
const checks = [...site, ...response, ...adapter];
|
||||
const failed = checks.filter(({ status }) => status === "failed").length;
|
||||
const unverified = checks.filter(({ status }) => status === "unverified").length;
|
||||
return {
|
||||
taskId: task.id,
|
||||
status: failed > 0 ? "failed" : unverified > 0 ? "passed-with-unverified" : "passed",
|
||||
summary: {
|
||||
passed: checks.length - failed - unverified,
|
||||
failed,
|
||||
unverified,
|
||||
total: checks.length,
|
||||
},
|
||||
checks,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export const evalDirectory = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
export const casesDirectory = join(evalDirectory, "cases");
|
||||
export const fixturesDirectory = join(evalDirectory, "fixtures");
|
||||
export const schemasDirectory = join(evalDirectory, "schemas");
|
||||
export const resultsDirectory = join(evalDirectory, "results");
|
||||
@@ -0,0 +1,71 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
function appendCaptured(current, chunk) {
|
||||
if (current.length >= MAX_CAPTURE_BYTES) return current;
|
||||
return `${current}${chunk}`.slice(0, MAX_CAPTURE_BYTES);
|
||||
}
|
||||
|
||||
export function runProcess(command, args, { cwd, env, timeoutMs = 300_000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const startedAt = Date.now();
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
const child = spawn(command, args, {
|
||||
cwd,
|
||||
env: { ...process.env, ...env },
|
||||
shell: false,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
child.stdout.on("data", (chunk) => {
|
||||
stdout = appendCaptured(stdout, chunk.toString());
|
||||
});
|
||||
child.stderr.on("data", (chunk) => {
|
||||
stderr = appendCaptured(stderr, chunk.toString());
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => child.kill("SIGKILL"), 2_000).unref();
|
||||
}, timeoutMs);
|
||||
|
||||
const finish = (result) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve({
|
||||
command,
|
||||
args,
|
||||
stdout,
|
||||
stderr,
|
||||
timedOut,
|
||||
durationMs: Date.now() - startedAt,
|
||||
...result,
|
||||
});
|
||||
};
|
||||
|
||||
child.once("error", (error) => finish({ exitCode: null, signal: null, error: error.message }));
|
||||
child.once("close", (exitCode, signal) => finish({ exitCode, signal }));
|
||||
});
|
||||
}
|
||||
|
||||
export function substituteArgs(args, values) {
|
||||
return args.map((argument) => {
|
||||
let result = argument;
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
result = result.replaceAll(`{${key}}`, String(value));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
export function countPattern(text, pattern) {
|
||||
if (!pattern) return null;
|
||||
const matches = text.match(new RegExp(pattern, "g"));
|
||||
return matches?.length ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { relative, sep } from "node:path";
|
||||
|
||||
import { validateCaseFixtureLinks } from "./fixture-registry.mjs";
|
||||
import { casesDirectory } from "./paths.mjs";
|
||||
|
||||
function templateRoots(value) {
|
||||
if (typeof value === "string") {
|
||||
return [...value.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1].split(".")[0]);
|
||||
}
|
||||
if (Array.isArray(value)) return value.flatMap(templateRoots);
|
||||
if (value && typeof value === "object") return Object.values(value).flatMap(templateRoots);
|
||||
return [];
|
||||
}
|
||||
|
||||
export function validateRepositoryCases(cases, fixtureRegistry) {
|
||||
const errors = [...validateCaseFixtureLinks(cases, fixtureRegistry)];
|
||||
for (const testCase of cases) {
|
||||
const relativePath = relative(casesDirectory, testCase.sourceFile);
|
||||
const suiteDirectory = relativePath.split(sep)[0];
|
||||
if (suiteDirectory !== testCase.suite) {
|
||||
errors.push(
|
||||
`case ${testCase.id} declares suite ${testCase.suite} but is stored under ${suiteDirectory}`,
|
||||
);
|
||||
}
|
||||
|
||||
const availableVariables = new Set(["baseUrl", "runId", "seed", "sessionId", "url"]);
|
||||
const evidence = new Set(["sessionStopped"]);
|
||||
for (const [index, step] of testCase.smokeSteps.entries()) {
|
||||
for (const root of templateRoots(step)) {
|
||||
if (!availableVariables.has(root)) {
|
||||
errors.push(
|
||||
`case ${testCase.id} smoke.steps[${index}] references unavailable variable ${root}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (step.saveAs) availableVariables.add(step.saveAs);
|
||||
if (step.evidence) evidence.add(step.evidence);
|
||||
}
|
||||
for (const assertion of testCase.adapterAssertions) {
|
||||
if (!evidence.has(assertion.key)) {
|
||||
errors.push(
|
||||
`case ${testCase.id} expects adapter evidence ${assertion.key} but no smoke step produces it`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export function repositorySummary(cases, fixtureRegistry) {
|
||||
const suites = Object.fromEntries(
|
||||
[...new Set(cases.map(({ suite }) => suite))]
|
||||
.sort()
|
||||
.map((suite) => [suite, cases.filter((testCase) => testCase.suite === suite).length]),
|
||||
);
|
||||
const tags = [...new Set(cases.flatMap(({ tags }) => tags))].sort();
|
||||
return {
|
||||
cases: cases.length,
|
||||
suites,
|
||||
tags: tags.length,
|
||||
fixtureModules: fixtureRegistry.definitions.length,
|
||||
fixtureRoutes: fixtureRegistry.routes.length,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { mkdir, realpath, stat, writeFile } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
|
||||
import { casesDirectory, evalDirectory } from "./paths.mjs";
|
||||
|
||||
const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
|
||||
async function exists(path) {
|
||||
try {
|
||||
await stat(path);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error?.code === "ENOENT") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function moduleSpecifier(fromDirectory, target) {
|
||||
const path = relative(await realpath(fromDirectory), await realpath(target))
|
||||
.split(sep)
|
||||
.join("/");
|
||||
return path.startsWith(".") ? path : `./${path}`;
|
||||
}
|
||||
|
||||
export async function scaffoldCase({
|
||||
id,
|
||||
title = id,
|
||||
suite = "regression",
|
||||
source,
|
||||
rootCasesDirectory = casesDirectory,
|
||||
}) {
|
||||
if (!ID_PATTERN.test(id ?? "")) throw new Error("case id must use lowercase kebab-case");
|
||||
if (!ID_PATTERN.test(suite ?? "")) throw new Error("suite must use lowercase kebab-case");
|
||||
const directory = join(rootCasesDirectory, suite, id);
|
||||
if (await exists(directory)) throw new Error(`case directory already exists: ${directory}`);
|
||||
await mkdir(directory, { recursive: true });
|
||||
|
||||
const marker = `CASE-${id.toUpperCase().replaceAll("-", "_")}`;
|
||||
const startPath = `/cases/${id}`;
|
||||
const manifest = {
|
||||
$schema: "../../../schemas/case.schema.json",
|
||||
schemaVersion: 1,
|
||||
id,
|
||||
title,
|
||||
order: 10,
|
||||
suite,
|
||||
tags: ["badcase", "regression"],
|
||||
...(source ? { source: { type: "user-badcase", reference: source } } : {}),
|
||||
fixture: { startPath },
|
||||
prompts: {
|
||||
en: `Open {url}, complete the minimal regression scenario, report ${marker}, and close the browser session.`,
|
||||
"zh-CN": `打开 {url},完成最小回归场景,报告 ${marker},最后关闭浏览器会话。`,
|
||||
},
|
||||
coverage: ["session.start", "session.stop", "page.navigate", "inspect.observe"],
|
||||
assertions: {
|
||||
site: [
|
||||
{
|
||||
label: "regression fixture was displayed",
|
||||
type: "page.shown",
|
||||
where: { "data.path": startPath },
|
||||
minCount: 1,
|
||||
},
|
||||
],
|
||||
response: [{ label: "reported regression marker", includes: marker }],
|
||||
adapter: [{ label: "browser session was closed", key: "sessionStopped" }],
|
||||
},
|
||||
smoke: { steps: [{ action: "navigate" }, { action: "observe" }] },
|
||||
};
|
||||
|
||||
const fixtureHelper = await moduleSpecifier(
|
||||
directory,
|
||||
join(evalDirectory, "lib", "fixtures.mjs"),
|
||||
);
|
||||
const fixture = `import { escapeHtml, page } from ${JSON.stringify(fixtureHelper)};
|
||||
|
||||
const title = ${JSON.stringify(title)};
|
||||
|
||||
export default {
|
||||
id: ${JSON.stringify(id)},
|
||||
routes: [${JSON.stringify(startPath)}],
|
||||
render() {
|
||||
return page({
|
||||
title,
|
||||
body: \`<section class="card"><h1>\${escapeHtml(title)}</h1><p class="marker">${marker}</p><p>Replace this page with a privacy-safe minimal reproduction.</p></section>\`,
|
||||
});
|
||||
},
|
||||
};
|
||||
`;
|
||||
const readme = `# ${title}
|
||||
|
||||
## Original symptom
|
||||
|
||||
Describe what the user observed without including private data or proprietary page content.
|
||||
|
||||
## Minimal reproduction
|
||||
|
||||
Explain the smallest DOM, timing, or browser-state condition that reproduces the failure.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
Describe the observable success condition and update the case assertions accordingly.
|
||||
|
||||
## Regression history
|
||||
|
||||
- Source: ${source ?? "add issue, PR, or anonymized user report reference"}
|
||||
- Fix: add the fixing PR when available
|
||||
`;
|
||||
|
||||
const files = {
|
||||
manifest: join(directory, `${id}.case.json`),
|
||||
fixture: join(directory, `${id}.fixture.mjs`),
|
||||
readme: join(directory, "README.md"),
|
||||
};
|
||||
await Promise.all([
|
||||
writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`, { flag: "wx" }),
|
||||
writeFile(files.fixture, fixture, { flag: "wx" }),
|
||||
writeFile(files.readme, readme, { flag: "wx" }),
|
||||
]);
|
||||
return { directory, files };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
function hashSeed(value) {
|
||||
const text = String(value);
|
||||
let hash = 2166136261;
|
||||
for (const character of text) {
|
||||
hash ^= character.codePointAt(0);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return hash >>> 0;
|
||||
}
|
||||
|
||||
function mulberry32(seed) {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state += 0x6d2b79f5;
|
||||
let value = state;
|
||||
value = Math.imul(value ^ (value >>> 15), value | 1);
|
||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
|
||||
return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeSeed(value) {
|
||||
const numeric = Number(value);
|
||||
return Number.isSafeInteger(numeric) ? numeric : hashSeed(value);
|
||||
}
|
||||
|
||||
export function describeSeed(value) {
|
||||
const seed = normalizeSeed(value);
|
||||
const random = mulberry32(seed);
|
||||
const choose = (values) => values[Math.floor(random() * values.length)];
|
||||
return {
|
||||
seed,
|
||||
labelMode: choose(["wrapped", "for", "aria"]),
|
||||
nestingDepth: 1 + Math.floor(random() * 4),
|
||||
hydrationDelayMs: choose([0, 40, 120, 250]),
|
||||
decoy: choose(["none", "disabled-input", "duplicate-text"]),
|
||||
fieldOrder: choose(["text-first", "select-first"]),
|
||||
idSuffix: hashSeed(`${seed}:id`).toString(36).slice(0, 6),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createServer } from "node:http";
|
||||
|
||||
import { loadFixtureRegistry } from "./fixture-registry.mjs";
|
||||
|
||||
const RUN_ID_PATTERN = /^[A-Za-z0-9._-]{1,120}$/;
|
||||
|
||||
function validRunId(value) {
|
||||
return typeof value === "string" && RUN_ID_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function json(response, status, value) {
|
||||
response.writeHead(status, {
|
||||
"cache-control": "no-store",
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
});
|
||||
response.end(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function html(response, status, value) {
|
||||
response.writeHead(status, {
|
||||
"cache-control": "no-store",
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
});
|
||||
response.end(value);
|
||||
}
|
||||
|
||||
async function readJson(request) {
|
||||
let raw = "";
|
||||
for await (const chunk of request) {
|
||||
raw += chunk;
|
||||
if (raw.length > 64 * 1024) {
|
||||
throw new Error("request body exceeds 64 KiB");
|
||||
}
|
||||
}
|
||||
return raw ? JSON.parse(raw) : {};
|
||||
}
|
||||
|
||||
export function createEvalServer({ host = "127.0.0.1", port = 0, fixtureRegistry } = {}) {
|
||||
const runs = new Map();
|
||||
let sequence = 0;
|
||||
let server;
|
||||
let registry = fixtureRegistry;
|
||||
|
||||
function eventsFor(runId) {
|
||||
if (!runs.has(runId)) runs.set(runId, []);
|
||||
return runs.get(runId);
|
||||
}
|
||||
|
||||
function record(runId, type, data = {}, metadata = {}) {
|
||||
if (!validRunId(runId)) return null;
|
||||
const event = {
|
||||
sequence: ++sequence,
|
||||
timestamp: new Date().toISOString(),
|
||||
type,
|
||||
data,
|
||||
...metadata,
|
||||
};
|
||||
eventsFor(runId).push(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
function snapshot(runId) {
|
||||
return { runId, events: [...(runs.get(runId) ?? [])] };
|
||||
}
|
||||
|
||||
function reset(runId) {
|
||||
runs.set(runId, []);
|
||||
}
|
||||
|
||||
async function handle(request, response) {
|
||||
const origin = `http://${request.headers.host ?? `${host}:${port}`}`;
|
||||
const url = new URL(request.url ?? "/", origin);
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/healthz") {
|
||||
return json(response, 200, { ok: true });
|
||||
}
|
||||
|
||||
if (request.method === "POST" && url.pathname === "/api/events") {
|
||||
const body = await readJson(request);
|
||||
if (!validRunId(body.runId) || typeof body.type !== "string") {
|
||||
return json(response, 400, { error: "runId and type are required" });
|
||||
}
|
||||
const event = record(body.runId, body.type, body.data ?? {}, {
|
||||
path: typeof body.path === "string" ? body.path : undefined,
|
||||
});
|
||||
return json(response, 202, { accepted: true, sequence: event.sequence });
|
||||
}
|
||||
|
||||
const runMatch = url.pathname.match(/^\/api\/runs\/([^/]+)$/);
|
||||
if (runMatch) {
|
||||
const runId = decodeURIComponent(runMatch[1]);
|
||||
if (!validRunId(runId)) return json(response, 400, { error: "invalid run id" });
|
||||
if (request.method === "GET") return json(response, 200, snapshot(runId));
|
||||
if (request.method === "DELETE") {
|
||||
reset(runId);
|
||||
return json(response, 200, { runId, reset: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (request.method === "GET" && url.pathname === "/api/ping") {
|
||||
const runId = url.searchParams.get("run");
|
||||
if (!validRunId(runId)) return json(response, 400, { error: "invalid run id" });
|
||||
record(runId, "network.ping", { token: "NETWORK-73" }, { path: url.pathname });
|
||||
return json(response, 200, { ok: true, token: "NETWORK-73" });
|
||||
}
|
||||
|
||||
if (request.method !== "GET") return json(response, 405, { error: "method not allowed" });
|
||||
|
||||
const runId = url.searchParams.get("run") ?? "manual";
|
||||
if (!validRunId(runId)) return json(response, 400, { error: "invalid run id" });
|
||||
|
||||
const fixture = registry.render(url.pathname, {
|
||||
runId,
|
||||
query: url.searchParams,
|
||||
record: (type, data, metadata) => record(runId, type, data, metadata),
|
||||
});
|
||||
if (!fixture) return html(response, 404, "<!doctype html><h1>Not found</h1>");
|
||||
record(runId, "page.request", { path: url.pathname }, { path: url.pathname });
|
||||
return html(response, 200, fixture);
|
||||
}
|
||||
|
||||
return {
|
||||
record,
|
||||
reset,
|
||||
snapshot,
|
||||
async start() {
|
||||
if (server) throw new Error("eval server is already running");
|
||||
registry ??= await loadFixtureRegistry();
|
||||
server = createServer((request, response) => {
|
||||
handle(request, response).catch((error) => {
|
||||
json(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
||||
});
|
||||
});
|
||||
await new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(port, host, resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("unexpected server address");
|
||||
return { host, port: address.port, baseUrl: `http://${host}:${address.port}` };
|
||||
},
|
||||
async stop() {
|
||||
if (!server) return;
|
||||
const active = server;
|
||||
server = undefined;
|
||||
await new Promise((resolve, reject) => {
|
||||
active.close((error) => (error ? reject(error) : resolve()));
|
||||
active.closeAllConnections?.();
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
function durationFor(result) {
|
||||
if (result.execution?.durationMs !== undefined) return result.execution.durationMs;
|
||||
return (result.steps ?? []).reduce((sum, step) => sum + step.durationMs, 0);
|
||||
}
|
||||
|
||||
export function summarizeReports(reports) {
|
||||
const groups = new Map();
|
||||
for (const report of reports) {
|
||||
for (const result of report.results ?? []) {
|
||||
const adapter = result.adapter ?? report.adapter ?? "unknown";
|
||||
const variant = result.variant ?? report.variant ?? "unspecified";
|
||||
const key = `${adapter}\u0000${variant}`;
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, {
|
||||
adapter,
|
||||
variant,
|
||||
runs: 0,
|
||||
passed: 0,
|
||||
fullyVerified: 0,
|
||||
executionFailures: 0,
|
||||
errors: 0,
|
||||
durationMs: 0,
|
||||
toolCalls: 0,
|
||||
toolCallSamples: 0,
|
||||
});
|
||||
}
|
||||
const group = groups.get(key);
|
||||
group.runs += 1;
|
||||
group.durationMs += durationFor(result);
|
||||
group.errors += result.metrics?.errorCount ?? (result.executionError ? 1 : 0);
|
||||
if (result.metrics?.toolCallCount !== null && result.metrics?.toolCallCount !== undefined) {
|
||||
group.toolCalls += result.metrics.toolCallCount;
|
||||
group.toolCallSamples += 1;
|
||||
}
|
||||
const executionFailed =
|
||||
Boolean(result.executionError) ||
|
||||
result.execution?.timedOut ||
|
||||
(result.execution?.exitCode !== undefined && result.execution.exitCode !== 0);
|
||||
if (executionFailed) group.executionFailures += 1;
|
||||
if (result.verification?.status !== "failed" && !executionFailed) group.passed += 1;
|
||||
if (result.verification?.status === "passed" && !executionFailed) group.fullyVerified += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.values()].map((group) => ({
|
||||
adapter: group.adapter,
|
||||
variant: group.variant,
|
||||
runs: group.runs,
|
||||
passRate: group.runs ? group.passed / group.runs : 0,
|
||||
fullyVerifiedRate: group.runs ? group.fullyVerified / group.runs : 0,
|
||||
executionFailures: group.executionFailures,
|
||||
errors: group.errors,
|
||||
averageToolCalls: group.toolCallSamples
|
||||
? Math.round((group.toolCalls / group.toolCallSamples) * 10) / 10
|
||||
: null,
|
||||
averageDurationMs: group.runs ? Math.round(group.durationMs / group.runs) : 0,
|
||||
}));
|
||||
}
|
||||
|
||||
export function printSummary(rows) {
|
||||
const printable = rows.map((row) => ({
|
||||
adapter: row.adapter,
|
||||
variant: row.variant,
|
||||
runs: row.runs,
|
||||
pass: `${Math.round(row.passRate * 100)}%`,
|
||||
verified: `${Math.round(row.fullyVerifiedRate * 100)}%`,
|
||||
exec_failures: row.executionFailures,
|
||||
errors: row.errors,
|
||||
avg_tools: row.averageToolCalls ?? "-",
|
||||
avg_ms: row.averageDurationMs,
|
||||
}));
|
||||
console.table(printable);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { loadCaseManifests } from "./case-loader.mjs";
|
||||
|
||||
let casesPromise;
|
||||
|
||||
export function allTasks({ reload = false } = {}) {
|
||||
if (reload || !casesPromise) casesPromise = loadCaseManifests();
|
||||
return casesPromise;
|
||||
}
|
||||
|
||||
export function listTasks(cases) {
|
||||
return cases.map(({ id, title, suite, tags, seed }) => ({ id, title, suite, tags, seed }));
|
||||
}
|
||||
|
||||
export function getTask(taskId, cases) {
|
||||
const task = cases.find(({ id }) => id === taskId);
|
||||
if (!task) {
|
||||
const ids = cases.map(({ id }) => id).join(", ");
|
||||
throw new Error(`unknown case ${JSON.stringify(taskId)}; expected one of: ${ids}`);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
export function taskUrl(task, baseUrl, runId, seed = task.seed) {
|
||||
const url = new URL(task.startPath, baseUrl);
|
||||
url.searchParams.set("run", runId);
|
||||
if (seed !== undefined) url.searchParams.set("seed", String(seed));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function expandTemplate(template, values) {
|
||||
return Object.entries(values).reduce(
|
||||
(result, [name, value]) => result.replaceAll(`{${name}}`, String(value)),
|
||||
template,
|
||||
);
|
||||
}
|
||||
|
||||
export function renderPrompt(task, { baseUrl, runId, locale = "zh-CN", seed = task.seed }) {
|
||||
const template = task.prompts[locale];
|
||||
if (!template) {
|
||||
throw new Error(`unsupported locale ${JSON.stringify(locale)}; expected en or zh-CN`);
|
||||
}
|
||||
return expandTemplate(template, {
|
||||
baseUrl,
|
||||
runId: encodeURIComponent(runId),
|
||||
seed: seed ?? "",
|
||||
url: taskUrl(task, baseUrl, runId, seed),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://browser-skill.local/schemas/browser-eval-case.schema.json",
|
||||
"title": "BrowserSkill browser evaluation case",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schemaVersion",
|
||||
"id",
|
||||
"title",
|
||||
"suite",
|
||||
"tags",
|
||||
"fixture",
|
||||
"prompts",
|
||||
"coverage",
|
||||
"assertions",
|
||||
"smoke"
|
||||
],
|
||||
"properties": {
|
||||
"$schema": { "type": "string" },
|
||||
"schemaVersion": { "const": 1 },
|
||||
"id": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
|
||||
"title": { "type": "string", "minLength": 1 },
|
||||
"order": { "type": "integer", "minimum": 0 },
|
||||
"suite": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": { "type": "string", "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" },
|
||||
"uniqueItems": true
|
||||
},
|
||||
"fixture": {
|
||||
"type": "object",
|
||||
"required": ["startPath"],
|
||||
"properties": { "startPath": { "type": "string", "pattern": "^/" } },
|
||||
"additionalProperties": false
|
||||
},
|
||||
"prompts": {
|
||||
"type": "object",
|
||||
"required": ["en", "zh-CN"],
|
||||
"properties": {
|
||||
"en": { "type": "string", "minLength": 1 },
|
||||
"zh-CN": { "type": "string", "minLength": 1 }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"coverage": { "type": "array", "items": { "type": "string" }, "uniqueItems": true },
|
||||
"assertions": {
|
||||
"type": "object",
|
||||
"required": ["site", "response", "adapter"],
|
||||
"properties": {
|
||||
"site": { "type": "array", "items": { "type": "object" } },
|
||||
"response": { "type": "array", "items": { "type": "object" } },
|
||||
"adapter": { "type": "array", "items": { "type": "object" } }
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"smoke": {
|
||||
"type": "object",
|
||||
"required": ["steps"],
|
||||
"properties": {
|
||||
"steps": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["action"],
|
||||
"properties": { "action": { "type": "string" } },
|
||||
"additionalProperties": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"seed": { "type": "integer" },
|
||||
"source": { "type": "object" }
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
import { runCommandTask } from "../lib/agent-runner.mjs";
|
||||
import { loadCaseManifests, validateCaseManifest } from "../lib/case-loader.mjs";
|
||||
import { buildOperationCoverage } from "../lib/coverage.mjs";
|
||||
import { loadFixtureRegistry } from "../lib/fixture-registry.mjs";
|
||||
import { verifyTask } from "../lib/oracle.mjs";
|
||||
import { runProcess } from "../lib/process.mjs";
|
||||
import { repositorySummary, validateRepositoryCases } from "../lib/repository-validation.mjs";
|
||||
import { scaffoldCase } from "../lib/scaffold-case.mjs";
|
||||
import { describeSeed } from "../lib/seeded-generator.mjs";
|
||||
import { createEvalServer } from "../lib/server.mjs";
|
||||
import { summarizeReports } from "../lib/summary.mjs";
|
||||
import { allTasks, getTask, renderPrompt } from "../lib/tasks.mjs";
|
||||
|
||||
const cases = await allTasks();
|
||||
const fixtureRegistry = await loadFixtureRegistry();
|
||||
|
||||
async function withServer(run) {
|
||||
const server = createEvalServer({ fixtureRegistry });
|
||||
const info = await server.start();
|
||||
try {
|
||||
await run(server, info);
|
||||
} finally {
|
||||
await server.stop();
|
||||
}
|
||||
}
|
||||
|
||||
test("case manifests are discovered, ordered, and grouped into suites", () => {
|
||||
assert.deepEqual(
|
||||
cases.map(({ id }) => id),
|
||||
[
|
||||
"navigation-history",
|
||||
"form-controls",
|
||||
"hover-inspect",
|
||||
"tabs",
|
||||
"diagnostics",
|
||||
"mobile-emulation",
|
||||
"generated-form",
|
||||
],
|
||||
);
|
||||
assert.deepEqual(repositorySummary(cases, fixtureRegistry).suites, { core: 6, matrix: 1 });
|
||||
});
|
||||
|
||||
test("repository validation links every case to a fixture and valid workflow evidence", () => {
|
||||
assert.deepEqual(validateRepositoryCases(cases, fixtureRegistry), []);
|
||||
const summary = repositorySummary(cases, fixtureRegistry);
|
||||
assert.equal(summary.cases, 7);
|
||||
assert.equal(summary.fixtureModules, 8);
|
||||
assert.equal(summary.fixtureRoutes, 12);
|
||||
});
|
||||
|
||||
test("manifest validation rejects unknown operations and incomplete workflow steps", () => {
|
||||
const invalid = {
|
||||
schemaVersion: 1,
|
||||
id: "invalid-case",
|
||||
title: "Invalid",
|
||||
suite: "regression",
|
||||
tags: ["regression"],
|
||||
fixture: { startPath: "/invalid" },
|
||||
prompts: { en: "Open {url}", "zh-CN": "打开 {url}" },
|
||||
coverage: ["page.teleport"],
|
||||
assertions: { site: [], response: [], adapter: [] },
|
||||
smoke: { steps: [{ action: "select", selector: "#choice", values: [] }] },
|
||||
typo: true,
|
||||
};
|
||||
const errors = validateCaseManifest(invalid);
|
||||
assert.ok(errors.some((error) => error.includes("unknown top-level property typo")));
|
||||
assert.ok(errors.some((error) => error.includes("unknown operation page.teleport")));
|
||||
assert.ok(errors.some((error) => error.includes("values must be a non-empty array")));
|
||||
});
|
||||
|
||||
test("fixture server exposes deterministic task and seeded matrix markers", async () => {
|
||||
await withServer(async (_server, { baseUrl }) => {
|
||||
const fixtures = [
|
||||
["/navigation/detail?run=test-markers", "NAV-42"],
|
||||
["/form?run=test-markers", '<option value="two">Two</option>'],
|
||||
["/hover-inspect?run=test-markers", "INSPECT-27"],
|
||||
["/tabs/child?run=test-markers", "TAB-29"],
|
||||
["/diagnostics?run=test-markers", "CONSOLE-61"],
|
||||
["/responsive?run=test-markers", "VIEWPORT-84"],
|
||||
["/matrix/generated-form?run=test-markers&seed=17", "SEED-17"],
|
||||
];
|
||||
for (const [path, marker] of fixtures) {
|
||||
const response = await fetch(`${baseUrl}${path}`);
|
||||
assert.equal(response.status, 200);
|
||||
assert.match(await response.text(), new RegExp(marker));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test("server records and resets run-scoped events", async () => {
|
||||
await withServer(async (server, { baseUrl }) => {
|
||||
const response = await fetch(`${baseUrl}/api/events`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ runId: "event-test", type: "example", data: { value: 7 } }),
|
||||
});
|
||||
assert.equal(response.status, 202);
|
||||
assert.equal(server.snapshot("event-test").events[0].data.value, 7);
|
||||
const resetResponse = await fetch(`${baseUrl}/api/runs/event-test`, { method: "DELETE" });
|
||||
assert.equal(resetResponse.status, 200);
|
||||
assert.deepEqual(server.snapshot("event-test").events, []);
|
||||
});
|
||||
});
|
||||
|
||||
test("form case oracle checks submitted values and separates adapter evidence", () => {
|
||||
const task = getTask("form-controls", cases);
|
||||
const events = [
|
||||
{ type: "form.enter_pressed", data: {} },
|
||||
{
|
||||
type: "form.submitted",
|
||||
data: { text: "agent-parity", notes: "BrowserSkill works", choice: "two" },
|
||||
},
|
||||
{ type: "page.shown", data: { path: "/result" } },
|
||||
];
|
||||
const partial = verifyTask(task, { events, responseText: "The page says Received!" });
|
||||
assert.equal(partial.status, "passed-with-unverified");
|
||||
assert.equal(partial.summary.unverified, 2);
|
||||
|
||||
const complete = verifyTask(task, {
|
||||
events,
|
||||
responseText: "The page says Received!",
|
||||
adapterEvidence: { screenshotCreated: true, sessionStopped: true },
|
||||
});
|
||||
assert.equal(complete.status, "passed");
|
||||
});
|
||||
|
||||
test("navigation case fails when reload is missing", () => {
|
||||
const task = getTask("navigation-history", cases);
|
||||
const verification = verifyTask(task, {
|
||||
events: [
|
||||
{ type: "navigation.detail.clicked", data: {} },
|
||||
{ type: "page.shown", data: { path: "/navigation/start" } },
|
||||
{ type: "page.shown", data: { path: "/navigation/start" } },
|
||||
{ type: "page.shown", data: { path: "/navigation/detail" } },
|
||||
{ type: "page.shown", data: { path: "/navigation/detail" } },
|
||||
],
|
||||
responseText: "NAV-42",
|
||||
});
|
||||
assert.equal(verification.status, "failed");
|
||||
assert.equal(
|
||||
verification.checks.find(({ label }) => label === "detail page was reloaded").status,
|
||||
"failed",
|
||||
);
|
||||
});
|
||||
|
||||
test("prompt rendering is run-scoped, localized, and seed-aware", () => {
|
||||
const task = getTask("generated-form", cases);
|
||||
const input = { baseUrl: "http://127.0.0.1:4173", runId: "prompt-test", seed: 17 };
|
||||
assert.match(renderPrompt(task, { ...input, locale: "en" }), /seed=17/);
|
||||
assert.match(renderPrompt(task, { ...input, locale: "zh-CN" }), /seeded form/);
|
||||
});
|
||||
|
||||
test("command adapter carries a run from process launch through oracle verification", async () => {
|
||||
await withServer(async (server, serverInfo) => {
|
||||
const script = `
|
||||
const [baseUrl, runId] = process.argv.slice(1);
|
||||
const send = (type, data) => fetch(baseUrl + "/api/events", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ runId, type, data }),
|
||||
});
|
||||
await send("navigation.detail.clicked", {});
|
||||
await send("page.shown", { path: "/navigation/start" });
|
||||
await send("page.shown", { path: "/navigation/start" });
|
||||
await send("page.shown", { path: "/navigation/detail" });
|
||||
await send("page.shown", { path: "/navigation/detail" });
|
||||
await send("page.shown", { path: "/navigation/detail", navigationType: "reload" });
|
||||
console.log("NAV-42");
|
||||
`;
|
||||
const result = await runCommandTask({
|
||||
server,
|
||||
serverInfo,
|
||||
task: getTask("navigation-history", cases),
|
||||
adapter: {
|
||||
command: process.execPath,
|
||||
args: ["--input-type=module", "-e", script, "{baseUrl}", "{runId}"],
|
||||
variant: "fake-test",
|
||||
},
|
||||
adapterName: "fake-agent",
|
||||
configDirectory: process.cwd(),
|
||||
iteration: 1,
|
||||
locale: "en",
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
assert.equal(result.execution.exitCode, 0);
|
||||
assert.equal(result.verification.status, "passed-with-unverified");
|
||||
assert.equal(result.eventCount, 6);
|
||||
});
|
||||
});
|
||||
|
||||
test("report summary keeps partial verification distinct from full verification", () => {
|
||||
const rows = summarizeReports([
|
||||
{
|
||||
results: [
|
||||
{
|
||||
adapter: "agent-a",
|
||||
variant: "granular-28",
|
||||
execution: { exitCode: 0, durationMs: 100 },
|
||||
metrics: { errorCount: 0, toolCallCount: 4 },
|
||||
verification: { status: "passed-with-unverified" },
|
||||
},
|
||||
{
|
||||
adapter: "agent-a",
|
||||
variant: "granular-28",
|
||||
execution: { exitCode: 0, durationMs: 300 },
|
||||
metrics: { errorCount: 1, toolCallCount: 6 },
|
||||
verification: { status: "passed" },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
assert.equal(rows[0].passRate, 1);
|
||||
assert.equal(rows[0].fullyVerifiedRate, 0.5);
|
||||
assert.equal(rows[0].averageDurationMs, 200);
|
||||
assert.equal(rows[0].averageToolCalls, 5);
|
||||
assert.equal(rows[0].errors, 1);
|
||||
});
|
||||
|
||||
test("coverage inventory contains all 28 operations and three manual lanes", () => {
|
||||
const coverage = buildOperationCoverage(cases);
|
||||
const operations = coverage.map(({ operation }) => operation);
|
||||
assert.equal(operations.length, 28);
|
||||
assert.equal(new Set(operations).size, 28);
|
||||
assert.deepEqual(
|
||||
coverage.filter(({ directSmoke }) => !directSmoke).map(({ operation }) => operation),
|
||||
["tabs.borrow", "tabs.return", "assist.request-help"],
|
||||
);
|
||||
assert.deepEqual(coverage.find(({ operation }) => operation === "interact.fill").smokeCases, [
|
||||
"form-controls",
|
||||
"generated-form",
|
||||
]);
|
||||
});
|
||||
|
||||
test("seeded dimensions are reproducible and vary across seeds", () => {
|
||||
assert.deepEqual(describeSeed("badcase-17"), describeSeed("badcase-17"));
|
||||
assert.notDeepEqual(describeSeed("badcase-17"), describeSeed("badcase-18"));
|
||||
assert.equal(describeSeed(17).seed, 17);
|
||||
});
|
||||
|
||||
test("badcase scaffold creates a loadable, escaped, self-contained case", async () => {
|
||||
const temporaryRoot = await mkdtemp(join(tmpdir(), "browser-eval-scaffold-"));
|
||||
try {
|
||||
const title = "Quoted `title` ${notCode} <unsafe>";
|
||||
const result = await scaffoldCase({
|
||||
id: "reported-timeout",
|
||||
title,
|
||||
suite: "regression",
|
||||
source: "issue-123",
|
||||
rootCasesDirectory: temporaryRoot,
|
||||
});
|
||||
const loaded = await loadCaseManifests({ casesDirectory: temporaryRoot });
|
||||
assert.equal(loaded[0].id, "reported-timeout");
|
||||
assert.equal(loaded[0].source.reference, "issue-123");
|
||||
|
||||
const generatedRegistry = await loadFixtureRegistry({ roots: [temporaryRoot] });
|
||||
const html = generatedRegistry.render("/cases/reported-timeout", {
|
||||
runId: "scaffold-test",
|
||||
query: new URLSearchParams(),
|
||||
record() {},
|
||||
});
|
||||
assert.match(html, /Quoted `title` \$\{notCode\} <unsafe>/);
|
||||
assert.match(await readFile(result.files.readme, "utf8"), /issue-123/);
|
||||
} finally {
|
||||
await rm(temporaryRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("CLI accepts pnpm separator and supports suite and tag filters", async () => {
|
||||
const cli = resolve("evals/browser/cli.mjs");
|
||||
const coverageResult = await runProcess(process.execPath, [cli, "--", "coverage", "--json"], {
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
assert.equal(coverageResult.exitCode, 0, coverageResult.stderr);
|
||||
assert.equal(JSON.parse(coverageResult.stdout).length, 28);
|
||||
|
||||
const coreResult = await runProcess(
|
||||
process.execPath,
|
||||
[cli, "list", "--suite", "core", "--json"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
},
|
||||
);
|
||||
assert.equal(coreResult.exitCode, 0, coreResult.stderr);
|
||||
assert.equal(JSON.parse(coreResult.stdout).length, 6);
|
||||
|
||||
const formResult = await runProcess(process.execPath, [cli, "list", "--tag", "form", "--json"], {
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
assert.equal(formResult.exitCode, 0, formResult.stderr);
|
||||
assert.deepEqual(
|
||||
JSON.parse(formResult.stdout).map(({ id }) => id),
|
||||
["form-controls", "generated-form"],
|
||||
);
|
||||
});
|
||||
|
||||
test("CLI validation and seed generation are machine-readable", async () => {
|
||||
const cli = resolve("evals/browser/cli.mjs");
|
||||
const validation = await runProcess(process.execPath, [cli, "validate", "--json"], {
|
||||
timeoutMs: 5_000,
|
||||
});
|
||||
assert.equal(validation.exitCode, 0, validation.stderr);
|
||||
assert.equal(JSON.parse(validation.stdout).ok, true);
|
||||
|
||||
const generated = await runProcess(
|
||||
process.execPath,
|
||||
[cli, "generate", "--seed", "known-badcase", "--json"],
|
||||
{ timeoutMs: 5_000 },
|
||||
);
|
||||
assert.equal(generated.exitCode, 0, generated.stderr);
|
||||
assert.equal(typeof JSON.parse(generated.stdout).hydrationDelayMs, "number");
|
||||
|
||||
const generatedSet = await runProcess(
|
||||
process.execPath,
|
||||
[cli, "generate", "--seed", "4,7,14", "--json"],
|
||||
{ timeoutMs: 5_000 },
|
||||
);
|
||||
assert.equal(generatedSet.exitCode, 0, generatedSet.stderr);
|
||||
assert.deepEqual(
|
||||
JSON.parse(generatedSet.stdout).map(({ seed }) => seed),
|
||||
[4, 7, 14],
|
||||
);
|
||||
});
|
||||
@@ -4,6 +4,9 @@
|
||||
"packageManager": "pnpm@10.17.0",
|
||||
"scripts": {
|
||||
"cli:build": "cargo run -p bsk-protocol --bin dump-schema --locked && pnpm -r build",
|
||||
"eval:browser": "node evals/browser/cli.mjs",
|
||||
"eval:browser:check": "node evals/browser/cli.mjs validate && node --test evals/browser/tests/*.test.mjs",
|
||||
"eval:browser:test": "node --test evals/browser/tests/*.test.mjs",
|
||||
"ext:build": "pnpm --filter @browser-skill/extension build",
|
||||
"ext:build:zip": "pnpm --filter @browser-skill/extension zip",
|
||||
"ext:dev": "pnpm --filter @browser-skill/extension dev",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user