d878f0db21
统一设备配置和浏览器启动入口,加入窗口焦点守卫,并按运行隔离报告和追踪文件。
198 lines
7.9 KiB
JavaScript
198 lines
7.9 KiB
JavaScript
/*
|
||
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;
|
||
},
|
||
};
|
||
}
|