import { randomUUID } from 'node:crypto';
import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { loadSharp } from '../../images/sharpRuntime.js';
import { agentStateDir } from '../../context/agentHome.js';
import { pinBrowserLaunch, unpinBrowserLaunch, withPinnedBrowserLaunch, runBounded, spawnRunnerWithEnv } from './browser.js';
import { getBrowserAutomation, releaseBrowserAutomation, type CdpConnection } from './browserAutomation.js';
import { captureVerifiedScreenshot } from './browserScreenshot.js';
// Offline, deterministic colors and real input/click effects; never touches user pages.
export const BROWSER_HEALTH_HTML = `
browser-health
`;
export async function assertHealthPixels(input: Buffer | string): Promise {
const sharp = await loadSharp();
const { data, info } = await sharp(input).removeAlpha().raw().toBuffer({ resolveWithObject: true });
if (info.width < 220 || info.height < 220) throw new Error('自检截图尺寸异常');
for (const [x, y, rgb] of [[20, 20, [220, 40, 60]], [200, 200, [20, 180, 80]]] as const) {
const offset = (y * info.width + x) * info.channels;
if (rgb.some((value, index) => Math.abs(data[offset + index]! - value) > 8))
throw new Error('自检页面操作后的色块未正确呈现,截图链路未通过');
}
}
export interface BrowserHealthOptions {
executablePath?: string;
signal?: AbortSignal;
onProgress?: (message: string) => void;
}
/** Explicit enable-time test. Artifacts contain only the synthetic page, no user data. */
export async function verifyBrowserEnvironment(bin: string, options: BrowserHealthOptions = {}): Promise {
options.signal?.throwIfAborted();
const root = join(agentStateDir(), 'browser', 'health');
await mkdir(root, { recursive: true, mode: 0o700 });
const dir = await mkdtemp(join(root, 'check-'));
const session = `ma-health-${randomUUID()}`;
const config = join(dir, 'config.json');
await writeFile(config, '{}', { mode: 0o600 });
const env: NodeJS.ProcessEnv = {};
// Ambient attach/provider/profile options must not point the probe at a live user browser.
for (const key of Object.keys(process.env)) if (key.startsWith('AGENT_BROWSER_')) env[key] = undefined;
const args = ['--session', session, '--config', config, '--profile', join(dir, 'profile'),
...(options.executablePath ? ['--executable-path', options.executablePath] : []), '--json'];
pinBrowserLaunch(bin, session, args);
const runner = (path: string, commandArgs: string[], signal?: AbortSignal) =>
spawnRunnerWithEnv(path, withPinnedBrowserLaunch(path, commandArgs), signal, env);
let stage = 'launch';
let cdp: CdpConnection | undefined;
let failure: unknown;
const controller = new AbortController();
const abort = () => controller.abort(options.signal?.reason);
options.signal?.addEventListener('abort', abort, { once: true });
if (options.signal?.aborted) abort();
const deadline = setTimeout(() => controller.abort(new Error('浏览器自检超时')), 60_000);
const command = async (step: string[]) => {
const result = await runBounded(bin, [...args, ...step], { signal: controller.signal, timeoutMs: 20_000 }, runner);
if (result.code !== 0 || result.aborted || result.timedOut) throw new Error(`${stage} 执行失败(退出码 ${result.code},超时 ${Boolean(result.timedOut)}):${result.stderr.slice(0, 4000)}`);
const json = JSON.parse(result.stdout);
if (json.success !== true) throw new Error(`${stage} 未返回成功状态:${String(json.error ?? '').slice(0, 4000)}`);
return json.data;
};
try {
options.onProgress?.('真实浏览器自检:打开本地测试页、输入、点击并检查截图…');
const url = `data:text/html,${encodeURIComponent(BROWSER_HEALTH_HTML)}`;
await command(['open', url]);
stage = 'interaction';
await command(['fill', '#health-input', 'health-passed']);
await command(['click', '#health-button']);
if ((await command(['get', 'title']))?.title !== 'health-passed') throw new Error('输入/点击状态验证未通过');
stage = 'cli-screenshot';
const shot = join(dir, 'cli.png');
await command(['screenshot', shot]);
await assertHealthPixels(shot);
stage = 'cdp-screenshot';
cdp = await getBrowserAutomation(session, bin, runner, controller.signal, url);
const identity = await cdp.send('Runtime.evaluate', { expression: '({title:document.title,url:location.href})', returnByValue: true }, undefined, 5_000, controller.signal) as { result?: { value?: { title?: string; url?: string } } };
if (identity.result?.value?.title !== 'health-passed') throw new Error('CDP 绑定页面与自检页面不一致');
const captured = await captureVerifiedScreenshot(cdp, controller.signal);
await writeFile(join(dir, 'cdp.png'), captured.image, { mode: 0o600 });
await assertHealthPixels(captured.image);
stage = 'passed';
} catch (error) { failure = error; }
finally {
clearTimeout(deadline);
options.signal?.removeEventListener('abort', abort);
if (cdp) { releaseBrowserAutomation(cdp); cdp.close(); }
// Cleanup has its own deadline even when the caller cancelled; never close --all.
const closed = await runBounded(bin, [...args, 'close'], { timeoutMs: 5_000 }, runner);
unpinBrowserLaunch(bin, session);
let cleanupConfirmed = false;
try { cleanupConfirmed = closed.code === 0 && JSON.parse(closed.stdout).success === true; } catch { /* retain uncertain profile */ }
if (!cleanupConfirmed && !failure) {
stage = 'cleanup';
failure = new Error('自检会话关闭未确认,保留现场,不自动终止其他浏览器');
}
// Only discard this probe's generated profile after its daemon has stopped.
const profile = join(dir, 'profile');
if (cleanupConfirmed && await realpath(profile).catch(() => '') === join(await realpath(dir), 'profile')) {
await rm(profile, { recursive: true, force: true }).catch(() => undefined);
}
await writeFile(join(dir, 'report.json'), JSON.stringify({ stage, platform: process.platform, arch: process.arch,
runner: bin, browser: options.executablePath ?? 'auto', passed: !failure,
cleanupConfirmed, at: new Date().toISOString(),
error: failure instanceof Error ? failure.message : failure ? String(failure) : undefined,
}, null, 2), { mode: 0o600 });
if (!cleanupConfirmed) options.onProgress?.(`自检会话关闭未确认,保留现场:${dir};未终止其他浏览器。`);
}
if (failure) {
options.signal?.throwIfAborted();
throw new Error(`浏览器端到端自检未通过(${stage})。诊断报告:${join(dir, 'report.json')}。未删除系统浏览器或用户资料;请结合报告检查运行依赖/启动配置,修复后重新开启。`);
}
options.onProgress?.('浏览器输入、点击、CLI/CDP 截图自检通过。');
}