Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): prevent sidebar favicon update loops (#2166)
wang2fcacec8e10e5
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.tsindex a2dfbd3276..7af12bcf7a 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/rightSidebarTabs.test.ts@@ -245,6 +245,26 @@ describe('rightSidebarTabs IPC', () => {).rejects.toThrow(/RIGHT_SIDEBAR_STATE_TOO_LARGE/);});+ it.each([+ ['cyclic state', () => {+ const state: Record<string, unknown> = {};+ state.self = state;+ return state;+ }],+ ['BigInt state', () => ({ value: BigInt(1) })],+ ['top-level function state', () => () => undefined],+ ])('rejects non-JSON-serializable %s with INVALID_PARAMS', async (_name, makeState) => {+ await expect(+ invoke('local-db:right-sidebar-tabs:upsert', {+ id: 't1',+ sessionId: 's1',+ kind: 'web-browser',+ position: 0,+ state: makeState(),+ }),+ ).rejects.toThrow(/\[INVALID_PARAMS\] tab state must be JSON-serializable/);+ });+it('rejects invalid params (missing sessionId)', async () => {await expect(invoke('local-db:right-sidebar-tabs:upsert', {diff --git a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.tsindex 1478f5ad90..baa9ce1df6 100644--- a/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts+++ b/apps/desktop/src/main/localDb/ipc/rightSidebarTabs.ts@@ -26,6 +26,7 @@ import { and, asc, eq } from 'drizzle-orm';import { getDbClient } from '../client/current.js';import { rightSidebarTabs, sessions } from '../schema.js';+import { MAX_STATE_JSON_BYTES } from '../../../shared/rightSidebarTabState.js';import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';import { requireObject, requireString, throwIpcError } from '../../utils/ipcValidate.js';import { createLogger } from '../../logger.js';@@ -34,10 +35,6 @@ const log = createLogger('rightSidebarTabs');/** 单 session 最多 20 个 tab,超抛 RIGHT_SIDEBAR_TOO_MANY_TABS。 */const MAX_TABS_PER_SESSION = 20;-/** 单行 state JSON 序列化字节上限,超抛 RIGHT_SIDEBAR_STATE_TOO_LARGE。- 16KB 已远超浏览器 tab(url + title + favicon URL ~400B)/ 文件 tab(~500B)实际需要,- 够防 plugin 误塞 dataURL / 大对象。 */-const MAX_STATE_JSON_BYTES = 16 * 1024;const SINGLETON_TAB_KINDS = new Set(['subagents']);export interface TabRow {@@ -83,7 +80,16 @@ function requireInt(value: unknown, name: string): number {function serializeState(value: unknown): string {// undefined → 用默认 '{}';其它一律 stringify(包含 null,plugin 真要存 null 也能存)if (value === undefined) return '{}';- const json = JSON.stringify(value);+ let json: string | undefined;+ try {+ json = JSON.stringify(value);+ } catch {+ throwIpcError('INVALID_PARAMS', 'tab state must be JSON-serializable');+ }+ // JSON.stringify 顶层 function / symbol 时不抛错而返回 undefined,不能交给 DB。+ if (typeof json !== 'string') {+ throwIpcError('INVALID_PARAMS', 'tab state must be JSON-serializable');+ }const bytes = Buffer.byteLength(json, 'utf8');if (bytes > MAX_STATE_JSON_BYTES) {throwIpcError(diff --git a/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts b/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.tsindex f622a2ac2e..6249057a91 100644--- a/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts+++ b/apps/desktop/src/main/rsb-browser-bridge/__tests__/native-popup-surfaces.test.ts@@ -181,13 +181,17 @@ describe('main-owned RSB native popup surfaces', () => {expect(electronMocks.views[0]?.visible).toBe(true);});- it('publishes null when a favicon update has no usable URL', async () => {+ it('publishes an empty string when Chromium explicitly reports no favicon', async () => {const host = makeContents(1);const popup = makeContents(42);electronMocks.windows.set(host, makeWindow());const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;- await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });+ const claimed = await claim(+ { sender: host },+ { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' },+ );+ expect(claimed).toMatchObject({ alive: true, snapshot: { favicon: null } });popup.emit('page-favicon-updated', {}, ['', ' ']);@@ -196,7 +200,33 @@ describe('main-owned RSB native popup surfaces', () => {payload: {surfaceId,type: 'state',- snapshot: expect.objectContaining({ favicon: null }),+ snapshot: expect.objectContaining({ favicon: '' }),+ },+ });+ });++ it('skips non-persistable popup favicon candidates and publishes a safe fallback', async () => {+ const host = makeContents(1);+ const popup = makeContents(42);+ electronMocks.windows.set(host, makeWindow());+ const surfaceId = createRsbNativePopupSurface(host as never, popup as never)!;+ const claim = electronMocks.handlers.get(RSB_NATIVE_POPUP_CLAIM_CHANNEL)!;+ await claim({ sender: host }, { surfaceId, sessionId: 'session-a', tabId: 'tab-popup' });++ popup.emit('page-favicon-updated', {}, [+ 'blob:https://accounts.example.test/favicon',+ `data:image/png;base64,${'x'.repeat(3 * 1024)}`,+ 'https://accounts.example.test/favicon.ico',+ ]);++ expect(host.sent.at(-1)).toEqual({+ channel: 'rsb-native-popup:event',+ payload: {+ surfaceId,+ type: 'state',+ snapshot: expect.objectContaining({+ favicon: 'https://accounts.example.test/favicon.ico',+ }),},});});diff --git a/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts b/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.tsindex 2d0c806d93..733d588066 100644--- a/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts+++ b/apps/desktop/src/main/rsb-browser-bridge/native-popup-surfaces.ts@@ -8,6 +8,7 @@ import {type WebContents,} from 'electron';+import { selectPersistableFavicon } from '../../shared/faviconPersistence.js';import {RSB_NATIVE_POPUP_CLAIM_CHANNEL,RSB_NATIVE_POPUP_CLOSE_CHANNEL,@@ -166,7 +167,9 @@ function installSurfaceObservers(record: SurfaceRecord): void {wc.on('did-navigate-in-page', publish);wc.on('page-title-updated', publish);wc.on('page-favicon-updated', (_event, favicons) => {- record.favicon = favicons.find((candidate) => candidate.trim().length > 0) ?? null;+ // 与 renderer WebView 保持三态语义:null = 尚未观测到;'' = Chromium+ // 明确报告无图标;非空字符串 = 从全部候选中选出的可持久化 URL。+ record.favicon = selectPersistableFavicon(favicons);publish();});wc.on('audio-state-changed', publish);diff --git a/apps/desktop/src/main/utils/ipcValidate.ts b/apps/desktop/src/main/utils/ipcValidate.tsindex eea328505b..33b2ba0267 100644--- a/apps/desktop/src/main/utils/ipcValidate.ts+++ b/apps/desktop/src/main/utils/ipcValidate.ts@@ -1,4 +1,4 @@-import type { IpcErrorCode } from '../../shared/ipc-errors.js';+import { createIpcError, type IpcErrorCode } from '../../shared/ipc-errors.js';/*** IPC 参数运行时校验工具 — main 进程所有 IPC handler 共用。@@ -6,9 +6,7 @@ import type { IpcErrorCode } from '../../shared/ipc-errors.js';/** 抛出带 code 的 IPC 错误,renderer 侧可通过 err.code 做统一处理 */export function throwIpcError(code: IpcErrorCode, message: string): never {- const err = new Error(`[${code}] ${message}`);- (err as { code?: IpcErrorCode }).code = code;- throw err;+ throw createIpcError(code, message);}export function requireString(value: unknown, name: string): string {diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.tsindex a6b2cd23b0..8c702c056c 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/store.test.ts@@ -186,6 +186,64 @@ describe('RSB store', () => {expect((store.getBucket('ghost-s1').tabs[0].state as { title: string }).title).toBe('Example');});+ it('sanitizes non-persistable favicons when hydrating web-browser tabs', async () => {+ ipc.list.mockResolvedValueOnce({+ tabs: [+ {+ id: 't1',+ kind: 'web-browser',+ position: 0,+ state: { url: 'https://a.com', title: 'A', favicon: 'blob:https://a.com/favicon' },+ },+ {+ id: 't2',+ kind: 'web-browser',+ position: 1,+ state: { url: 'https://b.com', title: 'B', favicon: 'data:image/png;base64,eA==' },+ },+ { id: 't3', kind: 'file-browser', position: 2, state: { selectedFilePath: 'x.md' } },+ ],+ activeTabId: 't1',+ });+ await store.ensureHydrated('s1');+ const tabs = store.getBucket('s1').tabs;+ // blob: 不可持久化 → 清成"无图标"。+ expect((tabs[0].state as { favicon: string | null }).favicon).toBeNull();+ // 小 data: 保留。+ expect((tabs[1].state as { favicon: string | null }).favicon).toBe('data:image/png;base64,eA==');+ // 非 web-browser kind 原样透传。+ expect(tabs[2].state).toEqual({ selectedFilePath: 'x.md' });+ });++ it('lets title patches succeed after hydrating a poisoned web-browser tab', async () => {+ // 发布前已把超大 data: favicon 落库的存量 tab:hydrate 消毒后,后续 patch+ // 不再因 16KB 预检被拒(否则 title 变更也会把坏 favicon 重新并进预检)。+ ipc.list.mockResolvedValueOnce({+ tabs: [+ {+ id: 't1',+ kind: 'web-browser',+ position: 0,+ state: {+ url: 'https://a.com',+ title: 'A',+ favicon: `data:image/png;base64,${'x'.repeat(20 * 1024)}`,+ },+ },+ ],+ activeTabId: 't1',+ });+ await store.ensureHydrated('s1');+ ipc.upsert.mockClear();+ const tab = store.getBucket('s1').tabs[0];+ await store.patchTabState('s1', tab.id, (current) => ({+ ...(current as object),+ title: 'A2',+ }));+ expect((store.getBucket('s1').tabs[0].state as { title: string }).title).toBe('A2');+ expect(ipc.upsert).toHaveBeenCalledOnce();+ });+it('keeps the tab count limit for memory-only sessions', async () => {ipc.list.mockResolvedValueOnce({ tabs: [], activeTabId: null, persistable: false });await store.ensureHydrated('ghost-s1');@@ -246,6 +304,55 @@ describe('RSB store', () => {expect(store.getBucket('s1').activeTabId).toBe(prevActiveId);});+ it('rejects oversized persisted state before optimistic insertion', async () => {+ const before = store.getBucket('s1');+ const listener = vi.fn();+ const onOptimisticAdd = vi.fn();+ const unsubscribe = store.subscribe(listener);++ const rejection = store.addTab(+ 's1',+ 'web-browser',+ { favicon: `data:image/png;base64,${'x'.repeat(20 * 1024)}` },+ { onOptimisticAdd },+ );+ await expect(rejection).rejects.toMatchObject({+ code: 'RIGHT_SIDEBAR_STATE_TOO_LARGE',+ });+ await expect(rejection).rejects.toThrow(/tab state JSON too large/);++ expect(store.getBucket('s1')).toBe(before);+ expect(listener).not.toHaveBeenCalled();+ expect(onOptimisticAdd).not.toHaveBeenCalled();+ expect(ipc.upsert).not.toHaveBeenCalled();+ expect(ipc.setActive).not.toHaveBeenCalled();+ unsubscribe();+ });++ it.each([+ ['cyclic state', () => {+ const state: Record<string, unknown> = {};+ state.self = state;+ return state;+ }],+ ['BigInt state', () => ({ value: BigInt(1) })],+ ['top-level function state', () => () => undefined],+ ])('rejects non-JSON-serializable %s before optimistic insertion', async (_name, makeState) => {+ const before = store.getBucket('s1');+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);++ const rejection = store.addTab('s1', 'web-browser', makeState());+ await expect(rejection).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ await expect(rejection).rejects.toThrow(/tab state must be JSON-serializable/);++ expect(store.getBucket('s1')).toBe(before);+ expect(listener).not.toHaveBeenCalled();+ expect(ipc.upsert).not.toHaveBeenCalled();+ expect(ipc.setActive).not.toHaveBeenCalled();+ unsubscribe();+ });+it('falls back to memory-only when the first persist hits a missing session FK', async () => {ipc.upsert.mockRejectedValueOnce(new Error('SQLITE_CONSTRAINT_FOREIGNKEY: FOREIGN KEY constraint failed'));const tab = await store.addTab('ghost-race', 'web-browser', { url: 'https://example.com' });@@ -904,6 +1011,30 @@ describe('RSB store', () => {expect((bucket.tabs[0].state as { selectedFilePath: string | null }).selectedFilePath).toBeNull();});+ it('rejects oversized persisted patches without notifying or writing', async () => {+ const a = await store.addTab('s1', 'web-browser', { favicon: null });+ ipc.upsert.mockClear();+ const before = store.getBucket('s1');+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);++ const oversizedFavicon = `data:image/png;base64,${'x'.repeat(20 * 1024)}`;+ const rejection = store.patchTabState('s1', a.id, (current) => ({+ ...(current as object),+ favicon: oversizedFavicon,+ }));+ await expect(rejection).rejects.toMatchObject({+ code: 'RIGHT_SIDEBAR_STATE_TOO_LARGE',+ });+ await expect(rejection).rejects.toThrow(/tab state JSON too large/);++ expect(store.getBucket('s1')).toBe(before);+ expect(store.getBucket('s1').tabs[0].state).toEqual({ favicon: null });+ expect(listener).not.toHaveBeenCalled();+ expect(ipc.upsert).not.toHaveBeenCalled();+ unsubscribe();+ });+it('serializes DB writes and coalesces the latest pending state per tab', async () => {const a = await store.addTab('s1', 'web-browser', { url: 'https://example.com/0' });ipc.upsert.mockClear();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.tsindex 083a358dcf..c5e230d276 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@@ -387,6 +387,57 @@ describe('useBrowserWebview', () => {expect(result!.favicon).toBe('');});+ it('skips non-persistable favicon candidates and keeps a safe fallback', () => {+ let result: UseBrowserWebviewResult | null = null;+ render(createElement(HookProbe, {+ visible: true,+ onResult: (next) => { result = next; },+ }));++ act(() => {+ mockWebview.dispatch('page-favicon-updated', {+ favicons: [+ `data:image/png;base64,${'x'.repeat(20 * 1024)}`,+ 'blob:https://example.com/favicon',+ `https://example.com/${'x'.repeat(20 * 1024)}`,+ 'https://example.com/favicon.ico',+ ],+ });+ });+ expect(result!.favicon).toBe('https://example.com/favicon.ico');+ });++ it('persists small data: favicons and returns null when every candidate is non-persistable', () => {+ let result: UseBrowserWebviewResult | null = null;+ render(createElement(HookProbe, {+ visible: true,+ onResult: (next) => { result = next; },+ }));++ act(() => {+ mockWebview.dispatch('page-favicon-updated', {+ favicons: ['data:image/png;base64,eA=='],+ });+ });+ // 小 data: 是自包含、可跨重启的,应当被持久化(SPA dev-server 场景)。+ expect(result!.favicon).toBe('data:image/png;base64,eA==');++ act(() => {+ mockWebview.dispatch('page-favicon-updated', {+ favicons: ['blob:https://example.com/favicon'],+ });+ });+ // 全部候选不可持久化 → null(保留已有持久化图标,不覆盖)。+ expect(result!.favicon).toBeNull();++ act(() => {+ mockWebview.dispatch('page-favicon-updated', {+ favicons: ['file:///etc/passwd', 'javascript:alert(1)'],+ });+ });+ expect(result!.favicon).toBeNull();+ });+it('does not treat a suppressed stale navigation report as a missing favicon', () => {let result: UseBrowserWebviewResult | null = null;render(createElement(HookProbe, {diff --git a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.tsindex 561f8d000f..fd2e8ca8a5 100644--- a/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts@@ -29,6 +29,7 @@import { useCallback, useEffect, useRef, useState } from 'react';import type { WebviewTag } from 'electron';+import { selectPersistableFavicon } from '../../../../shared/faviconPersistence';import { browserWebviewPool } from '../lib/browserWebviewPool';import {consumePendingKillCause,@@ -66,8 +67,9 @@ export interface UseBrowserWebviewResult {/** 当前页面 title(`page-title-updated`)。 */title: string;/**- * 当前页面 favicon URL。null = 当前 webview 代际尚未观测到 favicon;- * 空串 = 已明确观测到页面没有 favicon。+ * 当前页面 favicon URL。null = 当前 webview 代际尚未观测到 favicon,或观测到+ * 但全部候选不可持久化(blob: / 超大 / 非白名单协议)——两种都不覆盖已持久化+ * 图标;空串 = 已明确观测到页面没有 favicon。*/favicon: string | null;/** 正在加载中(`did-start-loading` 翻 true,`did-stop-loading` 翻 false)。 */@@ -245,7 +247,7 @@ export function useBrowserWebview(const onTitle = (e: Electron.PageTitleUpdatedEvent) => setTitle(e.title);const onFavicon = (e: Electron.PageFaviconUpdatedEvent) => {- setFavicon(e.favicons.find((candidate) => candidate.trim().length > 0) ?? '');+ setFavicon(selectPersistableFavicon(e.favicons));};const onDidNavigate = (e: Electron.DidNavigateEvent) => {const previousUrl = urlRef.current;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.tsxindex 15d21052dc..7cc2934171 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@@ -31,6 +31,7 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'reactimport { AlertTriangle, Gauge, RotateCw, X } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { normalizePersistableFavicon } from '../../../../../shared/faviconPersistence';import { useAppShortcut } from '@/hooks/useAppShortcut';import { createLogger } from '@/lib/logger';import { isSidebarWindow } from '@/lib/sidebarWindow';@@ -198,10 +199,20 @@ export function BrowserTabBody({ state, ctx, active, shellVisible }: BrowserTabB}, [browser.title, ctx, state.title]);useEffect(() => {- // null 表示当前 webview 代际尚未观测到 favicon,不能据此清掉持久化图标;- // 空串才是 page-favicon-updated 明确报告 "无图标"。+ // null 表示当前 webview 代际尚未观测到 favicon,或观测到但全部候选不可+ // 持久化(如只有 blob:)——两种都不能据此清掉 / 覆盖已持久化图标。if (browser.favicon === null) return;- const nextFavicon = browser.favicon || null;+ // 空串才是 page-favicon-updated 明确报告 "页面无图标" → 清空持久化 favicon。+ if (browser.favicon === '') {+ if (state.favicon === null) return;+ ctx.patchState({ favicon: null });+ return;+ }+ // 非空候选:WebView 和原生 popup 两套事件源必须在共用写入边界再做一次+ // 过滤,避免 blob: / 超长 / 非白名单 scheme 进入 tab state。+ // 不可持久化 → 保留已有图标,不写不清。+ const nextFavicon = normalizePersistableFavicon(browser.favicon);+ if (nextFavicon === null) return;if (nextFavicon === state.favicon) return;ctx.patchState({ favicon: nextFavicon });}, [browser.favicon, ctx, state.favicon]);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.tsindex e2eade7c0b..34c4efbeda 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@@ -422,6 +422,70 @@ describe('BrowserTabBody navigation', () => {expect(patchState).toHaveBeenCalledWith({ favicon: null });});+ it('clears a persisted favicon when a native popup explicitly reports none', () => {+ registerNativePopupTab('tab-browser', 'session-a', 'surface-oauth');+ nativePopupHook.mockReturnValue({+ ...makeBrowserState({ wrapper: null, webview: null, favicon: '' }),+ closed: false,+ });+ const patchState = vi.fn();++ render(renderBrowserTab(+ 'https://www.taptap.cn/',+ patchState,+ true,+ { favicon: 'https://www.taptap.cn/favicon.ico' },+ ));++ expect(patchState).toHaveBeenCalledWith({ favicon: null });+ });++ it('does not persist a non-persistable favicon reported by a native popup', () => {+ registerNativePopupTab('tab-browser', 'session-a', 'surface-oauth');+ nativePopupHook.mockReturnValue({+ ...makeBrowserState({+ wrapper: null,+ webview: null,+ favicon: 'blob:https://oauth.example/favicon',+ }),+ closed: false,+ });+ const patchState = vi.fn();++ render(renderBrowserTab(+ 'https://www.taptap.cn/',+ patchState,+ true,+ { favicon: 'https://www.taptap.cn/favicon.ico' },+ ));++ // 不可持久化 favicon:保留已持久化图标,不写、不清。+ expect(patchState).not.toHaveBeenCalledWith({ favicon: 'blob:https://oauth.example/favicon' });+ expect(patchState).not.toHaveBeenCalledWith({ favicon: null });+ });++ it('persists a small data: favicon reported by a native popup', () => {+ registerNativePopupTab('tab-browser', 'session-a', 'surface-oauth');+ nativePopupHook.mockReturnValue({+ ...makeBrowserState({+ wrapper: null,+ webview: null,+ favicon: 'data:image/png;base64,eA==',+ }),+ closed: false,+ });+ const patchState = vi.fn();++ render(renderBrowserTab(+ 'https://www.taptap.cn/',+ patchState,+ true,+ { favicon: 'https://www.taptap.cn/favicon.ico' },+ ));++ expect(patchState).toHaveBeenCalledWith({ favicon: 'data:image/png;base64,eA==' });+ });+it('does not run browser shortcuts while an editable target has focus', () => {const reload = vi.fn();const goBack = vi.fn();diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsxindex 61fb21c11b..0a62e0ed46 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx@@ -21,6 +21,7 @@ import { useState } from 'react';import { cn } from '@/lib/utils';+import { normalizePersistableFavicon } from '../../../../../shared/faviconPersistence';import { registerTabKind } from '../../registry';import type { TabKindPlugin } from '../../types';import { BrowserTabBody } from './BrowserTabBody';@@ -31,7 +32,8 @@ export interface WebBrowserState {url: string;/** 当前页面 title(用作 tab pill 文案)。空串 / 未拿到时 pill 走"新标签"占位。 */title: string;- /** 当前页面 favicon URL(用作 tab pill icon)。null = 没拿到,走 Globe fallback。 */+ /** 当前页面 favicon URL(用作 tab pill icon)。null = 没拿到 / 拿到但不可+ * 持久化(blob: / 超大 / 非白名单协议),都走 Globe fallback。 */favicon: string | null;/** guest 正在发声(`audio-state-changed`)。tab pill 据此叠喇叭图标,跟 Chrome* 行为对齐 + Codex `main-cC-d0ezP.js:48434` 等价。后台 tab 不持久化(切走重启@@ -132,6 +134,7 @@ const plugin: TabKindPlugin<WebBrowserState> = {defaultState: () => ({ ...DEFAULT_STATE }),// hydrate:容忍持久化 schema 演进。Phase 2 时期空 state(`null`)→ default。// isAudible 不从持久化恢复(重启后 webview 重新加载,默认静默才合理)。+ // favicon 再消毒一次:存量坏数据(超大 / blob: / 非白名单)在显示层也不放行。hydrateState: (raw): WebBrowserState => {if (!raw || typeof raw !== 'object') return { ...DEFAULT_STATE };const obj = raw as Record<string, unknown>;@@ -139,7 +142,7 @@ const plugin: TabKindPlugin<WebBrowserState> = {const title = typeof obj.title === 'string' ? obj.title : DEFAULT_STATE.title;const favicon =typeof obj.favicon === 'string'- ? obj.favicon+ ? normalizePersistableFavicon(obj.favicon): obj.favicon === null? null: DEFAULT_STATE.favicon;diff --git a/apps/desktop/src/renderer/features/right-sidebar/store.ts b/apps/desktop/src/renderer/features/right-sidebar/store.tsindex cf990870e7..01b2d1b722 100644--- a/apps/desktop/src/renderer/features/right-sidebar/store.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/store.ts@@ -18,6 +18,9 @@import { createLogger } from '@/lib/logger';import { extractIpcError } from '@/utils/ipcError';+import { normalizePersistableFavicon } from '../../../shared/faviconPersistence';+import { createIpcError } from '../../../shared/ipc-errors';+import { MAX_STATE_JSON_BYTES } from '../../../shared/rightSidebarTabState';import { getSessionDeviceId } from '@/features/device-link/remoteProjectsStore';import { getTabKind } from './registry';import { browserWebviewPool } from './lib/browserWebviewPool';@@ -39,7 +42,6 @@ type Listener = (sessionId: string) => void;export type TabCloseInterceptor = () => Promise<boolean | void> | boolean | void;const MAX_TABS_PER_SESSION = 20;-const MAX_STATE_JSON_BYTES = 16 * 1024;const cache = new Map<string, TabBucket>();const inflight = new Map<string, Promise<void>>();const singletonInflight = new Map<string, Promise<TabState>>();@@ -417,17 +419,51 @@ function markMemoryOnlySession(sessionId: string): void {memoryOnlySessions.add(sessionId);}-function validateMemoryOnlyStateSize(state: unknown): void {- const json = state === undefined ? '{}' : JSON.stringify(state);+/**+ * Renderer-side preflight matching the main-process 16KB persistence guard.+ *+ * This must run before optimistic cache updates for both persisted and+ * memory-only sessions. If main rejects an oversized optimistic patch and the+ * plugin derives that patch from an unchanged external source (for example a+ * WebView favicon), rollback would notify React and immediately retrigger the+ * same patch forever.+ */+function validateTabStateSize(state: unknown): void {+ let json: string | undefined;+ try {+ json = state === undefined ? '{}' : JSON.stringify(state);+ } catch {+ throw createIpcError('INVALID_PARAMS', 'tab state must be JSON-serializable');+ }+ // JSON.stringify 顶层 function / symbol 时不抛错而返回 undefined,同样不能持久化。if (typeof json !== 'string') {- throw new Error('tab state JSON must be serializable');+ throw createIpcError('INVALID_PARAMS', 'tab state must be JSON-serializable');}const bytes = new TextEncoder().encode(json).byteLength;if (bytes > MAX_STATE_JSON_BYTES) {- throw new Error(`tab state JSON too large: ${bytes} bytes (limit ${MAX_STATE_JSON_BYTES})`);+ throw createIpcError(+ 'RIGHT_SIDEBAR_STATE_TOO_LARGE',+ `tab state JSON too large: ${bytes} bytes (limit ${MAX_STATE_JSON_BYTES})`,+ );}}+/**+ * hydrate 路径消毒:发布前已把超大 / blob: / 非白名单 favicon 持久化进 DB 的+ * 存量 tab,读回缓存时直接清洗。否则任何后续 patchState(哪怕只是 title 变更)+ * 都会把坏 favicon 重新并进 16KB 预检而持续被拒,复发更新循环。+ * web-browser 以外的 kind 没有 favicon 字段,原样透传。+ */+function sanitizeHydratedTabState(kind: string, raw: unknown): unknown {+ if (kind !== 'web-browser' || !raw || typeof raw !== 'object') return raw;+ const state = raw as Record<string, unknown>;+ if (typeof state.favicon !== 'string') return raw;+ const normalized = normalizePersistableFavicon(state.favicon);+ if (normalized === state.favicon) return raw;+ // normalized 为 null(不可持久化)时清成"无图标";为安全 URL 时做归一化。+ return { ...state, favicon: normalized };+}+/*** 当前快照(同步)。无 sessionId 或 cache miss 时返回 EMPTY_BUCKET 单例* (hydrated:false,语义 "尚未加载")。@@ -478,7 +514,7 @@ export async function ensureHydrated(sessionId: string): Promise<void> {const tabs: TabState[] = result.tabs.map((row) => ({id: row.id,kind: row.kind as TabKindId,- state: row.state,+ state: sanitizeHydratedTabState(row.kind, row.state),}));setBucket(sessionId, { hydrated: true, tabs, activeTabId: result.activeTabId });} finally {@@ -519,9 +555,7 @@ export async function addTab(`session ${sessionId} already has ${MAX_TABS_PER_SESSION} tabs (limit reached)`,);}- if (!shouldPersist(sessionId)) {- validateMemoryOnlyStateSize(initialState);- }+ validateTabStateSize(initialState);const id = makeTabId();const position = prev.tabs.length;const newTab: TabState = { id, kind, state: initialState };@@ -957,12 +991,13 @@ export function patchTabState(if (idx < 0) return Promise.resolve();const oldTab = prev.tabs[idx];const newState = patch(oldTab.state);- if (!shouldPersist(sessionId)) {- try {- validateMemoryOnlyStateSize(newState);- } catch (err) {- return Promise.reject(err);- }+ try {+ validateTabStateSize(newState);+ } catch (err) {+ // patchTabState is intentionally promise-shaped. Keep validation failures+ // asynchronous so effect callers can handle them with the existing catch+ // path instead of throwing through React's commit phase.+ return Promise.reject(err);}const nextTabs = [...prev.tabs];nextTabs[idx] = { ...oldTab, state: newState };diff --git a/apps/desktop/src/shared/__tests__/faviconPersistence.test.ts b/apps/desktop/src/shared/__tests__/faviconPersistence.test.tsnew file mode 100644index 0000000000..90447d486f--- /dev/null+++ b/apps/desktop/src/shared/__tests__/faviconPersistence.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it } from 'vitest';++import {+ normalizePersistableFavicon,+ selectPersistableFavicon,+} from '../faviconPersistence';++describe('normalizePersistableFavicon', () => {+ it('keeps http(s) favicons and normalizes them', () => {+ expect(normalizePersistableFavicon('https://www.taptap.cn/favicon.ico')).toBe(+ 'https://www.taptap.cn/favicon.ico',+ );+ expect(normalizePersistableFavicon('http://example.com/a.png')).toBe(+ 'http://example.com/a.png',+ );+ // 前后空白 / 裸域名补斜杠 / 控制字符前缀都被 URL 解析器归一化。+ expect(normalizePersistableFavicon(' https://example.com/f.ico ')).toBe(+ 'https://example.com/f.ico',+ );+ expect(normalizePersistableFavicon('https://example.com')).toBe('https://example.com/');+ expect(normalizePersistableFavicon('\x01https://example.com/favicon')).toBe(+ 'https://example.com/favicon',+ );+ });++ it('keeps small data: favicons (SPA dev-server case)', () => {+ const svg = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>';+ expect(normalizePersistableFavicon(svg)).toBe(svg);+ expect(normalizePersistableFavicon('data:image/png;base64,eA==')).toBe(+ 'data:image/png;base64,eA==',+ );+ });++ it('rejects oversized data: favicons', () => {+ const large = `data:image/png;base64,${'x'.repeat(3 * 1024)}`;+ expect(normalizePersistableFavicon(large)).toBeNull();+ });++ it('rejects blob: favicons (session-local, cannot survive restart)', () => {+ expect(normalizePersistableFavicon('blob:https://example.com/favicon')).toBeNull();+ });++ it('rejects non-http(s) schemes (file / javascript / chrome-extension / custom app)', () => {+ expect(normalizePersistableFavicon('file:///etc/passwd')).toBeNull();+ expect(normalizePersistableFavicon('javascript:alert(1)')).toBeNull();+ expect(normalizePersistableFavicon('chrome-extension://abc/favicon.png')).toBeNull();+ expect(normalizePersistableFavicon('myapp://favicon.png')).toBeNull();+ expect(normalizePersistableFavicon('about:blank')).toBeNull();+ });++ it('rejects empty / unparsable candidates', () => {+ expect(normalizePersistableFavicon('')).toBeNull();+ expect(normalizePersistableFavicon(' ')).toBeNull();+ // 相对路径没有 base,URL 解析直接失败。+ expect(normalizePersistableFavicon('favicon.ico')).toBeNull();+ });++ it('rejects over-budget http(s) URLs', () => {+ const long = `https://example.com/${'x'.repeat(3 * 1024)}`;+ expect(normalizePersistableFavicon(long)).toBeNull();+ });+});++describe('selectPersistableFavicon', () => {+ it('returns "" for an explicitly empty candidate list (page has no icon)', () => {+ expect(selectPersistableFavicon([])).toBe('');+ // 全空白候选等同无图标 → 清掉旧图标。+ expect(selectPersistableFavicon(['', ' '])).toBe('');+ });++ it('returns the first persistable candidate', () => {+ expect(+ selectPersistableFavicon([+ 'blob:https://example.com/favicon',+ 'data:image/svg+xml,<svg/>',+ 'https://example.com/favicon.ico',+ ]),+ ).toBe('data:image/svg+xml,<svg/>');+ });++ it('returns null when every candidate is non-persistable (keep existing icon)', () => {+ expect(selectPersistableFavicon(['blob:https://example.com/favicon'])).toBeNull();+ expect(selectPersistableFavicon(['file:///etc/passwd', 'javascript:alert(1)'])).toBeNull();+ expect(selectPersistableFavicon([`data:image/png;base64,${'x'.repeat(3 * 1024)}`])).toBeNull();+ });+});diff --git a/apps/desktop/src/shared/faviconPersistence.ts b/apps/desktop/src/shared/faviconPersistence.tsnew file mode 100644index 0000000000..6ff80d0ffb--- /dev/null+++ b/apps/desktop/src/shared/faviconPersistence.ts@@ -0,0 +1,63 @@+/**+ * Favicon URL 持久化白名单。+ *+ * 规则:+ * - 只允许 `http:` / `https:`,以及 2KB 以内的小 `data:`。data URI 自包含、+ * 可跨重启,SPA dev server 常用 `data:image/svg+xml` 当 favicon,不能一刀切+ * 拒绝;但过大仍会挤占 16KB 总预算,因此 favicon 字段统一限制为 2KB。+ * - 一律拒绝 `blob:`(会话内临时对象,重启即失效)、`file:`(宿主 renderer 里+ * 可读本地文件)、`javascript:` / `chrome-extension:` / 自定义 app 协议等+ * 一切非白名单 scheme。白名单比黑名单安全,且不依赖前缀匹配 —— 前缀黑名单+ * 可被 C0 控制字符 / 大小写绕过,这里直接用 URL 解析后的 protocol 判定。+ * - 超长 URL 拒绝:单字段也要给 url / title 留足 16KB 总预算。+ *+ * 返回值用 `new URL(...).href` 归一化(去前后空白与控制字符、补默认端口 / 斜杠),+ * 存进状态的是干净 URL。+ *+ * store 仍对整份 state 做权威 16KB 预检,这里是第一道过滤,让坏数据进不了状态、+ * 也不会触发"乐观写 → main 拒 → 回滚 → 重写"的更新循环。+ */+const MAX_PERSISTED_FAVICON_URL_BYTES = 2 * 1024;+const MAX_PERSISTED_DATA_FAVICON_BYTES = 2 * 1024;+const PERSISTABLE_PROTOCOLS = new Set(['http:', 'https:']);++/**+ * 单候选归一化。返回:+ * - 持久化安全的 favicon URL(归一化后)+ * - null = 不可持久化(空 / 非白名单 scheme / 超长 / 无法解析)+ */+export function normalizePersistableFavicon(candidate: string): string | null {+ const trimmed = candidate.trim();+ if (!trimmed) return null;+ let url: URL;+ try {+ url = new URL(trimmed);+ } catch {+ return null;+ }+ const bytes = new TextEncoder().encode(url.href).byteLength;+ if (url.protocol === 'data:') {+ if (bytes > MAX_PERSISTED_DATA_FAVICON_BYTES) return null;+ return url.href;+ }+ if (!PERSISTABLE_PROTOCOLS.has(url.protocol)) return null;+ if (bytes > MAX_PERSISTED_FAVICON_URL_BYTES) return null;+ return url.href;+}++/**+ * 从事件候选里挑一个可持久化 favicon:+ * - 空 / 全空白候选 = 页面明确无图标 → 返回 ''(调用方据此清掉旧图标)+ * - 有非空候选但全部不可持久化(如只有 blob:)→ 返回 null(保留已持久化图标,+ * 不要用"无图标"覆盖好图标;blob: 反正重启即失效)+ * - 否则返回第一个可持久化候选+ */+export function selectPersistableFavicon(candidates: string[]): string | null {+ let sawNonEmptyCandidate = false;+ for (const candidate of candidates) {+ const normalized = normalizePersistableFavicon(candidate);+ if (normalized) return normalized;+ if (candidate.trim()) sawNonEmptyCandidate = true;+ }+ return sawNonEmptyCandidate ? null : '';+}diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex e5c02512d9..4945c8bb4e 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -395,6 +395,20 @@ export function isIpcErrorCode(code: unknown): code is IpcErrorCode {return typeof code === 'string' && IPC_ERROR_CODES.has(code as IpcErrorCode);}+/**+ * 标准 IpcError 构造器 —— main 的 throwIpcError 与 renderer 侧预检共用同一形状+ * (`[code] message` + err.code),避免两处手写漂移。isIpcError 按 err.code 判定,+ * 不依赖 err.name。+ */+export function createIpcError(+ code: IpcErrorCode,+ message: string,+): Error & { code: IpcErrorCode } {+ const err = new Error(`[${code}] ${message}`) as Error & { code: IpcErrorCode };+ err.code = code;+ return err;+}+export function isIpcError(err: unknown): err is Error & { code: IpcErrorCode } {return err instanceof Error && isIpcErrorCode((err as { code?: unknown }).code);}diff --git a/apps/desktop/src/shared/rightSidebarTabState.ts b/apps/desktop/src/shared/rightSidebarTabState.tsnew file mode 100644index 0000000000..54f64045ad--- /dev/null+++ b/apps/desktop/src/shared/rightSidebarTabState.ts@@ -0,0 +1,5 @@+/**+ * 右侧栏 tab 持久化上限 —— main(权威校验)与 renderer(写入前预检)共用同一常量,+ * 避免跨进程两份定义漂移。单行 tab state JSON 序列化字节上限。+ */+export const MAX_STATE_JSON_BYTES = 16 * 1024;diff --git a/apps/desktop/src/shared/rsbNativePopup.ts b/apps/desktop/src/shared/rsbNativePopup.tsindex c92d8d53fb..0b2a9cf878 100644--- a/apps/desktop/src/shared/rsbNativePopup.ts+++ b/apps/desktop/src/shared/rsbNativePopup.ts@@ -22,6 +22,7 @@ export interface RsbNativePopupBounds {export interface RsbNativePopupSnapshot {url: string;title: string;+ /** null = 尚未观测到 / 无可持久化候选;空串 = 明确无图标;非空 = 可持久化 URL。 */favicon: string | null;isLoading: boolean;canGoBack: boolean;