electron-window-recorder.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { randomUUID } from "node:crypto";
  2. import { copyFile, mkdir, rm, stat, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join, resolve } from "node:path";
  5. import { runElectronRecordingCommand, runWithTimeout } from "./electron-window-recorder-timeout.js";
  6. export const ELECTRON_WINDOW_RECORDING_CAPTURE_MODE = "electron_capture_page";
  7. const DEFAULT_CAPTURE_TIMEOUT_MS = 5_000;
  8. const DEFAULT_ENCODE_TIMEOUT_MS = 30_000;
  9. const DEFAULT_STOP_TIMEOUT_MS = 45_000;
  10. const MAX_RECORDING_TIMEOUT_MS = 5 * 60_000;
  11. export interface ElectronWindowRecordingResult {
  12. captureError?: string;
  13. captureMode: typeof ELECTRON_WINDOW_RECORDING_CAPTURE_MODE;
  14. frameCount: number;
  15. videoPath: string;
  16. }
  17. export interface EncodeElectronWindowVideoInput {
  18. ffmpegPath: string;
  19. framePaths: string[];
  20. frameRate: number;
  21. outputPath: string;
  22. signal?: AbortSignal;
  23. timeoutMs?: number;
  24. }
  25. export interface StartElectronWindowRecordingOptions {
  26. browser?: WebdriverIO.Browser;
  27. captureFrame?: () => Promise<Buffer>;
  28. /** 单次 capturePage 请求的最大等待时间。 */
  29. captureTimeoutMs?: number;
  30. cleanupFrames?: boolean;
  31. encodeVideo?: (input: EncodeElectronWindowVideoInput) => Promise<void>;
  32. /** ffmpeg 或自定义编码器的最大等待时间。 */
  33. encodeTimeoutMs?: number;
  34. ffmpegPath?: string;
  35. frameDir?: string;
  36. frameIntervalMs?: number;
  37. outputPath?: string;
  38. /** 在返回录制 session 前先持续采集的时间,用于保留测试动作发生前的画面。 */
  39. preRollDurationMs?: number;
  40. /** stop() 从尾录制到编码完成的总预算。 */
  41. stopTimeoutMs?: number;
  42. }
  43. export interface StopElectronWindowRecordingOptions {
  44. /** 在测试结束后继续采集的时间,供失败证据保留异步 UI 收尾。 */
  45. tailDurationMs?: number;
  46. /** 覆盖 session 级 stop 总预算。 */
  47. timeoutMs?: number;
  48. }
  49. export interface ElectronWindowRecordingSession {
  50. captureMode: typeof ELECTRON_WINDOW_RECORDING_CAPTURE_MODE;
  51. discard: () => Promise<void>;
  52. stop: (options?: StopElectronWindowRecordingOptions) => Promise<ElectronWindowRecordingResult>;
  53. videoPath: string;
  54. }
  55. /** 录屏编码器默认路径;与 startElectronWindowRecording 的解析顺序一致。 */
  56. export function resolveElectronRecordingFfmpegPath(ffmpegPath?: string): string {
  57. return ffmpegPath?.trim() || process.env.ZCODE_E2E_FFMPEG_PATH?.trim() || "ffmpeg";
  58. }
  59. /**
  60. * 判断录屏编码器可用:`ffmpeg -version` 必须在超时内以 0 退出。
  61. * 修复原因:正式用例在无 ffmpeg 的 runner 上会在 stop() 编码时报 spawn ENOENT,把只作证据的
  62. * 录屏失败记成行为失败;调用方先探测,不可用时跳过录屏并保留全部行为断言。
  63. * 只看 spawn 成功不够:能启动但损坏、错配或被策略拒绝的程序同样会在编码阶段失败,
  64. * 所以复用编码命令的执行器,按退出码、启动错误与超时统一判定。
  65. */
  66. export async function isElectronRecordingEncoderAvailable(ffmpegPath?: string): Promise<boolean> {
  67. try {
  68. await runElectronRecordingCommand(
  69. resolveElectronRecordingFfmpegPath(ffmpegPath),
  70. ["-version"],
  71. {
  72. timeoutMs: 10_000,
  73. },
  74. );
  75. return true;
  76. } catch {
  77. return false;
  78. }
  79. }
  80. export async function startElectronWindowRecording(
  81. options: StartElectronWindowRecordingOptions = {},
  82. ): Promise<ElectronWindowRecordingSession> {
  83. const outputPath = resolveElectronRecordingOutputPath(options.outputPath);
  84. const frameDir = resolve(
  85. options.frameDir ?? join(tmpdir(), `zcode-electron-recording-${randomUUID()}`),
  86. );
  87. const frameIntervalMs = normalizeFrameIntervalMs(options.frameIntervalMs);
  88. const preRollDurationMs = normalizePreRollDurationMs(options.preRollDurationMs);
  89. const captureTimeoutMs = normalizeRecordingTimeoutMs(
  90. options.captureTimeoutMs,
  91. DEFAULT_CAPTURE_TIMEOUT_MS,
  92. );
  93. const encodeTimeoutMs = normalizeRecordingTimeoutMs(
  94. options.encodeTimeoutMs,
  95. DEFAULT_ENCODE_TIMEOUT_MS,
  96. );
  97. const configuredStopTimeoutMs = normalizeRecordingTimeoutMs(
  98. options.stopTimeoutMs,
  99. DEFAULT_STOP_TIMEOUT_MS,
  100. );
  101. const frameRate = Math.max(1, Math.round(1000 / frameIntervalMs));
  102. const ffmpegPath = resolveElectronRecordingFfmpegPath(options.ffmpegPath);
  103. const captureFrame = options.captureFrame ?? (() => captureElectronWindowFrame(options.browser));
  104. const encodeVideo = options.encodeVideo ?? encodeElectronWindowVideo;
  105. const cleanupFrames = options.cleanupFrames ?? true;
  106. const capturedFrames: Array<{ capturedAt: number; path: string }> = [];
  107. let startedAt = Date.now();
  108. let stopped = false;
  109. let pendingCapture: Promise<void> | null = null;
  110. let captureErrorCount = 0;
  111. let firstCaptureError: unknown;
  112. await mkdir(frameDir, { recursive: true });
  113. const captureOnce = async () => {
  114. if (stopped || pendingCapture) {
  115. return pendingCapture;
  116. }
  117. pendingCapture = (async () => {
  118. try {
  119. // 修复原因:窗口崩溃或 DevTools 断连时 capturePage 可能永不返回;单帧必须
  120. // 有独立上限,否则 discard/stop 会一直等待同一个 pendingCapture。
  121. const frame = await runWithTimeout(
  122. captureFrame,
  123. captureTimeoutMs,
  124. "Electron window frame capture",
  125. );
  126. if (stopped) {
  127. return;
  128. }
  129. const framePath = join(
  130. frameDir,
  131. `captured-${String(capturedFrames.length + 1).padStart(6, "0")}.png`,
  132. );
  133. await writeFile(framePath, frame);
  134. capturedFrames.push({ capturedAt: Date.now(), path: framePath });
  135. } catch (error) {
  136. firstCaptureError ??= error;
  137. captureErrorCount += 1;
  138. } finally {
  139. pendingCapture = null;
  140. }
  141. })();
  142. return pendingCapture;
  143. };
  144. await captureOnce();
  145. if (capturedFrames.length === 0) {
  146. throw asError(firstCaptureError, "Electron window recording could not capture the first frame");
  147. }
  148. startedAt = Date.now();
  149. const timer = setInterval(() => {
  150. void captureOnce();
  151. }, frameIntervalMs);
  152. if (preRollDurationMs > 0) {
  153. await waitFor(preRollDurationMs);
  154. }
  155. return {
  156. captureMode: ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  157. videoPath: outputPath,
  158. async discard() {
  159. stopped = true;
  160. clearInterval(timer);
  161. const capture = pendingCapture;
  162. if (capture) {
  163. await runWithTimeout(
  164. () => capture,
  165. captureTimeoutMs,
  166. "Electron window pending capture discard",
  167. ).catch(() => undefined);
  168. }
  169. // 修复原因:失败录屏在 case 开始时先采帧,若通过 case 仍调用 stop 会无意义地
  170. // 启动 ffmpeg 编码。discard 只回收帧和可能残留的输出文件,避免通过用例产生视频。
  171. await Promise.all([
  172. rm(frameDir, { force: true, recursive: true }),
  173. rm(outputPath, { force: true }),
  174. ]);
  175. },
  176. async stop(stopOptions = {}) {
  177. const tailDurationMs = normalizeTailDurationMs(stopOptions.tailDurationMs);
  178. const stopTimeoutMs = normalizeRecordingTimeoutMs(
  179. stopOptions.timeoutMs,
  180. configuredStopTimeoutMs,
  181. );
  182. const stopController = new AbortController();
  183. try {
  184. return await runWithTimeout(
  185. async () => {
  186. if (tailDurationMs > 0) {
  187. await waitFor(tailDurationMs, stopController.signal);
  188. }
  189. await captureOnce();
  190. stopped = true;
  191. clearInterval(timer);
  192. const capture = pendingCapture;
  193. if (capture) {
  194. await capture;
  195. }
  196. if (capturedFrames.length === 0) {
  197. throw asError(firstCaptureError, "Electron window recording captured no frames");
  198. }
  199. // 修复原因:capturePage 是异步 CDP 请求,慢帧会被采样器跳过。之前编码器只按
  200. // 实际帧数计算时长,长 case 可能因只拿到首帧而被压缩为约 1 秒。按真实墙钟时间
  201. // 生成连续时间轴,缺失采样复用最近帧,才能使视频覆盖整个 case。
  202. const framePaths = await materializeRecordingTimeline({
  203. capturedFrames,
  204. frameDir,
  205. frameIntervalMs,
  206. startedAt,
  207. stoppedAt: Date.now(),
  208. });
  209. await mkdir(dirname(outputPath), { recursive: true });
  210. await runWithTimeout(
  211. () =>
  212. encodeVideo({
  213. ffmpegPath,
  214. framePaths: [...framePaths],
  215. frameRate,
  216. outputPath,
  217. signal: stopController.signal,
  218. timeoutMs: encodeTimeoutMs,
  219. }),
  220. encodeTimeoutMs,
  221. "Electron window video encoding",
  222. (error) => stopController.abort(error),
  223. );
  224. const outputStats = await stat(outputPath);
  225. if (outputStats.size <= 0) {
  226. throw new Error(`Electron window recording produced an empty video: ${outputPath}`);
  227. }
  228. if (cleanupFrames) {
  229. await rm(frameDir, { force: true, recursive: true });
  230. }
  231. return {
  232. captureError:
  233. captureErrorCount > 0
  234. ? `${captureErrorCount} frame capture request(s) failed: ${asError(firstCaptureError, "unknown capture error").message}`
  235. : undefined,
  236. captureMode: ELECTRON_WINDOW_RECORDING_CAPTURE_MODE,
  237. frameCount: framePaths.length,
  238. videoPath: outputPath,
  239. };
  240. },
  241. stopTimeoutMs,
  242. "Electron window recording stop",
  243. (error) => stopController.abort(error),
  244. );
  245. } finally {
  246. // 修复原因:总预算到期后即使底层 CDP promise 仍未 settle,也必须停止新采帧,
  247. // 让 WDIO afterTest 能继续进入资源清理和 summary 写入。
  248. stopped = true;
  249. clearInterval(timer);
  250. }
  251. },
  252. };
  253. }
  254. export function buildElectronRecordingFfmpegArgs(input: EncodeElectronWindowVideoInput): string[] {
  255. const firstFramePath = input.framePaths[0];
  256. if (!firstFramePath) {
  257. throw new Error("Electron window recording cannot encode without frames");
  258. }
  259. return [
  260. "-y",
  261. "-framerate",
  262. String(input.frameRate),
  263. "-i",
  264. join(dirname(firstFramePath), "frame-%06d.png"),
  265. "-vf",
  266. "scale=trunc(iw/2)*2:trunc(ih/2)*2",
  267. "-c:v",
  268. "libvpx-vp9",
  269. "-pix_fmt",
  270. "yuv420p",
  271. "-deadline",
  272. "realtime",
  273. "-cpu-used",
  274. "5",
  275. input.outputPath,
  276. ];
  277. }
  278. async function captureElectronWindowFrame(
  279. maybeBrowser: WebdriverIO.Browser | undefined,
  280. ): Promise<Buffer> {
  281. const sessionBrowser =
  282. maybeBrowser ?? (globalThis as typeof globalThis & { browser?: WebdriverIO.Browser }).browser;
  283. if (!sessionBrowser?.electron) {
  284. throw new Error("Electron window recording requires a WDIO Electron browser session");
  285. }
  286. const pngBase64 = await sessionBrowser.electron.execute(async (electron) => {
  287. const windows = electron.BrowserWindow.getAllWindows()
  288. .filter((win) => !win.isDestroyed())
  289. .sort((left, right) => Number(right.isFocused()) - Number(left.isFocused()));
  290. const target = windows.find((win) => win.isVisible()) ?? windows[0];
  291. if (!target) {
  292. throw new Error("No Electron BrowserWindow is available for recording");
  293. }
  294. const image = await target.webContents.capturePage();
  295. if (image.isEmpty()) {
  296. throw new Error("Electron BrowserWindow capturePage returned an empty image");
  297. }
  298. return image.toPNG().toString("base64");
  299. });
  300. return Buffer.from(String(pngBase64), "base64");
  301. }
  302. async function encodeElectronWindowVideo(input: EncodeElectronWindowVideoInput): Promise<void> {
  303. await runElectronRecordingCommand(input.ffmpegPath, buildElectronRecordingFfmpegArgs(input), {
  304. signal: input.signal,
  305. timeoutMs: input.timeoutMs,
  306. });
  307. }
  308. function normalizeFrameIntervalMs(value: number | undefined): number {
  309. if (!Number.isFinite(value) || !value) {
  310. return 500;
  311. }
  312. return Math.max(100, Math.round(value));
  313. }
  314. function normalizeTailDurationMs(value: number | undefined): number {
  315. if (!Number.isFinite(value) || !value) {
  316. return 0;
  317. }
  318. return Math.max(0, Math.min(10_000, Math.round(value)));
  319. }
  320. function normalizePreRollDurationMs(value: number | undefined): number {
  321. if (!Number.isFinite(value) || !value) {
  322. return 0;
  323. }
  324. return Math.max(0, Math.min(10_000, Math.round(value)));
  325. }
  326. function normalizeRecordingTimeoutMs(value: number | undefined, fallback: number): number {
  327. if (!Number.isFinite(value) || !value) {
  328. return fallback;
  329. }
  330. return Math.max(1, Math.min(MAX_RECORDING_TIMEOUT_MS, Math.round(value)));
  331. }
  332. async function materializeRecordingTimeline(options: {
  333. capturedFrames: Array<{ capturedAt: number; path: string }>;
  334. frameDir: string;
  335. frameIntervalMs: number;
  336. startedAt: number;
  337. stoppedAt: number;
  338. }): Promise<string[]> {
  339. const firstFrame = options.capturedFrames[0];
  340. if (!firstFrame) {
  341. throw new Error("Electron window recording lost the first captured frame");
  342. }
  343. const timelineDir = join(options.frameDir, "timeline");
  344. const durationMs = Math.max(0, options.stoppedAt - options.startedAt);
  345. const frameCount = Math.max(2, Math.ceil(durationMs / options.frameIntervalMs) + 1);
  346. const timelinePaths: string[] = [];
  347. let sourceIndex = 0;
  348. await mkdir(timelineDir, { recursive: true });
  349. for (let index = 0; index < frameCount; index += 1) {
  350. const timestamp = options.startedAt + index * options.frameIntervalMs;
  351. while (
  352. sourceIndex + 1 < options.capturedFrames.length &&
  353. (options.capturedFrames[sourceIndex + 1]?.capturedAt ?? Number.POSITIVE_INFINITY) <= timestamp
  354. ) {
  355. sourceIndex += 1;
  356. }
  357. const sourcePath = options.capturedFrames[sourceIndex]?.path ?? firstFrame.path;
  358. const timelinePath = join(timelineDir, `frame-${String(index + 1).padStart(6, "0")}.png`);
  359. await copyFile(sourcePath, timelinePath);
  360. timelinePaths.push(timelinePath);
  361. }
  362. return timelinePaths;
  363. }
  364. async function waitFor(durationMs: number, signal?: AbortSignal): Promise<void> {
  365. await new Promise<void>((resolveWait, reject) => {
  366. if (signal?.aborted) {
  367. reject(asError(signal.reason, "Electron window recording wait aborted"));
  368. return;
  369. }
  370. const timer = setTimeout(() => {
  371. signal?.removeEventListener("abort", handleAbort);
  372. resolveWait();
  373. }, durationMs);
  374. const handleAbort = () => {
  375. clearTimeout(timer);
  376. reject(asError(signal?.reason, "Electron window recording wait aborted"));
  377. };
  378. signal?.addEventListener("abort", handleAbort, { once: true });
  379. });
  380. }
  381. function resolveElectronRecordingOutputPath(value: string | undefined): string {
  382. return resolve(
  383. value?.trim() ||
  384. process.env.CODEX_E2E_VIDEO_PATH?.trim() ||
  385. join(process.env.ZCODE_E2E_ARTIFACT_DIR?.trim() || process.cwd(), "electron-repro.webm"),
  386. );
  387. }
  388. function asError(value: unknown, fallback: string): Error {
  389. if (value instanceof Error) {
  390. return value;
  391. }
  392. return new Error(value ? String(value) : fallback);
  393. }