import { loadSharp } from '../../images/sharpRuntime.js'; import type { CdpConnection } from './browserAutomation.js'; export interface ScreenshotAssessment { width: number; height: number; uniform: boolean; warning?: string; } export const UNIFORM_SCREENSHOT_WARNING = '截图几乎为单色,视觉证据不足;可能是页面本身、加载/绘制时机或渲染链路异常,原因未确认。DOM 完整不等于视觉通过;不要直接归因于 headless,也不要据此重放点击、提交或重装浏览器。'; /** Decode the actual artifact; low variance is an observation, never a diagnosis. */ export async function assessScreenshot(input: Buffer | string): Promise { const sharp = await loadSharp(); const image = sharp(input, { limitInputPixels: 40_000_000 }); const metadata = await image.metadata(); if (!metadata.width || !metadata.height) throw new Error('截图缺少有效尺寸'); const stats = await image.clone().flatten({ background: '#fff' }).removeAlpha().stats(); const uniform = stats.channels.every(channel => channel.max - channel.min <= 2); return { width: metadata.width, height: metadata.height, uniform, ...(uniform ? { warning: UNIFORM_SCREENSHOT_WARNING } : {}) }; } /** Wait for a paint opportunity, not for indefinite network-idle or business completion. */ export const SCREENSHOT_PAINT_BARRIER = `new Promise(resolve => { const timer = setTimeout(resolve, 400); requestAnimationFrame(() => requestAnimationFrame(() => { clearTimeout(timer); resolve(); })); })`; export async function captureVerifiedScreenshot( cdp: Pick, signal?: AbortSignal, ): Promise<{ image: Buffer; assessment: ScreenshotAssessment; attempts: number }> { for (let attempt = 1; attempt <= 2; attempt++) { signal?.throwIfAborted(); // Do not activate another tab or disable animations; observation must not change app state. await cdp.send('Runtime.evaluate', { expression: SCREENSHOT_PAINT_BARRIER, awaitPromise: true, returnByValue: true, }, undefined, 2_000, signal).catch(error => { if (signal?.aborted) throw error; // A navigating page may lose its execution context; still attempt a screenshot. }); const result = await cdp.send('Page.captureScreenshot', { format: 'png', fromSurface: true, }, undefined, 10_000, signal) as { data?: string }; if (!result.data) throw new Error('浏览器未返回截图'); const image = Buffer.from(result.data, 'base64'); const assessment = await assessScreenshot(image); if (!assessment.uniform || attempt === 2) return { image, assessment, attempts: attempt }; // Retry only the observation, never the preceding action. } throw new Error('截图检查未完成'); }