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): 持久化外观设置并统一界面字号 (#1780)

DavidShenXD688cabaea132
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
new file mode 100644
index 0000000000..f74a0375a7
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/appearanceSettingsIpcSecurity.test.ts
@@ -0,0 +1,127 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ ipcOn: vi.fn(),
+ ipcHandle: vi.fn(),
+ allWindows: [] as Array<unknown>,
+ trustedRead: vi.fn(),
+ trustedReadWindow: vi.fn(),
+ assertTrustedAppRendererEvent: vi.fn(),
+ readAppearanceSettings: vi.fn(),
+ readAppearanceSettingsState: vi.fn(),
+ writeAppearanceSettingsPatch: vi.fn(),
+ resetAppearanceSettings: vi.fn(),
+ updateAppearanceSettingsAtomic: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => mocks.allWindows },
+ ipcMain: { on: mocks.ipcOn, handle: mocks.ipcHandle },
+}));
+
+vi.mock('../appearance-settings-reader.js', () => ({
+ isTrustedAppearanceSettingsReadEvent: mocks.trustedRead,
+ isTrustedAppearanceSettingsReadWindow: mocks.trustedReadWindow,
+}));
+
+vi.mock('../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: mocks.assertTrustedAppRendererEvent,
+}));
+
+vi.mock('../appearance-settings-store.js', () => ({
+ readAppearanceSettings: mocks.readAppearanceSettings,
+ readAppearanceSettingsState: mocks.readAppearanceSettingsState,
+ writeAppearanceSettingsPatch: mocks.writeAppearanceSettingsPatch,
+ resetAppearanceSettings: mocks.resetAppearanceSettings,
+ updateAppearanceSettingsAtomic: mocks.updateAppearanceSettingsAtomic,
+}));
+
+import { registerAppearanceSettingsIpc } from '../appearance-settings-ipc.js';
+
+const persisted = {
+ uiFamily: 'Inter',
+ codeFamily: 'JetBrains Mono',
+ uiSize: 15,
+ codeSize: 14,
+ windowZoom: 1.1,
+};
+
+describe('appearance settings IPC authorization', () => {
+ beforeAll(() => {
+ registerAppearanceSettingsIpc();
+ });
+
+ beforeEach(() => {
+ mocks.allWindows.length = 0;
+ mocks.trustedRead.mockReset();
+ mocks.trustedReadWindow.mockReset().mockReturnValue(false);
+ mocks.assertTrustedAppRendererEvent.mockReset();
+ mocks.readAppearanceSettings.mockReset().mockReturnValue(persisted);
+ });
+
+ it('同步启动读取只向已授权的外观 reader 返回持久快照', () => {
+ const handler = mocks.ipcOn.mock.calls.find(
+ ([channel]) => channel === 'appearance-settings:get-sync',
+ )?.[1] as (event: { returnValue?: unknown }) => void;
+
+ mocks.trustedRead.mockReturnValue(true);
+ const trustedEvent: { returnValue?: unknown } = {};
+ handler(trustedEvent);
+ expect(trustedEvent.returnValue).toEqual(persisted);
+
+ mocks.trustedRead.mockReturnValue(false);
+ const untrustedEvent: { returnValue?: unknown } = {};
+ handler(untrustedEvent);
+ expect(untrustedEvent.returnValue).toBeNull();
+ });
+
+ it('异步读取和写通道继续使用 app-content 高权限断言', async () => {
+ const getHandler = mocks.ipcHandle.mock.calls.find(
+ ([channel]) => channel === 'appearance-settings:get',
+ )?.[1] as (event: unknown) => unknown;
+ const setHandler = mocks.ipcHandle.mock.calls.find(
+ ([channel]) => channel === 'appearance-settings:set-patch',
+ )?.[1] as (event: unknown, patch: unknown) => Promise<unknown>;
+ const resetHandler = mocks.ipcHandle.mock.calls.find(
+ ([channel]) => channel === 'appearance-settings:reset',
+ )?.[1] as (event: unknown) => Promise<unknown>;
+
+ mocks.readAppearanceSettingsState.mockReturnValue({ settings: persisted, overrides: {} });
+ mocks.writeAppearanceSettingsPatch.mockResolvedValue(persisted);
+ mocks.resetAppearanceSettings.mockResolvedValue(persisted);
+
+ const event = {};
+ getHandler(event);
+ await setHandler(event, { uiSize: 15 });
+ await resetHandler(event);
+
+ expect(mocks.assertTrustedAppRendererEvent).toHaveBeenCalledTimes(3);
+ expect(mocks.assertTrustedAppRendererEvent).toHaveBeenNthCalledWith(1, event);
+ expect(mocks.assertTrustedAppRendererEvent).toHaveBeenNthCalledWith(2, event);
+ expect(mocks.assertTrustedAppRendererEvent).toHaveBeenNthCalledWith(3, event);
+ });
+
+ it('外观变更广播也覆盖显式授权的 utility 窗口', async () => {
+ const setHandler = mocks.ipcHandle.mock.calls.find(
+ ([channel]) => channel === 'appearance-settings:set-patch',
+ )?.[1] as (event: unknown, patch: unknown) => Promise<unknown>;
+ const allowedSend = vi.fn();
+ const deniedSend = vi.fn();
+ const allowed = {
+ isDestroyed: () => false,
+ webContents: { isDestroyed: () => false, send: allowedSend },
+ };
+ const denied = {
+ isDestroyed: () => false,
+ webContents: { isDestroyed: () => false, send: deniedSend },
+ };
+ mocks.allWindows.push(allowed, denied);
+ mocks.trustedReadWindow.mockImplementation((win) => win === allowed);
+ mocks.writeAppearanceSettingsPatch.mockResolvedValue(persisted);
+
+ await setHandler({}, { uiSize: 15 });
+
+ expect(allowedSend).toHaveBeenCalledWith('appearance-settings:changed', persisted);
+ expect(deniedSend).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/appearanceSettingsReader.test.ts b/apps/desktop/src/main/__tests__/appearanceSettingsReader.test.ts
new file mode 100644
index 0000000000..5dca952657
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/appearanceSettingsReader.test.ts
@@ -0,0 +1,76 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ fromWebContents: vi.fn(),
+ trustedTopLevel: vi.fn(),
+ trustedWindow: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: mocks.fromWebContents },
+}));
+
+vi.mock('../security/trustedAppRenderer.js', () => ({
+ isTrustedCindyRendererWindow: mocks.trustedWindow,
+ isTrustedTopLevelCindyRendererEvent: mocks.trustedTopLevel,
+}));
+
+import {
+ isTrustedAppearanceSettingsReadEvent,
+ isTrustedAppearanceSettingsReadWindow,
+ markAppearanceSettingsReaderWindow,
+} from '../appearance-settings-reader.js';
+import { isAppContentWindow, markAppContentWindow } from '../windowFocusClassifier.js';
+
+function fakeWindow(destroyed = false) {
+ return { isDestroyed: () => destroyed } as never;
+}
+
+describe('appearance settings reader authorization', () => {
+ beforeEach(() => {
+ mocks.fromWebContents.mockReset();
+ mocks.trustedTopLevel.mockReset().mockReturnValue(true);
+ mocks.trustedWindow.mockReset().mockReturnValue(true);
+ });
+
+ it('允许 app-content 窗口读取启动快照', () => {
+ const win = fakeWindow();
+ markAppContentWindow(win);
+ mocks.fromWebContents.mockReturnValue(win);
+
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(true);
+ });
+
+ it('只允许显式登记的 utility 窗口读取,且不提升为 app-content', () => {
+ const registered = fakeWindow();
+ markAppearanceSettingsReaderWindow(registered);
+ mocks.fromWebContents.mockReturnValue(registered);
+
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(true);
+ expect(isAppContentWindow(registered)).toBe(false);
+ expect(isTrustedAppearanceSettingsReadWindow(registered)).toBe(true);
+
+ mocks.fromWebContents.mockReturnValue(fakeWindow());
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(false);
+ });
+
+ it('拒绝非可信页面、无法归属窗口和已销毁窗口', () => {
+ const destroyed = fakeWindow(true);
+ markAppearanceSettingsReaderWindow(destroyed);
+ mocks.fromWebContents.mockReturnValue(destroyed);
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(false);
+
+ mocks.fromWebContents.mockReturnValue(null);
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(false);
+
+ mocks.trustedTopLevel.mockReturnValue(false);
+ const registered = fakeWindow();
+ markAppearanceSettingsReaderWindow(registered);
+ mocks.fromWebContents.mockReturnValue(registered);
+ expect(isTrustedAppearanceSettingsReadEvent({ sender: {} } as never)).toBe(false);
+
+ mocks.trustedTopLevel.mockReturnValue(true);
+ mocks.trustedWindow.mockReturnValue(false);
+ expect(isTrustedAppearanceSettingsReadWindow(registered)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
new file mode 100644
index 0000000000..9f3ba51a58
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
@@ -0,0 +1,41 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+function readMainSource(relativePath: string): string {
+ return readFileSync(resolve(__dirname, '..', relativePath), 'utf8');
+}
+
+function expectBefore(source: string, registration: string, load: string): void {
+ const registrationIndex = source.indexOf(registration);
+ const loadIndex = source.indexOf(load, registrationIndex);
+ expect(registrationIndex).toBeGreaterThanOrEqual(0);
+ expect(loadIndex).toBeGreaterThan(registrationIndex);
+}
+
+describe('utility window appearance bootstrap registration', () => {
+ it('权限引导的 backdrop 与 guide 在加载 renderer 前登记只读权限', () => {
+ const source = readMainSource('computer-permission-guide/window.ts');
+ expectBefore(
+ source,
+ 'markAppearanceSettingsReaderWindow(backdrop)',
+ 'loadPermissionView(backdrop',
+ );
+ expectBefore(source, 'markAppearanceSettingsReaderWindow(guide)', 'loadPermissionView(guide');
+ });
+
+ it('语音浮窗与词典 toast 在加载 renderer 前登记只读权限', () => {
+ const source = readMainSource('voice-input/global.ts');
+ expectBefore(source, 'markAppearanceSettingsReaderWindow(window)', 'window.loadURL(');
+ const toastFactory = source.slice(source.indexOf('function createDictionaryToastWindow'));
+ expectBefore(toastFactory, 'markAppearanceSettingsReaderWindow(window)', 'window.loadURL(');
+ });
+
+ it('utility renderer 订阅运行期外观变化并直接更新 CSS 字体变量', () => {
+ const source = readMainSource('../renderer/index.tsx');
+ expect(source).toContain('isAppearanceUtilityView');
+ expect(source).toContain('appearanceSettings?.onChanged?.(applyFontSettings)');
+ expect(source).toContain('import.meta.hot?.dispose(disposeUtilityAppearanceSettingsSync)');
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/appearanceZoomMenu.test.ts b/apps/desktop/src/main/__tests__/appearanceZoomMenu.test.ts
new file mode 100644
index 0000000000..20d40eac29
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/appearanceZoomMenu.test.ts
@@ -0,0 +1,29 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const bootstrapSource = readFileSync(resolve(__dirname, '..', 'bootstrap-electron.ts'), 'utf8');
+
+describe('persisted page zoom menu accelerators', () => {
+ it('keeps both macOS zoom-in accelerator paths', () => {
+ expect(bootstrapSource).toContain("'CommandOrControl+Plus'");
+ expect(bootstrapSource).toContain("accelerator: 'CommandOrControl+='");
+ expect(bootstrapSource).toContain('acceleratorWorksWhenHidden: true');
+ expect(bootstrapSource).toContain("id: 'persisted-page-zoom-in-unshifted'");
+ });
+
+ it('guards every persistent renderer zoom write with the app-content sender check', () => {
+ for (const channel of ['page-zoom:in', 'page-zoom:out', 'page-zoom:reset']) {
+ const start = bootstrapSource.indexOf(`ipcMain.handle('${channel}'`);
+ const end = bootstrapSource.indexOf('\n });', start);
+ const handler = bootstrapSource.slice(start, end);
+
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(handler).toContain('assertTrustedAppRendererEvent(event);');
+ expect(handler.indexOf('assertTrustedAppRendererEvent(event);')).toBeLessThan(
+ handler.indexOf('updatePersistedWindowZoom('),
+ );
+ expect(handler).not.toContain('mainWindowRef');
+ }
+ });
+});
diff --git a/apps/desktop/src/main/appearance-settings-ipc.ts b/apps/desktop/src/main/appearance-settings-ipc.ts
new file mode 100644
index 0000000000..e51ebe8a84
--- /dev/null
+++ b/apps/desktop/src/main/appearance-settings-ipc.ts
@@ -0,0 +1,170 @@
+import { BrowserWindow, ipcMain } from 'electron';
+
+import {
+ APPEARANCE_LIMITS,
+ clampAppearanceCodeSize,
+ clampAppearanceUiSize,
+ clampAppearanceWindowZoom,
+ type AppearanceOverrides,
+ type AppearanceSettings,
+} from '../shared/appearanceSettings.js';
+import {
+ isTrustedAppearanceSettingsReadEvent,
+ isTrustedAppearanceSettingsReadWindow,
+} from './appearance-settings-reader.js';
+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
+import { throwIpcError } from './utils/ipcValidate.js';
+import { isAppContentWindow } from './windowFocusClassifier.js';
+import {
+ readAppearanceSettings,
+ readAppearanceSettingsState,
+ resetAppearanceSettings,
+ updateAppearanceSettingsAtomic,
+ writeAppearanceSettingsPatch,
+} from './appearance-settings-store.js';
+
+export { writeAppearanceSettingsPatch } from './appearance-settings-store.js';
+
+export const APPEARANCE_SETTINGS_CHANGED_CHANNEL = 'appearance-settings:changed';
+
+let registered = false;
+
+export function registerAppearanceSettingsIpc(): void {
+ if (registered) return;
+ registered = true;
+
+ // Must be registered before BrowserWindow creation: preload reads this on
+ // the first synchronous bootstrap frame.
+ ipcMain.on('appearance-settings:get-sync', (event) => {
+ event.returnValue = isTrustedAppearanceSettingsReadEvent(event)
+ ? readAppearanceSettings()
+ : null;
+ });
+
+ ipcMain.handle('appearance-settings:get', (event) => {
+ assertTrustedAppRendererEvent(event);
+ return readAppearanceSettingsState();
+ });
+
+ ipcMain.handle('appearance-settings:set-patch', async (event, rawPatch: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const patch = parsePatch(rawPatch);
+ const settings = await writeAppearanceSettingsPatch(patch);
+ applyAppearanceToWindows(settings);
+ broadcast(settings);
+ return settings;
+ });
+
+ ipcMain.handle('appearance-settings:reset', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const settings = await resetAppearanceSettings();
+ applyAppearanceToWindows(settings);
+ broadcast(settings);
+ return settings;
+ });
+}
+
+export function applyAppearanceToWindow(
+ win: BrowserWindow,
+ settings: Pick<AppearanceSettings, 'windowZoom'> = readAppearanceSettings(),
+): void {
+ if (win.isDestroyed() || win.webContents.isDestroyed() || !isAppContentWindow(win)) return;
+ win.webContents.setZoomFactor(settings.windowZoom);
+}
+
+export function applyAppearanceToWindows(settings = readAppearanceSettings()): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ applyAppearanceToWindow(win, settings);
+ }
+}
+
+export function getPersistedWindowZoom(): number {
+ return readAppearanceSettings().windowZoom;
+}
+
+export async function updatePersistedWindowZoom(
+ delta: number | null,
+): Promise<AppearanceSettings> {
+ const settings = await updateAppearanceSettingsAtomic((current) => ({
+ windowZoom: clampAppearanceWindowZoom(
+ delta === null ? 1 : current.windowZoom + delta,
+ ),
+ }));
+ applyAppearanceToWindows(settings);
+ broadcast(settings);
+ return settings;
+}
+
+function broadcast(settings: AppearanceSettings): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!isTrustedAppearanceSettingsReadWindow(win)) continue;
+ try {
+ win.webContents.send(APPEARANCE_SETTINGS_CHANGED_CHANNEL, settings);
+ } catch {
+ // A window may be torn down between enumeration and send.
+ }
+ }
+}
+
+function parsePatch(rawPatch: unknown): AppearanceOverrides {
+ if (!rawPatch || typeof rawPatch !== 'object' || Array.isArray(rawPatch)) {
+ throwIpcError('INVALID_PARAMS', 'appearance patch must be an object');
+ }
+ const raw = rawPatch as Record<string, unknown>;
+ const allowed = new Set(['uiFamily', 'codeFamily', 'uiSize', 'codeSize', 'windowZoom']);
+ for (const key of Object.keys(raw)) {
+ if (!allowed.has(key)) throwIpcError('INVALID_PARAMS', `unknown appearance field: ${key}`);
+ }
+ const patch: AppearanceOverrides = {};
+ if ('uiFamily' in raw) patch.uiFamily = parseFamily(raw.uiFamily, 'uiFamily');
+ if ('codeFamily' in raw) patch.codeFamily = parseFamily(raw.codeFamily, 'codeFamily');
+ if ('uiSize' in raw)
+ patch.uiSize = parseNumber(
+ raw.uiSize,
+ 'uiSize',
+ clampAppearanceUiSize,
+ APPEARANCE_LIMITS.uiSize,
+ );
+ if ('codeSize' in raw)
+ patch.codeSize = parseNumber(
+ raw.codeSize,
+ 'codeSize',
+ clampAppearanceCodeSize,
+ APPEARANCE_LIMITS.codeSize,
+ );
+ if ('windowZoom' in raw) {
+ patch.windowZoom = parseNumber(
+ raw.windowZoom,
+ 'windowZoom',
+ clampAppearanceWindowZoom,
+ APPEARANCE_LIMITS.windowZoom,
+ );
+ }
+ return patch;
+}
+
+function parseFamily(value: unknown, name: string): string {
+ if (typeof value !== 'string' || value.length > 256) {
+ throwIpcError('INVALID_PARAMS', `${name} must be a string up to 256 characters`);
+ }
+ return value.trim();
+}
+
+function parseNumber(
+ value: unknown,
+ name: string,
+ clamp: (value: number) => number,
+ limits: { min: number; max: number },
+): number {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ throwIpcError('INVALID_PARAMS', `${name} must be a finite number`);
+ }
+ if (value < limits.min || value > limits.max) {
+ // Main owns clamping: accepting out-of-range values keeps the IPC stable
+ // for sliders and keyboard controls without allowing invalid disk state.
+ return clamp(value);
+ }
+ return clamp(value);
+}
+
+export const __testing = { parsePatch };
diff --git a/apps/desktop/src/main/appearance-settings-reader.ts b/apps/desktop/src/main/appearance-settings-reader.ts
new file mode 100644
index 0000000000..ede6142d55
--- /dev/null
+++ b/apps/desktop/src/main/appearance-settings-reader.ts
@@ -0,0 +1,44 @@
+/**
+ * 外观设置首帧快照的只读窗口登记表。
+ *
+ * Utility 窗口会加载 Cindy renderer 与共享 preload,但不应因此获得 app-content
+ * 的高权限 IPC。这里单独登记允许读取外观启动快照的窗口,避免扩大权限边界。
+ */
+
+import { BrowserWindow, type IpcMainEvent, type IpcMainInvokeEvent } from 'electron';
+
+import {
+ isTrustedCindyRendererWindow,
+ isTrustedTopLevelCindyRendererEvent,
+} from './security/trustedAppRenderer.js';
+import { isAppContentWindow } from './windowFocusClassifier.js';
+
+type AppearanceSettingsReadEvent = IpcMainEvent | IpcMainInvokeEvent;
+
+const appearanceSettingsReaderWindows = new WeakSet<BrowserWindow>();
+
+export function markAppearanceSettingsReaderWindow(win: BrowserWindow): void {
+ appearanceSettingsReaderWindows.add(win);
+}
+
+export function isTrustedAppearanceSettingsReadEvent(event: AppearanceSettingsReadEvent): boolean {
+ if (!isTrustedTopLevelCindyRendererEvent(event)) return false;
+ const win = BrowserWindow.fromWebContents(event.sender);
+ return isAppearanceSettingsReaderWindow(win);
+}
+
+export function isTrustedAppearanceSettingsReadWindow(
+ win: BrowserWindow | null | undefined,
+): win is BrowserWindow {
+ return isAppearanceSettingsReaderWindow(win) && isTrustedCindyRendererWindow(win);
+}
+
+function isAppearanceSettingsReaderWindow(
+ win: BrowserWindow | null | undefined,
+): win is BrowserWindow {
+ return Boolean(
+ win &&
+ !win.isDestroyed() &&
+ (isAppContentWindow(win) || appearanceSettingsReaderWindows.has(win)),
+ );
+}
diff --git a/apps/desktop/src/main/appearance-settings-store.ts b/apps/desktop/src/main/appearance-settings-store.ts
new file mode 100644
index 0000000000..f692a11f2a
--- /dev/null
+++ b/apps/desktop/src/main/appearance-settings-store.ts
@@ -0,0 +1,60 @@
+import { app } from 'electron';
+import path from 'node:path';
+
+import {
+ DEFAULT_APPEARANCE_SETTINGS,
+ normalizeAppearanceSettings,
+ type AppearanceOverrides,
+ type AppearanceSettings,
+} from '../shared/appearanceSettings.js';
+import { desktopMakerLogger } from './maker-host/logger-adapter.js';
+import {
+ createOverrideSettingsFile,
+ type OverrideSettingsState,
+} from './maker-host/override-settings-file.js';
+
+const log = desktopMakerLogger.child('appearance-settings-store');
+
+function settingsFilePath(): string {
+ return path.join(app.getPath('userData'), 'appearance-settings.json');
+}
+
+const store = createOverrideSettingsFile<AppearanceSettings>({
+ filePath: settingsFilePath,
+ defaults: DEFAULT_APPEARANCE_SETTINGS,
+ normalize: normalizeAppearanceSettings,
+ log,
+ label: 'appearance',
+ maxBytes: 16 * 1024,
+ preserveUnreadableFile: true,
+});
+
+export function readAppearanceSettings(): AppearanceSettings {
+ return store.read();
+}
+
+export function readAppearanceSettingsState(): OverrideSettingsState<AppearanceSettings> {
+ return store.readState();
+}
+
+export async function writeAppearanceSettingsPatch(
+ patch: AppearanceOverrides,
+): Promise<AppearanceSettings> {
+ await store.writePatchAtomic(patch);
+ return store.read();
+}
+
+export async function updateAppearanceSettingsAtomic(
+ updater: (current: AppearanceSettings) => AppearanceOverrides,
+): Promise<AppearanceSettings> {
+ return store.updateAtomic((current) => updater(current.value));
+}
+
+export async function resetAppearanceSettings(): Promise<AppearanceSettings> {
+ return store.resetAtomic();
+}
+
+export const __testing = {
+ normalize: normalizeAppearanceSettings,
+ settingsFilePath,
+};
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 5b78d5bfcf..a024efc748 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -163,7 +163,15 @@ import { RendererBootGuard } from './renderer-boot-guard';
import yaml from 'js-yaml';
import matter from 'gray-matter';
import type { Maker } from '@cindy/maker-core';
-import { im, feishuIm, telegramIm, registerTelegramBotConfigIpc, startImOrchestrators, startImConnection, stopImConnection } from './im';
+import {
+ im,
+ feishuIm,
+ telegramIm,
+ registerTelegramBotConfigIpc,
+ startImOrchestrators,
+ startImConnection,
+ stopImConnection,
+} from './im';
import { setTelegramRemoteSource } from './device-link/telegramRemoteControl';
import * as authManager from './authManager';
import { hasPersistedSessionHint } from './authSessionHint';
@@ -625,6 +633,13 @@ import {
initClientEndpoints,
registerClientEndpointsIpc,
} from './clientEndpointsService.js';
+import {
+ applyAppearanceToWindow,
+ applyAppearanceToWindows,
+ getPersistedWindowZoom,
+ registerAppearanceSettingsIpc,
+ updatePersistedWindowZoom,
+} from './appearance-settings-ipc.js';
import { registerBillingIpc } from './billing/index.js';
import {
initModelAccess,
@@ -675,10 +690,7 @@ import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-
import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';
-import {
- registerPluginMarketIpc,
- syncDefaultMarketPlugins,
-} from './plugin-market/registerIpc.js';
+import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';
import { findCindyFileInArgv } from './cindy-brain/argv.js';
import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';
import { registerCindyFileAssociation } from './cindy-brain/fileAssociation.js';
@@ -1335,6 +1347,7 @@ registerBrowserBackendIpc();
// renderer 启动同步拉 overrides、设置页写路径、changed 广播。顶层注册,
// ipcMain.handle 在 app ready 前注册也有效。
registerAppShortcutIpc();
+registerAppearanceSettingsIpc();
// ── 主界面布局树存储 IPC──────────────────────────────────────────────
// renderer 首帧 sendSync 拉布局(规则 7 无跳变)、set/reset 写路径、changed
@@ -1488,6 +1501,62 @@ function menuAcceleratorFor(id: AppShortcutId): string | undefined {
return comboToElectronAccelerator(first, process.platform) ?? undefined;
}
+function nativeMenuRoleLabel(role: 'resetZoom' | 'zoomIn' | 'zoomOut'): string {
+ try {
+ return Menu.buildFromTemplate([{ role }]).items[0]?.label ?? role;
+ } catch {
+ return role;
+ }
+}
+
+function persistedZoomMenuItem(
+ role: 'resetZoom' | 'zoomIn' | 'zoomOut',
+ delta: number | null,
+ registerAccelerator: boolean,
+): Electron.MenuItemConstructorOptions {
+ const accelerator =
+ role === 'resetZoom'
+ ? 'CommandOrControl+0'
+ : role === 'zoomIn'
+ ? 'CommandOrControl+Plus'
+ : 'CommandOrControl+-';
+ return {
+ label: nativeMenuRoleLabel(role),
+ accelerator,
+ registerAccelerator,
+ click: () => {
+ void updatePersistedWindowZoom(delta).catch((error: unknown) => {
+ createLogger('appearance-settings-menu').error('persisted page zoom update failed', {
+ role,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ },
+ };
+}
+
+function persistedZoomMenuItems(
+ role: 'resetZoom' | 'zoomIn' | 'zoomOut',
+ delta: number | null,
+ registerAccelerator: boolean,
+): Electron.MenuItemConstructorOptions[] {
+ const item = persistedZoomMenuItem(role, delta, registerAccelerator);
+ if (process.platform !== 'darwin' || role !== 'zoomIn') return [item];
+
+ // macOS treats ⌘= (unshifted Equal) and ⇧⌘= (Plus) as separate accelerator
+ // paths. Keep the second path registered while leaving one visible menu item.
+ return [
+ item,
+ {
+ ...item,
+ id: 'persisted-page-zoom-in-unshifted',
+ accelerator: 'CommandOrControl+=',
+ visible: false,
+ acceleratorWorksWhenHidden: true,
+ },
+ ];
+}
+
function installApplicationMenu(
mainWindow: BrowserWindow,
locale: ApplicationMenuLocale = getPreferredApplicationLocale(),
@@ -1521,9 +1590,9 @@ function installApplicationMenu(
submenu: [
toggleSidebarItem,
{ type: 'separator' },
- { role: 'resetZoom', registerAccelerator: registerMenuAccelerators },
- { role: 'zoomIn', registerAccelerator: registerMenuAccelerators },
- { role: 'zoomOut', registerAccelerator: registerMenuAccelerators },
+ ...persistedZoomMenuItems('resetZoom', null, registerMenuAccelerators),
+ ...persistedZoomMenuItems('zoomIn', PAGE_ZOOM_FACTOR_STEP, registerMenuAccelerators),
+ ...persistedZoomMenuItems('zoomOut', -PAGE_ZOOM_FACTOR_STEP, registerMenuAccelerators),
{ type: 'separator' },
{ role: 'togglefullscreen', registerAccelerator: registerMenuAccelerators },
],
@@ -1537,9 +1606,9 @@ function installApplicationMenu(
{ role: 'forceReload', registerAccelerator: registerMenuAccelerators },
{ role: 'toggleDevTools', registerAccelerator: registerMenuAccelerators },
{ type: 'separator' },
- { role: 'resetZoom', registerAccelerator: registerMenuAccelerators },
- { role: 'zoomIn', registerAccelerator: registerMenuAccelerators },
- { role: 'zoomOut', registerAccelerator: registerMenuAccelerators },
+ ...persistedZoomMenuItems('resetZoom', null, registerMenuAccelerators),
+ ...persistedZoomMenuItems('zoomIn', PAGE_ZOOM_FACTOR_STEP, registerMenuAccelerators),
+ ...persistedZoomMenuItems('zoomOut', -PAGE_ZOOM_FACTOR_STEP, registerMenuAccelerators),
{ type: 'separator' },
{ role: 'togglefullscreen', registerAccelerator: registerMenuAccelerators },
],
@@ -1746,10 +1815,9 @@ let mainWindowBackgroundThrottlingAllowed = true;
const isUpdateRelaunchCandidate =
process.platform === 'darwin' && isMacOSUpdateRelaunch(process.argv);
let updatePresentationRecoveryInitialized = false;
-const PAGE_ZOOM_LEVEL_MIN = -3;
-const PAGE_ZOOM_LEVEL_MAX = 3;
-const PAGE_ZOOM_LEVEL_STEP = 0.5;
-const pageZoomLevels = new WeakMap<BrowserWindow, number>();
+const PAGE_ZOOM_FACTOR_MIN = 0.5;
+const PAGE_ZOOM_FACTOR_MAX = 3;
+const PAGE_ZOOM_FACTOR_STEP = 0.1;
const updatePresentationRecovery = isUpdateRelaunchCandidate
? createUpdatePresentationRecoveryController({
@@ -2119,27 +2187,21 @@ function focusMainWindow(): boolean {
return true;
}
-function roundPageZoomLevel(level: number): number {
- return Math.round(level / PAGE_ZOOM_LEVEL_STEP) * PAGE_ZOOM_LEVEL_STEP;
-}
-
-function clampPageZoomLevel(level: number): number {
- return Math.min(PAGE_ZOOM_LEVEL_MAX, Math.max(PAGE_ZOOM_LEVEL_MIN, roundPageZoomLevel(level)));
-}
-
-function getPageZoomLevel(mainWindow: BrowserWindow): number {
- return pageZoomLevels.get(mainWindow) ?? 0;
+function roundPageZoomFactor(factor: number): number {
+ return Math.round(factor / PAGE_ZOOM_FACTOR_STEP) * PAGE_ZOOM_FACTOR_STEP;
}
-function applyPageZoomLevel(mainWindow: BrowserWindow, nextLevel: number): number {
- const zoomLevel = clampPageZoomLevel(nextLevel);
- pageZoomLevels.set(mainWindow, zoomLevel);
- mainWindow.webContents.setZoomLevel(zoomLevel);
- return zoomLevel;
+function clampPageZoomFactor(factor: number): number {
+ return Math.min(
+ PAGE_ZOOM_FACTOR_MAX,
+ Math.max(PAGE_ZOOM_FACTOR_MIN, roundPageZoomFactor(factor)),
+ );
}
-function adjustPageZoomLevel(mainWindow: BrowserWindow, delta: number): number {
- return applyPageZoomLevel(mainWindow, getPageZoomLevel(mainWindow) + delta);
+function applyPageZoomLevel(mainWindow: BrowserWindow, nextFactor: number): number {
+ const zoomFactor = clampPageZoomFactor(nextFactor);
+ applyAppearanceToWindow(mainWindow, { windowZoom: zoomFactor });
+ return zoomFactor;
}
// ── Custom URL scheme (cindy://... + 历史 xdt-maker://...) ───────────────
@@ -2402,14 +2464,17 @@ const createWindow = () => {
installWindowResponsivenessDiagnostics(mainWindow, { label: 'main' });
mainWindowRef = mainWindow;
applyMainWindowBackgroundThrottling();
- applyPageZoomLevel(mainWindow, 0);
+ applyPageZoomLevel(mainWindow, getPersistedWindowZoom());
+ mainWindow.webContents.on('did-finish-load', () => {
+ if (mainWindow.isDestroyed()) return;
+ applyPageZoomLevel(mainWindow, getPersistedWindowZoom());
+ });
// Deep link 模块持有同一个 mainWindow 引用 — 解析出的 URL 通过 webContents.send
// 推给 renderer (channel 'deep-link:navigate')。关窗时同步清空, 避免给已销毁
// 的 BrowserWindow 发 IPC 触发 'Object has been destroyed'。
setDeepLinkMainWindow(mainWindow);
mainWindow.once('closed', () => {
if (mainWindowRef === mainWindow) mainWindowRef = null;
- pageZoomLevels.delete(mainWindow);
setDeepLinkMainWindow(null);
});
// Main-window close policy is explicit because hidden utility windows (for
@@ -2873,13 +2938,16 @@ const registerIpcHandlers = () => {
!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey;
return applyCodexSpawnConfigChangeWithRestart(async () => {
if (!stillValid()) {
- throwIpcError('PRECONDITION_FAILED', 'app session changed during codex restart; write dropped');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'app session changed during codex restart; write dropped',
+ );
}
writeSubagentModelSettingsPatch(parsed);
return subagentModelSettingsWire();
- // stillValid 同时传给执行体:busy 路径 persist 与登记之间还有一个 await 边界,
- // 该窗口内 owner boundary 清掉旧登记后,本请求不得再 schedule(codex review
- // P1 第 3 轮)。
+ // stillValid 同时传给执行体:busy 路径 persist 与登记之间还有一个 await 边界,
+ // 该窗口内 owner boundary 清掉旧登记后,本请求不得再 schedule(codex review
+ // P1 第 3 轮)。
}, stillValid);
});
ipcMain.handle(MAKER_IPC_INVOKE.SUBAGENT_MODEL_SETTINGS_RESET, async (event) => {
@@ -2900,7 +2968,10 @@ const registerIpcHandlers = () => {
!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey;
return applyCodexSpawnConfigChangeWithRestart(async () => {
if (!stillValid()) {
- throwIpcError('PRECONDITION_FAILED', 'app session changed during codex restart; reset dropped');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'app session changed during codex restart; reset dropped',
+ );
}
resetSubagentModelSettings();
return subagentModelSettingsWire();
@@ -3238,34 +3309,28 @@ const registerIpcHandlers = () => {
ipcMain.on('window-close-self', (event) => {
BrowserWindow.fromWebContents(event.sender)?.close();
});
- ipcMain.handle('page-zoom:in', (event) => {
- const targetWindow = BrowserWindow.fromWebContents(event.sender) ?? mainWindowRef;
- if (!targetWindow || targetWindow.isDestroyed()) {
- return { ok: true as const, zoomLevel: 0 };
- }
+ ipcMain.handle('page-zoom:in', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const settings = await updatePersistedWindowZoom(PAGE_ZOOM_FACTOR_STEP);
return {
ok: true as const,
- zoomLevel: adjustPageZoomLevel(targetWindow, PAGE_ZOOM_LEVEL_STEP),
+ zoomFactor: settings.windowZoom,
};
});
- ipcMain.handle('page-zoom:out', (event) => {
- const targetWindow = BrowserWindow.fromWebContents(event.sender) ?? mainWindowRef;
- if (!targetWindow || targetWindow.isDestroyed()) {
- return { ok: true as const, zoomLevel: 0 };
- }
+ ipcMain.handle('page-zoom:out', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const settings = await updatePersistedWindowZoom(-PAGE_ZOOM_FACTOR_STEP);
return {
ok: true as const,
- zoomLevel: adjustPageZoomLevel(targetWindow, -PAGE_ZOOM_LEVEL_STEP),
+ zoomFactor: settings.windowZoom,
};
});
- ipcMain.handle('page-zoom:reset', (event) => {
- const targetWindow = BrowserWindow.fromWebContents(event.sender) ?? mainWindowRef;
- if (!targetWindow || targetWindow.isDestroyed()) {
- return { ok: true as const, zoomLevel: 0 };
- }
+ ipcMain.handle('page-zoom:reset', async (event) => {
+ assertTrustedAppRendererEvent(event);
+ const settings = await updatePersistedWindowZoom(null);
return {
ok: true as const,
- zoomLevel: applyPageZoomLevel(targetWindow, 0),
+ zoomFactor: settings.windowZoom,
};
});
@@ -3560,7 +3625,11 @@ const registerIpcHandlers = () => {
// 向所有窗口广播 PROVIDER_CHANGED:useProviders 依赖此消息刷新连接态快照(多窗口同步)。
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
- try { win.webContents.send(MAKER_PUSH.PROVIDER_CHANGED, {}); } catch { /* no-op */ }
+ try {
+ win.webContents.send(MAKER_PUSH.PROVIDER_CHANGED, {});
+ } catch {
+ /* no-op */
+ }
}
}
};
@@ -3726,7 +3795,11 @@ const registerIpcHandlers = () => {
ipcMain.handle(
'builtin-api-key-store',
- async (event: Electron.IpcMainInvokeEvent, providerId: unknown, value: unknown): Promise<void> => {
+ async (
+ event: Electron.IpcMainInvokeEvent,
+ providerId: unknown,
+ value: unknown,
+ ): Promise<void> => {
assertTrustedAppRendererEvent(event);
builtinApiKeyStore(builtinApiKeyDeps, providerId, value);
},
@@ -4270,9 +4343,10 @@ const registerIpcHandlers = () => {
broadcastFailure: false,
signal: piInstallSignal,
});
- piInfo = piRes.ready && piRes.path
- ? { status: 'passed' as const, path: piRes.path }
- : { status: 'failed' as const, error: piRes.error ?? 'pi binary not available' };
+ piInfo =
+ piRes.ready && piRes.path
+ ? { status: 'passed' as const, path: piRes.path }
+ : { status: 'failed' as const, error: piRes.error ?? 'pi binary not available' };
} catch (err: unknown) {
piInfo = {
status: 'failed' as const,
@@ -4331,9 +4405,8 @@ const registerIpcHandlers = () => {
// ChatGPT Desktop 当前注册 `codex:` 协议(macOS bundle id com.openai.codex;
// Windows 安装包也由系统协议注册表接管)。独立无参 IPC 保持最小权限,不能借此
// 打开 renderer 提供的任意自定义 scheme / deep link。
- ipcMain.handle(
- 'shell:open-chatgpt-app',
- async (event): Promise<{ success: boolean }> => handleOpenChatGPTApp(event, {
+ ipcMain.handle('shell:open-chatgpt-app', async (event): Promise<{ success: boolean }> =>
+ handleOpenChatGPTApp(event, {
assertTrustedSender: assertTrustedAppRendererEvent,
openExternal: (url) => shell.openExternal(url),
}),
@@ -4714,23 +4787,24 @@ const registerIpcHandlers = () => {
const params = requireObject(payload);
const defaultPathValue = params.defaultPath;
if (
- defaultPathValue !== undefined
- && (
- typeof defaultPathValue !== 'string'
- || defaultPathValue.length > 4096
- || !path.isAbsolute(defaultPathValue)
- )
+ defaultPathValue !== undefined &&
+ (typeof defaultPathValue !== 'string' ||
+ defaultPathValue.length > 4096 ||
+ !path.isAbsolute(defaultPathValue))
) {
throwIpcError('INVALID_PARAMS', 'defaultPath must be an absolute path');
}
const owner = BrowserWindow.fromWebContents(event.sender);
if (!owner) return { success: true, path: null, kind: null };
try {
- const picked = await pickNativeAtResource({
- platform: process.platform,
- showOpenDialog: (options) => dialog.showOpenDialog(owner, options),
- isDirectory: (selectedPath) => fs.statSync(selectedPath).isDirectory(),
- }, defaultPathValue);
+ const picked = await pickNativeAtResource(
+ {
+ platform: process.platform,
+ showOpenDialog: (options) => dialog.showOpenDialog(owner, options),
+ isDirectory: (selectedPath) => fs.statSync(selectedPath).isDirectory(),
+ },
+ defaultPathValue,
+ );
return { success: true, ...picked };
} catch {
throwIpcError('INTERNAL', 'unable to open resource picker');
@@ -5111,7 +5185,7 @@ const registerIpcHandlers = () => {
filePath,
hasUrlState,
fallback: hasUrlState
- ? openFileUrlWithWindowsHandler
+ ? openFileUrlWithWindowsHandler
? 'windows-url-handler'
: 'disabled'
: 'openPath',
@@ -5224,26 +5298,23 @@ const registerIpcHandlers = () => {
return stageChatAttachment(params);
},
);
- ipcMain.handle(
- 'chat-attachment:cleanup',
- async (event, filePaths: readonly string[]) => {
- assertTrustedAppRendererEvent(event);
- if (!Array.isArray(filePaths)) return;
- const ownerScopeKey = activeOwnerScopeKey();
- const ownerId = getActiveAppSession().dataOwnerId;
- if (!ownerId || isAppSessionBoundaryPending()) return;
- const protectedPaths = await listPersistedChatAttachmentPaths();
- const isCurrentOwner = () =>
- activeOwnerScopeKey() === ownerScopeKey && !isAppSessionBoundaryPending();
- if (!isCurrentOwner()) return;
- await cleanupOwnedUnpersistedStagedChatAttachments({
- ownerId,
- filePaths,
- protectedPaths,
- canRemove: isCurrentOwner,
- });
- },
- );
+ ipcMain.handle('chat-attachment:cleanup', async (event, filePaths: readonly string[]) => {
+ assertTrustedAppRendererEvent(event);
+ if (!Array.isArray(filePaths)) return;
+ const ownerScopeKey = activeOwnerScopeKey();
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (!ownerId || isAppSessionBoundaryPending()) return;
+ const protectedPaths = await listPersistedChatAttachmentPaths();
+ const isCurrentOwner = () =>
+ activeOwnerScopeKey() === ownerScopeKey && !isAppSessionBoundaryPending();
+ if (!isCurrentOwner()) return;
+ await cleanupOwnedUnpersistedStagedChatAttachments({
+ ownerId,
+ filePaths,
+ protectedPaths,
+ canRemove: isCurrentOwner,
+ });
+ });
ipcMain.handle(
'chat-attachment:save-as',
(event, params: { sourcePath?: unknown; suggestedName?: unknown }) => {
@@ -6015,9 +6086,8 @@ app.on('ready', async () => {
// Provider discovery is detached from DB read readiness for the same owner, but a
// different owner must not replace the DB while the previous account task can still
// update owner-scoped catalogs or agent environments.
- const previousProviderTaskSettled = await accountProviderReadinessBarrier.waitForPreviousScope(
- activeOwnerScopeKey(),
- );
+ const previousProviderTaskSettled =
+ await accountProviderReadinessBarrier.waitForPreviousScope(activeOwnerScopeKey());
// The old task may have completed its owner-scoped DB read after teardown cleared the
// process-global catalog. Clear once more after joining it so a failed next-owner reload
// cannot inherit the old endpoint/model snapshot. Same-scope ensure retries skip this.
@@ -6172,9 +6242,7 @@ app.on('ready', async () => {
});
}
await refreshCustomProvidersIntoCatalog(
- () =>
- activeOwnerScopeKey() === providerScopeKey &&
- !isAppSessionBoundaryPending(),
+ () => activeOwnerScopeKey() === providerScopeKey && !isAppSessionBoundaryPending(),
);
await refreshProviderModelsAfterAccountReady({
restartCodex: restartCodexAfterAuthModeChange,
diff --git a/apps/desktop/src/main/computer-permission-guide/window.ts b/apps/desktop/src/main/computer-permission-guide/window.ts
index e81fd89be8..b1f1b9c7be 100644
--- a/apps/desktop/src/main/computer-permission-guide/window.ts
+++ b/apps/desktop/src/main/computer-permission-guide/window.ts
@@ -18,6 +18,7 @@ import {
} from 'electron';
import type { Rectangle, WebContents } from 'electron';
+import { markAppearanceSettingsReaderWindow } from '../appearance-settings-reader.js';
import { scheduleMainAppPresenceRestore } from '../appPresence.js';
import { getResolvedMainLocale } from '../i18n.js';
import { createLogger } from '../logger.js';
@@ -937,6 +938,7 @@ export async function showComputerPermissionGuideWindow(
spellcheck: false,
},
});
+ markAppearanceSettingsReaderWindow(backdrop);
backdropWindow = backdrop;
backdrop.setIgnoreMouseEvents(true, { forward: true });
preventPermissionGuideNavigation(backdrop.webContents);
@@ -1006,6 +1008,7 @@ export async function showComputerPermissionGuideWindow(
spellcheck: false,
},
});
+ markAppearanceSettingsReaderWindow(guide);
guideWindow = guide;
preventPermissionGuideNavigation(guide.webContents);
guide.webContents.once('did-finish-load', () => {
diff --git a/apps/desktop/src/main/ghost-panel-window/window.ts b/apps/desktop/src/main/ghost-panel-window/window.ts
index 0b55e49202..248a01eec0 100644
--- a/apps/desktop/src/main/ghost-panel-window/window.ts
+++ b/apps/desktop/src/main/ghost-panel-window/window.ts
@@ -21,6 +21,7 @@ import { markAppContentWindow } from '../windowFocusClassifier.js';
import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js';
import { installExternalLinkGuards } from '../secondary-windows.js';
import { installSelectionContextMenu } from '../selection-context-menu.js';
+import { applyAppearanceToWindow } from '../appearance-settings-ipc.js';
const log = createLogger('ghost-panel-window');
@@ -74,6 +75,11 @@ export function createGhostPanelWindow(ghostId: string, title: string): BrowserW
},
});
markAppContentWindow(win);
+ applyAppearanceToWindow(win);
+ win.webContents.on('did-finish-load', () => {
+ if (win.isDestroyed()) return;
+ applyAppearanceToWindow(win);
+ });
installSelectionContextMenu(win);
windowState.manage(win);
diff --git a/apps/desktop/src/main/maker-host/override-settings-file.ts b/apps/desktop/src/main/maker-host/override-settings-file.ts
index edc21433e2..d5affba960 100644
--- a/apps/desktop/src/main/maker-host/override-settings-file.ts
+++ b/apps/desktop/src/main/maker-host/override-settings-file.ts
@@ -20,6 +20,11 @@ export interface OverrideSettingsFile<T> {
writePatch(patch: Partial<T>, options?: { preserveDefaults?: boolean }): void;
/** 跨进程锁内强制现读盘上 overrides,再合并 patch 并原子替换文件。 */
writePatchAtomic(patch: Partial<T>, options?: { preserveDefaults?: boolean }): Promise<void>;
+ /** 在同一把跨进程锁内基于最新磁盘快照计算并写入 patch。 */
+ updateAtomic(
+ updater: (current: OverrideSettingsState<T>) => Partial<T>,
+ options?: { preserveDefaults?: boolean },
+ ): Promise<T>;
reset(): T;
/** 跨进程锁内删除 override 文件。 */
resetAtomic(): Promise<T>;
@@ -187,6 +192,33 @@ export function createOverrideSettingsFile<T>(options: {
);
}
+ async function updateAtomic(
+ updater: (current: OverrideSettingsState<T>) => Partial<T>,
+ writeOptions?: { preserveDefaults?: boolean },
+ ): Promise<T> {
+ const file = options.filePath();
+ const scopeKey = options.scopeKey?.();
+ fs.mkdirSync(pathDirname(file), { recursive: true });
+ return withCrossProcessLock(
+ `${file}.lock`,
+ { label: `${options.label}-settings`, waitMs: 12_000 },
+ async (status) => {
+ if (!status.held) {
+ throw new Error(`${options.label} settings are busy in another process`);
+ }
+ if (options.filePath() !== file || options.scopeKey?.() !== scopeKey) {
+ throw new Error(
+ `${options.label} settings scope changed while waiting for the write lock`,
+ );
+ }
+ invalidate();
+ const current = readState();
+ writePatch(updater(current), writeOptions);
+ return readState().value;
+ },
+ );
+ }
+
function writeOverrides(overrides: Record<string, unknown>): void {
if (Object.keys(overrides).length === 0) {
reset();
@@ -261,6 +293,7 @@ export function createOverrideSettingsFile<T>(options: {
readState,
writePatch,
writePatchAtomic,
+ updateAtomic,
reset,
resetAtomic,
invalidateIfChanged,
diff --git a/apps/desktop/src/main/right-sidebar-window/window.ts b/apps/desktop/src/main/right-sidebar-window/window.ts
index b2f6f80617..fe75baccc8 100644
--- a/apps/desktop/src/main/right-sidebar-window/window.ts
+++ b/apps/desktop/src/main/right-sidebar-window/window.ts
@@ -19,6 +19,7 @@ import { markAppContentWindow } from '../windowFocusClassifier.js';
import { readWindowBehaviorSettings } from '../window-behavior-settings-store.js';
import { installExternalLinkGuards } from '../secondary-windows.js';
import { installSelectionContextMenu } from '../selection-context-menu.js';
+import { applyAppearanceToWindow } from '../appearance-settings-ipc.js';
const log = createLogger('right-sidebar-window');
@@ -73,6 +74,11 @@ export function createRightSidebarWindow(
},
});
markAppContentWindow(win);
+ applyAppearanceToWindow(win);
+ win.webContents.on('did-finish-load', () => {
+ if (win.isDestroyed()) return;
+ applyAppearanceToWindow(win);
+ });
installSelectionContextMenu(win);
windowState.manage(win);
diff --git a/apps/desktop/src/main/secondary-windows.ts b/apps/desktop/src/main/secondary-windows.ts
index fa18fb9049..3716f8aed8 100644
--- a/apps/desktop/src/main/secondary-windows.ts
+++ b/apps/desktop/src/main/secondary-windows.ts
@@ -25,6 +25,7 @@ import { markAppContentWindow } from './windowFocusClassifier.js';
import { readWindowBehaviorSettings } from './window-behavior-settings-store.js';
import { resolveVibrancyConfig, type WindowsBackdropMaterial } from './vibrancyConfig.js';
import { installSelectionContextMenu } from './selection-context-menu.js';
+import { applyAppearanceToWindow } from './appearance-settings-ipc.js';
const log = createLogger('secondary-windows');
@@ -79,10 +80,7 @@ export function installExternalLinkGuards(win: BrowserWindow): void {
* 新开一个完整应用窗口并定位到指定 session。
* @param mainWindow 主窗口,用来取当前 bounds 作为新窗初始大小(右下错开);可为 null。
*/
-export function openSessionInNewWindow(
- sessionId: string,
- mainWindow: BrowserWindow | null,
-): void {
+export function openSessionInNewWindow(sessionId: string, mainWindow: BrowserWindow | null): void {
// frame 配置复刻主窗(bootstrap-electron.ts createWindow): Mac 隐藏标题栏留红绿灯,
// Windows 无边框 + 自绘标题栏。
const platformOptions =
@@ -120,11 +118,18 @@ export function openSessionInNewWindow(
},
});
markAppContentWindow(win);
+ applyAppearanceToWindow(win);
+ win.webContents.on('did-finish-load', () => {
+ if (win.isDestroyed()) return;
+ applyAppearanceToWindow(win);
+ });
installNewMakerWindowShortcut(win);
installSelectionContextMenu(win);
// E4D:副窗加入 set,供 vibrancy 动态开关;关闭时移除。
secondaryWindows.add(win);
- win.once('closed', () => { secondaryWindows.delete(win); });
+ win.once('closed', () => {
+ secondaryWindows.delete(win);
+ });
installExternalLinkGuards(win);
@@ -147,10 +152,10 @@ export function openSessionInNewWindow(
url.hash = hash;
void win.loadURL(url.toString());
} else {
- void win.loadFile(
- path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
- { query: { secondaryWindow: '1', bootSession: sessionId }, hash },
- );
+ void win.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`), {
+ query: { secondaryWindow: '1', bootSession: sessionId },
+ hash,
+ });
}
log.info('opened session in new window', { sessionId });
diff --git a/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts b/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
index a552f5ad5a..5690c39733 100644
--- a/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
+++ b/apps/desktop/src/main/security/__tests__/trustedAppRenderer.test.ts
@@ -18,6 +18,8 @@ import {
isTrustedAppRendererEventForLocation,
isTrustedAppRendererUrl,
isTrustedAppRendererWindowForLocation,
+ isTrustedCindyRendererWindowForLocation,
+ isTrustedTopLevelCindyRendererEventForLocation,
} from '../trustedAppRenderer';
const packagedRendererFile = path.resolve('/Applications/Cindy/resources/app/renderer/index.html');
@@ -54,6 +56,28 @@ describe('trustedAppRenderer · URL', () => {
});
describe('trustedAppRenderer · sender frame', () => {
+ it('URL-only 顶层判据接受同源 utility renderer,但仍拒绝子 frame 与外部地址', () => {
+ electronMocks.fromWebContents.mockReturnValue({ isDestroyed: () => false });
+ const utilityEvent = fakeEvent(pathToFileURL(packagedRendererFile).toString());
+
+ expect(
+ isTrustedTopLevelCindyRendererEventForLocation(utilityEvent, packagedOptions),
+ ).toBe(true);
+ expect(isTrustedAppRendererEventForLocation(utilityEvent, packagedOptions)).toBe(false);
+ expect(
+ isTrustedTopLevelCindyRendererEventForLocation(
+ fakeEvent(pathToFileURL(packagedRendererFile).toString(), { child: true }),
+ packagedOptions,
+ ),
+ ).toBe(false);
+ expect(
+ isTrustedTopLevelCindyRendererEventForLocation(
+ fakeEvent('https://attacker.example/'),
+ packagedOptions,
+ ),
+ ).toBe(false);
+ });
+
it('登记过的 Cindy 窗口顶层 frame 才通过', () => {
const win = { isDestroyed: () => false };
markAppContentWindow(win as never);
@@ -94,7 +118,16 @@ describe('trustedAppRenderer · sender frame', () => {
*/
describe('trustedAppRenderer · 窗口级判据(出站推送用)', () => {
const fakeWindow = (url: string) =>
- ({ isDestroyed: () => false, webContents: { mainFrame: { url } } }) as never;
+ ({
+ isDestroyed: () => false,
+ webContents: { isDestroyed: () => false, mainFrame: { url } },
+ }) as never;
+
+ it('URL-only 判据允许 Cindy utility 窗口,但不把它视为 app-content', () => {
+ const utility = fakeWindow(pathToFileURL(packagedRendererFile).toString());
+ expect(isTrustedCindyRendererWindowForLocation(utility, packagedOptions)).toBe(true);
+ expect(isTrustedAppRendererWindowForLocation(utility, packagedOptions)).toBe(false);
+ });
it('登记过且停在 renderer 页的窗口才可收推送', () => {
const win = fakeWindow(pathToFileURL(packagedRendererFile).toString());
@@ -114,7 +147,10 @@ describe('trustedAppRenderer · 窗口级判据(出站推送用)', () => {
const destroyed = {
isDestroyed: () => true,
- webContents: { mainFrame: { url: pathToFileURL(packagedRendererFile).toString() } },
+ webContents: {
+ isDestroyed: () => false,
+ mainFrame: { url: pathToFileURL(packagedRendererFile).toString() },
+ },
} as never;
markAppContentWindow(destroyed);
expect(isTrustedAppRendererWindowForLocation(destroyed, packagedOptions)).toBe(false);
diff --git a/apps/desktop/src/main/security/trustedAppRenderer.ts b/apps/desktop/src/main/security/trustedAppRenderer.ts
index 8613f48398..58af5345b5 100644
--- a/apps/desktop/src/main/security/trustedAppRenderer.ts
+++ b/apps/desktop/src/main/security/trustedAppRenderer.ts
@@ -55,16 +55,35 @@ export function isTrustedAppRendererEvent(event: MainIpcEvent): boolean {
return isTrustedAppRendererEventForLocation(event, currentRendererUrlOptions());
}
+/**
+ * 判断 IPC 是否来自 Cindy 自有 renderer 地址的顶层页面。
+ *
+ * 该判据不要求窗口登记为 app-content,只能与具体能力的 Main 侧窗口登记表组合使用。
+ * 禁止单独用于文件、进程、凭证、持久化写入或其它特权能力。
+ */
+export function isTrustedTopLevelCindyRendererEvent(event: MainIpcEvent): boolean {
+ return isTrustedTopLevelCindyRendererEventForLocation(event, currentRendererUrlOptions());
+}
+
/** 与生产判定相同,但允许测试显式传入 renderer 地址。 */
-export function isTrustedAppRendererEventForLocation(
+export function isTrustedTopLevelCindyRendererEventForLocation(
event: MainIpcEvent,
options: TrustedRendererUrlOptions,
): boolean {
const frame = event.senderFrame;
if (!frame || frame !== event.sender.mainFrame || frame.parent !== null) return false;
+ return isTrustedAppRendererUrl(frame.url, options);
+}
+
+/** 与生产判定相同,但允许测试显式传入 renderer 地址。 */
+export function isTrustedAppRendererEventForLocation(
+ event: MainIpcEvent,
+ options: TrustedRendererUrlOptions,
+): boolean {
+ if (!isTrustedTopLevelCindyRendererEventForLocation(event, options)) return false;
const win = BrowserWindow.fromWebContents(event.sender);
if (!isAppContentWindow(win)) return false;
- return isTrustedAppRendererUrl(frame.url, options);
+ return true;
}
/**
@@ -79,17 +98,31 @@ export function isTrustedAppRendererWindow(win: BrowserWindow | null | undefined
return isTrustedAppRendererWindowForLocation(win, currentRendererUrlOptions());
}
+/** 判断窗口当前是否仍加载 Cindy 自有 renderer,不包含 app-content 身份授权。 */
+export function isTrustedCindyRendererWindow(win: BrowserWindow | null | undefined): boolean {
+ return isTrustedCindyRendererWindowForLocation(win, currentRendererUrlOptions());
+}
+
/** 与生产判定相同,但允许测试显式传入 renderer 地址。 */
-export function isTrustedAppRendererWindowForLocation(
+export function isTrustedCindyRendererWindowForLocation(
win: BrowserWindow | null | undefined,
options: TrustedRendererUrlOptions,
): boolean {
- if (!isAppContentWindow(win)) return false;
+ if (!win || win.isDestroyed() || win.webContents.isDestroyed()) return false;
const frame = win.webContents.mainFrame;
if (!frame) return false;
return isTrustedAppRendererUrl(frame.url, options);
}
+/** 与生产判定相同,但允许测试显式传入 renderer 地址。 */
+export function isTrustedAppRendererWindowForLocation(
+ win: BrowserWindow | null | undefined,
+ options: TrustedRendererUrlOptions,
+): boolean {
+ if (!isAppContentWindow(win)) return false;
+ return isTrustedCindyRendererWindowForLocation(win, options);
+}
+
/** 高权限 IPC 的统一断言;失败时不泄露真实允许地址。 */
export function assertTrustedAppRendererEvent(event: MainIpcEvent): void {
if (!isTrustedAppRendererEvent(event)) {
diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.ts
index 56f5f66e97..abbf968164 100644
--- a/apps/desktop/src/main/voice-input/global.ts
+++ b/apps/desktop/src/main/voice-input/global.ts
@@ -17,6 +17,7 @@ import {
type DictationDictionaryAdviceInput,
} from '@cindy/voice-input-core';
+import { markAppearanceSettingsReaderWindow } from '../appearance-settings-reader.js';
import { createLogger } from '../logger.js';
import { scheduleMainAppPresenceRestore } from '../appPresence.js';
import { openMainWindowVoiceSettings } from '../deepLink.js';
@@ -2116,6 +2117,7 @@ function createOverlayWindow(shortcutInvokedAt: number): BrowserWindow {
},
});
+ markAppearanceSettingsReaderWindow(window);
overlayWindow = window;
overlayLoaded = false;
// 浮窗建窗即 backgroundThrottling:false(保住麦克风回调调度),它的 Renderer 也装了
@@ -2251,6 +2253,7 @@ function createDictionaryToastWindow(payload: DictionaryToastPayload): BrowserWi
},
});
+ markAppearanceSettingsReaderWindow(window);
window.once('closed', () => {
if (dictionaryToastWindow === window) dictionaryToastWindow = null;
if (dictionaryToastCloseTimer) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index d75bbf4d59..b0eaeda00c 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,5 +1,6 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
+import type { AppearanceSettings } from '../shared/appearanceSettings';
import {
AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL,
AGENT_ISLAND_PREVIEW_SOUND_CHANNEL,
@@ -601,6 +602,7 @@ const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:respo
const fanOutMakerDraftPrefApply = createIpcFanOut('maker:draft-pref:apply');
const fanOutMakerWorktreePrefApply = createIpcFanOut('maker:worktree-pref:apply');
const fanOutMakerSessionPrefApply = createIpcFanOut('maker:session-pref:apply');
+const fanOutAppearanceSettingsChanged = createIpcFanOut('appearance-settings:changed');
// 跨 Agent 迁移项的 wire 形态(同 main/cross-agent-convert/types.ts 的 MigrationItem,
// 但 preload 是单独编译单元,不便 import;renderer 真正消费在 vite-env.d.ts 重新声明)。
@@ -769,6 +771,10 @@ const clientEndpointsInfo = ipcRenderer.sendSync('client-endpoints:get-sync') as
websiteUrl: string;
};
+const appearanceSettingsInfo = ipcRenderer.sendSync(
+ 'appearance-settings:get-sync',
+) as AppearanceSettings | null;
+
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
osRelease: ipcRenderer.sendSync('get-os-release') as string,
@@ -798,10 +804,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
* catch 后兜底当作 false (那个阶段本来就不可能有 in-flight)。
*/
anySessionInTurn: (): Promise<boolean> => ipcRenderer.invoke('maker:any-session-in-turn'),
- pageZoomIn: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:in'),
- pageZoomOut: (): Promise<{ ok: true; zoomLevel: number }> => ipcRenderer.invoke('page-zoom:out'),
- pageZoomReset: (): Promise<{ ok: true; zoomLevel: number }> =>
+ pageZoomIn: (): Promise<{ ok: true; zoomFactor: number }> => ipcRenderer.invoke('page-zoom:in'),
+ pageZoomOut: (): Promise<{ ok: true; zoomFactor: number }> => ipcRenderer.invoke('page-zoom:out'),
+ pageZoomReset: (): Promise<{ ok: true; zoomFactor: number }> =>
ipcRenderer.invoke('page-zoom:reset'),
+ appearanceSettings: {
+ getSync: (): AppearanceSettings | null => appearanceSettingsInfo,
+ get: (): Promise<unknown> => ipcRenderer.invoke('appearance-settings:get'),
+ setPatch: (patch: Partial<AppearanceSettings>): Promise<AppearanceSettings> =>
+ ipcRenderer.invoke('appearance-settings:set-patch', patch),
+ reset: (): Promise<AppearanceSettings> => ipcRenderer.invoke('appearance-settings:reset'),
+ onChanged: fanOutAppearanceSettingsChanged,
+ },
onApplicationMenuCommand: (callback: (command: ApplicationMenuCommand) => void): (() => void) =>
fanOutApplicationMenuCommand((payload) => {
if (isApplicationMenuCommand(payload)) {
@@ -950,8 +964,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
clearUnread: (id: string, seenAt?: number): Promise<{ ok: boolean }> =>
ipcRenderer.invoke('ghosts:clear-unread', id, seenAt),
/** 配置就绪检查(插件页「使用」前置门;main 现查凭证/账号/连接/kv)。 */
- setupStatus: (id: string): Promise<unknown> =>
- ipcRenderer.invoke('ghosts:setup-status', id),
+ setupStatus: (id: string): Promise<unknown> => ipcRenderer.invoke('ghosts:setup-status', id),
install: (
lizFilePath: string,
opts: { enable?: boolean; expectedPackageSha256: string },
diff --git a/apps/desktop/src/renderer/__tests__/compactComposerTypography.test.ts b/apps/desktop/src/renderer/__tests__/compactComposerTypography.test.ts
new file mode 100644
index 0000000000..ca9d369805
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/compactComposerTypography.test.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+const globalsSource = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');
+
+describe('compact composer typography', () => {
+ it('scales named text size line heights with the UI font settings', () => {
+ const compactComposerBlock = globalsSource.match(
+ /\.chat-rail-compact \[data-chat-input-root\][\s\S]*?\/\* Tiptap ChatInput/,
+ )?.[0];
+ expect(compactComposerBlock).toBeDefined();
+
+ for (const token of ['xs', 'sm', 'base', 'lg']) {
+ expect(compactComposerBlock).toContain(`line-height: var(--text-${token}-line-height);`);
+ }
+ expect(compactComposerBlock).not.toMatch(/line-height:\s*1(?:rem|\.25rem|\.5rem|\.75rem);/);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/fontSettings.test.ts b/apps/desktop/src/renderer/__tests__/fontSettings.test.ts
index 4a963c3d28..b1f3875ea7 100644
--- a/apps/desktop/src/renderer/__tests__/fontSettings.test.ts
+++ b/apps/desktop/src/renderer/__tests__/fontSettings.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
-import { beforeEach, describe, expect, it } from 'vitest';
-import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import {
@@ -16,33 +16,21 @@ import {
} from '@/hooks/useFontSettings';
function resetRootStyles() {
- document.documentElement.style.removeProperty('--app-font-ui');
- document.documentElement.style.removeProperty('--app-font-code');
- document.documentElement.style.removeProperty('--app-code-font-size');
- document.documentElement.style.removeProperty('--app-ui-font-size');
- for (const tokenSize of [
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 16,
- 17,
- 18,
- 19,
- 20,
- 21,
- 22,
- 23,
- 24,
- 25,
- 26,
- 27,
- 28,
- ]) {
- document.documentElement.style.removeProperty(`--text-${tokenSize}`);
+ const targets = [document.documentElement, document.body];
+ for (const target of targets) {
+ target.style.removeProperty('--app-font-ui');
+ target.style.removeProperty('--app-font-code');
+ target.style.removeProperty('--app-code-font-size');
+ target.style.removeProperty('--app-ui-font-size');
+ for (const tokenSize of [
+ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
+ ]) {
+ target.style.removeProperty(`--text-${tokenSize}`);
+ }
+ for (const token of ['xs', 'sm', 'base', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl']) {
+ target.style.removeProperty(`--text-${token}`);
+ target.style.removeProperty(`--text-${token}-line-height`);
+ }
}
}
@@ -61,17 +49,17 @@ describe('font settings', () => {
});
});
- it('falls back when stored font sizes are invalid', () => {
+ it('ignores legacy renderer storage after the clean cut-over', () => {
localStorage.setItem('font.uiFamily', ' "Segoe UI" ');
localStorage.setItem('font.codeFamily', ' Consolas ');
localStorage.setItem('font.uiSize', 'not-a-number');
localStorage.setItem('font.codeSize', '99');
expect(getInitialFontSettings()).toEqual({
- uiFamily: '"Segoe UI"',
- codeFamily: 'Consolas',
+ uiFamily: '',
+ codeFamily: '',
uiSize: DEFAULT_UI_FONT_SIZE,
- codeSize: 24,
+ codeSize: DEFAULT_CODE_FONT_SIZE,
});
});
@@ -101,6 +89,10 @@ describe('font settings', () => {
'Consolas, var(--app-font-code-default)',
);
expect(rootStyle.getPropertyValue('--app-code-font-size')).toBe('16px');
+ expect(document.body.style.getPropertyValue('--app-font-ui')).toBe(
+ '"Segoe UI", var(--app-font-ui-default)',
+ );
+ expect(document.body.style.getPropertyValue('--app-code-font-size')).toBe('16px');
});
it('writes UI font-size tokens with the default scale', () => {
@@ -116,29 +108,12 @@ describe('font settings', () => {
const rootStyle = document.documentElement.style;
expect(rootStyle.getPropertyValue('--app-ui-font-size')).toBe(`${DEFAULT_UI_FONT_SIZE}px`);
for (const tokenSize of [
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 16,
- 17,
- 18,
- 19,
- 20,
- 21,
- 22,
- 23,
- 24,
- 25,
- 26,
- 27,
- 28,
+ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
]) {
expect(rootStyle.getPropertyValue(`--text-${tokenSize}`)).toBe(`${tokenSize}px`);
}
+ expect(rootStyle.getPropertyValue('--text-sm-line-height')).toBe('20px');
+ expect(document.body.style.getPropertyValue('--text-sm-line-height')).toBe('20px');
});
it('scales UI font-size tokens from uiSize', () => {
@@ -154,31 +129,14 @@ describe('font settings', () => {
const rootStyle = document.documentElement.style;
expect(rootStyle.getPropertyValue('--app-ui-font-size')).toBe('18px');
for (const tokenSize of [
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 16,
- 17,
- 18,
- 19,
- 20,
- 21,
- 22,
- 23,
- 24,
- 25,
- 26,
- 27,
- 28,
+ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
]) {
expect(rootStyle.getPropertyValue(`--text-${tokenSize}`)).toBe(
`${Math.round((tokenSize * 18) / DEFAULT_UI_FONT_SIZE)}px`,
);
}
+ expect(rootStyle.getPropertyValue('--text-sm-line-height')).toBe('26px');
+ expect(document.body.style.getPropertyValue('--text-sm-line-height')).toBe('26px');
});
it('removes font overrides and keeps code size clamped', () => {
@@ -196,6 +154,8 @@ describe('font settings', () => {
expect(rootStyle.getPropertyValue('--app-font-ui')).toBe('');
expect(rootStyle.getPropertyValue('--app-font-code')).toBe('');
expect(rootStyle.getPropertyValue('--app-code-font-size')).toBe(`${DEFAULT_CODE_FONT_SIZE}px`);
+ expect(document.body.style.getPropertyValue('--app-font-ui')).toBe('');
+ expect(document.body.style.getPropertyValue('--app-font-code')).toBe('');
});
it('resets UI font size to the default', () => {
@@ -207,7 +167,7 @@ describe('font settings', () => {
result.current.setUiSize(18);
});
expect(result.current.uiSize).toBe(18);
- expect(localStorage.getItem('font.uiSize')).toBe('18');
+ expect(localStorage.getItem('font.uiSize')).toBeNull();
act(() => {
result.current.resetUiSize();
@@ -216,4 +176,66 @@ describe('font settings', () => {
expect(result.current.uiSize).toBe(DEFAULT_UI_FONT_SIZE);
expect(localStorage.getItem('font.uiSize')).toBeNull();
});
+
+ it('keeps newer optimistic font updates when an older main snapshot arrives', async () => {
+ let onChanged:
+ | ((settings: {
+ uiFamily: string;
+ codeFamily: string;
+ uiSize: number;
+ codeSize: number;
+ windowZoom: number;
+ }) => void)
+ | undefined;
+ const setPatch = vi.fn(() => new Promise<void>(() => undefined));
+ const originalElectronApi = window.electronAPI;
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ appearanceSettings: {
+ getSync: () => ({
+ uiFamily: '',
+ codeFamily: '',
+ uiSize: DEFAULT_UI_FONT_SIZE,
+ codeSize: DEFAULT_CODE_FONT_SIZE,
+ windowZoom: 1,
+ }),
+ setPatch,
+ onChanged: (callback: typeof onChanged) => {
+ onChanged = callback;
+ return () => undefined;
+ },
+ },
+ },
+ });
+
+ try {
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(FontSettingsProvider, null, children);
+ const { result } = renderHook(() => useFontSettings(), { wrapper });
+
+ act(() => {
+ result.current.setUiSize(16);
+ result.current.setUiSize(18);
+ });
+ expect(result.current.uiSize).toBe(18);
+ await waitFor(() => expect(setPatch).toHaveBeenCalledTimes(1));
+
+ act(() => {
+ onChanged?.({
+ uiFamily: '',
+ codeFamily: '',
+ uiSize: 16,
+ codeSize: DEFAULT_CODE_FONT_SIZE,
+ windowZoom: 1,
+ });
+ });
+ expect(result.current.uiSize).toBe(18);
+ } finally {
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: originalElectronApi,
+ });
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/hooks/useFontSettings.ts b/apps/desktop/src/renderer/hooks/useFontSettings.ts
index fe2168eecf..11b0e6a572 100644
--- a/apps/desktop/src/renderer/hooks/useFontSettings.ts
+++ b/apps/desktop/src/renderer/hooks/useFontSettings.ts
@@ -6,13 +6,22 @@ import {
useContext,
useEffect,
useMemo,
+ useRef,
useState,
} from 'react';
+import {
+ APPEARANCE_LIMITS,
+ DEFAULT_APPEARANCE_SETTINGS,
+ clampAppearanceCodeSize,
+ clampAppearanceUiSize,
+ normalizeAppearanceSettings,
+ type AppearanceSettings,
+} from '@/../shared/appearanceSettings';
+
export interface FontSettings {
uiFamily: string;
codeFamily: string;
- // UI size applies through --app-ui-font-size and opt-in --text-N tokens.
uiSize: number;
codeSize: number;
}
@@ -28,44 +37,41 @@ interface FontSettingsContextValue extends FontSettings {
resetCodeSize: () => void;
}
-const UI_FAMILY_KEY = 'font.uiFamily';
-const CODE_FAMILY_KEY = 'font.codeFamily';
-const UI_SIZE_KEY = 'font.uiSize';
-const CODE_SIZE_KEY = 'font.codeSize';
+export const DEFAULT_UI_FONT_SIZE = DEFAULT_APPEARANCE_SETTINGS.uiSize;
+export const DEFAULT_CODE_FONT_SIZE = DEFAULT_APPEARANCE_SETTINGS.codeSize;
+const MIN_UI_FONT_SIZE = APPEARANCE_LIMITS.uiSize.min;
+const MIN_FONT_SIZE = APPEARANCE_LIMITS.codeSize.min;
+const MAX_FONT_SIZE = APPEARANCE_LIMITS.codeSize.max;
-export const DEFAULT_UI_FONT_SIZE = 14;
-export const DEFAULT_CODE_FONT_SIZE = 14;
-const MIN_UI_FONT_SIZE = 12;
-const MIN_FONT_SIZE = 10;
-const MAX_FONT_SIZE = 24;
const UI_TEXT_TOKEN_SIZES = [
- 9,
- 10,
- 11,
- 12,
- 13,
- 14,
- 15,
- 16,
- 17,
- 18,
- 19,
- 20,
- 21,
- 22,
- 23,
- 24,
- 25,
- 26,
- 27,
- 28,
+ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
] as const;
-const FontSettingsContext = createContext<FontSettingsContextValue | undefined>(undefined);
+const SCALED_TAILWIND_TOKENS = {
+ xs: 12,
+ sm: 14,
+ base: 16,
+ lg: 18,
+ xl: 20,
+ '2xl': 24,
+ '3xl': 30,
+ '4xl': 36,
+ '5xl': 48,
+} as const;
-function normalizeFamily(value: string): string {
- return value.trim();
-}
+const TAILWIND_LINE_HEIGHTS = {
+ xs: 16,
+ sm: 20,
+ base: 24,
+ lg: 28,
+ xl: 28,
+ '2xl': 32,
+ '3xl': 36,
+ '4xl': 40,
+ '5xl': 48,
+} as const;
+
+const FontSettingsContext = createContext<FontSettingsContextValue | undefined>(undefined);
export function clampFontSize(value: number, fallback = DEFAULT_CODE_FONT_SIZE): number {
if (!Number.isFinite(value)) return fallback;
@@ -74,74 +80,29 @@ export function clampFontSize(value: number, fallback = DEFAULT_CODE_FONT_SIZE):
export function clampUiFontSize(value: number, fallback = DEFAULT_UI_FONT_SIZE): number {
if (!Number.isFinite(value)) return fallback;
- return Math.min(MAX_FONT_SIZE, Math.max(MIN_UI_FONT_SIZE, Math.round(value)));
-}
-
-function getStoredString(key: string): string {
- try {
- return localStorage.getItem(key)?.trim() ?? '';
- } catch {
- return '';
- }
+ return Math.min(APPEARANCE_LIMITS.uiSize.max, Math.max(MIN_UI_FONT_SIZE, Math.round(value)));
}
-function getStoredSize(key: string, fallback: number): number {
- try {
- const raw = localStorage.getItem(key);
- if (raw == null || raw.trim() === '') return fallback;
- return clampFontSize(Number(raw), fallback);
- } catch {
- return fallback;
- }
-}
-
-function getStoredUiSize(key: string, fallback: number): number {
- try {
- const raw = localStorage.getItem(key);
- if (raw == null || raw.trim() === '') return fallback;
- return clampUiFontSize(Number(raw), fallback);
- } catch {
- return fallback;
- }
-}
-
-function setOrRemoveStorage(key: string, value: string): void {
- try {
- if (value) {
- localStorage.setItem(key, value);
- } else {
- localStorage.removeItem(key);
- }
- } catch {
- // localStorage may be unavailable
- }
+function normalizeFamily(value: string): string {
+ return value.trim().slice(0, 256);
}
-function setSizeStorage(key: string, value: number, fallback: number): void {
- try {
- if (value === fallback) {
- localStorage.removeItem(key);
- } else {
- localStorage.setItem(key, String(value));
- }
- } catch {
- // localStorage may be unavailable
- }
+function getBridge(): typeof window.electronAPI.appearanceSettings | null {
+ return window.electronAPI?.appearanceSettings ?? null;
}
-function withDefaultFallback(
- family: string,
- defaultVar: '--app-font-ui-default' | '--app-font-code-default',
-): string {
- return family ? `${family}, var(${defaultVar})` : '';
+export function getInitialAppearanceSettings(): AppearanceSettings {
+ const snapshot = getBridge()?.getSync?.();
+ return normalizeAppearanceSettings(snapshot ?? DEFAULT_APPEARANCE_SETTINGS);
}
export function getInitialFontSettings(): FontSettings {
+ const settings = getInitialAppearanceSettings();
return {
- uiFamily: getStoredString(UI_FAMILY_KEY),
- codeFamily: getStoredString(CODE_FAMILY_KEY),
- uiSize: getStoredUiSize(UI_SIZE_KEY, DEFAULT_UI_FONT_SIZE),
- codeSize: getStoredSize(CODE_SIZE_KEY, DEFAULT_CODE_FONT_SIZE),
+ uiFamily: settings.uiFamily,
+ codeFamily: settings.codeFamily,
+ uiSize: settings.uiSize,
+ codeSize: settings.codeSize,
};
}
@@ -149,62 +110,131 @@ export function applyFontSettings(settings: FontSettings): void {
const root = document.documentElement;
const uiFamily = normalizeFamily(settings.uiFamily);
const codeFamily = normalizeFamily(settings.codeFamily);
+ const uiSize = clampUiFontSize(settings.uiSize);
+ const codeSize = clampFontSize(settings.codeSize);
+ const scale = uiSize / DEFAULT_UI_FONT_SIZE;
+ const targets = [root, document.body].filter(Boolean);
- const uiValue = withDefaultFallback(uiFamily, '--app-font-ui-default');
- if (uiValue) {
- root.style.setProperty('--app-font-ui', uiValue);
- } else {
- root.style.removeProperty('--app-font-ui');
- }
+ const set = (name: string, value: string) => {
+ for (const target of targets) target.style.setProperty(name, value);
+ };
- const codeValue = withDefaultFallback(codeFamily, '--app-font-code-default');
- if (codeValue) {
- root.style.setProperty('--app-font-code', codeValue);
- } else {
- root.style.removeProperty('--app-font-code');
+ for (const target of targets) {
+ if (uiFamily) {
+ target.style.setProperty('--app-font-ui', `${uiFamily}, var(--app-font-ui-default)`);
+ } else {
+ target.style.removeProperty('--app-font-ui');
+ }
+ if (codeFamily) {
+ target.style.setProperty('--app-font-code', `${codeFamily}, var(--app-font-code-default)`);
+ } else {
+ target.style.removeProperty('--app-font-code');
+ }
}
+ set('--app-code-font-size', `${codeSize}px`);
+ set('--app-ui-font-size', `${uiSize}px`);
- root.style.setProperty('--app-code-font-size', `${clampFontSize(settings.codeSize)}px`);
-
- const uiSize = clampUiFontSize(settings.uiSize);
- const scale = uiSize / DEFAULT_UI_FONT_SIZE;
- root.style.setProperty('--app-ui-font-size', `${uiSize}px`);
for (const tokenSize of UI_TEXT_TOKEN_SIZES) {
- root.style.setProperty(`--text-${tokenSize}`, `${Math.round(tokenSize * scale)}px`);
+ set(`--text-${tokenSize}`, `${Math.round(tokenSize * scale)}px`);
+ }
+ for (const [token, base] of Object.entries(SCALED_TAILWIND_TOKENS)) {
+ set(`--text-${token}`, `${Math.round(base * scale)}px`);
+ }
+ for (const [token, base] of Object.entries(TAILWIND_LINE_HEIGHTS)) {
+ set(`--text-${token}-line-height`, `${Math.round(base * scale)}px`);
}
}
export function FontSettingsProvider({ children }: { children: ReactNode }) {
const [settings, setSettings] = useState<FontSettings>(getInitialFontSettings);
+ const settingsRef = useRef(settings);
+ const confirmedSettingsRef = useRef(settings);
+ const pendingWritesRef = useRef<Array<{ id: number; patch: Partial<FontSettings> }>>([]);
+ const writeQueueRef = useRef<Promise<void>>(Promise.resolve());
+ const nextRequestIdRef = useRef(0);
useEffect(() => {
applyFontSettings(settings);
}, [settings]);
- const setUiFamily = useCallback((family: string) => {
- const next = normalizeFamily(family);
- setOrRemoveStorage(UI_FAMILY_KEY, next);
- setSettings((prev) => ({ ...prev, uiFamily: next }));
- }, []);
-
- const setCodeFamily = useCallback((family: string) => {
- const next = normalizeFamily(family);
- setOrRemoveStorage(CODE_FAMILY_KEY, next);
- setSettings((prev) => ({ ...prev, codeFamily: next }));
- }, []);
-
- const setUiSize = useCallback((size: number) => {
- const next = clampUiFontSize(size, DEFAULT_UI_FONT_SIZE);
- setSizeStorage(UI_SIZE_KEY, next, DEFAULT_UI_FONT_SIZE);
- setSettings((prev) => ({ ...prev, uiSize: next }));
+ useEffect(() => {
+ const bridge = getBridge();
+ if (!bridge?.onChanged) return;
+ return bridge.onChanged((next: AppearanceSettings) => {
+ const normalized = normalizeAppearanceSettings(next);
+ const confirmed = {
+ uiFamily: normalized.uiFamily,
+ codeFamily: normalized.codeFamily,
+ uiSize: normalized.uiSize,
+ codeSize: normalized.codeSize,
+ };
+ confirmedSettingsRef.current = confirmed;
+ const optimistic = pendingWritesRef.current.reduce(
+ (current, pending) => ({ ...current, ...pending.patch }),
+ confirmed,
+ );
+ settingsRef.current = optimistic;
+ setSettings(optimistic);
+ });
}, []);
- const setCodeSize = useCallback((size: number) => {
- const next = clampFontSize(size, DEFAULT_CODE_FONT_SIZE);
- setSizeStorage(CODE_SIZE_KEY, next, DEFAULT_CODE_FONT_SIZE);
- setSettings((prev) => ({ ...prev, codeSize: next }));
+ const patch = useCallback((next: Partial<FontSettings>) => {
+ const previous = settingsRef.current;
+ const merged = { ...previous, ...next };
+ const bridge = getBridge();
+ if (!bridge) {
+ settingsRef.current = merged;
+ setSettings(merged);
+ return;
+ }
+ const requestId = nextRequestIdRef.current + 1;
+ nextRequestIdRef.current = requestId;
+ pendingWritesRef.current.push({ id: requestId, patch: next });
+ settingsRef.current = merged;
+ setSettings(merged);
+ writeQueueRef.current = writeQueueRef.current
+ .catch(() => undefined)
+ .then(async () => {
+ try {
+ await bridge.setPatch(next);
+ pendingWritesRef.current = pendingWritesRef.current.filter(
+ (pending) => pending.id !== requestId,
+ );
+ } catch (error: unknown) {
+ window.electronAPI?.logToMain?.(
+ 'error',
+ 'renderer/appearance-settings',
+ `appearance settings write failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ pendingWritesRef.current = pendingWritesRef.current.filter(
+ (pending) => pending.id !== requestId,
+ );
+ const optimistic = pendingWritesRef.current.reduce(
+ (current, pending) => ({ ...current, ...pending.patch }),
+ confirmedSettingsRef.current,
+ );
+ settingsRef.current = optimistic;
+ setSettings(optimistic);
+ }
+ });
}, []);
+ const setUiFamily = useCallback(
+ (family: string) => patch({ uiFamily: normalizeFamily(family) }),
+ [patch],
+ );
+ const setCodeFamily = useCallback(
+ (family: string) => patch({ codeFamily: normalizeFamily(family) }),
+ [patch],
+ );
+ const setUiSize = useCallback(
+ (size: number) => patch({ uiSize: clampAppearanceUiSize(size) }),
+ [patch],
+ );
+ const setCodeSize = useCallback(
+ (size: number) => patch({ codeSize: clampAppearanceCodeSize(size) }),
+ [patch],
+ );
const resetUiFamily = useCallback(() => setUiFamily(''), [setUiFamily]);
const resetCodeFamily = useCallback(() => setCodeFamily(''), [setCodeFamily]);
const resetUiSize = useCallback(() => setUiSize(DEFAULT_UI_FONT_SIZE), [setUiSize]);
diff --git a/apps/desktop/src/renderer/index.tsx b/apps/desktop/src/renderer/index.tsx
index ca83043e96..043e7bb4dc 100644
--- a/apps/desktop/src/renderer/index.tsx
+++ b/apps/desktop/src/renderer/index.tsx
@@ -81,6 +81,8 @@ const isVoiceInputDictionaryToast = view === 'voice-input-dictionary-toast';
const isComputerPermissionGuide = view === 'computer-permission-guide';
const isComputerPermissionBackdrop = view === 'computer-permission-backdrop';
const isComputerPermissionView = isComputerPermissionGuide || isComputerPermissionBackdrop;
+const isAppearanceUtilityView =
+ isVoiceInputOverlay || isVoiceInputDictionaryToast || isComputerPermissionView;
document.documentElement.dataset.platform = window.electronAPI.platform;
if (isVoiceInputOverlay || isVoiceInputDictionaryToast) {
document.documentElement.dataset.voiceInputOverlay = 'true';
@@ -131,6 +133,10 @@ if (import.meta.env.DEV) {
bootstrapLocalThemesSync();
themeService.applyTheme(getInitialThemeVariant().theme);
applyFontSettings(getInitialFontSettings());
+const disposeUtilityAppearanceSettingsSync = isAppearanceUtilityView
+ ? (window.electronAPI.appearanceSettings?.onChanged?.(applyFontSettings) ?? (() => {}))
+ : (): void => {};
+import.meta.hot?.dispose(disposeUtilityAppearanceSettingsSync);
const rootElement = document.getElementById('root');
if (!rootElement) {
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index 793601fa3d..adeae4ad96 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -25,6 +25,24 @@
收敛成统一 compact-delta 机制。 */
--app-code-font-size: 14px;
--app-ui-font-size: 14px;
+ --text-xs: 12px;
+ --text-sm: 14px;
+ --text-base: 16px;
+ --text-lg: 18px;
+ --text-xl: 20px;
+ --text-2xl: 24px;
+ --text-3xl: 30px;
+ --text-4xl: 36px;
+ --text-5xl: 48px;
+ --text-xs-line-height: 16px;
+ --text-sm-line-height: 20px;
+ --text-base-line-height: 24px;
+ --text-lg-line-height: 28px;
+ --text-xl-line-height: 28px;
+ --text-2xl-line-height: 32px;
+ --text-3xl-line-height: 36px;
+ --text-4xl-line-height: 40px;
+ --text-5xl-line-height: 48px;
--text-9: 9px;
--text-10: 10px;
--text-11: 11px;
@@ -199,6 +217,7 @@
同一行,出现"一个半角一个全角"。把 CJK 字体提前后,Inter 没覆盖的
CJK 标点直接落到 PingFang/YaHei,宽度统一。Latin 仍然走 Inter,无副作用。 */
font-family: var(--app-font-ui, var(--app-font-ui-default));
+ font-size: var(--text-base);
-webkit-font-smoothing: antialiased;
}
@@ -262,18 +281,18 @@ html:lang(ko) {
ChatInput 区域(data-chat-input-root)单独还原回默认字号,避免输入框
字号也跟着缩。 */
.chat-rail-compact .text-xs {
- font-size: 11px;
+ font-size: calc(var(--text-xs) - 1px);
}
.chat-rail-compact .text-sm {
- font-size: 13px;
+ font-size: calc(var(--text-sm) - 1px);
line-height: 1.4;
}
.chat-rail-compact .text-base {
- font-size: 15px;
+ font-size: calc(var(--text-base) - 1px);
line-height: 1.5;
}
.chat-rail-compact .text-lg {
- font-size: 17px;
+ font-size: calc(var(--text-lg) - 1px);
line-height: 1.5;
}
.chat-rail-compact .text-\[12px\] {
@@ -319,20 +338,20 @@ html:lang(ko) {
}
.chat-rail-compact [data-chat-input-root] .text-xs {
- font-size: 0.75rem;
- line-height: 1rem;
+ font-size: var(--text-xs);
+ line-height: var(--text-xs-line-height);
}
.chat-rail-compact [data-chat-input-root] .text-sm {
- font-size: 0.875rem;
- line-height: 1.25rem;
+ font-size: var(--text-sm);
+ line-height: var(--text-sm-line-height);
}
.chat-rail-compact [data-chat-input-root] .text-base {
- font-size: 1rem;
- line-height: 1.5rem;
+ font-size: var(--text-base);
+ line-height: var(--text-base-line-height);
}
.chat-rail-compact [data-chat-input-root] .text-lg {
- font-size: 1.125rem;
- line-height: 1.75rem;
+ font-size: var(--text-lg);
+ line-height: var(--text-lg-line-height);
}
.chat-rail-compact [data-chat-input-root] .text-\[12px\] {
font-size: 12px;
@@ -504,12 +523,8 @@ html:lang(ko) {
@font-face {
font-family: 'Cindy CJK Punctuation Local';
src:
- local('PingFang SC'),
- local('Hiragino Sans GB'),
- local('Microsoft YaHei UI'),
- local('Microsoft YaHei'),
- local('Noto Sans CJK SC'),
- local('Source Han Sans SC');
+ local('PingFang SC'), local('Hiragino Sans GB'), local('Microsoft YaHei UI'),
+ local('Microsoft YaHei'), local('Noto Sans CJK SC'), local('Source Han Sans SC');
font-style: normal;
font-weight: 400;
font-display: swap;
@@ -1088,7 +1103,9 @@ body.resizing-pane [data-ghost-webview] {
(✓ 复用 Done 语义的唯一批准 overshoot 曲线,同 status-done-pop)。
motion-reduce 下全部禁用,直接落终态帧。 */
.summon-seal-arc {
- transition: stroke-dasharray 600ms var(--motion-ease-out), opacity 600ms var(--motion-ease-out);
+ transition:
+ stroke-dasharray 600ms var(--motion-ease-out),
+ opacity 600ms var(--motion-ease-out);
}
@keyframes summon-seal-halo {
0% {
@@ -1726,7 +1743,7 @@ body.resizing-pane [data-ghost-webview] {
.doc-search-mark[data-active] → currently focused match (中黄实底 + 1px 琥珀内描边)
Color spec follows the GitHub Primer attention family. */
.doc-search-mark {
- background-color: #fff8c5; /* Primer attention-muted */
+ background-color: #fff8c5; /* Primer attention-muted */
color: inherit;
/* font / line-height 显式继承 —— <mark> 是 phrasing element,Chromium UA
默认不改字号,但跨主题 / 跨 reset 时把字体属性钉在 inherit 最稳,避免
@@ -1744,7 +1761,7 @@ body.resizing-pane [data-ghost-webview] {
box-shadow: inset 0 0 0 1px #d4a72c;
}
.dark .doc-search-mark {
- background-color: #362d1b; /* ≈ #bb8009 @ 15% on dark bg */
+ background-color: #362d1b; /* ≈ #bb8009 @ 15% on dark bg */
}
.dark .doc-search-mark[data-active] {
background-color: #9e6a03;
@@ -1910,23 +1927,49 @@ body.resizing-pane [data-ghost-webview] {
出现 = 面板收走 → 等 300ms → 圆圈渐显(160ms)→ 幽灵跳进来(240ms,回弹);
消失 = 幽灵跳走(160ms)→ 圆圈渐隐(120ms 延迟 + 140ms)→ 面板滑入。 */
@keyframes ghost-bubble-circle-in {
- from { transform: scale(0.85); opacity: 0; }
- to { transform: scale(1); opacity: 1; }
+ from {
+ transform: scale(0.85);
+ opacity: 0;
+ }
+ to {
+ transform: scale(1);
+ opacity: 1;
+ }
}
@keyframes ghost-bubble-circle-out {
- to { transform: scale(0.9); opacity: 0; }
+ to {
+ transform: scale(0.9);
+ opacity: 0;
+ }
}
@keyframes ghost-bubble-ghost-in {
- 0% { transform: translateY(12px) scale(0.4); opacity: 0; }
- 65% { transform: translateY(-4px) scale(1.08); opacity: 1; }
- 100% { transform: none; opacity: 1; }
+ 0% {
+ transform: translateY(12px) scale(0.4);
+ opacity: 0;
+ }
+ 65% {
+ transform: translateY(-4px) scale(1.08);
+ opacity: 1;
+ }
+ 100% {
+ transform: none;
+ opacity: 1;
+ }
}
@keyframes ghost-bubble-ghost-out {
- to { transform: translateY(-14px) scale(0.4); opacity: 0; }
+ to {
+ transform: translateY(-14px) scale(0.4);
+ opacity: 0;
+ }
}
@keyframes ghost-bubble-bob {
- 0%, 100% { transform: translateY(0); }
- 50% { transform: translateY(-3px); }
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-3px);
+ }
}
.ghost-bubble-enter .ghost-bubble-circle {
animation: ghost-bubble-circle-in 160ms ease-out 300ms backwards;
@@ -1948,11 +1991,23 @@ body.resizing-pane [data-ghost-webview] {
这是 §7 compositor-only 的窄例外(同登录 handoff 的容器形变口径):
一次性、有状态含义;内容层定实宽被外壳裁切,webview 不逐帧重排。
keyframes 缺省端取元素实宽(inline style),不用变量传宽。 */
-@keyframes ghost-panel-expand { from { width: 0; } }
-@keyframes ghost-panel-collapse { to { width: 0; } }
-.ghost-panel-enter { animation: ghost-panel-expand 200ms ease-out; }
+@keyframes ghost-panel-expand {
+ from {
+ width: 0;
+ }
+}
+@keyframes ghost-panel-collapse {
+ to {
+ width: 0;
+ }
+}
+.ghost-panel-enter {
+ animation: ghost-panel-expand 200ms ease-out;
+}
/* exit 在 enter 之后声明:出现瞬间就点收起时,后者整段覆盖前者。 */
-.ghost-panel-exit { animation: ghost-panel-collapse 180ms ease-in forwards; }
+.ghost-panel-exit {
+ animation: ghost-panel-collapse 180ms ease-in forwards;
+}
@media (prefers-reduced-motion: reduce) {
.ghost-bubble-enter .ghost-bubble-circle,
.ghost-bubble-enter .ghost-bubble-face-jump,
@@ -1960,5 +2015,7 @@ body.resizing-pane [data-ghost-webview] {
.ghost-bubble-exit .ghost-bubble-face-jump,
.ghost-panel-enter,
.ghost-panel-exit,
- .ghost-bubble:hover .ghost-bubble-face { animation: none; }
+ .ghost-bubble:hover .ghost-bubble-face {
+ animation: none;
+ }
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 56f88a7626..58b1059c53 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1060,9 +1060,20 @@ interface ElectronAPI {
* splash / login 阶段会 reject (handler 未注册), 调用方需 catch 兜底成 false。
*/
anySessionInTurn: () => Promise<boolean>;
- pageZoomIn: () => Promise<{ ok: true; zoomLevel: number }>;
- pageZoomOut: () => Promise<{ ok: true; zoomLevel: number }>;
- pageZoomReset: () => Promise<{ ok: true; zoomLevel: number }>;
+ pageZoomIn: () => Promise<{ ok: true; zoomFactor: number }>;
+ pageZoomOut: () => Promise<{ ok: true; zoomFactor: number }>;
+ pageZoomReset: () => Promise<{ ok: true; zoomFactor: number }>;
+ appearanceSettings: {
+ getSync: () => import('../shared/appearanceSettings').AppearanceSettings | null;
+ get: () => Promise<unknown>;
+ setPatch: (
+ patch: Partial<import('../shared/appearanceSettings').AppearanceSettings>,
+ ) => Promise<import('../shared/appearanceSettings').AppearanceSettings>;
+ reset: () => Promise<import('../shared/appearanceSettings').AppearanceSettings>;
+ onChanged: (
+ callback: (settings: import('../shared/appearanceSettings').AppearanceSettings) => void,
+ ) => () => void;
+ };
onApplicationMenuCommand: (callback: (command: ApplicationMenuCommand) => void) => () => void;
setApplicationMenuLocale: (locale: ApplicationMenuLocale) => Promise<{ ok: true }>;
billing: import('../shared/billing').BillingRendererApi;
@@ -1449,11 +1460,7 @@ interface ElectronAPI {
id?: string,
) => Promise<{ states?: Record<string, string>; state?: string }>;
/** dev-only:经正式插件派发/权限链调用一个已声明工具。 */
- devCall: (
- id: string,
- tool: string,
- args: Record<string, unknown>,
- ) => Promise<unknown>;
+ devCall: (id: string, tool: string, args: Record<string, unknown>) => Promise<unknown>;
};
/** Plugin Protocol v2 市场;网络、下载与安装全部在 main 进程完成。 */
@@ -1634,9 +1641,7 @@ interface ElectronAPI {
onGlobalOverlayCommand: (
callback: (command: { type: 'start' | 'submit' | 'cancel' }) => void,
) => () => void;
- adviseDictionaryLearning: (
- payload: VoiceInputDictionaryAdviceInput,
- ) => Promise<
+ adviseDictionaryLearning: (payload: VoiceInputDictionaryAdviceInput) => Promise<
| {
ok: true;
actions: VoiceInputDictionaryLearningAction[];
@@ -3802,11 +3807,14 @@ interface ElectronAPI {
// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──
// today aggregate 已搬到 electronAPI.maker.usage.* (Claude USD + Codex token 统一)。
onUsageSessionSpendChanged: (
- cb: (data: {
- sessionId: string;
- totalMoney: import('../shared/regionalMoney').RegionalMoney;
- totalCostUsd?: number;
- }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,
+ cb: (
+ data: {
+ sessionId: string;
+ totalMoney: import('../shared/regionalMoney').RegionalMoney;
+ totalCostUsd?: number;
+ },
+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => void,
) => () => void;
onUsageSessionTokensChanged: (
cb: (
@@ -3829,11 +3837,14 @@ interface ElectronAPI {
// per-message 维度: turn 结束检测到模型被上游降级 / 替换时 main 推标记
// (挂在该轮最后一条 assistant 上,AssistantMessage 渲染降级提示行)。
onUsageMessageModelMismatch: (
- cb: (data: {
- sessionId: string;
- clientId: string;
- modelMismatch: import('../shared/modelMismatch').ModelMismatchInfo;
- }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,
+ cb: (
+ data: {
+ sessionId: string;
+ clientId: string;
+ modelMismatch: import('../shared/modelMismatch').ModelMismatchInfo;
+ },
+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => void,
) => () => void;
// ── 首登轻量数据迁移(mToc) — 老 userData → Cindy 一次性复制迁移弹窗 ──
@@ -4072,7 +4083,9 @@ interface ElectronAPI {
getByLeadSession: (leadSessionId: string) => Promise<OrcaTeamRecord | null>;
getByWorkerSession: (workerSessionId: string) => Promise<OrcaTeamRecord | null>;
listWorkersByLead: (leadSessionId: string) => Promise<OrcaWorkerRecord[]>;
- listWorkersByLeads?: (leadSessionIds: string[]) => Promise<Record<string, OrcaWorkerRecord[]>>;
+ listWorkersByLeads?: (
+ leadSessionIds: string[],
+ ) => Promise<Record<string, OrcaWorkerRecord[]>>;
updateWorkerStatus: (
workerId: string,
status: 'idle' | 'running' | 'done' | 'error',
@@ -4139,10 +4152,13 @@ interface ElectronAPI {
clientId: string,
) => Promise<import('@/lib/ccAgent.types').Message>;
onCreated: (
- callback: (payload: {
- sessionId: string;
- message: import('@/lib/ccAgent.types').Message;
- }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,
+ callback: (
+ payload: {
+ sessionId: string;
+ message: import('@/lib/ccAgent.types').Message;
+ },
+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => void,
) => () => void;
onDeleted: (
callback: (
@@ -4165,10 +4181,13 @@ interface ElectronAPI {
) => void,
) => () => void;
onPatched: (
- callback: (payload: {
- sessionId: string;
- patch: Partial<import('@/lib/ccAgent.types').Session>;
- }, ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp) => void,
+ callback: (
+ payload: {
+ sessionId: string;
+ patch: Partial<import('@/lib/ccAgent.types').Session>;
+ },
+ ownerStamp?: import('../shared/dataOwnerPush').DataOwnerPushStamp,
+ ) => void,
) => () => void;
};
/** V0.4 (C10): one-shot toast trigger when ensureReady ran two-level fallback. */
@@ -4874,9 +4893,7 @@ interface ElectronAPI {
}) => Promise<void>;
/** 快照:某会话当前挂起交互(permission/ask/plan),打开/重连/刷新会话时拉一次重建面板。 */
- getPendingInteractions: (
- sessionId: string,
- ) => Promise<
+ getPendingInteractions: (sessionId: string) => Promise<
Array<{
request: { kind: string; requestId: string; [k: string]: unknown };
persistId?: string;
@@ -5060,9 +5077,7 @@ interface ElectronAPI {
defaultEnabled?: boolean;
}>;
/** Takes effect immediately for proxy recovery. */
- silentEncryptedRetrySet: (
- enabled: boolean,
- ) => Promise<{
+ silentEncryptedRetrySet: (enabled: boolean) => Promise<{
enabled: boolean;
isCustomized: boolean;
defaultEnabled: boolean;
@@ -5112,9 +5127,7 @@ interface ElectronAPI {
defaultAutoSnapshotEnabled: boolean;
}>;
/** 立即生效; Codex rewind 入口跟随此开关显示 */
- gitSafetySet: (
- enabled: boolean,
- ) => Promise<{
+ gitSafetySet: (enabled: boolean) => Promise<{
autoSnapshotEnabled: boolean;
isCustomized: boolean;
defaultAutoSnapshotEnabled: boolean;
@@ -5435,9 +5448,7 @@ interface ElectronAPI {
workingDir: string,
agentKind: 'claude-code' | 'codex' | 'pi',
) => Promise<{ items: CrossAgentMigrationItem[] }>;
- convert: (
- items: CrossAgentMigrationItem[],
- ) => Promise<{
+ convert: (items: CrossAgentMigrationItem[]) => Promise<{
total: number;
successCount: number;
skippedCount: number;
diff --git a/apps/desktop/src/shared/appearanceSettings.ts b/apps/desktop/src/shared/appearanceSettings.ts
new file mode 100644
index 0000000000..3c0a30f91f
--- /dev/null
+++ b/apps/desktop/src/shared/appearanceSettings.ts
@@ -0,0 +1,105 @@
+/**
+ * Desktop appearance preferences shared by main, preload and renderer.
+ *
+ * The persisted file contains only user overrides; callers normally consume
+ * the effective snapshot returned by main.
+ */
+
+export interface AppearanceOverrides {
+ uiFamily?: string;
+ codeFamily?: string;
+ uiSize?: number;
+ codeSize?: number;
+ windowZoom?: number;
+}
+
+export interface AppearanceSettings {
+ uiFamily: string;
+ codeFamily: string;
+ uiSize: number;
+ codeSize: number;
+ windowZoom: number;
+}
+
+export const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings = {
+ uiFamily: '',
+ codeFamily: '',
+ uiSize: 14,
+ codeSize: 14,
+ windowZoom: 1,
+};
+
+export const APPEARANCE_LIMITS = {
+ uiSize: { min: 12, max: 24 },
+ codeSize: { min: 10, max: 24 },
+ windowZoom: { min: 0.5, max: 3, step: 0.1 },
+} as const;
+
+export function clampAppearanceUiSize(
+ value: number,
+ fallback = DEFAULT_APPEARANCE_SETTINGS.uiSize,
+): number {
+ return clampInteger(value, APPEARANCE_LIMITS.uiSize.min, APPEARANCE_LIMITS.uiSize.max, fallback);
+}
+
+export function clampAppearanceCodeSize(
+ value: number,
+ fallback = DEFAULT_APPEARANCE_SETTINGS.codeSize,
+): number {
+ return clampInteger(
+ value,
+ APPEARANCE_LIMITS.codeSize.min,
+ APPEARANCE_LIMITS.codeSize.max,
+ fallback,
+ );
+}
+
+export function clampAppearanceWindowZoom(
+ value: number,
+ fallback = DEFAULT_APPEARANCE_SETTINGS.windowZoom,
+): number {
+ if (!Number.isFinite(value)) return fallback;
+ const stepped =
+ Math.round(value / APPEARANCE_LIMITS.windowZoom.step) * APPEARANCE_LIMITS.windowZoom.step;
+ return roundDecimal(
+ Math.min(APPEARANCE_LIMITS.windowZoom.max, Math.max(APPEARANCE_LIMITS.windowZoom.min, stepped)),
+ 2,
+ );
+}
+
+export function normalizeAppearanceSettings(raw: unknown): AppearanceSettings {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ...DEFAULT_APPEARANCE_SETTINGS };
+ }
+ const value = raw as Record<string, unknown>;
+ return {
+ uiFamily: normalizeFamily(value.uiFamily),
+ codeFamily: normalizeFamily(value.codeFamily),
+ uiSize:
+ typeof value.uiSize === 'number'
+ ? clampAppearanceUiSize(value.uiSize)
+ : DEFAULT_APPEARANCE_SETTINGS.uiSize,
+ codeSize:
+ typeof value.codeSize === 'number'
+ ? clampAppearanceCodeSize(value.codeSize)
+ : DEFAULT_APPEARANCE_SETTINGS.codeSize,
+ windowZoom:
+ typeof value.windowZoom === 'number'
+ ? clampAppearanceWindowZoom(value.windowZoom)
+ : DEFAULT_APPEARANCE_SETTINGS.windowZoom,
+ };
+}
+
+function normalizeFamily(value: unknown): string {
+ return typeof value === 'string' ? value.trim().slice(0, 256) : '';
+}
+
+function clampInteger(value: number, min: number, max: number, fallback: number): number {
+ if (!Number.isFinite(value)) return fallback;
+ return Math.min(max, Math.max(min, Math.round(value)));
+}
+
+function roundDecimal(value: number, places: number): number {
+ const factor = 10 ** places;
+ return Math.round(value * factor) / factor;
+}
diff --git a/apps/desktop/tailwind.config.ts b/apps/desktop/tailwind.config.ts
index ae128fddee..1d4c2ada96 100644
--- a/apps/desktop/tailwind.config.ts
+++ b/apps/desktop/tailwind.config.ts
@@ -58,6 +58,15 @@ const config: Config = {
mono: ['var(--app-font-code, var(--app-font-code-default))'],
},
fontSize: {
+ xs: ['var(--text-xs)', { lineHeight: 'var(--text-xs-line-height)' }],
+ sm: ['var(--text-sm)', { lineHeight: 'var(--text-sm-line-height)' }],
+ base: ['var(--text-base)', { lineHeight: 'var(--text-base-line-height)' }],
+ lg: ['var(--text-lg)', { lineHeight: 'var(--text-lg-line-height)' }],
+ xl: ['var(--text-xl)', { lineHeight: 'var(--text-xl-line-height)' }],
+ '2xl': ['var(--text-2xl)', { lineHeight: 'var(--text-2xl-line-height)' }],
+ '3xl': ['var(--text-3xl)', { lineHeight: 'var(--text-3xl-line-height)' }],
+ '4xl': ['var(--text-4xl)', { lineHeight: 'var(--text-4xl-line-height)' }],
+ '5xl': ['var(--text-5xl)', { lineHeight: 'var(--text-5xl-line-height)' }],
9: 'var(--text-9)',
10: 'var(--text-10)',
11: 'var(--text-11)',
@@ -123,8 +132,7 @@ const config: Config = {
animation: {
// 功能性 loading spinner 使用 DESIGN.md §14.4 明确登记的语义循环 token;
// 不复用 Tailwind animate-spin 的硬编码 1s,也不耦合 enter/exit 交互档位。
- spinner:
- 'spin var(--motion-spinner-cycle, 1000ms) linear infinite',
+ spinner: 'spin var(--motion-spinner-cycle, 1000ms) linear infinite',
// float-out 需要 forwards:Radix 等 animationend 才卸载,fill 不驻留
// 会在动画结束到卸载之间闪回原状。
'float-in':