electron-window-recorder.ts 14 KB

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