chore(tooling): 对齐协作规范与浏览器验收工具

验证:713 项单测、8 视口环境、代码及格式检查通过;未运行生产构建。
This commit is contained in:
zhanjunhao
2026-11-17 14:48:50 +08:00
parent e7a7541b2b
commit 92380ebab6
30 changed files with 2089 additions and 160 deletions
+59
View File
@@ -0,0 +1,59 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。
// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。
// Use this for static review captures, not for interaction/animation tests.
export async function prepareStaticCapture(page) {
await page.evaluate(async () => {
await Promise.race([
Promise.all([
document.fonts.ready,
...[...document.images]
.filter((image) => image.currentSrc && image.checkVisibility())
.map((image) => image.decode().catch(() => {})),
]),
new Promise((_, reject) =>
setTimeout(
() =>
reject(
new Error(
'Static capture fonts/images did not settle within 10s',
),
),
10000,
),
),
]);
});
}
export const staticScreenshotOptions = {
scale: 'css',
animations: 'disabled',
caret: 'hide',
style:
'*, *::before, *::after { animation: none !important; transition: none !important; caret-color: transparent !important; }',
};
export async function captureStatic(page, options = {}) {
await prepareStaticCapture(page);
return page.screenshot({ ...options, ...staticScreenshotOptions });
}
+81
View File
@@ -0,0 +1,81 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { devices } from '@playwright/test';
import { browserStabilityArgs } from './playwright-runtime.mjs';
// The review JSON is also read by Python; keep dimensions and device choices there.
const config = JSON.parse(
readFileSync(new URL('./ui-review/config.json', import.meta.url), 'utf8'),
);
const aliases = {
'desktop-boundary': 'laptop',
'laptop-hd': 'hd',
'laptop-wxga': 'wxga',
};
export const browserChannel = config.browser.channel;
export const projectViewports = [
'desktop',
'mobile',
'tablet',
'desktop-boundary',
'laptop-hd',
'laptop-wxga',
'qhd',
'uhd',
];
export function deviceOptions(name) {
const key = aliases[name] || name;
const size = config.viewports[key];
if (!size) throw new Error(`Unknown viewport: ${name}`);
const descriptor =
devices[
config.browser[key === 'mobile' ? 'mobileDevice' : 'desktopDevice']
];
if (!descriptor) throw new Error(`Unknown device profile for ${name}`);
const { defaultBrowserType, ...context } = descriptor;
return { ...context, viewport: { width: size[0], height: size[1] } };
}
export function contextOptions(name, reducedMotion = 'reduce') {
return {
...deviceOptions(name),
locale: config.browser.locale,
timezoneId: config.browser.timezone,
colorScheme: 'light',
reducedMotion,
};
}
export function environmentFingerprint(name, reducedMotion = 'reduce') {
return createHash('sha256')
.update(
JSON.stringify({
version: 2,
channel: browserChannel,
options: contextOptions(name, reducedMotion),
launchArgs: browserStabilityArgs,
screenshotScale: 'css',
}),
)
.digest('hex');
}
+322
View File
@@ -0,0 +1,322 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 有头 Chrome 焦点守卫:唯一页面、禁止新建 / 切换标签页、后台建页兜底、前台状态检测。
// 规则见 docs/ui/GLOBAL_UI_BASELINE.md 第 7.1 节。
import { contextOptions as sharedContextOptions } from './browser-environment.mjs';
import { prepareStaticCapture } from './browser-capture.mjs';
import { browserRuntime, browserStabilityArgs } from './playwright-runtime.mjs';
import { execFile } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
export const FOCUS_SAFE_ARGS = Object.freeze([
...browserStabilityArgs,
'--window-position=-32000,-32000',
]);
export const FOCUS_EVENTS = Object.freeze({
STARTUP: '启动焦点激活事件',
STARTUP_PERSIST: '启动焦点仍保持',
REACTIVATED: '二次焦点激活',
UNKNOWN: '无法确认后台状态',
EXTRA_PAGE: '意外新页面',
FORBIDDEN: '禁止的焦点操作',
BACKGROUND_TARGET: '后台创建页面',
});
export class FocusGuardError extends Error {
constructor(message) {
super(message);
this.name = 'FocusGuardError';
}
}
export function createFocusLog(sink = console.log) {
const entries = [];
return {
entries,
record(type, detail = {}) {
const entry = { time: new Date().toISOString(), type, ...detail };
entries.push(entry);
sink(`[focus] ${type} ${JSON.stringify(detail)}`);
return entry;
},
};
}
// 在页面内拦截 window.open 与 target 非 _self 的链接,避免应用自行打开新标签页。
export const BLOCK_POPUP_SCRIPT = `(() => {
if (window.__focusGuardBlockedOpens) return;
const blocked = [];
Object.defineProperty(window, '__focusGuardBlockedOpens', { value: blocked });
window.open = function (url) {
blocked.push(String(url ?? ''));
return null;
};
const intercept = (event) => {
const anchor = event.target && event.target.closest && event.target.closest('a[target]');
if (!anchor) return;
const target = String(anchor.getAttribute('target') || '').toLowerCase();
if (!target || target === '_self' || target === '_top' || target === '_parent') return;
event.preventDefault();
blocked.push(anchor.href);
};
document.addEventListener('click', intercept, true);
document.addEventListener('auxclick', intercept, true);
})();`;
export function installFocusGuards(context, page, log) {
const browser = context.browser?.();
const forbid = (api) => async () => {
log.record(FOCUS_EVENTS.FORBIDDEN, { api });
throw new FocusGuardError(
`${api} 被焦点约束禁止:只能在唯一页面内用 goto 导航`,
);
};
const original = {
newPage: context.newPage,
bringToFront: page.bringToFront,
browserNewPage: browser?.newPage,
browserNewContext: browser?.newContext,
};
context.newPage = forbid('context.newPage');
page.bringToFront = forbid('page.bringToFront');
if (browser) {
browser.newPage = forbid('browser.newPage');
browser.newContext = forbid('browser.newContext');
}
const onPage = async (extra) => {
if (extra === page) return;
log.record(FOCUS_EVENTS.EXTRA_PAGE, { url: extra.url() });
await extra.close().catch(() => {});
};
context.on('page', onPage);
return () => {
context.off('page', onPage);
context.newPage = original.newPage;
page.bringToFront = original.bringToFront;
if (browser) {
browser.newPage = original.browserNewPage;
browser.newContext = original.browserNewContext;
}
};
}
// 状态迁移:启动阶段的激活只记录;之后仅“后台 → 前台”视为二次激活。
export function classifyFocus({ phase, previous, current }) {
if (current === 'unknown')
return { event: FOCUS_EVENTS.UNKNOWN, fatal: true };
if (current !== 'foreground') return { event: null, fatal: false };
if (phase === 'startup') return { event: FOCUS_EVENTS.STARTUP, fatal: false };
if (previous === 'foreground')
return { event: FOCUS_EVENTS.STARTUP_PERSIST, fatal: false };
return { event: FOCUS_EVENTS.REACTIVATED, fatal: true };
}
const FOREGROUND_PS = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;
Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '[DllImport("user32.dll")] public static extern System.IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(System.IntPtr h, out uint p);'
$fg = 0; [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fg)
$dir = $env:FOCUS_GUARD_PROFILE
$ids = @()
if ($dir) { $ids = @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($dir) } | ForEach-Object { $_.ProcessId }) }
Write-Output ("$fg|" + ($ids -join ','))`;
export function parseForegroundOutput(output) {
const match = /^(\d+)\|([\d,]*)$/.exec(String(output).trim());
if (!match) return { state: 'unknown', reason: 'unparsable' };
const pids = match[2] ? match[2].split(',').map(Number) : [];
if (!pids.length) return { state: 'unknown', reason: 'no-browser-process' };
return {
state: pids.includes(Number(match[1])) ? 'foreground' : 'background',
foregroundPid: Number(match[1]),
browserPids: pids,
};
}
// 只读查询系统前台窗口所属进程,并与本次 profile 启动的 chrome.exe 比对;不调用任何激活 API。
export function probeOsForeground(profileDir) {
if (process.platform !== 'win32')
return Promise.resolve({
state: 'unknown',
reason: 'unsupported-platform',
});
const encoded = Buffer.from(FOREGROUND_PS, 'utf16le').toString('base64');
return new Promise((resolve) => {
execFile(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
{
windowsHide: true,
timeout: 15000,
env: { ...process.env, FOCUS_GUARD_PROFILE: profileDir },
},
(error, stdout) =>
resolve(
error
? { state: 'unknown', reason: 'probe-failed' }
: parseForegroundOutput(stdout),
),
);
});
}
async function createBackgroundPage(context, log) {
const browser = context.browser();
if (!browser)
throw new FocusGuardError('无法获取 Browser,不能用 CDP 后台创建页面');
const session = await browser.newBrowserCDPSession();
try {
const pagePromise = context.waitForEvent('page', { timeout: 10000 });
await session.send('Target.createTarget', {
url: 'about:blank',
background: true,
newWindow: false,
});
const page = await pagePromise;
log.record(FOCUS_EVENTS.BACKGROUND_TARGET, { via: 'Target.createTarget' });
return page;
} finally {
await session.detach().catch(() => {});
}
}
/**
* 启动唯一页面的有头 Chrome。切换桌面 / 移动需关闭后重新启动(计为新的启动阶段)。
* 返回 { context, page, log, checkpoint, resetSession, blockedPopups, close }。
*/
export async function launchFocusSafe(options = {}) {
const runtime = browserRuntime({
...process.env,
...(options.headless === undefined
? {}
: { PW_HEADLESS: options.headless ? '1' : '0' }),
});
const {
chromium = (await import('@playwright/test')).chromium,
device = 'desktop',
colorScheme = 'light',
headless = runtime.headless,
blockPopups = true,
extraArgs = [],
contextOptions = {},
log = createFocusLog(),
} = options;
const deviceEnvironment = sharedContextOptions(device);
const profileDir = await mkdtemp(path.join(os.tmpdir(), 'monkey-pw-focus-'));
let context;
try {
context = await chromium.launchPersistentContext(profileDir, {
...deviceEnvironment,
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
colorScheme,
reducedMotion: 'reduce',
serviceWorkers: 'block',
...contextOptions,
channel: 'chrome',
headless,
args: [...extraArgs, ...runtime.launchArgs],
});
} catch (error) {
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
throw error;
}
if (blockPopups) await context.addInitScript(BLOCK_POPUP_SCRIPT);
const page = context.pages()[0] ?? (await createBackgroundPage(context, log));
const removeGuards = installFocusGuards(context, page, log);
const screenshot = page.screenshot.bind(page);
page.screenshot = async (options = {}) => {
await prepareStaticCapture(page);
return screenshot({ scale: 'css', ...options });
};
let previous = 'background';
let phase = 'startup';
async function checkpoint(label, { pauseOnUnknown = true } = {}) {
if (
log.entries.some((entry) =>
[FOCUS_EVENTS.FORBIDDEN, FOCUS_EVENTS.EXTRA_PAGE].includes(entry.type),
)
) {
throw new FocusGuardError(
`焦点守护发现禁止操作或意外新页面(${label}),已停止`,
);
}
let state;
let detail = {};
if (headless) state = 'background';
else {
const osProbe = await probeOsForeground(profileDir);
// Playwright 默认开启焦点模拟,document.hasFocus() 恒为 true,只作记录;以系统前台进程为准。
const pageFocus = await page
.evaluate(() => document.hasFocus())
.catch(() => null);
detail = {
os: osProbe.state,
reason: osProbe.reason,
foregroundPid: osProbe.foregroundPid,
documentHasFocus: pageFocus,
};
state = osProbe.state;
}
const verdict = classifyFocus({ phase, previous, current: state });
if (verdict.event) log.record(verdict.event, { label, ...detail });
phase = 'running';
if (state !== 'unknown') previous = state;
if (verdict.fatal && (state !== 'unknown' || pauseOnUnknown))
throw new FocusGuardError(`${verdict.event}(${label}),已暂停`);
return { state, ...detail };
}
async function resetSession(origins = []) {
await context.clearCookies();
const session = await context.newCDPSession(page);
try {
for (const origin of origins)
await session.send('Storage.clearDataForOrigin', {
origin,
storageTypes: 'all',
});
} finally {
await session.detach().catch(() => {});
}
await page.goto('about:blank');
}
const blockedPopups = () =>
page.evaluate(() => [...(window.__focusGuardBlockedOpens || [])]);
async function close() {
removeGuards();
await context.close().catch(() => {});
await rm(profileDir, { recursive: true, force: true, maxRetries: 5 });
}
try {
await checkpoint('launch');
} catch (error) {
await close();
throw error;
}
return { context, page, log, checkpoint, resetSession, blockedPopups, close };
}
+75
View File
@@ -0,0 +1,75 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
const FOCUS_ANNOTATION = 'focus-guard';
export default class AcceptanceReporter {
onBegin(config, suite) {
this.suite = suite;
this.focusEvents = new Set();
this.focusChecks = new Set();
this.headed = config.projects.some(
(project) => project.use?.headless === false,
);
}
onTestEnd(test, result) {
for (const note of [...(result.annotations || []), ...test.annotations]) {
if (note.type === FOCUS_ANNOTATION)
this.focusEvents.add(
`${test.titlePath().slice(1).join(' > ')}:${note.description}`,
);
if (note.type === 'focus-guard-checked')
this.focusChecks.add(`${test.id}:${note.description}`);
}
}
onEnd(result) {
// 焦点守护汇总:有事件时如实列出,不能宣称已保证后台运行
if (this.focusEvents.size) {
console.warn(
`\n[focus-guard] 记录到 ${this.focusEvents.size} 条焦点事件,本次运行不能宣称已保证后台运行:`,
);
for (const entry of this.focusEvents) console.warn(`- ${entry}`);
} else if (this.headed && this.focusChecks.size) {
console.log(
'\n[focus-guard] 各采样点(页面创建后、用例结束后)未检测到 Playwright Chrome 处于前台;采样点之间的瞬时激活无法排除',
);
}
if (process.env.PW_REQUIRE_ALL !== '1') return;
const incomplete = this.suite
.allTests()
.filter(
(test) =>
test.expectedStatus !== 'passed' ||
test.results.length === 0 ||
test.results.some((run) => run.status === 'skipped') ||
test.outcome() === 'flaky',
);
if (incomplete.length) {
console.error(
'Full acceptance requires every test to pass without skips, expected failures or flaky retries:',
);
for (const test of incomplete)
console.error(`- ${test.titlePath().join(' > ')}`);
return { status: 'failed' };
}
return { status: result.status };
}
}
+197
View File
@@ -0,0 +1,197 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 浏览器焦点守护:有头真实 Chrome 运行时尽最大可能不抢占用户桌面焦点。
// - 唯一页面:每个用例只有一个页面,由 CDP Target.createTarget({ background: true }) 后台创建,
// 不走 context.newPage()(Playwright 内部创建时不带 background,会以前台方式打开窗口)。
// - 禁止新建/切换标签页:context.newPage、browser.newPage、browser.newContext、page.bringToFront 调用即报错;
// 页面隐式打开的新标签页(target=_blank、window.open)立即关闭并判定用例失败。
// - 焦点探测:页面创建后与用例结束后各查一次前台窗口,若属于本 worker 启动的 Chrome,
// 记录「启动焦点激活事件」/「运行中焦点激活事件」;探测失败记为「焦点状态未确认」。只记录,不做任何激活操作。
// CI(无头)不创建窗口,跳过探测;页面仍按同样规程创建。
import { spawn } from 'node:child_process';
import { createInterface } from 'node:readline';
export const FOCUS_ANNOTATION = 'focus-guard';
const PROBE_SCRIPT = [
'[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;',
"Add-Type -Namespace FocusGuard -Name User32 -MemberDefinition '",
'[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();',
'[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);',
"';",
// 预热 CIM(首次查询需数秒),就绪后才应答查询
'[void](Get-CimInstance Win32_Process -Filter "ProcessId=$PID")',
'[Console]::Out.WriteLine("ready"); [Console]::Out.Flush()',
'while ($null -ne ($line = [Console]::In.ReadLine())) {',
' try {',
' $fgPid = [uint32]0',
' [void][FocusGuard.User32]::GetWindowThreadProcessId([FocusGuard.User32]::GetForegroundWindow(), [ref]$fgPid)',
' $parent = (Get-CimInstance Win32_Process -Filter "ProcessId=$fgPid").ParentProcessId',
' [Console]::Out.WriteLine("$fgPid $parent")',
' } catch { [Console]::Out.WriteLine("error") }',
' [Console]::Out.Flush()',
'}',
].join('\n');
// 每个 worker 一个常驻 PowerShell 只读探测进程(Add-Type 编译只发生一次),按行应答「前台窗口进程号 父进程号」
export function createFocusProbe() {
if (process.platform !== 'win32') return null;
const child = spawn(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-Command', PROBE_SCRIPT],
{
stdio: ['pipe', 'pipe', 'ignore'],
windowsHide: true,
},
);
child.on('error', () => {});
const lines = createInterface({ input: child.stdout });
const waiting = [];
let markReady;
const ready = new Promise((resolve) => {
markReady = resolve;
});
lines.on('line', (line) => {
if (line.trim() === 'ready') markReady(true);
else waiting.shift()?.(line.trim());
});
child.on('exit', () => {
markReady(false);
while (waiting.length) waiting.shift()(null);
});
return {
// 返回 { foregroundPid, parentPid };探测失败或超时返回 null
async query(timeout = 8000) {
const started = await Promise.race([
ready,
new Promise((resolve) => {
setTimeout(resolve, 15000, false).unref();
}),
]);
if (!started || child.exitCode !== null || !child.stdin.writable)
return null;
const answer = await new Promise((resolve) => {
const timer = setTimeout(() => {
resolve(null);
}, timeout);
waiting.push((line) => {
clearTimeout(timer);
resolve(line);
});
child.stdin.write('q\n');
});
const match = /^(\d+) (\d+)$/.exec(answer || '');
return match
? { foregroundPid: Number(match[1]), parentPid: Number(match[2]) }
: null;
},
dispose() {
child.stdin.end();
if (child.exitCode === null)
setTimeout(() => {
if (child.exitCode === null) child.kill();
}, 2000).unref();
},
};
}
// 前台窗口是否属于本 worker 启动的 Chrome(Chrome 主进程由 worker 进程直接启动并持有窗口)
export async function checkFocus(probe, stage, testInfo) {
if (!probe) return;
const state = await probe.query();
let description;
if (!state) {
description = `焦点状态未确认(${stage}):前台窗口探测失败,不能宣称已保证后台运行`;
} else if (state.parentPid === process.pid) {
description = `${stage === '页面创建后' ? '启动焦点激活事件' : '运行中焦点激活事件'}:${stage}前台窗口属于 Playwright Chrome(pid ${state.foregroundPid})`;
} else {
testInfo.annotations.push({
type: 'focus-guard-checked',
description: stage,
});
return;
}
testInfo.annotations.push({ type: FOCUS_ANNOTATION, description });
console.warn(
`[${FOCUS_ANNOTATION}] ${new Date().toISOString()} ${testInfo.titlePath.join(' > ')}:${description}`,
);
throw new Error(description);
}
// 本用例上下文的 CDP browserContextId:每个 worker 独占一个浏览器且用例串行,同一时刻只应有一个上下文
async function contextIdOf(cdp) {
const { browserContextIds } = await cdp.send('Target.getBrowserContexts');
if (browserContextIds.length !== 1) {
throw new Error(
`焦点守护:无法唯一确定当前浏览器上下文(共 ${browserContextIds.length} 个),拒绝以前台方式创建页面`,
);
}
return browserContextIds[0];
}
// 唯一页面:通过 CDP Target.createTarget({ background: true }) 后台创建,由 Playwright 自动接管为 context 的页面
export async function openBackgroundPage(browser, context) {
const cdp = await browser.newBrowserCDPSession();
try {
const browserContextId = await contextIdOf(cdp);
const pageEvent = context.waitForEvent('page', { timeout: 15000 });
await cdp.send('Target.createTarget', {
url: 'about:blank',
browserContextId,
background: true,
});
return await pageEvent;
} finally {
await cdp.detach().catch(() => {});
}
}
const forbid = (name, violations) => () => {
violations.push(`禁止调用 ${name}`);
throw new Error(
`焦点守护:禁止调用 ${name}(唯一页面原则,不得新建或切换标签页/窗口;访问新地址请在当前页 page.goto)`,
);
};
// 安装禁止项,返回 { violations, restore };restore 在用例结束时调用,恢复 worker 共享的 browser 方法
export function installGuards(browser, context, page) {
const violations = [];
const saved = { newPage: browser.newPage, newContext: browser.newContext };
context.newPage = forbid('context.newPage()', violations);
page.bringToFront = forbid('page.bringToFront()', violations);
browser.newPage = forbid('browser.newPage()', violations);
browser.newContext = forbid('browser.newContext()', violations);
const onPage = (extra) => {
if (extra === page) return;
violations.push(
`页面隐式打开了新标签页/窗口:${extra.url() || 'about:blank'}(已立即关闭)`,
);
extra.close().catch(() => {});
};
context.on('page', onPage);
return {
violations,
restore() {
context.off('page', onPage);
browser.newPage = saved.newPage;
browser.newContext = saved.newContext;
},
};
}
+149
View File
@@ -0,0 +1,149 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { randomUUID } from 'node:crypto';
export const browserStabilityArgs = Object.freeze([
'--hide-scrollbars',
'--disable-backgrounding-occluded-windows',
'--disable-renderer-backgrounding',
'--disable-background-timer-throttling',
'--disable-features=CalculateNativeWinOcclusion',
'--no-first-run',
'--no-default-browser-check',
]);
export function positiveInteger(value, name) {
const text = String(value);
if (
!['number', 'string'].includes(typeof value) ||
text !== text.trim() ||
!/^[1-9]\d*$/.test(text) ||
!Number.isSafeInteger(Number(value))
) {
throw new Error(`${name} must be a positive safe integer (1, 2, 3, ...)`);
}
return Number(value);
}
function flag(env, name, fallback) {
if (env[name] === undefined) return fallback;
if (!['0', '1'].includes(env[name]))
throw new Error(`${name} must be 0 or 1`);
return env[name] === '1';
}
export function browserRuntime(env = process.env) {
const isCI = Boolean(env.CI && env.CI !== 'false' && env.CI !== '0');
const headless = flag(env, 'PW_HEADLESS', isCI);
if (isCI && !headless)
throw new Error(
'CI requires headless Chrome; PW_HEADLESS=0 is not allowed',
);
// UI_VISUAL_OFFSCREEN=0 仅限人工本地可视化调试时临时使用。
// Agent、CI、无头/自动化环境禁止设置该值,必须保持默认离屏模式
// (或 UI_VISUAL_OFFSCREEN=1),避免弹出 UI 或依赖显示环境。
const offscreen = flag(env, 'UI_VISUAL_OFFSCREEN', true);
const knownAgent = Boolean(
env.CODEX_THREAD_ID || env.CLAUDECODE || env.CLAUDE_CODE_ENTRYPOINT,
);
if (!offscreen && (isCI || headless || knownAgent))
throw new Error(
'UI_VISUAL_OFFSCREEN=0 is only allowed for manual local headed debugging',
);
return {
isCI,
headless,
offscreen,
launchArgs: [
...browserStabilityArgs,
...(offscreen ? ['--window-position=-32000,-32000'] : []),
],
};
}
export function runtimeOptions({
defaultPort,
defaultWorkers,
env = process.env,
}) {
const target = env.PW_TARGET || 'local-dev';
if (!['local-dev', 'local-dist', 'remote'].includes(target))
throw new Error('PW_TARGET must be local-dist, local-dev or remote');
if (target === 'remote' && !env.PW_BASE_URL)
throw new Error('PW_BASE_URL is required for remote tests');
const baseURL = new URL(
env.PW_BASE_URL || `http://127.0.0.1:${defaultPort}/`,
);
if (
!['http:', 'https:'].includes(baseURL.protocol) ||
baseURL.username ||
baseURL.password ||
baseURL.search ||
baseURL.hash
) {
throw new Error(
'PW_BASE_URL must be an HTTP(S) URL without credentials, query or hash',
);
}
if (!baseURL.pathname.endsWith('/'))
throw new Error('PW_BASE_URL directory path must end with /');
if (
target !== 'remote' &&
(baseURL.hostname !== '127.0.0.1' ||
baseURL.protocol !== 'http:' ||
baseURL.pathname !== '/')
) {
throw new Error('Local targets require http://127.0.0.1:<port>/');
}
const browser = browserRuntime(env);
const { isCI } = browser;
const workers =
env.PW_WORKERS === undefined
? isCI
? 1
: positiveInteger(defaultWorkers, 'resources.concurrency')
: positiveInteger(env.PW_WORKERS, 'PW_WORKERS');
const extended = flag(env, 'PW_EXTENDED_LAYOUT', false);
const video = flag(env, 'PW_VIDEO', false);
const requireAll = flag(env, 'PW_REQUIRE_ALL', false);
const runId = env.PW_RUN_ID ?? `${target}-${Date.now()}-${randomUUID()}`;
if (
typeof runId !== 'string' ||
runId !== runId.trim() ||
!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/.test(runId)
)
throw new Error(
'PW_RUN_ID must be a safe directory name of 1-100 letters, digits, underscores or hyphens',
);
// Workers inherit this ID; every run keeps its traces and reports together.
env.PW_RUN_ID = runId;
return {
target,
baseURL,
...browser,
workers,
extended,
video,
requireAll,
runId,
outputDir: `test-results/${runId}`,
reportDir: `playwright-report/${runId}`,
};
}
+69
View File
@@ -0,0 +1,69 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { test as base, expect } from '@playwright/test';
import {
checkFocus,
createFocusProbe,
installGuards,
openBackgroundPage,
} from './playwright-runner-focus.mjs';
import { prepareStaticCapture } from './browser-capture.mjs';
export const test = base.extend({
focusProbe: [
async ({ headless }, use) => {
const probe = headless ? null : createFocusProbe();
if (!headless && !probe)
throw new Error(
'焦点状态未确认:当前系统不支持前台窗口探测,请使用 PW_HEADLESS=1',
);
try {
await use(probe);
} finally {
probe?.dispose();
}
},
{ scope: 'worker' },
],
page: async ({ browser, context, focusProbe, headless }, use, testInfo) => {
if (!headless && process.env.CI && !['0', 'false'].includes(process.env.CI))
throw new Error('CI requires headless Chrome');
const page = await openBackgroundPage(browser, context);
const guards = installGuards(browser, context, page);
const screenshot = page.screenshot.bind(page);
page.screenshot = async (options = {}) => {
await prepareStaticCapture(page);
return screenshot({ scale: 'css', ...options });
};
try {
await checkFocus(focusProbe, '页面创建后', testInfo);
await use(page);
await checkFocus(focusProbe, '用例结束后', testInfo);
} finally {
guards.restore();
expect(
guards.violations,
'焦点守护:用例不得新建或切换标签页/窗口',
).toEqual([]);
}
},
});
export { expect };
+41
View File
@@ -0,0 +1,41 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { preview } from 'vite';
import { fileURLToPath } from 'node:url';
import { positiveInteger } from './playwright-runtime.mjs';
import { verifyBuild } from './verify-build.mjs';
const directory =
process.env.PW_DIST_DIR ||
fileURLToPath(new URL('../dist/', import.meta.url));
const portIndex = process.argv.indexOf('--port');
const port = positiveInteger(
portIndex === -1 ? 4176 : process.argv[portIndex + 1],
'port',
);
if (port > 65535) throw new Error('port must be <= 65535');
await verifyBuild(directory);
const server = await preview({
build: { outDir: directory },
preview: { host: '127.0.0.1', port, strictPort: true },
});
server.printUrls();
for (const signal of ['SIGTERM', 'SIGINT'])
process.on(signal, () => server.httpServer.close());
+65
View File
@@ -0,0 +1,65 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { spawn } from 'node:child_process';
import { verifyBuild } from './verify-build.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
const directory = await mkdtemp(path.join(tmpdir(), 'monkey-pw-build-'));
const env = {
...process.env,
PW_TARGET: 'local-dist',
PW_BASE_URL: 'http://127.0.0.1:4176/',
PW_REQUIRE_ALL: '1',
PW_DIST_DIR: directory,
};
function run(script, args) {
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [script, ...args], {
cwd: root,
stdio: 'inherit',
env,
});
child.on('error', reject);
child.on('exit', (code) =>
code === 0
? resolve()
: reject(new Error(`${path.basename(script)} failed (${code})`)),
);
});
}
try {
await run(path.join(root, 'node_modules/vite/bin/vite.js'), [
'build',
'--outDir',
directory,
'--emptyOutDir',
]);
await verifyBuild(directory);
await run(path.join(root, 'node_modules/@playwright/test/cli.js'), [
'test',
...process.argv.slice(2),
]);
} finally {
await rm(directory, { recursive: true, force: true });
}
+91
View File
@@ -0,0 +1,91 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { spawn } from 'node:child_process';
import { readdir, stat, access } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
export async function latestReport(directory) {
const reports = [];
try {
const legacy = await stat(path.join(directory, 'index.html'));
reports.push({ candidate: directory, modified: legacy.mtimeMs });
} catch {
/* Older runners wrote index.html directly in this directory. */
}
for (const entry of await readdir(directory, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const candidate = path.join(directory, entry.name);
try {
const info = await stat(path.join(candidate, 'index.html'));
reports.push({ candidate, modified: info.mtimeMs });
} catch {
/* Incomplete runs have no report to open. */
}
}
reports.sort((a, b) => b.modified - a.modified);
if (!reports.length) throw new Error('No completed HTML report found');
return reports[0].candidate;
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
const [mode, ...args] = process.argv.slice(2);
const env = { ...process.env };
const cli = fileURLToPath(
new URL('../node_modules/@playwright/test/cli.js', import.meta.url),
);
let command = ['test', ...args];
if (mode === 'headless') env.PW_HEADLESS = '1';
else if (mode === 'extended') env.PW_EXTENDED_LAYOUT = '1';
else if (mode === 'dist') {
env.PW_TARGET = 'local-dist';
env.PW_BASE_URL = 'http://127.0.0.1:4176/';
const root =
env.PW_DIST_DIR || fileURLToPath(new URL('../dist/', import.meta.url));
await access(path.join(root, 'index.html'));
} else if (mode === 'report') {
const explicitDirectory = args[0] && !args[0].startsWith('-');
const directory = explicitDirectory
? args[0]
: await latestReport(
fileURLToPath(new URL('../playwright-report/', import.meta.url)),
);
command = [
'show-report',
directory,
...(explicitDirectory ? args.slice(1) : args),
];
} else throw new Error('Expected headless, extended, dist or report');
const child = spawn(process.execPath, [cli, ...command], {
cwd: fileURLToPath(new URL('../', import.meta.url)),
stdio: 'inherit',
env,
});
child.on('error', (error) => {
console.error(error);
process.exitCode = 1;
});
child.on('exit', (code) => {
process.exitCode = code ?? 1;
});
}
+86
View File
@@ -0,0 +1,86 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { spawn } from 'node:child_process';
const root = fileURLToPath(new URL('../', import.meta.url));
const directory = await mkdtemp(path.join(tmpdir(), 'pw-environment-'));
const url = (name) => pathToFileURL(path.join(root, name)).href;
try {
await writeFile(
path.join(directory, 'playwright.config.mjs'),
`
import config from ${JSON.stringify(url('playwright.config.js'))}
export default { ...config, testDir: ${JSON.stringify(directory)}, testMatch: '**/*.spec.mjs', fullyParallel: false, workers: 1,
outputDir: ${JSON.stringify(root)} + config.outputDir,
reporter: config.reporter.map(([name, options]) => [name.startsWith('.') ? ${JSON.stringify(root)} + name : name, name === 'html' ? { ...options, outputFolder: ${JSON.stringify(root)} + options.outputFolder } : options]),
webServer: config.webServer ? { ...config.webServer, cwd: ${JSON.stringify(root)} } : undefined }
`,
);
await writeFile(
path.join(directory, 'environment.spec.mjs'),
`
import { test, expect } from ${JSON.stringify(url('scripts/playwright-test.mjs'))}
import { contextOptions } from ${JSON.stringify(url('scripts/browser-environment.mjs'))}
import { captureStatic } from ${JSON.stringify(url('scripts/browser-capture.mjs'))}
test('设备上下文、触摸、DPR、CSS 截图与稳定字体', async ({ page, baseURL }, info) => {
const expected = contextOptions(info.project.name.replace('chrome-', ''))
await page.route('**/__pw_environment__', route => route.fulfill({ contentType: 'text/html', body: '<meta name="viewport" content="width=device-width, initial-scale=1"><style>body{margin:0} div{width:100px;height:50px;background:orange;animation:move 3s infinite}@keyframes move{to{transform:translateX(100px)}}</style><div>环境验证</div>' }))
await page.goto(new URL('__pw_environment__', baseURL).href)
const actual = await page.evaluate(() => ({ width: innerWidth, height: innerHeight, dpr: devicePixelRatio, ua: navigator.userAgent, touch: navigator.maxTouchPoints > 0, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, reduced: matchMedia('(prefers-reduced-motion: reduce)').matches }))
expect(actual).toMatchObject({ width: expected.viewport.width, height: expected.viewport.height, dpr: expected.deviceScaleFactor, touch: expected.hasTouch, language: expected.locale, timezone: expected.timezoneId, reduced: true })
expect(actual.ua).toBe(expected.userAgent)
const image = await captureStatic(page)
expect(image.readUInt32BE(16)).toBe(expected.viewport.width)
expect(image.readUInt32BE(20)).toBe(expected.viewport.height)
expect((await captureStatic(page)).equals(image)).toBe(true)
})
`,
);
const env = {
...process.env,
PW_HEADLESS: '1',
UI_VISUAL_OFFSCREEN: '1',
PW_EXTENDED_LAYOUT: '1',
PW_WORKERS: '1',
};
delete env.PW_RUN_ID;
delete env.PLAYWRIGHT_HTML_OUTPUT_DIR;
const code = await new Promise((resolve, reject) => {
const child = spawn(
process.execPath,
[
path.join(root, 'node_modules/@playwright/test/cli.js'),
'test',
'--config',
path.join(directory, 'playwright.config.mjs'),
],
{ cwd: root, env, stdio: 'inherit' },
);
child.on('error', reject);
child.on('exit', (code) => resolve(code ?? 1));
});
process.exitCode = code;
} finally {
await rm(directory, { recursive: true, force: true });
}
+19
View File
@@ -0,0 +1,19 @@
{
"browser": {
"channel": "chrome",
"desktopDevice": "Desktop Chrome",
"mobileDevice": "Pixel 5",
"locale": "zh-CN",
"timezone": "Asia/Shanghai"
},
"viewports": {
"desktop": [1920, 1080],
"mobile": [360, 800],
"tablet": [768, 1024],
"laptop": [1024, 768],
"hd": [1366, 768],
"wxga": [1440, 900],
"qhd": [2560, 1440],
"uhd": [3840, 2160]
}
}
+56
View File
@@ -0,0 +1,56 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { readFile, access } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
export async function verifyBuild(directory) {
const root = path.resolve(directory);
const html = await readFile(path.join(root, 'index.html'), 'utf8');
// Inspect actual resource tags, not URLs embedded in comments or inline scripts.
const markup = html
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/(<script\b[^>]*>)[\s\S]*?<\/script\s*>/gi, '$1</script>');
const tags = [
...markup.matchAll(/<(?:script|link|img|source)\b[^>]*>/gi),
].map((match) => match[0]);
const assets = tags
.flatMap((tag) => [...tag.matchAll(/\s(?:src|href)\s*=["']([^"']+)["']/g)])
.map((match) => match[1].split(/[?#]/)[0])
// The inline brand bootstrap resolves this server placeholder to /logo.svg.
.map((value) => (value === '__WL_BRAND_FAVICON__' ? '/logo.svg' : value))
.filter((value) => value && !/^(?:[a-z]+:|\/\/|#)/i.test(value));
if (!assets.some((value) => /\.js$/.test(value)))
throw new Error('Build has no JavaScript entry');
for (const asset of assets) {
const filename = path.resolve(root, asset.replace(/^\//, ''));
if (!filename.startsWith(root + path.sep))
throw new Error(`Build asset escapes output directory: ${asset}`);
await access(filename);
}
return { root, assets: assets.length };
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
console.log(await verifyBuild(process.argv[2] || 'dist'));
}