diff --git a/.oxlintrc.json b/.oxlintrc.json index e40c1c3c..fa7dc74d 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -237,7 +237,8 @@ "tests/tools-axe.test.ts", "tests/tools-scanPageMatrix.test.ts", "tests/tools-auditKeyboard.test.ts", - "tests/tools-auditSite.integration.test.ts" + "tests/tools-auditSite.integration.test.ts", + "bench/**" ], "rules": { "notice/notice": "off" diff --git a/AGENTS.md b/AGENTS.md index 246d38c1..3f884ee0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,7 @@ - Test: `npm test` - Coverage: `npm run test:coverage` - Docker smoke test: `npm run test:docker` +- Tool latency benchmark: `npm run bench` (see the Benchmarking section of `README.md`; build first, and compare revisions with `npm run bench:compare`) - TypeScript config is driven by `tsconfig.json` and `tsconfig.all.json`. - Accessibility behavior centers around Axe + Playwright integrations in `src/tools/axe.ts`, `src/tools/auditSite.ts`, `src/tools/auditKeyboard.ts`, and related helpers. - Keep output and report paths compatible with the current README and CLI expectations. diff --git a/README.md b/README.md index ac332785..48ca999b 100644 --- a/README.md +++ b/README.md @@ -221,13 +221,13 @@ Create a `config.json` file with the following options: - `browser.contextOptions.storageState`: Start each session from a recorded Playwright storage state; applied in every mode except `--extension` (fresh contexts receive it at creation, reused contexts via `setStorageState()`). Sessions that share one reused context (non-isolated CDP modes) get the state applied once per context — a session joining a live context inherits its current state, not a fresh copy of the file; see [Auditing pages behind a login](#auditing-pages-behind-a-login) - `timeouts.navigationTimeout`: Maximum time for page navigation in milliseconds (default: `60000`) - `timeouts.defaultTimeout`: Default timeout for Playwright operations in milliseconds (default: `5000`) -- `timeouts.settle`: How long to wait after each action for triggered work to settle before responding (default: `500`) +- `timeouts.settle`: How long to wait after every action before responding (default: `500`). An action that finishes quietly is first watched for up to 100ms (or the settle delay, whichever is shorter) so scheduled network work can still be awaited before the settle delay. - `network.allowedOrigins`: List of origins to allow (blocks all others if specified) - `network.blockedOrigins`: List of origins to block CLI equivalents are also available: `--cdp-launch-command`, `--cdp-launch-args`, `--cdp-launch-cwd`, `--cdp-launch-port`, `--cdp-launch-startup-timeout`, `--cdp-endpoint`, `--cdp-header` (repeat for multiple headers, e.g. `--cdp-header "Authorization: Bearer "`), and `--cdp-timeout`. The CDP headers and timeout can also be set via the `PLAYWRIGHT_MCP_CDP_HEADERS` (one `Name: Value` entry per line) and `PLAYWRIGHT_MCP_CDP_TIMEOUT` environment variables. -Use `--timeout-settle` or `PLAYWRIGHT_MCP_TIMEOUT_SETTLE` to override the post-action settle delay. +Use `--timeout-settle` or `PLAYWRIGHT_MCP_TIMEOUT_SETTLE` to override the post-action settle delay. It applies after every action so delayed DOM-only updates are included in the response; a short observation window also catches scheduled requests and waits for them before that delay. #### HTTP Heartbeat @@ -360,6 +360,13 @@ In `audit_site`, selectors apply to every crawled page, so an `includeSelectors` **Incomplete ("needs review") results:** Axe returns `incomplete` for checks it cannot decide on its own -- contrast over a background image or gradient, ambiguous labels, elements it could not fully evaluate. `scan_page`, `audit_site`, and `scan_page_matrix` report these in a section separate from violations so you can resolve them by inspecting the page (screenshot, snapshot, `browser_evaluate`). Set `includeIncomplete: false` to suppress them. +**Frames that could not be scanned:** +Axe is installed into every frame of the page before the scan runs. A frame that navigates mid-injection, or whose renderer does not answer within a second, is left out -- and its contents then contribute no findings. Rather than let that pass as a clean result, all three scan tools print a `WARNING: Axe could not be installed in N frame(s)` block listing the frame URLs, and `audit_site` and `scan_page_matrix` also record them per page and per variant in their JSON reports (`unscannedFrames`) and in `structuredContent`. A frame that was still loading usually succeeds on a re-run; one that fails consistently has to be audited on its own. + +A nested frame is reported when any frame above it went unscanned, even if its own injection succeeded: Axe reaches a nested document only by relaying through the frames above it, so an outer frame without Axe takes everything below it out of the scan. + +A frame you scoped out yourself is not reported: with `excludeSelectors: ["iframe.intercom-frame"]` that widget failing to load is the outcome you asked for, not a gap. Scope is resolved through the whole frame chain and across shadow boundaries, so an `includeSelectors` entry naming an ancestor still covers frames nested several levels below it or inside a shadow root, and excluding an outer frame or a shadow host silences everything inside it. Anything the check cannot resolve is reported rather than hidden. + ### Audit Tools #### `audit_site` @@ -381,6 +388,7 @@ Runs Axe scans on the same page across viewport/media/zoom variants and compares - Default variants: baseline, mobile, desktop, forced-colors, reduced-motion, zoom-200 - Supports custom variants and optional reload between variants - Always writes a JSON report (default filename: `scan-matrix-{timestamp}.json`) +- JSON report and structured result schema `v2` set baseline deltas to `null` when either scan left frames unscanned, because their coverage is not comparable **Example flow:** ```text @@ -694,6 +702,33 @@ cd mcp-accessibility-scanner npm install ``` +### Benchmarking tool latency + +`bench/mcp-bench.mjs` measures what a client actually waits for: it serves a fixed +synthetic site, speaks MCP to the built server over stdio, and times real +`tools/call` round trips for navigation, interaction, snapshots and every audit +tool. Build first — it runs the compiled server from `lib/`. + +```bash +npm run build +npm run bench -- --out after.json --label after +``` + +Useful flags: `--iterations ` and `--warmups ` (defaults 5 and 1), +`--browser`/`--executable-path` when the browser lives outside Playwright's own +download directory, and `--server ` plus `--lib ` +(supplied together) to point at a different build — that is how revisions compare: + +```bash +git worktree add /tmp/baseline main && (cd /tmp/baseline && npm install && npm run build) +npm run bench -- --server /tmp/baseline/cli.js --lib /tmp/baseline/lib --out before.json --label before +npm run bench -- --out after.json --label after +npm run bench:compare -- before.json after.json +``` + +The comparison total uses only end-to-end scenarios present in both reports, +so adding or removing a scenario does not distort the reported speedup. + ## License MIT diff --git a/SKILL.md b/SKILL.md index 8b6a2baa..6693ed12 100644 --- a/SKILL.md +++ b/SKILL.md @@ -93,7 +93,7 @@ Scan the current page for accessibility violations using Axe. {"violationsTag": ["wcag2aa", "wcag21aa", "wcag22aa"]} ``` -For Electron CDP targets, `scan_page` may currently fail with `Target.createTarget: Not supported`. If that happens, keep using the CLI session, select the live app tab with `browser_tabs`, and run Axe through `browser_evaluate` by injecting the local `node_modules/axe-core/axe.min.js` bundle. +The scan injects Axe into the frames that are already open and runs it there; it no longer opens a helper page, which is what used to fail on Electron CDP targets with `Target.createTarget: Not supported`. If a scan still fails on such a target, keep using the CLI session, select the live app tab with `browser_tabs`, and run Axe through `browser_evaluate` by injecting the local `node_modules/axe-core/axe.min.js` bundle. ### audit_site @@ -311,7 +311,7 @@ Typical REPL flow: > browser_evaluate {"function":"() => document.querySelector('SELECTOR_FOR_NEXT_STEP')?.click()"} ``` -If `scan_page {}` fails on the Electron target, use this Axe fallback from the same REPL session: +If `scan_page {}` still fails on the Electron target, use this Axe fallback from the same REPL session: ```json { diff --git a/bench/fixture.mjs b/bench/fixture.mjs new file mode 100644 index 00000000..fddb62eb --- /dev/null +++ b/bench/fixture.mjs @@ -0,0 +1,96 @@ +/** + * Deterministic pages served to the benchmarked MCP server. + * + * The markup is generated from a fixed seed so every run - and every revision + * compared against another - scans exactly the same DOM. + */ + +const seededRandom = seed => () => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + return seed / 0x7fffffff; +}; + +function heavyPage() { + const random = seededRandom(42); + const rows = []; + for (let index = 0; index < 220; index++) { + const label = `Item ${index}`; + // A mix of named and unnamed controls so axe finds real violations and the + // aria snapshot has interactive refs to click. + const missingAlt = random() < 0.2; + // Every fifth button is genuinely unnamed - no label, and an aria-hidden + // glyph for its only content - so the scan really does report button-name. + const unnamed = index % 5 === 0; + rows.push([ + '
  • ', + `${label} link`, + unnamed + ? `` + : ``, + ``, + `Low contrast text ${index}`, + '
  • ', + ].join('')); + } + return [ + '', + 'Benchmark heavy page', + '', + '', + '', + '
    ', + '

    Benchmark heavy page

    ', + '
    ', + '', + '
    ', + `
      ${rows.join('')}
    `, + '
    ', + ].join(''); +} + +function smallPage(index) { + return [ + '', + `Benchmark page ${index}`, + `

    Page ${index}

    `, + `

    Body copy for page ${index}.

    `, + `Next page`, + `Skip ahead`, + ``, + '', + '
    ', + ].join(''); +} + +export const pages = new Map([ + ['/', heavyPage()], + ['/heavy.html', heavyPage()], + ...Array.from({ length: 12 }, (_, index) => [`/page-${index}.html`, smallPage(index)]), +]); + +/** A string with many embedded data URLs, for the string-processing micro benchmark. */ +export function dataUrlHeavyText(repeat = 400) { + const payload = 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'.repeat(4); + const lines = []; + for (let index = 0; index < repeat; index++) { + lines.push(`- img "Thumb ${index}" [ref=e${index}]:`); + lines.push(` - /url: data:image/gif;base64,${payload}`); + lines.push(`- text: plain aria node ${index} with no url at all`); + lines.push(`- link "Item ${index}" [ref=e${index}b]:`); + lines.push(` - /url: https://example.com/page-${index}`); + } + return lines.join('\n'); +} + +/** A large aria snapshot with no data URLs at all - the common case. */ +export function plainSnapshotText(repeat = 2000) { + const lines = []; + for (let index = 0; index < repeat; index++) { + lines.push(`- listitem [ref=e${index}]:`); + lines.push(` - link "Item ${index} link" [ref=e${index}a]: /page-${index % 12}.html`); + lines.push(` - button "Action ${index}" [ref=e${index}b]`); + lines.push(` - text: Low contrast text ${index}`); + } + return lines.join('\n'); +} diff --git a/bench/mcp-bench.mjs b/bench/mcp-bench.mjs new file mode 100644 index 00000000..4c9aec62 --- /dev/null +++ b/bench/mcp-bench.mjs @@ -0,0 +1,379 @@ +#!/usr/bin/env node +/** + * End-to-end latency benchmark for the MCP tool surface. + * + * Every scenario is a real `tools/call` against a real browser driven by the + * built server, so the numbers include the MCP round trip, Playwright IPC and + * the page work - the latency a client actually waits for. + * + * Usage: + * node bench/mcp-bench.mjs --out results.json [--label name] [--iterations 5] + * node bench/mcp-bench.mjs --server /path/to/other/cli.js --lib /path/to/other/lib + * node bench/mcp-bench.mjs --compare before.json after.json + */ + +import fs from 'node:fs'; +import http from 'node:http'; +import path from 'node:path'; +import process from 'node:process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; + +import { dataUrlHeavyText, pages, plainSnapshotText } from './fixture.mjs'; + +const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const options = parseArgs(process.argv.slice(2)); + +if (options.compare) { + compare(options.compare[0], options.compare[1]); + // process.exit() drops whatever is still buffered, and stdout is only + // synchronous on a TTY - piped into anything that applies backpressure, the + // tail of the table is simply lost. Wait for the writes to drain first. + await new Promise(resolve => process.stdout.write('', resolve)); + process.exit(0); +} +if (!!options.server !== !!options.lib) + throw new Error('--server and --lib must be provided together.'); + +const serverEntry = options.server ? path.resolve(options.server) : path.join(projectRoot, 'cli.js'); +const libRoot = options.lib ? path.resolve(options.lib) : path.join(projectRoot, 'lib'); +const reportPath = options.out ? writableReportPath(options.out) : undefined; +const iterations = options.iterations ?? 5; +const warmups = options.warmups ?? 1; + +const server = await startFixtureServer(); +const origin = `http://127.0.0.1:${server.address().port}`; +const outputDir = fs.mkdtempSync(path.join(process.env.TMPDIR ?? '/tmp', 'mcp-bench-')); + +const transport = new StdioClientTransport({ + command: process.execPath, + args: [ + serverEntry, + '--headless', + '--no-sandbox', + '--isolated', + '--browser', options.browser ?? 'chromium', + '--output-dir', outputDir, + // Sandboxes and CI images often ship a browser outside Playwright's own + // download directory; point at it explicitly when asked. + ...(options.executablePath ? ['--executable-path', options.executablePath] : []), + ], + cwd: projectRoot, +}); +const client = new Client({ name: 'mcp-bench', version: '1.0.0' }); + +/** + * Scenarios run in declaration order; `setup` is excluded from the timing so a + * scenario measures one tool call and nothing else. + */ +const scenarios = [ + { + name: 'tools/list', + run: () => client.listTools(), + }, + { + name: 'browser_navigate (heavy page)', + run: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + }, + { + name: 'browser_snapshot (heavy page)', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('browser_snapshot', {}), + }, + { + name: 'browser_click (ref + snapshot)', + setup: async () => { + const snapshot = await call('browser_navigate', { url: `${origin}/heavy.html` }); + return { ref: refFor(snapshot, 'Submit search') }; + }, + run: state => call('browser_click', { element: 'Submit search button', ref: state.ref }), + }, + { + // browser_type only asks for a snapshot on its `slowly` and `submit` paths, + // so a plain fill is what this measures: ref resolution plus the settle. + name: 'browser_type (ref, fill only)', + setup: async () => { + const snapshot = await call('browser_navigate', { url: `${origin}/heavy.html` }); + return { ref: refFor(snapshot, 'Search') }; + }, + run: state => call('browser_type', { element: 'Search box', ref: state.ref, text: 'benchmark' }), + }, + { + name: 'browser_hover (ref + snapshot)', + setup: async () => { + const snapshot = await call('browser_navigate', { url: `${origin}/heavy.html` }); + return { ref: refFor(snapshot, 'Home') }; + }, + run: state => call('browser_hover', { element: 'Home link', ref: state.ref }), + }, + { + name: 'browser_press_key', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('browser_press_key', { key: 'Tab' }), + }, + { + name: 'browser_find', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('browser_find', { text: 'Item 200 link' }), + }, + { + name: 'scan_page (axe)', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('scan_page', {}), + }, + { + name: 'audit_keyboard (12 tabs)', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('audit_keyboard', { maxTabs: 12 }), + }, + { + name: 'scan_page_matrix (3 variants)', + setup: () => call('browser_navigate', { url: `${origin}/heavy.html` }), + run: () => call('scan_page_matrix', { + variants: [ + { name: 'baseline' }, + { name: 'mobile', viewport: { width: 375, height: 812 } }, + { name: 'zoom-200', zoomPercent: 200 }, + ], + }), + }, + { + name: 'audit_site (6 pages)', + setup: () => call('browser_navigate', { url: `${origin}/page-0.html` }), + run: () => call('audit_site', { startUrl: `${origin}/page-0.html`, maxPages: 6, maxDepth: 2 }), + }, + { + name: 'audit_screen_reader', + setup: () => call('browser_navigate', { url: `${origin}/page-0.html` }), + run: () => call('audit_screen_reader', {}), + }, +]; + +const results = []; +try { + // Inside the guard: a missing or unbuilt --server rejects here, and the temp + // output directory has already been created. + await client.connect(transport); + + for (const scenario of scenarios) { + const samples = []; + let state; + for (let index = 0; index < warmups + iterations; index++) { + state = scenario.setup ? await scenario.setup() : undefined; + const startedAt = performance.now(); + await scenario.run(state); + const elapsed = performance.now() - startedAt; + if (index >= warmups) + samples.push(elapsed); + } + const stats = summarize(samples); + results.push({ name: scenario.name, ...stats }); + process.stderr.write(`${scenario.name.padEnd(34)} median ${stats.median.toFixed(1).padStart(9)} ms mean ${stats.mean.toFixed(1).padStart(9)} ms\n`); + } + + results.push(...await runMicroBenchmarks()); +} finally { + // A scenario that throws must not leave the server process, the browser it + // launched, or the temporary report directory behind: a few failed runs would + // otherwise pile up orphaned Chromiums. + await client.close().catch(() => {}); + await new Promise(resolve => server.close(resolve)); + fs.rmSync(outputDir, { recursive: true, force: true }); +} + +const report = { + label: options.label ?? 'run', + server: serverEntry, + node: process.version, + iterations, + scenarios: results, + totalMedianMs: results.filter(entry => !entry.micro).reduce((sum, entry) => sum + entry.median, 0), +}; + +if (reportPath) { + fs.writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); + process.stderr.write(`\nWrote ${options.out}\n`); +} +process.stderr.write(`\nTotal median tool latency: ${report.totalMedianMs.toFixed(1)} ms\n`); + +// --- helpers ------------------------------------------------------------- + +async function runMicroBenchmarks() { + const { truncateDataUrls } = await import(pathToFileURL(path.join(libRoot, 'utils/dataUrl.js'))); + const { toMcpTool } = await import(pathToFileURL(path.join(libRoot, 'mcp/tool.js'))); + const { allTools } = await import(pathToFileURL(path.join(libRoot, 'tools.js'))); + + const plain = plainSnapshotText(); + const withDataUrls = dataUrlHeavyText(); + const micro = [ + ['micro: truncateDataUrls (no data urls, 240 KB)', () => truncateDataUrls(plain)], + ['micro: truncateDataUrls (data url heavy)', () => truncateDataUrls(withDataUrls)], + ['micro: tool schema -> JSON schema (all tools)', () => allTools.map(tool => toMcpTool(tool.schema))], + ]; + + const out = []; + for (const [name, run] of micro) { + const samples = []; + for (let index = 0; index < 25; index++) { + const startedAt = performance.now(); + run(); + const elapsed = performance.now() - startedAt; + if (index >= 5) + samples.push(elapsed); + } + const stats = summarize(samples); + out.push({ name, micro: true, ...stats }); + process.stderr.write(`${name.padEnd(34)} median ${stats.median.toFixed(3).padStart(9)} ms\n`); + } + return out; +} + +function summarize(samples) { + const sorted = [...samples].sort((first, second) => first - second); + const middle = Math.floor(sorted.length / 2); + return { + samples: samples.length, + median: sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2, + mean: samples.reduce((sum, value) => sum + value, 0) / samples.length, + min: sorted[0], + max: sorted[sorted.length - 1], + }; +} + +async function call(name, args) { + const result = await client.callTool({ name, arguments: args }); + if (result.isError) + throw new Error(`${name} failed: ${textOf(result).slice(0, 400)}`); + return result; +} + +function textOf(result) { + return (result.content ?? []).filter(entry => entry.type === 'text').map(entry => entry.text).join('\n'); +} + +function refFor(result, needle) { + const line = textOf(result).split('\n').find(entry => entry.includes(needle) && entry.includes('[ref=')); + const ref = line && /\[ref=([^\]]+)\]/.exec(line); + if (!ref) + throw new Error(`No ref found for "${needle}"`); + return ref[1]; +} + +function startFixtureServer() { + const httpServer = http.createServer((request, response) => { + const body = pages.get(new URL(request.url, 'http://localhost').pathname); + if (body === undefined) { + response.writeHead(404, { 'content-type': 'text/plain' }).end('not found'); + return; + } + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(body); + }); + return new Promise(resolve => httpServer.listen(0, '127.0.0.1', () => resolve(httpServer))); +} + +function compare(beforePath, afterPath) { + const before = JSON.parse(fs.readFileSync(beforePath, 'utf-8')); + const after = JSON.parse(fs.readFileSync(afterPath, 'utf-8')); + const byName = new Map(before.scenarios.map(entry => [entry.name, entry])); + const rows = [['Scenario', `${before.label} (ms)`, `${after.label} (ms)`, 'Change', 'Speedup']]; + let beforeTotal = 0; + let afterTotal = 0; + for (const entry of after.scenarios) { + const baseline = byName.get(entry.name); + if (!baseline) + continue; + if (!entry.micro && !baseline.micro) { + beforeTotal += baseline.median; + afterTotal += entry.median; + } + const change = (entry.median - baseline.median) / baseline.median * 100; + rows.push([ + entry.name, + format(baseline.median), + format(entry.median), + `${change >= 0 ? '+' : ''}${change.toFixed(1)}%`, + `${(baseline.median / entry.median).toFixed(2)}x`, + ]); + } + if (!beforeTotal) + throw new Error('The reports have no end-to-end scenarios in common.'); + const totalChange = (afterTotal - beforeTotal) / beforeTotal * 100; + rows.push([ + 'TOTAL (end-to-end tool calls)', + format(beforeTotal), + format(afterTotal), + `${totalChange >= 0 ? '+' : ''}${totalChange.toFixed(1)}%`, + `${(beforeTotal / afterTotal).toFixed(2)}x`, + ]); + const widths = rows[0].map((_, column) => Math.max(...rows.map(row => row[column].length))); + rows.forEach((row, index) => { + process.stdout.write(`| ${row.map((cell, column) => cell.padEnd(widths[column])).join(' | ')} |\n`); + if (index === 0) + process.stdout.write(`|${widths.map(width => '-'.repeat(width + 2)).join('|')}|\n`); + }); +} + +function format(value) { + return value >= 10 ? value.toFixed(1) : value.toFixed(3); +} + +function parseArgs(argv) { + const parsed = {}; + // Every flag takes a value, and a missing one must fail here rather than as a + // silently skipped report after a full benchmark run. + const value = (index, flag) => { + const next = argv[index]; + if (next === undefined || next.startsWith('--') || !next.trim()) + throw new Error(`${flag} needs a value, got: ${next ?? '(nothing)'}`); + return next; + }; + for (let index = 0; index < argv.length; index++) { + const arg = argv[index]; + if (arg === '--compare') + parsed.compare = [value(++index, arg), value(++index, arg)]; + else if (arg === '--out') + parsed.out = value(++index, arg); + else if (arg === '--label') + parsed.label = value(++index, arg); + else if (arg === '--server') + parsed.server = value(++index, arg); + else if (arg === '--lib') + parsed.lib = value(++index, arg); + else if (arg === '--browser') + parsed.browser = value(++index, arg); + else if (arg === '--executable-path') + parsed.executablePath = value(++index, arg); + else if (arg === '--iterations') + parsed.iterations = wholeNumber(value(++index, arg), arg, 1); + else if (arg === '--warmups') + parsed.warmups = wholeNumber(value(++index, arg), arg, 0); + else + throw new Error(`Unknown argument: ${arg}`); + } + return parsed; +} + +// A missing or non-numeric count would otherwise reach the sampling loop as NaN, +// collect no samples, and crash while formatting undefined statistics - after +// the fixture server and the browser have already started. +function wholeNumber(value, flag, minimum) { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < minimum) + throw new Error(`${flag} needs an integer >= ${minimum}, got: ${value ?? '(nothing)'}`); + return parsed; +} + +function writableReportPath(value) { + const resolved = path.resolve(value); + const parent = path.dirname(resolved); + if (!fs.statSync(parent).isDirectory()) + throw new Error(`--out parent must be a directory: ${parent}`); + fs.accessSync(parent, fs.constants.W_OK); + if (fs.existsSync(resolved)) { + if (!fs.statSync(resolved).isFile()) + throw new Error(`--out must name a file: ${resolved}`); + fs.accessSync(resolved, fs.constants.W_OK); + } + return resolved; +} diff --git a/package-lock.json b/package-lock.json index 3c9f490f..3f3929b2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,6 @@ "version": "3.0.0", "license": "MIT", "dependencies": { - "@axe-core/playwright": "4.12.1", "@cfworker/json-schema": "^4.1.1", "@modelcontextprotocol/sdk": "^1.29.0", "axe-core": "4.12.1", @@ -47,18 +46,6 @@ "node": ">=24.0.0" } }, - "node_modules/@axe-core/playwright": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.12.1.tgz", - "integrity": "sha512-rMd7xriptqKpP+w5265i4Hdkv2X5kbu6uiBi/B2I7uf3hieRBM3qDCfaKPtxfiYb2mKXfF+yLODJwIx+Jv1GDw==", - "license": "MPL-2.0", - "dependencies": { - "axe-core": "~4.12.1" - }, - "peerDependencies": { - "playwright-core": ">= 1.0.0" - } - }, "node_modules/@babel/helper-string-parser": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", diff --git a/package.json b/package.json index 1e3d9174..1754dcb6 100644 --- a/package.json +++ b/package.json @@ -37,12 +37,13 @@ "test:docker": "bash ./tests/docker-smoke.sh", "test:mcp": "node .claude/run-mcp-direct-harness.mjs", "test:mcp:install": "node .claude/run-mcp-direct-harness.mjs --include-install", + "bench": "node bench/mcp-bench.mjs", + "bench:compare": "node bench/mcp-bench.mjs --compare", "test:watch": "vitest", "test:ui": "vitest --ui", "test:coverage": "vitest run --coverage" }, "dependencies": { - "@axe-core/playwright": "4.12.1", "@cfworker/json-schema": "^4.1.1", "@modelcontextprotocol/sdk": "^1.29.0", "axe-core": "4.12.1", diff --git a/src/browserServerBackend.ts b/src/browserServerBackend.ts index f3cd1e70..a1729c55 100644 --- a/src/browserServerBackend.ts +++ b/src/browserServerBackend.ts @@ -32,6 +32,10 @@ import type { ServerBackend } from './mcp/server.js'; export class BrowserServerBackend implements ServerBackend { private _tools: Tool[]; + private _toolsByName: Map; + // Converting the zod schemas to JSON schema costs a few milliseconds for the + // whole set and never changes, so it is done once per server. + private _mcpTools: mcpServer.Tool[] | undefined; private _context: Context | undefined; private _sessionLog: SessionLog | undefined; private _config: FullConfig; @@ -41,6 +45,7 @@ export class BrowserServerBackend implements ServerBackend { this._config = config; this._browserContextFactory = factory; this._tools = filteredTools(config); + this._toolsByName = new Map(this._tools.map(tool => [tool.schema.name, tool])); } async initialize(_context: mcpServer.ServerBackendContext, clientVersion: mcpServer.ClientVersion, roots: mcpServer.Root[]): Promise { @@ -61,11 +66,12 @@ export class BrowserServerBackend implements ServerBackend { } async listTools(): Promise { - return this._tools.map(tool => toMcpTool(tool.schema)); + this._mcpTools ??= this._tools.map(tool => toMcpTool(tool.schema)); + return this._mcpTools; } async callTool(name: string, rawArguments: mcpServer.CallToolRequest['params']['arguments'], requestContext?: mcpServer.CallToolRequestContext) { - const tool = this._tools.find(tool => tool.schema.name === name); + const tool = this._toolsByName.get(name); if (!tool) throw new McpError(ErrorCode.InvalidParams, `Tool "${name}" not found`); let parsedArguments: Record; diff --git a/src/response.ts b/src/response.ts index 98f71948..1720ce77 100644 --- a/src/response.ts +++ b/src/response.ts @@ -157,13 +157,17 @@ export class Response { // All the async snapshotting post-action is happening here. // Everything below should race against modal states. const currentTab = this._context.currentTab(); - if (this._includeSnapshot && currentTab) - this._tabSnapshot = await currentTab.captureSnapshot(); - + // The snapshot of the current tab and the titles of the others are + // independent page reads, so they go out together rather than one after the + // other. Only the current tab's snapshot also refreshes its title. const tabsToUpdate = this._includeTabs ? this._context.tabs().filter(tab => !this._includeSnapshot || tab !== currentTab) : currentTab && !this._includeSnapshot ? [currentTab] : []; - await Promise.allSettled(tabsToUpdate.map(tab => tab.updateTitle())); + const [snapshot] = await Promise.all([ + this._includeSnapshot && currentTab ? currentTab.captureSnapshot() : undefined, + Promise.allSettled(tabsToUpdate.map(tab => tab.updateTitle())), + ]); + this._tabSnapshot = snapshot; } tabSnapshot(): TabSnapshot | undefined { diff --git a/src/tab.ts b/src/tab.ts index 19699436..070972f3 100644 --- a/src/tab.ts +++ b/src/tab.ts @@ -42,6 +42,8 @@ export type TabSnapshot = { downloads: { download: playwright.Download, finished: boolean, outputFile: string }[]; }; +class StaleAriaSnapshotError extends Error {} + export class Tab extends EventEmitter { readonly context: Context; readonly page: playwright.Page; @@ -54,6 +56,11 @@ export class Tab extends EventEmitter { private _modalStates: ModalState[] = []; private _downloads: { download: playwright.Download, finished: boolean, outputFile: string }[] = []; private _defaultTimeout: number; + // The aria snapshot last handed to the caller; the refs in it are the refs the + // next tool call will name. Cleared whenever the page it described is gone. + private _lastAriaSnapshot: string | undefined; + private _ariaSnapshotGeneration = 0; + private _pageGeneration = 0; private _pageListeners: { event: string, listener: (...args: any[]) => void }[] = []; @@ -70,6 +77,17 @@ export class Tab extends EventEmitter { page.on(event as any, listener); this._pageListeners.push({ event, listener }); }; + // Every document swap invalidates the cached snapshot, whoever caused it: + // goBack(), page.reload() from scan_page_matrix, a meta refresh, or the page + // assigning location itself. Tab.navigate() is only one of those routes, and + // a ref resolved against the page the user has left would target the wrong + // document. + listen('framenavigated', (frame: playwright.Frame) => { + if (!frame.parentFrame()) { + ++this._pageGeneration; + this._invalidateAriaSnapshot(); + } + }); listen('console', event => this._handleConsoleMessage(messageToConsoleMessage(event))); listen('pageerror', error => this._handleConsoleMessage(pageErrorToConsoleMessage(error))); listen('request', request => this._requests.set(request, null)); @@ -152,6 +170,13 @@ export class Tab extends EventEmitter { this._recentConsoleMessages.length = 0; this._requests.clear(); this._mainDocumentStatus = undefined; + ++this._pageGeneration; + this._invalidateAriaSnapshot(); + } + + private _invalidateAriaSnapshot() { + ++this._ariaSnapshotGeneration; + this._lastAriaSnapshot = undefined; } private _handleConsoleMessage(message: ConsoleMessage) { @@ -253,13 +278,22 @@ export class Tab extends EventEmitter { async captureSnapshot(): Promise { let tabSnapshot: TabSnapshot | undefined; + const capture = { valid: true }; + const snapshotGeneration = this._ariaSnapshotGeneration; const modalStates = await this._raceAgainstModalStates(async () => { const [snapshot, title] = await Promise.all([ this._withPageStateTimeout( - this.page.ariaSnapshot({ mode: 'ai' }), + this._captureAriaSnapshot(capture), 'capturing page accessibility snapshot', ).catch(error => { - logUnhandledError(error); + // Nothing describes the page any more, and the refs of an older + // snapshot must not be trusted against it. + if (!(error instanceof StaleAriaSnapshotError)) { + capture.valid = false; + logUnhandledError(error); + if (snapshotGeneration === this._ariaSnapshotGeneration) + this._invalidateAriaSnapshot(); + } return `# Page snapshot unavailable: ${formatPageStateError(error)}`; }), this._withPageStateTimeout( @@ -286,6 +320,10 @@ export class Tab extends EventEmitter { tabSnapshot.consoleMessages = this._recentConsoleMessages; this._recentConsoleMessages = []; } + if (!tabSnapshot) { + capture.valid = false; + this._invalidateAriaSnapshot(); + } return tabSnapshot ?? { url: this.page.url(), title: '', @@ -348,7 +386,16 @@ export class Tab extends EventEmitter { } async refLocators(params: { element: string, ref: string }[]): Promise { - const snapshot = await this.page.ariaSnapshot({ mode: 'ai' }); + // The refs a caller passes come from the snapshot the last tool call + // returned, which is the one cached here, so the common case needs no fresh + // capture. Playwright keeps a ref bound to the element it was issued for, + // but that element can change its accessible role or name while staying + // connected. Re-checking only the referenced nodes is still cheaper than a + // full-page snapshot and prevents an old ref from targeting repurposed UI. + const cached = this._lastAriaSnapshot; + const snapshot = cached && await this._refsMatchSnapshot(params, cached) + ? cached + : await this._captureAriaSnapshot(); return params.map(param => { if (!snapshot.includes(`[ref=${param.ref}]`)) throw new Error(`Ref ${param.ref} not found in the current page snapshot. Try capturing new snapshot.`); @@ -356,6 +403,34 @@ export class Tab extends EventEmitter { }); } + private async _refsMatchSnapshot(params: { ref: string }[], snapshot: string): Promise { + const pageGeneration = this._pageGeneration; + const lines = snapshot.split('\n'); + const timeout = Math.min(this._pageStateTimeoutMs(), 1000); + const matches = await Promise.all(params.map(async param => { + const cached = lines.find(line => line.includes(`[ref=${param.ref}]`)); + if (!cached) + return false; + const current = await this.page.locator(`aria-ref=${param.ref}`) + .ariaSnapshot({ mode: 'ai', depth: 1, timeout }) + .catch(() => ''); + // Refs are assigned from the full role and name before long names are + // omitted from rendering, so a semantic change still changes this line. + return current.split('\n', 1)[0]?.trim() === cached.trim(); + })); + return pageGeneration === this._pageGeneration && matches.every(Boolean); + } + + private async _captureAriaSnapshot(capture = { valid: true }): Promise { + const pageGeneration = this._pageGeneration; + const snapshot = await this.page.ariaSnapshot({ mode: 'ai' }); + if (!capture.valid || pageGeneration !== this._pageGeneration) + throw new StaleAriaSnapshotError('Page changed while capturing accessibility snapshot.'); + ++this._ariaSnapshotGeneration; + this._lastAriaSnapshot = snapshot; + return snapshot; + } + async waitForTimeout(time: number) { if (this._javaScriptBlocked()) { await new Promise(f => setTimeout(f, time)); @@ -406,7 +481,7 @@ export function renderModalStates(context: Context, modalStates: ModalState[]): if (modalStates.length === 0) result.push('- There is no modal state present'); for (const state of modalStates) { - const tool = context.tools.filter(tool => 'clearsModalState' in tool).find(tool => tool.clearsModalState === state.type); + const tool = context.tools.find(tool => tool.clearsModalState === state.type); result.push(`- [${truncateDataUrls(state.description)}]: can be handled by the "${tool?.schema.name}" tool`); } return result; diff --git a/src/tools/auditSite.ts b/src/tools/auditSite.ts index 27ed3b74..1dd2304f 100644 --- a/src/tools/auditSite.ts +++ b/src/tools/auditSite.ts @@ -14,7 +14,6 @@ import { summarizeAxeViolations, type AxeTag, type AxeViolation, - type TrimmedAxeViolation } from './axe.js'; type CrawlStrategy = 'links' | 'nav' | 'sitemap' | 'provided'; @@ -36,8 +35,11 @@ type PageReport = { status: PageScanStatus; error: string | null; summary: ReturnType | null; - violations: TrimmedAxeViolation[]; - incomplete: TrimmedAxeViolation[]; + violations: AxeViolation[]; + incomplete: AxeViolation[]; + // Frames Axe never reached on this page, so a page with no violations is + // distinguishable from a page that was only partly scanned. + unscannedFrames: string[]; }; type SummaryViolation = { @@ -295,22 +297,25 @@ async function findCookieLoss( }; } -async function extractLinks(page: import('playwright').Page): Promise { - return await page.evaluate(() => { - return Array.from(document.querySelectorAll('a[href]')) - .map(anchor => (anchor as HTMLAnchorElement).href) - .filter(Boolean); - }); +/** + * Title and outgoing links in one round trip: both are wanted for every crawled + * page, and a second evaluate per page is pure latency on a 200-page crawl. + * `linkSelector` is empty when this page contributes no links (depth exhausted, + * or a strategy that only reads the entry page). + */ +async function readPage(page: import('playwright').Page, linkSelector: string): Promise<{ title: string, links: string[] }> { + return await page.evaluate(selector => ({ + title: document.title, + links: selector + ? Array.from(document.querySelectorAll(selector)) + .map(anchor => (anchor as HTMLAnchorElement).href) + .filter(Boolean) + : [], + }), linkSelector); } -async function extractNavLinks(page: import('playwright').Page): Promise { - return await page.evaluate(() => { - const selectors = 'nav a[href], header a[href], [role="navigation"] a[href]'; - return Array.from(document.querySelectorAll(selectors)) - .map(anchor => (anchor as HTMLAnchorElement).href) - .filter(Boolean); - }); -} +const allLinksSelector = 'a[href]'; +const navLinksSelector = 'nav a[href], header a[href], [role="navigation"] a[href]'; async function extractSitemapUrls(page: import('playwright').Page, sitemapUrl: string): Promise { const response = await page.request.get(sitemapUrl, { timeout: 15000 }); @@ -541,6 +546,7 @@ const auditSite = defineTabTool({ summary: null, violations: [], incomplete: [], + unscannedFrames: [], }; pages.push(pageReport); @@ -569,22 +575,20 @@ const auditSite = defineTabTool({ try { await crawlTab.navigate(item.url); await crawlTab.waitForTimeout(params.waitAfterNavigationMs); - pageReport.title = await crawlTab.page.title(); // Discover before scanning. A scoped scan throws when an // includeSelectors entry is absent from this page, and that must not // silently drop every descendant reachable only through it. - if (params.strategy === 'links' && item.depth < params.maxDepth) { - const links = await extractLinks(crawlTab.page); - for (const link of links) - enqueueUrl(link, item.depth + 1, item.url); - } + let linkSelector = ''; + if (params.strategy === 'links' && item.depth < params.maxDepth) + linkSelector = allLinksSelector; + else if (params.strategy === 'nav' && item.depth === 0) + linkSelector = navLinksSelector; - if (params.strategy === 'nav' && item.depth === 0) { - const links = await extractNavLinks(crawlTab.page); - for (const link of links) - enqueueUrl(link, item.depth + 1, item.url); - } + const { title, links } = await readPage(crawlTab.page, linkSelector); + pageReport.title = title; + for (const link of links) + enqueueUrl(link, item.depth + 1, item.url); const axeResult = await runAxeScan(crawlTab.page, { tags: params.violationsTag as AxeTag[], @@ -596,6 +600,7 @@ const auditSite = defineTabTool({ const violations = prepareAxeResults(axeResult.violations, params.maxNodesPerViolation); pageReport.status = 'scanned'; + pageReport.unscannedFrames = axeResult.unscannedFrames; pageReport.violations = violations.trimmed; pageReport.summary = summarizeAxeViolations(violations.trimmed); aggregateIntoSummary(summaryByViolation, violations.deduped, item.url); @@ -652,6 +657,9 @@ const auditSite = defineTabTool({ const summaryViolations = toSortedSummaryViolations(summaryByViolation); const summaryIncomplete = toSortedSummaryViolations(summaryByIncomplete); + // A partly-scanned page reports fewer violations, and a reader counting them + // must know which pages those numbers are incomplete for. + const pagesWithUnscannedFrames = pages.filter(page => page.unscannedFrames.length); const scannedPagesByViolations = sortScannedPagesByViolations(pages); const summary: SummaryReport = { totals: { @@ -724,6 +732,10 @@ const auditSite = defineTabTool({ }, totals: summary.totals, sessionLosses, + pagesWithUnscannedFrames: pagesWithUnscannedFrames.map(page => ({ + url: page.url, + unscannedFrames: page.unscannedFrames, + })), topViolations: summaryViolations.slice(0, 5).map(violation => ({ id: violation.id, impact: violation.impact ?? null, @@ -751,6 +763,11 @@ const auditSite = defineTabTool({ const topViolations = summarizeTopViolations(summaryViolations, 10); const topIncomplete = summarizeTopViolations(summaryIncomplete, 10); const topPages = summarizeTopPages(scannedPagesByViolations, 20); + const frameWarning = pagesWithUnscannedFrames.length ? [ + `WARNING: Axe could not be installed in frames on ${pagesWithUnscannedFrames.length} page(s); their contents were not scanned and contribute no findings below.`, + ...pagesWithUnscannedFrames.slice(0, 10).map(page => `- ${page.url}: ${page.unscannedFrames.join(', ')}`), + '', + ] : []; const sessionWarning = sessionLosses.length ? [ ...sessionLosses.map(loss => `WARNING: cookie(s) ${loss.cookies.join(', ')} present when the crawl started disappeared while loading ${loss.url}.`), 'If one of these was a session cookie, pages scanned after the URL that dropped it were audited as a signed-out user. Add that URL to excludePathPatterns, sign in again, and re-run.', @@ -758,6 +775,7 @@ const auditSite = defineTabTool({ ] : []; response.addCode('// Crawled pages in a temporary tab and aggregated Axe violations.'); response.addResult([ + ...frameWarning, ...sessionWarning, `Scanned pages: ${summary.totals.scannedPages}`, `Errored pages: ${summary.totals.erroredPages}`, diff --git a/src/tools/axe.ts b/src/tools/axe.ts index 7851d6ec..1499c8e6 100644 --- a/src/tools/axe.ts +++ b/src/tools/axe.ts @@ -1,8 +1,9 @@ -import { AxeBuilder } from '@axe-core/playwright'; import axe from 'axe-core'; -import type { AxeResults } from 'axe-core'; +import { randomUUID } from 'node:crypto'; import { z } from 'zod'; +import { truncateDataUrls } from '../utils/dataUrl.js'; + import type * as playwright from 'playwright'; export const axeTagValues = [ @@ -36,24 +37,38 @@ export type AxeTag = (typeof axeTagValues)[number]; export const defaultAxeTags: readonly AxeTag[] = axeTagValues.filter( tag => tag.startsWith('wcag') || tag === 'section508' ); -export type AxeScanResult = AxeResults; -export type AxeViolation = AxeScanResult['violations'][number]; -export type AxeNode = AxeViolation['nodes'][number]; - -export type TrimmedAxeNode = { - target: AxeNode['target']; +// The scan result carries only what the reporting tools read. Axe's own result +// object additionally holds the per-node check arrays and the full node list of +// every passing rule, which together are ~85% of a content-heavy page's result +// and are dropped inside the page rather than serialized across the CDP +// connection and thrown away here. +export type AxeNode = { + target: axe.NodeResult['target']; html: string; failureSummary: string | null; }; -export type TrimmedAxeViolation = { +export type AxeViolation = { id: string; - impact: AxeViolation['impact']; + impact: axe.ImpactValue | null | undefined; tags: string[]; help: string; helpUrl: string; description: string; - nodes: TrimmedAxeNode[]; + nodes: AxeNode[]; +}; + +export type AxeScanResult = { + url: string; + violations: AxeViolation[]; + incomplete: AxeViolation[]; + // Only the rule count of these is ever reported, so only the ids survive. + passes: { id: string }[]; + inapplicable: { id: string }[]; + // Child frames Axe could not be installed in, and whose contents therefore + // contributed nothing to the results above. Empty on a scan that covered + // everything, so an empty violation list means something only when this is. + unscannedFrames: string[]; }; export type AxeScanOptions = { @@ -76,13 +91,9 @@ export const axeRuleSchemaShape = { disableRules: z.array(z.string().min(1)).optional().describe('Axe rule ids to skip, e.g. ["color-contrast"]. Unlike withRules this narrows whatever is already selected, so it applies to violationsTag and withRules alike. Disabling every rule in withRules is an error, not an empty scan. Unknown rule ids are rejected rather than silently skipped.'), }; -// The rule catalogue comes from the same axe-core build that AxeBuilder injects -// into the page (it ships `axe.source`), so ids can never drift from what the -// scan actually supports and no extra injection is needed to check them. -// package.json pins axe-core AND @axe-core/playwright to the same exact -// release: a ranged wrapper could resolve to a newer version on a clean -// install and nest its own newer axe-core, so validation would use one rule -// catalogue while AxeBuilder injects another. +// The rule catalogue comes from the very axe-core build injected into the page +// (`axe.source` below), so ids can never drift from what the scan supports and +// no extra injection is needed to check them. // Axe does reject unknown ids itself, but only from inside the page after // injection, surfacing as an opaque `frame.evaluate` failure; checking up front // names the bad id and costs nothing. @@ -131,56 +142,430 @@ export function assertRuleOptionsValid(options: Pick list.map(selector => { try { return document.querySelectorAll(selector).length; } catch { return -1; } - }), [...selectors]); + }), selectors); - const invalid = selectors.filter((_, index) => counts[index] === -1); - if (invalid.length) - throw new Error(`Invalid CSS in ${label}: ${invalid.join(', ')}`); + for (const [label, list, offset] of [ + ['includeSelectors', include, 0], + ['excludeSelectors', exclude, include.length], + ] as const) { + const invalid = list.filter((_, index) => counts[offset + index] === -1); + if (invalid.length) + throw new Error(`Invalid CSS in ${label}: ${invalid.join(', ')}`); + } // An unmatched exclude only leaves extra content in scope, and a crawl may // legitimately hit pages without the excluded widget, so it is not an error. - if (label === 'excludeSelectors') - return; - const unmatched = selectors.filter((_, index) => counts[index] === 0); + const unmatched = include.filter((_, index) => counts[index] === 0); if (unmatched.length) - throw new Error(`No elements matched ${label}: ${unmatched.join(', ')}. The scan would have silently covered less of the page than requested.`); + throw new Error(`No elements matched includeSelectors: ${unmatched.join(', ')}. The scan would have silently covered less of the page than requested.`); +} + +// Set by the configure step below, and the only thing the coverage check +// trusts. A frame that navigated to a document carrying its own axe of the same +// version would answer a bare version probe while lacking the allowedOrigins +// configuration the top-level run needs - and so would go unscanned while +// looking covered. +// +// Ceiling: any in-page marker can be forged by the page itself. The name is +// distinctive enough that an accidental collision does not happen; a page +// deliberately evading its own audit is out of scope. +const axeReadyMarker = '__mcpAccessibilityScannerAxeReady'; +let axeReadySequence = 0; +const axeReadyNonce = randomUUID(); + +// Axe's frame support needs its own copy in every frame, and the copy talks to +// the top-level run over postMessage. `` is what lets a +// cross-origin frame answer; without it those frames go unscanned. +const axeConfigureSource = `;axe.configure({ allowedOrigins: [''], branding: { application: 'playwright' } });`; + +// Injected fresh for every scan rather than reused when `window.axe` already +// looks right: that global belongs to the page, which may have installed its own +// axe or reconfigured ours since, and a scan must run this server's build and +// configuration. Re-injection costs ~70ms per frame against a multi-second scan. +async function injectAxe(frame: playwright.Frame, source: string): Promise { + await frame.evaluate(source); +} + +// A child frame that never answers must not hang the scan. It goes unscanned +// instead - but not silently: a frame Axe never reached contributes no +// violations, and an unreported one turns into a clean-looking report. +const childFrameInjectionTimeoutMs = 1000; + +// Every read from a child frame is bounded by it, not just the injection: an +// unresponsive renderer answers neither, and `frame.evaluate` has no timeout of +// its own, so an unbounded probe would hang the whole scan rather than produce +// the partial-coverage warning it exists to produce. +async function withFrameTimeout(work: Promise, fallback: T): Promise { + let timeoutId: ReturnType | undefined; + try { + // Both branches resolve: a rejected loser of the race would surface as an + // unhandled rejection once the winner has already been awaited. + return await Promise.race([ + work.catch(() => fallback), + new Promise(resolve => { + timeoutId = setTimeout(() => resolve(fallback), childFrameInjectionTimeoutMs); + }), + ]); + } finally { + clearTimeout(timeoutId); + } +} + +// Injections run a few at a time rather than all at once. Frames sharing a +// renderer run their evaluations on one thread, so launching every injection +// together starts every timeout clock together too, and a frame still queued +// behind its siblings is timed out for being slow before it has had a turn - +// the budget is meant to catch an unresponsive renderer, not a busy one. +// +// A pool fixes that because a frame's clock starts when a slot frees, never +// while it waits. Measured on a page of 48 same-origin frames: launching them +// all at once reported 28 healthy frames as unscanned and 96 frames reported +// every one of them; through the pool, none, at every size tried. +const frameInjectionConcurrency = 4; + +async function withConcurrency(items: readonly T[], run: (item: T) => Promise): Promise { + let next = 0; + const results: R[] = []; + await Promise.all(Array.from( + { length: Math.min(frameInjectionConcurrency, items.length) }, + async () => { + while (next < items.length) { + const index = next++; + results[index] = await run(items[index]); + } + }, + )); + return results; +} + +// A frame name is author-controlled and unbounded, so it is normalized and +// capped before going anywhere near a report. +const maxFrameNameLength = 80; +const maxFrameUrlLength = 2048; + +// Identifies a frame for the coverage warning. The URL alone is not enough for +// a srcdoc or scripted about:blank frame - both report "about:blank" while +// holding a whole document - so the frame's name comes along when it has one. +// Both are truncated: a data: frame's URL is its document, a name can carry one +// too, and this string ends up in tool text, structured content and JSON +// reports alike. +function describeFrame(frame: playwright.Frame): string { + const rawUrl = truncateDataUrls(frame.url()) || 'about:blank'; + const url = rawUrl.length > maxFrameUrlLength ? `${rawUrl.slice(0, maxFrameUrlLength - 3)}...` : rawUrl; + const name = truncateDataUrls(frame.name().replace(/\s+/g, ' ').trim()).slice(0, maxFrameNameLength); + return name ? `${url} (name="${name}")` : url; +} + +// Whether this frame currently holds the Axe this server injected and +// configured. A frame that navigated after its injection - or that appeared +// since, or that carries only the page's own axe - answers no. +async function hasAxe(frame: playwright.Frame, token: string): Promise { + return withFrameTimeout( + frame.evaluate(({ marker, token }) => (window as any)[marker] === token, { marker: axeReadyMarker, token }), + false, + ); +} + +// A frame the caller scoped out of the scan is not a coverage gap: its contents +// were never going to be reported. Answered from the iframe element in its +// parent document, so an `excludeSelectors: ["iframe.chat-widget"]` entry - the +// documented recipe for dropping a flaky third-party widget - does not produce a +// warning about the very frame it removed. +// +// The whole ancestor chain is walked, not just the immediate parent document, +// because `closest()` stops at a frame boundary while an Axe context does not: +// `includeSelectors: ["#main"]` covers an iframe nested inside an iframe inside +// `#main`, and an exclude naming an outer frame drops everything below it. +// +// Only a positive determination suppresses the warning. An unreachable frame +// element or a probe that cannot answer in time falls through to reporting, so +// no genuine gap is hidden by a check that failed to resolve. +async function isFrameInScope( + frame: playwright.Frame, + mainFrame: playwright.Frame, + include: readonly string[], + exclude: readonly string[] +): Promise { + let includeMatched = !include.length; + for (let current = frame; current.parentFrame(); current = current.parentFrame()!) { + // Bounded like every other child-frame read: `frameElement()` takes no + // timeout of its own, so an unresponsive parent renderer would hang the + // scan here - on the very check that exists to report unresponsive frames. + const elementPromise = current.frameElement().catch(() => null); + const element = await withFrameTimeout(elementPromise, null); + if (!element) { + // The lookup may still land after the bound; do not leak that handle. + void elementPromise.then(late => late?.dispose().catch(() => {})); + return true; + } + let matches: { included: boolean, excluded: boolean, hidden: boolean } | null; + try { + matches = await withFrameTimeout(element.evaluate((node, scope) => { + const composedParent = (element: Element) => { + const root = element.getRootNode(); + if (element.assignedSlot) { + const slotRoot = element.assignedSlot.getRootNode(); + return element.assignedSlot.parentElement ?? (slotRoot instanceof ShadowRoot ? slotRoot.host : null); + } + return element.parentElement ?? (root instanceof ShadowRoot ? root.host : null); + }; + const matchesAny = (selectors: string[]) => selectors.some(selector => { + try { + for (let current: Element | null = node as Element; current;) { + if (current.matches(selector)) + return true; + current = composedParent(current); + } + return false; + } catch { + return false; + } + }); + const roots: (Document | ShadowRoot)[] = [document]; + const modals: Element[] = []; + for (const root of roots) { + modals.push(...[...root.querySelectorAll('dialog:modal')].filter(modal => { + const style = getComputedStyle(modal); + const rect = modal.getBoundingClientRect(); + const visible = modal.checkVisibility?.({ checkOpacity: true, checkVisibilityCSS: true }) ?? + (style.display !== 'none' && !['hidden', 'collapse'].includes(style.visibility) && style.opacity !== '0'); + return visible && + rect.width > 0 && rect.height > 0 && + (modal.getRootNode() as Document | ShadowRoot).elementsFromPoint(rect.left + 1, rect.top + 1).includes(modal); + })); + for (const element of root.querySelectorAll('*')) { + if (element.shadowRoot) + roots.push(element.shadowRoot); + } + } + const insideModal = modals.some(modal => { + for (let current: Element | null = node as Element; current;) { + if (current === modal) + return true; + current = composedParent(current); + } + return false; + }); + let hidden = !!modals.length && !insideModal; + for (let current: Element | null = node as Element; current;) { + const parent = current.assignedSlot?.parentElement ?? current.parentElement; + const style = getComputedStyle(current); + const ariaHidden = current.getAttribute('aria-hidden') === 'true'; + const flattenedChildren = parent ? [...parent.children].flatMap(child => { + if (child.localName !== 'slot') + return [child]; + const assigned = (child as HTMLSlotElement).assignedElements({ flatten: true }); + return assigned.length ? assigned : [...child.children]; + }) : []; + const closedDetails = parent?.localName === 'details' && !parent.hasAttribute('open') && + (current.localName !== 'summary' || flattenedChildren.find(child => child.localName === 'summary') !== current); + const contentHidden = current !== node && style.getPropertyValue('content-visibility') === 'hidden'; + if (ariaHidden || style.display === 'none' || current.hasAttribute('inert') || closedDetails || contentHidden) { + hidden = true; + break; + } + current = composedParent(current); + } + const visibility = getComputedStyle(node as Element).visibility; + hidden ||= visibility === 'hidden' || visibility === 'collapse'; + return { included: matchesAny(scope.include), excluded: matchesAny(scope.exclude), hidden }; + }, current.parentFrame() === mainFrame + ? { include: [...include], exclude: [...exclude] } + : { include: [], exclude: [] }), null); + } finally { + await element.dispose().catch(() => {}); + } + if (!matches) + return true; + // Axe does not traverse a frame hidden from the accessibility tree, so a + // failed injection there is not missing coverage. + if (matches.hidden) + return false; + // Exclude wins wherever it matches: it drops the whole subtree under it. + if (matches.excluded) + return false; + includeMatched ||= matches.included; + } + return includeMatched; +} + +// Returns an identifier for every child frame Axe could not be installed in, so +// the caller can say what the scan did not cover. Every failure is reported +// whatever the URL scheme: injection into an empty about:blank frame succeeds, +// so a frame that reaches here failed for a reason worth knowing about. +// +// Duplicates are kept: two unnamed about:blank frames that both fail are two +// documents that went unscanned, and collapsing them would under-count. +async function injectAxeIntoFrames( + page: playwright.Page, + include: readonly string[], + exclude: readonly string[] +): Promise { + const token = `${axe.version}:${axeReadyNonce}:${++axeReadySequence}`; + const source = `${axe.source}${axeConfigureSource}window[${JSON.stringify(axeReadyMarker)}]=${JSON.stringify(token)};`; + const mainFrame = page.mainFrame(); + await injectAxe(mainFrame, source); + await withConcurrency( + page.frames().filter(frame => frame !== mainFrame), + frame => withFrameTimeout(injectAxe(frame, source), undefined), + ); + + // Coverage is decided here rather than from the injection results: a frame + // that navigated while a slower sibling was still injecting has a new document + // without Axe, and one that appeared since was never injected at all. Both + // would otherwise contribute nothing to a report that still looked complete. + // The frame list is re-read for the same reason. + // + // Ceiling: a frame that navigates between this check and the run below is + // still missed. The window is microseconds rather than the length of the + // slowest injection, but it cannot be closed from outside the page. + const frameIds = new Map(); + const frameId = (frame: playwright.Frame) => { + if (!frameIds.has(frame)) + frameIds.set(frame, frameIds.size); + return frameIds.get(frame)!; + }; + let previousSignature: string | undefined; + for (let round = 0; round < 4; round++) { + const children = page.frames().filter(frame => frame !== mainFrame); + const covered = await withConcurrency(children, frame => hasReachableAxe(frame, token)); + const withoutAxe = new Set(children.filter((_, index) => !covered[index])); + + // A frame whose own injection succeeded is still unreachable when an ancestor + // has no Axe: the top-level run reaches a nested document only by relaying + // through the frames above it, and a frame without Axe relays nothing. + const missed = children.filter(frame => { + for (let current: playwright.Frame | null = frame; current && current !== mainFrame; current = current.parentFrame()) { + if (withoutAxe.has(current)) + return true; + } + return false; + }); + const matches = await withConcurrency(missed, frame => isFrameInScope(frame, mainFrame, include, exclude)); + const inScope = new Map(missed.map((frame, index) => [frame, matches[index]])); + const latest = page.frames().filter(frame => frame !== mainFrame); + const attached = new Set(latest); + const signature = `${children.map((frame, index) => `${frameId(frame)}:${covered[index] ? 1 : 0}:${inScope.get(frame) ? 1 : 0}`).join(',')}>${latest.map(frameId).join(',')}`; + const reported = missed.filter(frame => attached.has(frame) && inScope.get(frame)).map(describeFrame); + + const unchanged = children.length === latest.length && children.every((frame, index) => frame === latest[index]); + if (!unchanged) { + previousSignature = undefined; + continue; + } + // A healthy, unchanged frame tree had no slow scope probes to race with. + if (!missed.length) + return []; + if (signature === previousSignature) + return reported; + previousSignature = signature; + } + throw new Error('The frame tree kept changing while Axe coverage was checked. Retry the scan once the page settles.'); +} + +async function hasReachableAxe(frame: playwright.Frame, token: string): Promise { + if (!await hasAxe(frame, token)) + return false; + const elementPromise = frame.frameElement().catch(() => null); + const element = await withFrameTimeout(elementPromise, null); + if (!element) { + void elementPromise.then(late => late?.dispose().catch(() => {})); + return false; + } + let reachable: boolean; + try { + reachable = await withFrameTimeout(element.evaluate(node => { + for (let current = node as Element; ;) { + const root = current.getRootNode(); + if (!(root instanceof ShadowRoot)) + return true; + if (root.host.shadowRoot !== root) + return false; + current = root.host; + } + }), false); + } finally { + await element.dispose().catch(() => {}); + } + return reachable && await hasAxe(frame, token); +} + +// Runs in the page. Keeps axe's own result shape minus the parts nothing reads: +// per-node check arrays, and the node lists of passing/inapplicable rules. +async function runAxeInPage({ context, options }: { context: unknown, options: unknown }) { + const results = await (window as any).axe.run(context ?? document, options); + const findings = (rules: any[]) => rules.map(rule => ({ + id: rule.id, + impact: rule.impact, + tags: rule.tags, + help: rule.help, + helpUrl: rule.helpUrl, + description: rule.description, + nodes: rule.nodes.map((node: any) => ({ + target: node.target, + html: node.html, + failureSummary: node.failureSummary ?? null, + })), + })); + return { + url: results.url, + violations: findings(results.violations), + incomplete: findings(results.incomplete), + passes: results.passes.map((rule: any) => ({ id: rule.id })), + inapplicable: results.inapplicable.map((rule: any) => ({ id: rule.id })), + }; } export async function runAxeScan(page: playwright.Page, options: AxeScanOptions = {}): Promise { const rules = assertRuleOptionsValid(options); - await assertScopeSelectorsResolve(page, options.include ?? [], 'includeSelectors'); - await assertScopeSelectorsResolve(page, options.exclude ?? [], 'excludeSelectors'); - - const builder = new AxeBuilder({ page }); - // withRules and withTags both overwrite axe's single `runOnly` slot, so only - // one may be called. Explicit rule ids are the more specific request, so they - // win over tags. - if (rules.length) { - builder.withRules(rules); - } else { - builder.withTags([...(options.tags ?? defaultAxeTags)]); - if (options.disableRules?.length) - builder.disableRules([...options.disableRules]); - } - // include/exclude are cumulative in AxeBuilder; exclude wins over include for - // overlapping subtrees, which is what "scan this component minus the widget" - // needs. - for (const selector of options.include ?? []) - builder.include(selector); - for (const selector of options.exclude ?? []) - builder.exclude(selector); - return await builder.analyze(); + const include = options.include ?? []; + const exclude = options.exclude ?? []; + await assertScopeSelectorsResolve(page, include, exclude); + + // `runOnly` holds either a rule list or a tag list, never both. Explicit rule + // ids are the more specific request, so they win over tags — and the per-rule + // `enabled` flag disableRules would set is ignored on that branch, which is + // why assertRuleOptionsValid already subtracted them from the list. + const axeOptions: Record = rules.length + ? { runOnly: { type: 'rule', values: rules } } + : { runOnly: { type: 'tag', values: [...(options.tags ?? defaultAxeTags)] } }; + if (!rules.length && options.disableRules?.length) + axeOptions.rules = Object.fromEntries(options.disableRules.map(rule => [rule, { enabled: false }])); + + // exclude wins over include for overlapping subtrees, which is what "scan + // this component minus the widget" needs. + const context = include.length || exclude.length ? { include: [...include], exclude: [...exclude] } : null; + + const unscannedFrames = await injectAxeIntoFrames(page, include, exclude); + const results = await page.evaluate(runAxeInPage, { context, options: axeOptions }) as AxeScanResult; + return { ...results, unscannedFrames }; +} + +// A scan that could not reach a frame covered less than it looks like it did, +// so every tool that reports results says so in the same words. +export function unscannedFrameLines(unscannedFrames: string[]): string[] { + if (!unscannedFrames.length) + return []; + return [ + '', + `WARNING: Axe could not be installed in ${unscannedFrames.length} frame(s), whose contents were not scanned and contribute no findings above:`, + ...unscannedFrames.map(url => `- ${url}`), + 'A frame that is still loading may succeed on a re-run; one that consistently fails must be audited on its own.', + ]; } export function dedupeAxeNodes(nodes: AxeNode[]): AxeNode[] { @@ -199,27 +584,14 @@ export function dedupeAxeNodes(nodes: AxeNode[]): AxeNode[] { export function trimAxeResults( violations: AxeViolation[], options: { maxNodesPerViolation: number; dedupe?: boolean } -): TrimmedAxeViolation[] { +): AxeViolation[] { // Callers that already deduped node lists can pass `dedupe: false` to skip a // redundant second dedup pass over potentially large node sets. const shouldDedupe = options.dedupe ?? true; - return violations.map(violation => { - const sourceNodes = shouldDedupe ? dedupeAxeNodes(violation.nodes) : violation.nodes; - const nodes = sourceNodes.slice(0, options.maxNodesPerViolation).map(node => ({ - target: [...(node.target ?? [])], - html: node.html ?? '', - failureSummary: node.failureSummary ?? null, - })); - return { - id: violation.id, - impact: violation.impact, - tags: [...violation.tags], - help: violation.help, - helpUrl: violation.helpUrl, - description: violation.description, - nodes, - }; - }); + return violations.map(violation => ({ + ...violation, + nodes: (shouldDedupe ? dedupeAxeNodes(violation.nodes) : violation.nodes).slice(0, options.maxNodesPerViolation), + })); } // Dedupe once and reuse: callers need the deduped nodes for per-rule counting @@ -227,7 +599,7 @@ export function trimAxeResults( export function prepareAxeResults( violations: AxeViolation[], maxNodesPerViolation: number -): { deduped: AxeViolation[]; trimmed: TrimmedAxeViolation[] } { +): { deduped: AxeViolation[]; trimmed: AxeViolation[] } { const deduped = violations.map(violation => ({ ...violation, nodes: dedupeAxeNodes(violation.nodes), @@ -235,7 +607,7 @@ export function prepareAxeResults( return { deduped, trimmed: trimAxeResults(deduped, { maxNodesPerViolation, dedupe: false }) }; } -export function summarizeAxeViolations(violations: TrimmedAxeViolation[]) { +export function summarizeAxeViolations(violations: AxeViolation[]) { const byImpact: Record = {}; const byRuleId: Record = {}; let totalNodes = 0; diff --git a/src/tools/scanPageMatrix.ts b/src/tools/scanPageMatrix.ts index 6a3574e3..8ff5a4dd 100644 --- a/src/tools/scanPageMatrix.ts +++ b/src/tools/scanPageMatrix.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; import { z } from 'zod'; +import type * as playwright from 'playwright'; import { defineTabTool } from './tool.js'; import { sanitizeForFilePath } from '../utils/fileUtils.js'; import { @@ -12,7 +13,7 @@ import { runAxeScan, summarizeAxeViolations, type AxeTag, - type TrimmedAxeViolation + type AxeViolation, } from './axe.js'; type VariantResult = { @@ -28,14 +29,20 @@ type VariantResult = { zoomPercent: number | null; }; summary: ReturnType; - violations: TrimmedAxeViolation[]; - incomplete: TrimmedAxeViolation[]; + violations: AxeViolation[]; + incomplete: AxeViolation[]; + // Frames Axe never reached for this variant, so a variant that looks clean is + // distinguishable from one that was only partly scanned. + unscannedFrames: string[]; nodeCountByRuleId: Record; + // null when this variant or the baseline left frames unscanned: the two runs + // then covered different documents, and a delta between them would report a + // coverage artefact as a fixed or newly introduced violation. diffFromBaseline: { newViolationIds: string[]; resolvedViolationIds: string[]; changedCounts: Record; - }; + } | null; }; const variantSchema = z.object({ @@ -91,12 +98,44 @@ const scanPageMatrixSchema = z.object({ ...axeRuleSchemaShape, }); -function normalizeMedia(variantMedia: z.output['media'] | undefined) { +type MediaState = VariantResult['applied']['media']; + +// Playwright has no getter for a page's media emulation, and passing null to +// emulateMedia resets a feature to the browser default rather than to whatever +// the context was created with: a context made with `colorScheme: 'dark'` reads +// light again after a null. So the effective state is measured from the page +// before the first variant and used both as the per-variant fallback and to put +// the page back afterwards - the same way the viewport and zoom already are. +async function readPageState(page: playwright.Page): Promise<{ zoom: string, media: MediaState }> { + return await page.evaluate(() => ({ + zoom: document.documentElement.style.zoom || '', + media: { + // Neither query matching is a third state, not light. Pinning it to light + // would emulate a preference the page never had, so it is left + // un-emulated - the same treatment the unrepresentable contrast values get. + colorScheme: matchMedia('(prefers-color-scheme: dark)').matches + ? 'dark' as const + : matchMedia('(prefers-color-scheme: light)').matches ? 'light' as const : null, + forcedColors: matchMedia('(forced-colors: active)').matches ? 'active' as const : 'none' as const, + reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'reduce' as const : 'no-preference' as const, + // `less` and `custom` are values emulateMedia cannot express. Leaving the + // feature un-emulated reproduces them exactly, naming a value cannot. + contrast: matchMedia('(prefers-contrast: more)').matches + ? 'more' as const + : matchMedia('(prefers-contrast: no-preference)').matches ? 'no-preference' as const : null, + }, + })); +} + +// An unset property means "whatever this page had before the scan started", not +// "the browser default" - undoing the previous variant must not also undo the +// media emulation the session was configured with. +function normalizeMedia(variantMedia: z.output['media'] | undefined, original: MediaState): MediaState { return { - colorScheme: variantMedia?.colorScheme ?? null, - forcedColors: variantMedia?.forcedColors ?? null, - contrast: variantMedia?.contrast ?? null, - reducedMotion: variantMedia?.reducedMotion ?? null, + colorScheme: variantMedia?.colorScheme ?? original.colorScheme, + forcedColors: variantMedia?.forcedColors ?? original.forcedColors, + contrast: variantMedia?.contrast ?? original.contrast, + reducedMotion: variantMedia?.reducedMotion ?? original.reducedMotion, }; } @@ -152,22 +191,34 @@ const scanPageMatrix = defineTabTool({ width: window.innerWidth, height: window.innerHeight, })); - const originalZoom = await tab.page.evaluate(() => document.documentElement.style.zoom || ''); + const { zoom: originalZoom, media: originalMedia } = await readPageState(tab.page); const variantResults: VariantResult[] = []; try { for (const variant of variants) { // Apply each property once per variant: the variant value when set, // otherwise the original page state (undoing the previous variant). + // Strictly in this order, not in parallel: a page that reacts to a + // viewport or media change by writing document.documentElement.style.zoom + // would overwrite a zoom applied alongside it, and the variant would be + // scanned - and reported - at a zoom it never actually had. await tab.page.setViewportSize(variant.viewport ?? originalViewport); - await tab.page.emulateMedia(normalizeMedia(variant.media)); - await tab.page.evaluate(zoom => { - document.documentElement.style.zoom = zoom; - }, variant.zoomPercent !== undefined ? `${variant.zoomPercent}%` : originalZoom); + // One value, applied and then reported, so `applied.media` cannot drift + // from what the variant was actually scanned under. + const media = normalizeMedia(variant.media, originalMedia); + await tab.page.emulateMedia(media); + // Before the zoom, not after it. Viewport and media emulation survive a + // reload, but the zoom is an inline style on documentElement and the new + // document does not have it - applying it first would scan the variant + // unzoomed while `applied.zoomPercent` still claimed the requested zoom. if (params.reloadBetweenVariants) await tab.page.reload({ waitUntil: 'domcontentloaded' }); + await tab.page.evaluate(zoom => { + document.documentElement.style.zoom = zoom; + }, variant.zoomPercent !== undefined ? `${variant.zoomPercent}%` : originalZoom); + await tab.waitForTimeout(params.waitAfterApplyMs); const axeResult = await runAxeScan(tab.page, { @@ -184,20 +235,17 @@ const scanPageMatrix = defineTabTool({ name: variant.name, applied: { viewport: variant.viewport ?? null, - media: normalizeMedia(variant.media), + media, zoomPercent: variant.zoomPercent ?? null, }, summary: summarizeAxeViolations(violations.trimmed), + unscannedFrames: axeResult.unscannedFrames, violations: violations.trimmed, incomplete: params.includeIncomplete ? prepareAxeResults(axeResult.incomplete, params.maxNodesPerViolation).trimmed : [], nodeCountByRuleId, - diffFromBaseline: { - newViolationIds: [], - resolvedViolationIds: [], - changedCounts: {}, - }, + diffFromBaseline: null, }); await response.reportProgress({ @@ -207,24 +255,32 @@ const scanPageMatrix = defineTabTool({ }); } - const baselineCounts = variantResults[0]?.nodeCountByRuleId ?? {}; - for (const result of variantResults) - result.diffFromBaseline = computeDiffFromBaseline(baselineCounts, result.nodeCountByRuleId); + const baseline = variantResults[0]; + const baselineCounts = baseline?.nodeCountByRuleId ?? {}; + for (const result of variantResults) { + // Only comparable when both sides scanned the same documents. With a + // frame missed on either side, a rule absent from one run may simply + // live in the document that went unscanned, and calling that "resolved" + // - or its reappearance "new" - states an accessibility outcome the run + // cannot support. The warning already says coverage differs; the + // numbers must not quietly contradict it. + const comparable = !result.unscannedFrames.length && !baseline?.unscannedFrames.length; + result.diffFromBaseline = comparable + ? computeDiffFromBaseline(baselineCounts, result.nodeCountByRuleId) + : null; + } } finally { + // Same ordering as the apply path, and for the same reason. await tab.page.setViewportSize(originalViewport); - await tab.page.emulateMedia({ - colorScheme: null, - forcedColors: null, - contrast: null, - reducedMotion: null, - }); + await tab.page.emulateMedia(originalMedia); await tab.page.evaluate(zoom => { document.documentElement.style.zoom = zoom; }, originalZoom); } const report = { - version: 'v1', + // v2 allows diffFromBaseline to be null when scan coverage differs. + version: 'v2', metadata: { url: tab.page.url(), baselineVariant: variantResults[0]?.name ?? 'baseline', @@ -255,6 +311,7 @@ const scanPageMatrix = defineTabTool({ }); response.setStructuredContent({ kind: 'scan_page_matrix', + version: 'v2', report: { path: reportPath, uri: reportResourceLink.uri, @@ -274,18 +331,37 @@ const scanPageMatrix = defineTabTool({ // includeIncomplete, so a 0 here is indistinguishable from a variant // with no needs-review findings. Matches the "-" in the markdown table. totalIncomplete: params.includeIncomplete ? result.incomplete.length : null, - newViolationIds: result.diffFromBaseline.newViolationIds, - resolvedViolationIds: result.diffFromBaseline.resolvedViolationIds, - changedRuleIds: Object.keys(result.diffFromBaseline.changedCounts), + // Without this a client reading only structured output cannot tell a + // partly-scanned variant from a clean one. + unscannedFrames: result.unscannedFrames, + // null, not [], when the coverage differs from the baseline's: an empty + // list reads as "nothing changed", which is the one thing an incomplete + // pair of scans cannot establish. + newViolationIds: result.diffFromBaseline?.newViolationIds ?? null, + resolvedViolationIds: result.diffFromBaseline?.resolvedViolationIds ?? null, + changedRuleIds: result.diffFromBaseline ? Object.keys(result.diffFromBaseline.changedCounts) : null, reportUri: reportResourceLink.uri, })), }); + const variantsWithUnscannedFrames = variantResults.filter(result => result.unscannedFrames.length); const lines = [ + ...(variantsWithUnscannedFrames.length ? [ + `WARNING: Axe could not be installed in frames on ${variantsWithUnscannedFrames.length} variant(s); their contents were not scanned and contribute no findings below.`, + ...variantsWithUnscannedFrames.map(result => `- ${result.name}: ${result.unscannedFrames.join(', ')}`), + 'Baseline deltas are reported as "n/a" wherever the two scans did not cover the same documents.', + '', + ] : []), 'Variant | Violations | Nodes | Incomplete | Top new vs baseline', '--- | --- | --- | --- | ---', ...variantResults.map(result => { - const topNew = result.diffFromBaseline.newViolationIds.slice(0, 5).join(', ') || '-'; + // "n/a" rather than "-": "-" means "compared, nothing new", which is a + // claim a pair of scans with differing coverage cannot make. The reason + // names neither side, because the gap may be in the baseline - in which + // case every other row is uncomparable through no fault of its own. + const topNew = result.diffFromBaseline + ? result.diffFromBaseline.newViolationIds.slice(0, 5).join(', ') || '-' + : 'n/a (coverage differs)'; // "-" rather than 0: with collection off, 0 is indistinguishable from // "no needs-review findings". audit_site omits its section for the same // reason. diff --git a/src/tools/snapshot.ts b/src/tools/snapshot.ts index 93b77b20..66b9b86f 100644 --- a/src/tools/snapshot.ts +++ b/src/tools/snapshot.ts @@ -20,7 +20,7 @@ import { z } from 'zod'; import { defineTabTool, defineTool } from './tool.js'; import * as javascript from '../utils/codegen.js'; import { generateLocator } from './utils.js'; -import { axeRuleSchemaShape, axeScopeSchemaShape, axeTagValues, dedupeAxeNodes, defaultAxeTags, prepareAxeResults, runAxeScan } from './axe.js'; +import { axeRuleSchemaShape, axeScopeSchemaShape, axeTagValues, dedupeAxeNodes, defaultAxeTags, prepareAxeResults, runAxeScan, unscannedFrameLines } from './axe.js'; import { truncateDataUrls } from '../utils/dataUrl.js'; import { sanitizeForFilePath } from '../utils/fileUtils.js'; @@ -102,6 +102,7 @@ const scanPage = defineTool({ `URL: ${results.url}`, '', `Violations: ${results.violations.length}, ${incompleteCount}Passes: ${results.passes.length}, Inapplicable: ${results.inapplicable.length}`, + ...unscannedFrameLines(results.unscannedFrames), ...annotationLines, ].join('\n')); diff --git a/src/tools/tool.ts b/src/tools/tool.ts index 41995ec1..c0929bfc 100644 --- a/src/tools/tool.ts +++ b/src/tools/tool.ts @@ -39,6 +39,9 @@ export type ModalState = FileUploadModalState | DialogModalState; export type Tool = { capability: ToolCapability; schema: ToolSchema; + // Set by the tab tools that resolve a modal state, so a blocked tab can name + // the tool that unblocks it. + clearsModalState?: ModalState['type']; handle: (context: Context, params: z.output, response: Response) => Promise; }; diff --git a/src/tools/utils.ts b/src/tools/utils.ts index cd6e284e..af96b3be 100644 --- a/src/tools/utils.ts +++ b/src/tools/utils.ts @@ -21,23 +21,46 @@ const { asLocator } = coreBundle.iso; import type * as playwright from 'playwright'; import type { Tab } from '../tab.js'; +// How long an action that finished quietly is watched for work it scheduled +// rather than started - a click handler whose fetch fires from a timer has +// issued nothing by the time its own promise resolves. Capped by the settle +// delay it defers to, so lowering that lowers this with it. +const quietWindowMs = 100; + export async function waitForCompletion(tab: Tab, callback: () => Promise): Promise { const settleMs = tab.context.config.timeouts.settle ?? 500; const requests = new Set(); + let requestSeen = false; let frameNavigated = false; let waitCallback: () => void = () => {}; const waitBarrier = new Promise(f => { waitCallback = f; }); + // Resolves on the first sign of page work, whenever it arrives. + let signalCallback: () => void = () => {}; + const firstSignal = new Promise(f => { signalCallback = f; }); - const requestListener = (request: playwright.Request) => requests.add(request); - const requestFinishedListener = (request: playwright.Request) => { + const requestListener = (request: playwright.Request) => { + requestSeen = true; + requests.add(request); + signalCallback(); + }; + // A request that fails - offline, blocked by CORS, aborted - emits + // `requestfailed` and never `requestfinished`. Without the same removal path + // it would sit in the set until the 10s timeout below, turning a click that + // fired one doomed fetch into a ten-second tool call. + const requestSettledListener = (request: playwright.Request) => { requests.delete(request); if (!requests.size) waitCallback(); }; const frameNavigateListener = (frame: playwright.Frame) => { - if (frame.parentFrame()) + signalCallback(); + if (frame.parentFrame()) { + // A child frame swapping documents is page work too, and it can issue no + // request at all. It must not gate the barrier on a top-level load state + // that this navigation will never produce. return; + } frameNavigated = true; dispose(); clearTimeout(timeout); @@ -50,29 +73,62 @@ export async function waitForCompletion(tab: Tab, callback: () => Promise) }; tab.page.on('request', requestListener); - tab.page.on('requestfinished', requestFinishedListener); + tab.page.on('requestfinished', requestSettledListener); + tab.page.on('requestfailed', requestSettledListener); tab.page.on('framenavigated', frameNavigateListener); const timeout = setTimeout(onTimeout, 10000); const dispose = () => { tab.page.off('request', requestListener); - tab.page.off('requestfinished', requestFinishedListener); + tab.page.off('requestfinished', requestSettledListener); + tab.page.off('requestfailed', requestSettledListener); tab.page.off('framenavigated', frameNavigateListener); clearTimeout(timeout); }; try { const result = await callback(); + // Nothing has happened yet, which is not the same as nothing being about to: + // watch briefly for work the action scheduled instead of started. + if (!requestSeen && !frameNavigated) + await raceTimeout(firstSignal, Math.min(quietWindowMs, settleMs)); if (!requests.size && !frameNavigated) waitCallback(); await waitBarrier; - await tab.waitForTimeout(settleMs); + // Timers can schedule DOM-only work without producing any observable page + // signal. Preserve the configured settle delay so the returned snapshot + // includes those updates too. + if (!tab.page.isClosed()) { + try { + await tab.waitForTimeout(settleMs); + } catch (error) { + const targetClosed = error instanceof Error && /Target (?:page, context or browser has been closed|page closed|closed)/i.test(error.message); + if (!tab.page.isClosed() || !targetClosed) + throw error; + } + } return result; } finally { dispose(); } } +// Resolves with `promise` or when the timeout elapses, whichever comes first. +// Both branches resolve, so the losing one leaves nothing unhandled behind. +async function raceTimeout(promise: Promise, timeoutMs: number): Promise { + let timeoutId: ReturnType | undefined; + try { + await Promise.race([ + promise, + new Promise(resolve => { + timeoutId = setTimeout(resolve, timeoutMs); + }), + ]); + } finally { + clearTimeout(timeoutId); + } +} + export async function generateLocator(locator: playwright.Locator): Promise { // playwright-core 1.61 replaced the private `_resolveSelector` helper with the // public `Locator.normalize()` method (microsoft/playwright). `normalize()` diff --git a/src/utils/dataUrl.ts b/src/utils/dataUrl.ts index 8c151876..06fd1b59 100644 --- a/src/utils/dataUrl.ts +++ b/src/utils/dataUrl.ts @@ -29,17 +29,15 @@ export function truncateDataUrl(url: string): string { } export function truncateDataUrls(text: string): string { + // Snapshots are routinely hundreds of KB and usually hold no data URL at all, + // so nothing is copied or rebuilt until the first one is actually found. + let start = findDataUrlStart(text, 0); + if (start === -1) + return text; + let result = ''; let offset = 0; - const lowerText = text.toLowerCase(); - - while (offset < text.length) { - const start = findDataUrlStart(text, lowerText, offset); - if (start === -1) { - result += text.slice(offset); - break; - } - + while (start !== -1) { result += text.slice(offset, start); const match = parseDataUrl(text, start); @@ -47,15 +45,14 @@ export function truncateDataUrls(text: string): string { const prefixLength = dataUrlPrefixLengthAt(text, start); result += text.slice(start, start + prefixLength); offset = start + prefixLength; - continue; + } else { + result += `${match.displayPrefix}...`; + offset = findDataUrlEnd(text, match); } - - const end = findDataUrlEnd(text, match); - result += `${match.displayPrefix}...`; - offset = end; + start = findDataUrlStart(text, offset); } - return result; + return result + text.slice(offset); } type DataUrlMatch = { @@ -66,26 +63,19 @@ type DataUrlMatch = { quote: '"' | '\'' | undefined; }; -function findDataUrlStart(text: string, lowerText: string, offset: number): number { - let start = nextDataUrlPrefix(lowerText, offset); - while (start !== -1) { - if (isDataUrlStartBoundary(text, start)) - return start; - start = nextDataUrlPrefix(lowerText, start + dataUrlPrefixLengthAt(lowerText, start)); +// Matches either prefix case-insensitively without lower-casing a copy of the +// whole text, which on a large snapshot costs more than the scan itself. +const dataUrlPrefixPattern = /data(?::|%3a)/gi; + +function findDataUrlStart(text: string, offset: number): number { + dataUrlPrefixPattern.lastIndex = offset; + for (let match = dataUrlPrefixPattern.exec(text); match; match = dataUrlPrefixPattern.exec(text)) { + if (isDataUrlStartBoundary(text, match.index)) + return match.index; } return -1; } -function nextDataUrlPrefix(lowerText: string, offset: number): number { - const literalStart = lowerText.indexOf(dataUrlPrefix, offset); - const encodedStart = lowerText.indexOf(encodedDataUrlPrefix, offset); - if (literalStart === -1) - return encodedStart; - if (encodedStart === -1) - return literalStart; - return Math.min(literalStart, encodedStart); -} - function dataUrlPrefixLengthAt(text: string, start: number): number { return startsWithIgnoreCase(text, start, encodedDataUrlPrefix) ? encodedDataUrlPrefix.length : dataUrlPrefix.length; } @@ -204,8 +194,20 @@ function isLineBreak(char: string): boolean { return char === '\n' || char === '\r'; } +// Runs once per character of a base64 payload, which is the longest run in any +// snapshot, so it stays a plain switch rather than a regex plus an array scan. function isBase64PayloadTerminator(char: string): boolean { - return /\s/.test(char) || ['"', '\'', '<', '>', ')', ']', '}', '`', ':'].includes(char); + switch (char) { + case '"': case '\'': case '<': case '>': + case ')': case ']': case '}': case '`': case ':': + return true; + default: + return isWhitespace(char); + } +} + +function isWhitespace(char: string): boolean { + return /\s/.test(char); } function isQueryParamBoundary(text: string, match: DataUrlMatch, ampersand: number): boolean { @@ -216,14 +218,14 @@ function isQueryParamBoundary(text: string, match: DataUrlMatch, ampersand: numb function isRawPayloadCompleteBefore(text: string, payloadStart: number, end: number): boolean { let position = end - 1; - while (position >= payloadStart && /\s/.test(text[position])) + while (position >= payloadStart && isWhitespace(text[position])) position--; return text[position] === '>' || (position >= payloadStart + 2 && startsWithIgnoreCase(text, position - 2, '%3e')); } function isRawPayloadSuffixBoundary(text: string, match: DataUrlMatch, position: number): boolean { const char = text[position]; - if (/\s/.test(char)) + if (isWhitespace(char)) return !isRawMarkupPayload(text, match.payloadStart) || isRawPayloadCompleteBefore(text, match.payloadStart, position); if (isRawPayloadWrapperBoundary(text, match, position)) return true; @@ -250,7 +252,7 @@ function looksLikeSourceLocationSuffix(text: string, colon: number): boolean { return false; while (position < text.length && /\d/.test(text[position])) position++; - return position === text.length || isLineBreak(text[position]) || /\s/.test(text[position]); + return position === text.length || isLineBreak(text[position]) || isWhitespace(text[position]); } function looksLikeQueryParam(text: string, offset: number): boolean { @@ -260,7 +262,7 @@ function looksLikeQueryParam(text: string, offset: number): boolean { const char = text[position]; if (char === '=') return position > offset; - if (isLineBreak(char) || /\s/.test(char) || ['&', '#', '"', '\'', '<', '>', ')', '}', '`'].includes(char)) + if (isLineBreak(char) || isWhitespace(char) || ['&', '#', '"', '\'', '<', '>', ')', '}', '`'].includes(char)) return false; } return false; @@ -292,7 +294,7 @@ function isRawPayloadBoundarySuffix(text: string, offset: number): boolean { if (offset >= text.length) return true; const char = text[offset]; - return isLineBreak(char) || /\s/.test(char) || ['"', '\'', ')', ']', '}', '`'].includes(char) || (char === '&' && looksLikeQueryParam(text, offset + 1)); + return isLineBreak(char) || isWhitespace(char) || ['"', '\'', ')', ']', '}', '`'].includes(char) || (char === '&' && looksLikeQueryParam(text, offset + 1)); } function isEncodedPayloadTerminator(text: string, position: number): boolean { @@ -310,6 +312,18 @@ function percentEncodedCharAt(text: string, position: number): string | undefine return String.fromCharCode(Number.parseInt(text.slice(position + 1, position + 3), 16)); } +// `value` is always lower-case ASCII here, so a char-code compare answers this +// without allocating the slice these hot per-character scans would otherwise make. function startsWithIgnoreCase(text: string, position: number, value: string): boolean { - return text.slice(position, position + value.length).toLowerCase() === value; + if (position < 0 || position + value.length > text.length) + return false; + for (let index = 0; index < value.length; index++) { + const char = text.charCodeAt(position + index); + const expected = value.charCodeAt(index); + // Fold upper-case ASCII only; folding by bit would also equate control + // characters with punctuation. + if (char !== expected && !(char >= 65 && char <= 90 && char + 32 === expected)) + return false; + } + return true; } diff --git a/tests/bench.test.ts b/tests/bench.test.ts new file mode 100644 index 00000000..1c811ee0 --- /dev/null +++ b/tests/bench.test.ts @@ -0,0 +1,118 @@ +/** + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { afterEach, expect, it } from 'vitest'; + +const temporaryDirectories: string[] = []; + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) + fs.rmSync(directory, { recursive: true, force: true }); +}); + +it('compares totals over only the shared end-to-end scenarios', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-bench-test-')); + temporaryDirectories.push(directory); + const before = path.join(directory, 'before.json'); + const after = path.join(directory, 'after.json'); + fs.writeFileSync(before, JSON.stringify({ + label: 'before', + totalMedianMs: 110, + scenarios: [ + { name: 'shared', median: 10 }, + { name: 'removed', median: 100 }, + { name: 'micro-shared', median: 1000, micro: true }, + ], + })); + fs.writeFileSync(after, JSON.stringify({ + label: 'after', + totalMedianMs: 1020, + scenarios: [ + { name: 'shared', median: 20 }, + { name: 'added', median: 1000 }, + { name: 'micro-shared', median: 2000, micro: true }, + ], + })); + + const output = execFileSync(process.execPath, ['bench/mcp-bench.mjs', '--compare', before, after], { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + const totalRow = output.split('\n').find(line => line.includes('TOTAL (end-to-end tool calls)')); + expect(totalRow?.split('|').map(cell => cell.trim())).toEqual([ + '', 'TOTAL (end-to-end tool calls)', '10.0', '20.0', '+100.0%', '0.50x', '', + ]); + expect(output).toMatch(/^\| shared\s+\|/m); + expect(output).not.toMatch(/^\| added\s+\|/m); + expect(output).not.toMatch(/^\| removed\s+\|/m); + expect(output).not.toContain('110.0'); + expect(output).not.toContain('1020.0'); +}); + +it.each(['--server', '--lib'])('rejects an unpaired %s override', flag => { + const result = spawnSync(process.execPath, ['bench/mcp-bench.mjs', flag, '/tmp/revision'], { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('--server and --lib must be provided together.'); +}); + +it.each(['--out', '--server', '--lib'])('rejects a blank %s value', flag => { + const result = spawnSync(process.execPath, ['bench/mcp-bench.mjs', flag, ' '], { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('needs a value'); +}); + +it('rejects an invalid report directory before starting the benchmark', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-bench-test-')); + temporaryDirectories.push(directory); + const result = spawnSync(process.execPath, [ + 'bench/mcp-bench.mjs', '--out', path.join(directory, 'missing', 'report.json'), + ], { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('ENOENT'); +}); + +it('rejects a report path whose parent is a file', () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-bench-test-')); + temporaryDirectories.push(directory); + const parent = path.join(directory, 'file'); + fs.writeFileSync(parent, 'not a directory'); + const result = spawnSync(process.execPath, [ + 'bench/mcp-bench.mjs', '--out', path.join(parent, 'report.json'), + ], { + cwd: path.resolve(import.meta.dirname, '..'), + encoding: 'utf8', + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain('--out parent must be a directory'); +}); diff --git a/tests/tab.test.ts b/tests/tab.test.ts index cf3375e9..5e565fda 100644 --- a/tests/tab.test.ts +++ b/tests/tab.test.ts @@ -23,6 +23,7 @@ describe('Tab', () => { let mockContext: Context; let mockPage: any; let onPageClose: any; + let locatorSnapshot: string | undefined; beforeEach(() => { mockPage = new EventEmitter(); @@ -35,8 +36,14 @@ describe('Tab', () => { mockPage.setDefaultTimeout = vi.fn(); mockPage.goBack = vi.fn().mockResolvedValue(null); mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + locatorSnapshot = 'button "Submit" [ref=1]'; mockPage.locator = vi.fn().mockReturnValue({ describe: vi.fn().mockReturnValue({}), + ariaSnapshot: vi.fn(async () => { + if (locatorSnapshot === undefined) + throw new Error('Element not found'); + return locatorSnapshot; + }), }); mockContext = { @@ -386,6 +393,121 @@ describe('Tab', () => { expect(snapshot.ariaSnapshot).toContain('capturing page accessibility snapshot'); }); + it('does not cache an accessibility snapshot that resolves after its timeout', async () => { + vi.useFakeTimers(); + mockContext.config.timeouts.defaultTimeout = 25; + let resolveSnapshot!: (snapshot: string) => void; + mockPage.ariaSnapshot = vi.fn().mockReturnValue(new Promise(resolve => { resolveSnapshot = resolve; })); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const snapshotPromise = tab.captureSnapshot(); + await vi.advanceTimersByTimeAsync(25); + await snapshotPromise; + resolveSnapshot('button "Submit" [ref=1]'); + await Promise.resolve(); + + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Other" [ref=2]'); + await expect( + tab.refLocators([{ element: 'Submit', ref: '1' }]) + ).rejects.toThrow('Ref 1 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('does not return an accessibility snapshot captured before navigation', async () => { + let resolveSnapshot!: (snapshot: string) => void; + mockPage.ariaSnapshot = vi.fn().mockReturnValue(new Promise(resolve => { resolveSnapshot = resolve; })); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const snapshotPromise = tab.captureSnapshot(); + mockPage.emit('framenavigated', { parentFrame: () => null }); + resolveSnapshot('button "Old page" [ref=1]'); + const snapshot = await snapshotPromise; + + expect(snapshot.ariaSnapshot).toContain('Page snapshot unavailable'); + expect(snapshot.ariaSnapshot).not.toContain('Old page'); + }); + + it('does not invalidate a newer overlapping snapshot when an old capture resolves', async () => { + let resolveOld!: (snapshot: string) => void; + let resolveFresh!: (snapshot: string) => void; + mockPage.ariaSnapshot = vi.fn() + .mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve; })) + .mockReturnValueOnce(new Promise(resolve => { resolveFresh = resolve; })); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const oldCapture = tab.captureSnapshot(); + mockPage.emit('framenavigated', { parentFrame: () => null }); + const freshCapture = tab.captureSnapshot(); + resolveFresh('button "Fresh page" [ref=2]'); + expect((await freshCapture).ariaSnapshot).toContain('Fresh page'); + resolveOld('button "Old page" [ref=1]'); + expect((await oldCapture).ariaSnapshot).toContain('Page snapshot unavailable'); + + locatorSnapshot = 'button "Fresh page" [ref=2]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Other" [ref=3]'); + await tab.refLocators([{ element: 'Fresh page', ref: '2' }]); + expect(mockPage.ariaSnapshot).not.toHaveBeenCalled(); + }); + + it('does not invalidate a newer overlapping snapshot when an old capture times out', async () => { + vi.useFakeTimers(); + mockContext.config.timeouts.defaultTimeout = 25; + mockPage.ariaSnapshot = vi.fn() + .mockReturnValueOnce(new Promise(() => {})) + .mockResolvedValueOnce('button "Fresh page" [ref=2]'); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const oldCapture = tab.captureSnapshot(); + const freshCapture = tab.captureSnapshot(); + expect((await freshCapture).ariaSnapshot).toContain('Fresh page'); + await vi.advanceTimersByTimeAsync(25); + expect((await oldCapture).ariaSnapshot).toContain('Page snapshot unavailable'); + + locatorSnapshot = 'button "Fresh page" [ref=2]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Other" [ref=3]'); + await tab.refLocators([{ element: 'Fresh page', ref: '2' }]); + expect(mockPage.ariaSnapshot).not.toHaveBeenCalled(); + }); + + it('does not cache a snapshot completed after a modal interrupts capture', async () => { + let resolveSnapshot!: (snapshot: string) => void; + mockPage.ariaSnapshot = vi.fn().mockReturnValue(new Promise(resolve => { resolveSnapshot = resolve; })); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const pending = tab.captureSnapshot(); + const modal = { type: 'dialog', description: 'Dialog', dialog: {} } as any; + tab.setModalState(modal); + expect((await pending).ariaSnapshot).toBe(''); + tab.clearModalState(modal); + resolveSnapshot('button "Unseen" [ref=2]'); + await Promise.resolve(); + + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Current" [ref=3]'); + await expect(tab.refLocators([{ element: 'Unseen', ref: '2' }])).rejects.toThrow('Ref 2 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('caches overlapping snapshots in completion order', async () => { + let resolveFirst!: (snapshot: string) => void; + let resolveSecond!: (snapshot: string) => void; + mockPage.ariaSnapshot = vi.fn() + .mockReturnValueOnce(new Promise(resolve => { resolveFirst = resolve; })) + .mockReturnValueOnce(new Promise(resolve => { resolveSecond = resolve; })); + const tab = new Tab(mockContext, mockPage as any, onPageClose); + + const first = tab.captureSnapshot(); + const second = tab.captureSnapshot(); + resolveSecond('button "B" [ref=2]'); + await second; + resolveFirst('button "A" [ref=1]'); + await first; + + locatorSnapshot = 'button "A" [ref=1]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Other" [ref=3]'); + await tab.refLocators([{ element: 'A', ref: '1' }]); + expect(mockPage.ariaSnapshot).not.toHaveBeenCalled(); + }); + it('keeps data URL payloads in captured accessibility snapshots for session logs', async () => { const payload = 'Hello'; mockPage.ariaSnapshot = vi.fn().mockResolvedValue(`- link "Example" [ref=e1]:\n - /url: data:image/svg+xml,${payload}`); @@ -431,6 +553,174 @@ describe('Tab', () => { expect(mockPage.locator).toHaveBeenCalledWith('aria-ref=2'); expect(mockPage.ariaSnapshot).toHaveBeenCalledWith({ mode: 'ai' }); }); + + it('resolves refs against the snapshot already returned to the caller', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + + await tab.refLocators([{ element: 'Submit', ref: '1' }]); + + // The ref came from that snapshot, so re-reading the page adds nothing. + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + expect(mockPage.locator).toHaveBeenCalledWith('aria-ref=1'); + }); + + it('re-captures when a cached ref no longer resolves to an element', async () => { + // The element was removed after the snapshot went out: the ref is still in + // the cached text, but it matches nothing, and handing back that locator + // would fail as an action timeout instead of a useful message. + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + locatorSnapshot = undefined; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Other" [ref=2]'); + + await expect( + tab.refLocators([{ element: 'Submit', ref: '1' }]) + ).rejects.toThrow('Ref 1 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('re-captures when a cached ref has different accessible semantics', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + await tab.captureSnapshot(); + locatorSnapshot = 'button "Delete" [ref=2]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Delete" [ref=2]'); + + await expect( + tab.refLocators([{ element: 'Submit', ref: '1' }]) + ).rejects.toThrow('Ref 1 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('re-captures when the page navigates during cached ref validation', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + await tab.captureSnapshot(); + let resolveValidation!: (snapshot: string) => void; + mockPage.locator = vi.fn().mockReturnValue({ + ariaSnapshot: vi.fn().mockReturnValue(new Promise(resolve => { resolveValidation = resolve; })), + describe: vi.fn().mockReturnValue({}), + }); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "New page" [ref=2]'); + + const locators = tab.refLocators([{ element: 'Submit', ref: '1' }]); + mockPage.emit('framenavigated', { parentFrame: () => null }); + resolveValidation('button "Submit" [ref=1]'); + + await expect(locators).rejects.toThrow('Ref 1 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('does not accept a generated locator that only partially matches the old name', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Save" [ref=1]'); + await tab.captureSnapshot(); + locatorSnapshot = 'button "Save 2" [ref=2]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Save 2" [ref=2]'); + + await expect( + tab.refLocators([{ element: 'Save', ref: '1' }]) + ).rejects.toThrow('Ref 1 not found'); + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('revalidates YAML-quoted snapshot entries without a full-page capture', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + locatorSnapshot = `- 'button "Warning: Delete" [ref=1]'`; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue(`- 'button "Warning: Delete" [ref=1]'`); + await tab.captureSnapshot(); + + await tab.refLocators([{ element: 'Delete', ref: '1' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('accepts Playwright synthetic roles when the public ARIA role is empty', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + locatorSnapshot = 'generic [ref=1]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('generic [ref=1]'); + await tab.captureSnapshot(); + + await tab.refLocators([{ element: 'Target', ref: '1' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('reuses a cached ref whose long name is omitted from the snapshot', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + locatorSnapshot = 'button [ref=1]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button [ref=1]'); + await tab.captureSnapshot(); + + await tab.refLocators([{ element: 'Long name', ref: '1' }]); + await tab.refLocators([{ element: 'Long name', ref: '1' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); + + it('re-captures when an omitted long name changes the Playwright ref', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button [ref=1]'); + await tab.captureSnapshot(); + locatorSnapshot = 'button [ref=2]'; + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button [ref=2]'); + + await expect( + tab.refLocators([{ element: 'Long name', ref: '1' }]) + ).rejects.toThrow('Ref 1 not found'); + }); + + it('re-reads the page for a ref the last snapshot does not hold', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1] button "Added" [ref=2]'); + + await tab.refLocators([{ element: 'Added', ref: '2' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledWith({ mode: 'ai' }); + expect(mockPage.locator).toHaveBeenCalledWith('aria-ref=2'); + }); + + it('stops trusting the cached snapshot once the tab navigates', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + mockPage.goto = vi.fn().mockResolvedValue(undefined); + mockPage.waitForLoadState = vi.fn().mockResolvedValue(undefined); + await tab.navigate('https://example.com/next'); + + await tab.refLocators([{ element: 'Submit', ref: '1' }]); + + // Two captures: the first one described a page that is gone. + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(2); + }); + + it('stops trusting the cached snapshot after any main-frame navigation', async () => { + // goBack(), page.reload() and a page-driven location change never reach + // Tab.navigate(), so the cache is keyed on the navigation event itself. + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + + mockPage.emit('framenavigated', { parentFrame: () => null }); + await tab.refLocators([{ element: 'Submit', ref: '1' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(2); + }); + + it('keeps the cached snapshot when only a sub-frame navigates', async () => { + const tab = new Tab(mockContext, mockPage as any, onPageClose); + mockPage.ariaSnapshot = vi.fn().mockResolvedValue('button "Submit" [ref=1]'); + await tab.captureSnapshot(); + + mockPage.emit('framenavigated', { parentFrame: () => ({}) }); + await tab.refLocators([{ element: 'Submit', ref: '1' }]); + + expect(mockPage.ariaSnapshot).toHaveBeenCalledTimes(1); + }); }); describe('consoleMessages', () => { diff --git a/tests/tools-auditSite.integration.test.ts b/tests/tools-auditSite.integration.test.ts index 741a0b40..652fd702 100644 --- a/tests/tools-auditSite.integration.test.ts +++ b/tests/tools-auditSite.integration.test.ts @@ -31,6 +31,7 @@ function createAxeResult(url: string, violations: any[]) { incomplete: [], passes: [], inapplicable: [], + unscannedFrames: [], } as any; } @@ -59,7 +60,10 @@ describe('audit_site integration', () => { context: vi.fn(() => ({ cookies: vi.fn(async () => []) })), url: vi.fn(() => currentUrl), title: vi.fn(async () => `Title for ${currentUrl}`), - evaluate: vi.fn(async () => linkMap[currentUrl] ?? []), + evaluate: vi.fn(async (_callback: unknown, selector?: string) => ({ + title: `Title for ${currentUrl}`, + links: selector ? linkMap[currentUrl] ?? [] : [], + })), }; const crawlTab: any = { diff --git a/tests/tools-auditSite.test.ts b/tests/tools-auditSite.test.ts index f1c25e93..053b5676 100644 --- a/tests/tools-auditSite.test.ts +++ b/tests/tools-auditSite.test.ts @@ -29,6 +29,7 @@ function createAxeResult(url: string, violations: any[], incomplete: any[] = []) incomplete, passes: [], inapplicable: [], + unscannedFrames: [], } as any; } @@ -69,12 +70,15 @@ function createHarness( context: vi.fn(() => ({ cookies: cookiesMock })), url: vi.fn(() => currentUrl), title: vi.fn(async () => `Title for ${currentUrl}`), - evaluate: vi.fn(async (callback: () => unknown) => { - const callbackText = String(callback); - const isNavExtraction = /role=.*navigation.*a\[href\]/.test(callbackText); - if (isNavExtraction) - return navLinkMap[currentUrl] ?? []; - return linkMap[currentUrl] ?? []; + // Mirrors readPage(): one evaluate per crawled page returning the title and, + // when a link selector is passed, the links that selector would collect. + evaluate: vi.fn(async (_callback: unknown, selector?: string) => { + const links = !selector + ? [] + : /navigation/.test(selector) + ? navLinkMap[currentUrl] ?? [] + : linkMap[currentUrl] ?? []; + return { title: `Title for ${currentUrl}`, links }; }), }; @@ -174,6 +178,66 @@ describe('audit_site tool', () => { writeFileSpy = vi.spyOn(fs.promises, 'writeFile').mockResolvedValue(undefined); }); + it('warns about pages whose frames the scan could not reach', async () => { + // A page scanned with a frame missing reports fewer violations, so a reader + // counting them has to know which pages those numbers are incomplete for. + const { context, response } = createHarness({ + 'https://example.com/': ['https://example.com/embedded'], + 'https://example.com/embedded': [], + }); + vi.spyOn(axe, 'runAxeScan').mockImplementation(async (page: any) => ({ + ...createAxeResult(page.url(), []), + unscannedFrames: page.url() === 'https://example.com/embedded' ? ['https://widget.example/embed'] : [], + })); + + await tool.handle(context as any, { + strategy: 'links', + maxPages: 5, + maxDepth: 1, + sameOriginOnly: true, + includeSubdomains: false, + excludePathPatterns: [], + ignoreQueryParams: [], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterNavigationMs: 0, + } as any, response); + + expect(response.result()).toContain('WARNING: Axe could not be installed in frames on 1 page(s)'); + expect(response.result()).toContain('- https://example.com/embedded: https://widget.example/embed'); + + const report = JSON.parse(writeFileSpy.mock.calls[0][1] as string); + const embedded = report.pages.find((page: any) => page.url === 'https://example.com/embedded'); + expect(embedded.unscannedFrames).toEqual(['https://widget.example/embed']); + // A client reading only structured output must be able to tell the same. + expect(response.structuredContent()!.pagesWithUnscannedFrames).toEqual([ + { url: 'https://example.com/embedded', unscannedFrames: ['https://widget.example/embed'] }, + ]); + }); + + it('says nothing about frames when every page was scanned in full', async () => { + const { context, response } = createHarness({ 'https://example.com/': [] }); + vi.spyOn(axe, 'runAxeScan').mockImplementation(async (page: any) => createAxeResult(page.url(), [])); + + await tool.handle(context as any, { + strategy: 'links', + maxPages: 1, + maxDepth: 0, + sameOriginOnly: true, + includeSubdomains: false, + excludePathPatterns: [], + ignoreQueryParams: [], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterNavigationMs: 0, + } as any, response); + + expect(response.result()).not.toContain('could not be installed'); + expect(response.structuredContent()!.pagesWithUnscannedFrames).toEqual([]); + }); + it('passes tags, rule filters and scope selectors through to the axe scan', async () => { const { context, response } = createHarness({ 'https://example.com/': [] }); const runAxeScanSpy = vi.spyOn(axe, 'runAxeScan') @@ -708,7 +772,11 @@ describe('audit_site tool', () => { const report = JSON.parse(writeFileSpy.mock.calls[0][1] as string); const crawledUrls = report.pages.map((page: any) => page.url); expect(crawledUrls).toEqual(['https://example.com/a', 'https://example.com/b']); - expect(crawlTab.page.evaluate).not.toHaveBeenCalled(); + // The page is still read for its title - `every` alone would also pass if + // that read disappeared - and what must not happen is link discovery, which + // is what a non-empty selector argument would mean. + expect(crawlTab.page.evaluate.mock.calls.length).toBeGreaterThan(0); + expect(crawlTab.page.evaluate.mock.calls.every((call: unknown[]) => !call[1])).toBe(true); }); it('supports sitemap strategy by parsing loc entries', async () => { diff --git a/tests/tools-axe.test.ts b/tests/tools-axe.test.ts index ea753694..b9351f12 100644 --- a/tests/tools-axe.test.ts +++ b/tests/tools-axe.test.ts @@ -1,65 +1,92 @@ import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { describe, expect, it, vi } from 'vitest'; +import { chromium } from 'playwright'; +import { describe, expect, it } from 'vitest'; import { z } from 'zod'; -const builderCalls: { withTags: string[][]; withRules: string[][]; disableRules: string[][]; include: string[]; exclude: string[] } = { - withTags: [], - withRules: [], - disableRules: [], - include: [], - exclude: [], -}; -let analyzeResult: any = { violations: [], incomplete: [], passes: [], inapplicable: [] }; - -vi.mock('@axe-core/playwright', () => ({ - AxeBuilder: class { - withTags(tags: string[]) { - builderCalls.withTags.push(tags); - return this; - } - withRules(rules: string[]) { - builderCalls.withRules.push(rules); - return this; - } - disableRules(rules: string[]) { - builderCalls.disableRules.push(rules); - return this; - } - include(selector: string) { - builderCalls.include.push(selector); - return this; - } - exclude(selector: string) { - builderCalls.exclude.push(selector); - return this; - } - async analyze() { - if (analyzeResult instanceof Error) - throw analyzeResult; - return analyzeResult; - } - }, -})); - -const { assertRuleOptionsValid, axeRuleSchemaShape, axeTagValues, defaultAxeTags, dedupeAxeNodes, prepareAxeResults, runAxeScan, summarizeAxeViolations, trimAxeResults } = await import('../src/tools/axe.js'); - -function resetBuilderCalls() { - builderCalls.withTags = []; - builderCalls.withRules = []; - builderCalls.disableRules = []; - builderCalls.include = []; - builderCalls.exclude = []; - analyzeResult = { violations: [], incomplete: [], passes: [], inapplicable: [] }; -} +import { assertRuleOptionsValid, axeRuleSchemaShape, axeTagValues, defaultAxeTags, dedupeAxeNodes, prepareAxeResults, runAxeScan, summarizeAxeViolations, trimAxeResults } from '../src/tools/axe.js'; + +// The scan drives the page itself: axe-core is injected into every frame, then +// run in the main one. The fake page records what the run was asked to do, and +// answers the scope check with the match count each selector should resolve to +// (-1 for CSS the browser rejects). +type ScanCall = { context: unknown; options: any }; -// Stands in for page.evaluate(selectors => …): returns the match count each -// selector should resolve to, or -1 for CSS the browser rejects. -function pageWithSelectorCounts(countBySelector: Record) { +let lastScan: ScanCall | undefined; +let scanResult: any; + +type FrameScope = { included: boolean, excluded: boolean, hidden?: boolean, reachable?: boolean }; + +function makeFrame( + countBySelector: Record, + url = 'https://example.com/', + injectable = true, + name = '', + keepsAxe = true, + scope: FrameScope = { included: true, excluded: false } +) { + let readyToken: string | undefined; return { - evaluate: async (_fn: unknown, selectors: string[]) => - selectors.map(selector => countBySelector[selector] ?? 0), + url: () => url, + name: () => name, + // Set by pageWithSelectorCounts, or by hand to build a nested frame chain. + parentFrame: () => null as any, + // The scope check reads the owning iframe element in the parent document, + // walking up one document per ancestor frame. + frameElement: async () => ({ + evaluate: async (_script: unknown, arg?: { include: string[], exclude: string[] }) => arg === undefined + ? scope.reachable ?? true + : { + included: !!arg.include.length && scope.included, + excluded: !!arg.exclude.length && scope.excluded, + hidden: scope.hidden ?? false, + }, + dispose: async () => undefined, + }), + evaluate: async (script: unknown, arg?: unknown) => { + // Injection: the axe source and its configuration, both plain strings. + if (typeof script === 'string') { + if (!injectable) + throw new Error('Execution context was destroyed'); + const match = /window\["__mcpAccessibilityScannerAxeReady"\]=("[^"]+")/.exec(script); + readyToken = match ? JSON.parse(match[1]) : undefined; + return undefined; + } + // The post-injection coverage probe reads the marker this server sets + // when it configures its own injection. + if (arg && typeof arg === 'object' && 'token' in arg) + return injectable && keepsAxe && readyToken === arg.token; + if (Array.isArray(arg)) + return arg.map(selector => countBySelector[selector as string] ?? 0); + lastScan = arg as ScanCall; + if (scanResult instanceof Error) + throw scanResult; + return scanResult; + }, + }; +} + +function pageWithSelectorCounts(countBySelector: Record = {}, childFrames: any[] = []) { + const frame = makeFrame(countBySelector); + const page = { + ...frame, + frames: () => [frame, ...childFrames], + mainFrame: () => frame, } as any; + // The main frame has no parent; a child hangs off it unless a test already + // placed it deeper in a chain of its own. + page.parentFrame = () => null; + frame.parentFrame = () => null; + for (const child of childFrames) { + if (!child.parentFrame()) + child.parentFrame = () => frame; + } + return page; +} + +function resetScan() { + lastScan = undefined; + scanResult = { url: 'https://example.com', violations: [], incomplete: [], passes: [], inapplicable: [] }; } function node(target: string, html: string) { @@ -148,31 +175,26 @@ describe('axe helpers', () => { }); it('scans with the default tag set and no scope when given no options', async () => { - resetBuilderCalls(); - await runAxeScan({} as any); - expect(builderCalls.withTags).toEqual([[...defaultAxeTags]]); - expect(builderCalls.withRules).toEqual([]); - expect(builderCalls.disableRules).toEqual([]); - expect(builderCalls.include).toEqual([]); - expect(builderCalls.exclude).toEqual([]); + resetScan(); + await runAxeScan(pageWithSelectorCounts()); + expect(lastScan?.options).toEqual({ runOnly: { type: 'tag', values: [...defaultAxeTags] } }); + expect(lastScan?.context).toBeNull(); }); it('runs explicit rule ids instead of tags, because axe runOnly holds only one of them', async () => { - resetBuilderCalls(); - await runAxeScan({} as any, { tags: ['wcag2aa'], rules: ['image-alt', 'label'] }); - expect(builderCalls.withRules).toEqual([['image-alt', 'label']]); - // withTags would overwrite the rule list in axe's single runOnly slot. - expect(builderCalls.withTags).toEqual([]); + resetScan(); + await runAxeScan(pageWithSelectorCounts(), { tags: ['wcag2aa'], rules: ['image-alt', 'label'] }); + // A tag list would overwrite the rule list in axe's single runOnly slot. + expect(lastScan?.options).toEqual({ runOnly: { type: 'rule', values: ['image-alt', 'label'] } }); }); it('rejects an explicitly empty rule list instead of silently scanning the full tag set', async () => { - resetBuilderCalls(); + resetScan(); // "Run only these rules: none" is a contradiction; falling back to tags // would scan far more than the caller asked for. - await expect(runAxeScan({} as any, { tags: ['wcag2aa'], rules: [] })) + await expect(runAxeScan(pageWithSelectorCounts(), { tags: ['wcag2aa'], rules: [] })) .rejects.toThrow(/withRules is an empty list/); - expect(builderCalls.withTags).toEqual([]); - expect(builderCalls.withRules).toEqual([]); + expect(lastScan).toBeUndefined(); }); it('rejects an empty withRules list at the schema layer too', () => { @@ -185,55 +207,55 @@ describe('axe helpers', () => { }); it('composes disableRules with tags', async () => { - resetBuilderCalls(); - await runAxeScan({} as any, { tags: ['wcag2aa'], disableRules: ['color-contrast'] }); - expect(builderCalls.withTags).toEqual([['wcag2aa']]); - expect(builderCalls.disableRules).toEqual([['color-contrast']]); + resetScan(); + await runAxeScan(pageWithSelectorCounts(), { tags: ['wcag2aa'], disableRules: ['color-contrast'] }); + expect(lastScan?.options).toEqual({ + runOnly: { type: 'tag', values: ['wcag2aa'] }, + rules: { 'color-contrast': { enabled: false } }, + }); }); it('subtracts disableRules from an explicit rule list rather than relying on axe', async () => { - resetBuilderCalls(); + resetScan(); // axe ignores the per-rule enabled flag once runOnly holds a rule list, so // passing both through would still have run `label`. - await runAxeScan({} as any, { rules: ['image-alt', 'label'], disableRules: ['label'] }); - expect(builderCalls.withRules).toEqual([['image-alt']]); - expect(builderCalls.disableRules).toEqual([]); + await runAxeScan(pageWithSelectorCounts(), { rules: ['image-alt', 'label'], disableRules: ['label'] }); + expect(lastScan?.options).toEqual({ runOnly: { type: 'rule', values: ['image-alt'] } }); }); it('refuses a rule list that disableRules empties, instead of silently scanning everything', async () => { - resetBuilderCalls(); - await expect(runAxeScan({} as any, { rules: ['image-alt'], disableRules: ['image-alt'] })) + resetScan(); + await expect(runAxeScan(pageWithSelectorCounts(), { rules: ['image-alt'], disableRules: ['image-alt'] })) .rejects.toThrow(/disableRules disabled every rule in withRules \(image-alt\)/); - expect(builderCalls.withRules).toEqual([]); - expect(builderCalls.withTags).toEqual([]); + expect(lastScan).toBeUndefined(); }); it('rejects an unknown rule id in withRules instead of scanning nothing', async () => { - resetBuilderCalls(); - await expect(runAxeScan({} as any, { rules: ['image-alt', 'image-altt'] })) + resetScan(); + await expect(runAxeScan(pageWithSelectorCounts(), { rules: ['image-alt', 'image-altt'] })) .rejects.toThrow(/Unknown Axe rule id\(s\) in withRules: image-altt/); - expect(builderCalls.withRules).toEqual([]); + expect(lastScan).toBeUndefined(); }); it('rejects an unknown rule id in disableRules instead of disabling nothing', async () => { - resetBuilderCalls(); - await expect(runAxeScan({} as any, { disableRules: ['colour-contrast'] })) + resetScan(); + await expect(runAxeScan(pageWithSelectorCounts(), { disableRules: ['colour-contrast'] })) .rejects.toThrow(/Unknown Axe rule id\(s\) in disableRules: colour-contrast/); - expect(builderCalls.disableRules).toEqual([]); + expect(lastScan).toBeUndefined(); }); it('validates rule ids before touching the page, so a bad id cannot cost a scan', async () => { - resetBuilderCalls(); + resetScan(); const page = { evaluate: () => { throw new Error('page should not be touched'); } } as any; await expect(runAxeScan(page, { rules: ['nope'], include: ['#content'] })) .rejects.toThrow(/Unknown Axe rule id/); }); it('accepts every rule id axe-core actually ships', async () => { - resetBuilderCalls(); + resetScan(); // Guards against the catalogue check drifting from the injected axe build. - await runAxeScan({} as any, { rules: ['color-contrast', 'region', 'frame-tested', 'aria-allowed-attr'] }); - expect(builderCalls.withRules[0]).toHaveLength(4); + await runAxeScan(pageWithSelectorCounts(), { rules: ['color-contrast', 'region', 'frame-tested', 'aria-allowed-attr'] }); + expect(lastScan?.options.runOnly.values).toHaveLength(4); }); it('validates rule options without a page, so crawlers can check them before navigating', () => { @@ -249,9 +271,9 @@ describe('axe helpers', () => { .toThrow(/disableRules disabled every rule in withRules \(image-alt\)/); }); - it('validates rule ids against the exact axe-core build @axe-core/playwright injects', async () => { - // The catalogue check is only meaningful while both resolve to one version, - // which is why package.json pins axe-core exactly. + it('validates rule ids against the exact axe-core build it injects', async () => { + // The rule catalogue and the injected source are the same module, and the + // exact pin keeps a lockfile-less install from resolving a different one. const [ownPackage, installedAxeCore] = await Promise.all([ import('../package.json', { with: { type: 'json' } }), import('axe-core/package.json', { with: { type: 'json' } }), @@ -259,20 +281,6 @@ describe('axe helpers', () => { expect(ownPackage.default.dependencies['axe-core']).toBe(installedAxeCore.default.version); }); - it('pins @axe-core/playwright exactly so a newer wrapper cannot nest a different axe-core', async () => { - // A ranged wrapper could resolve to a newer release on a clean install and - // bring its own nested axe-core; validation would then use one catalogue - // while AxeBuilder injects another. The exact pin makes the two axe-core - // requirements (ours and the wrapper's) meet in a single resolved copy. - const ownPackage = await import('../package.json', { with: { type: 'json' } }); - // The wrapper's exports map hides its package.json from import(), so read it. - const installedWrapper = JSON.parse(fs.readFileSync( - fileURLToPath(new URL('../node_modules/@axe-core/playwright/package.json', import.meta.url)), 'utf-8')); - expect(ownPackage.default.dependencies['@axe-core/playwright']).toBe(installedWrapper.version); - // The proof that nothing nested: the wrapper has no private axe-core copy. - expect(fs.existsSync(fileURLToPath(new URL('../node_modules/@axe-core/playwright/node_modules/axe-core', import.meta.url)))).toBe(false); - }); - it('documents the codegen command with the pinned Playwright version', async () => { // The recorded storage state should come from the same Playwright the // server replays it with, and an unpinned npx command resolves whatever is @@ -288,30 +296,29 @@ describe('axe helpers', () => { } }); - it('applies include and exclude selectors to the builder', async () => { - resetBuilderCalls(); + it('applies include and exclude selectors as the scan context', async () => { + resetScan(); await runAxeScan(pageWithSelectorCounts({ '#checkout': 1, '#summary': 2, '#cookie-banner': 1 }), { tags: ['wcag2aa'], include: ['#checkout', '#summary'], exclude: ['#cookie-banner'], }); - expect(builderCalls.withTags).toEqual([['wcag2aa']]); - expect(builderCalls.include).toEqual(['#checkout', '#summary']); - expect(builderCalls.exclude).toEqual(['#cookie-banner']); + expect(lastScan?.options).toEqual({ runOnly: { type: 'tag', values: ['wcag2aa'] } }); + expect(lastScan?.context).toEqual({ include: ['#checkout', '#summary'], exclude: ['#cookie-banner'] }); }); it('fails instead of silently narrowing when one of several include selectors matches nothing', async () => { - resetBuilderCalls(); + resetScan(); // Axe itself only errors when the whole include set is empty, so this is // the case that would otherwise produce a clean but half-scoped report. await expect(runAxeScan(pageWithSelectorCounts({ '#checkout': 1, '#billing-summry': 0 }), { include: ['#checkout', '#billing-summry'], })).rejects.toThrow(/No elements matched includeSelectors: #billing-summry/); - expect(builderCalls.include).toEqual([]); + expect(lastScan).toBeUndefined(); }); it('rejects CSS the browser cannot parse, for includes and excludes alike', async () => { - resetBuilderCalls(); + resetScan(); await expect(runAxeScan(pageWithSelectorCounts({ '#ok': 1, ':::bad': -1 }), { include: ['#ok'], exclude: [':::bad'], @@ -319,17 +326,407 @@ describe('axe helpers', () => { }); it('allows an exclude selector that matches nothing on this page', async () => { - resetBuilderCalls(); + resetScan(); // A crawl legitimately hits pages without the excluded widget. await runAxeScan(pageWithSelectorCounts({ '#cookie-banner': 0 }), { exclude: ['#cookie-banner'] }); - expect(builderCalls.exclude).toEqual(['#cookie-banner']); + expect(lastScan?.context).toEqual({ include: [], exclude: ['#cookie-banner'] }); + }); + + it('reports a child frame Axe could not be installed in, rather than scanning around it', async () => { + resetScan(); + // A frame that navigates mid-injection contributes no violations, and a + // report that stays silent about it reads as a clean scan of the whole page. + const broken = makeFrame({}, 'https://example.com/widget', false); + const result = await runAxeScan(pageWithSelectorCounts({}, [broken])); + + expect(result.unscannedFrames).toEqual(['https://example.com/widget']); + }); + + it('reports a failed frame whatever its URL scheme', async () => { + resetScan(); + // A srcdoc or scripted about:blank frame reports "about:blank" while holding + // a whole document, and injection into a genuinely empty one succeeds - so a + // frame that failed is worth reporting regardless of scheme. + const srcdoc = makeFrame({}, 'about:blank', false, 'promo'); + const result = await runAxeScan(pageWithSelectorCounts({}, [srcdoc])); + + expect(result.unscannedFrames).toEqual(['about:blank (name="promo")']); + }); + + it('falls back to the URL alone for an unnamed failed frame', async () => { + resetScan(); + const unnamed = makeFrame({}, '', false); + const result = await runAxeScan(pageWithSelectorCounts({}, [unnamed])); + + expect(result.unscannedFrames).toEqual(['about:blank']); + }); + + it('reports no unscanned frames when every injection succeeds', async () => { + resetScan(); + const healthy = makeFrame({}, 'https://example.com/widget', true); + const result = await runAxeScan(pageWithSelectorCounts({}, [healthy])); + + expect(result.unscannedFrames).toEqual([]); + }); + + it('reports an injected frame that Axe cannot reach through a closed shadow root', async () => { + resetScan(); + const closedShadow = makeFrame({}, 'https://example.com/closed-shadow', true, '', true, { + included: true, + excluded: false, + reachable: false, + }); + const result = await runAxeScan(pageWithSelectorCounts({}, [closedShadow])); + + expect(result.unscannedFrames).toEqual(['https://example.com/closed-shadow']); + }); + + it('reports a frame that took the injection and then navigated away from it', async () => { + resetScan(); + // A frame that navigates while a slower sibling is still injecting has a new + // document with no Axe in it, so the run below silently skips it. The + // coverage check runs against the frames as they are, not against what the + // injection returned. + const navigated = makeFrame({}, 'https://example.com/widget', true, '', false); + const result = await runAxeScan(pageWithSelectorCounts({}, [navigated])); + + expect(result.unscannedFrames).toEqual(['https://example.com/widget']); + }); + + it('rechecks a frame that navigates during its reachability probe', async () => { + resetScan(); + const navigated = makeFrame({}, 'https://example.com/widget'); + const evaluate = navigated.evaluate; + let navigatedAway = false; + navigated.evaluate = async (script: unknown, arg?: unknown) => + arg && typeof arg === 'object' && 'token' in arg && navigatedAway ? false : evaluate(script, arg); + navigated.frameElement = async () => ({ + evaluate: async () => { + navigatedAway = true; + return true; + }, + dispose: async () => undefined, + }); + + expect((await runAxeScan(pageWithSelectorCounts({}, [navigated]))).unscannedFrames) + .toEqual(['https://example.com/widget']); + }); + + it('does not report a failed frame that detached during coverage checks', async () => { + resetScan(); + const detached = makeFrame({}, 'https://example.com/widget', false); + const page = pageWithSelectorCounts({}, [detached]); + const mainFrame = page.mainFrame(); + let reads = 0; + page.frames = () => ++reads < 3 ? [mainFrame, detached] : [mainFrame]; + + expect((await runAxeScan(page)).unscannedFrames).toEqual([]); + }); + + it('reports a replacement frame that attaches during coverage checks', async () => { + resetScan(); + const detached = makeFrame({}, 'https://example.com/old', false); + const replacement = makeFrame({}, 'https://example.com/replacement', false); + const page = pageWithSelectorCounts({}, [detached]); + const mainFrame = page.mainFrame(); + replacement.parentFrame = () => mainFrame; + let reads = 0; + page.frames = () => ++reads < 4 ? [mainFrame, detached] : [mainFrame, replacement]; + + expect((await runAxeScan(page)).unscannedFrames).toEqual(['https://example.com/replacement']); + }); + + it('does not report an excluded replacement frame that attaches during coverage checks', async () => { + resetScan(); + const detached = makeFrame({}, 'https://example.com/old', false); + const replacement = makeFrame({}, 'https://example.com/replacement', false, '', true, { + included: true, + excluded: true, + }); + const page = pageWithSelectorCounts({}, [detached]); + const mainFrame = page.mainFrame(); + replacement.parentFrame = () => mainFrame; + let reads = 0; + page.frames = () => ++reads < 4 ? [mainFrame, detached] : [mainFrame, replacement]; + + expect((await runAxeScan(page, { exclude: ['iframe.widget'] })).unscannedFrames).toEqual([]); + }); + + it('fails instead of reporting complete coverage when frames keep changing', async () => { + resetScan(); + const frames = Array.from({ length: 9 }, (_, index) => makeFrame({}, `https://example.com/${index}`, false)); + const page = pageWithSelectorCounts({}, [frames[0]]); + const mainFrame = page.mainFrame(); + frames.forEach(frame => frame.parentFrame = () => mainFrame); + let reads = 0; + page.frames = () => [mainFrame, frames[Math.min(reads++, frames.length - 1)]]; + + await expect(runAxeScan(page)).rejects.toThrow(/frame tree kept changing/); + }); + + it('fails when frame replacements repeat the same transition', async () => { + resetScan(); + const frames = [makeFrame({}, 'https://example.com/a', false), makeFrame({}, 'https://example.com/b', false)]; + const page = pageWithSelectorCounts({}, frames); + const mainFrame = page.mainFrame(); + frames.forEach(frame => frame.parentFrame = () => mainFrame); + const snapshots = [frames[0], frames[0], frames[0], frames[1], frames[1], frames[0], frames[0], frames[1], frames[1]]; + let reads = 0; + page.frames = () => [mainFrame, snapshots[Math.min(reads++, snapshots.length - 1)]]; + + await expect(runAxeScan(page)).rejects.toThrow(/frame tree kept changing/); + }); + + it('limits concurrent coverage and scope probes', async () => { + resetScan(); + let activeCoverage = 0; + let activeScope = 0; + let maxCoverage = 0; + let maxScope = 0; + const pause = () => new Promise(resolve => setTimeout(resolve, 5)); + const frames = Array.from({ length: 8 }, (_, index) => { + const frame = makeFrame({}, `https://example.com/${index}`); + const evaluate = frame.evaluate; + frame.evaluate = async (script: unknown, arg?: unknown) => { + if (arg && typeof arg === 'object' && 'token' in arg) { + maxCoverage = Math.max(maxCoverage, ++activeCoverage); + await pause(); + activeCoverage--; + } + return evaluate(script, arg); + }; + frame.frameElement = async () => ({ + evaluate: async (_script: unknown, arg?: unknown) => { + if (arg === undefined) + return false; + maxScope = Math.max(maxScope, ++activeScope); + await pause(); + activeScope--; + return { included: true, excluded: false, hidden: false }; + }, + dispose: async () => undefined, + }); + return frame; + }); + + expect((await runAxeScan(pageWithSelectorCounts({}, frames))).unscannedFrames).toHaveLength(frames.length); + expect({ maxCoverage, maxScope }).toEqual({ maxCoverage: 4, maxScope: 4 }); + }); + + it('does not accept a readiness marker left by an earlier scan', async () => { + resetScan(); + const stale = makeFrame({}, 'https://example.com/widget'); + const evaluate = stale.evaluate; + let injections = 0; + stale.evaluate = async (script: unknown, arg?: unknown) => { + if (typeof script === 'string' && ++injections === 2) + return new Promise(() => {}); + return evaluate(script, arg); + }; + const page = pageWithSelectorCounts({}, [stale]); + + expect((await runAxeScan(page)).unscannedFrames).toEqual([]); + expect((await runAxeScan(page)).unscannedFrames).toEqual(['https://example.com/widget']); + }); + + it('reports a frame carrying only the page own Axe, not this injection', async () => { + resetScan(); + // Same version, but no marker: the page's own instance is not configured + // with allowedOrigins, so the top-level run's ping goes unanswered and the + // frame contributes nothing. It must not read as covered. + const pageOwned = makeFrame({}, 'https://example.com/widget'); + pageOwned.evaluate = async (script: unknown, arg?: unknown) => { + if (typeof script === 'string') + return undefined; + // Answers a bare `window.axe.version` probe, but not the marker. + if (typeof arg === 'string') + return undefined; + return undefined; + }; + const result = await runAxeScan(pageWithSelectorCounts({}, [pageOwned])); + + expect(result.unscannedFrames).toEqual(['https://example.com/widget']); + }); + + it('caps and truncates an author-controlled frame name', async () => { + resetScan(); + // The name attribute is author-controlled and unbounded, and can carry a + // data URL of its own. + const noisy = makeFrame({}, 'https://example.com/widget', false, `promo data:text/html;base64,${'A'.repeat(4000)}`); + const result = await runAxeScan(pageWithSelectorCounts({}, [noisy])); + + expect(result.unscannedFrames).toEqual(['https://example.com/widget (name="promo data:text/html;base64,...")']); + }); + + it('counts every failed frame, even when they describe identically', async () => { + resetScan(); + // Two unnamed about:blank frames are two documents that went unscanned; + // collapsing them would under-count the coverage gap. + const first = makeFrame({}, 'about:blank', false); + const second = makeFrame({}, 'about:blank', false); + const result = await runAxeScan(pageWithSelectorCounts({}, [first, second])); + + expect(result.unscannedFrames).toEqual(['about:blank', 'about:blank']); + }); + + it('truncates a data URL frame rather than echoing the whole document', async () => { + resetScan(); + // A data: frame's URL is its document, and this string reaches tool text, + // structured content and the JSON reports. + const payload = 'A'.repeat(5000); + const dataFrame = makeFrame({}, `data:text/html;base64,${payload}`, false); + const result = await runAxeScan(pageWithSelectorCounts({}, [dataFrame])); + + expect(result.unscannedFrames).toEqual(['data:text/html;base64,...']); + }); + + it('truncates a data URL embedded in a failed frame URL', async () => { + resetScan(); + const payload = 'A'.repeat(5000); + const frame = makeFrame({}, `https://example.com/frame?src=data:text/html;base64,${payload}`, false); + const result = await runAxeScan(pageWithSelectorCounts({}, [frame])); + + expect(result.unscannedFrames).toEqual(['https://example.com/frame?src=data:text/html;base64,...']); + }); + + it('caps an ordinary failed frame URL', async () => { + resetScan(); + const frame = makeFrame({}, `https://example.com/frame?value=${'A'.repeat(5000)}`, false); + const [url] = (await runAxeScan(pageWithSelectorCounts({}, [frame]))).unscannedFrames; + + expect(url).toHaveLength(2048); + expect(url).toMatch(/^https:\/\/example\.com\/frame\?value=A+\.\.\.$/); + }); + + it('does not warn about a failed frame hidden from the accessibility tree', async () => { + resetScan(); + const hidden = makeFrame({}, 'https://example.com/hidden', false, '', true, { + included: true, + excluded: false, + hidden: true, + }); + const result = await runAxeScan(pageWithSelectorCounts({}, [hidden])); + + expect(result.unscannedFrames).toEqual([]); + }); + + it('warns about a failed hidden-until-found frame that Axe still traverses', async () => { + resetScan(); + const untilFound = makeFrame({}, 'https://example.com/until-found', false, '', true, { + included: true, + excluded: false, + hidden: false, + }); + const result = await runAxeScan(pageWithSelectorCounts({}, [untilFound])); + + expect(result.unscannedFrames).toEqual(['https://example.com/until-found']); + }); + + it('warns about a failed slotted frame inside a shadow-root modal', async () => { + resetScan(); + const slotted = makeFrame({}, 'https://example.com/slotted-modal', false, '', true, { + included: true, + excluded: false, + hidden: false, + }); + const result = await runAxeScan(pageWithSelectorCounts({}, [slotted])); + + expect(result.unscannedFrames).toEqual(['https://example.com/slotted-modal']); + }); + + it('does not warn about a frame the caller scoped out of the scan', async () => { + resetScan(); + // excludeSelectors: ["iframe.chat-widget"] is the documented way to drop a + // flaky third-party widget. Warning that the widget went unscanned would be + // a false alarm about content the caller removed on purpose. + const excluded = makeFrame({ '#main': 1, 'iframe.chat-widget': 1 }, 'https://widget.example/', false, '', true, { included: false, excluded: true }); + const result = await runAxeScan( + pageWithSelectorCounts({ '#main': 1, 'iframe.chat-widget': 1 }, [excluded]), + { exclude: ['iframe.chat-widget'] }, + ); + + expect(result.unscannedFrames).toEqual([]); + }); + + it('still warns about an in-scope frame when a scope is set', async () => { + resetScan(); + const inScope = makeFrame({ '#main': 1 }, 'https://widget.example/', false, '', true, { included: true, excluded: false }); + const result = await runAxeScan( + pageWithSelectorCounts({ '#main': 1 }, [inScope]), + { include: ['#main'] }, + ); + + expect(result.unscannedFrames).toEqual(['https://widget.example/']); + }); + + it('keeps a nested frame in scope when the include names an ancestor frame', async () => { + resetScan(); + // #main holds iframe A, which holds iframe B. B's own iframe element lives + // in A's document, where `closest('#main')` cannot reach - but Axe's context + // descends into B all the same, so a failed B is a real coverage gap. + const outer = makeFrame({ '#main': 1 }, 'https://example.com/outer', true, '', true, { included: true, excluded: false }); + const nested = makeFrame({ '#main': 1 }, 'https://example.com/nested', false, '', true, { included: false, excluded: false }); + nested.parentFrame = () => outer as any; + + const result = await runAxeScan( + pageWithSelectorCounts({ '#main': 1 }, [outer, nested]), + { include: ['#main'] }, + ); + + expect(result.unscannedFrames).toEqual(['https://example.com/nested']); + }); + + it('reports a nested frame whose ancestor never got Axe', async () => { + resetScan(); + // The nested frame took the injection fine, but the top-level run reaches it + // only by relaying through the outer frame, and a frame without Axe relays + // nothing. Both documents go unscanned, so both have to be listed. + const outer = makeFrame({}, 'https://example.com/outer', false); + const nested = makeFrame({}, 'https://example.com/nested', true); + nested.parentFrame = () => outer as any; + + const result = await runAxeScan(pageWithSelectorCounts({}, [outer, nested])); + + expect(result.unscannedFrames).toEqual([ + 'https://example.com/outer', + 'https://example.com/nested', + ]); + }); + + it('drops a nested frame when an ancestor frame is excluded', async () => { + resetScan(); + // The mirror case: excluding the outer frame removes everything below it, + // so warning about the nested document would be the same false alarm. + const outer = makeFrame({ 'iframe.widget': 1 }, 'https://example.com/outer', true, '', true, { included: false, excluded: true }); + const nested = makeFrame({ 'iframe.widget': 1 }, 'https://example.com/nested', false, '', true, { included: false, excluded: false }); + nested.parentFrame = () => outer as any; + + const result = await runAxeScan( + pageWithSelectorCounts({ 'iframe.widget': 1 }, [outer, nested]), + { exclude: ['iframe.widget'] }, + ); + + expect(result.unscannedFrames).toEqual([]); + }); + + it('does not reapply a flat exclude selector inside a descendant document', async () => { + resetScan(); + const outer = makeFrame({}, 'https://example.com/outer', true, '', true, { included: false, excluded: false }); + const nested = makeFrame({}, 'https://example.com/nested', false, '', true, { included: false, excluded: true }); + nested.parentFrame = () => outer as any; + + const result = await runAxeScan(pageWithSelectorCounts({ '.widget': 1 }, [outer, nested]), { + exclude: ['.widget'], + }); + + expect(result.unscannedFrames).toEqual(['https://example.com/nested']); }); it('rethrows scan failures untouched', async () => { - resetBuilderCalls(); - const failure = new Error('axe injection failed'); - analyzeResult = failure; - await expect(runAxeScan({} as any)).rejects.toBe(failure); + resetScan(); + const failure = new Error('axe run failed'); + scanResult = failure; + await expect(runAxeScan(pageWithSelectorCounts())).rejects.toBe(failure); }); it('summarizes counts by impact and rule id', () => { @@ -344,3 +741,57 @@ describe('axe helpers', () => { }); }); }); + +describe.skipIf(!fs.existsSync(chromium.executablePath()))('axe frame coverage in a real browser', () => { + it('reports a hidden iframe made visible by author CSS outside a CSS-hidden modal', async () => { + const browser = await chromium.launch({ headless: true, chromiumSandbox: false }); + try { + const page = await browser.newPage(); + await page.setContent('
    '); + const loaded = page.waitForEvent('framenavigated', frame => frame.url() === 'about:srcdoc'); + await page.evaluate(() => { + const dialog = document.createElement('dialog'); + document.body.append(dialog); + dialog.showModal(); + dialog.style.opacity = '0'; + const root = document.querySelector('#host')!.attachShadow({ mode: 'closed' }); + const style = document.createElement('style'); + style.textContent = 'iframe[hidden]{display:block}'; + const frame = document.createElement('iframe'); + frame.hidden = true; + frame.srcdoc = ''; + root.append(style, frame); + }); + await loaded; + + expect((await runAxeScan(page)).unscannedFrames).toEqual(['about:srcdoc']); + } finally { + await browser.close(); + } + }); + + it('reports a frame inside the first slotted summary of closed details', async () => { + const browser = await chromium.launch({ headless: true, chromiumSandbox: false }); + try { + const page = await browser.newPage(); + await page.setContent('
    '); + const loaded = page.waitForEvent('framenavigated', frame => frame.url() === 'about:srcdoc'); + await page.evaluate(() => { + const host = document.querySelector('#host')!; + host.attachShadow({ mode: 'closed' }).innerHTML = '
    '; + const summary = document.createElement('summary'); + const innerHost = document.createElement('span'); + const frame = document.createElement('iframe'); + frame.srcdoc = ''; + innerHost.attachShadow({ mode: 'closed' }).append(frame); + summary.append(innerHost); + host.append(summary); + }); + await loaded; + + expect((await runAxeScan(page)).unscannedFrames).toEqual(['about:srcdoc']); + } finally { + await browser.close(); + } + }); +}); diff --git a/tests/tools-scanPageMatrix.test.ts b/tests/tools-scanPageMatrix.test.ts index 68f728de..3054ee38 100644 --- a/tests/tools-scanPageMatrix.test.ts +++ b/tests/tools-scanPageMatrix.test.ts @@ -4,6 +4,21 @@ import scanPageMatrixTools from '../src/tools/scanPageMatrix.js'; import { Response } from '../src/response.js'; import * as axe from '../src/tools/axe.js'; +// The page's media emulation as an unconfigured browser reports it. Variants +// fall back to this rather than to null, so emulation the session was created +// with survives both the scan and the restore. +const defaultMedia = { + colorScheme: 'light', + forcedColors: 'none', + contrast: 'no-preference', + reducedMotion: 'no-preference', +}; + +// What the single setup evaluate returns: the page's zoom and media state. +function pageState(zoom = '', media: Record = {}) { + return { zoom, media: { ...defaultMedia, ...media } }; +} + function createViolation(id: string) { return { id, @@ -29,6 +44,7 @@ function createAxeResult(url: string, violationIds: string[], incompleteIds: str incomplete: incompleteIds.map(id => createViolation(id)), passes: [], inapplicable: [], + unscannedFrames: [], } as any; } @@ -38,7 +54,7 @@ function createMatrixHarness(outputFile: string) { viewportSize: vi.fn(() => ({ width: 1024, height: 768 })), setViewportSize: vi.fn(async () => undefined), emulateMedia: vi.fn(async () => undefined), - evaluate: vi.fn().mockResolvedValueOnce('').mockResolvedValue(undefined), + evaluate: vi.fn().mockResolvedValueOnce(pageState('')).mockResolvedValue(undefined), reload: vi.fn(async () => undefined), }; const mockTab = { @@ -154,7 +170,7 @@ describe('scan_page_matrix tool', () => { it('runs variants in baseline-first order and computes baseline diffs', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { @@ -214,7 +230,7 @@ describe('scan_page_matrix tool', () => { it('restores viewport, media emulation, and zoom in finally', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('150%') + .mockResolvedValueOnce(pageState('150%')) .mockResolvedValue(undefined); const mockPage = { @@ -257,18 +273,164 @@ describe('scan_page_matrix tool', () => { const lastEvaluateCall = mockPage.evaluate.mock.calls.at(-1); expect(lastViewportCall?.[0]).toEqual({ width: 1280, height: 720 }); - expect(lastMediaCall?.[0]).toEqual({ - colorScheme: null, - forcedColors: null, - contrast: null, - reducedMotion: null, - }); + expect(lastMediaCall?.[0]).toEqual(defaultMedia); expect(lastEvaluateCall?.[1]).toBe('150%'); }); + it('keeps the session’s own media emulation across the scan', async () => { + // A context created with colorScheme "dark" is the state this page is meant + // to be audited in. Passing null for the properties a variant leaves unset + // resets them to the browser default instead, so the baseline would be + // scanned light and the page would stay light after the tool returned. + const configured = { colorScheme: 'dark', reducedMotion: 'reduce' }; + const { context, mockPage, response } = createMatrixHarness('/tmp/scan-configured-media.json'); + mockPage.evaluate = vi.fn() + .mockResolvedValueOnce(pageState('', configured)) + .mockResolvedValue(undefined) as any; + + vi.spyOn(axe, 'runAxeScan').mockResolvedValue(createAxeResult('https://example.com/page', [])); + + await tool.handle(context as any, { + variants: [{ name: 'baseline' }, { name: 'forced-colors', media: { forcedColors: 'active' } }], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterApplyMs: 0, + reloadBetweenVariants: false, + } as any, response); + + const media = { ...defaultMedia, ...configured }; + // The baseline variant sets nothing of its own, so it runs as configured. + expect(mockPage.emulateMedia.mock.calls[0][0]).toEqual(media); + // A variant overrides only the property it names. + expect(mockPage.emulateMedia.mock.calls[1][0]).toEqual({ ...media, forcedColors: 'active' }); + // And the page is handed back in the state it arrived in. + expect(mockPage.emulateMedia.mock.calls.at(-1)?.[0]).toEqual(media); + + const report = JSON.parse(writeFileSpy.mock.calls[0][1] as string); + expect(report.variants[0].applied.media.colorScheme).toBe('dark'); + }); + + it('reports no baseline delta when the two scans covered different documents', async () => { + // A rule missing from a variant whose iframe went unscanned has not been + // "resolved" - the document it lives in was never looked at. Reporting that + // as a delta states an accessibility outcome the run cannot support. + const { context, response } = createMatrixHarness('/tmp/scan-partial-delta.json'); + vi.spyOn(axe, 'runAxeScan') + .mockResolvedValueOnce(createAxeResult('https://example.com/page', ['color-contrast', 'label'])) + .mockResolvedValueOnce({ + ...createAxeResult('https://example.com/page', ['color-contrast']), + unscannedFrames: ['https://widget.example/'], + } as any); + + await tool.handle(context as any, { + variants: [{ name: 'baseline' }, { name: 'mobile', viewport: { width: 375, height: 812 } }], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterApplyMs: 0, + reloadBetweenVariants: false, + } as any, response); + + const report = JSON.parse(writeFileSpy.mock.calls[0][1] as string); + expect(report.version).toBe('v2'); + // The baseline itself was fully covered, so it still compares with itself. + expect(report.variants[0].diffFromBaseline).not.toBeNull(); + // "label" is absent from the variant only because a frame went unscanned. + expect(report.variants[1].diffFromBaseline).toBeNull(); + + const structured = response.structuredContent() as any; + expect(structured.version).toBe('v2'); + // null, not [] - an empty list would read as "compared, nothing changed". + expect(structured.variants[1].resolvedViolationIds).toBeNull(); + expect(structured.variants[1].newViolationIds).toBeNull(); + expect(structured.variants[1].changedRuleIds).toBeNull(); + expect(response.result()).toContain('n/a (coverage differs)'); + }); + + it('reports no delta on a complete variant when the baseline is the incomplete one', async () => { + // The mirror of the case above. A fully scanned variant still cannot be + // compared against a baseline that missed a frame, and the reason must not + // read as though this variant were the partial one - the gap is upstream. + const { context, response } = createMatrixHarness('/tmp/scan-partial-baseline.json'); + vi.spyOn(axe, 'runAxeScan') + .mockResolvedValueOnce({ + ...createAxeResult('https://example.com/page', ['color-contrast']), + unscannedFrames: ['https://widget.example/'], + } as any) + .mockResolvedValueOnce(createAxeResult('https://example.com/page', ['color-contrast'])); + + await tool.handle(context as any, { + variants: [{ name: 'baseline' }, { name: 'mobile', viewport: { width: 375, height: 812 } }], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterApplyMs: 0, + reloadBetweenVariants: false, + } as any, response); + + const report = JSON.parse(writeFileSpy.mock.calls[0][1] as string); + // Neither row is comparable: the baseline is the one with the gap. + expect(report.variants[0].diffFromBaseline).toBeNull(); + expect(report.variants[1].diffFromBaseline).toBeNull(); + expect(report.variants[1].unscannedFrames).toEqual([]); + + const structured = response.structuredContent() as any; + expect(structured.variants[1].newViolationIds).toBeNull(); + // The wording must not blame the variant for the baseline's missing frame. + expect(response.result()).not.toContain('partial scan'); + expect(response.result()).toContain('n/a (coverage differs)'); + }); + + it('leaves an unnameable color scheme un-emulated rather than pinning it light', async () => { + // If neither media query matches, the page is in a state emulateMedia + // cannot name. Recording it as "light" would emulate a preference the page + // never had, and leave it emulated after the tool returned. + const { context, mockPage, response } = createMatrixHarness('/tmp/scan-unnamed-scheme.json'); + mockPage.evaluate = vi.fn() + .mockResolvedValueOnce(pageState('', { colorScheme: null })) + .mockResolvedValue(undefined) as any; + + vi.spyOn(axe, 'runAxeScan').mockResolvedValue(createAxeResult('https://example.com/page', [])); + + await tool.handle(context as any, { + variants: [{ name: 'baseline' }], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterApplyMs: 0, + reloadBetweenVariants: false, + } as any, response); + + expect(mockPage.emulateMedia.mock.calls[0][0].colorScheme).toBeNull(); + expect(mockPage.emulateMedia.mock.calls.at(-1)?.[0].colorScheme).toBeNull(); + }); + + it('applies zoom after a reload, not before it', async () => { + // Zoom is an inline style on documentElement, so a reload discards it while + // the viewport and media emulation survive. Applying it first would scan the + // variant unzoomed while applied.zoomPercent still claimed 200. + const { context, mockPage, response } = createMatrixHarness('/tmp/scan-reload-zoom.json'); + vi.spyOn(axe, 'runAxeScan').mockResolvedValue(createAxeResult('https://example.com/page', [])); + + await tool.handle(context as any, { + variants: [{ name: 'zoom-200', zoomPercent: 200 }], + violationsTag: ['wcag2aa'], + includeIncomplete: false, + maxNodesPerViolation: 10, + waitAfterApplyMs: 0, + reloadBetweenVariants: true, + } as any, response); + + const zoomCallIndex = mockPage.evaluate.mock.calls.findIndex(call => call[1] === '200%'); + expect(zoomCallIndex).toBeGreaterThan(-1); + expect(mockPage.evaluate.mock.invocationCallOrder[zoomCallIndex]) + .toBeGreaterThan(mockPage.reload.mock.invocationCallOrder[0]); + }); + it('runs only custom variants and treats first variant as baseline', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { @@ -319,7 +481,7 @@ describe('scan_page_matrix tool', () => { it('records forced-colors/contrast media and zoomPercent metadata in report', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { @@ -369,7 +531,7 @@ describe('scan_page_matrix tool', () => { it('reloads page between variants when reloadBetweenVariants=true', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { @@ -413,7 +575,7 @@ describe('scan_page_matrix tool', () => { it('restores page state even when axe scan fails mid-run', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('125%') + .mockResolvedValueOnce(pageState('125%')) .mockResolvedValue(undefined); const mockPage = { @@ -456,18 +618,13 @@ describe('scan_page_matrix tool', () => { const lastMediaCall = mockPage.emulateMedia.mock.calls.at(-1); const lastEvaluateCall = mockPage.evaluate.mock.calls.at(-1); expect(lastViewportCall?.[0]).toEqual({ width: 1440, height: 900 }); - expect(lastMediaCall?.[0]).toEqual({ - colorScheme: null, - forcedColors: null, - contrast: null, - reducedMotion: null, - }); + expect(lastMediaCall?.[0]).toEqual(defaultMedia); expect(lastEvaluateCall?.[1]).toBe('125%'); }); it('writes report using custom reportFile name', async () => { const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { @@ -512,7 +669,7 @@ describe('scan_page_matrix tool', () => { it('emits progress notifications as variants finish', async () => { const sendNotification = vi.fn(async () => undefined); const evaluateMock = vi.fn() - .mockResolvedValueOnce('') + .mockResolvedValueOnce(pageState('')) .mockResolvedValue(undefined); const mockPage = { diff --git a/tests/tools-snapshot.test.ts b/tests/tools-snapshot.test.ts index 2329416b..3a999f9f 100644 --- a/tests/tools-snapshot.test.ts +++ b/tests/tools-snapshot.test.ts @@ -244,7 +244,7 @@ describe('Snapshot Tools', () => { const scanPageTool = snapshotTools.find(tool => tool.schema.name === 'scan_page')!; function scanResult(violations: any[], incomplete: any[] = []) { - return { url: 'https://example.com/', violations, incomplete, passes: [], inapplicable: [] } as any; + return { url: 'https://example.com/', violations, incomplete, passes: [], inapplicable: [], unscannedFrames: [] } as any; } function scanRule(id: string, nodeCount: number) { @@ -293,6 +293,39 @@ describe('Snapshot Tools', () => { }); }); + it('warns about frames the scan could not reach, naming them', async () => { + // A frame Axe never reached contributes no violations, so a silent result + // reads as a clean page rather than a partly-scanned one. + vi.spyOn(axe, 'runAxeScan').mockResolvedValue({ + ...scanResult([]), + unscannedFrames: ['https://widget.example/embed', 'about:blank (name="promo")'], + }); + const { context, response, text } = scanHarness(); + + await scanPageTool.handle(context as any, { + violationsTag: ['wcag2aa'], + includeIncomplete: true, + maxNodesPerViolation: 10, + } as any, response as any); + + expect(text()).toContain('WARNING: Axe could not be installed in 2 frame(s)'); + expect(text()).toContain('- https://widget.example/embed'); + expect(text()).toContain('- about:blank (name="promo")'); + }); + + it('says nothing about frames when the scan covered all of them', async () => { + vi.spyOn(axe, 'runAxeScan').mockResolvedValue(scanResult([])); + const { context, response, text } = scanHarness(); + + await scanPageTool.handle(context as any, { + violationsTag: ['wcag2aa'], + includeIncomplete: true, + maxNodesPerViolation: 10, + } as any, response as any); + + expect(text()).not.toContain('could not be installed'); + }); + it('reports the rule id and flags truncated node lists', async () => { vi.spyOn(axe, 'runAxeScan').mockResolvedValue(scanResult([scanRule('image-alt', 3), scanRule('label', 1)])); const { context, response, text } = scanHarness(); @@ -475,7 +508,7 @@ describe.skipIf(!fs.existsSync(chromium.executablePath()))('scan_page annotated const page = await context.newPage(); await page.setContent(html); vi.spyOn(axe, 'runAxeScan').mockResolvedValue({ - url: 'https://example.com/', violations, incomplete: [], passes: [], inapplicable: [], + url: 'https://example.com/', violations, incomplete: [], passes: [], inapplicable: [], unscannedFrames: [], } as any); const screenshot = page.screenshot.bind(page); let drawn: any; @@ -656,6 +689,7 @@ function scanHarness(options: { violations?: any[], markedNodes?: number, screen incomplete: [], passes: [], inapplicable: [], + unscannedFrames: [], } as any); const evaluate = vi.fn(async () => { diff --git a/tests/tools-utils.test.ts b/tests/tools-utils.test.ts index 1d45a8dd..6b10e002 100644 --- a/tests/tools-utils.test.ts +++ b/tests/tools-utils.test.ts @@ -57,6 +57,7 @@ describe('Tool Utils', () => { beforeEach(() => { mockPage = new EventEmitter(); mockPage.url = () => 'https://example.com'; + mockPage.isClosed = vi.fn().mockReturnValue(false); mockPage.waitForLoadState = vi.fn().mockResolvedValue(undefined); mockPage.evaluate = vi.fn().mockResolvedValue(undefined); mockPage._wrapApiCall = vi.fn().mockImplementation(cb => cb()); @@ -101,8 +102,8 @@ describe('Tool Utils', () => { await waitForCompletion(mockTab, callback); - // Should not wait for load state for sub-frames - expect(mockTab.waitForTimeout).toHaveBeenCalled(); + // Should not wait for the load state of a sub-frame navigation. + expect(mockTab.waitForLoadState).not.toHaveBeenCalled(); }); it('should timeout after 10 seconds', async () => { @@ -126,13 +127,94 @@ describe('Tool Utils', () => { vi.useRealTimers(); }); - it('should use the configured settle delay after completion', async () => { + it('should use the configured settle delay after a request', async () => { + mockTab.context.config.timeouts.settle = 25; + const callback = vi.fn().mockImplementation(() => { + const request = { url: 'https://api.example.com' }; + mockPage.emit('request', request); + mockPage.emit('requestfinished', request); + return Promise.resolve('result'); + }); + + await waitForCompletion(mockTab, callback); + + expect(mockTab.waitForTimeout).toHaveBeenCalledWith(25); + }); + + it('should preserve the settle delay for delayed DOM-only work', async () => { + // A timer can update the DOM without a request or navigation signal. + mockTab.context.config.timeouts.settle = 5; const callback = vi.fn().mockResolvedValue('result'); + + await waitForCompletion(mockTab, callback); + + expect(mockTab.waitForTimeout).toHaveBeenCalledWith(5); + }); + + it('should not fail when the action closes its page before settling', async () => { + mockTab.waitForTimeout = vi.fn().mockImplementation(async () => { + mockPage.isClosed.mockReturnValue(true); + throw new Error('page._wrapApiCall: Target page, context or browser has been closed'); + }); + + await expect(waitForCompletion(mockTab, vi.fn().mockResolvedValue('result'))).resolves.toBe('result'); + }); + + it('should not hide an unrelated settle error when the page also closes', async () => { + mockTab.waitForTimeout = vi.fn().mockImplementation(async () => { + mockPage.isClosed.mockReturnValue(true); + throw new Error('Protocol failure'); + }); + + await expect(waitForCompletion(mockTab, vi.fn().mockResolvedValue('result'))).rejects.toThrow('Protocol failure'); + }); + + it('should settle for work the action scheduled rather than started', async () => { + // A click handler whose fetch fires from a timer has issued no request by + // the time its own promise resolves; the quiet window still catches it. + mockTab.context.config.timeouts.settle = 25; + const request = { url: 'https://api.example.com' }; + const callback = vi.fn().mockImplementation(() => { + setTimeout(() => { + mockPage.emit('request', request); + mockPage.emit('requestfinished', request); + }, 5); + return Promise.resolve('result'); + }); + + await waitForCompletion(mockTab, callback); + + expect(mockTab.waitForTimeout).toHaveBeenCalledWith(25); + }); + + it('should settle after a main-frame navigation', async () => { + mockTab.context.config.timeouts.settle = 25; + const callback = vi.fn().mockImplementation(() => { + mockPage.emit('framenavigated', { parentFrame: () => null }); + return Promise.resolve('result'); + }); + + await waitForCompletion(mockTab, callback); + + expect(mockTab.waitForTimeout).toHaveBeenCalledWith(25); + }); + + it('should settle after a sub-frame navigation that issued no request', async () => { + // Swapping an iframe's srcdoc or pointing it at a data: URL replaces a + // document without touching the network, so nothing else here marks it as + // page work. Skipping the settle would capture the old frame while the + // replacement is still initializing. mockTab.context.config.timeouts.settle = 25; + const callback = vi.fn().mockImplementation(() => { + mockPage.emit('framenavigated', { parentFrame: () => ({}) }); + return Promise.resolve('result'); + }); await waitForCompletion(mockTab, callback); expect(mockTab.waitForTimeout).toHaveBeenCalledWith(25); + // Still no top-level load state: a sub-frame navigation never produces one. + expect(mockTab.waitForLoadState).not.toHaveBeenCalled(); }); }); diff --git a/tests/utils.test.ts b/tests/utils.test.ts index fa264298..78ce0c52 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -125,6 +125,17 @@ describe('Utils', () => { expect(result).not.toContain(''); }); + it('should truncate data URLs whatever the case of the scheme', () => { + expect(truncateDataUrls('- /url: DATA:TEXT/HTML;BASE64,PHAgLz4=')).toBe('- /url: DATA:TEXT/HTML;BASE64,...'); + expect(truncateDataUrls('?src=Data%3Atext/html;base64%2CPHAgLz4=')).toBe('?src=Data%3Atext/html;base64%2C...'); + }); + + it('should keep offsets correct when text before the URL lower-cases to a different length', () => { + // "İ".toLowerCase() is two code units, so matching against a lower-cased + // copy of the text would shift every later offset by one. + expect(truncateDataUrls('İ data:text/html;base64,PHAgLz4=')).toBe('İ data:text/html;base64,...'); + }); + it('should truncate data URLs embedded in query strings', () => { const payload = Buffer.from('

    hello

    ').toString('base64'); const text = `https://api.example/upload?src=data:text/html;base64,${payload}&id=123`;