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): restrict wallpaper snapshots and restore detached window backgrounds

DavidShen6e4614c2a5b1
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
index fd98bb1ab2..73d4ecccd3 100644
--- a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
importWallpaper: vi.fn(),
removeWallpaper: vi.fn(),
ensureVideo: vi.fn(),
+ fromWebContents: vi.fn(),
}));
vi.mock('../appSessionState.js', () => ({
@@ -30,7 +31,7 @@ vi.mock('../custom-wallpaper.js', () => ({
vi.mock('../wallpaper-video.js', () => ({ ensureWallpaperVideo: mocks.ensureVideo }));
vi.mock('electron', () => ({
- BrowserWindow: { getAllWindows: () => mocks.allWindows, fromWebContents: () => ({}) },
+ BrowserWindow: { getAllWindows: () => mocks.allWindows, fromWebContents: mocks.fromWebContents },
ipcMain: { on: mocks.ipcOn, handle: mocks.ipcHandle },
}));
@@ -53,6 +54,7 @@ vi.mock('../appearance-settings-store.js', () => ({
import { registerAppearanceSettingsIpc, __testing } from '../appearance-settings-ipc.js';
import { normalizeAppearanceSettings } from '../../shared/appearanceSettings.js';
+import { markAppContentWindow } from '../windowFocusClassifier.js';
const persisted = {
uiFamily: 'Inter',
@@ -145,6 +147,7 @@ describe('appearance settings IPC authorization', () => {
mocks.trustedReadWindow.mockReset().mockReturnValue(false);
mocks.assertTrustedAppRendererEvent.mockReset();
mocks.readAppearanceSettings.mockReset().mockReturnValue(persisted);
+ mocks.fromWebContents.mockReset().mockReturnValue({ isDestroyed: () => false });
});
it('同步启动读取只向已授权的外观 reader 返回持久快照', () => {
@@ -189,6 +192,35 @@ describe('appearance settings IPC authorization', () => {
expect(mocks.assertTrustedAppRendererEvent).toHaveBeenNthCalledWith(3, event);
});
+ it('withholds private media from utility bootstrap and broadcasts, while retaining it for app content', async () => {
+ const settings = normalizeAppearanceSettings({
+ wallpaperId: 'custom',
+ customWallpaperUrl: `cindy-media://blobs/${'a'.repeat(64)}.webp`,
+ });
+ const utility = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn() } };
+ const content = { isDestroyed: () => false, webContents: { isDestroyed: () => false, send: vi.fn(), setZoomFactor: vi.fn() } };
+ markAppContentWindow(content as never);
+ mocks.trustedRead.mockReturnValue(true);
+ mocks.readAppearanceSettings.mockReturnValue(settings);
+ const sync = mocks.ipcOn.mock.calls.find(([name]) => name === 'appearance-settings:get-sync')![1];
+ const event = { sender: {}, returnValue: undefined as unknown };
+ mocks.fromWebContents.mockReturnValue(utility);
+ sync(event);
+ expect(event.returnValue).not.toHaveProperty('customWallpaperUrl');
+ expect(event.returnValue).toMatchObject({ wallpaperId: 'none', uiSize: settings.uiSize });
+ mocks.fromWebContents.mockReturnValue(content);
+ sync(event);
+ expect(event.returnValue).toEqual(settings);
+
+ mocks.allWindows.push(utility, content);
+ mocks.trustedReadWindow.mockReturnValue(true);
+ mocks.writeAppearanceSettingsPatch.mockResolvedValue(settings);
+ const set = mocks.ipcHandle.mock.calls.find(([name]) => name === 'appearance-settings:set-patch')![1];
+ await set({}, { uiSize: 15 });
+ expect(utility.webContents.send.mock.calls[0][1]).not.toHaveProperty('customWallpaperUrl');
+ expect(content.webContents.send).toHaveBeenCalledWith('appearance-settings:changed', settings);
+ });
+
it('外观变更广播也覆盖显式授权的 utility 窗口', async () => {
const setHandler = mocks.ipcHandle.mock.calls.find(
([channel]) => channel === 'appearance-settings:set-patch',
diff --git a/apps/desktop/src/main/__tests__/customWallpaper.test.ts b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
index ce61de7e65..55683633aa 100644
--- a/apps/desktop/src/main/__tests__/customWallpaper.test.ts
+++ b/apps/desktop/src/main/__tests__/customWallpaper.test.ts
@@ -17,7 +17,7 @@ vi.mock('electron', () => ({ dialog: { showOpenDialog: h.picker } }));
vi.mock('../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
vi.mock('../utils/readBoundedFile.js', () => ({ readBoundedFileNoFollow: h.read }));
vi.mock('../localDb/client/current.js', () => ({ getCurrentDbClientSnapshot: () => h.snapshot }));
-vi.mock('../appSessionState.js', () => ({ ownerScopedUserDataPath: () => 'test-lock' }));
+vi.mock('../appSessionState.js', () => ({ ownerScopedUserDataPath: () => `test-lock-${h.snapshot.userId}` }));
vi.mock('../device-link/crossProcessLock.js', () => ({
withCrossProcessLock: (_p: string, _o: unknown, fn: Function) => fn({ held: true }),
}));
@@ -42,6 +42,7 @@ import {
const url = `cindy-media://blobs/${'a'.repeat(64)}.webp`;
beforeEach(async () => {
vi.resetAllMocks();
+ h.snapshot = { client: { drizzle: {} }, userId: 'test', clientEpoch: 1 };
h.picker.mockResolvedValue({ canceled: false, filePaths: ['chosen-image'] });
h.read.mockResolvedValue(
await sharp({ create: { width: 8, height: 4, channels: 3, background: 'blue' } })
@@ -52,6 +53,38 @@ beforeEach(async () => {
});
describe('custom wallpaper import', () => {
+ it('lets another owner remove their image while the old owner picker remains open', async () => {
+ let closePicker!: (value: { canceled: boolean; filePaths: string[] }) => void;
+ h.picker.mockReturnValueOnce(new Promise(resolve => { closePicker = resolve; }));
+ const oldImport = importCustomWallpaper({} as never);
+ const rejected = expect(oldImport).rejects.toThrow('Wallpaper owner changed');
+ await vi.waitFor(() => expect(h.picker).toHaveBeenCalledOnce());
+ h.snapshot = { client: { drizzle: {} }, userId: 'other', clientEpoch: 2 };
+ const removal = removeCustomWallpaper();
+ try {
+ await vi.waitFor(() => expect(h.reset).toHaveBeenCalledOnce());
+ } finally {
+ closePicker({ canceled: true, filePaths: [] });
+ await rejected;
+ await removal;
+ }
+ expect(h.ingest).not.toHaveBeenCalled();
+ expect(h.remove).toHaveBeenCalledWith(expect.anything(), h.snapshot.client.drizzle);
+ });
+
+ it('serializes operations for the same owner until their picker closes', async () => {
+ let closePicker!: (value: { canceled: boolean; filePaths: string[] }) => void;
+ h.picker.mockReturnValueOnce(new Promise(resolve => { closePicker = resolve; }));
+ const importing = importCustomWallpaper({} as never);
+ await vi.waitFor(() => expect(h.picker).toHaveBeenCalledOnce());
+ const removal = removeCustomWallpaper();
+ await Promise.resolve();
+ expect(h.reset).not.toHaveBeenCalled();
+ closePicker({ canceled: true, filePaths: [] });
+ await importing;
+ await removal;
+ expect(h.reset).toHaveBeenCalledOnce();
+ });
it('decodes and pins the image before publishing, then removes only older wallpaper refs', async () => {
expect(await importCustomWallpaper({} as never)).toBe(true);
expect(h.ingest).toHaveBeenCalledWith(
diff --git a/apps/desktop/src/main/appearance-settings-ipc.ts b/apps/desktop/src/main/appearance-settings-ipc.ts
index a0fa9620fd..c830ab022a 100644
--- a/apps/desktop/src/main/appearance-settings-ipc.ts
+++ b/apps/desktop/src/main/appearance-settings-ipc.ts
@@ -53,7 +53,7 @@ export function registerAppearanceSettingsIpc(): void {
// the first synchronous bootstrap frame.
ipcMain.on('appearance-settings:get-sync', (event) => {
event.returnValue = isTrustedAppearanceSettingsReadEvent(event)
- ? readAppearanceSettings()
+ ? appearanceForWindow(readAppearanceSettings(), BrowserWindow.fromWebContents(event.sender))
: null;
});
@@ -157,11 +157,21 @@ export async function updatePersistedWindowZoom(delta: number | null): Promise<A
return settings;
}
+// A font/theme reader is not a grant to the owner's private media capability.
+function appearanceForWindow(settings: AppearanceSettings, win: BrowserWindow | null): AppearanceSettings {
+ if (isAppContentWindow(win)) return settings;
+ const { customWallpaperUrl: _privateUrl, ...publicSettings } = settings;
+ return {
+ ...publicSettings,
+ wallpaperId: settings.wallpaperId === 'custom' ? 'none' : settings.wallpaperId,
+ };
+}
+
function broadcast(settings: AppearanceSettings): void {
for (const win of BrowserWindow.getAllWindows()) {
if (!isTrustedAppearanceSettingsReadWindow(win)) continue;
try {
- win.webContents.send(APPEARANCE_SETTINGS_CHANGED_CHANNEL, settings);
+ win.webContents.send(APPEARANCE_SETTINGS_CHANGED_CHANNEL, appearanceForWindow(settings, win));
} catch {
// A window may be torn down between enumeration and send.
}
diff --git a/apps/desktop/src/main/custom-wallpaper.ts b/apps/desktop/src/main/custom-wallpaper.ts
index ac04cdff07..ac29fbc616 100644
--- a/apps/desktop/src/main/custom-wallpaper.ts
+++ b/apps/desktop/src/main/custom-wallpaper.ts
@@ -15,7 +15,7 @@ import { withCrossProcessLock } from './device-link/crossProcessLock.js';
const log = createLogger('custom-wallpaper');
const REF = { refKind: 'import' as const, refId: 'desktop-custom-wallpaper' };
const MAX_BYTES = 20 * 1024 * 1024;
-let queue: Promise<unknown> = Promise.resolve();
+const queues = new Map<string, Promise<unknown>>();
function captureScope() {
const snapshot = getCurrentDbClientSnapshot();
@@ -31,7 +31,7 @@ function captureScope() {
function serialize<T>(action: () => Promise<T>): Promise<T> {
const lockPath = ownerScopedUserDataPath('custom-wallpaper-operation.lock');
- const result = queue
+ const result = (queues.get(lockPath) ?? Promise.resolve())
.catch(() => undefined)
.then(() =>
withCrossProcessLock(
@@ -44,7 +44,11 @@ function serialize<T>(action: () => Promise<T>): Promise<T> {
},
),
);
- queue = result;
+ queues.set(lockPath, result);
+ const release = () => {
+ if (queues.get(lockPath) === result) queues.delete(lockPath);
+ };
+ void result.then(release, release);
return result;
}
diff --git a/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx
new file mode 100644
index 0000000000..ab149c86ab
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/detachedWallpaperEntry.test.tsx
@@ -0,0 +1,109 @@
+// @vitest-environment jsdom
+import React, { act, type ReactNode } from 'react';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ DEFAULT_APPEARANCE_SETTINGS,
+ type AppearanceSettings,
+} from '../../shared/appearanceSettings';
+
+const h = vi.hoisted(() => ({ roots: [] as Array<{ unmount(): void }> }));
+vi.mock('react-dom/client', async (original) => {
+ const actual = await original<typeof import('react-dom/client')>();
+ return {
+ ...actual,
+ createRoot: (...args: Parameters<typeof actual.createRoot>) => {
+ const root = actual.createRoot(...args);
+ h.roots.push(root);
+ return root;
+ },
+ };
+});
+vi.mock('@/i18n', () => ({}));
+vi.mock('../themes/colors', () => ({}));
+vi.mock('../themes/local-themes', () => ({ bootstrapLocalThemesSync: vi.fn() }));
+vi.mock('../themes/theme-service', () => ({ themeService: { applyTheme: vi.fn() } }));
+vi.mock('../hooks/useTheme', () => ({ getInitialThemeVariant: () => ({ theme: 'test' }) }));
+vi.mock('../hooks/useFontSettings', () => ({
+ applyFontSettings: vi.fn(),
+ getInitialFontSettings: vi.fn(),
+}));
+vi.mock('../hooks/useLocale', () => ({
+ bootstrapInitialLocale: vi.fn(),
+ LocaleProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('../components/error/TopLevelErrorBoundary', () => ({
+ TopLevelErrorBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('../components/ui/confirm-dialog-provider', () => ({
+ ConfirmDialogProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('../contexts/AuthContext', () => ({
+ AuthProvider: ({ children }: { children: ReactNode }) => children,
+}));
+vi.mock('../cindy-brain/ghostPanels', () => ({ ensureGhostPanelsRegistered: vi.fn() }));
+vi.mock('../components/layout/SidebarWindowLayout', () => ({
+ SidebarWindowLayout: () => <div>sidebar host</div>,
+}));
+vi.mock('../components/layout/GhostPanelWindowLayout', () => ({
+ GhostPanelWindowLayout: () => <div>plugin host</div>,
+}));
+
+afterEach(async () => {
+ await act(async () => {
+ for (const root of h.roots.splice(0)) root.unmount();
+ });
+ document.body.innerHTML = '';
+ document.documentElement.classList.remove('dark');
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+it.each(['sidebar', 'plugin'] as const)(
+ 'boots %s with a wallpaper using its read-only bridge and follows live changes',
+ async (kind) => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
+ vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue();
+ vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {});
+ vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {});
+ document.body.innerHTML = '<div id="root"></div>';
+ let changed!: (settings: AppearanceSettings) => void;
+ vi.stubGlobal('electronAPI', {
+ platform: 'win32',
+ appearanceSettings: {
+ getSync: () => ({
+ ...DEFAULT_APPEARANCE_SETTINGS,
+ wallpaperId: 'cindy-window',
+ wallpaperMotion: 'dynamic',
+ }),
+ onChanged: (fn: typeof changed) => {
+ changed = fn;
+ return () => {};
+ },
+ },
+ });
+ await act(async () => {
+ if (kind === 'sidebar') await import('../sidebar-window-entry');
+ else await import('../ghost-panel-window-entry');
+ });
+ expect(document.body.textContent).toContain(
+ kind === 'sidebar' ? 'sidebar host' : 'plugin host',
+ );
+ expect(document.documentElement.dataset.wallpaperActive).toBe('true');
+ expect(document.querySelectorAll('video')).toHaveLength(1);
+ const lightVeil = document.documentElement.style.getPropertyValue('--app-wallpaper-veil');
+ await act(async () => {
+ document.documentElement.classList.add('dark');
+ });
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-veil')).not.toBe(
+ lightVeil,
+ );
+ const url = 'cindy-media://blobs/' + 'a'.repeat(64) + '.webp';
+ await act(async () =>
+ changed({ ...DEFAULT_APPEARANCE_SETTINGS, wallpaperId: 'custom', customWallpaperUrl: url }),
+ );
+ expect(document.querySelector('video')).toBeNull();
+ expect(document.documentElement.style.getPropertyValue('--app-wallpaper-image')).toContain(url);
+ await act(async () => changed(DEFAULT_APPEARANCE_SETTINGS));
+ expect(document.documentElement.dataset.wallpaperActive).toBeUndefined();
+ },
+);
diff --git a/apps/desktop/src/renderer/ghost-panel-window-entry.tsx b/apps/desktop/src/renderer/ghost-panel-window-entry.tsx
index b554897ce9..017d75e299 100644
--- a/apps/desktop/src/renderer/ghost-panel-window-entry.tsx
+++ b/apps/desktop/src/renderer/ghost-panel-window-entry.tsx
@@ -26,6 +26,7 @@ import { ConfirmDialogProvider } from './components/ui/confirm-dialog-provider';
import { applyFontSettings, getInitialFontSettings } from './hooks/useFontSettings';
import { bootstrapInitialLocale, LocaleProvider } from './hooks/useLocale';
import { getInitialThemeVariant } from './hooks/useTheme';
+import { WallpaperSettingsProvider } from './hooks/useWallpaperSettings';
import { bootstrapLocalThemesSync } from './themes/local-themes';
import { themeService } from './themes/theme-service';
import {
@@ -46,7 +47,9 @@ createRoot(rootElement).render(
<TopLevelErrorBoundary>
<LocaleProvider>
<ConfirmDialogProvider>
- <GhostPanelWindowLayout />
+ <WallpaperSettingsProvider>
+ <GhostPanelWindowLayout />
+ </WallpaperSettingsProvider>
</ConfirmDialogProvider>
</LocaleProvider>
</TopLevelErrorBoundary>,
diff --git a/apps/desktop/src/renderer/sidebar-window-entry.tsx b/apps/desktop/src/renderer/sidebar-window-entry.tsx
index 89aae4ad0f..30e8c74248 100644
--- a/apps/desktop/src/renderer/sidebar-window-entry.tsx
+++ b/apps/desktop/src/renderer/sidebar-window-entry.tsx
@@ -25,6 +25,7 @@ import { ConfirmDialogProvider } from './components/ui/confirm-dialog-provider';
import { applyFontSettings, getInitialFontSettings } from './hooks/useFontSettings';
import { LocaleProvider, bootstrapInitialLocale } from './hooks/useLocale';
import { getInitialThemeVariant } from './hooks/useTheme';
+import { WallpaperSettingsProvider } from './hooks/useWallpaperSettings';
import { bootstrapLocalThemesSync } from './themes/local-themes';
import { themeService } from './themes/theme-service';
@@ -42,7 +43,9 @@ createRoot(rootElement).render(
<LocaleProvider>
<ConfirmDialogProvider>
<AuthProvider enableSessionExpiredPrompt={false}>
- <SidebarWindowLayout />
+ <WallpaperSettingsProvider>
+ <SidebarWindowLayout />
+ </WallpaperSettingsProvider>
</AuthProvider>
</ConfirmDialogProvider>
</LocaleProvider>