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): 内置浏览器 guest 崩溃隔离 + 资源看门狗 (#420)

xxxcc60a6009802ef
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.ts
index 5641f73ce5..bcbb3d42ee 100644
--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts
@@ -159,6 +159,79 @@ describe('runQuitDisposers', () => {
});
});
+describe('installQuitHandler render-process-gone', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ type RenderGoneHandler = (
+ event: unknown,
+ webContents: { id: number; getType(): string },
+ details: { reason: string; exitCode: number },
+ ) => void;
+
+ /** 装好 handler 后把 app.on 捕到的 render-process-gone 回调挖出来。 */
+ async function installAndGrabHandler() {
+ const snapshot = snapshotProcessListeners([
+ 'SIGINT',
+ 'SIGTERM',
+ 'exit',
+ 'uncaughtException',
+ 'unhandledRejection',
+ ]);
+ const { installQuitHandler } = await freshLifecycle();
+ installQuitHandler(50);
+ const { app } = await import('electron');
+ const onMock = vi.mocked(app.on);
+ // app.on 的类型是重载联合,TS 会把 event 收窄到第一个重载的字面量;按数据看待。
+ const call = (onMock.mock.calls as unknown as Array<[string, unknown]>).find(
+ ([event]) => event === 'render-process-gone',
+ );
+ expect(call).toBeDefined();
+ return {
+ handler: call![1] as unknown as RenderGoneHandler,
+ app,
+ restore: () => snapshot.restore(),
+ };
+ }
+
+ it('webview guest crash (e.g. OOM) does NOT shut the app down', async () => {
+ const { handler, app, restore } = await installAndGrabHandler();
+ try {
+ handler(
+ undefined,
+ { id: 42, getType: () => 'webview' },
+ { reason: 'oom', exitCode: 1 },
+ );
+ // beginShutdown 是异步链;等一拍再断言"什么都没发生"。
+ await new Promise((r) => setTimeout(r, 20));
+ expect(app.exit).not.toHaveBeenCalled();
+ expect(mocks.logger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('webview guest render-process-gone'),
+ );
+ expect(mocks.logger.error).not.toHaveBeenCalled();
+ } finally {
+ restore();
+ }
+ });
+
+ it('main window renderer crash still shuts the app down with exit(1)', async () => {
+ const { handler, app, restore } = await installAndGrabHandler();
+ try {
+ handler(
+ undefined,
+ { id: 1, getType: () => 'window' },
+ { reason: 'crashed', exitCode: 5 },
+ );
+ await vi.waitFor(() => {
+ expect(app.exit).toHaveBeenCalledWith(1);
+ });
+ } finally {
+ restore();
+ }
+ });
+});
+
describe('installQuitHandler', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/apps/desktop/src/main/lifecycle.ts b/apps/desktop/src/main/lifecycle.ts
index af94ff934c..d82d18a9cb 100644
--- a/apps/desktop/src/main/lifecycle.ts
+++ b/apps/desktop/src/main/lifecycle.ts
@@ -280,9 +280,13 @@ export function installQuitHandler(timeoutMs = 2000): void {
// ── Layer 4: renderer crashed (main alive) ──────────────────────────────
// Main 还活着, 但 renderer 死了。继续让用户看一个空白窗没意义, 走 disposer
// chain 把 IM offline / 子进程都收掉再 exit(1)。
- // 例外:意识沙箱(cindy-brain/runtime)的渲染进程"允许死"——崩溃隔离正是它的
+ // 例外 1:意识沙箱(cindy-brain/runtime)的渲染进程"允许死"——崩溃隔离正是它的
// 设计属性(docs/dev-rules/plugin-security-and-authoring.md),由 GhostRuntime 自己收尸/熔断,
// 绝不能触发整个应用关机(实证:强崩沙箱曾把主界面一起带走)。
+ // 例外 2:`<webview>` guest(内置浏览器等)的崩溃/OOM 只影响那一个 tab——
+ // renderer 侧 useBrowserWebview 已有 crash banner + reload 恢复链路。此前
+ // 这里不区分 guest,网页死递归吃满内存被 OOM kill 时会把整个 App 一起带走
+ // (VS Code / Cursor 的边界都是 guest 崩溃不退 Workbench)。
app.on('render-process-gone', (_event, webContents, details) => {
if (isGhostSandboxWebContentsId(webContents.id)) {
log.warn(
@@ -290,6 +294,12 @@ export function installQuitHandler(timeoutMs = 2000): void {
);
return;
}
+ if (webContents.getType() === 'webview') {
+ log.warn(
+ `webview guest render-process-gone (isolated, no shutdown): reason=${details.reason} exitCode=${details.exitCode}`,
+ );
+ return;
+ }
log.error(`render-process-gone: reason=${details.reason} exitCode=${details.exitCode}`);
if (_isDisposing) return;
void beginShutdown(timeoutMs, `render-process-gone:${details.reason}`).finally(() =>
diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-force-kill.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-force-kill.test.ts
new file mode 100644
index 0000000000..5ac0f6c5d7
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/ipc-force-kill.test.ts
@@ -0,0 +1,140 @@
+// Verifies the `force-kill` IPC handler:
+// - registry hit + host match → forcefullyCrashRenderer + {ok:true}
+// - registry miss + valid fallback webContentsId(webview guest、宿主为 sender)
+// → 兜底解析后 kill(页面在首个 dom-ready 前锁死 renderer 的场景)
+// - fallback 指向非 webview / 宿主不符 → 拒绝(不放松 report 同款信任模型)
+// - forcefullyCrashRenderer 抛 → [INTERNAL](TOCTOU 竞态转统一 IPC 错误协议)
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => {
+ const ipcMainHandlers = new Map<string, (e: unknown, payload: unknown) => unknown>();
+ return {
+ ipcMain: {
+ handle: vi.fn((channel: string, fn: (e: unknown, payload: unknown) => unknown) => {
+ ipcMainHandlers.set(channel, fn);
+ }),
+ __handlers: ipcMainHandlers,
+ },
+ webContents: { fromId: vi.fn() },
+ clipboard: { writeImage: vi.fn() },
+ app: { getAppMetrics: vi.fn(() => []) },
+ };
+});
+
+import { ipcMain, webContents as electronWebContents } from 'electron';
+
+import { RSB_BROWSER_BRIDGE_FORCE_KILL_CHANNEL } from '../../../shared/rsbBrowserBridge.js';
+import { registerRsbBrowserBridgeIpc, _resetRsbBrowserBridgeIpcForTests } from '../ipc.js';
+import type { TabRegistry } from '../registry.js';
+
+function fakeRegistry(overrides: { getWebContentsByTabId?: (tabId: string) => unknown }) {
+ return {
+ getWebContentsByTabId: overrides.getWebContentsByTabId ?? (() => null),
+ onPinChange: () => () => undefined,
+ listAll: () => [],
+ isPinned: () => false,
+ } as unknown as TabRegistry;
+}
+
+interface FakeGuestOpts {
+ hostId?: number;
+ type?: string;
+ destroyed?: boolean;
+ killThrows?: boolean;
+}
+
+function fakeGuestWc(opts: FakeGuestOpts) {
+ return {
+ hostWebContents: opts.hostId == null ? undefined : { id: opts.hostId },
+ getType: () => opts.type ?? 'webview',
+ isDestroyed: () => opts.destroyed === true,
+ forcefullyCrashRenderer: vi.fn(() => {
+ if (opts.killThrows) throw new Error('boom');
+ }),
+ };
+}
+
+function logger() {
+ return { info: vi.fn(), warn: vi.fn() };
+}
+
+function register(registry: TabRegistry) {
+ registerRsbBrowserBridgeIpc({
+ registry,
+ getHostWebContents: () => null,
+ logger: logger(),
+ });
+ const handlers = (ipcMain as unknown as {
+ __handlers: Map<string, (e: unknown, payload: unknown) => unknown>;
+ }).__handlers;
+ const handler = handlers.get(RSB_BROWSER_BRIDGE_FORCE_KILL_CHANNEL);
+ if (!handler) throw new Error('force-kill handler not registered');
+ return handler;
+}
+
+const senderEvent = { sender: { id: 10, once: vi.fn() } };
+
+describe('rsb-browser-bridge force-kill IPC', () => {
+ beforeEach(() => {
+ _resetRsbBrowserBridgeIpcForTests();
+ vi.mocked(electronWebContents.fromId).mockReset();
+ });
+
+ afterEach(() => {
+ _resetRsbBrowserBridgeIpcForTests();
+ vi.clearAllMocks();
+ });
+
+ it('kills a registry-resolved guest hosted by the sender', () => {
+ const guest = fakeGuestWc({ hostId: 10 });
+ const handler = register(fakeRegistry({ getWebContentsByTabId: () => guest }));
+
+ expect(handler(senderEvent, { tabId: 't1' })).toEqual({ ok: true });
+ expect(guest.forcefullyCrashRenderer).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the reported webContentsId when the registry has no row', () => {
+ const guest = fakeGuestWc({ hostId: 10 });
+ vi.mocked(electronWebContents.fromId).mockReturnValue(guest as never);
+ const handler = register(fakeRegistry({}));
+
+ expect(handler(senderEvent, { tabId: 't1', webContentsId: 77 })).toEqual({ ok: true });
+ expect(electronWebContents.fromId).toHaveBeenCalledWith(77);
+ expect(guest.forcefullyCrashRenderer).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects a fallback id that is not a webview guest', () => {
+ const notWebview = fakeGuestWc({ hostId: 10, type: 'window' });
+ vi.mocked(electronWebContents.fromId).mockReturnValue(notWebview as never);
+ const handler = register(fakeRegistry({}));
+
+ expect(() => handler(senderEvent, { tabId: 't1', webContentsId: 77 })).toThrow(
+ /NOT_FOUND/,
+ );
+ expect(notWebview.forcefullyCrashRenderer).not.toHaveBeenCalled();
+ });
+
+ it('rejects a fallback guest hosted by a different renderer', () => {
+ const foreign = fakeGuestWc({ hostId: 99 });
+ vi.mocked(electronWebContents.fromId).mockReturnValue(foreign as never);
+ const handler = register(fakeRegistry({}));
+
+ expect(() => handler(senderEvent, { tabId: 't1', webContentsId: 77 })).toThrow(
+ /INVALID_PARAMS/,
+ );
+ expect(foreign.forcefullyCrashRenderer).not.toHaveBeenCalled();
+ });
+
+ it('rejects when neither registry nor fallback resolves', () => {
+ const handler = register(fakeRegistry({}));
+ expect(() => handler(senderEvent, { tabId: 't1' })).toThrow(/NOT_FOUND/);
+ });
+
+ it('converts forcefullyCrashRenderer failures into [INTERNAL]', () => {
+ const guest = fakeGuestWc({ hostId: 10, killThrows: true });
+ const handler = register(fakeRegistry({ getWebContentsByTabId: () => guest }));
+
+ expect(() => handler(senderEvent, { tabId: 't1' })).toThrow(/INTERNAL/);
+ });
+});
diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/resource-watchdog.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/resource-watchdog.test.ts
new file mode 100644
index 0000000000..335027923b
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/resource-watchdog.test.ts
@@ -0,0 +1,394 @@
+/**
+ * resource-watchdog.test.ts
+ * ---------------------------------------------------------------------------
+ * 覆盖 BrowserGuestResourceWatchdog 的阶梯策略(全部依赖注入,不碰 Electron):
+ * - 后台内存超限 → 立即 evict
+ * - 后台高 CPU 连击 → evict;发声 / pinned 豁免;中断清零
+ * - 前台内存超限 → kill-notice + forcefullyCrashRenderer
+ * - 前台高 CPU 连击 → cpu-alert + 冷却,不杀进程
+ * - ForegroundTabTracker 的 per-sender 状态语义
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ BG_CPU_EVICT_STRIKES,
+ BG_CPU_PERCENT,
+ BG_MEMORY_EVICT_KB,
+ BrowserGuestResourceWatchdog,
+ FG_CPU_ALERT_COOLDOWN_TICKS,
+ FG_CPU_ALERT_STRIKES,
+ FG_CPU_PERCENT,
+ FG_MEMORY_KILL_KB,
+ ForegroundTabTracker,
+ pickResourceEventTarget,
+ type GuestProcessMetric,
+ type GuestWebContentsLike,
+ type ResourceWatchdogDeps,
+} from '../resource-watchdog';
+
+interface FakeGuest extends GuestWebContentsLike {
+ destroyed: boolean;
+ audible: boolean;
+ crashed: boolean;
+}
+
+function makeGuest(pid: number): FakeGuest {
+ return {
+ destroyed: false,
+ audible: false,
+ crashed: false,
+ isDestroyed() {
+ return this.destroyed;
+ },
+ getOSProcessId() {
+ return pid;
+ },
+ isCurrentlyAudible() {
+ return this.audible;
+ },
+ forcefullyCrashRenderer() {
+ this.crashed = true;
+ },
+ };
+}
+
+/** 单 tab harness:metric / 前台 / pin 状态可逐 tick 调整。 */
+function makeHarness() {
+ const guest = makeGuest(1001);
+ const metric: GuestProcessMetric = {
+ pid: 1001,
+ cpu: { percentCPUUsage: 0 },
+ memory: { workingSetSize: 100_000 },
+ };
+ const flags = { foreground: false, pinned: false, registered: true };
+ const notifyEvict = vi.fn();
+ const notifyKillNotice = vi.fn();
+ const notifyCpuAlert = vi.fn();
+ const deps: ResourceWatchdogDeps = {
+ listTabs: () => (flags.registered ? [{ tabId: 't1', webContentsId: 7 }] : []),
+ isPinned: () => flags.pinned,
+ isForeground: () => flags.foreground,
+ lookupWebContents: (id) => (id === 7 ? guest : null),
+ getMetrics: () => [metric],
+ notifyEvict,
+ notifyKillNotice,
+ notifyCpuAlert,
+ logger: { info: vi.fn(), warn: vi.fn() },
+ };
+ return {
+ watchdog: new BrowserGuestResourceWatchdog(deps),
+ guest,
+ metric,
+ flags,
+ notifyEvict,
+ notifyKillNotice,
+ notifyCpuAlert,
+ };
+}
+
+describe('BrowserGuestResourceWatchdog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('evicts a background guest immediately when memory exceeds the threshold', () => {
+ const h = makeHarness();
+ h.metric.memory.workingSetSize = BG_MEMORY_EVICT_KB;
+ h.watchdog.tick();
+ expect(h.notifyEvict).toHaveBeenCalledTimes(1);
+ expect(h.notifyEvict).toHaveBeenCalledWith('t1');
+ expect(h.guest.crashed).toBe(false);
+ });
+
+ it('evicts a background guest only after sustained high CPU strikes', () => {
+ const h = makeHarness();
+ h.metric.cpu.percentCPUUsage = BG_CPU_PERCENT + 10;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ h.watchdog.tick();
+ expect(h.notifyEvict).toHaveBeenCalledTimes(1);
+ });
+
+ it('a low-CPU sample resets the background strike counter', () => {
+ const h = makeHarness();
+ h.metric.cpu.percentCPUUsage = BG_CPU_PERCENT + 10;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ h.metric.cpu.percentCPUUsage = 5;
+ h.watchdog.tick(); // 清零
+ h.metric.cpu.percentCPUUsage = BG_CPU_PERCENT + 10;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ });
+
+ it('spares an audible background guest from CPU eviction but not memory eviction', () => {
+ const h = makeHarness();
+ h.guest.audible = true;
+ h.metric.cpu.percentCPUUsage = 100;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES * 2; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ h.metric.memory.workingSetSize = BG_MEMORY_EVICT_KB + 1;
+ h.watchdog.tick();
+ expect(h.notifyEvict).toHaveBeenCalledTimes(1);
+ });
+
+ it('exempts automation-pinned tabs from every action', () => {
+ const h = makeHarness();
+ h.flags.pinned = true;
+ h.metric.cpu.percentCPUUsage = 100;
+ h.metric.memory.workingSetSize = FG_MEMORY_KILL_KB * 2;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES * 2; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ expect(h.notifyKillNotice).not.toHaveBeenCalled();
+ expect(h.guest.crashed).toBe(false);
+ });
+
+ it('kills a foreground guest over the memory hard limit, notice first', () => {
+ const h = makeHarness();
+ h.flags.foreground = true;
+ h.metric.memory.workingSetSize = FG_MEMORY_KILL_KB;
+ h.watchdog.tick();
+ expect(h.notifyKillNotice).toHaveBeenCalledWith('t1');
+ expect(h.guest.crashed).toBe(true);
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ });
+
+ it('does NOT kill a foreground guest below the memory hard limit', () => {
+ const h = makeHarness();
+ h.flags.foreground = true;
+ // 后台早就该淘汰的量,前台必须容忍。
+ h.metric.memory.workingSetSize = BG_MEMORY_EVICT_KB + 1;
+ h.watchdog.tick();
+ expect(h.guest.crashed).toBe(false);
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ });
+
+ it('alerts (not kills) on sustained foreground CPU, then cools down', () => {
+ const h = makeHarness();
+ h.flags.foreground = true;
+ h.metric.cpu.percentCPUUsage = FG_CPU_PERCENT + 5;
+ for (let i = 0; i < FG_CPU_ALERT_STRIKES; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyCpuAlert).toHaveBeenCalledTimes(1);
+ expect(h.notifyCpuAlert).toHaveBeenCalledWith('t1', FG_CPU_PERCENT + 5);
+ expect(h.guest.crashed).toBe(false);
+
+ // 冷却期内即便持续高 CPU 也不重复告警。
+ for (let i = 0; i < FG_CPU_ALERT_COOLDOWN_TICKS - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyCpuAlert).toHaveBeenCalledTimes(1);
+
+ // 冷却结束 + 再次连击 → 第二次告警。
+ for (let i = 0; i < FG_CPU_ALERT_STRIKES + 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyCpuAlert).toHaveBeenCalledTimes(2);
+ });
+
+ it('foreground/background transition resets the other side strike counter', () => {
+ const h = makeHarness();
+ // 后台攒 strikes 差一次就淘汰,切前台后回到后台需要重新累计。
+ h.metric.cpu.percentCPUUsage = BG_CPU_PERCENT + 10;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ h.flags.foreground = true;
+ h.watchdog.tick();
+ h.flags.foreground = false;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ h.watchdog.tick();
+ expect(h.notifyEvict).toHaveBeenCalledTimes(1);
+ });
+
+ it('drops stale per-tab state when the tab is no longer registered', () => {
+ const h = makeHarness();
+ h.metric.cpu.percentCPUUsage = BG_CPU_PERCENT + 10;
+ h.watchdog.tick();
+ h.flags.registered = false;
+ h.watchdog.tick(); // listTabs 为空 → states 清空,不抛
+ h.flags.registered = true;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES - 1; i += 1) {
+ h.watchdog.tick();
+ }
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ });
+
+ it('skips destroyed guests and survives metrics collection failure', () => {
+ const h = makeHarness();
+ h.guest.destroyed = true;
+ h.metric.memory.workingSetSize = FG_MEMORY_KILL_KB * 2;
+ expect(() => h.watchdog.tick()).not.toThrow();
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+
+ const throwingDeps: ResourceWatchdogDeps = {
+ listTabs: () => [{ tabId: 't1', webContentsId: 7 }],
+ isPinned: () => false,
+ isForeground: () => false,
+ lookupWebContents: () => makeGuest(1),
+ getMetrics: () => {
+ throw new Error('metrics boom');
+ },
+ notifyEvict: vi.fn(),
+ notifyKillNotice: vi.fn(),
+ notifyCpuAlert: vi.fn(),
+ logger: { info: vi.fn(), warn: vi.fn() },
+ };
+ expect(() => new BrowserGuestResourceWatchdog(throwingDeps).tick()).not.toThrow();
+ });
+});
+
+describe('BrowserGuestResourceWatchdog — shared renderer process (PID) grouping', () => {
+ /** 双 tab harness:两个 tab 可指向同一个或不同的 guest 进程。 */
+ function makePairHarness(opts: { samePid: boolean }) {
+ const pidA = 2001;
+ const pidB = opts.samePid ? pidA : 2002;
+ const guestA = makeGuest(pidA);
+ const guestB = makeGuest(pidB);
+ const metricA: GuestProcessMetric = {
+ pid: pidA,
+ cpu: { percentCPUUsage: 0 },
+ memory: { workingSetSize: 100_000 },
+ };
+ const metricB: GuestProcessMetric = {
+ pid: pidB,
+ cpu: { percentCPUUsage: 0 },
+ memory: { workingSetSize: 100_000 },
+ };
+ const flags = {
+ pinned: new Set<string>(),
+ foreground: new Set<string>(),
+ };
+ const notifyEvict = vi.fn();
+ const notifyKillNotice = vi.fn();
+ const notifyCpuAlert = vi.fn();
+ const deps: ResourceWatchdogDeps = {
+ listTabs: () => [
+ { tabId: 'ta', webContentsId: 71 },
+ { tabId: 'tb', webContentsId: 72 },
+ ],
+ isPinned: (tabId) => flags.pinned.has(tabId),
+ isForeground: (tabId) => flags.foreground.has(tabId),
+ lookupWebContents: (id) => (id === 71 ? guestA : id === 72 ? guestB : null),
+ getMetrics: () => (opts.samePid ? [metricA] : [metricA, metricB]),
+ notifyEvict,
+ notifyKillNotice,
+ notifyCpuAlert,
+ logger: { info: vi.fn(), warn: vi.fn() },
+ };
+ return {
+ watchdog: new BrowserGuestResourceWatchdog(deps),
+ guestA,
+ guestB,
+ metricA,
+ metricB,
+ flags,
+ notifyEvict,
+ notifyKillNotice,
+ notifyCpuAlert,
+ };
+ }
+
+ it('a pinned sibling in the same process exempts every tab of that process', () => {
+ const h = makePairHarness({ samePid: true });
+ h.flags.pinned.add('tb');
+ h.flags.foreground.add('ta');
+ h.metricA.memory.workingSetSize = FG_MEMORY_KILL_KB * 2;
+ for (let i = 0; i < BG_CPU_EVICT_STRIKES * 2; i += 1) h.watchdog.tick();
+ expect(h.guestA.crashed).toBe(false);
+ expect(h.notifyKillNotice).not.toHaveBeenCalled();
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ });
+
+ it('a background sibling of a foreground process is not evicted for shared metrics', () => {
+ const h = makePairHarness({ samePid: true });
+ h.flags.foreground.add('ta'); // tb 后台,但与 ta 同进程
+ // 进程级内存超后台淘汰线但低于前台强杀线:tb 不能替前台负载背锅被淘汰。
+ h.metricA.memory.workingSetSize = BG_MEMORY_EVICT_KB + 1;
+ h.watchdog.tick();
+ expect(h.notifyEvict).not.toHaveBeenCalled();
+ // 对照组:不同进程时,后台 tb 自己的内存超线照常淘汰。
+ const h2 = makePairHarness({ samePid: false });
+ h2.flags.foreground.add('ta');
+ h2.metricB.memory.workingSetSize = BG_MEMORY_EVICT_KB + 1;
+ h2.watchdog.tick();
+ expect(h2.notifyEvict).toHaveBeenCalledWith('tb');
+ });
+
+ it('kills a shared process at most once per tick, noticing every sibling tab', () => {
+ const h = makePairHarness({ samePid: true });
+ // 只有 ta 前台;tb 是同进程后台兄弟 —— 遍历顺序无论先命中谁,kill-notice
+ // 都要覆盖进程内全部 tab(它们的 guest 会一起崩,各自 banner 都要显示原因)。
+ h.flags.foreground.add('ta');
+ h.metricA.memory.workingSetSize = FG_MEMORY_KILL_KB;
+ h.watchdog.tick();
+ expect(h.notifyKillNotice).toHaveBeenCalledTimes(2);
+ expect(h.notifyKillNotice).toHaveBeenCalledWith('ta');
+ expect(h.notifyKillNotice).toHaveBeenCalledWith('tb');
+ // 同一进程:两个 guest fake 各自记 crashed,但只允许对进程杀一次。
+ expect(Number(h.guestA.crashed) + Number(h.guestB.crashed)).toBe(1);
+ });
+});
+
+describe('pickResourceEventTarget', () => {
+ const live = () => ({ isDestroyed: () => false });
+ const dead = () => ({ isDestroyed: () => true });
+
+ it('delivers only to the live guest owner renderer', () => {
+ const owner = live();
+ expect(pickResourceEventTarget(owner)).toBe(owner);
+ });
+
+ it('drops delivery (no cross-window fallback) when the owner is missing or destroyed', () => {
+ expect(pickResourceEventTarget(null)).toBeNull();
+ expect(pickResourceEventTarget(undefined)).toBeNull();
+ expect(pickResourceEventTarget(dead())).toBeNull();
+ });
+});
+
+describe('ForegroundTabTracker', () => {
+ it('tracks per-sender foreground claims and clears on null / drop', () => {
+ const tracker = new ForegroundTabTracker();
+ expect(tracker.isForeground('a')).toBe(false);
+
+ tracker.set(1, 'a');
+ tracker.set(2, 'b');
+ expect(tracker.isForeground('a')).toBe(true);
+ expect(tracker.isForeground('b')).toBe(true);
+
+ // 同一 sender 的新声明覆盖旧声明。
+ tracker.set(1, 'c');
+ expect(tracker.isForeground('a')).toBe(false);
+ expect(tracker.isForeground('c')).toBe(true);
+
+ tracker.set(2, null);
+ expect(tracker.isForeground('b')).toBe(false);
+
+ tracker.drop(1);
+ expect(tracker.isForeground('c')).toBe(false);
+ });
+
+ it('isForegroundFor only accepts the claim from the specified sender', () => {
+ const tracker = new ForegroundTabTracker();
+ tracker.set(1, 'a');
+ // sender 1 声明了 a → 只有以 sender 1 的身份查询才算前台;
+ // 别的 renderer(如 tab 实际宿主是 2)冒领不生效。
+ expect(tracker.isForegroundFor('a', 1)).toBe(true);
+ expect(tracker.isForegroundFor('a', 2)).toBe(false);
+ expect(tracker.isForegroundFor('b', 1)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
index 13553ad3f2..b20c7d92fd 100644
--- a/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
+++ b/apps/desktop/src/main/rsb-browser-bridge/ipc.ts
@@ -13,17 +13,27 @@
* All `invoke` handlers validate inputs and throw via `throwIpcError` (rule 13).
*/
-import { clipboard, ipcMain, webContents as electronWebContents, type WebContents } from 'electron';
+import {
+ app,
+ clipboard,
+ ipcMain,
+ webContents as electronWebContents,
+ type WebContents,
+} from 'electron';
import {
RSB_BROWSER_BRIDGE_CAPTURE_SCREENSHOT_CHANNEL,
RSB_BROWSER_BRIDGE_CAPTURE_SCREENSHOT_DATA_CHANNEL,
+ RSB_BROWSER_BRIDGE_FORCE_KILL_CHANNEL,
RSB_BROWSER_BRIDGE_PIN_CHANNEL,
RSB_BROWSER_BRIDGE_RELEASE_CHANNEL,
RSB_BROWSER_BRIDGE_REPORT_CHANNEL,
+ RSB_BROWSER_BRIDGE_RESOURCE_EVENT_CHANNEL,
+ RSB_BROWSER_BRIDGE_SET_FOREGROUND_CHANNEL,
RSB_BROWSER_BRIDGE_SNAPSHOT_CHANNEL,
RSB_BROWSER_BRIDGE_UNPIN_CHANNEL,
type RsbBrowserBridgeReportPayload,
+ type RsbBrowserBridgeResourceEvent,
} from '../../shared/rsbBrowserBridge.js';
import {
requireNonNegativeInt,
@@ -32,6 +42,12 @@ import {
throwIpcError,
} from '../utils/ipcValidate.js';
import type { TabRegistry } from './registry.js';
+import {
+ BrowserGuestResourceWatchdog,
+ ForegroundTabTracker,
+ pickResourceEventTarget,
+ type GuestWebContentsLike,
+} from './resource-watchdog.js';
interface IpcLogger {
info(message: string, ...args: unknown[]): void;
@@ -55,6 +71,8 @@ export interface RegisterRsbBrowserBridgeOptions {
* calls are no-ops.
*/
let registered = false;
+/** 当前活跃的看门狗实例 —— 测试 reset 时必须 stop,否则 interval 泄漏到后续用例。 */
+let activeWatchdog: BrowserGuestResourceWatchdog | null = null;
export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOptions): () => void {
if (registered) {
@@ -210,6 +228,107 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
},
);
+ // ── 资源看门狗(前台/后台阶梯处置,策略见 resource-watchdog.ts) ─────────
+ const foregroundTracker = new ForegroundTabTracker();
+ // senderId → 是否已挂 destroyed 清理。renderer 销毁(窗口关 / 崩溃)时槽位
+ // 必须清掉,否则残留的"前台 tab"会永远享受前台豁免。
+ const foregroundCleanupAttached = new Set<number>();
+
+ ipcMain.handle(RSB_BROWSER_BRIDGE_SET_FOREGROUND_CHANNEL, (event, payload: unknown) => {
+ const obj = requireObject(payload, 'set-foreground payload');
+ if (obj.tabId !== null && (typeof obj.tabId !== 'string' || obj.tabId === '')) {
+ throwIpcError('INVALID_PARAMS', 'tabId must be a non-empty string or null');
+ }
+ foregroundTracker.set(event.sender.id, obj.tabId as string | null);
+ if (!foregroundCleanupAttached.has(event.sender.id)) {
+ foregroundCleanupAttached.add(event.sender.id);
+ const senderId = event.sender.id;
+ event.sender.once('destroyed', () => {
+ foregroundTracker.drop(senderId);
+ foregroundCleanupAttached.delete(senderId);
+ });
+ }
+ return { ok: true };
+ });
+
+ // 用户主动终止 guest 进程(unresponsive banner / cpu-alert 提示条的按钮)。
+ // 归属校验与截图相同:tabId → registry → 该 guest 必须挂在发起请求的 renderer
+ // 下,防止拿别的窗口的 webContents 强杀。registry 未命中时(页面在首个
+ // dom-ready 前锁死 renderer,还没 report 进来)接受 renderer 自报的
+ // webContentsId 兜底 —— 对其执行与 report 相同的三重校验(可解析、是 webview
+ // guest、宿主为 sender),不放松信任模型。
+ ipcMain.handle(RSB_BROWSER_BRIDGE_FORCE_KILL_CHANNEL, (event, payload: unknown) => {
+ const obj = requireObject(payload, 'force-kill payload');
+ const tabId = requireString(obj.tabId, 'tabId');
+ let target = registry.getWebContentsByTabId(tabId);
+ if (!target && obj.webContentsId !== undefined) {
+ const webContentsId = requireNonNegativeInt(obj.webContentsId, 'webContentsId');
+ const fallback = electronWebContents.fromId(webContentsId);
+ if (fallback && !fallback.isDestroyed() && fallback.getType() === 'webview') {
+ target = fallback;
+ }
+ }
+ if (!target) {
+ throwIpcError('NOT_FOUND', `no live webContents for tab ${tabId}`);
+ }
+ const host = (target as unknown as { hostWebContents?: WebContents }).hostWebContents;
+ if (!host || host.id !== event.sender.id) {
+ throwIpcError('INVALID_PARAMS', `tab ${tabId} is not hosted by the sender`);
+ }
+ logger.info('RSB browser guest force-killed by user', { tabId });
+ try {
+ target.forcefullyCrashRenderer();
+ } catch (err) {
+ // TOCTOU:registry 反查和 kill 之间 guest 可能刚好死掉。裸抛会把原始
+ // Electron 错误回给 renderer,统一转 IPC 错误协议。
+ logger.warn('forcefullyCrashRenderer threw', { tabId, err });
+ throwIpcError('INTERNAL', 'forcefullyCrashRenderer failed');
+ }
+ return { ok: true };
+ });
+
+ // 资源事件必须送到"实际托管该 guest 的 renderer":经 registry 反查 guest 再
+ // 取其 hostWebContents;宿主不可用时放弃本轮投递,不回退到别的窗口(见
+ // pickResourceEventTarget 注释;review P1:送错 renderer 时 evict 是空操作、
+ // cpu-alert 无人消费,还会掩盖问题)。
+ const sendResourceEvent = (event: RsbBrowserBridgeResourceEvent) => {
+ const guest = registry.getWebContentsByTabId(event.tabId);
+ const owner = guest
+ ? (guest as unknown as { hostWebContents?: WebContents }).hostWebContents
+ : null;
+ const wc = pickResourceEventTarget(owner);
+ if (!wc) return;
+ wc.send(RSB_BROWSER_BRIDGE_RESOURCE_EVENT_CHANNEL, event);
+ };
+
+ const watchdog = new BrowserGuestResourceWatchdog({
+ listTabs: () =>
+ registry.listAll().map((r) => ({ tabId: r.tabId, webContentsId: r.webContentsId })),
+ isPinned: (tabId) => registry.isPinned(tabId),
+ // 前台判定带归属校验:声明者必须就是 guest 当前的宿主 renderer,防止别的
+ // renderer 冒领前台给目标 tab 骗豁免。guest 反查失败(注册竞态)时退回
+ // 无归属版本 —— 此时该 tab 也不在 listTabs 里,不会被误处置。
+ isForeground: (tabId) => {
+ const guest = registry.getWebContentsByTabId(tabId);
+ const owner = guest
+ ? (guest as unknown as { hostWebContents?: WebContents }).hostWebContents
+ : null;
+ return owner
+ ? foregroundTracker.isForegroundFor(tabId, owner.id)
+ : foregroundTracker.isForeground(tabId);
+ },
+ lookupWebContents: (id) =>
+ (electronWebContents.fromId(id) as GuestWebContentsLike | undefined) ?? null,
+ getMetrics: () => app.getAppMetrics(),
+ notifyEvict: (tabId) => sendResourceEvent({ tabId, kind: 'evict-request' }),
+ notifyKillNotice: (tabId) => sendResourceEvent({ tabId, kind: 'kill-notice', cause: 'memory' }),
+ notifyCpuAlert: (tabId, cpuPercent) =>
+ sendResourceEvent({ tabId, kind: 'cpu-alert', cpuPercent }),
+ logger,
+ });
+ watchdog.start();
+ activeWatchdog = watchdog;
+
// Pin broadcast wiring: when the registry's pin set changes, push a `pin` /
// `unpin` message to the host renderer so the pool can suppress LRU eviction.
// The host might be unavailable during early boot or app quit — `getHostWebContents`
@@ -230,6 +349,7 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
return () => {
unsubscribe();
+ watchdog.stop();
// Note: ipcMain.removeHandler is intentionally NOT called here. Handlers
// are process-lifetime (registered once during boot); on app quit the
// process tears down. Tests use `_resetRsbBrowserBridgeIpcForTests` below.
@@ -242,4 +362,6 @@ export function registerRsbBrowserBridgeIpc(opts: RegisterRsbBrowserBridgeOption
*/
export function _resetRsbBrowserBridgeIpcForTests(): void {
registered = false;
+ activeWatchdog?.stop();
+ activeWatchdog = null;
}
diff --git a/apps/desktop/src/main/rsb-browser-bridge/resource-watchdog.ts b/apps/desktop/src/main/rsb-browser-bridge/resource-watchdog.ts
new file mode 100644
index 0000000000..8f7ac8c780
--- /dev/null
+++ b/apps/desktop/src/main/rsb-browser-bridge/resource-watchdog.ts
@@ -0,0 +1,338 @@
+/**
+ * BrowserGuestResourceWatchdog —— RSB 浏览器 `<webview>` guest 的资源看门狗。
+ *
+ * 为什么需要它:guest 是独立进程,JS 死循环 / 泄漏不会阻塞主界面的 event loop,
+ * 但会通过三条系统级路径拖垮整个 App:
+ * 1. 系统内存压力(guest 吃到几个 GB → 全系统换页,主窗口整体卡顿);
+ * 2. 共享 GPU 进程被打满(所有 surface 由同一 GPU 进程合成);
+ * 3. 停车区的后台 webview 在 Chromium 眼里仍"可见",不吃后台降频,全速烧 CPU。
+ * 对"高占用但不崩溃"的页面,唯一有效的手段是主动淘汰 / 主动终止(Chrome 的
+ * out-of-memory tab kill 同理)。终止后的善后复用现成链路:forcefullyCrashRenderer
+ * 触发 guest `render-process-gone` → renderer 的 crash banner + reload 恢复。
+ *
+ * 阶梯策略(阈值全部导出为常量,便于按线上数据调整):
+ * - 后台 & 内存 ≥ BG_MEMORY_EVICT_KB → 淘汰(renderer pool.release;
+ * 对用户等价于 LRU 淘汰,tab 保留,下次激活重新加载)
+ * - 后台 & CPU ≥ BG_CPU_PERCENT 连续 N 个采样 → 淘汰(正在发声的除外 ——
+ * 用户后台放音乐 / 视频是合法场景)
+ * - 前台 & 内存 ≥ FG_MEMORY_KILL_KB → 先发 kill-notice 再强杀,
+ * banner 显示"内存过高被终止"
+ * - 前台 & CPU ≥ FG_CPU_PERCENT 连续 N 个采样 → 只发 cpu-alert 提示,不自动杀
+ * (可能是用户在跑正经的重页面);告警后进入冷却,不反复骚扰
+ * - automation pinned 的 tab 全部豁免 —— agent 正在驱动的页面,杀了会让自动化
+ * 拿到 destroyed webContents 中途失败;pin 的生命周期本来就短
+ *
+ * 依赖全部注入(metrics / webContents 查找 / 前台判定 / 通知动作),不直接 import
+ * electron —— main 侧业务逻辑默认带单测(engineering-conventions 规则 3)。
+ */
+
+interface WatchdogLogger {
+ info(message: string, ...args: unknown[]): void;
+ warn(message: string, ...args: unknown[]): void;
+}
+
+/** app.getAppMetrics() 返回项的最小子集。memory.workingSetSize 单位是 KB。 */
+export interface GuestProcessMetric {
+ pid: number;
+ cpu: { percentCPUUsage: number };
+ memory: { workingSetSize: number };
+}
+
+/** 看门狗对 guest webContents 的最小依赖面(便于测试注入 fake)。 */
+export interface GuestWebContentsLike {
+ isDestroyed(): boolean;
+ getOSProcessId(): number;
+ isCurrentlyAudible(): boolean;
+ forcefullyCrashRenderer(): void;
+}
+
+export interface ResourceWatchdogDeps {
+ /** 当前注册的全部浏览器 tab(TabRegistry.listAll 的子集视图)。 */
+ listTabs(): Array<{ tabId: string; webContentsId: number }>;
+ /** tabId 是否被 automation pin(TabRegistry.isPinned)。 */
+ isPinned(tabId: string): boolean;
+ /** tabId 是否是某个 renderer 正在展示的前台 tab(ForegroundTabTracker)。 */
+ isForeground(tabId: string): boolean;
+ lookupWebContents(id: number): GuestWebContentsLike | null;
+ /** app.getAppMetrics() —— 每次 tick 调一次,percentCPUUsage 即两次调用间的均值。 */
+ getMetrics(): GuestProcessMetric[];
+ /** 请 renderer 淘汰该后台 tab(main → renderer resource-event: evict-request)。 */
+ notifyEvict(tabId: string): void;
+ /** 通知 renderer "即将强杀"(kill-notice),banner 才能显示资源原因。 */
+ notifyKillNotice(tabId: string): void;
+ /** 前台持续高 CPU 提示(cpu-alert)。 */
+ notifyCpuAlert(tabId: string, cpuPercent: number): void;
+ logger: WatchdogLogger;
+}
+
+/** 采样周期。30s 在"及时止损"和"采样本身的开销 / 误报率"之间取平衡。 */
+export const RESOURCE_WATCHDOG_INTERVAL_MS = 30_000;
+
+/** 后台 guest 内存淘汰阈值(KB)= 1 GiB。淘汰对用户无感(等价 LRU),从严。 */
+export const BG_MEMORY_EVICT_KB = 1024 * 1024;
+/** 后台 guest 高 CPU 阈值(%,单核百分比)。 */
+export const BG_CPU_PERCENT = 50;
+/** 后台高 CPU 连续命中多少个采样后淘汰(2 分钟)。 */
+export const BG_CPU_EVICT_STRIKES = 4;
+
+/** 前台 guest 内存强杀阈值(KB)= 2 GiB。前台动作要保守,只拦真失控的。 */
+export const FG_MEMORY_KILL_KB = 2 * 1024 * 1024;
+/** 前台 guest 高 CPU 阈值(%)。 */
+export const FG_CPU_PERCENT = 90;
+/** 前台高 CPU 连续命中多少个采样后提示(2 分钟)。 */
+export const FG_CPU_ALERT_STRIKES = 4;
+/** cpu-alert 发出后的冷却 tick 数(5 分钟),避免反复弹提示。 */
+export const FG_CPU_ALERT_COOLDOWN_TICKS = 10;
+
+/** 单个 tab 的连击计数状态。tab 淘汰 / 被杀 / 注销后清除。 */
+interface TabWatchState {
+ bgCpuStrikes: number;
+ fgCpuStrikes: number;
+ alertCooldownTicks: number;
+}
+
+export class BrowserGuestResourceWatchdog {
+ private readonly states = new Map<string, TabWatchState>();
+ private timer: ReturnType<typeof setInterval> | null = null;
+
+ constructor(private readonly deps: ResourceWatchdogDeps) {}
+
+ start(intervalMs: number = RESOURCE_WATCHDOG_INTERVAL_MS): void {
+ if (this.timer) return;
+ this.timer = setInterval(() => this.tick(), intervalMs);
+ // 采样定时器不该阻止进程退出(main 退出编排在 lifecycle.ts)。
+ this.timer.unref?.();
+ }
+
+ stop(): void {
+ if (this.timer) {
+ clearInterval(this.timer);
+ this.timer = null;
+ }
+ this.states.clear();
+ }
+
+ /** 单次采样 + 阶梯裁决。导出为 public 供单测直接驱动(不用假时钟)。 */
+ tick(): void {
+ const tabs = this.deps.listTabs();
+ if (tabs.length === 0) {
+ this.states.clear();
+ return;
+ }
+
+ let metricsByPid: Map<number, GuestProcessMetric>;
+ try {
+ metricsByPid = new Map(this.deps.getMetrics().map((m) => [m.pid, m]));
+ } catch (err) {
+ this.deps.logger.warn('resource watchdog metrics collection failed', err);
+ return;
+ }
+
+ // ── 第一遍:解析每个 tab 的进程归属,按 PID 聚合豁免状态 ────────────────
+ // Chromium 可能把 same-site 的多个 webview guest 合并进同一个 renderer 进程,
+ // 此时 CPU / 内存指标是进程级的,pin / 前台却是 tab 级 —— 独立裁决会出现
+ // "杀前台超限 tab 连带杀掉同进程的 pinned 兄弟"或"后台兄弟替前台的负载
+ // 背锅被淘汰"。聚合规则:同 PID 内任一 tab pinned → 全体豁免;任一 tab
+ // 前台 → 全体按前台策略;kill 每 tick 每 PID 至多一次(杀进程本来就会
+ // 带走同进程所有 tab,重复调用无意义)。
+ interface ResolvedTab {
+ tabId: string;
+ wc: GuestWebContentsLike;
+ pid: number;
+ metric: GuestProcessMetric;
+ }
+ const resolved: ResolvedTab[] = [];
+ const pidPinned = new Set<number>();
+ const pidForeground = new Set<number>();
+ const pidTabs = new Map<number, string[]>();
+ const liveTabIds = new Set<string>();
+ for (const tab of tabs) {
+ liveTabIds.add(tab.tabId);
+ const wc = this.deps.lookupWebContents(tab.webContentsId);
+ if (!wc || wc.isDestroyed()) {
+ this.states.delete(tab.tabId);
+ continue;
+ }
+ let pid: number;
+ try {
+ pid = wc.getOSProcessId();
+ } catch {
+ // guest 正处于 crash / attach 中间态,取不到 pid —— 本轮跳过。
+ continue;
+ }
+ const metric = metricsByPid.get(pid);
+ if (!metric) continue;
+ if (this.deps.isPinned(tab.tabId)) pidPinned.add(pid);
+ if (this.deps.isForeground(tab.tabId)) pidForeground.add(pid);
+ const siblings = pidTabs.get(pid);
+ if (siblings) {
+ siblings.push(tab.tabId);
+ } else {
+ pidTabs.set(pid, [tab.tabId]);
+ }
+ resolved.push({ tabId: tab.tabId, wc, pid, metric });
+ }
+
+ // ── 第二遍:按聚合后的进程级状态执行阶梯 ─────────────────────────────
+ const killedPids = new Set<number>();
+ for (const tab of resolved) {
+ if (pidPinned.has(tab.pid)) {
+ // automation 驱动中的进程全豁免(含同进程兄弟 tab);连击计数一并清零,
+ // pin 释放后重新累计,避免 automation 期间的高负载"记账"到用户头上。
+ this.states.delete(tab.tabId);
+ continue;
+ }
+
+ const state = this.states.get(tab.tabId) ?? {
+ bgCpuStrikes: 0,
+ fgCpuStrikes: 0,
+ alertCooldownTicks: 0,
+ };
+ this.states.set(tab.tabId, state);
+ if (state.alertCooldownTicks > 0) state.alertCooldownTicks -= 1;
+
+ const cpu = tab.metric.cpu.percentCPUUsage;
+ const memoryKB = tab.metric.memory.workingSetSize;
+ const wc = tab.wc;
+
+ if (pidForeground.has(tab.pid)) {
+ state.bgCpuStrikes = 0;
+ if (memoryKB >= FG_MEMORY_KILL_KB) {
+ // 同 PID 每 tick 至多杀一次:forcefullyCrashRenderer 杀的是整个进程,
+ // 同进程兄弟 tab 会一起收到 render-process-gone,重复调用无意义。
+ if (killedPids.has(tab.pid)) {
+ this.states.delete(tab.tabId);
+ continue;
+ }
+ killedPids.add(tab.pid);
+ this.deps.logger.warn(
+ `resource watchdog killing foreground guest: tab=${tab.tabId} pid=${tab.pid} memoryKB=${memoryKB}`,
+ );
+ // 先 notice 后 kill:renderer 记下原因,随后的 render-process-gone
+ // banner 才能显示"内存过高被终止"而不是笼统的"页面崩溃"。
+ // notice 发给该进程的**所有** tab —— 杀进程会让同进程兄弟一起崩,
+ // 每个 tab 的 banner 都该显示真实原因,而不是只有恰好先被遍历到的
+ // 那个(遍历顺序可能先命中后台兄弟,导致可见 tab 拿不到原因)。
+ for (const sibling of pidTabs.get(tab.pid) ?? [tab.tabId]) {
+ this.deps.notifyKillNotice(sibling);
+ }
+ try {
+ wc.forcefullyCrashRenderer();
+ } catch (err) {
+ this.deps.logger.warn('forcefullyCrashRenderer threw', err);
+ }
+ this.states.delete(tab.tabId);
+ continue;
+ }
+ if (cpu >= FG_CPU_PERCENT) {
+ state.fgCpuStrikes += 1;
+ if (state.fgCpuStrikes >= FG_CPU_ALERT_STRIKES && state.alertCooldownTicks === 0) {
+ this.deps.logger.info(
+ `resource watchdog cpu alert: tab=${tab.tabId} cpu=${cpu.toFixed(0)}%`,
+ );
+ this.deps.notifyCpuAlert(tab.tabId, cpu);
+ state.fgCpuStrikes = 0;
+ state.alertCooldownTicks = FG_CPU_ALERT_COOLDOWN_TICKS;
+ }
+ } else {
+ state.fgCpuStrikes = 0;
+ }
+ continue;
+ }
+
+ // ── 后台 ────────────────────────────────────────────────────────────
+ state.fgCpuStrikes = 0;
+ if (memoryKB >= BG_MEMORY_EVICT_KB) {
+ this.deps.logger.info(
+ `resource watchdog evicting background guest (memory): tab=${tab.tabId} memoryKB=${memoryKB}`,
+ );
+ this.deps.notifyEvict(tab.tabId);
+ this.states.delete(tab.tabId);
+ continue;
+ }
+ if (cpu >= BG_CPU_PERCENT) {
+ // 正在发声的后台页面(音乐 / 视频)是用户的合法使用场景,CPU 规则放行;
+ // 内存规则(上面)不豁免 —— 音频页也不该吃 1GB。
+ let audible = false;
+ try {
+ audible = wc.isCurrentlyAudible();
+ } catch {
+ // 中间态取不到,按不发声处理。
+ }
+ if (audible) {
+ state.bgCpuStrikes = 0;
+ continue;
+ }
+ state.bgCpuStrikes += 1;
+ if (state.bgCpuStrikes >= BG_CPU_EVICT_STRIKES) {
+ this.deps.logger.info(
+ `resource watchdog evicting background guest (cpu): tab=${tab.tabId} cpu=${cpu.toFixed(0)}%`,
+ );
+ this.deps.notifyEvict(tab.tabId);
+ this.states.delete(tab.tabId);
+ }
+ } else {
+ state.bgCpuStrikes = 0;
+ }
+ }
+
+ // 已注销 tab 的残留状态清理(registry 淘汰 / 关 tab 后)。
+ for (const tabId of [...this.states.keys()]) {
+ if (!liveTabIds.has(tabId)) this.states.delete(tabId);
+ }
+ }
+}
+
+/**
+ * 资源事件的目标 renderer 选择(纯函数,ipc.ts 消费):只认 guest 的实际宿主
+ * (hostWebContents)—— 主窗内嵌 RSB / detached 子窗口 / 副窗口各自是独立
+ * renderer,pool 与订阅只在宿主侧存在,送给别的 renderer 是空操作还会掩盖
+ * 问题。宿主已销毁 / guest 已死的竞态下返回 null 放弃本轮投递:webview guest
+ * 与宿主 renderer 同生共死,这种瞬态里 tab 要么正随宿主消亡,要么马上会被新
+ * 宿主 re-report,下个采样周期自然重试,不做"回退到另一个窗口"的错投。
+ */
+export function pickResourceEventTarget<T extends { isDestroyed(): boolean }>(
+ owner: T | null | undefined,
+): T | null {
+ return owner && !owner.isDestroyed() ? owner : null;
+}
+
+/**
+ * ForegroundTabTracker —— 记录"每个 renderer 当前展示哪个浏览器 tab"。
+ *
+ * renderer 通过 `set-foreground` 上报全量状态(tabId | null);多窗口(主窗内嵌
+ * RSB + detached 侧边栏子窗口)各自上报,按 senderId 分槽。任何一个 renderer
+ * 正在展示的 tab 都算前台。renderer 销毁时槽位由 ipc.ts 调 drop 清除。
+ */
+export class ForegroundTabTracker {
+ private readonly bySender = new Map<number, string>();
+
+ set(senderId: number, tabId: string | null): void {
+ if (tabId === null) {
+ this.bySender.delete(senderId);
+ } else {
+ this.bySender.set(senderId, tabId);
+ }
+ }
+
+ drop(senderId: number): void {
+ this.bySender.delete(senderId);
+ }
+
+ isForeground(tabId: string): boolean {
+ for (const v of this.bySender.values()) {
+ if (v === tabId) return true;
+ }
+ return false;
+ }
+
+ /**
+ * 归属校验版:仅当"声明该 tab 为前台的 sender"就是指定 renderer 时才算前台。
+ * 看门狗消费时用它交叉验证 guest 的实际 hostWebContents —— 防止别的 renderer
+ * 冒领前台让目标 tab 享受豁免(review:set-foreground 不做上报时校验是因为
+ * 上报可能早于 dom-ready 的 registry report,硬拒会把可见 tab 永久打成后台)。
+ */
+ isForegroundFor(tabId: string, senderId: number): boolean {
+ return this.bySender.get(senderId) === tabId;
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 98397452ca..b2d832fb77 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -315,6 +315,7 @@ const fanOutRsbBrowserCommand = createIpcFanOut('rsb:browser-command');
// LRU 据此跳过 pinned tab,避免 automation 操作期间 webContents 被销毁。
const fanOutRsbBrowserBridgePin = createIpcFanOut('rsb-browser-bridge:pin');
const fanOutRsbBrowserBridgeUnpin = createIpcFanOut('rsb-browser-bridge:unpin');
+const fanOutRsbBrowserBridgeResourceEvent = createIpcFanOut('rsb-browser-bridge:resource-event');
// Phase 3: RsbWebviewBackend (open/focus/close) push 给 renderer 让它代调 store。
const fanOutRsbBrowserBridgeTabOpRequest = createIpcFanOut('rsb-browser-bridge:tab-op-request');
// session-git-pr-context: HEAD 分支变化 / session PR 引用变化推送
@@ -3493,6 +3494,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** Push renderer's currently-focused RSB sessionId to main (Phase 5). */
setActiveSession: (input: { sessionId: string | null }): Promise<unknown> =>
ipcRenderer.invoke('rsb-browser-bridge:set-active-session', input),
+ /** 资源看门狗:上报本 renderer 当前展示的浏览器 tab(null = 无)。 */
+ setForeground: (input: { tabId: string | null }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:set-foreground', input),
+ /** 用户主动强杀 guest 进程(unresponsive banner / cpu 提示条的「强制终止」);
+ * webContentsId 供 registry 未命中(attach 后、首个 dom-ready 前)兜底。 */
+ forceKill: (input: { tabId: string; webContentsId?: number }): Promise<unknown> =>
+ ipcRenderer.invoke('rsb-browser-bridge:force-kill', input),
+ /** main → renderer 资源看门狗事件(evict-request / kill-notice / cpu-alert)。 */
+ onResourceEvent: (cb: (event: unknown) => void) =>
+ fanOutRsbBrowserBridgeResourceEvent(cb as IpcCallback),
},
// ── Browser backend toggle (Phase 5) ─────────────────────────────────────
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
index d5a1c7b9c7..96458a037d 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/RightSidebarShell.test.ts
@@ -64,6 +64,9 @@ function installElectronApi(tabsIpc: RightSidebarTabsIpcStub, fullscreen = false
onUnpin: ReturnType<typeof vi.fn>;
onTabOpRequest: ReturnType<typeof vi.fn>;
tabOpResult: ReturnType<typeof vi.fn>;
+ setForeground: ReturnType<typeof vi.fn>;
+ forceKill: ReturnType<typeof vi.fn>;
+ onResourceEvent: ReturnType<typeof vi.fn>;
};
gitReview: { summary: ReturnType<typeof vi.fn> };
onRsbBrowserPopup: ReturnType<typeof vi.fn>;
@@ -89,6 +92,9 @@ function installElectronApi(tabsIpc: RightSidebarTabsIpcStub, fullscreen = false
onUnpin: vi.fn(() => () => undefined),
onTabOpRequest: vi.fn(() => () => undefined),
tabOpResult: vi.fn(async () => undefined),
+ setForeground: vi.fn(async () => undefined),
+ forceKill: vi.fn(async () => undefined),
+ onResourceEvent: vi.fn(() => () => undefined),
},
gitReview: {
summary: vi.fn(async () => ({
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
index 9fde78cd78..78048824f3 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/__tests__/useBrowserWebview.test.ts
@@ -27,18 +27,46 @@ interface MockWebview {
let mockWebview: MockWebview;
+const poolMocks = vi.hoisted(() => ({
+ releaseListeners: new Set<(tabId: string) => void>(),
+ fireRelease(tabId: string) {
+ for (const cb of [...this.releaseListeners]) cb(tabId);
+ },
+}));
+
+const bridgeMocks = vi.hoisted(() => ({
+ resourceCb: null as ((event: Record<string, unknown>) => void) | null,
+ consumePendingKillCause: undefined as unknown as ReturnType<typeof vi.fn>,
+}));
+
vi.mock('../../lib/browserWebviewPool', () => ({
browserWebviewPool: {
acquire: vi.fn(() => ({
wrapper: document.createElement('div'),
webview: mockWebview,
})),
+ onRelease: vi.fn((cb: (tabId: string) => void) => {
+ poolMocks.releaseListeners.add(cb);
+ return () => poolMocks.releaseListeners.delete(cb);
+ }),
},
}));
-vi.mock('../../lib/rsbBrowserBridge', () => ({
- reportRsbBrowserTab: vi.fn(),
-}));
+vi.mock('../../lib/rsbBrowserBridge', () => {
+ bridgeMocks.consumePendingKillCause = vi.fn(() => null);
+ return {
+ reportRsbBrowserTab: vi.fn(),
+ subscribeTabResourceEvent: vi.fn(
+ (_tabId: string, cb: (event: Record<string, unknown>) => void) => {
+ bridgeMocks.resourceCb = cb;
+ return () => {
+ bridgeMocks.resourceCb = null;
+ };
+ },
+ ),
+ consumePendingKillCause: (tabId: string) => bridgeMocks.consumePendingKillCause(tabId),
+ };
+});
function makeMockWebview(initialUrl: string): MockWebview {
const listeners = new Map<string, Set<(event: Record<string, unknown>) => void>>();
@@ -68,8 +96,14 @@ function makeMockWebview(initialUrl: string): MockWebview {
};
}
-function HookProbe({ onResult }: { onResult: (result: UseBrowserWebviewResult) => void }) {
- const result = useBrowserWebview('tab-a', 'session-a');
+function HookProbe({
+ onResult,
+ visible,
+}: {
+ onResult: (result: UseBrowserWebviewResult) => void;
+ visible?: boolean;
+}) {
+ const result = useBrowserWebview('tab-a', 'session-a', visible);
onResult(result);
return null;
}
@@ -82,6 +116,8 @@ describe('useBrowserWebview', () => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
+ poolMocks.releaseListeners.clear();
+ bridgeMocks.resourceCb = null;
});
it('restores the real webview URL when an optimistic navigation is aborted', () => {
@@ -156,4 +192,94 @@ describe('useBrowserWebview', () => {
act(() => current().navigate('https://example.com/recovered'));
expect(mockWebview.loadURL).toHaveBeenCalledTimes(BROWSER_NAVIGATION_FUSE_LIMIT + 1);
});
+
+ it('re-acquires a fresh pool entry when an evicted tab becomes visible again', async () => {
+ const { browserWebviewPool } = await import('../../lib/browserWebviewPool');
+ const acquire = vi.mocked(browserWebviewPool.acquire);
+ let result: UseBrowserWebviewResult | null = null;
+ const view = render(
+ createElement(HookProbe, { visible: false, onResult: (next) => { result = next; } }),
+ );
+ expect(acquire).toHaveBeenCalledTimes(1);
+ const firstWrapper = result!.wrapper;
+
+ // 后台淘汰(资源看门狗 / LRU):entry 被 release,不可见期间不得重建。
+ act(() => poolMocks.fireRelease('tab-a'));
+ expect(acquire).toHaveBeenCalledTimes(1);
+
+ // 重新可见 → 重新 acquire,拿到新一代 entry,观测 state 复位。
+ mockWebview = makeMockWebview('');
+ view.rerender(
+ createElement(HookProbe, { visible: true, onResult: (next) => { result = next; } }),
+ );
+ expect(acquire).toHaveBeenCalledTimes(2);
+ expect(result!.wrapper).not.toBe(firstWrapper);
+ expect(result!.url).toBe('');
+ expect(result!.crash).toBeNull();
+ });
+
+ it('does not re-acquire when a foreign tab is released', async () => {
+ const { browserWebviewPool } = await import('../../lib/browserWebviewPool');
+ const acquire = vi.mocked(browserWebviewPool.acquire);
+ render(createElement(HookProbe, { visible: true, onResult: () => undefined }));
+ expect(acquire).toHaveBeenCalledTimes(1);
+ act(() => poolMocks.fireRelease('tab-other'));
+ expect(acquire).toHaveBeenCalledTimes(1);
+ });
+
+ it('marks a watchdog kill as resource-memory when the notice arrived first', () => {
+ let result: UseBrowserWebviewResult | null = null;
+ render(createElement(HookProbe, { onResult: (next) => { result = next; } }));
+
+ bridgeMocks.consumePendingKillCause.mockReturnValueOnce('memory');
+ act(() => {
+ mockWebview.dispatch('render-process-gone', { details: { reason: 'killed' } });
+ });
+ expect(result!.crash).toEqual({ reason: 'killed', cause: 'resource-memory' });
+ });
+
+ it('upgrades the crash when gone + late notice land in the same React batch', () => {
+ let result: UseBrowserWebviewResult | null = null;
+ render(createElement(HookProbe, { onResult: (next) => { result = next; } }));
+
+ // 两个事件在同一次 act(同一批,React 尚未 commit)内先后到达 ——
+ // 订阅回调必须能看到 crash 已发生(靠同步写 ref,不能等渲染期镜像)。
+ act(() => {
+ mockWebview.dispatch('render-process-gone', { details: { reason: 'killed' } });
+ bridgeMocks.resourceCb?.({ tabId: 'tab-a', kind: 'kill-notice', cause: 'memory' });
+ });
+ expect(result!.crash).toEqual({ reason: 'killed', cause: 'resource-memory' });
+ });
+
+ it('upgrades an existing crash on a late kill-notice and consumes the pending cause', () => {
+ let result: UseBrowserWebviewResult | null = null;
+ render(createElement(HookProbe, { onResult: (next) => { result = next; } }));
+
+ // crash 事件先到:此时还没有 pending cause,banner 是笼统的 killed。
+ act(() => {
+ mockWebview.dispatch('render-process-gone', { details: { reason: 'killed' } });
+ });
+ expect(result!.crash).toEqual({ reason: 'killed' });
+
+ // notice 晚到:升级 banner,并消费 pending cause(否则会错标下一次崩溃)。
+ const callsBefore = bridgeMocks.consumePendingKillCause.mock.calls.length;
+ act(() => {
+ bridgeMocks.resourceCb?.({ tabId: 'tab-a', kind: 'kill-notice', cause: 'memory' });
+ });
+ expect(result!.crash).toEqual({ reason: 'killed', cause: 'resource-memory' });
+ expect(bridgeMocks.consumePendingKillCause.mock.calls.length).toBe(callsBefore + 1);
+ });
+
+ it('shows and dismisses the cpu resource alert', () => {
+ let result: UseBrowserWebviewResult | null = null;
+ render(createElement(HookProbe, { onResult: (next) => { result = next; } }));
+
+ act(() => {
+ bridgeMocks.resourceCb?.({ tabId: 'tab-a', kind: 'cpu-alert', cpuPercent: 95 });
+ });
+ expect(result!.resourceAlert).toEqual({ cpuPercent: 95 });
+
+ act(() => result!.dismissResourceAlert());
+ expect(result!.resourceAlert).toBeNull();
+ });
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
index 51b6053505..62511d257c 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts
@@ -30,7 +30,11 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import type { WebviewTag } from 'electron';
import { browserWebviewPool } from '../lib/browserWebviewPool';
-import { reportRsbBrowserTab } from '../lib/rsbBrowserBridge';
+import {
+ consumePendingKillCause,
+ reportRsbBrowserTab,
+ subscribeTabResourceEvent,
+} from '../lib/rsbBrowserBridge';
/** 2 秒内最多允许 12 次 renderer 主动导航;网页自身导航不计入。 */
export const BROWSER_NAVIGATION_FUSE_LIMIT = 12;
@@ -68,8 +72,12 @@ export interface UseBrowserWebviewResult {
isAudible: boolean;
/** guest renderer 进程已崩溃 / 卡死(`render-process-gone` / `unresponsive`),
* BrowserTabBody 据此渲染 crash banner。null = 正常,非 null 是崩溃原因码。
- * reload 后清回 null(由 did-start-loading 触发)。 */
- crash: { reason: string } | null;
+ * `cause === 'resource-memory'` 表示是资源看门狗因内存超限主动终止的,banner
+ * 显示资源文案而不是笼统的"页面崩溃"。reload 后清回 null(did-start-loading)。 */
+ crash: { reason: string; cause?: 'resource-memory' } | null;
+ /** 资源看门狗 cpu-alert:前台页面持续高 CPU。BrowserTabBody 显示非阻断提示条
+ * (带「强制终止」按钮),null = 无告警。导航 / reload / 用户关闭时清除。 */
+ resourceAlert: { cpuPercent: number } | null;
/** 加载新 URL(URL bar 输入或外部跳转入口)。 */
navigate: (url: string) => void;
@@ -81,9 +89,22 @@ export interface UseBrowserWebviewResult {
goForward: () => void;
/** 停止当前加载(loading 时给 abort 按钮用)。 */
stop: () => void;
+ /** 关闭资源提示条(用户点「忽略」)。 */
+ dismissResourceAlert: () => void;
}
-export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowserWebviewResult {
+/**
+ * @param visible 本 tab 当前是否真的展示给用户(active && shellVisible)。
+ * 用于"淘汰后重建":资源看门狗 / LRU 淘汰会销毁后台 tab 的 pool entry,而
+ * Shell 常驻挂载所有 TabBody(不卸载),acquire effect 不会自然重跑 —— 这里
+ * 监听 pool release,等 tab 重新可见时 bump epoch 重新 acquire,否则用户切回
+ * 被淘汰的 tab 会看到空壳。不可见期间保持懒惰,不为看不见的 tab 重建 webview。
+ */
+export function useBrowserWebview(
+ tabId: string,
+ sessionId?: string,
+ visible?: boolean,
+): UseBrowserWebviewResult {
// pool entry 引用 + 反应式 state。entry 本身在 pool 模块管;hook 只观察。
const [wrapper, setWrapper] = useState<HTMLDivElement | null>(null);
const [url, setUrl] = useState('');
@@ -93,13 +114,47 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
const [canGoBack, setCanGoBack] = useState(false);
const [canGoForward, setCanGoForward] = useState(false);
const [isAudible, setIsAudible] = useState(false);
- const [crash, setCrash] = useState<{ reason: string } | null>(null);
+ const [crash, setCrash] = useState<{ reason: string; cause?: 'resource-memory' } | null>(
+ null,
+ );
+ const [resourceAlert, setResourceAlert] = useState<{ cpuPercent: number } | null>(null);
// webview ref —— actions 用,避免 stale closure。
const webviewRef = useRef<WebviewTag | null>(null);
const urlRef = useRef('');
const suppressStaleUrlRef = useRef<{ targetUrl: string; staleUrl: string } | null>(null);
const navigationAttemptsRef = useRef<number[]>([]);
const navigationFuseTrippedRef = useRef(false);
+ // crash 的渲染期镜像 —— kill-notice 晚于 render-process-gone 到达时,订阅回调
+ // 需要读当前 crash 值来决定升级 / 挂起,useState 闭包会 stale,走 ref。
+ const crashRef = useRef(crash);
+ crashRef.current = crash;
+ // 淘汰后重建:entry 被 pool release 后置位;tab 重新可见时 bump epoch 让
+ // acquire effect 重跑(见函数头注释)。
+ const [entryEpoch, setEntryEpoch] = useState(0);
+ const releasedRef = useRef(false);
+ const visibleRef = useRef(visible === true);
+ visibleRef.current = visible === true;
+
+ useEffect(() => {
+ const unsub = browserWebviewPool.onRelease((releasedTabId) => {
+ if (releasedTabId !== tabId) return;
+ // 可见中被 release(理论上只有用户关 tab —— 此时本组件即将 unmount,
+ // bump 一次也无害);不可见的淘汰恢复推迟到重新可见。
+ if (visibleRef.current) {
+ setEntryEpoch((e) => e + 1);
+ } else {
+ releasedRef.current = true;
+ }
+ });
+ return unsub;
+ }, [tabId]);
+
+ useEffect(() => {
+ if (visible && releasedRef.current) {
+ releasedRef.current = false;
+ setEntryEpoch((e) => e + 1);
+ }
+ }, [visible]);
const setObservedUrl = useCallback((nextUrl: string) => {
const suppress = suppressStaleUrlRef.current;
if (suppress) {
@@ -118,6 +173,22 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
useEffect(() => {
const entry = browserWebviewPool.acquire(tabId);
+ if (webviewRef.current && webviewRef.current !== entry.webview) {
+ // 重新物化(淘汰后再激活):上一代 webview 的观测 state 全部失效。复位为
+ // 空值,让 BrowserTabBody 的"按 wrapper 代际"首次导航重新驱动加载,否则
+ // stale url 会让导航判定"已在目标页"而跳过。
+ urlRef.current = '';
+ suppressStaleUrlRef.current = null;
+ setUrl('');
+ setTitle('');
+ setFavicon('');
+ setIsLoading(false);
+ setCanGoBack(false);
+ setCanGoForward(false);
+ setIsAudible(false);
+ setCrash(null);
+ setResourceAlert(null);
+ }
webviewRef.current = entry.webview;
setWrapper(entry.wrapper);
@@ -149,6 +220,8 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
// 任何主动导航 / reload 都视为崩溃后的恢复 — 清掉 crash banner。
// navigation-loop 是主动熔断,必须等用户点 banner 的重新加载才解除。
setCrash((prev) => (prev?.reason === 'navigation-loop' ? prev : null));
+ // 换页 / reload 后旧页面的高 CPU 告警不再成立。
+ setResourceAlert(null);
};
const onStopLoading = () => {
setIsLoading(false);
@@ -214,10 +287,21 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
};
// render-process-gone:guest renderer 进程崩 / 杀掉。details.reason 给原因码
// (crashed / killed / oom / launch-failed 等)。UI 据此显示 crash banner。
+ // 资源看门狗强杀前会先发 kill-notice(cause 记在 bridge 模块),这里取走
+ // 并挂到 crash state 上,banner 显示"内存过高被终止"。
const onRenderProcessGone = (e: Electron.RenderProcessGoneEvent) => {
setIsLoading(false);
setIsAudible(false);
- setCrash({ reason: e.details.reason });
+ setResourceAlert(null);
+ const cause = consumePendingKillCause(tabId);
+ const next = {
+ reason: e.details.reason,
+ ...(cause === 'memory' ? { cause: 'resource-memory' as const } : {}),
+ };
+ // 同步写 ref:kill-notice 可能与本事件同一批到达(React 还没 commit),
+ // 订阅回调靠 crashRef 判断"crash 是否已发生",不能等渲染期镜像。
+ crashRef.current = next;
+ setCrash(next);
};
// unresponsive:guest renderer 卡死(主线程长时间不响应)。当成软崩处理 ——
// 也显示 crash banner,但 reason='unresponsive'(UI 可分支显示"卡死"vs"崩溃")。
@@ -242,6 +326,22 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
entry.webview.addEventListener('unresponsive', onUnresponsive);
entry.webview.addEventListener('responsive', onResponsive);
+ // 资源看门狗事件(bridge 转发):cpu-alert → 提示条;kill-notice → 若 crash
+ // 事件先到、notice 后到,把已有 crash state 升级成资源原因(反序兜底)。
+ // 升级路径必须同时消费掉 pending cause —— 否则残留的 'memory' 会错标该 tab
+ // 下一次无关崩溃(review P1)。notice 先到的正序路径 pending 保留,由随后的
+ // render-process-gone handler 消费。
+ const unsubResourceEvent = subscribeTabResourceEvent(tabId, (event) => {
+ if (event.kind === 'cpu-alert') {
+ setResourceAlert({ cpuPercent: event.cpuPercent });
+ } else if (event.kind === 'kill-notice' && crashRef.current) {
+ consumePendingKillCause(tabId);
+ const upgraded = { ...crashRef.current, cause: 'resource-memory' as const };
+ crashRef.current = upgraded;
+ setCrash(upgraded);
+ }
+ });
+
// 初次挂上来 —— 如果 webview 已经载过(切回旧 tab),把当前 URL 同步进 state。
try {
const currentUrl = entry.webview.getURL?.();
@@ -265,10 +365,11 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
entry.webview.removeEventListener('render-process-gone', onRenderProcessGone);
entry.webview.removeEventListener('unresponsive', onUnresponsive);
entry.webview.removeEventListener('responsive', onResponsive);
+ unsubResourceEvent();
// **不**释放 pool entry —— webview DOM 节点继续保活,切回该 tab 时可直接
// 复用。释放是 plugin 在用户主动关闭 tab 时显式调 pool.release(tabId)。
};
- }, [tabId, sessionId, setObservedUrl]);
+ }, [tabId, sessionId, setObservedUrl, entryEpoch]);
const navigate = useCallback((nextUrl: string) => {
const wv = webviewRef.current;
@@ -324,6 +425,7 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
const goBack = useCallback(() => webviewRef.current?.goBack(), []);
const goForward = useCallback(() => webviewRef.current?.goForward(), []);
const stop = useCallback(() => webviewRef.current?.stop(), []);
+ const dismissResourceAlert = useCallback(() => setResourceAlert(null), []);
return {
wrapper,
@@ -335,10 +437,12 @@ export function useBrowserWebview(tabId: string, sessionId?: string): UseBrowser
canGoForward,
isAudible,
crash,
+ resourceAlert,
navigate,
reload,
goBack,
goForward,
stop,
+ dismissResourceAlert,
};
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/rsbBrowserBridge.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/rsbBrowserBridge.test.ts
index 24aa825246..a8d1c0322e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/rsbBrowserBridge.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/rsbBrowserBridge.test.ts
@@ -19,10 +19,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { browserWebviewPool } from '../browserWebviewPool';
import {
_resetRsbBrowserBridgeForTests,
+ consumePendingKillCause,
+ forceKillBrowserTab,
initRsbBrowserBridge,
+ PENDING_KILL_CAUSE_TTL_MS,
releaseRsbBrowserTab,
reportRsbBrowserTab,
+ setForegroundBrowserTab,
snapshotRsbBrowserTabs,
+ subscribeTabResourceEvent,
} from '../rsbBrowserBridge';
interface FakeIpcApi {
@@ -33,10 +38,15 @@ interface FakeIpcApi {
onUnpin: ReturnType<typeof vi.fn>;
onTabOpRequest: ReturnType<typeof vi.fn>;
tabOpResult: ReturnType<typeof vi.fn>;
- // Captured callbacks the bridge registered via onPin / onUnpin / onTabOpRequest.
+ setForeground: ReturnType<typeof vi.fn>;
+ forceKill: ReturnType<typeof vi.fn>;
+ onResourceEvent: ReturnType<typeof vi.fn>;
+ // Captured callbacks the bridge registered via onPin / onUnpin / onTabOpRequest /
+ // onResourceEvent.
pinCb: ((p: { tabId: string }) => void) | null;
unpinCb: ((p: { tabId: string }) => void) | null;
tabOpCb: ((req: unknown) => void) | null;
+ resourceCb: ((event: unknown) => void) | null;
}
function installFakeIpc(): FakeIpcApi {
@@ -48,9 +58,13 @@ function installFakeIpc(): FakeIpcApi {
onUnpin: vi.fn(),
onTabOpRequest: vi.fn(),
tabOpResult: vi.fn(async () => ({ ok: true })),
+ setForeground: vi.fn(async () => ({ ok: true })),
+ forceKill: vi.fn(async () => ({ ok: true })),
+ onResourceEvent: vi.fn(),
pinCb: null,
unpinCb: null,
tabOpCb: null,
+ resourceCb: null,
};
api.onPin.mockImplementation((cb: (p: { tabId: string }) => void) => {
api.pinCb = cb;
@@ -70,6 +84,12 @@ function installFakeIpc(): FakeIpcApi {
api.tabOpCb = null;
};
});
+ api.onResourceEvent.mockImplementation((cb: (event: unknown) => void) => {
+ api.resourceCb = cb;
+ return () => {
+ api.resourceCb = null;
+ };
+ });
(window as unknown as { electronAPI?: { rsbBrowserBridge: FakeIpcApi } }).electronAPI = {
rsbBrowserBridge: api,
};
@@ -360,3 +380,88 @@ describe('rsbBrowserBridge — initialization & teardown', () => {
expect(browserWebviewPool.isPinnedForAutomation('t-from-main')).toBe(true);
});
});
+
+describe('rsbBrowserBridge — resource watchdog events', () => {
+ it('evict-request releases the pool entry (and syncs main via release)', () => {
+ const api = installFakeIpc();
+ initRsbBrowserBridge();
+
+ browserWebviewPool.acquire('tab-r');
+ api.resourceCb?.({ tabId: 'tab-r', kind: 'evict-request' });
+
+ expect(browserWebviewPool.inspectTabIds()).not.toContain('tab-r');
+ expect(api.release).toHaveBeenCalledWith({ tabId: 'tab-r' });
+ });
+
+ it('kill-notice records a pending cause consumable exactly once', () => {
+ const api = installFakeIpc();
+ initRsbBrowserBridge();
+
+ api.resourceCb?.({ tabId: 'tab-k', kind: 'kill-notice', cause: 'memory' });
+
+ expect(consumePendingKillCause('tab-k')).toBe('memory');
+ // 第二次取应为空 —— cause 只对紧随其后的那次 render-process-gone 生效。
+ expect(consumePendingKillCause('tab-k')).toBeNull();
+ });
+
+ it('expires a stale pending kill cause after the freshness window', () => {
+ const api = installFakeIpc();
+ initRsbBrowserBridge();
+ vi.useFakeTimers();
+ try {
+ api.resourceCb?.({ tabId: 'tab-k', kind: 'kill-notice', cause: 'memory' });
+ // kill 在 main 侧失败 / guest 已死时 crash 事件永远不来 —— 超窗后残留的
+ // cause 不能错标下一次无关崩溃。
+ vi.advanceTimersByTime(PENDING_KILL_CAUSE_TTL_MS + 1);
+ expect(consumePendingKillCause('tab-k')).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('fans kill-notice / cpu-alert out to per-tab subscribers only', () => {
+ const api = installFakeIpc();
+ initRsbBrowserBridge();
+
+ const onTabA = vi.fn();
+ const onTabB = vi.fn();
+ const unsubA = subscribeTabResourceEvent('tab-a', onTabA);
+ subscribeTabResourceEvent('tab-b', onTabB);
+
+ api.resourceCb?.({ tabId: 'tab-a', kind: 'cpu-alert', cpuPercent: 95 });
+ expect(onTabA).toHaveBeenCalledWith({ tabId: 'tab-a', kind: 'cpu-alert', cpuPercent: 95 });
+ expect(onTabB).not.toHaveBeenCalled();
+
+ unsubA();
+ api.resourceCb?.({ tabId: 'tab-a', kind: 'cpu-alert', cpuPercent: 96 });
+ expect(onTabA).toHaveBeenCalledTimes(1);
+ });
+
+ it('setForegroundBrowserTab tracks a single claimant — stale deactivation is ignored', () => {
+ const api = installFakeIpc();
+ initRsbBrowserBridge();
+
+ setForegroundBrowserTab('tab-a', true);
+ expect(api.setForeground).toHaveBeenLastCalledWith({ tabId: 'tab-a' });
+
+ // tab-b 接管前台后,tab-a 的 unmount(false)不能把 tab-b 的声明冲掉。
+ setForegroundBrowserTab('tab-b', true);
+ expect(api.setForeground).toHaveBeenLastCalledWith({ tabId: 'tab-b' });
+ api.setForeground.mockClear();
+ setForegroundBrowserTab('tab-a', false);
+ expect(api.setForeground).not.toHaveBeenCalled();
+
+ // 当前 claimant 自己退场才发 null。
+ setForegroundBrowserTab('tab-b', false);
+ expect(api.setForeground).toHaveBeenLastCalledWith({ tabId: null });
+ });
+
+ it('forceKillBrowserTab forwards to ipc and swallows failures', async () => {
+ const api = installFakeIpc();
+ await forceKillBrowserTab('tab-x');
+ expect(api.forceKill).toHaveBeenCalledWith({ tabId: 'tab-x' });
+
+ api.forceKill.mockRejectedValueOnce(new Error('boom'));
+ await expect(forceKillBrowserTab('tab-x')).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts
index 3a324dc5a1..94bb07cfa6 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts
@@ -20,6 +20,7 @@
import type {
RsbBrowserBridgePinPayload,
+ RsbBrowserBridgeResourceEvent,
RsbBrowserBridgeTabOpRequest,
RsbBrowserBridgeTabOpResult,
} from '../../../../shared/rsbBrowserBridge';
@@ -50,6 +51,12 @@ interface RsbBrowserBridgeIpcSubset {
onTabOpRequest(cb: (req: RsbBrowserBridgeTabOpRequest) => void): () => void;
/** renderer → main result of a tab-op-request, keyed by reqId. */
tabOpResult(result: RsbBrowserBridgeTabOpResult): Promise<unknown>;
+ /** 资源看门狗:上报本 renderer 当前展示的浏览器 tab(null = 无)。 */
+ setForeground(input: { tabId: string | null }): Promise<unknown>;
+ /** 用户主动强杀 guest 进程(webContentsId = registry 未命中时的兜底解析)。 */
+ forceKill(input: { tabId: string; webContentsId?: number }): Promise<unknown>;
+ /** main → renderer 资源看门狗事件。 */
+ onResourceEvent(cb: (event: RsbBrowserBridgeResourceEvent) => void): () => void;
}
function ipc(): RsbBrowserBridgeIpcSubset | undefined {
@@ -69,6 +76,95 @@ let teardown: (() => void) | null = null;
*/
const lastReportedWebContentsId = new Map<string, number>();
+/**
+ * 资源看门狗 kill-notice 的 pending 原因(tabId → cause + 记录时间)。main 先发
+ * notice 再 forcefullyCrashRenderer,但两条消息走不同 channel,到达顺序无硬保证:
+ * - notice 先到:useBrowserWebview 的 render-process-gone handler 用
+ * `consumePendingKillCause` 取走,banner 直接显示资源原因;
+ * - crash 事件先到:per-tab 订阅回调随后升级已有 crash state。
+ * 带新鲜度窗口:kill 在 main 侧失败 / guest 已死时 crash 事件永远不来,残留的
+ * cause 不能在很久之后错标一次无关崩溃 —— 超窗直接作废。
+ */
+const pendingKillCauses = new Map<string, { cause: 'memory'; at: number }>();
+
+/** pending kill cause 的有效窗口(ms)。notice → crash 事件正常在毫秒级到达,
+ * 10s 足够覆盖慢 IPC,又不至于跨到下一次无关崩溃。 */
+export const PENDING_KILL_CAUSE_TTL_MS = 10_000;
+
+/** per-tab 资源事件订阅(useBrowserWebview 挂/卸)。 */
+const resourceEventListeners = new Map<
+ string,
+ Set<(event: RsbBrowserBridgeResourceEvent) => void>
+>();
+
+/**
+ * 订阅某个 tab 的资源看门狗事件(kill-notice / cpu-alert;evict-request 在
+ * bridge 内部直接消化,不会到订阅者)。返回退订函数。
+ */
+export function subscribeTabResourceEvent(
+ tabId: string,
+ cb: (event: RsbBrowserBridgeResourceEvent) => void,
+): () => void {
+ let set = resourceEventListeners.get(tabId);
+ if (!set) {
+ set = new Set();
+ resourceEventListeners.set(tabId, set);
+ }
+ set.add(cb);
+ return () => {
+ const listeners = resourceEventListeners.get(tabId);
+ if (!listeners) return;
+ listeners.delete(cb);
+ if (listeners.size === 0) resourceEventListeners.delete(tabId);
+ };
+}
+
+/** 取走(并清除)该 tab 的 pending kill 原因;无或已超新鲜度窗口则 null。 */
+export function consumePendingKillCause(tabId: string): 'memory' | null {
+ const entry = pendingKillCauses.get(tabId) ?? null;
+ pendingKillCauses.delete(tabId);
+ if (!entry) return null;
+ return Date.now() - entry.at <= PENDING_KILL_CAUSE_TTL_MS ? entry.cause : null;
+}
+
+/**
+ * 上报"本 renderer 当前展示的浏览器 tab"给 main 的资源看门狗。
+ * BrowserTabBody 在 active 变化时调;模块内维护单一 claimant,避免两个 TabBody
+ * 的 mount / unmount 交错时后发的 null 把先发的前台声明冲掉。
+ */
+let currentForegroundTabId: string | null = null;
+
+export function setForegroundBrowserTab(tabId: string, active: boolean): void {
+ const api = ipc();
+ if (active) {
+ currentForegroundTabId = tabId;
+ if (api) void api.setForeground({ tabId }).catch(() => undefined);
+ } else if (currentForegroundTabId === tabId) {
+ currentForegroundTabId = null;
+ if (api) void api.setForeground({ tabId: null }).catch(() => undefined);
+ }
+}
+
+/** 用户主动强杀 guest 进程(unresponsive banner / cpu 提示条的「强制终止」)。
+ * 随包携带 webview 的现值 webContentsId:页面在首个 dom-ready 前锁死 renderer
+ * 时 tab 还没 report 进 main 的 registry,main 用它做兜底解析(归属校验不变)。 */
+export function forceKillBrowserTab(tabId: string): Promise<void> {
+ const api = ipc();
+ if (!api) return Promise.resolve();
+ let webContentsId: number | undefined;
+ try {
+ webContentsId = browserWebviewPool.peek(tabId)?.webview.getWebContentsId();
+ } catch {
+ // attach 尚未完成时 getWebContentsId 抛 —— 不带兜底 id,交给 main 判 NOT_FOUND。
+ }
+ return api
+ .forceKill(webContentsId === undefined ? { tabId } : { tabId, webContentsId })
+ .then(
+ () => undefined,
+ () => undefined,
+ );
+}
+
/**
* Bind the renderer ↔ main bridge. Returns a teardown function that's safe to
* call multiple times.
@@ -120,11 +216,39 @@ export function initRsbBrowserBridge(): () => void {
void handleTabOpRequest(req, api);
});
+ // 资源看门狗事件(main → renderer):
+ // - evict-request:后台 guest 资源超限,直接走 pool.release 淘汰(对用户
+ // 等价于 LRU 淘汰;release → onRelease → main registry 同步清理)。
+ // - kill-notice:main 即将强杀该 guest。记 pending cause + 转发给 per-tab
+ // 订阅者(useBrowserWebview),两条路径覆盖 notice / render-process-gone
+ // 两种到达顺序,banner 都能显示"内存过高被终止"。
+ // - cpu-alert:转发给 per-tab 订阅者显示非阻断提示条。
+ const unsubResource = api.onResourceEvent((event) => {
+ if (event.kind === 'evict-request') {
+ browserWebviewPool.release(event.tabId);
+ return;
+ }
+ if (event.kind === 'kill-notice') {
+ pendingKillCauses.set(event.tabId, { cause: event.cause, at: Date.now() });
+ }
+ const listeners = resourceEventListeners.get(event.tabId);
+ if (listeners) {
+ for (const cb of [...listeners]) {
+ try {
+ cb(event);
+ } catch {
+ // listener throw must not break event fan-out
+ }
+ }
+ }
+ });
+
teardown = () => {
unsubRelease();
unsubPin();
unsubUnpin();
unsubTabOp();
+ unsubResource();
};
// Initial snapshot — drop main-side rows that the renderer no longer
@@ -424,4 +548,7 @@ export function _resetRsbBrowserBridgeForTests(): void {
initialized = false;
teardown = null;
lastReportedWebContentsId.clear();
+ pendingKillCauses.clear();
+ resourceEventListeners.clear();
+ currentForegroundTabId = null;
}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
index ac62558b8b..91effe48e8 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx
@@ -28,7 +28,7 @@
*/
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
-import { AlertTriangle, RotateCw } from 'lucide-react';
+import { AlertTriangle, Gauge, RotateCw, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useAppShortcut } from '@/hooks/useAppShortcut';
@@ -38,6 +38,10 @@ import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import { browserWebviewPool } from '../../lib/browserWebviewPool';
+import {
+ forceKillBrowserTab,
+ setForegroundBrowserTab,
+} from '../../lib/rsbBrowserBridge';
import { closeTab } from '../../store';
import { useBrowserWebview } from '../../hooks/useBrowserWebview';
import type { TabKindHostContext } from '../../types';
@@ -55,6 +59,10 @@ interface BrowserTabBodyProps {
/** 顶层 active tab 才响应来自 main 的 webview-内 Cmd+L 信号 + 后续 mute /
* 暂停媒体等行为。Shell 注入。 */
active?: boolean;
+ /** 整个右侧栏是否展开可见。Shell 注入;真实可见性 = active && shellVisible ——
+ * 侧栏收起时 active tab 依旧 mount 且 active=true,资源看门狗的前台判定
+ * 必须用组合值,否则收起的 tab 永远享受前台豁免(review P1)。 */
+ shellVisible?: boolean;
}
function normalizeNavigationUrl(url: string): string {
@@ -69,19 +77,22 @@ function isSameNavigationUrl(a: string, b: string): boolean {
return normalizeNavigationUrl(a) === normalizeNavigationUrl(b);
}
-export function BrowserTabBody({ state, ctx, active }: BrowserTabBodyProps) {
+export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabBodyProps) {
const { t } = useTranslation();
// tabId 从 ctx 拿(Shell 注入,每个 tab 实例稳定),用作 BrowserWebviewPool 的
// entry key — pool 据此把同一个 webview DOM 节点跟 tab 绑定一辈子。
// sessionId 跟 tabId 一起喂给 hook,用于 dom-ready 后给 main 端 TabRegistry
// 上报 (sessionId, tabId, webContentsId) 三元组(Phase 2 browser bridge)。
const { tabId, sessionId } = ctx;
+ // 真实可见性:顶层 active tab 且整个侧栏展开。shellVisible 缺省(旧宿主 /
+ // 测试)按可见处理,与 active 的既有缺省语义一致。
+ const tabVisible = active === true && shellVisible !== false;
// BrowserChrome 的 imperative ref —— Cmd/Ctrl+L 快捷键调它的 focusUrlBar()。
const chromeRef = useRef<BrowserChromeHandle>(null);
const rootRef = useRef<HTMLDivElement>(null);
const slotRef = useRef<HTMLDivElement>(null);
- const browser = useBrowserWebview(tabId, sessionId);
- const initialNavigationTabRef = useRef<string | null>(null);
+ const browser = useBrowserWebview(tabId, sessionId, tabVisible);
+ const lastNavigatedWrapperRef = useRef<HTMLDivElement | null>(null);
const stateUrlRef = useRef(state.url);
const browserUrlRef = useRef(browser.url);
const suppressStaleUrlRef = useRef<{ targetUrl: string; staleUrl: string } | null>(null);
@@ -157,16 +168,21 @@ export function BrowserTabBody({ state, ctx, active }: BrowserTabBodyProps) {
// 的观测结果,绝不能再反向驱动 loadURL:跨 origin 重定向时 React state 可能
// 落后一帧,双向 reconcile 会把 authorize / callback 互相覆盖成死循环。
// 用户地址栏与 agent 导航都有各自明确的命令入口,不依赖 state 反向触发。
+ //
+ // 按 wrapper **代际**(而不是 tabId)判定"首次":资源看门狗 / LRU 淘汰销毁
+ // entry 后,重新可见时 hook 会 acquire 出一个全新 wrapper —— 新代际的 webview
+ // 是空的,必须重新用持久化 URL 驱动一次加载(review P1:淘汰后空壳)。
useEffect(() => {
- if (initialNavigationTabRef.current === tabId) return;
- initialNavigationTabRef.current = tabId;
+ const wrapper = browser.wrapper;
+ if (!wrapper || lastNavigatedWrapperRef.current === wrapper) return;
+ lastNavigatedWrapperRef.current = wrapper;
const nextUrl = stateUrlRef.current || 'about:blank';
const currentUrl = browserUrlRef.current;
if (currentUrl && isSameNavigationUrl(currentUrl, nextUrl)) return;
// about:blank 默认状态下也要 navigate,确保 webview 真的处于 about:blank,
// 不会停留在 pool 创建时未 setAttribute('src') 的"未初始化"状态。
navigateRef.current(nextUrl);
- }, [tabId]);
+ }, [tabId, browser.wrapper]);
const reloadRef = useRef(browser.reload);
const goBackRef = useRef(browser.goBack);
@@ -261,6 +277,17 @@ export function BrowserTabBody({ state, ctx, active }: BrowserTabBodyProps) {
{ enabled: active },
);
+ // 前台上报:资源看门狗据此区分前台 / 后台 guest(前台只在内存超硬阈值时才
+ // 强杀,后台可激进淘汰)。用 tabVisible(active && shellVisible)而不是裸
+ // active:侧栏收起时 active tab 依旧 mount,不算前台。可见性翻转 / tab 切换 /
+ // 组件卸载都要同步。
+ useEffect(() => {
+ setForegroundBrowserTab(tabId, tabVisible);
+ return () => {
+ setForegroundBrowserTab(tabId, false);
+ };
+ }, [tabVisible, tabId]);
+
// webview guest 内 Cmd/Ctrl+L:main 推送过来,只有 active tab 响应。
useEffect(() => {
if (!active) return;
@@ -411,7 +438,48 @@ export function BrowserTabBody({ state, ctx, active }: BrowserTabBodyProps) {
data-browser-tab-slot={tabId}
>
{browser.crash && (
- <BrowserCrashBanner reason={browser.crash.reason} onRecover={handleRecover} />
+ <BrowserCrashBanner
+ reason={browser.crash.reason}
+ cause={browser.crash.cause}
+ onRecover={handleRecover}
+ onForceKill={
+ browser.crash.reason === 'unresponsive'
+ ? () => void forceKillBrowserTab(tabId)
+ : undefined
+ }
+ />
+ )}
+ {/* 资源看门狗 cpu-alert 提示条:非阻断,固定在 slot 顶部居中。用户可
+ 「强制终止」失控页面,或「忽略」继续(可能是正经的重页面)。 */}
+ {!browser.crash && browser.resourceAlert && (
+ <div
+ className={cn(
+ 'absolute left-1/2 top-2 z-10 flex -translate-x-1/2 items-center gap-2',
+ 'rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)]',
+ 'py-1 pl-3 pr-1 text-[11px] text-[var(--text-secondary)] shadow-sm',
+ )}
+ >
+ <Gauge size={12} strokeWidth={2} className="shrink-0 text-[var(--warning-fg)]" />
+ <span>{t('rightSidebar.browser.resourceAlert.cpuHint')}</span>
+ <button
+ type="button"
+ onClick={() => {
+ browser.dismissResourceAlert();
+ void forceKillBrowserTab(tabId);
+ }}
+ className="rounded-full px-2 py-0.5 text-[11px] font-medium text-[var(--error-fg)] hover:bg-[var(--surface-hover)]"
+ >
+ {t('rightSidebar.browser.resourceAlert.terminate')}
+ </button>
+ <button
+ type="button"
+ aria-label={t('rightSidebar.browser.resourceAlert.dismiss')}
+ onClick={browser.dismissResourceAlert}
+ className="flex size-5 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"
+ >
+ <X size={12} strokeWidth={2} />
+ </button>
+ </div>
)}
{/* 评论模式提示条:点选中显示操作说明,固定在 slot 顶部居中,不挡 chrome。 */}
{comment.mode === 'selecting' && (
@@ -447,25 +515,38 @@ export function BrowserTabBody({ state, ctx, active }: BrowserTabBodyProps) {
* 崩溃 banner —— absolute 覆盖整个 webview slot,半透明黑底 + 中心一个卡片。
* Codex 也对崩溃做 UI 反馈(`render-process-gone` 事件链),Chrome 在 tab 内显示
* "Aw, Snap!" 页。我们做精简版:图标 + 原因 + 重载按钮。
+ *
+ * `cause === 'resource-memory'`:资源看门狗因内存超限主动终止(不是页面自己崩),
+ * 换专属文案让用户明白"是保护机制在工作"。`onForceKill` 只在 unresponsive 时传:
+ * 卡死的 guest 进程还在烧 CPU,「强制终止」给用户一个立即止损的出口(终止后
+ * 走 render-process-gone → 本 banner 切到 crashed 文案 → 重新加载恢复)。
*/
function BrowserCrashBanner({
reason,
+ cause,
onRecover,
+ onForceKill,
}: {
reason: string;
+ cause?: 'resource-memory';
onRecover: () => void;
+ onForceKill?: () => void;
}) {
const { t } = useTranslation();
- // 区分导航熔断、unresponsive 与进程崩溃。沿用同一个克制的恢复 banner,
- // 不新增布局或视觉分支。
+ // 区分资源终止、导航熔断、unresponsive 与进程崩溃。沿用同一个克制的恢复
+ // banner,不新增布局或视觉分支。
const titleKey =
- reason === 'navigation-loop'
+ cause === 'resource-memory'
+ ? 'rightSidebar.browser.crash.resourceKilledTitle'
+ : reason === 'navigation-loop'
? 'rightSidebar.browser.crash.navigationLoopTitle'
: reason === 'unresponsive'
? 'rightSidebar.browser.crash.unresponsiveTitle'
: 'rightSidebar.browser.crash.crashedTitle';
const descKey =
- reason === 'navigation-loop'
+ cause === 'resource-memory'
+ ? 'rightSidebar.browser.crash.resourceKilledDesc'
+ : reason === 'navigation-loop'
? 'rightSidebar.browser.crash.navigationLoopDesc'
: reason === 'unresponsive'
? 'rightSidebar.browser.crash.unresponsiveDesc'
@@ -476,14 +557,25 @@ function BrowserCrashBanner({
<AlertTriangle size={28} strokeWidth={1.5} className="text-[var(--error-fg)]" />
<div className="text-[13px] font-medium text-[var(--text-primary)]">{t(titleKey)}</div>
<div className="text-[12px] text-[var(--text-secondary)]">{t(descKey)}</div>
- <button
- type="button"
- onClick={onRecover}
- className="mt-1 flex h-7 items-center gap-1.5 rounded-md bg-[var(--accent-cta-bg)] px-3 text-[12px] font-medium text-[var(--accent-pure-cta-fg)] hover:bg-[var(--accent-hover)]"
- >
- <RotateCw size={12} strokeWidth={2.5} />
- {t('rightSidebar.browser.crash.reload')}
- </button>
+ <div className="mt-1 flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onRecover}
+ className="flex h-7 items-center gap-1.5 rounded-md bg-[var(--accent-cta-bg)] px-3 text-[12px] font-medium text-[var(--accent-pure-cta-fg)] hover:bg-[var(--accent-hover)]"
+ >
+ <RotateCw size={12} strokeWidth={2.5} />
+ {t('rightSidebar.browser.crash.reload')}
+ </button>
+ {onForceKill && (
+ <button
+ type="button"
+ onClick={onForceKill}
+ className="flex h-7 items-center rounded-md border border-[var(--border-default)] px-3 text-[12px] font-medium text-[var(--error-fg)] hover:bg-[var(--surface-hover)]"
+ >
+ {t('rightSidebar.browser.crash.forceKill')}
+ </button>
+ )}
+ </div>
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
index 194e5c8072..f9be60cf4b 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/__tests__/BrowserTabBody.navigation.test.ts
@@ -30,11 +30,16 @@ vi.mock('../../../lib/browserWebviewPool', () => ({
},
}));
+// 稳定的 wrapper 元素:BrowserTabBody 的首次导航按 wrapper 代际判定(淘汰后
+// 重建需要重新导航),测试里跨 rerender 复用同一个元素,行为与"每 tab 一次"
+// 的旧语义一致。
+const sharedWrapper = document.createElement('div');
+
function makeBrowserState(
patch: Partial<UseBrowserWebviewResult> = {},
): UseBrowserWebviewResult {
return {
- wrapper: null,
+ wrapper: sharedWrapper,
url: 'https://www.taptap.cn/',
title: '',
favicon: '',
@@ -43,11 +48,13 @@ function makeBrowserState(
canGoForward: false,
isAudible: false,
crash: null,
+ resourceAlert: null,
navigate: browserNavigate,
reload: vi.fn(),
goBack: vi.fn(),
goForward: vi.fn(),
stop: vi.fn(),
+ dismissResourceAlert: vi.fn(),
...patch,
};
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index daa808064e..7def7936e3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3239,7 +3239,15 @@
"unresponsiveDesc": "The page has not responded for a while. Reload or wait a moment.",
"navigationLoopTitle": "Repeated Navigation Stopped",
"navigationLoopDesc": "The page navigated repeatedly in a short time. Reload the page to try again.",
+ "resourceKilledTitle": "Page used too much memory",
+ "resourceKilledDesc": "This page was using too much memory and was stopped to keep the app running. You can reload it.",
+ "forceKill": "Force stop",
"reload": "Reload"
+ },
+ "resourceAlert": {
+ "cpuHint": "This page is using significant system resources",
+ "terminate": "Stop page",
+ "dismiss": "Dismiss"
}
},
"terminal": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 060d22759c..7f70ce0eb3 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3238,7 +3238,15 @@
"unresponsiveDesc": "ページがしばらく応答していません。再読み込みするか、少し待ってください。",
"navigationLoopTitle": "繰り返しナビゲーションを停止しました",
"navigationLoopDesc": "短時間にページ遷移が繰り返されたため、ナビゲーションを停止しました。ページを再読み込みして再試行してください。",
+ "resourceKilledTitle": "ページのメモリ使用量が多すぎます",
+ "resourceKilledDesc": "このページはメモリを大量に使用していたため、アプリを保護するために終了しました。再読み込みできます。",
+ "forceKill": "強制終了",
"reload": "再読み込み"
+ },
+ "resourceAlert": {
+ "cpuHint": "このページはシステムリソースを大量に使用しています",
+ "terminate": "ページを終了",
+ "dismiss": "無視"
}
},
"terminal": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b9cf8235ef..f90bc3479d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3238,7 +3238,15 @@
"unresponsiveDesc": "페이지가 한동안 응답하지 않습니다. 다시 로드하거나 잠시 기다리세요.",
"navigationLoopTitle": "반복 탐색을 중지했습니다",
"navigationLoopDesc": "페이지가 짧은 시간에 반복해서 이동하여 탐색을 중지했습니다. 페이지를 다시 로드한 후 재시도하세요.",
+ "resourceKilledTitle": "페이지의 메모리 사용량이 너무 많습니다",
+ "resourceKilledDesc": "이 페이지가 메모리를 과도하게 사용하여 앱 보호를 위해 종료되었습니다. 다시 로드할 수 있습니다.",
+ "forceKill": "강제 종료",
"reload": "다시 로드"
+ },
+ "resourceAlert": {
+ "cpuHint": "이 페이지가 시스템 리소스를 많이 사용하고 있습니다",
+ "terminate": "페이지 종료",
+ "dismiss": "무시"
}
},
"terminal": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index eefa9a3d16..5c9e9df5da 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3238,7 +3238,15 @@
"unresponsiveDesc": "页面长时间未响应,可重新加载或稍候等待",
"navigationLoopTitle": "已停止重复跳转",
"navigationLoopDesc": "页面在短时间内反复跳转,已暂停导航。请重新加载页面后重试",
+ "resourceKilledTitle": "页面占用内存过高",
+ "resourceKilledDesc": "该页面占用内存过高,已被终止以保护应用运行。可重新加载",
+ "forceKill": "强制终止",
"reload": "重新加载"
+ },
+ "resourceAlert": {
+ "cpuHint": "此页面占用大量系统资源",
+ "terminate": "终止页面",
+ "dismiss": "忽略"
}
},
"terminal": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 291f1366c5..2b5165eb9c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3369,6 +3369,17 @@ interface ElectronAPI {
) => Promise<{ ok: true } | { ok: false; error: string }>;
/** 推送 renderer 当前 focused 的 RSB sessionId(Phase 5)。 */
setActiveSession: (input: { sessionId: string | null }) => Promise<{ ok: true }>;
+ /** 资源看门狗:上报本 renderer 当前展示的浏览器 tab(null = 无)。 */
+ setForeground: (input: { tabId: string | null }) => Promise<{ ok: true }>;
+ /** 用户主动强杀 guest 进程(unresponsive banner / cpu 提示条按钮);
+ * webContentsId 供 registry 未命中(attach 后、首个 dom-ready 前)兜底。 */
+ forceKill: (input: { tabId: string; webContentsId?: number }) => Promise<{ ok: true }>;
+ /** main → renderer:资源看门狗事件(evict-request / kill-notice / cpu-alert)。 */
+ onResourceEvent: (
+ cb: (
+ event: import('../shared/rsbBrowserBridge').RsbBrowserBridgeResourceEvent,
+ ) => void,
+ ) => () => void;
};
/**
diff --git a/apps/desktop/src/shared/rsbBrowserBridge.ts b/apps/desktop/src/shared/rsbBrowserBridge.ts
index e01f3971ae..5989bee7d4 100644
--- a/apps/desktop/src/shared/rsbBrowserBridge.ts
+++ b/apps/desktop/src/shared/rsbBrowserBridge.ts
@@ -60,6 +60,35 @@ export const RSB_BROWSER_BRIDGE_PIN_CHANNEL = 'rsb-browser-bridge:pin';
/** Channel name for main → renderer "release the pin on this tab". */
export const RSB_BROWSER_BRIDGE_UNPIN_CHANNEL = 'rsb-browser-bridge:unpin';
+/**
+ * Channel name for renderer → main "the user is currently looking at THIS
+ * browser tab (or none)". 资源看门狗据此区分前台 / 后台 guest:前台页面只在
+ * 内存超硬阈值时才强杀,后台页面可以被更激进地淘汰(对用户等价于 LRU 淘汰)。
+ * 语义是 per-renderer 的"全量状态"(最新一次上报覆盖之前的),不是增量事件。
+ */
+export const RSB_BROWSER_BRIDGE_SET_FOREGROUND_CHANNEL = 'rsb-browser-bridge:set-foreground';
+
+/**
+ * Channel name for renderer → main "force-kill the guest process of tab Y"。
+ * 用户在 crash banner(unresponsive)或资源提示条上点「强制终止」时调。kill 必须
+ * 在 main:`forcefullyCrashRenderer()` 是 webContents 的特权方法。归属校验与
+ * 截图 channel 相同(tabId → registry → hostWebContents === sender)。
+ */
+export const RSB_BROWSER_BRIDGE_FORCE_KILL_CHANNEL = 'rsb-browser-bridge:force-kill';
+
+/**
+ * Channel name for main → renderer resource watchdog events(见
+ * `main/rsb-browser-bridge/resource-watchdog.ts` 的阶梯策略):
+ * - `evict-request`:后台 guest 资源超限,请 renderer 走 pool.release 淘汰
+ * (tab 保留,下次激活重建 webview 重新加载)。
+ * - `kill-notice`:main 即将 forcefullyCrashRenderer 强杀该前台 guest;renderer
+ * 记下原因,让随后的 render-process-gone crash banner 显示"内存过高被终止"
+ * 而不是笼统的"页面崩溃"。
+ * - `cpu-alert`:前台 guest 持续高 CPU;renderer 显示非阻断提示条 + 终止按钮,
+ * 不自动杀(可能是用户在跑正经的重页面)。
+ */
+export const RSB_BROWSER_BRIDGE_RESOURCE_EVENT_CHANNEL = 'rsb-browser-bridge:resource-event';
+
/**
* Channel name for main → renderer "execute this tab operation against the
* store" (RsbWebviewBackend dispatches `open` / `focus` / `close` actions).
@@ -169,3 +198,31 @@ export interface RsbBrowserBridgeSnapshotPayload {
export interface RsbBrowserBridgePinPayload {
tabId: string;
}
+
+/**
+ * Payload renderer sends on `set-foreground`。`tabId = null` 表示该 renderer
+ * 当前没有可见的浏览器 tab(RSB 收起 / 切到非浏览器 tab)。
+ */
+export interface RsbBrowserBridgeSetForegroundPayload {
+ tabId: string | null;
+}
+
+/**
+ * Payload renderer sends on `force-kill`。
+ *
+ * `webContentsId`(可选)= renderer 侧 `webview.getWebContentsId()` 的现值,
+ * 供 registry 未命中时兜底:页面在首个 dom-ready 前就把 renderer 锁死(内联
+ * 死循环)时,tab 还没 report 进 TabRegistry,但 guest 已 attach、unresponsive
+ * banner 已出现 —— 没有兜底的话「强制终止」按钮会静默失效。main 端对该 id 做
+ * 与 report 相同的归属校验(必须是 webview guest 且宿主为 sender)后才执行。
+ */
+export interface RsbBrowserBridgeForceKillPayload {
+ tabId: string;
+ webContentsId?: number;
+}
+
+/** Resource watchdog event main pushes on `resource-event`(kind 语义见 channel 注释)。 */
+export type RsbBrowserBridgeResourceEvent =
+ | { tabId: string; kind: 'evict-request' }
+ | { tabId: string; kind: 'kill-notice'; cause: 'memory' }
+ | { tabId: string; kind: 'cpu-alert'; cpuPercent: number };