Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 减少停帧误报并完善窗口诊断 (#5628)

Dashdb0bfc4243ad
diff --git a/apps/desktop/scripts/render-recovery/README.md b/apps/desktop/scripts/render-recovery/README.md
new file mode 100644
index 0000000000..bc78f910b8
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/README.md
@@ -0,0 +1,108 @@
+# Windows 窗口恢复对照
+
+为 [Cindy #5627](https://github.com/makecindy/cindy/issues/5627) 提供不依赖提报者的
+Electron 渲染实验。生产 Electron pin 暂时保持 41.10.3;候选版本只安装到独立临时目录。
+
+## 假设与版本选择
+
+[Electron #42378](https://github.com/electron/electron/issues/42378) 报告了 Windows 上
+最小化期间关闭后台节流、恢复后等待 5~10 分钟才出现空白的路径。
+[修复 #52844](https://releases.electronjs.org/pr/52844) 已进入 43.4.1,矩阵使用该系列
+43.7.9 与 Cindy 当前的 41.10.3 对照。它修复的是窗口、view 和 compositor 的显隐同步,
+尚不能据此认定 Cindy 的这一次黑屏已经解决。
+
+不在此改动中直接跨到 44:该系列还涉及剪贴板 API 迁移和 macOS 最低版本变化。
+后续的 [#54311](https://releases.electronjs.org/pr/54311) 修复“重新开启节流后仍继续绘制”,
+与本实验的关闭节流方向不同,43.7.9 不能被当作包含所有相关修复。
+
+## 手动运行
+
+保留独立脚本供有明确新证据目标时手动运行,不提供 GitHub Actions workflow 或标签触发。
+在 Windows PowerShell 中,从仓库根目录运行一组对照(需 Node.js 22 与 npm):
+
+```powershell
+$probeVersion = '41.10.3' # 另一候选版本为 43.7.9
+$env:RENDER_PROBE_ELECTRON_DIR = Join-Path ([System.IO.Path]::GetTempPath()) ('cindy-render-electron-' + [guid]::NewGuid())
+npm install --prefix "$env:RENDER_PROBE_ELECTRON_DIR" --ignore-scripts --no-audit --no-fund "electron@$probeVersion"
+if ($LASTEXITCODE -ne 0) { throw 'Electron package installation failed' }
+node "$env:RENDER_PROBE_ELECTRON_DIR/node_modules/electron/install.js"
+if ($LASTEXITCODE -ne 0) { throw 'Electron binary installation failed' }
+$env:RENDER_PROBE_SCENARIO = 'minimize' # 或 hide
+$env:RENDER_PROBE_SURFACE = 'window' # 或 view
+$env:RENDER_PROBE_IDLE_SECONDS = '900'
+$env:RENDER_PROBE_HIDDEN_SECONDS = '3'
+node apps/desktop/scripts/render-recovery/run.mjs
+```
+
+- 默认恢复后保持 900 秒不操作;`RENDER_PROBE_HIDDEN_SECONDS=8100` 可覆盖约 2 小时 15 分钟隐藏。
+- 完整对照为 8 组:2 个 Electron 版本 × hide/minimize × BrowserWindow/WebContentsView。
+ Windows 使用无边框 Acrylic 窗口;WebContentsView 用例对应上游修复的直接回归形状。
+- 独立安装 Electron,不安装整仓依赖,不加载 Cindy、账号、任务、UU 或真实业务内容。
+ 不关闭 GPU、不改变系统设置;记录运行环境的实际 GPU 功能状态。
+
+执行顺序:先证明基线色块和原生输入正常,再隐藏/最小化、关闭节流、等待隐藏时长、恢复,
+然后保持 15 分钟不截图、不注入输入、不 resize、不刷新。最后读取页面状态,先保存截图,
+再做一次 rAF 探针和点击检查,避免主动请求新帧提前唤醒画面。页面普通 timer 只增加内存
+计数,不更新 DOM,也没有常驻动画。
+避免探测动作维持渲染,掩盖延迟帧回收问题。
+
+每组在输出目录保存合成页面的 `baseline.png`、`after-idle.png`、`events.jsonl` 和 `report.json`。
+报告包含原生显隐、节流值、renderer 身份、页面可见性、timer、rAF、截图色块及输入结果。
+输入前后检查承载窗口焦点;失焦时 `inputResponded=null`,不把无效输入探针判为失败,
+也不主动聚焦来唤醒画面。像素正常但输入无法判断时为 `inconclusive`;真实像素不匹配仍为 `failed`。
+截图来自 `capturePage()`,**不是物理显示器或 UU 远控画面的采样**;采集/输入本身也可能唤醒
+停滞的 surface,因此保留采集前后的分项观察,不能用最后一张截图证明此前从未黑屏。
+
+## 如何判读
+
+| 状态 | 含义 |
+| ----------------------- | --------------------------------------------------------------------------------- |
+| `passed` / exit 0 | 本轮最后的色块、输入、rAF 检查通过;不等于原故障已修复 |
+| `failed` / exit 1 | 基线正常,但恢复后的色块或输入检查失败 |
+| `inconclusive` / exit 2 | 基线不具备检测条件、窗口操作未生效、仅 rAF 超时、进程退出或探测超时;不能记为通过 |
+
+- 41 失败、43 通过:支持接入上游修复,接着验证完整 Cindy 的升级兼容性。
+- 两版都通过:没有复现,不能关闭 #5627;先确认环境覆盖与新证据目标,不重复运行等价对照。
+- 两版都失败:先看截图、原生状态和退出记录,区分测试环境限制与候选版本仍有问题。
+- Windows runner 是虚拟机,不能代表提报者的 Windows 11、显示驱动、多显示器或 UU 环境。
+ 测试用注入的原生输入,不证明远程软件或真实鼠标输入链路正常。
+
+正式升级前仍需完整 Cindy 的启动、原生 SQLite/PTY、内嵌浏览器、远控检查。
+42/43 的兼容性检查重点还包括 Electron 二进制安装时机、macOS 通知签名要求、
+offscreen 默认缩放、`NativeImage.toBitmap()` 色彩空间和文件对话框默认目录变化。
+本轮实验和诊断修正不引入自动重载,也不改变后台任务运行策略。
+
+## 已完成的实验
+
+2026-10-09 的 [Windows 对照 run 37922969329](https://github.com/makecindy/cindy/actions/runs/37922969329)
+使用提交 `02c6f362f82288f9d2df1c9eb69ec9a2af17c17a`,8 份报告已逐份核验:
+41.10.3 与 43.7.9 各 4/4 通过,恢复后实际静置 899.993–900.025 秒,
+基线与恢复后的像素、rAF、输入焦点及点击响应均正常,未观察到恢复差异。
+8 组均为 `gpu_compositing=disabled_software`、`rasterization=disabled_software`,
+没有覆盖硬件 GPU 合成路径;这不是 #5627 已修复或应升级生产 Electron 的证据。
+
+实验完成后移除了专用 workflow,保留手动脚本与本节结论。原始截图和报告仍受历史
+Actions artifact 的保留期限约束;对应运行的默认保留期为 14 天。
+
+## 本地检查脚本
+
+在仓库依赖已安装的情况下,使用当前开发 Electron 跑短流程(Mac 只能验证脚本本身):
+
+```sh
+RENDER_PROBE_IDLE_SECONDS=2 RENDER_PROBE_HIDDEN_SECONDS=1 \
+RENDER_PROBE_OUTPUT=/tmp/render-probe-local \
+node apps/desktop/scripts/render-recovery/run.mjs
+```
+
+用 `RENDER_PROBE_SCENARIO=hide` 或 `RENDER_PROBE_SURFACE=view` 切换场景。
+设置 `RENDER_PROBE_ELECTRON_DIR` 可使用另一个临时 npm 安装目录中的 Electron;
+先执行该包的 `install.js` 准备二进制。每次创建独立临时 userData,并在进程结束后清理。
+未指定输出目录时,在系统临时目录创建独立结果目录,并打印其路径。复用指定输出目录会
+清除本脚本上轮生成的报告、事件和两张截图;其他文件保留。截图采集、转换或写入异常
+归为 `inconclusive`,不能据此认定色块不匹配。
+短流程不覆盖延迟回收时间,不作为长时回归通过的证据。
+
+watchdog 生产侧复用 `onWindowHiddenChange`,网页隐藏或原生隐藏时均停止探针。
+原生状态未知时明确记录 `null`,不会把未知记成已确认可见;HMR 保留最近的原生状态。
+告警通过既有日志 IPC 在 main 补充真实 sender 的窗口 ID、PID、节流值和显隐状态,
+不采集窗口标题、URL、任务或对话内容。
diff --git a/apps/desktop/scripts/render-recovery/fixture.html b/apps/desktop/scripts/render-recovery/fixture.html
new file mode 100644
index 0000000000..6af1e32168
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/fixture.html
@@ -0,0 +1,51 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'self'; style-src 'unsafe-inline'"
+ />
+ <title>Render recovery fixture</title>
+ <style>
+ body {
+ margin: 0;
+ background: #183048;
+ color: white;
+ font: 20px sans-serif;
+ }
+ .swatch {
+ position: absolute;
+ top: 20px;
+ width: 80px;
+ height: 80px;
+ }
+ #red {
+ left: 20px;
+ background: #e02040;
+ }
+ #green {
+ left: 120px;
+ background: #20d060;
+ }
+ #blue {
+ left: 220px;
+ background: #3060e0;
+ }
+ button {
+ position: absolute;
+ left: 40px;
+ top: 120px;
+ width: 200px;
+ height: 40px;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="red" class="swatch"></div>
+ <div id="green" class="swatch"></div>
+ <div id="blue" class="swatch"></div>
+ <button id="input">Input probe: 0</button>
+ <script src="renderer.js"></script>
+ </body>
+</html>
diff --git a/apps/desktop/scripts/render-recovery/main.cjs b/apps/desktop/scripts/render-recovery/main.cjs
new file mode 100644
index 0000000000..c7137f83e2
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/main.cjs
@@ -0,0 +1,201 @@
+// Run only in a disposable Electron process; never loads Cindy or its user data.
+const { app, BrowserWindow, WebContentsView } = require('electron');
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const { setTimeout: delay } = require('node:timers/promises');
+const { inspectPixels } = require('./pixels.cjs');
+
+const outputDir = process.env.RENDER_PROBE_OUTPUT;
+const idleSeconds = Number(process.env.RENDER_PROBE_IDLE_SECONDS);
+const hiddenSeconds = Number(process.env.RENDER_PROBE_HIDDEN_SECONDS);
+const scenario = process.env.RENDER_PROBE_SCENARIO;
+const surface = process.env.RENDER_PROBE_SURFACE;
+if (
+ !outputDir ||
+ !process.env.RENDER_PROBE_PROFILE ||
+ !Number.isInteger(idleSeconds) ||
+ idleSeconds < 1 ||
+ idleSeconds > 1800 ||
+ !Number.isInteger(hiddenSeconds) ||
+ hiddenSeconds < 1 ||
+ hiddenSeconds > 8100 ||
+ !['hide', 'minimize'].includes(scenario) ||
+ !['window', 'view'].includes(surface)
+) {
+ throw new Error('Invalid render probe configuration');
+}
+app.setPath('userData', process.env.RENDER_PROBE_PROFILE);
+fs.mkdirSync(outputDir, { recursive: true });
+const report = {
+ electron: process.versions.electron,
+ chromium: process.versions.chrome,
+ platform: process.platform,
+ osRelease: os.release(),
+ arch: process.arch,
+ scenario,
+ surface,
+ idleSeconds,
+ hiddenSeconds,
+ status: 'inconclusive',
+ events: [],
+ samples: [],
+};
+const record = (type, data = {}) => {
+ const event = { at: Date.now(), type, ...data };
+ report.events.push(event);
+ fs.appendFileSync(path.join(outputDir, 'events.jsonl'), `${JSON.stringify(event)}\n`);
+};
+const bounded = (promise, label) =>
+ Promise.race([
+ promise,
+ delay(10_000).then(() => {
+ throw new Error(`${label} timed out`);
+ }),
+ ]);
+let win;
+let contents;
+let view;
+let finished = false;
+function finish(status, error) {
+ if (finished) return;
+ finished = true;
+ report.status = status;
+ if (error) report.error = String(error.message ?? error);
+ fs.writeFileSync(path.join(outputDir, 'report.json'), JSON.stringify(report, null, 2));
+ if (view && !view.webContents.isDestroyed()) view.webContents.close();
+ if (win && !win.isDestroyed()) win.destroy();
+ app.exit(status === 'passed' ? 0 : status === 'failed' ? 1 : 2);
+}
+process.on('uncaughtException', (error) => finish('inconclusive', error));
+process.on('unhandledRejection', (error) => finish('inconclusive', error));
+app.on('child-process-gone', (_event, details) => record('child-process-gone', details));
+const nativeState = () => ({
+ visible: win.isVisible(),
+ minimized: win.isMinimized(),
+ focused: win.isFocused(),
+ webContentsId: contents.id,
+ rendererPid: contents.getOSProcessId(),
+ backgroundThrottling: contents.getBackgroundThrottling(),
+});
+
+async function sample(label) {
+ const result = { label, at: Date.now(), native: nativeState() };
+ report.samples.push(result);
+ // Read without changing pixels first. capturePage/input may themselves wake a
+ // stalled surface; record each observation separately, not just a final verdict.
+ result.before = await bounded(contents.executeJavaScript('window.readProbe()'), 'snapshot');
+ // A capture/conversion/write exception reaches finish('inconclusive'). Only
+ // successfully collected pixels may establish a color mismatch.
+ const image = await bounded(contents.capturePage(), 'capture');
+ fs.writeFileSync(path.join(outputDir, `${label}.png`), image.toPNG());
+ const bitmap = image.resize({ width: 640, height: 480 }).toBitmap({ scaleFactor: 1 });
+ Object.assign(result, inspectPixels(bitmap));
+ // Preserve pixels before requesting a new frame, which may wake the compositor.
+ result.frame = await bounded(contents.executeJavaScript('window.probeFrame()'), 'frame probe');
+ // sendInputEvent requires a focused host window. Do not focus it here: that
+ // could wake the surface being observed. Missing focus is not failed input.
+ result.inputFocused = win.isFocused();
+ if (result.inputFocused) {
+ contents.sendInputEvent({ type: 'mouseDown', x: 140, y: 140, button: 'left', clickCount: 1 });
+ contents.sendInputEvent({ type: 'mouseUp', x: 140, y: 140, button: 'left', clickCount: 1 });
+ await delay(150);
+ }
+ result.after = await bounded(contents.executeJavaScript('window.readProbe()'), 'input snapshot');
+ result.inputFocused = result.inputFocused && win.isFocused();
+ result.inputResponded = result.inputFocused
+ ? result.after.clicks === result.before.clicks + 1
+ : null;
+ record('sample', result);
+ return result;
+}
+
+app
+ .whenReady()
+ .then(async () => {
+ report.gpuFeatures = app.getGPUFeatureStatus();
+ // Fixed synthetic page, no network, no preload, no credentials. This fixture
+ // intentionally tests native show/minimize rather than production UI readiness.
+ const webPreferences = {
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ backgroundThrottling: true,
+ };
+ win = new BrowserWindow({
+ width: 640,
+ height: 480,
+ useContentSize: true,
+ frame: false,
+ show: false,
+ backgroundColor: '#183048',
+ ...(process.platform === 'win32' ? { backgroundMaterial: 'acrylic' } : {}),
+ webPreferences,
+ });
+ contents = win.webContents;
+ if (surface === 'view') {
+ view = new WebContentsView({ webPreferences });
+ win.contentView.addChildView(view);
+ view.setBounds({ x: 0, y: 0, width: 640, height: 480 });
+ contents = view.webContents;
+ }
+ for (const event of ['show', 'hide', 'minimize', 'restore', 'unresponsive', 'responsive']) {
+ win.on(event, () => record(event, nativeState()));
+ }
+ contents.on('render-process-gone', (_event, details) => record('render-process-gone', details));
+ contents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ await contents.loadFile(path.join(__dirname, 'fixture.html'));
+ win.show();
+ win.focus();
+ contents.focus();
+ await delay(1000);
+ const baseline = await sample('baseline');
+ report.gpuFeatures = app.getGPUFeatureStatus();
+ if (
+ !baseline.native.visible ||
+ baseline.native.minimized ||
+ !baseline.pixelsMatch ||
+ !baseline.inputResponded
+ ) {
+ return finish(
+ 'inconclusive',
+ new Error('Baseline window/capture/input unavailable on this runner'),
+ );
+ }
+ win[scenario]();
+ await delay(1000);
+ if (scenario === 'hide' ? win.isVisible() : !win.isMinimized()) {
+ return finish('inconclusive', new Error(`Native ${scenario} did not take effect`));
+ }
+ contents.setBackgroundThrottling(false);
+ record('throttling-disabled-while-hidden', nativeState());
+ await delay(hiddenSeconds * 1000);
+ if (scenario === 'minimize') win.restore();
+ else win.show();
+ record('restored-start-idle', nativeState());
+ // No captures, rAF probes, input, resize or focus changes during this wait.
+ await delay(idleSeconds * 1000);
+ const recovered = await sample('after-idle');
+ if (!recovered.native.visible || recovered.native.minimized) {
+ return finish(
+ 'inconclusive',
+ new Error('Native window was not visible at final observation'),
+ );
+ }
+ // An rAF timeout alone does not mean black pixels or unresponsive input.
+ finish(
+ !recovered.pixelsMatch || recovered.inputResponded === false
+ ? 'failed'
+ : recovered.frame.arrived && recovered.inputResponded === true
+ ? 'passed'
+ : 'inconclusive',
+ );
+ })
+ .catch((error) => finish('inconclusive', error));
diff --git a/apps/desktop/scripts/render-recovery/main.test.mjs b/apps/desktop/scripts/render-recovery/main.test.mjs
new file mode 100644
index 0000000000..88dd5662bb
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/main.test.mjs
@@ -0,0 +1,192 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+import vm from 'node:vm';
+import { describe, expect, it } from 'vitest';
+
+const require = createRequire(import.meta.url);
+const source = readFileSync(new URL('./main.cjs', import.meta.url), 'utf8');
+
+// Exercise the complete probe with an in-memory window and filesystem. The
+// baseline is healthy; each fault is injected only after the window recovers.
+async function probe(fault) {
+ let captures = 0;
+ let clicks = 0;
+ let inputEvents = 0;
+ let lostFocus = false;
+ let wokenByFrame = false;
+ let report;
+ let complete;
+ const done = new Promise((resolve) => {
+ complete = resolve;
+ });
+ const contents = {
+ id: 1,
+ getOSProcessId: () => 2,
+ getBackgroundThrottling: () => false,
+ setBackgroundThrottling() {},
+ on() {},
+ focus() {},
+ setWindowOpenHandler() {},
+ async loadFile() {},
+ async executeJavaScript(script) {
+ if (script.includes('probeFrame') && clicks === 1) wokenByFrame = true;
+ return script.includes('probeFrame') ? { arrived: true } : { clicks };
+ },
+ async capturePage() {
+ captures++;
+ if (captures === 2 && fault === 'capture') throw new Error('capture rejected');
+ if (captures === 2 && fault === 'timeout') return new Promise(() => {});
+ return {
+ toPNG: () => Buffer.alloc(1),
+ resize() {
+ return this;
+ },
+ toBitmap() {
+ if (captures === 2 && fault === 'conversion') throw new Error('conversion failed');
+ return Buffer.alloc(1);
+ },
+ };
+ },
+ sendInputEvent(event) {
+ inputEvents++;
+ if (captures === 2 && fault === 'focus-during-input') lostFocus = true;
+ if (event.type === 'mouseUp' && !(captures === 2 && fault === 'input')) clicks++;
+ },
+ };
+ class Window {
+ webContents = contents;
+ visible = false;
+ show() {
+ this.visible = true;
+ }
+ hide() {
+ this.visible = false;
+ }
+ isVisible() {
+ return this.visible;
+ }
+ isMinimized() {
+ return false;
+ }
+ isFocused() {
+ return !lostFocus && !(captures === 2 && ['focus', 'pixels-unfocused'].includes(fault));
+ }
+ isDestroyed() {
+ return false;
+ }
+ on() {}
+ focus() {}
+ destroy() {}
+ }
+ const dependencies = {
+ electron: {
+ app: {
+ setPath() {},
+ on() {},
+ whenReady: () => Promise.resolve(),
+ getGPUFeatureStatus: () => ({}),
+ exit: (code) => complete({ code, report, inputEvents }),
+ },
+ BrowserWindow: Window,
+ },
+ 'node:fs': {
+ mkdirSync() {},
+ appendFileSync() {},
+ writeFileSync(file, data) {
+ if (file.endsWith('after-idle.png') && fault === 'write') throw new Error('write failed');
+ if (file.endsWith('report.json')) report = JSON.parse(data);
+ },
+ },
+ 'node:timers/promises': {
+ setTimeout: (ms) =>
+ ms === 10_000 && !(captures === 2 && fault === 'timeout')
+ ? new Promise(() => {})
+ : Promise.resolve(),
+ },
+ './pixels.cjs': {
+ inspectPixels: () => ({
+ pixelsMatch: !(
+ captures === 2 &&
+ (['pixels', 'pixels-unfocused'].includes(fault) ||
+ (fault === 'woken-by-frame' && !wokenByFrame))
+ ),
+ }),
+ },
+ };
+ vm.runInNewContext(source, {
+ require: (name) => dependencies[name] ?? require(name),
+ __dirname: path.dirname(fileURLToPath(import.meta.url)),
+ process: {
+ env: {
+ RENDER_PROBE_OUTPUT: 'memory-output',
+ RENDER_PROBE_PROFILE: 'memory-profile',
+ RENDER_PROBE_IDLE_SECONDS: '1',
+ RENDER_PROBE_HIDDEN_SECONDS: '1',
+ RENDER_PROBE_SCENARIO: 'hide',
+ RENDER_PROBE_SURFACE: 'window',
+ },
+ versions: {},
+ platform: 'win32',
+ arch: 'x64',
+ on() {},
+ },
+ });
+ return done;
+}
+
+describe('render probe evidence classification', () => {
+ it.each(['capture', 'timeout', 'conversion', 'write'])(
+ 'treats %s errors as inconclusive',
+ async (fault) => {
+ const { code, report } = await probe(fault);
+ expect(code).toBe(2);
+ expect(report.status).toBe('inconclusive');
+ expect(report.error).toBeTruthy();
+ expect(report.samples.at(-1).pixelsMatch).toBeUndefined();
+ },
+ );
+ it('fails only when collected pixels mismatch', async () => {
+ const { code, report } = await probe('pixels');
+ expect(code).toBe(1);
+ expect(report.samples.at(-1).pixelsMatch).toBe(false);
+ });
+ it('passes healthy evidence', async () => {
+ expect((await probe()).report.status).toBe('passed');
+ });
+ it.each(['focus', 'focus-during-input'])(
+ 'treats %s as inconclusive instead of failed input',
+ async (fault) => {
+ const { code, report, inputEvents } = await probe(fault);
+ expect(code).toBe(2);
+ expect(report.status).toBe('inconclusive');
+ expect(report.samples.at(-1)).toMatchObject({
+ pixelsMatch: true,
+ frame: { arrived: true },
+ inputFocused: false,
+ inputResponded: null,
+ });
+ expect(inputEvents).toBe(fault === 'focus' ? 2 : 4);
+ },
+ );
+ it('preserves pixel failure even when input cannot be assessed without focus', async () => {
+ const { code, report } = await probe('pixels-unfocused');
+ expect(code).toBe(1);
+ expect(report.samples.at(-1)).toMatchObject({ pixelsMatch: false, inputResponded: null });
+ });
+ it('still fails unresponsive input in a focused window', async () => {
+ const { code, report } = await probe('input');
+ expect(code).toBe(1);
+ expect(report.samples.at(-1)).toMatchObject({ inputFocused: true, inputResponded: false });
+ });
+ it('preserves a bad restored frame even when the rAF probe wakes the compositor', async () => {
+ const { code, report } = await probe('woken-by-frame');
+ expect(code).toBe(1);
+ expect(report.samples.at(-1)).toMatchObject({
+ pixelsMatch: false,
+ frame: { arrived: true },
+ inputResponded: true,
+ });
+ });
+});
diff --git a/apps/desktop/scripts/render-recovery/pixels.cjs b/apps/desktop/scripts/render-recovery/pixels.cjs
new file mode 100644
index 0000000000..8a1db2d6ea
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/pixels.cjs
@@ -0,0 +1,19 @@
+// NativeImage bitmap is BGRA. The caller explicitly requests scaleFactor: 1.
+function inspectPixels(bitmap) {
+ if (bitmap.length !== 640 * 480 * 4) return { pixelsMatch: false, bitmapBytes: bitmap.length };
+ const colors = [60, 160, 260].map((x) => {
+ const offset = (60 * 640 + x) * 4;
+ return [bitmap[offset + 2], bitmap[offset + 1], bitmap[offset]];
+ });
+ return {
+ colors,
+ // Electron 41 returns the display color space; 43 defaults to sRGB. Test
+ // three distinct dominant channels rather than requiring identical bytes.
+ pixelsMatch: colors.every(
+ (rgb, dominant) =>
+ rgb[dominant] >= 150 &&
+ rgb.every((value, channel) => channel === dominant || rgb[dominant] - value >= 70),
+ ),
+ };
+}
+module.exports = { inspectPixels };
diff --git a/apps/desktop/scripts/render-recovery/pixels.test.mjs b/apps/desktop/scripts/render-recovery/pixels.test.mjs
new file mode 100644
index 0000000000..dbdd595abb
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/pixels.test.mjs
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import pixels from './pixels.cjs';
+
+describe('render probe pixel evidence', () => {
+ it('rejects black, backing-only and empty frames', () => {
+ expect(pixels.inspectPixels(Buffer.alloc(640 * 480 * 4)).pixelsMatch).toBe(false);
+ expect(pixels.inspectPixels(Buffer.alloc(640 * 480 * 4, 80)).pixelsMatch).toBe(false);
+ expect(pixels.inspectPixels(Buffer.alloc(0)).pixelsMatch).toBe(false);
+ });
+ it.each([
+ [
+ [224, 33, 64],
+ [33, 208, 96],
+ [48, 96, 224],
+ ],
+ [
+ [206, 56, 70],
+ [99, 205, 109],
+ [60, 95, 216],
+ ],
+ ])(
+ 'accepts distinct fixture swatches across sRGB and display color spaces',
+ (red, green, blue) => {
+ const bitmap = Buffer.alloc(640 * 480 * 4);
+ for (const [x, rgb] of [
+ [60, red],
+ [160, green],
+ [260, blue],
+ ]) {
+ const offset = (60 * 640 + x) * 4;
+ bitmap.set([rgb[2], rgb[1], rgb[0], 255], offset);
+ }
+ expect(pixels.inspectPixels(bitmap).pixelsMatch).toBe(true);
+ bitmap.fill(0, (60 * 640 + 160) * 4, (60 * 640 + 160) * 4 + 4);
+ expect(pixels.inspectPixels(bitmap).pixelsMatch).toBe(false);
+ },
+ );
+ it('rejects an unexpected scale factor instead of reading the wrong pixel offsets', () => {
+ expect(pixels.inspectPixels(Buffer.alloc(1280 * 960 * 4))).toEqual({
+ pixelsMatch: false,
+ bitmapBytes: 1280 * 960 * 4,
+ });
+ });
+});
diff --git a/apps/desktop/scripts/render-recovery/renderer.js b/apps/desktop/scripts/render-recovery/renderer.js
new file mode 100644
index 0000000000..1b8bc93145
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/renderer.js
@@ -0,0 +1,34 @@
+// Synthetic content only. No continuous animation/DOM updates: those would prevent
+// the delayed frame eviction that electron/electron#42378 describes.
+let clicks = 0;
+let timerTicks = 0;
+const visibilityEvents = [];
+setInterval(() => {
+ timerTicks += 1;
+}, 1000);
+document.addEventListener('visibilitychange', () => {
+ visibilityEvents.push({ at: Date.now(), state: document.visibilityState });
+});
+document.getElementById('input').addEventListener('click', (event) => {
+ if (!event.isTrusted) return;
+ clicks += 1;
+ event.currentTarget.textContent = `Input probe: ${clicks}`;
+});
+window.readProbe = () => ({
+ clicks,
+ timerTicks,
+ visibility: document.visibilityState,
+ visibilityEvents,
+});
+window.probeFrame = () =>
+ new Promise((resolve) => {
+ const startedAt = performance.now();
+ const raf = requestAnimationFrame(() => {
+ clearTimeout(timeout);
+ resolve({ arrived: true, elapsedMs: performance.now() - startedAt });
+ });
+ const timeout = setTimeout(() => {
+ cancelAnimationFrame(raf);
+ resolve({ arrived: false, elapsedMs: performance.now() - startedAt });
+ }, 2500);
+ });
diff --git a/apps/desktop/scripts/render-recovery/run.mjs b/apps/desktop/scripts/render-recovery/run.mjs
new file mode 100644
index 0000000000..76dda01f81
--- /dev/null
+++ b/apps/desktop/scripts/render-recovery/run.mjs
@@ -0,0 +1,101 @@
+import { spawn } from 'node:child_process';
+import { createRequire } from 'node:module';
+import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { fileURLToPath } from 'node:url';
+
+const outputDir = process.env.RENDER_PROBE_OUTPUT
+ ? path.resolve(process.env.RENDER_PROBE_OUTPUT)
+ : await mkdtemp(path.join(os.tmpdir(), 'cindy-render-results-'));
+const installDir = process.env.RENDER_PROBE_ELECTRON_DIR;
+const require = createRequire(
+ installDir ? path.join(path.resolve(installDir), 'package.json') : import.meta.url,
+);
+const electron = require('electron');
+const env = {
+ ...process.env,
+ RENDER_PROBE_OUTPUT: outputDir,
+ RENDER_PROBE_IDLE_SECONDS: process.env.RENDER_PROBE_IDLE_SECONDS ?? '900',
+ RENDER_PROBE_HIDDEN_SECONDS: process.env.RENDER_PROBE_HIDDEN_SECONDS ?? '3',
+ RENDER_PROBE_SCENARIO: process.env.RENDER_PROBE_SCENARIO ?? 'minimize',
+ RENDER_PROBE_SURFACE: process.env.RENDER_PROBE_SURFACE ?? 'window',
+};
+delete env.ELECTRON_RUN_AS_NODE;
+delete env.NODE_OPTIONS;
+const idleSeconds = Number(env.RENDER_PROBE_IDLE_SECONDS);
+const hiddenSeconds = Number(env.RENDER_PROBE_HIDDEN_SECONDS);
+if (
+ !Number.isInteger(idleSeconds) ||
+ idleSeconds < 1 ||
+ idleSeconds > 1800 ||
+ !Number.isInteger(hiddenSeconds) ||
+ hiddenSeconds < 1 ||
+ hiddenSeconds > 8100
+) {
+ throw new Error('Invalid probe durations: idle 1..1800, hidden 1..8100 seconds');
+}
+const profile = await mkdtemp(path.join(os.tmpdir(), 'cindy-render-probe-'));
+env.RENDER_PROBE_PROFILE = profile;
+await mkdir(outputDir, { recursive: true });
+// A reused local output directory must not supply evidence from an earlier run.
+for (const file of ['report.json', 'events.jsonl', 'baseline.png', 'after-idle.png']) {
+ await rm(path.join(outputDir, file), { force: true });
+}
+process.stdout.write(`Render probe output: ${outputDir}\n`);
+const child = spawn(electron, [fileURLToPath(new URL('./main.cjs', import.meta.url))], {
+ env,
+ stdio: 'inherit',
+});
+const timeout = setTimeout(() => child.kill(), (idleSeconds + hiddenSeconds + 90) * 1000);
+const exitCode = await new Promise((resolve) => {
+ child.once('error', () => resolve(2));
+ child.once('close', (code) => resolve(code ?? 2));
+});
+clearTimeout(timeout);
+let resultExitCode = exitCode;
+try {
+ const report = JSON.parse(await readFile(path.join(outputDir, 'report.json'), 'utf8'));
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ if (report.status !== 'passed' && resultExitCode === 0) resultExitCode = 2;
+ if (process.env.GITHUB_STEP_SUMMARY) {
+ const final = report.samples?.at(-1);
+ await appendFile(
+ process.env.GITHUB_STEP_SUMMARY,
+ [
+ `Electron ${report.electron}: **${report.status}**`,
+ '',
+ `Scenario: ${report.scenario}; surface: ${report.surface}; idle: ${idleSeconds}s; hidden: ${hiddenSeconds}s.`,
+ '',
+ `Final pixels: ${final?.pixelsMatch ?? 'unknown'}; input: ${final?.inputResponded ?? 'unknown'}; rAF: ${final?.frame?.arrived ?? 'unknown'}.`,
+ '',
+ 'Synthetic Electron fixture only. A pass does not prove Cindy #5627 is fixed.',
+ '',
+ ].join('\n'),
+ ).catch((error) => {
+ // A CI summary failure must not overwrite the original diagnostic report.
+ process.stderr.write(`Could not write step summary: ${error.message}\n`);
+ });
+ }
+} catch {
+ resultExitCode = 2;
+ process.stderr.write('Electron probe exited without a report; result is inconclusive.\n');
+ await writeFile(
+ path.join(outputDir, 'report.json'),
+ JSON.stringify(
+ {
+ status: 'inconclusive',
+ error: 'Electron probe exited without a report',
+ exitCode,
+ },
+ null,
+ 2,
+ ),
+ );
+}
+try {
+ await rm(profile, { recursive: true, force: true, maxRetries: 3 });
+} catch {
+ /* Runner teardown also removes its temporary profile. */
+}
+process.exitCode = resultExitCode;
diff --git a/apps/desktop/src/main/__tests__/renderWatchdogContext.test.ts b/apps/desktop/src/main/__tests__/renderWatchdogContext.test.ts
new file mode 100644
index 0000000000..f47a2cf87f
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/renderWatchdogContext.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+import { getRenderWatchdogContext } from '../renderWatchdogContext';
+
+const contents = {
+ id: 7,
+ isDestroyed: () => false,
+ getOSProcessId: () => 42,
+ getBackgroundThrottling: () => false,
+};
+const win = {
+ id: 3,
+ isDestroyed: () => false,
+ isVisible: () => true,
+ isMinimized: () => true,
+};
+
+describe('render watchdog native context', () => {
+ it('captures sender identity and real window/throttling state without URLs or titles', () => {
+ expect(getRenderWatchdogContext(contents, win)).toEqual({
+ webContentsId: 7,
+ windowId: 3,
+ nativeObservedAt: expect.any(Number),
+ rendererPid: 42,
+ backgroundThrottling: false,
+ nativeVisible: true,
+ nativeMinimized: true,
+ });
+ });
+
+ it('marks a missing native window as unknown rather than visible', () => {
+ expect(getRenderWatchdogContext(contents, null)).toMatchObject({
+ windowId: null,
+ nativeVisible: null,
+ nativeMinimized: null,
+ });
+ });
+
+ it('does not throw when shutdown destroys the sender or a native getter fails', () => {
+ expect(getRenderWatchdogContext({ ...contents, isDestroyed: () => true }, win)).toMatchObject({
+ nativeStateUnavailable: true,
+ });
+ expect(getRenderWatchdogContext(contents, { ...win, isDestroyed: () => true })).toMatchObject({
+ nativeStateUnavailable: true,
+ });
+ expect(
+ getRenderWatchdogContext(
+ {
+ ...contents,
+ getOSProcessId: () => {
+ throw new Error('Object has been destroyed');
+ },
+ },
+ win,
+ ),
+ ).toMatchObject({ nativeStateUnavailable: true });
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 4295b05449..2a244ef953 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -941,6 +941,7 @@ import { registerFileBrowserDeviceOp } from './file-browser/device-op.js';
import { registerSearchIpc } from './file-browser/search/index.js';
import { registerVoiceInputIpc } from './voice-input/index.js';
import { installWindowHiddenBroadcast } from './windowHiddenBroadcast.js';
+import { getRenderWatchdogContext } from './renderWatchdogContext.js';
import {
isSecondaryAppWindow,
openSessionInNewWindow,
@@ -4503,14 +4504,21 @@ const registerIpcHandlers = () => {
ipcMain.on(
'renderer:log',
(
- _e,
+ event,
level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
scope: string,
msg: string,
) => {
// renderer 能发日志 = JS 已跑起来 → 解除 dev 启动看门狗(见 renderer-boot-guard.ts)。
rendererBootGuard?.markAlive();
- writeFromRenderer(level, scope, msg);
+ // 原生状态在收到告警时从真正的 sender 读取,无需增加 renderer 查询 IPC。
+ if (scope === 'render-watchdog') {
+ const win = event.sender.isDestroyed() ? null : BrowserWindow.fromWebContents(event.sender);
+ const context = getRenderWatchdogContext(event.sender, win);
+ writeFromRenderer(level, scope, `${msg} ${JSON.stringify(context)}`);
+ } else {
+ writeFromRenderer(level, scope, msg);
+ }
},
);
diff --git a/apps/desktop/src/main/renderWatchdogContext.ts b/apps/desktop/src/main/renderWatchdogContext.ts
new file mode 100644
index 0000000000..1ae3cabe9b
--- /dev/null
+++ b/apps/desktop/src/main/renderWatchdogContext.ts
@@ -0,0 +1,25 @@
+import type { BrowserWindow, WebContents } from 'electron';
+
+/** 只读原生数值/状态,不采集窗口标题、URL 或任何业务内容。 */
+export function getRenderWatchdogContext(
+ contents: Pick<WebContents, 'id' | 'isDestroyed' | 'getOSProcessId' | 'getBackgroundThrottling'>,
+ win: Pick<BrowserWindow, 'id' | 'isDestroyed' | 'isVisible' | 'isMinimized'> | null,
+) {
+ const identity = { webContentsId: contents.id, windowId: win?.id ?? null };
+ try {
+ if (contents.isDestroyed() || win?.isDestroyed()) {
+ return { ...identity, nativeStateUnavailable: true };
+ }
+ return {
+ ...identity,
+ nativeObservedAt: Date.now(),
+ rendererPid: contents.getOSProcessId(),
+ backgroundThrottling: contents.getBackgroundThrottling(),
+ nativeVisible: win?.isVisible() ?? null,
+ nativeMinimized: win?.isMinimized() ?? null,
+ };
+ } catch {
+ // 窗口在退出过程中销毁时,诊断不能反过来打断退出/原始日志。
+ return { ...identity, nativeStateUnavailable: true };
+ }
+}
diff --git a/apps/desktop/src/renderer/__tests__/renderLoopWatchdog.test.ts b/apps/desktop/src/renderer/__tests__/renderLoopWatchdog.test.ts
index 595face1c0..47a6840eeb 100644
--- a/apps/desktop/src/renderer/__tests__/renderLoopWatchdog.test.ts
+++ b/apps/desktop/src/renderer/__tests__/renderLoopWatchdog.test.ts
@@ -34,6 +34,7 @@ function createHarness(initialVisibility: DocumentVisibilityState = 'visible') {
const timeouts = new Map<number, () => void>();
const rafs = new Map<number, FrameRequestCallback>();
const visibilityListeners = new Set<() => void>();
+ const nativeHiddenListeners = new Set<(hidden: boolean) => void>();
let nextHandle = 1;
const target: RenderLoopWatchdogTarget = {
@@ -49,6 +50,12 @@ function createHarness(initialVisibility: DocumentVisibilityState = 'visible') {
},
},
window: {
+ electronAPI: {
+ onWindowHiddenChange: (cb) => {
+ nativeHiddenListeners.add(cb);
+ return () => nativeHiddenListeners.delete(cb);
+ },
+ },
setInterval: ((cb: () => void) => {
const id = nextHandle++;
intervals.set(id, cb);
@@ -86,6 +93,10 @@ function createHarness(initialVisibility: DocumentVisibilityState = 'visible') {
visibility = v;
for (const cb of [...visibilityListeners]) cb();
},
+ setNativeHidden(hidden: boolean) {
+ for (const cb of nativeHiddenListeners) cb(hidden);
+ },
+ nativeListenerCount: () => nativeHiddenListeners.size,
fireInterval() {
for (const cb of [...intervals.values()]) cb();
},
@@ -184,7 +195,7 @@ describe('renderLoopWatchdog', () => {
h.flushTimeouts(); // 探针超时,帧一直没来
expect(loggerMock.warn).toHaveBeenCalledWith(
- '页面可见但帧管线无输出(疑似白屏)',
+ '可见状态下动画帧探针超时',
expect.objectContaining({ probeTimeoutMs: 2_000 }),
);
@@ -198,7 +209,7 @@ describe('renderLoopWatchdog', () => {
h.advance(3_000);
h.flushFrames();
expect(loggerMock.warn).toHaveBeenCalledWith(
- '帧管线恢复出帧',
+ '动画帧回调恢复',
expect.objectContaining({ stalledDurationMs: expect.any(Number) }),
);
dispose();
@@ -238,6 +249,7 @@ describe('renderLoopWatchdog', () => {
expect(h.pendingIntervalCount()).toBe(0);
expect(h.pendingRafCount()).toBe(0);
expect(h.pendingTimeoutCount()).toBe(0);
+ expect(h.nativeListenerCount()).toBe(0);
});
it('重复 install 会先卸载旧实例(disposer key 幂等)', () => {
@@ -245,8 +257,88 @@ describe('renderLoopWatchdog', () => {
installRenderLoopWatchdog(h.target);
installRenderLoopWatchdog(h.target);
expect(h.pendingIntervalCount()).toBe(1);
- (h.target.window as { __xdtRenderLoopWatchdogDisposer?: () => void })
- .__xdtRenderLoopWatchdogDisposer?.();
+ (
+ h.target.window as { __xdtRenderLoopWatchdogDisposer?: () => void }
+ ).__xdtRenderLoopWatchdogDisposer?.();
expect(h.pendingIntervalCount()).toBe(0);
});
+
+ it('原生隐藏但网页仍 visible 时取消探针,隐藏期漂移不告警', () => {
+ const h = createHarness();
+ const dispose = installRenderLoopWatchdog(h.target);
+ h.fireInterval();
+ h.setNativeHidden(true);
+ h.advance(60_000);
+ h.flushTimeouts();
+ h.fireInterval();
+ expect(h.pendingRafCount()).toBe(0);
+ expect(loggerMock.warn).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('原生恢复而网页没有 visibilitychange 时立即探测,跳过隐藏期漂移', () => {
+ const h = createHarness();
+ const dispose = installRenderLoopWatchdog(h.target);
+ h.setNativeHidden(true);
+ h.advance(60_000);
+ h.setNativeHidden(false);
+ expect(h.pendingRafCount()).toBe(1);
+ h.advance(2_000);
+ h.flushTimeouts();
+ expect(loggerMock.warn).toHaveBeenCalledWith(
+ '可见状态下动画帧探针超时',
+ expect.objectContaining({
+ observedAt: 62_000,
+ probeStartedAt: 60_000,
+ documentVisibility: 'visible',
+ nativeHidden: false,
+ nativeStateReceivedAt: 60_000,
+ }),
+ );
+ loggerMock.warn.mockClear();
+ h.advance(55_000);
+ h.fireInterval();
+ expect(loggerMock.warn).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('原生显示不覆盖页面隐藏,页面显示也不覆盖原生隐藏', () => {
+ const h = createHarness('hidden');
+ const dispose = installRenderLoopWatchdog(h.target);
+ h.setNativeHidden(false);
+ expect(h.pendingRafCount()).toBe(0);
+ h.setNativeHidden(true);
+ h.setVisibility('visible');
+ expect(h.pendingRafCount()).toBe(0);
+ h.setNativeHidden(false);
+ expect(h.pendingRafCount()).toBe(1);
+ dispose();
+ });
+
+ it('停顿后原生隐藏终止旧 episode,恢复后不会误报旧探针恢复', () => {
+ const h = createHarness();
+ const dispose = installRenderLoopWatchdog(h.target);
+ h.fireInterval();
+ h.advance(2_000);
+ h.flushTimeouts();
+ loggerMock.warn.mockClear();
+ h.setNativeHidden(true);
+ h.setNativeHidden(false);
+ h.flushFrames();
+ expect(loggerMock.warn).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('隐藏时 HMR 重装保留原生状态且只保留一个监听', () => {
+ const h = createHarness();
+ installRenderLoopWatchdog(h.target);
+ h.setNativeHidden(true);
+ const dispose = installRenderLoopWatchdog(h.target);
+ h.advance(60_000);
+ h.fireInterval();
+ expect(h.nativeListenerCount()).toBe(1);
+ expect(h.pendingRafCount()).toBe(0);
+ expect(loggerMock.warn).not.toHaveBeenCalled();
+ dispose();
+ });
});
diff --git a/apps/desktop/src/renderer/lib/renderLoopWatchdog.ts b/apps/desktop/src/renderer/lib/renderLoopWatchdog.ts
index d54b9c7a2c..7f59e4ec2c 100644
--- a/apps/desktop/src/renderer/lib/renderLoopWatchdog.ts
+++ b/apps/desktop/src/renderer/lib/renderLoopWatchdog.ts
@@ -13,8 +13,8 @@ const log = createLogger('render-watchdog');
* 系统睡眠也会产生大漂移,靠 main 侧 power-diagnostics 的 suspend/resume
* 日志时间戳交叉排除。
* 2. rAF 探针 —— 页面可见时每 tick 发一个 requestAnimationFrame,超时未回调
- * 且页面仍可见,说明主线程活着(timer 能跑)但合成器没在出帧,正是
- * 「白屏但没卡死」的指纹。每个停摆episode只记一次,恢复时再记一条。
+ * 且页面与原生窗口均未报告隐藏时记告警。它只证明回调超时,不能证明画面
+ * 全黑或 GPU 故障。每个 episode 只记一次,回调恢复时再记一条。
*
* 性能:仅一个 5s 间隔的 timer + 可见时每 5s 一个一次性 rAF,无常驻动画、
* 无每帧回调,不违反设计规范规则 7。
@@ -22,7 +22,7 @@ const log = createLogger('render-watchdog');
const CHECK_INTERVAL_MS = 5_000;
/** interval 实际触发晚于期望超过该值,视为主线程曾被阻塞,记一条日志。 */
const TIMER_STALL_THRESHOLD_MS = 3_000;
-/** 可见状态下 rAF 超过该时长未回调,视为帧管线停摆。 */
+/** 可见状态下 rAF 超过该时长未回调,记录探针超时。 */
const FRAME_PROBE_TIMEOUT_MS = 2_000;
const RENDER_LOOP_WATCHDOG_DISPOSER_KEY = '__xdtRenderLoopWatchdogDisposer';
@@ -34,6 +34,11 @@ export interface RenderLoopWatchdogTarget {
requestAnimationFrame: (cb: FrameRequestCallback) => number;
cancelAnimationFrame: (id: number) => void;
__xdtRenderLoopWatchdogDisposer?: () => void;
+ // HMR 不会触发 main 的 did-finish-load 基线补发,保留最近一次原生状态。
+ __xdtRenderLoopWatchdogNativeState?: { hidden: boolean; receivedAt: number };
+ electronAPI?: {
+ onWindowHiddenChange?: (callback: (hidden: boolean) => void) => () => void;
+ };
};
now: () => number;
}
@@ -48,6 +53,15 @@ export function installRenderLoopWatchdog(
target.window[RENDER_LOOP_WATCHDOG_DISPOSER_KEY]?.();
let lastTickAt = target.now();
+ const isVisible = (): boolean =>
+ target.document.visibilityState === 'visible' &&
+ target.window.__xdtRenderLoopWatchdogNativeState?.hidden !== true;
+ const diagnosticContext = () => ({
+ observedAt: target.now(),
+ documentVisibility: target.document.visibilityState,
+ nativeHidden: target.window.__xdtRenderLoopWatchdogNativeState?.hidden ?? null,
+ nativeStateReceivedAt: target.window.__xdtRenderLoopWatchdogNativeState?.receivedAt ?? null,
+ });
// 转入可见后的第一个 tick 不判漂移:该 tick 的实际触发时刻仍由隐藏期节流
// 调度决定,漂移不反映可见期主线程状态。
let skipNextDriftCheck = false;
@@ -76,7 +90,9 @@ export function installRenderLoopWatchdog(
probeTimeoutId = null;
}
if (probeState === 'stalled' && stalledSinceMs !== null) {
- log.warn('帧管线恢复出帧', {
+ log.warn('动画帧回调恢复', {
+ ...diagnosticContext(),
+ probeStartedAt: stalledSinceMs,
stalledDurationMs: Math.max(0, Math.round(target.now() - stalledSinceMs)),
});
}
@@ -87,7 +103,7 @@ export function installRenderLoopWatchdog(
const onProbeTimeout = (probeStartedAt: number): void => {
probeTimeoutId = null;
// 超时瞬间页面已隐藏的话不算停摆 —— 隐藏页 rAF 本来就不触发。
- if (target.document.visibilityState !== 'visible') {
+ if (!isVisible()) {
clearProbe();
probeState = 'idle';
stalledSinceMs = null;
@@ -96,7 +112,9 @@ export function installRenderLoopWatchdog(
if (probeState === 'probing') {
probeState = 'stalled';
stalledSinceMs = probeStartedAt;
- log.warn('页面可见但帧管线无输出(疑似白屏)', {
+ log.warn('可见状态下动画帧探针超时', {
+ ...diagnosticContext(),
+ probeStartedAt,
probeTimeoutMs: FRAME_PROBE_TIMEOUT_MS,
});
}
@@ -104,7 +122,7 @@ export function installRenderLoopWatchdog(
const startProbe = (): void => {
// 已有在途探针(含 stalled 后留下的 rAF,它一回调就是恢复信号)就不再叠加。
- if (probeRafId !== null || target.document.visibilityState !== 'visible') return;
+ if (probeRafId !== null || !isVisible()) return;
const startedAt = target.now();
if (probeState === 'idle') probeState = 'probing';
probeRafId = target.window.requestAnimationFrame(onProbeFrame);
@@ -123,12 +141,13 @@ export function installRenderLoopWatchdog(
// 隐藏期不判漂移 —— 主窗 backgroundThrottling 开着,页面隐藏超 5 分钟后
// Chromium intensive throttling 会把 interval 压到每分钟一次,漂移是预期
// 行为,判了就是整夜刷屏的假告警。可见期的漂移才是「主线程曾被阻塞」信号。
- const shouldCheckDrift = !skipNextDriftCheck && target.document.visibilityState === 'visible';
+ const shouldCheckDrift = !skipNextDriftCheck && isVisible();
skipNextDriftCheck = false;
if (driftMs >= TIMER_STALL_THRESHOLD_MS && shouldCheckDrift) {
// 事后追认:这段时间要么主线程被同步阻塞,要么系统在睡眠(与 main 侧
// power-diagnostics 的 resume 时间戳对照区分)。
log.warn('renderer 定时器漂移(主线程曾阻塞或系统睡眠)', {
+ ...diagnosticContext(),
driftMs: Math.round(driftMs),
});
}
@@ -136,7 +155,7 @@ export function installRenderLoopWatchdog(
};
const onVisibilityChange = (): void => {
- if (target.document.visibilityState === 'visible') {
+ if (isVisible()) {
// 隐藏期的节流漂移不能记到下个可见 tick 头上,重置漂移基准并跳过下个
// tick 的漂移判定(它的触发时刻仍是节流期排的)。
lastTickAt = target.now();
@@ -152,6 +171,10 @@ export function installRenderLoopWatchdog(
const intervalId = target.window.setInterval(onTick, CHECK_INTERVAL_MS);
target.document.addEventListener('visibilitychange', onVisibilityChange);
+ const unsubscribeWindowHidden = target.window.electronAPI?.onWindowHiddenChange?.((hidden) => {
+ target.window.__xdtRenderLoopWatchdogNativeState = { hidden, receivedAt: target.now() };
+ onVisibilityChange();
+ });
let disposed = false;
const dispose = (): void => {
@@ -159,6 +182,7 @@ export function installRenderLoopWatchdog(
disposed = true;
target.window.clearInterval(intervalId);
target.document.removeEventListener('visibilitychange', onVisibilityChange);
+ unsubscribeWindowHidden?.();
clearProbe();
if (target.window[RENDER_LOOP_WATCHDOG_DISPOSER_KEY] === dispose) {
delete target.window[RENDER_LOOP_WATCHDOG_DISPOSER_KEY];
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 10b225987f..45e25f2458 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -194,6 +194,12 @@ pnpm test:unit
对应规则,不以本页命令替代专项验证。
- 记录实际执行和结果;未执行的高相关检查必须说明原因。
+## Windows 窗口恢复实验
+
+Windows 偶发黑屏/灰屏的后台节流对照实验见
+[窗口恢复对照](../../apps/desktop/scripts/render-recovery/README.md)。它按需使用 GitHub
+Windows runner,独立于默认单测;短流程通过和完整 Cindy 故障已修复必须分开判断。
+
## Windows 安装目录与授权
NSIS 安装器保留当前用户/所有用户两种范围。普通用户可写的目录无需提权;选择受保护的