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。

perf(desktop): 页面不可见时冻结常驻装饰动画 (#658)

Dashe47a7369abff
diff --git a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
index db4e864dea..d9faaba378 100644
--- a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
+++ b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
@@ -8,8 +8,8 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, relative, resolve, sep } from 'node:path';
import {
hasAnySessionInTurn,
isTerminalTurnErrorEvent,
@@ -21,6 +21,20 @@ import type { AgentEvent } from '@cindy/maker-core';
const sourcePath = resolve(__dirname, '..', 'bootstrap-electron.ts');
const source = readFileSync(sourcePath, 'utf8').replace(/\r\n?/g, '\n');
+/**
+ * 剥掉 TS 注释后再做关键字计数:`backgroundThrottling: false` /
+ * `installWindowHiddenBroadcast` 这些串在说明性注释里也会出现,不剥会把数目算虚。
+ * `[^:]` 前导避免误伤 `https://` 这类。
+ */
+function stripComments(text: string): string {
+ return text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
+}
+
+/** 路径分隔符归一成 POSIX:Windows 上 path.relative 返回反斜杠。 */
+function toPosix(p: string): string {
+ return p.split(sep).join('/');
+}
+
describe('主 BrowserWindow 后台节流', () => {
afterEach(() => {
vi.useRealTimers();
@@ -128,3 +142,112 @@ describe('主 BrowserWindow 后台节流', () => {
expect(isTerminalTurnErrorEvent(legacyError)).toBe(true);
});
});
+
+/**
+ * 关闭节流会让 Renderer 的 document.visibilityState 一直停在 'visible'(Electron 41.2.0
+ * 实测:throttling=false 时 minimize()/hide() 后仍为 visible),所以装饰动画闸门不能只靠
+ * visibilityState —— 必须有 main 侧广播兜底。两者是同一套机制的两半,一旦广播被删掉,
+ * 闸门会在「窗口隐藏 + 节流关闭」这个主场景下静默失效,故在此加源码契约守护。
+ */
+describe('窗口可见性广播(装饰动画闸门的兜底信号)', () => {
+ const broadcastSource = readFileSync(
+ resolve(__dirname, '..', 'windowHiddenBroadcast.ts'),
+ 'utf8',
+ ).replace(/\r\n?/g, '\n');
+
+ it('按 BrowserWindow 显隐事件广播,判据同时覆盖 hide 与最小化', () => {
+ expect(broadcastSource).toContain(
+ 'const hidden = !win.isVisible() || win.isMinimized();',
+ );
+ expect(broadcastSource).toContain('win.webContents.send(WINDOW_HIDDEN_CHANGE_CHANNEL, hidden);');
+ for (const event of ['hide', 'show', 'minimize', 'restore']) {
+ expect(broadcastSource).toContain(`win.on('${event}', emit);`);
+ }
+ });
+
+ it('页面加载完成后补发基线,避免 Renderer 惰性订阅错过隐藏态', () => {
+ expect(broadcastSource).toContain("win.webContents.on('did-finish-load', emit);");
+ });
+
+ /**
+ * 关掉 backgroundThrottling 的窗口,若其 renderer 装了装饰动画闸门,就必须同时装广播:
+ * 节流关闭 → visibilityState 恒为 visible,又收不到广播 → 两路信号同时失效,闸门形同虚设。
+ *
+ * 不写死清单,而是扫描整个 main 目录。语音浮窗当初就是这么漏掉的(它和主窗一样加载
+ * index.html,闸门在 index.tsx 顶层安装,浮窗视图同样经过)。
+ *
+ * 豁免必须显式登记并写明理由——目的是逼一次判断,而不是让人默默跳过。
+ */
+ const BROADCAST_EXEMPT = new Map<string, string>([
+ [
+ 'computer-permission-guide/window.ts',
+ // 这两个窗口(guide / backdrop)确实也加载 index.html?view=、也装了闸门,但其视图
+ // (ComputerPermissionGuideWindow.tsx)不含任何常驻装饰动画,装广播纯属空转;且该文件
+ // 的测试 mock 用单 listener Map,多注册一个 did-finish-load 会覆盖既有回调。
+ // 将来这两个视图若引入常驻动画,删掉本豁免即可。
+ '权限引导窗与 backdrop 视图无常驻装饰动画',
+ ],
+ ]);
+
+ it('关闭了 backgroundThrottling 的窗口要么装广播,要么显式登记豁免', () => {
+ const mainDir = resolve(__dirname, '..');
+ const walk = (dir: string, out: string[] = []): string[] => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) walk(full, out);
+ else if (entry.name.endsWith('.ts')) out.push(full);
+ }
+ return out;
+ };
+
+ // 按「窗口」计数而不是「文件是否提到过」:voice-input/global.ts 里有两个关掉节流的
+ // 窗口(浮窗 + 词典 toast),只看 includes 的话第一个装了就把第二个放过去了。
+ // 计数前先剥注释:这些关键字在说明性注释里也会出现,不剥的话数目虚高。
+ // 调用点用带实参的形式计数,避免把 import 语句算进去。
+ const countMatches = (text: string, re: RegExp): number => [...text.matchAll(re)].length;
+
+ const offenders: string[] = [];
+ for (const file of walk(mainDir)) {
+ const content = stripComments(readFileSync(file, 'utf8'));
+ const unthrottled = countMatches(content, /backgroundThrottling:\s*false/g);
+ if (unthrottled === 0) continue;
+ // 归一成 POSIX 分隔符再比对:Windows 上 path.relative 返回反斜杠,
+ // 而 BROADCAST_EXEMPT 的 key 是 POSIX 写法,不归一会匹配不上豁免、误报 offender。
+ const rel = toPosix(relative(mainDir, file));
+ if (BROADCAST_EXEMPT.has(rel)) continue;
+ const installed = countMatches(content, /installWindowHiddenBroadcast\(\s*\w/g);
+ if (installed < unthrottled) {
+ offenders.push(`${rel}(关闭节流 ${unthrottled} 处,装了广播 ${installed} 处)`);
+ }
+ }
+
+ expect(
+ offenders,
+ '以下文件里关闭 backgroundThrottling 的窗口数多于装了 installWindowHiddenBroadcast 的数量,' +
+ '也没在 BROADCAST_EXEMPT 里登记豁免。若这些窗口的视图有常驻装饰动画,闸门会静默失效:\n' +
+ offenders.join('\n'),
+ ).toEqual([]);
+ });
+
+ it('主窗、语音浮窗与词典 toast 都装了广播', () => {
+ expect(source).toContain('installWindowHiddenBroadcast(mainWindow);');
+
+ // 同一文件里两个窗口各装一份:overlay 与 dictionary toast 的局部变量都叫 window。
+ const overlaySource = stripComments(
+ readFileSync(resolve(__dirname, '..', 'voice-input', 'global.ts'), 'utf8').replace(/\r\n?/g, '\n'),
+ );
+ expect([...overlaySource.matchAll(/backgroundThrottling:\s*false/g)]).toHaveLength(2);
+ expect([...overlaySource.matchAll(/installWindowHiddenBroadcast\(window\);/g)]).toHaveLength(2);
+ });
+
+ it('豁免清单里的文件确实存在且确实关闭了节流(防止豁免过期后静默失效)', () => {
+ const mainDir = resolve(__dirname, '..');
+ for (const [rel, reason] of BROADCAST_EXEMPT) {
+ const content = stripComments(readFileSync(resolve(mainDir, rel), 'utf8'));
+ expect(content, `${rel} 已不再关闭 backgroundThrottling,${reason} 这条豁免应删除`).toMatch(
+ /backgroundThrottling:\s*false/,
+ );
+ }
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b5c7fa88ca..20480ffce5 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -469,6 +469,7 @@ import { disposeRemoteFileBrowser } from './file-browser/remote-deps.js';
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 { openSessionInNewWindow } from './secondary-windows.js';
import {
isGlobalVoiceInputOverlayVisible,
@@ -2221,6 +2222,10 @@ const createWindow = () => {
}
});
+ // 装饰动画闸门的兜底信号。主窗在 running turn 期间会关掉 backgroundThrottling,
+ // 那之后 Renderer 的 visibilityState 就不再反映真实可见性,细节见模块头注释。
+ installWindowHiddenBroadcast(mainWindow);
+
// App badge: 用户把任意 XDMaker 窗口点回前台(Dock 点击 / taskbar / alt-tab / 点窗口)即视为
// 「已查看」,直接清空整个 dock 红点。badge 是 app 级状态,不该依赖当前停在哪个
// 路由 / 开没开会话 —— 之前清除逻辑寄生在 cc-agent sidebar 且只清 activeSessionId,
diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.ts
index 51bd99a738..c2bbfb87d0 100644
--- a/apps/desktop/src/main/voice-input/global.ts
+++ b/apps/desktop/src/main/voice-input/global.ts
@@ -43,6 +43,7 @@ import {
} from './overlayPlacement.js';
import { voiceInputOverlayPositionStore } from './overlayPositionStore.js';
import { voiceInputDataStore } from './VoiceInputDataStore.js';
+import { installWindowHiddenBroadcast } from '../windowHiddenBroadcast.js';
const log = createLogger('voice-input-global');
type GlobalVoiceInputShortcutPhase = 'start' | 'tap' | 'end';
@@ -1269,6 +1270,11 @@ function createOverlayWindow(shortcutInvokedAt: number): BrowserWindow {
overlayWindow = window;
overlayLoaded = false;
+ // 浮窗建窗即 backgroundThrottling:false(保住麦克风回调调度),它的 Renderer 也装了
+ // 装饰动画闸门(index.tsx 顶层安装,浮窗视图同样经过),但节流关闭会让 visibilityState
+ // 恒为 visible。浮窗 hide 后窗口是缓存复用的、Renderer 仍活着,不广播的话 mic 波形
+ // 这类常驻动画会在看不见的时候继续跑。
+ installWindowHiddenBroadcast(window);
window.on('show', () => {
if (!overlayPresentationActive) {
setImmediate(() => {
@@ -1396,6 +1402,11 @@ function createDictionaryToastWindow(payload: { entries: DictionaryToastEntryPay
scheduleMainAppPresenceRestore('voice-dictionary-toast-shown');
});
+ // 词典 toast 同样 backgroundThrottling:false 且加载主 renderer 入口(index.html
+ // ?view=voice-input-dictionary-toast),顶层已安装装饰动画闸门 —— 不广播的话
+ // hide(如 Cmd+H)后 visibilityState 恒为 visible,闸门静默失效。
+ installWindowHiddenBroadcast(window);
+
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
const url = new URL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
url.search = DICTIONARY_TOAST_QUERY;
diff --git a/apps/desktop/src/main/windowHiddenBroadcast.ts b/apps/desktop/src/main/windowHiddenBroadcast.ts
new file mode 100644
index 0000000000..f03afc294b
--- /dev/null
+++ b/apps/desktop/src/main/windowHiddenBroadcast.ts
@@ -0,0 +1,51 @@
+import type { BrowserWindow } from 'electron';
+
+/**
+ * 窗口「对用户不可见」广播 —— Renderer 的装饰动画闸门(hiddenAnimationGate)靠它兜底。
+ *
+ * 为什么 Renderer 不能只靠自己的 document.visibilityState:Electron 明确规定
+ * backgroundThrottling 关闭时 visibilityState 会一直停在 'visible',即使窗口已被最小化
+ * 或 hide()。已在 Electron 41.2.0 实测复现:
+ *
+ * backgroundThrottling=true minimize()/hide() → visibilityState 转 'hidden' ✅
+ * backgroundThrottling=false minimize()/hide() → visibilityState 仍 'visible' ❌
+ * 两种取值下 BrowserWindow 的 hide/minimize 事件都正常触发 ✅
+ *
+ * 所以判据是:**凡是会安装 hiddenAnimationGate、又关掉了节流的窗口,都必须装这条广播**,
+ * 否则它那份闸门形同虚设。是否安装闸门取决于窗口加载的 renderer 入口——闸门在
+ * index.tsx 顶层安装,所以凡加载主 renderer 入口(index.html,含各种 ?view= 变体)的窗口
+ * 都装了。这里不列具体窗口清单:新增窗口时清单必然过期,由
+ * mainWindowBackgroundThrottling.test.ts 的扫描测试按上述判据兜底(它按窗口计数,
+ * 并要求豁免必须显式登记理由)。
+ *
+ * 两路信号在 Renderer 侧取「或」:本广播不受节流影响、覆盖最小化与 hide;
+ * visibilityState 覆盖 macOS 的窗口遮挡(occlusion)——那个没有对应的 Electron 事件。
+ * Windows 的遮挡两路都覆盖不到(Electron 文档:occlusion 只在 macOS 影响可见性),
+ * 属于已知局限,表现为不冻结,即退回改动前行为。
+ *
+ * 该 channel 是窗口本地 UI 状态,不进 device-link allowlist —— 那里把 window-* 归为
+ * 「永不放行」类别,远程控制端的窗口可见性与被控端无关。
+ */
+export const WINDOW_HIDDEN_CHANGE_CHANNEL = 'window-hidden-change';
+
+export function installWindowHiddenBroadcast(win: BrowserWindow): void {
+ const emit = (): void => {
+ if (win.isDestroyed() || win.webContents.isDestroyed()) return;
+ const hidden = !win.isVisible() || win.isMinimized();
+ win.webContents.send(WINDOW_HIDDEN_CHANGE_CHANNEL, hidden);
+ };
+
+ // 逐个注册:BrowserWindow.on 是重载签名,传联合类型的事件名匹配不到任何一个重载。
+ win.on('hide', emit);
+ win.on('show', emit);
+ win.on('minimize', emit);
+ win.on('restore', emit);
+
+ // 补发基线:preload 的 createIpcFanOut 是惰性绑定(首个订阅者到来才 ipcRenderer.on),
+ // 订阅之前发生的事件会丢。窗口若在 Renderer 起来之前就已隐藏(启动即最小化、
+ // show:false 的浮窗等),Renderer 会一直停在初始的「未隐藏」;叠加节流关闭时
+ // visibilityState 恒为 visible,就永远不冻结。did-finish-load 对应 window load,必然
+ // 晚于 index.tsx 顶层的 installHiddenAnimationGate(),补一发即可拿到正确基线。
+ // reload / HMR 重新加载后同样会补发。
+ win.webContents.on('did-finish-load', emit);
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a17b9119d7..ef5fd386bb 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -300,6 +300,9 @@ const fanOutTapdbDailyActive = createIpcFanOut('tapdb:daily-active');
// 使用统计(TapDB)的同意状态 / 开关变化;renderer 据此即时 init 或 opt-out
const fanOutAnalyticsSettingsChange = createIpcFanOut(ANALYTICS_SETTINGS_CHANGE_CHANNEL);
const fanOutFullscreenChange = createIpcFanOut('fullscreen-change');
+// 窗口是否对用户不可见(最小化 / hide)。装饰动画闸门用它兜底 —— backgroundThrottling
+// 关闭时 Renderer 的 document.visibilityState 会一直停在 visible,见 main 侧注释。
+const fanOutWindowHiddenChange = createIpcFanOut('window-hidden-change');
const fanOutApplicationMenuCommand = createIpcFanOut('app-menu:command');
// 首登轻量数据迁移(mToc)弹窗阶段推送(confirm / running / done / failed)
const fanOutLegacyMigrationState = createIpcFanOut('legacy-migration:state');
@@ -2766,6 +2769,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
onFullscreenChange: fanOutFullscreenChange,
getFullscreenState: (): Promise<boolean> => ipcRenderer.invoke('get-fullscreen-state'),
+ // 窗口是否对用户不可见(最小化 / hide)。装饰动画闸门订阅它来决定要不要冻结常驻动画;
+ // 关掉 backgroundThrottling 的窗口里 document.visibilityState 不可信,只能靠这条。
+ onWindowHiddenChange: fanOutWindowHiddenChange,
+
// ── Release notes (per-version, fetched from CDN by main) ──
// Platform is resolved in main via getPlatformKey() to keep the CDN path
// axis identical to the hot-update manifest.
diff --git a/apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts b/apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts
new file mode 100644
index 0000000000..42544a65a8
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/hiddenAnimationGate.test.ts
@@ -0,0 +1,448 @@
+/**
+ * hiddenAnimationGate.test.ts
+ * ---------------------------------------------------------------------------
+ * 隐藏期装饰动画闸门的行为测试:通过注入面用假 visibilityState 驱动,并对
+ * globals.css 的冻结规则做一次静态回归 —— 一次性动画不得被纳入冻结清单。
+ */
+
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+
+import {
+ alignFrameWithGate,
+ HIDDEN_ANIMATION_ATTR,
+ installHiddenAnimationGate,
+ isLoopingAnimation,
+ syncFrameAnimations,
+ type GateAnimation,
+ type HiddenAnimationGateTarget,
+} from '../lib/hiddenAnimationGate';
+
+function createHarness(
+ initialVisibility: DocumentVisibilityState = 'visible',
+ opts: { withElectronAPI?: boolean } = { withElectronAPI: true },
+) {
+ let visibility: DocumentVisibilityState = initialVisibility;
+ const listeners = new Set<() => void>();
+ const attrs = new Map<string, string>();
+ const windowHiddenListeners = new Set<(hidden: boolean) => void>();
+
+ const target: HiddenAnimationGateTarget = {
+ document: {
+ get visibilityState() {
+ return visibility;
+ },
+ documentElement: {
+ setAttribute: (name: string, value: string) => {
+ attrs.set(name, value);
+ },
+ removeAttribute: (name: string) => {
+ attrs.delete(name);
+ },
+ },
+ addEventListener: ((type: string, cb: EventListenerOrEventListenerObject) => {
+ if (type === 'visibilitychange') listeners.add(cb as () => void);
+ }) as Document['addEventListener'],
+ removeEventListener: ((type: string, cb: EventListenerOrEventListenerObject) => {
+ if (type === 'visibilitychange') listeners.delete(cb as () => void);
+ }) as Document['removeEventListener'],
+ },
+ window: opts.withElectronAPI
+ ? {
+ electronAPI: {
+ onWindowHiddenChange: (cb: (hidden: boolean) => void) => {
+ windowHiddenListeners.add(cb);
+ return () => windowHiddenListeners.delete(cb);
+ },
+ },
+ }
+ : {},
+ };
+
+ return {
+ target,
+ listenerCount: () => listeners.size,
+ windowHiddenListenerCount: () => windowHiddenListeners.size,
+ isFrozen: () => attrs.get('data-app-hidden') === 'true',
+ setVisibility(next: DocumentVisibilityState) {
+ visibility = next;
+ for (const cb of [...listeners]) cb();
+ },
+ /** 模拟 main 侧 BrowserWindow hide/minimize 广播。 */
+ emitWindowHidden(hidden: boolean) {
+ for (const cb of [...windowHiddenListeners]) cb(hidden);
+ },
+ };
+}
+
+describe('installHiddenAnimationGate', () => {
+ it('页面隐藏时打上冻结标记,恢复可见时摘掉', () => {
+ const h = createHarness('visible');
+ installHiddenAnimationGate(h.target);
+ expect(h.isFrozen()).toBe(false);
+
+ h.setVisibility('hidden');
+ expect(h.isFrozen()).toBe(true);
+
+ h.setVisibility('visible');
+ expect(h.isFrozen()).toBe(false);
+ });
+
+ it('安装时已处于隐藏态则立即冻结(启动后马上切走的场景)', () => {
+ const h = createHarness('hidden');
+ installHiddenAnimationGate(h.target);
+ expect(h.isFrozen()).toBe(true);
+ });
+
+ it('dispose 后摘掉监听并恢复动画,不把页面留在冻结态', () => {
+ const h = createHarness('visible');
+ const dispose = installHiddenAnimationGate(h.target);
+ h.setVisibility('hidden');
+ expect(h.isFrozen()).toBe(true);
+
+ dispose();
+ expect(h.isFrozen()).toBe(false);
+ expect(h.listenerCount()).toBe(0);
+ expect(h.windowHiddenListenerCount()).toBe(0);
+ });
+
+ // 这是本模块存在的主要理由:backgroundThrottling 关闭时(有 running turn),
+ // visibilityState 会一直停在 'visible',只能靠 main 广播兜底。
+ it('visibilityState 始终 visible 时,main 广播的窗口隐藏仍能触发冻结', () => {
+ const h = createHarness('visible');
+ installHiddenAnimationGate(h.target);
+ expect(h.isFrozen()).toBe(false);
+
+ h.emitWindowHidden(true);
+ expect(h.isFrozen()).toBe(true);
+
+ h.emitWindowHidden(false);
+ expect(h.isFrozen()).toBe(false);
+ });
+
+ it('两路信号取或:任一为隐藏就冻结,两路都恢复才解冻', () => {
+ const h = createHarness('visible');
+ installHiddenAnimationGate(h.target);
+
+ h.emitWindowHidden(true);
+ h.setVisibility('hidden');
+ expect(h.isFrozen()).toBe(true);
+
+ // 只有 main 说恢复,但 visibilityState 仍是 hidden(如 macOS 遮挡)→ 保持冻结
+ h.emitWindowHidden(false);
+ expect(h.isFrozen()).toBe(true);
+
+ h.setVisibility('visible');
+ expect(h.isFrozen()).toBe(false);
+ });
+
+ it('缺少 electronAPI 时(非 Electron 宿主)不报错,退化为只认 visibilityState', () => {
+ const h = createHarness('visible', { withElectronAPI: false });
+ expect(() => installHiddenAnimationGate(h.target)).not.toThrow();
+ h.setVisibility('hidden');
+ expect(h.isFrozen()).toBe(true);
+ });
+
+ it('重复安装只保留一份监听(HMR 重入不叠加)', () => {
+ const h = createHarness('visible');
+ installHiddenAnimationGate(h.target);
+ installHiddenAnimationGate(h.target);
+ expect(h.listenerCount()).toBe(1);
+
+ h.setVisibility('hidden');
+ expect(h.isFrozen()).toBe(true);
+ });
+});
+
+describe('同源子文档(Ghost 卡片 iframe)动画同步', () => {
+ function makeAnim(iterations: number, playState = 'running') {
+ return {
+ playState,
+ effect: { getTiming: () => ({ iterations }) },
+ paused: false,
+ pause() {
+ this.paused = true;
+ this.playState = 'paused';
+ },
+ play() {
+ this.paused = false;
+ this.playState = 'running';
+ },
+ };
+ }
+
+ const docWith = (anims: unknown[]): HiddenAnimationGateTarget['document'] =>
+ ({
+ querySelectorAll: () => [{ contentDocument: { getAnimations: () => anims } }],
+ }) as unknown as HiddenAnimationGateTarget['document'];
+
+ it('只暂停无限循环动画,有限动画照播(避免冻在中途帧、恢复时突兀)', () => {
+ const loop = makeAnim(Infinity);
+ const oneShot = makeAnim(1);
+ const paused = new Set<GateAnimation>();
+
+ syncFrameAnimations(docWith([loop, oneShot]), true, paused);
+ expect(loop.paused).toBe(true);
+ expect(oneShot.paused).toBe(false);
+ });
+
+ it('恢复时只 play 本闸门暂停过的,不动意识自己 pause 的动画', () => {
+ const loop = makeAnim(Infinity);
+ const selfPaused = makeAnim(Infinity, 'paused');
+ const paused = new Set<GateAnimation>();
+
+ syncFrameAnimations(docWith([loop, selfPaused]), true, paused);
+ expect(loop.paused).toBe(true);
+ // 本来就是 paused 的不会被接管
+ expect(paused.has(selfPaused as unknown as GateAnimation)).toBe(false);
+
+ syncFrameAnimations(docWith([loop, selfPaused]), false, paused);
+ expect(loop.playState).toBe('running');
+ expect(selfPaused.playState).toBe('paused');
+ expect(paused.size).toBe(0);
+ });
+
+ it('跨源 iframe 读 contentDocument 抛错时跳过,不影响其它 frame', () => {
+ const loop = makeAnim(Infinity);
+ const crossOrigin = {
+ get contentDocument(): never {
+ throw new DOMException('cross-origin', 'SecurityError');
+ },
+ };
+ const doc = {
+ querySelectorAll: () => [crossOrigin, { contentDocument: { getAnimations: () => [loop] } }],
+ } as unknown as HiddenAnimationGateTarget['document'];
+
+ const paused = new Set<GateAnimation>();
+ expect(() => syncFrameAnimations(doc, true, paused)).not.toThrow();
+ expect(loop.paused).toBe(true);
+ });
+
+ it('宿主 document 没有 querySelectorAll 时安全跳过', () => {
+ const doc = {} as unknown as HiddenAnimationGateTarget['document'];
+ expect(() => syncFrameAnimations(doc, true, new Set())).not.toThrow();
+ });
+
+ it('isLoopingAnimation 只认 iterations === Infinity', () => {
+ expect(isLoopingAnimation({ effect: { getTiming: () => ({ iterations: Infinity }) } })).toBe(true);
+ expect(isLoopingAnimation({ effect: { getTiming: () => ({ iterations: 1 }) } })).toBe(false);
+ expect(isLoopingAnimation({})).toBe(false);
+ });
+
+ it('卡片 srcDoc 不再注通配暂停 CSS,改由 onLoad 精确暂停循环动画', () => {
+ const src = readFileSync(
+ fileURLToPath(new URL('../components/chat/GhostToolCard.tsx', import.meta.url)),
+ 'utf8',
+ );
+ // 通配 CSS 会把有限动画一并冻住,必须已经移除。
+ expect(src).not.toContain('animation-play-state:paused!important');
+ // 必须走闸门入口而不是自己 pause —— 自行 pause 不登记会让卡片动画永久停住。
+ expect(src).toContain('alignFrameWithGate(doc);');
+ });
+});
+
+describe('alignFrameWithGate(隐藏期间新挂载的卡片)', () => {
+ function makeAnim(iterations: number, playState = 'running') {
+ return {
+ playState,
+ effect: { getTiming: () => ({ iterations }) },
+ pause() {
+ this.playState = 'paused';
+ },
+ play() {
+ this.playState = 'running';
+ },
+ };
+ }
+ const hostDoc = (hidden: boolean) =>
+ ({
+ documentElement: { hasAttribute: (n: string) => hidden && n === HIDDEN_ANIMATION_ATTR },
+ }) as unknown as Pick<Document, 'documentElement'>;
+
+ it('窗口可见时不动任何动画', () => {
+ const loop = makeAnim(Infinity);
+ const win = {};
+ alignFrameWithGate({ getAnimations: () => [loop] }, hostDoc(false), win);
+ expect(loop.playState).toBe('running');
+ });
+
+ it('窗口已隐藏时暂停循环动画,且登记进闸门的共享恢复集合', () => {
+ const loop = makeAnim(Infinity);
+ const oneShot = makeAnim(1);
+ const win: { __xdtHiddenAnimationGatePausedAnims?: Set<GateAnimation> } = {};
+
+ alignFrameWithGate({ getAnimations: () => [loop, oneShot] }, hostDoc(true), win);
+
+ expect(loop.playState).toBe('paused');
+ expect(oneShot.playState).toBe('running');
+ // 关键:必须登记,否则统一恢复路径不会 play 它,卡片动画永久停住。
+ expect(win.__xdtHiddenAnimationGatePausedAnims?.has(loop as unknown as GateAnimation)).toBe(true);
+ });
+
+ it('登记后能被统一恢复路径播回来(端到端串起 onLoad → 恢复)', () => {
+ const loop = makeAnim(Infinity);
+ const win: { __xdtHiddenAnimationGatePausedAnims?: Set<GateAnimation> } = {};
+
+ alignFrameWithGate({ getAnimations: () => [loop] }, hostDoc(true), win);
+ expect(loop.playState).toBe('paused');
+
+ const doc = {
+ querySelectorAll: () => [{ contentDocument: { getAnimations: () => [loop] } }],
+ } as unknown as HiddenAnimationGateTarget['document'];
+ syncFrameAnimations(doc, false, win.__xdtHiddenAnimationGatePausedAnims!);
+
+ expect(loop.playState).toBe('running');
+ });
+});
+
+const CSS_PATH = fileURLToPath(new URL('../styles/globals.css', import.meta.url));
+const css = readFileSync(CSS_PATH, 'utf8');
+const frozenBlock =
+ /\[data-app-hidden='true'\][\s\S]*?animation-play-state:\s*paused\s*!important;/.exec(css)?.[0] ?? '';
+
+/**
+ * 取选择器里「真正挂动画的那个元素」——最后一段后代选择器。
+ * 冻结清单按这一段收敛:祖先条件不同、落点相同的规则(如 8 条
+ * `.agent-island-mascot-stage[data-motion=...] .agent-island-mascot-character`)只需一条。
+ * 按顶层空格切分,属性值内部的空格不算分隔符。
+ */
+function animatedElementToken(selector: string): string {
+ const parts: string[] = [];
+ let depth = 0;
+ let cur = '';
+ for (const ch of selector) {
+ if (ch === '[') depth++;
+ else if (ch === ']') depth--;
+ if (/\s/.test(ch) && depth === 0) {
+ if (cur) parts.push(cur);
+ cur = '';
+ } else {
+ cur += ch;
+ }
+ }
+ if (cur) parts.push(cur);
+ const last = parts[parts.length - 1] ?? selector;
+ // 去掉紧跟在落点元素后的状态限定(如 :hover),保留伪元素(::before 是独立的动画宿主)
+ return last.replace(/(?<!:):(?!:)[a-z-]+(\(.*\))?/g, '');
+}
+
+/**
+ * 扫描 globals.css 里所有 `animation: ... infinite` 规则,回溯其选择器。
+ * 先把注释替换成等长空白(保留换行以维持行号),否则注释里提到的
+ * `animation: ... infinite` 字样会被误判成真规则。
+ */
+function collectInfiniteRules(): { line: number; selector: string }[] {
+ const lines = css
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
+ .split('\n');
+ const found: { line: number; selector: string }[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (!/animation:.*\binfinite\b/.test(lines[i])) continue;
+ let j = i;
+ while (j >= 0 && !lines[j].includes('{')) j--;
+ const sel: string[] = [lines[j].split('{')[0].trim()];
+ let k = j - 1;
+ while (k >= 0 && /,\s*$/.test(lines[k])) {
+ sel.unshift(lines[k].trim());
+ k--;
+ }
+ found.push({ line: i + 1, selector: sel.join(' ').trim() });
+ }
+ return found;
+}
+
+describe('globals.css 冻结规则', () => {
+ it('冻结的是 play-state 而不是 animation: none', () => {
+ expect(frozenBlock).not.toBe('');
+ expect(frozenBlock).toContain('animation-play-state: paused');
+ expect(frozenBlock).not.toMatch(/animation:\s*none/);
+ });
+
+ it('每个 infinite 动画的宿主元素都在冻结清单里', () => {
+ const rules = collectInfiniteRules();
+ // 兜底:确认扫描逻辑确实抓到了规则,避免正则失效导致本用例空跑。
+ expect(rules.length).toBeGreaterThan(10);
+
+ const missing = rules
+ .filter((r) => !frozenBlock.includes(animatedElementToken(r.selector)))
+ .map((r) => `globals.css:${r.line} ${r.selector} (落点 ${animatedElementToken(r.selector)})`);
+
+ expect(
+ missing,
+ `以下 infinite 动画没有被 [data-app-hidden='true'] 冻结清单覆盖,隐藏窗口里它们会继续跑:\n${missing.join('\n')}\n\n` +
+ '请把落点元素补进 globals.css 的冻结清单,不要修改本测试。',
+ ).toEqual([]);
+ });
+
+ it('一次性动画不得纳入冻结清单(否则会冻在中途帧,恢复时突兀)', () => {
+ for (const oneShot of [
+ '.status-bar-done',
+ '.session-card--settle',
+ '.card-col-fade',
+ '.ghost-panel-enter',
+ '.ghost-panel-exit',
+ ]) {
+ expect(frozenBlock).not.toContain(oneShot);
+ }
+ });
+
+ it('Tailwind 动画用 [class*=] 匹配,以覆盖 motion-safe: 等变体的转义类名', () => {
+ expect(frozenBlock).toContain("[class*='animate-spin']");
+ expect(frozenBlock).toContain("[class*='animate-pulse']");
+ });
+
+ // 任意值工具类(animate-[spin_2.4s_linear_infinite])不含 animate-spin 子串,
+ // 也不在 globals.css 里,前面那条 CSS 扫描看不见它们 —— 单独扫源码兜住。
+ // 用 Node 自己遍历而不是外部 grep:Windows 上没有 POSIX grep,execFileSync 会
+ // 直接 ENOENT,测试在到达断言前就挂了。
+ it('源码里的任意值循环动画工具类都能被冻结清单匹配', () => {
+ const rendererDir = fileURLToPath(new URL('..', import.meta.url));
+
+ const walk = (dir: string, out: string[] = []): string[] => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
+ walk(full, out);
+ } else if (/\.tsx?$/.test(entry.name)) {
+ out.push(full);
+ }
+ }
+ return out;
+ };
+
+ const infiniteUtilities: string[] = [];
+ for (const file of walk(rendererDir)) {
+ const content = readFileSync(file, 'utf8');
+ for (const m of content.matchAll(/animate-\[[^\]]*\]/g)) {
+ if (m[0].includes('infinite')) {
+ infiniteUtilities.push(`${relative(rendererDir, file)} ${m[0]}`);
+ }
+ }
+ }
+
+ // 有任意值循环动画存在时,冻结清单必须有能匹配它们的选择器。
+ if (infiniteUtilities.length > 0) {
+ expect(
+ frozenBlock.includes("[class*='infinite']"),
+ `源码里存在任意值循环动画工具类,但冻结清单没有 [class*='infinite'] 兜底:\n${infiniteUtilities.join('\n')}`,
+ ).toBe(true);
+ }
+ });
+
+ // 属性名分散在 CSS / gate / GhostToolCard / 测试里,CSS 侧没法 import 常量,
+ // 这里替它把两边钉在一起。
+ // drawio viewer 把循环动画以 inline style 写到 SVG 上,类名不含任何可匹配的串,
+ // 且是压缩过的第三方脚本,前面的 CSS / tsx 扫描都够不着 —— 只能按容器子树冻结。
+ it('drawio viewer 子树在冻结清单里', () => {
+ expect(frozenBlock).toContain('[data-mxgraph]');
+ expect(frozenBlock).toContain('[data-mxgraph] *');
+ });
+
+ it('CSS 冻结清单用的属性名与模块导出的常量一致', () => {
+ expect(HIDDEN_ANIMATION_ATTR).toBe('data-app-hidden');
+ expect(frozenBlock).toContain(`[${HIDDEN_ANIMATION_ATTR}='true']`);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
index 3d61f940d3..1f9b5723bb 100644
--- a/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GhostToolCard.tsx
@@ -52,6 +52,7 @@ import {
subscribeGhostCards,
} from '@/cindy-brain/ghostCardStore';
import { useGhostCardThemeVars } from '@/cindy-brain/useGhostCardThemeVars';
+import { alignFrameWithGate } from '@/lib/hiddenAnimationGate';
import {
extractGhostCardGallerySrcs,
ghostCardGalleryId,
@@ -128,6 +129,10 @@ function buildCardSrcDoc(sanitizedHtml: string, themeVars: string): string {
// 减弱动效时,动画版卡片的意识自绘动画一律停播(srcdoc 内 media query
// 正常继承系统偏好)。背景仍由意识正文自己决定:透明画布是现行卡片
// 作者契约,宿主不能强铺 surface 改变其它 Ghost 的视觉。
+ // 窗口不可见时卡内动画的冻结不在这里做:CSS 选不出「只暂停无限循环动画」,通配
+ // 规则会把 cardSanitizer 允许的有限动画(如 animation:f 1s)一并冻在中途帧,恢复可见
+ // 时突兀。改由宿主用 Web Animations API 逐个判 iterations,见 hiddenAnimationGate 的
+ // syncFrameAnimations 与下面 onLoad 的对齐。
'<style>html,body{margin:0;padding:0;overflow:hidden;font-family:system-ui,-apple-system,sans-serif}img{max-width:100%;-webkit-user-drag:none;-webkit-user-select:none;user-select:none}@media (prefers-reduced-motion:reduce){*{animation:none!important}}</style>',
'</head><body>',
sanitizedHtml,
@@ -382,6 +387,10 @@ function GhostCardCanvas({
const attachClickBridge = useCallback(() => {
const doc = iframeRef.current?.contentDocument;
if (!doc) return;
+ // 与宿主的装饰动画闸门对齐一次:窗口可能在本卡挂载之前就已隐藏,那时闸门的遍历
+ // 还看不到这个 iframe。走闸门自己的入口,由它登记进共享的恢复集合 —— 自行 pause
+ // 而不登记的话,窗口切回来时统一恢复路径不会 play 它们,这张卡的动画会永久停住。
+ alignFrameWithGate(doc);
const imgs = doc.querySelectorAll<HTMLImageElement>('img[src^="cindy-media://"]');
let galleryImageIndex = 0;
imgs.forEach((img) => {
diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsx
index ac172ab3da..0286087b2e 100644
--- a/apps/desktop/src/renderer/index.tsx
+++ b/apps/desktop/src/renderer/index.tsx
@@ -40,6 +40,7 @@ import {
installPerformanceTimelineCleanupInterval,
} from './lib/foregroundRecoveryDiagnostics';
import { installRenderLoopWatchdog } from './lib/renderLoopWatchdog';
+import { installHiddenAnimationGate } from './lib/hiddenAnimationGate';
import { installInteractionJankProbe } from './lib/interactionJankProbe';
import { installSwallowActivationClick } from './lib/swallowActivationClick';
import { getSwallowActivationClickEnabled } from './hooks/useSwallowActivationClickSettings';
@@ -52,6 +53,10 @@ installScrollbarAutoHide();
const disposeForegroundRecoveryDiagnostics = installForegroundRecoveryDiagnostics();
// 睡醒白屏取证:主线程阻塞漂移 + 可见无帧探针,只记日志(见模块头注释)。
const disposeRenderLoopWatchdog = installRenderLoopWatchdog();
+// 隐藏期冻结常驻装饰动画 —— 有 running turn 时 backgroundThrottling 被主动关闭,
+// 不加这道闸门,看不见的窗口里动画会继续烧 CPU(见模块头注释)。浮窗同样适用:
+// 语音浮窗的 mic 波形也是 infinite 装饰动画。
+const disposeHiddenAnimationGate = installHiddenAnimationGate();
// Codex maker 化后, codex 事件流走 makerChatStore 内部的 maker:event 监听器,
// 不再需要专门的 codex progress dispatcher。
@@ -111,6 +116,7 @@ if (import.meta.env.DEV) {
import.meta.hot?.dispose(() => {
disposeForegroundRecoveryDiagnostics();
disposeRenderLoopWatchdog();
+ disposeHiddenAnimationGate();
disposePerformanceTimelineCleanupInterval();
disposeSwallowActivationClick();
disposeInteractionJankProbe();
diff --git a/apps/desktop/src/renderer/lib/hiddenAnimationGate.ts b/apps/desktop/src/renderer/lib/hiddenAnimationGate.ts
new file mode 100644
index 0000000000..1c5fcbfb1c
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/hiddenAnimationGate.ts
@@ -0,0 +1,236 @@
+/**
+ * 隐藏期装饰动画闸门 —— 窗口对用户不可见时冻结常驻 infinite 装饰动画。
+ *
+ * 背景:主窗 `backgroundThrottling` 默认开着,但 bootstrap-electron 的
+ * `setMainWindowBackgroundThrottlingForActiveTurn` 在有 running turn 时会主动
+ * 关掉它(保证 agent 流式输出与 IPC 不被后台降频)。副作用是:挂着一批 agent 跑、
+ * 人切去别的应用时,隐藏窗口里的无限循环装饰动画仍在全速推进并持续触发样式重算。
+ *
+ * 实测(2026-07-27,ABAB 四轮配对,低负载环境):10 个常驻动画令样式重算 29.8/s,
+ * 暂停后降到 5.7/s(-81%),该 renderer 进程 CPU 12.4% → 6.0%。动画数随运行中的
+ * 会话数线性增长(22 个动画时实测差值 40.2/s),会话越多代价越高。
+ *
+ * ## 为什么要两路信号
+ *
+ * 单靠 `document.visibilityState` 不行:Electron 规定 `backgroundThrottling` 关闭时
+ * visibilityState 会一直停在 `'visible'`,即便窗口已最小化或 hide()。而本模块要救的
+ * 正是「有 running turn(节流被关) + 人切走」这个场景,只认 visibilityState 等于永远
+ * 不触发。已在 Electron 41.2.0 / macOS 实测复现:
+ *
+ * backgroundThrottling=true minimize()/hide() → visibilityState 转 'hidden' ✅
+ * backgroundThrottling=false minimize()/hide() → visibilityState 仍 'visible' ❌
+ *
+ * 所以再接一路 main 侧广播(`onWindowHiddenChange`,基于 BrowserWindow 的
+ * hide/show/minimize/restore 事件),两路取「或」:
+ *
+ * - main 广播:不受节流影响,覆盖最小化与 hide;
+ * - visibilityState:覆盖 macOS 的窗口遮挡(occlusion)——那个没有对应的 Electron
+ * 事件,只能靠它。
+ *
+ * 已知局限:Windows 的窗口遮挡两路都盖不到(Electron 文档写明 occlusion 只在 macOS
+ * 影响可见性)。此时表现为「不冻结」,即退回改动前的行为,不会误冻可见窗口。
+ *
+ * 只认可见性,不认 focus —— 副屏场景下窗口失焦但仍然可见,按失焦暂停会被用户直接
+ * 看到。
+ *
+ * ## 两种暂停手段
+ *
+ * - **宿主文档**:翻 `documentElement` 上的 `data-app-hidden`,由 globals.css 的冻结
+ * 清单接管。声明式覆盖,隐藏期间新挂载的元素自动纳入;清单只列 infinite 装饰动画,
+ * 一次性动画刻意不进,免得被冻在中途帧。
+ * - **Ghost 卡片 srcDoc iframe**:CSS 跨不进子文档,且卡内动画是意识现画的、没有可枚举
+ * 清单,只能走 Web Animations API 逐个判 `iterations === Infinity`(见
+ * `syncFrameAnimations`)。用 JS 而非往 srcDoc 注一条通配 CSS,正是为了保住上面那条
+ * 「不冻一次性动画」的性质。
+ */
+/**
+ * 冻结标记的属性名。单一来源:CSS(globals.css 的冻结清单、GhostToolCard 注入进 srcDoc 的
+ * 规则)与 JS(本模块、iframe 传播、卡片 onLoad 对齐)必须用同一个名字,分散写字面量迟早
+ * 漏改。CSS 侧没法 import 常量,由 hiddenAnimationGate.test.ts 断言两边一致。
+ */
+export const HIDDEN_ANIMATION_ATTR = 'data-app-hidden';
+
+const HIDDEN_ATTR = HIDDEN_ANIMATION_ATTR;
+
+/** 存放 disposer 的槽位:本模块自有的私有约定,不在 lib.dom 的 Window 声明里。 */
+interface GateWindow {
+ __xdtHiddenAnimationGateDisposer?: () => void;
+ /**
+ * 最近一次 main 广播的窗口隐藏态。必须跨重装存活:preload 的 createIpcFanOut 不会向
+ * 新订阅者回放最后一次 payload,而 HMR 重装时页面没有重新加载、也就不会触发 main 侧
+ * did-finish-load 的补发。不缓存的话,「窗口已隐藏 + 节流关闭(visibilityState 恒为
+ * visible)」时重装,闸门会一直等不到下一次 hide/minimize 而静默失效。
+ */
+ __xdtHiddenAnimationGateLastHidden?: boolean;
+ /**
+ * 本闸门暂停过的子文档动画。挂在 window 上而非闭包里,因为隐藏期间新挂载的卡片要在
+ * 自己的 onLoad 里登记进来(见 alignFrameWithGate)——不登记的话恢复路径不会 play 它们,
+ * 卡片动画会永久停住。同时跨重装存活,理由同 LastHidden。
+ */
+ __xdtHiddenAnimationGatePausedAnims?: Set<GateAnimation>;
+ /** main 侧窗口可见性广播;非 Electron 宿主(单测 / 纯浏览器)下缺省。 */
+ electronAPI?: {
+ onWindowHiddenChange?: (callback: (hidden: boolean) => void) => () => void;
+ };
+}
+
+/** 注入面,让单测能用假 document/visibilityState/IPC 驱动。 */
+export interface HiddenAnimationGateTarget {
+ document: Pick<Document, 'addEventListener' | 'removeEventListener'> & {
+ readonly visibilityState: DocumentVisibilityState;
+ readonly documentElement: Pick<Element, 'setAttribute' | 'removeAttribute'>;
+ /** 用于把冻结标记传播进同源子文档(Ghost 卡片的 srcDoc iframe)。 */
+ querySelectorAll?: (selectors: string) => ArrayLike<HiddenAnimationGateFrame>;
+ };
+ window: GateWindow;
+}
+
+/** 子文档里一个动画的最小面(Web Animations API 的子集)。 */
+export interface GateAnimation {
+ readonly playState?: string;
+ effect?: { getTiming?: () => { iterations?: number } } | null;
+ pause?: () => void;
+ play?: () => void;
+}
+
+/** iframe 的最小面:同源子文档 + 其动画清单。 */
+export interface HiddenAnimationGateFrame {
+ readonly contentDocument?: {
+ getAnimations?: () => ArrayLike<GateAnimation>;
+ } | null;
+}
+
+/** 判断一个动画是不是无限循环。 */
+export function isLoopingAnimation(anim: GateAnimation): boolean {
+ return anim.effect?.getTiming?.()?.iterations === Infinity;
+}
+
+/** 子文档的最小面:只需要能列出自己的动画。 */
+export interface GateFrameDocument {
+ getAnimations?: () => ArrayLike<GateAnimation>;
+}
+
+/**
+ * 让一个刚加载完的子文档跟上当前闸门状态 —— 供 Ghost 卡片在 iframe onLoad 时调用。
+ *
+ * 窗口可能在这张卡挂载之前就已隐藏,那时闸门的遍历还看不到这个 iframe。**关键是必须把
+ * 暂停的动画登记进闸门的共享集合**:恢复路径只 play 集合里的,漏登记 = 这张卡的动画永久
+ * 停住(窗口切回来也不动)。所以这里不自己维护记账,直接复用 window 上那份。
+ *
+ * 只停无限循环的;有限动画照播 —— 冻在中途帧、恢复时才接着播才是突兀的那种。
+ */
+export function alignFrameWithGate(
+ frameDoc: GateFrameDocument,
+ hostDocument: Pick<Document, 'documentElement'> = document,
+ hostWindow: GateWindow = window as Window & GateWindow,
+): void {
+ if (!hostDocument.documentElement.hasAttribute(HIDDEN_ATTR)) return;
+ const paused = (hostWindow.__xdtHiddenAnimationGatePausedAnims ??= new Set<GateAnimation>());
+ for (const anim of Array.from(frameDoc.getAnimations?.() ?? [])) {
+ if (anim.playState !== 'running' || !isLoopingAnimation(anim)) continue;
+ anim.pause?.();
+ paused.add(anim);
+ }
+}
+
+/**
+ * 把冻结同步进同源子文档(Ghost 卡片的 srcDoc iframe)。
+ *
+ * Ghost 卡片是 `sandbox="allow-same-origin"` 的 srcDoc iframe,CSS 选择器跨不进去,而
+ * cardSanitizer 明确保留意识作者写的动画,所以隐藏期间这些卡片会继续吃渲染。
+ *
+ * 这里走 Web Animations API 而不是像宿主侧那样注一条 CSS 规则:CSS 选不出「只暂停无限
+ * 循环动画」——`animation-play-state` 加在通配选择器上会把有限动画一并冻住,而
+ * cardSanitizer 是允许 `animation:f 1s` 这类有限声明的。被冻在中途的有限动画会在窗口
+ * 恢复可见时突然从暂停帧接着播,正是宿主侧 allowlist 刻意规避的那种突兀感。
+ * `getAnimations()` 能逐个读 timing,精确只停 `iterations === Infinity` 的。
+ *
+ * 恢复时只 play 本闸门暂停过的那些,不动意识自己 pause 的动画 —— 调用方传入 paused 集合
+ * 承担这份记账。跨源 iframe 读 contentDocument 会抛,逐个吞掉即可。
+ */
+export function syncFrameAnimations(
+ doc: HiddenAnimationGateTarget['document'],
+ hidden: boolean,
+ pausedByGate: Set<GateAnimation>,
+): void {
+ const frames = doc.querySelectorAll?.('iframe');
+ if (!frames) return;
+ for (let i = 0; i < frames.length; i++) {
+ try {
+ const anims = frames[i]?.contentDocument?.getAnimations?.();
+ if (!anims) continue;
+ for (let j = 0; j < anims.length; j++) {
+ const anim = anims[j];
+ if (!anim) continue;
+ if (hidden) {
+ if (anim.playState !== 'running' || !isLoopingAnimation(anim)) continue;
+ anim.pause?.();
+ pausedByGate.add(anim);
+ } else if (pausedByGate.has(anim)) {
+ anim.play?.();
+ pausedByGate.delete(anim);
+ }
+ }
+ } catch {
+ // 跨源 / 已卸载的 frame:跳过
+ }
+ }
+ // 解冻时清账:已卸载的卡片对应的动画对象不会再出现在任何 frame 里。
+ if (!hidden) pausedByGate.clear();
+}
+
+function defaultTarget(): HiddenAnimationGateTarget {
+ return { document, window: window as Window & GateWindow };
+}
+
+export function installHiddenAnimationGate(
+ target: HiddenAnimationGateTarget = defaultTarget(),
+): () => void {
+ // 重复安装时先拆旧的,避免同一 document 上挂多份监听。
+ target.window.__xdtHiddenAnimationGateDisposer?.();
+
+ // main 广播的窗口态。优先复用上一轮缓存(HMR 重装时窗口可能已经是隐藏的,
+ // 见 GateWindow 上该字段的注释);首次安装则按「未隐藏」起步 —— 窗口刚建出来就是
+ // 可见的,真隐藏了 main 侧 did-finish-load 的补发会立刻纠正。
+ let windowHidden = target.window.__xdtHiddenAnimationGateLastHidden ?? false;
+ // 本闸门暂停过的子文档动画,解冻时只 play 这些,不动意识自己 pause 的。挂在 window 上
+ // 共享:隐藏期间新挂载的卡片走 alignFrameWithGate 往同一份集合里登记。
+ const pausedFrameAnimations = (target.window.__xdtHiddenAnimationGatePausedAnims ??=
+ new Set<GateAnimation>());
+
+ const apply = (): void => {
+ const hidden = windowHidden || target.document.visibilityState === 'hidden';
+ if (hidden) {
+ target.document.documentElement.setAttribute(HIDDEN_ATTR, 'true');
+ } else {
+ target.document.documentElement.removeAttribute(HIDDEN_ATTR);
+ }
+ // 已挂载的同源子文档跟着翻。隐藏期间新建的 iframe 由挂载方(GhostToolCard 的
+ // onLoad)自己对齐一次,那条路径不经过这里。
+ syncFrameAnimations(target.document, hidden, pausedFrameAnimations);
+ };
+
+ // 安装时先对齐一次:窗口可能已经处于隐藏态(例如启动后立刻切走)。
+ apply();
+ target.document.addEventListener('visibilitychange', apply);
+
+ const unsubscribeWindowHidden = target.window.electronAPI?.onWindowHiddenChange?.((hidden) => {
+ windowHidden = hidden;
+ target.window.__xdtHiddenAnimationGateLastHidden = hidden;
+ apply();
+ });
+
+ const dispose = (): void => {
+ target.document.removeEventListener('visibilitychange', apply);
+ unsubscribeWindowHidden?.();
+ // 拆闸门时一律恢复动画,不把页面(及子文档)留在冻结态。
+ target.document.documentElement.removeAttribute(HIDDEN_ATTR);
+ syncFrameAnimations(target.document, false, pausedFrameAnimations);
+ if (target.window.__xdtHiddenAnimationGateDisposer === dispose) {
+ delete target.window.__xdtHiddenAnimationGateDisposer;
+ }
+ };
+
+ target.window.__xdtHiddenAnimationGateDisposer = dispose;
+ return dispose;
+}
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 938c05d42e..4e231aed57 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -881,6 +881,59 @@ body.resizing-pane [data-ghost-webview] {
}
}
+/* 页面不可见时冻结常驻装饰动画(闸门见 lib/hiddenAnimationGate.ts)。
+ 主窗 backgroundThrottling 在有 running turn 时被主动关闭以保住流式输出,
+ 于是隐藏窗口里的 infinite 动画会继续推进并持续触发样式重算;实测 10 个动画
+ 令样式重算 29.8/s,冻结后 5.7/s(-81%),renderer CPU 12.4% → 6.0%。
+
+ ⚠️ 新增任何 `animation: ... infinite` 时必须同步把它的元素加进本清单。
+ `hiddenAnimationGate.test.ts` 会扫描本文件所有 infinite 规则并逐条核对,漏了会直接
+ 测试失败——不要改测试绕过,补选择器即可。清单按「真正挂动画的那个元素」(选择器的
+ 最后一段)收敛,所以祖先条件不同、落点相同的规则只需一条。
+
+ 只列 infinite 装饰动画。一次性动画(.status-bar-done / .session-card--settle /
+ .card-col-fade / ghost-bubble 进出场 / ghost-panel 展开收起)刻意不纳入:它们总时长
+ 有限、省不到东西,却会在隐藏期被冻在中途帧,恢复可见时反而突兀。这也是这里用
+ allowlist 而不是「全局暂停 + 一次性例外」的原因——漏掉 infinite 只是少省一点 CPU,
+ 漏掉一次性动画却会造成可见的视觉异常。
+
+ 用 animation-play-state 而非 animation: none —— 后者会让元素跳回静止态
+ (opacity 回到 1),恢复可见的瞬间比冻结更显眼。冻结点落在动画自身的取值区间内,
+ 恢复后接着播,用户不可察觉。
+
+ Tailwind 的 animate-spin / animate-pulse 用 [class*=] 匹配,以覆盖
+ motion-safe:animate-pulse 这类变体编译出的转义类名。任意值工具类
+ (animate-[spin_2.4s_linear_infinite] 之类,见 GhostSummonCard)不含 animate-spin
+ 子串,靠 [class*='infinite'] 兜住:Tailwind 把 keyframes 简写原样编进类名,
+ 循环动画必然带 infinite 字面量,而一次性的 animate-[xxx_200ms_ease-out] 不会。 */
+[data-app-hidden='true'] [data-voice-spinner-arc],
+[data-app-hidden='true'] [data-voice-mic-bar],
+[data-app-hidden='true'] .status-bar-shimmer,
+[data-app-hidden='true'] .session-status-breathing,
+[data-app-hidden='true'] .session-card-bar::before,
+[data-app-hidden='true'] .session-card-dot,
+[data-app-hidden='true'] .session-running-dot,
+[data-app-hidden='true'] .thinking-dot,
+[data-app-hidden='true'] .ghost-card-sweep,
+[data-app-hidden='true'] .ghost-bubble-face,
+[data-app-hidden='true'] .agent-island-mascot-character,
+[data-app-hidden='true'] .agent-island-mascot-keyboard,
+[data-app-hidden='true'] .agent-island-mascot-key,
+[data-app-hidden='true'] .agent-island-mascot-eyes,
+[data-app-hidden='true'] .agent-island-mascot-sparkle,
+[data-app-hidden='true'] [class*='animate-spin'],
+[data-app-hidden='true'] [class*='animate-pulse'],
+[data-app-hidden='true'] [class*='infinite'],
+/* drawio viewer(vendor/drawio/viewer-static.min.js)把循环动画以 inline style 直接写到
+ SVG 元素上(flowAnimation 的流动虚线、加载 spinner),类名既不含 animate-* 也不含
+ infinite,前面几条都够不着;它又是压缩过的第三方脚本,不归 globals.css / tsx 扫描管。
+ 按容器整棵子树冻结 —— 容器形态是 <div class="mxgraph" data-mxgraph="{json}">,
+ 见 DrawioPreview.tsx。 */
+[data-app-hidden='true'] [data-mxgraph],
+[data-app-hidden='true'] [data-mxgraph] * {
+ animation-play-state: paused !important;
+}
+
/* Running indicator — three horizontal dots, scale-up wave from left to right.
Color uses currentColor so the parent span controls accent vs gray. */
.session-running-dots {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index a8661c9e86..206639d30b 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2664,6 +2664,10 @@ interface ElectronAPI {
* that fired before the renderer had a chance to subscribe). */
getFullscreenState: () => Promise<boolean>;
+ /** 窗口是否对用户不可见(最小化 / hide)。装饰动画闸门用它兜底 ——
+ * backgroundThrottling 关闭时 document.visibilityState 会一直停在 visible。 */
+ onWindowHiddenChange: (callback: (hidden: boolean) => void) => () => void;
+
// ── Release notes (per-version, fetched from CDN by main) ──
/**
* Fetch the release notes JSON for a given version. Platform is resolved