Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(desktop): 优化 Acrylic 窗口缩放渲染 (#3188)

DavidShenXDadb363905ac6
diff --git a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
index 215f735039..b96ddbfe24 100644
--- a/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
+++ b/apps/desktop/src/main/__tests__/appearanceUtilityWindowRegistration.test.ts
@@ -37,5 +37,6 @@ describe('utility window appearance bootstrap registration', () => {
expect(source).toContain('isAppearanceUtilityView');
expect(source).toContain('appearanceSettings?.onChanged?.(applyFontSettings)');
expect(source).toContain('import.meta.hot?.dispose(disposeUtilityAppearanceSettingsSync)');
+ expect(source.match(/<ThemeProvider syncWindowVibrancy=\{false\}>/g)).toHaveLength(4);
});
});
diff --git a/apps/desktop/src/main/__tests__/resolved-app-theme.test.ts b/apps/desktop/src/main/__tests__/resolved-app-theme.test.ts
new file mode 100644
index 0000000000..50e2fb6c00
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/resolved-app-theme.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+describe('resolved app theme snapshot', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it('uses the persisted mode before the renderer reports its preference', async () => {
+ const { resolveAppThemeIsDark } = await import('../resolved-app-theme');
+
+ expect(resolveAppThemeIsDark(false)).toBe(false);
+ expect(resolveAppThemeIsDark(true)).toBe(true);
+ expect(resolveAppThemeIsDark(false, 'dark')).toBe(true);
+ expect(resolveAppThemeIsDark(true, 'light')).toBe(false);
+ expect(resolveAppThemeIsDark(false, 'light', true)).toBe(true);
+ expect(resolveAppThemeIsDark(true, 'dark', false)).toBe(false);
+ expect(resolveAppThemeIsDark(false, 'system', true)).toBe(false);
+ expect(resolveAppThemeIsDark(true, 'system', false)).toBe(true);
+ });
+
+ it('uses the latest renderer-resolved theme for windows created later', async () => {
+ const { rememberResolvedAppTheme, resolveAppThemeIsDark } = await import(
+ '../resolved-app-theme'
+ );
+
+ rememberResolvedAppTheme(true);
+ expect(resolveAppThemeIsDark(false)).toBe(true);
+
+ rememberResolvedAppTheme(false);
+ expect(resolveAppThemeIsDark(true)).toBe(false);
+ });
+
+ it('accepts only supported persisted modes', async () => {
+ const { isAppThemeMode } = await import('../resolved-app-theme');
+
+ expect(['system', 'light', 'dark'].every(isAppThemeMode)).toBe(true);
+ expect(isAppThemeMode('auto')).toBe(false);
+ expect(isAppThemeMode(null)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/vibrancyConfig.test.ts b/apps/desktop/src/main/__tests__/vibrancyConfig.test.ts
index a98222695d..1e865c85aa 100644
--- a/apps/desktop/src/main/__tests__/vibrancyConfig.test.ts
+++ b/apps/desktop/src/main/__tests__/vibrancyConfig.test.ts
@@ -71,14 +71,26 @@ describe('E4D resolveVibrancyConfig(familyId→vibrancy/backgroundColor 映射)'
}
});
- it('win32 × Win11 × CINDY:默认 acrylic + 透明底', () => {
+ it('win32 × Win11 × CINDY:默认 acrylic + 浅色侧栏 backing', () => {
expect(
resolveVibrancyConfig('cindy', false, 'win32', {
getSystemVersion: () => '10.0.22631',
}),
).toEqual({
vibrancy: null,
- backgroundColor: '#00000000',
+ backgroundColor: 'rgba(238, 238, 233, 0.85)',
+ backgroundMaterial: 'acrylic',
+ });
+ });
+
+ it('win32 × Win11 × CINDY:深色 acrylic 使用深色侧栏 backing', () => {
+ expect(
+ resolveVibrancyConfig('cindy', true, 'win32', {
+ getSystemVersion: () => '10.0.22631',
+ }),
+ ).toEqual({
+ vibrancy: null,
+ backgroundColor: 'rgba(5, 5, 5, 0.85)',
backgroundMaterial: 'acrylic',
});
});
@@ -118,7 +130,7 @@ describe('E4D resolveVibrancyConfig(familyId→vibrancy/backgroundColor 映射)'
}),
).toEqual({
vibrancy: null,
- backgroundColor: '#00000000',
+ backgroundColor: 'rgba(5, 5, 5, 0.85)',
backgroundMaterial: 'acrylic',
});
// 走统一 logger.warn,不再是裸 console.warn;文案不再带 [main] 前缀(scope 由 logger 注入)
diff --git a/apps/desktop/src/main/__tests__/window-theme-mode-store.test.ts b/apps/desktop/src/main/__tests__/window-theme-mode-store.test.ts
new file mode 100644
index 0000000000..e9398069d4
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/window-theme-mode-store.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from 'vitest';
+
+import { __testing, parseWindowThemeVibrancyPayload } from '../window-theme-mode-store';
+
+describe('window theme mode store', () => {
+ it('normalizes supported modes and falls back to system', () => {
+ expect(__testing.normalize({
+ mode: 'light',
+ resolvedIsDark: false,
+ systemIsDark: true,
+ familyId: 'cindy',
+ systemModeFollowsSystem: true,
+ })).toEqual({
+ mode: 'light',
+ resolvedIsDark: false,
+ systemIsDark: true,
+ familyId: 'cindy',
+ systemModeFollowsSystem: true,
+ });
+ expect(__testing.normalize({ mode: 'dark', resolvedIsDark: true })).toEqual({
+ mode: 'dark',
+ resolvedIsDark: true,
+ });
+ expect(__testing.normalize({ mode: 'system' })).toEqual({ mode: 'system' });
+ expect(__testing.normalize({ mode: 'auto', resolvedIsDark: 'dark' })).toEqual({
+ mode: 'system',
+ });
+ expect(__testing.normalize(null)).toEqual({ mode: 'system' });
+ });
+
+ it('runtime-validates the complete vibrancy payload before any theme side effect', () => {
+ expect(parseWindowThemeVibrancyPayload({
+ familyId: 'eclipse',
+ isDark: true,
+ mode: 'system',
+ systemModeFollowsSystem: false,
+ })).toEqual({
+ familyId: 'eclipse',
+ isDark: true,
+ mode: 'system',
+ systemModeFollowsSystem: false,
+ });
+ expect(parseWindowThemeVibrancyPayload({ familyId: 'cindy', isDark: false })).toEqual({
+ familyId: 'cindy',
+ isDark: false,
+ });
+
+ for (const invalid of [
+ null,
+ [],
+ { familyId: '', isDark: false },
+ { familyId: 'x'.repeat(513), isDark: false },
+ { familyId: 'cindy', isDark: 'false' },
+ { familyId: 'cindy', isDark: false, mode: 'auto' },
+ { familyId: 'cindy', isDark: false, systemModeFollowsSystem: 'yes' },
+ ]) {
+ expect(parseWindowThemeVibrancyPayload(invalid)).toBeNull();
+ }
+ });
+
+ it('reuses a system-mode fallback only while the system preference still matches', () => {
+ const snapshot = { mode: 'system' as const, resolvedIsDark: true, systemIsDark: false };
+
+ expect(__testing.resolveSnapshotForSystem(snapshot, false)).toEqual({
+ mode: 'dark',
+ resolvedIsDark: true,
+ systemIsDark: false,
+ });
+ expect(__testing.resolveSnapshotForSystem(snapshot, true)).toEqual({
+ mode: 'system',
+ systemIsDark: false,
+ });
+ expect(__testing.resolveSnapshotForSystem({ mode: 'system', resolvedIsDark: true }, true))
+ .toEqual({ mode: 'system' });
+ });
+
+ it('keeps a single-variant family resolved across a system preference change', () => {
+ const snapshot = {
+ mode: 'system' as const,
+ resolvedIsDark: true,
+ systemIsDark: true,
+ familyId: 'eclipse',
+ systemModeFollowsSystem: false,
+ };
+
+ expect(__testing.resolveSnapshotForSystem(snapshot, false)).toEqual({
+ ...snapshot,
+ mode: 'dark',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/windowThemeVibrancyIpcSecurity.test.ts b/apps/desktop/src/main/__tests__/windowThemeVibrancyIpcSecurity.test.ts
new file mode 100644
index 0000000000..6466d7cbb7
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/windowThemeVibrancyIpcSecurity.test.ts
@@ -0,0 +1,38 @@
+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('window theme vibrancy IPC trust boundary', () => {
+ it('validates the sender and payload before persistence or window mutations', () => {
+ const start = bootstrapSource.search(
+ /ipcMain\.on\(\s*['"]theme:apply-vibrancy['"]/u,
+ );
+ const endMatch = /ipcMain\.on\(\s*['"]get-app-version['"]/u.exec(
+ bootstrapSource.slice(start),
+ );
+ const end = endMatch ? start + endMatch.index : -1;
+ expect(start).toBeGreaterThanOrEqual(0);
+ expect(end).toBeGreaterThan(start);
+
+ const handler = bootstrapSource.slice(start, end);
+ const senderGuard = handler.indexOf('assertTrustedAppRendererEvent(event);');
+ const payloadParse = handler.indexOf('parseWindowThemeVibrancyPayload(rawPayload);');
+ const modeGuard = handler.indexOf('payload.mode === undefined');
+ const systemFollowGuard = handler.indexOf('payload.systemModeFollowsSystem === undefined');
+ const snapshotWrite = handler.indexOf('writeWindowThemeSnapshot(');
+ const resolvedThemeWrite = handler.indexOf('rememberResolvedAppTheme(payload.isDark);');
+ const vibrancyMutation = handler.indexOf('applyWindowVibrancy(payload.familyId');
+
+ expect(handler).toContain('(event, rawPayload: unknown)');
+ expect(senderGuard).toBeGreaterThanOrEqual(0);
+ expect(payloadParse).toBeGreaterThan(senderGuard);
+ expect(modeGuard).toBeGreaterThan(payloadParse);
+ expect(systemFollowGuard).toBeGreaterThan(payloadParse);
+ expect(snapshotWrite).toBeGreaterThan(systemFollowGuard);
+ expect(resolvedThemeWrite).toBeGreaterThan(systemFollowGuard);
+ expect(vibrancyMutation).toBeGreaterThan(systemFollowGuard);
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index cfda31e2b6..915383b443 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -19,6 +19,19 @@ import {
} from 'electron';
import { resolveVibrancyConfig } from './vibrancyConfig';
import { applyVibrancyToSecondaryWindows } from './secondary-windows';
+import {
+ rememberResolvedAppTheme,
+ resolveAppThemeIsDark,
+} from './resolved-app-theme';
+import {
+ parseWindowThemeVibrancyPayload,
+ readWindowThemeSnapshot,
+ writeWindowThemeSnapshot,
+} from './window-theme-mode-store';
+import {
+ createWindowBackdropMaterialArgument,
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+} from '../shared/windowBackdrop.js';
import path from 'node:path';
import fs from 'node:fs';
import os from 'node:os';
@@ -370,9 +383,7 @@ import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService
import { initNotificationService } from './notificationService';
import { initWecomGroupNotificationIpc } from './wecomGroupNotification';
import { getAgentIslandService, initAgentIslandService } from './agent-island/service.js';
-import {
- attachWorkLouderCodexWindowReveal,
-} from './worklouder-codex/index.js';
+import { attachWorkLouderCodexWindowReveal } from './worklouder-codex/index.js';
import {
disposeInputDevices,
resumeInputDeviceTaskSlots,
@@ -1025,10 +1036,7 @@ const _scheduleIpcRegistered = new WeakSet<object>();
*/
function isChatEmbeddingAvailable(): boolean {
try {
- return isCindyEmbeddingModelAvailable(
- getDesktopSelectableCatalog(),
- CHAT_EMBED_MODEL_ID,
- );
+ return isCindyEmbeddingModelAvailable(getDesktopSelectableCatalog(), CHAT_EMBED_MODEL_ID);
} catch {
return false;
}
@@ -1123,7 +1131,9 @@ function scheduleChatEmbeddingRuntimeReconcile(): void {
}
})
.catch((err: unknown) => {
- createSchedulerLogger('chat-embedding-runtime').error('reconcile failed', { error: String(err) });
+ createSchedulerLogger('chat-embedding-runtime').error('reconcile failed', {
+ error: String(err),
+ });
});
}
@@ -1235,10 +1245,8 @@ async function teardownGhostProjectionBoundary(reason: string): Promise<void> {
}
};
- await run('interruptGhostCallsForAccountBoundary', () =>
- withAuthBoundaryTimeout('interrupt Ghost calls', interruptGhostCallsForAccountBoundary));
- await run('waitForGhostMutations', () =>
- withAuthBoundaryTimeout('wait for Ghost mutations', waitForGhostMutations));
+ await run('interruptGhostCallsForAccountBoundary', () => withAuthBoundaryTimeout('interrupt Ghost calls', interruptGhostCallsForAccountBoundary));
+ await run('waitForGhostMutations', () => withAuthBoundaryTimeout('wait for Ghost mutations', waitForGhostMutations));
await run('suspendAllGhosts', suspendAllGhosts);
if (failures.length > 0) {
@@ -1667,7 +1675,10 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {
}
if (blockingFailures.length > 0) {
- throw new AggregateError(blockingFailures, `account boundary teardown on ${reason} was incomplete`);
+ throw new AggregateError(
+ blockingFailures,
+ `account boundary teardown on ${reason} was incomplete`,
+ );
}
// Reached only when the handover ran all the way through, which is exactly
// when a previous abort's blocking state stops being true.
@@ -1994,7 +2005,11 @@ const ghostPanelWindowsController = new GhostPanelWindowsController({
}
},
sendToWindow: (win, channel, payload) => {
- try { win.webContents.send(channel, payload); } catch { /* ignore */ }
+ try {
+ win.webContents.send(channel, payload);
+ } catch {
+ /* ignore */
+ }
},
isQuitting: () => isQuitting,
log: createLogger('ghost-panel-window-controller'),
@@ -3176,18 +3191,22 @@ const createWindow = () => {
// 效果由 renderer 的 swallowActivationClick DOM adapter 承接,即时生效。
const swallowActivationClick = readWindowBehaviorSettings().swallowActivationClick;
- // Use nativeTheme to pick initial background color matching OS preference,
- // avoiding white flash on startup for dark mode users.
+ // Windows uses the renderer theme-mode mirror before the first BrowserWindow exists;
+ // missing/invalid mirrors and other platforms keep the native OS-theme fallback.
// mac:创建期即透明底+sidebar 材质(Electron setBackgroundColor 运行时改 alpha 不可靠,是 vibrancy 不透壁纸的根因;非 CINDY 皮肤 body 不透明会自然盖住,视觉无影响)
+ const persistedTheme = process.platform === 'win32' ? readWindowThemeSnapshot() : null;
+ const isDark = process.platform === 'win32'
+ ? resolveAppThemeIsDark(
+ nativeTheme.shouldUseDarkColors,
+ persistedTheme?.mode,
+ persistedTheme?.resolvedIsDark,
+ )
+ : nativeTheme.shouldUseDarkColors;
const bgColor =
- process.platform === 'darwin'
- ? '#00000000'
- : nativeTheme.shouldUseDarkColors
- ? '#1f1f1e'
- : '#f8f8f6';
+ process.platform === 'darwin' ? '#00000000' : isDark ? '#1f1f1e' : '#f8f8f6';
const winBackdropConfig = resolveVibrancyConfig(
- 'cindy',
- nativeTheme.shouldUseDarkColors,
+ persistedTheme?.familyId ?? 'cindy',
+ isDark,
process.platform,
);
@@ -3228,6 +3247,9 @@ const createWindow = () => {
...platformOptions,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
+ additionalArguments: [
+ createWindowBackdropMaterialArgument(winBackdropConfig.backgroundMaterial ?? 'none'),
+ ],
spellcheck: false,
// 默认保留 Chromium 后台节流;只有 active turn 或 terminal grace 期间才由
// setMainWindowBackgroundThrottlingForActiveTurn 临时关闭,避免后台 idle 常驻耗电。
@@ -3704,14 +3726,34 @@ const registerIpcHandlers = () => {
}
if (process.platform === 'win32' && config.backgroundMaterial) {
win.setBackgroundMaterial(config.backgroundMaterial);
+ win.webContents.send(
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+ config.backgroundMaterial,
+ );
}
win.setBackgroundColor(config.backgroundColor);
applyVibrancyToSecondaryWindows(familyId, isDark);
}
- ipcMain.on('theme:apply-vibrancy', (_event, payload: { familyId: string; isDark: boolean }) => {
- applyWindowVibrancy(payload.familyId, payload.isDark);
- });
+ ipcMain.on(
+ 'theme:apply-vibrancy',
+ (event, rawPayload: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const payload = parseWindowThemeVibrancyPayload(rawPayload);
+ if (!payload) return;
+ if (payload.mode === undefined || payload.systemModeFollowsSystem === undefined) return;
+ if (process.platform === 'win32') {
+ writeWindowThemeSnapshot(
+ payload.mode,
+ payload.isDark,
+ payload.familyId,
+ payload.systemModeFollowsSystem,
+ );
+ }
+ rememberResolvedAppTheme(payload.isDark);
+ applyWindowVibrancy(payload.familyId, payload.isDark);
+ },
+ );
ipcMain.on('get-app-version', (event) => {
event.returnValue = app.getVersion();
@@ -7626,11 +7668,7 @@ app.on('ready', async () => {
setAccountProviderReadinessReadyHandler((ownerId) => {
startAccountIntegrationsAfterOwnerDbReady(ownerId, {
isOwnerCurrent: (id) =>
- isLocalDbOwnerCurrent(
- authManager.getAuthState(),
- id,
- isAppSessionBoundaryPending(),
- ),
+ isLocalDbOwnerCurrent(authManager.getAuthState(), id, isAppSessionBoundaryPending()),
startHookControlAccount,
startImConnection,
log: dbClientLog,
@@ -7640,7 +7678,8 @@ app.on('ready', async () => {
});
accountProviderReadinessArm.publish(userId, startProviderReadiness, resumeIncompleteDiscovery);
if (makerProviderRefreshConfigured) startProviderReadiness();
- else startPendingAccountProviderReadiness = { ownerId: userId, start: startProviderReadiness };
+ else
+ startPendingAccountProviderReadiness = { ownerId: userId, start: startProviderReadiness };
logStartupPhase('post-db-hooks-scheduled');
},
});
@@ -8324,7 +8363,10 @@ function parseVisionBridgeSettingsPatch(raw: unknown): Partial<VisionBridgeSetti
// trim 后拒绝空白元素,避免脏值(" deepseek " / " ")落盘。
const trimmed = input.targetModels.map((m) => (typeof m === 'string' ? m.trim() : ''));
if (trimmed.some((m) => m.length === 0)) {
- throwIpcError('INVALID_PARAMS', 'vision bridge targetModels must be a non-blank string array');
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'vision bridge targetModels must be a non-blank string array',
+ );
}
patch.targetModels = trimmed;
}
@@ -8336,11 +8378,17 @@ function parseVisionBridgeSettingsPatch(raw: unknown): Partial<VisionBridgeSetti
continue;
}
if (!value || typeof value !== 'object' || Array.isArray(value)) {
- throwIpcError('INVALID_PARAMS', `vision bridge ${key} must be { providerId, modelId } or null`);
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `vision bridge ${key} must be { providerId, modelId } or null`,
+ );
}
const ref = value as Record<string, unknown>;
if (typeof ref.providerId !== 'string' || typeof ref.modelId !== 'string') {
- throwIpcError('INVALID_PARAMS', `vision bridge ${key} must be { providerId, modelId } or null`);
+ throwIpcError(
+ 'INVALID_PARAMS',
+ `vision bridge ${key} must be { providerId, modelId } or null`,
+ );
}
// trim 后拒绝纯空白,避免脏配置(空白串)落盘。
const providerId = ref.providerId.trim();
diff --git a/apps/desktop/src/main/resolved-app-theme.ts b/apps/desktop/src/main/resolved-app-theme.ts
new file mode 100644
index 0000000000..300731bfdf
--- /dev/null
+++ b/apps/desktop/src/main/resolved-app-theme.ts
@@ -0,0 +1,26 @@
+let lastResolvedIsDark: boolean | undefined;
+
+export type AppThemeMode = 'system' | 'light' | 'dark';
+
+export function isAppThemeMode(value: unknown): value is AppThemeMode {
+ return value === 'system' || value === 'light' || value === 'dark';
+}
+
+/** Keep the renderer-resolved app theme available for windows created later. */
+export function rememberResolvedAppTheme(isDark: boolean): void {
+ lastResolvedIsDark = isDark;
+}
+
+/** Fall back to the persisted theme snapshot until the renderer resolves this run's preference. */
+export function resolveAppThemeIsDark(
+ systemIsDark: boolean,
+ persistedMode: AppThemeMode = 'system',
+ persistedResolvedIsDark?: boolean,
+): boolean {
+ if (lastResolvedIsDark !== undefined) return lastResolvedIsDark;
+ if (persistedMode === 'system') return systemIsDark;
+ if (persistedResolvedIsDark !== undefined) return persistedResolvedIsDark;
+ if (persistedMode === 'dark') return true;
+ if (persistedMode === 'light') return false;
+ return systemIsDark;
+}
diff --git a/apps/desktop/src/main/secondary-windows.ts b/apps/desktop/src/main/secondary-windows.ts
index 749f7a7a4b..440baa5b09 100644
--- a/apps/desktop/src/main/secondary-windows.ts
+++ b/apps/desktop/src/main/secondary-windows.ts
@@ -28,9 +28,16 @@ import {
type ScreenPoint,
} from './windowBounds.js';
import { readWindowBehaviorSettings } from './window-behavior-settings-store.js';
-import { resolveVibrancyConfig, type WindowsBackdropMaterial } from './vibrancyConfig.js';
+import { resolveVibrancyConfig } from './vibrancyConfig.js';
+import {
+ createWindowBackdropMaterialArgument,
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+} from '../shared/windowBackdrop.js';
+import type { WindowsBackdropMaterial } from './vibrancyConfig.js';
import { installSelectionContextMenu } from './selection-context-menu.js';
import { applyAppearanceToWindow } from './appearance-settings-ipc.js';
+import { resolveAppThemeIsDark } from './resolved-app-theme.js';
+import { readWindowThemeSnapshot } from './window-theme-mode-store.js';
const log = createLogger('secondary-windows');
@@ -98,7 +105,20 @@ export function openSessionInNewWindow(
process.platform === 'darwin'
? { titleBarStyle: 'hidden' as const, trafficLightPosition: { x: 12, y: 16 } }
: { frame: false };
- const bgColor = nativeTheme.shouldUseDarkColors ? '#1f1f1e' : '#f8f8f6';
+ const persistedTheme = process.platform === 'win32' ? readWindowThemeSnapshot() : null;
+ const isDark = process.platform === 'win32'
+ ? resolveAppThemeIsDark(
+ nativeTheme.shouldUseDarkColors,
+ persistedTheme?.mode,
+ persistedTheme?.resolvedIsDark,
+ )
+ : nativeTheme.shouldUseDarkColors;
+ const bgColor = isDark ? '#1f1f1e' : '#f8f8f6';
+ const winBackdropConfig = resolveVibrancyConfig(
+ persistedTheme?.familyId ?? 'cindy',
+ isDark,
+ process.platform,
+ );
const base = mainWindow && !mainWindow.isDestroyed() ? mainWindow.getBounds() : null;
const requestedSize = base
@@ -130,10 +150,19 @@ export function openSessionInNewWindow(
autoHideMenuBar: true,
show: false,
backgroundColor: bgColor,
+ ...(process.platform === 'win32' && winBackdropConfig.backgroundMaterial
+ ? {
+ backgroundMaterial: winBackdropConfig.backgroundMaterial,
+ backgroundColor: winBackdropConfig.backgroundColor,
+ }
+ : {}),
acceptFirstMouse: !swallowActivationClick,
...platformOptions,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
+ additionalArguments: [
+ createWindowBackdropMaterialArgument(winBackdropConfig.backgroundMaterial ?? 'none'),
+ ],
spellcheck: false,
// A task drag that misses a renderer drop target must never navigate the
// application window to the dragged plain-text fallback.
@@ -252,7 +281,13 @@ export function applyVibrancyToSecondaryWindows(familyId: string, isDark: boolea
const withMaterial = win as typeof win & {
setBackgroundMaterial?: (material: WindowsBackdropMaterial) => void;
};
- withMaterial.setBackgroundMaterial?.(config.backgroundMaterial);
+ if (withMaterial.setBackgroundMaterial) {
+ withMaterial.setBackgroundMaterial(config.backgroundMaterial);
+ win.webContents.send(
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+ config.backgroundMaterial,
+ );
+ }
}
win.setBackgroundColor(config.backgroundColor);
}
diff --git a/apps/desktop/src/main/vibrancyConfig.ts b/apps/desktop/src/main/vibrancyConfig.ts
index af8dee9ccc..d99db734a3 100644
--- a/apps/desktop/src/main/vibrancyConfig.ts
+++ b/apps/desktop/src/main/vibrancyConfig.ts
@@ -5,10 +5,15 @@
* 回退不透明。
*/
import { createLogger } from './logger.js';
+import {
+ CINDY_ACRYLIC_WINDOW_BACKING,
+ isWindowsBackdropMaterial,
+ type WindowsBackdropMaterial,
+} from '../shared/windowBackdrop.js';
-const log = createLogger('vibrancyConfig');
+export type { WindowsBackdropMaterial } from '../shared/windowBackdrop.js';
-export type WindowsBackdropMaterial = 'acrylic' | 'mica' | 'tabbed' | 'none';
+const log = createLogger('vibrancyConfig');
export interface VibrancyConfig {
vibrancy: string | null;
@@ -20,13 +25,6 @@ export interface ResolveVibrancyConfigOptions {
getSystemVersion?: () => string;
}
-const VALID_BACKDROP_MATERIALS = new Set<WindowsBackdropMaterial>([
- 'acrylic',
- 'mica',
- 'tabbed',
- 'none',
-]);
-
function readWindowsSystemVersion(options?: ResolveVibrancyConfigOptions): string | null {
try {
if (options?.getSystemVersion) return options.getSystemVersion();
@@ -54,13 +52,16 @@ function isWindows11(options?: ResolveVibrancyConfigOptions): boolean {
function resolveBackdropMaterial(): WindowsBackdropMaterial {
const raw = process.env.XDT_BACKDROP_MATERIAL;
if (!raw) return 'acrylic';
- if (VALID_BACKDROP_MATERIALS.has(raw as WindowsBackdropMaterial)) {
- return raw as WindowsBackdropMaterial;
- }
+ if (isWindowsBackdropMaterial(raw)) return raw;
log.warn(`Invalid XDT_BACKDROP_MATERIAL '${raw}', falling back to acrylic.`);
return 'acrylic';
}
+function resolveWindowsBackdropColor(material: WindowsBackdropMaterial, isDark: boolean): string {
+ if (material !== 'acrylic') return '#00000000';
+ return isDark ? CINDY_ACRYLIC_WINDOW_BACKING.dark : CINDY_ACRYLIC_WINDOW_BACKING.light;
+}
+
export function resolveVibrancyConfig(
familyId: string,
isDark: boolean,
@@ -80,10 +81,13 @@ export function resolveVibrancyConfig(
}
if (platform === 'win32') {
if (isCindy && isWindows11(options)) {
+ const backgroundMaterial = resolveBackdropMaterial();
return {
vibrancy: null,
- backgroundColor: '#00000000',
- backgroundMaterial: resolveBackdropMaterial(),
+ // Acrylic 的原生 backing 直接带侧栏染色,左栏稳态不再重复叠 CSS tint。
+ // live resize 全程保持同一材质;连续尺寸变化交给 Renderer 的 CSS 布局处理。
+ backgroundColor: resolveWindowsBackdropColor(backgroundMaterial, isDark),
+ backgroundMaterial,
};
}
return { vibrancy: null, backgroundColor: opaqueBg, backgroundMaterial: 'none' };
diff --git a/apps/desktop/src/main/window-theme-mode-store.ts b/apps/desktop/src/main/window-theme-mode-store.ts
new file mode 100644
index 0000000000..3a27eac56f
--- /dev/null
+++ b/apps/desktop/src/main/window-theme-mode-store.ts
@@ -0,0 +1,150 @@
+import { app, nativeTheme } from 'electron';
+import path from 'node:path';
+
+import { desktopMakerLogger } from './maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from './maker-host/override-settings-file.js';
+import { isAppThemeMode, type AppThemeMode } from './resolved-app-theme.js';
+
+const log = desktopMakerLogger.child('window-theme-mode-store');
+
+// Renderer localStorage remains the source of truth. This small main-side snapshot exists only so
+// Windows can choose the matching Acrylic backing before the first BrowserWindow is created.
+
+export interface WindowThemeSnapshot {
+ mode: AppThemeMode;
+ resolvedIsDark?: boolean;
+ systemIsDark?: boolean;
+ familyId?: string;
+ systemModeFollowsSystem?: boolean;
+}
+
+export interface WindowThemeVibrancyPayload {
+ familyId: string;
+ isDark: boolean;
+ mode?: AppThemeMode;
+ systemModeFollowsSystem?: boolean;
+}
+
+const DEFAULTS: WindowThemeSnapshot = { mode: 'system' };
+const MAX_FAMILY_ID_LENGTH = 512;
+
+export function parseWindowThemeVibrancyPayload(raw: unknown): WindowThemeVibrancyPayload | null {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const value = raw as Record<string, unknown>;
+ if (
+ typeof value.familyId !== 'string'
+ || value.familyId.trim().length === 0
+ || value.familyId.length > MAX_FAMILY_ID_LENGTH
+ || typeof value.isDark !== 'boolean'
+ || (value.mode !== undefined && !isAppThemeMode(value.mode))
+ || (
+ value.systemModeFollowsSystem !== undefined
+ && typeof value.systemModeFollowsSystem !== 'boolean'
+ )
+ ) return null;
+ return {
+ familyId: value.familyId,
+ isDark: value.isDark,
+ ...(isAppThemeMode(value.mode) ? { mode: value.mode } : {}),
+ ...(typeof value.systemModeFollowsSystem === 'boolean'
+ ? { systemModeFollowsSystem: value.systemModeFollowsSystem }
+ : {}),
+ };
+}
+
+function normalize(raw: unknown): WindowThemeSnapshot {
+ if (!raw || typeof raw !== 'object') return { ...DEFAULTS };
+ const value = raw as Record<string, unknown>;
+ const normalized: WindowThemeSnapshot = {
+ mode: isAppThemeMode(value.mode) ? value.mode : DEFAULTS.mode,
+ };
+ if (typeof value.resolvedIsDark === 'boolean') {
+ normalized.resolvedIsDark = value.resolvedIsDark;
+ }
+ if (typeof value.systemIsDark === 'boolean') {
+ normalized.systemIsDark = value.systemIsDark;
+ }
+ if (
+ typeof value.familyId === 'string'
+ && value.familyId.trim().length > 0
+ && value.familyId.length <= MAX_FAMILY_ID_LENGTH
+ ) {
+ normalized.familyId = value.familyId;
+ }
+ if (typeof value.systemModeFollowsSystem === 'boolean') {
+ normalized.systemModeFollowsSystem = value.systemModeFollowsSystem;
+ }
+ return normalized;
+}
+
+function resolveSnapshotForSystem(
+ snapshot: WindowThemeSnapshot,
+ currentSystemIsDark: boolean,
+): WindowThemeSnapshot {
+ if (snapshot.mode !== 'system') return snapshot;
+ if (
+ snapshot.resolvedIsDark !== undefined
+ && (
+ snapshot.systemModeFollowsSystem === false
+ || snapshot.systemIsDark === currentSystemIsDark
+ )
+ ) {
+ return {
+ ...snapshot,
+ mode: snapshot.resolvedIsDark ? 'dark' : 'light',
+ };
+ }
+ const { resolvedIsDark: _staleResolvedTheme, ...currentSystemSnapshot } = snapshot;
+ return currentSystemSnapshot;
+}
+
+function settingsFilePath(): string {
+ return path.join(app.getPath('userData'), 'window-theme-mode.json');
+}
+
+const store = createOverrideSettingsFile<WindowThemeSnapshot>({
+ filePath: settingsFilePath,
+ defaults: DEFAULTS,
+ normalize,
+ log,
+ label: 'window-theme-mode',
+ maxBytes: 4 * 1024,
+ preserveUnreadableFile: true,
+});
+
+export function readWindowThemeSnapshot(): WindowThemeSnapshot {
+ return resolveSnapshotForSystem(store.read(), nativeTheme.shouldUseDarkColors);
+}
+
+export function writeWindowThemeSnapshot(
+ mode: AppThemeMode,
+ resolvedIsDark: boolean,
+ familyId: string,
+ systemModeFollowsSystem: boolean,
+): void {
+ try {
+ const systemIsDark = nativeTheme.shouldUseDarkColors;
+ const current = store.read();
+ if (
+ current.mode === mode
+ && current.resolvedIsDark === resolvedIsDark
+ && current.systemIsDark === systemIsDark
+ && current.familyId === familyId
+ && current.systemModeFollowsSystem === systemModeFollowsSystem
+ ) return;
+ store.writePatch({
+ mode,
+ resolvedIsDark,
+ systemIsDark,
+ familyId,
+ systemModeFollowsSystem,
+ });
+ } catch (error) {
+ // Theme rendering must remain available even if the best-effort restart mirror cannot persist.
+ log.warn('window theme mode write failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
+
+export const __testing = { normalize, resolveSnapshotForSystem };
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 87c8381ad2..83cf8e03a1 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,6 +1,11 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import type { AppearanceSettings } from '../shared/appearanceSettings';
+import {
+ isWindowsBackdropMaterial,
+ readWindowBackdropMaterialFromArgv,
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+} from '../shared/windowBackdrop';
import { isDeepLinkProviderConnectId } from '../shared/deepLinkSchemes';
import {
parseProjectOrderSnapshot,
@@ -410,6 +415,9 @@ function createIpcFanOut(channel: string): FanOut {
// 老 7 个 fanOut + fanOutUserMessagePersisted 一起拿掉。
const fanOutUpdateStatus = createIpcFanOut('update-status');
const fanOutUpdateChannelSettings = createIpcFanOut('update-channel-settings');
+const fanOutWindowBackdropMaterialChanged = createIpcFanOut(
+ WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
+);
const fanOutOrcaWorkerChanged = createIpcFanOut('maker:orca:worker-changed');
// 右侧栏独立子窗口(RSB window)状态 / 上下文 / 命令推送
const fanOutRsbWindowStateChanged = createIpcFanOut('maker:rsb-window:state-changed');
@@ -892,6 +900,15 @@ type CindyMediaPreferenceKind = {
contextBridge.exposeInMainWorld('electronAPI', {
platform: process.platform,
+ windowBackdropMaterial: readWindowBackdropMaterialFromArgv(process.argv),
+ onWindowBackdropMaterialChanged: (
+ cb: (material: import('../shared/windowBackdrop').WindowsBackdropMaterial) => void,
+ ) =>
+ fanOutWindowBackdropMaterialChanged((material) => {
+ if (typeof material === 'string' && isWindowsBackdropMaterial(material)) {
+ cb(material);
+ }
+ }),
osRelease: ipcRenderer.sendSync('get-os-release') as string,
appVersion: ipcRenderer.sendSync('get-app-version') as string,
clientEndpoints: { websiteUrl: clientEndpointsInfo?.websiteUrl ?? '' },
@@ -2367,8 +2384,18 @@ contextBridge.exposeInMainWorld('electronAPI', {
// E4D 毛玻璃:family 切换/启动时通知 main 开关 macOS vibrancy(仅 CINDY 透壁纸)
theme: {
- applyVibrancy: (familyId: string, isDark: boolean): void => {
- ipcRenderer.send('theme:apply-vibrancy', { familyId, isDark });
+ applyVibrancy: (
+ familyId: string,
+ isDark: boolean,
+ mode: 'system' | 'light' | 'dark',
+ systemModeFollowsSystem: boolean,
+ ): void => {
+ ipcRenderer.send('theme:apply-vibrancy', {
+ familyId,
+ isDark,
+ mode,
+ systemModeFollowsSystem,
+ });
},
},
onAppUpdateProgress: fanOutAppUpdateProgress,
diff --git a/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts b/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts
index 2a46398734..04e796d071 100644
--- a/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/composerNarrowToolbarContract.test.ts
@@ -12,13 +12,13 @@ const modelSelectorSource = read('ModelSelector.tsx');
const permissionSelectorSource = read('PermissionSelector.tsx');
describe('composer narrow toolbar contract', () => {
- it('uses measured card width for both default-session and create-agent composers', () => {
+ it('uses discrete card-width modes for both default-session and create-agent composers', () => {
+ expect(chatInputSource).toContain("useState<ToolbarWidthMode>('unmeasured')");
+ expect(chatInputSource).toContain('currentMode === nextMode ? currentMode : nextMode');
expect(chatInputSource).toContain(
- 'const useNarrowToolbar = narrowToolbar || (toolbarWidth != null && toolbarWidth < 600);',
- );
- expect(chatInputSource).not.toContain(
- 'isCreateAgentVariant &&\n (narrowToolbar || (toolbarWidth != null && toolbarWidth < 600))',
+ 'const useNarrowToolbar = narrowToolbar || autoNarrowToolbar;',
);
+ expect(chatInputSource).not.toContain('setToolbarWidth(el.clientWidth)');
expect(chatInputSource).toContain('compactToolbar={useNarrowToolbar}');
expect(chatInputSource).toContain('ultraCompactToolbar={useUltraCompactToolbar}');
expect(chatInputSource).toContain('iconOnly={useUltraCompactToolbar}');
diff --git a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
index 5c2544f7f3..b1fc1ff090 100644
--- a/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
+++ b/apps/desktop/src/renderer/__tests__/controlledBannerPlacement.test.ts
@@ -51,13 +51,8 @@ describe('controlled banner placement', () => {
it('keeps only the collapsed breathing light anchored before token metadata', () => {
expect(sessionViewSource).toContain('const CONTROLLED_BANNER_MAX_WIDTH = 420;');
- expect(sessionViewSource).toContain('const CONTROLLED_BANNER_WIDTH_RATIO = 0.5;');
expect(sessionViewSource).toContain(
- 'function getControlledBannerMaxWidth(inputWidth?: number): number',
- );
- expect(sessionViewSource).toContain('(inputWidth - 16) * CONTROLLED_BANNER_WIDTH_RATIO');
- expect(sessionViewSource).toContain(
- 'const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);',
+ 'const controlledBannerMaxWidth = `min(${inputHalfWidth}, ${CONTROLLED_BANNER_MAX_WIDTH}px)`;',
);
expect(sessionViewSource).toContain('if (isHidden && !rightLeadingSlot) return null;');
expect(controlledBannerSource).toContain("placement?: 'floating' | 'inline' | 'composer';");
@@ -120,7 +115,7 @@ describe('controlled banner placement', () => {
});
it('caps the right-aligned composer chip without changing the input width', () => {
- expect(controlledBannerSource).toContain('maxWidth?: number;');
+ expect(controlledBannerSource).toContain("maxWidth?: CSSProperties['maxWidth'];");
expect(controlledBannerSource).toContain('style={maxWidth == null ? undefined : { maxWidth }}');
expect(sessionViewSource).toContain('maxWidth={controlledBannerMaxWidth}');
});
diff --git a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
index d2ed667851..d8f990b07e 100644
--- a/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
+++ b/apps/desktop/src/renderer/__tests__/focusScrollLifecycle.test.ts
@@ -288,8 +288,8 @@ describe('MessageStream focus cancellation wiring', () => {
it('replays a deferred deletion before the message navigation rail requests a fallible target', () => {
const railJump = sourceBetween(
- 'const handleNavRailJump = useCallback((clientId: string) => {',
- 'useLayoutEffect(() => {',
+ 'const handleNavRailJump = useCallback(',
+ 'useLayoutEffect(() => {\n if (!railJumpRequest) return;',
);
const cancelIndex = railJump.indexOf('cancelFocusJump();');
const requestIndex = railJump.indexOf(
diff --git a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
index 6ae5837b25..58420f0f71 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerCreateAgentVisualContract.test.ts
@@ -80,7 +80,8 @@ describe('NewMakerDraftRoute CREATE AGENT visual contract', () => {
// 内容列宽度从死锁 800px 改为跟随 useProportionalWidth 的 inputWidth(与进行中
// 对话页同源,封顶 914+20=934px):大屏留出左右呼吸空间、发送后同一 ChatInput 无宽度跳变。
expect(source).toContain('relative flex w-full flex-col items-start');
- expect(source).toContain('style={{ maxWidth: inputWidth || 800 }}');
+ expect(source).toContain('style={{ maxWidth: inputWidth }}');
+ expect(source).toContain('responsiveBreakpoints: DRAFT_INPUT_WIDTH_BREAKPOINTS');
expect(source).not.toContain('max-w-[800px]');
expect(source).toContain('absolute right-0 top-[22px]');
// 快捷入口与输入框同宽(w-full 跟随父列 inputWidth),左右两缘对齐 ChatInput;
diff --git a/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts b/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts
new file mode 100644
index 0000000000..86fe5dd7ec
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/windowBackdropAcrylic.test.ts
@@ -0,0 +1,89 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { CINDY_ACRYLIC_WINDOW_BACKING } from '../../shared/windowBackdrop';
+import { cindyDark } from '../themes/builtin/cindy-dark';
+import { cindyLight } from '../themes/builtin/cindy-light';
+
+const rendererRoot = resolve(__dirname, '..');
+const desktopSourceRoot = resolve(rendererRoot, '..');
+const normalizeSource = (source: string) => source.replace(/\r\n?/g, '\n');
+const globalsSource = normalizeSource(
+ readFileSync(resolve(rendererRoot, 'styles', 'globals.css'), 'utf8'),
+);
+const mainEntrySource = normalizeSource(
+ readFileSync(resolve(rendererRoot, 'main-entry.tsx'), 'utf8'),
+);
+const bootstrapSource = normalizeSource(
+ readFileSync(resolve(desktopSourceRoot, 'main', 'bootstrap-electron.ts'), 'utf8'),
+);
+const secondaryWindowsSource = normalizeSource(
+ readFileSync(resolve(desktopSourceRoot, 'main', 'secondary-windows.ts'), 'utf8'),
+);
+const preloadSource = normalizeSource(
+ readFileSync(resolve(desktopSourceRoot, 'preload', 'preload.ts'), 'utf8'),
+);
+
+describe('Windows Acrylic resize backing contract', () => {
+ it('uses the exact sidebar tint tokens for the native backing', () => {
+ expect(cindyLight.colors['surface-translucent-sidebar']).toBe(
+ CINDY_ACRYLIC_WINDOW_BACKING.light,
+ );
+ expect(cindyDark.colors['surface-translucent-sidebar']).toBe(CINDY_ACRYLIC_WINDOW_BACKING.dark);
+ });
+
+ it('uses the persisted family when choosing the creation-time material', () => {
+ expect(bootstrapSource).toContain(
+ "persistedTheme?.familyId ?? 'cindy',\n isDark,\n process.platform,",
+ );
+ expect(secondaryWindowsSource).toContain(
+ "persistedTheme?.familyId ?? 'cindy',\n isDark,\n process.platform,",
+ );
+ });
+
+ it('publishes the actual window material to a root data attribute', () => {
+ expect(bootstrapSource).toContain(
+ "createWindowBackdropMaterialArgument(winBackdropConfig.backgroundMaterial ?? 'none')",
+ );
+ expect(secondaryWindowsSource).toContain(
+ "createWindowBackdropMaterialArgument(winBackdropConfig.backgroundMaterial ?? 'none')",
+ );
+ expect(preloadSource).toContain(
+ 'windowBackdropMaterial: readWindowBackdropMaterialFromArgv(process.argv)',
+ );
+ expect(mainEntrySource).toMatch(
+ /dataset\.windowBackdropMaterial\s*=\s*\n?\s*window\.electronAPI\.windowBackdropMaterial\s*\?\?\s*'none'/,
+ );
+ });
+
+ it('keeps the root material attribute in sync with runtime material changes', () => {
+ expect(bootstrapSource).toContain(
+ 'win.webContents.send(\n WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\n config.backgroundMaterial,\n )',
+ );
+ expect(secondaryWindowsSource).toContain(
+ 'win.webContents.send(\n WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,\n config.backgroundMaterial,\n )',
+ );
+ expect(preloadSource).toContain(
+ 'fanOutWindowBackdropMaterialChanged((material) => {\n if (typeof material === \'string\' && isWindowsBackdropMaterial(material))',
+ );
+ expect(mainEntrySource).toContain(
+ 'window.electronAPI.onWindowBackdropMaterialChanged?.((material) => {\n document.documentElement.dataset.windowBackdropMaterial = material;',
+ );
+ });
+
+ it('lets only the ordinary Acrylic sidebar show the creation-time backing', () => {
+ expect(globalsSource).toContain(
+ "[data-platform='win32'][data-window-backdrop-material='acrylic'][data-theme='cindy-light']",
+ );
+ expect(globalsSource).toContain(
+ "[data-platform='win32'][data-window-backdrop-material='acrylic'][data-theme='cindy-dark']",
+ );
+ expect(globalsSource).toContain('aside.bg-sidebar:not([data-sidebar-peek-drawer])');
+ expect(globalsSource).toMatch(
+ /aside\.bg-sidebar:not\(\[data-sidebar-peek-drawer\]\)[\s\S]*?\{\s*background:\s*transparent;/,
+ );
+ expect(globalsSource).toMatch(
+ /aside\.bg-sidebar\[data-sidebar-peek-drawer\][\s\S]*?background:\s*var\(--surface-translucent-sidebar\);[\s\S]*?backdrop-filter:\s*blur\(28px\);/,
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx b/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx
index f229ab249d..aa67aff3de 100644
--- a/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx
@@ -83,6 +83,8 @@ export interface MessageNavRailProps {
scrollRef: { readonly current: HTMLDivElement | null };
/** 内容列 maxWidth(与 MessageStream contentRef 的 maxWidth 同值)。 */
contentMaxWidth: number;
+ /** ResizeObserver 测量时读取最新宽度,避免把连续像素变化回灌给 React。 */
+ getContentMaxWidth?: () => number;
/** 底部输入 overlay 高度(resolvedBottomPadding),刻度带避开这段。 */
bottomOffset: number;
/** 点击刻度 → 跳到该提问。目标可能在渲染窗口外,由父级扩窗后滚动。 */
@@ -102,6 +104,7 @@ export function MessageNavRail({
entries,
scrollRef,
contentMaxWidth,
+ getContentMaxWidth,
bottomOffset,
onJump,
onNavCoverageChange,
@@ -150,6 +153,8 @@ export function MessageNavRail({
}
const contentMaxWidthRef = useRef(contentMaxWidth);
contentMaxWidthRef.current = contentMaxWidth;
+ const getContentMaxWidthRef = useRef(getContentMaxWidth);
+ getContentMaxWidthRef.current = getContentMaxWidth;
const bottomOffsetRef = useRef(bottomOffset);
bottomOffsetRef.current = bottomOffset;
@@ -189,7 +194,8 @@ export function MessageNavRail({
if (!root) return;
const containerRect = root.getBoundingClientRect();
containerLeftRef.current = containerRect.left;
- const roomOk = hasNavRailRoom(containerRect.width, contentMaxWidthRef.current);
+ const liveContentMaxWidth = getContentMaxWidthRef.current?.() || contentMaxWidthRef.current;
+ const roomOk = hasNavRailRoom(containerRect.width, liveContentMaxWidth);
setHasRoom(roomOk);
const avail = Math.max(
0,
@@ -289,7 +295,7 @@ export function MessageNavRail({
// availHeight 与纵向出场门槛会停在旧值直到下次滚动(PR #830 review)。
useEffect(() => {
scheduleMeasure();
- }, [entries, bottomOffset, contentMaxWidth, scheduleMeasure]);
+ }, [entries, bottomOffset, contentMaxWidth, getContentMaxWidth, scheduleMeasure]);
// 挂载亮相的那次也要按空闲节奏淡出。
useEffect(() => {
@@ -543,8 +549,10 @@ export function MessageNavRail({
const isActive = entry.id === displayActiveId;
const fullIdx = plan.startIndex + i;
const interactionId = scrubId ?? hoveredId;
- const interactionIndex = interactionId == null ? -1 : entries.findIndex((item) => item.id === interactionId);
- const interactionDistance = interactionIndex < 0 ? null : Math.abs(fullIdx - interactionIndex);
+ const interactionIndex =
+ interactionId == null ? -1 : entries.findIndex((item) => item.id === interactionId);
+ const interactionDistance =
+ interactionIndex < 0 ? null : Math.abs(fullIdx - interactionIndex);
// 该轮次的内容当前正显示在视口里 → 提亮"屏上内容高亮";
// 当前项在提亮之上再加长,两个信号分工:范围 = 在看什么,长刻度 = 读到哪。
const inView = rangeStartIdx >= 0 && fullIdx >= rangeStartIdx && fullIdx <= rangeEndIdx;
@@ -615,7 +623,8 @@ export function MessageNavRail({
'ease-[var(--motion-ease-move)]',
tickWidthClass,
tickOpacityClass,
- interactionDistance === 0 || (interactionDistance === null && (isActive || inView))
+ interactionDistance === 0 ||
+ (interactionDistance === null && (isActive || inView))
? 'bg-[var(--text-primary)]'
: 'bg-[var(--text-secondary)] group-hover:bg-[var(--text-primary)]',
)}
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index f361f65ae9..08bd26a128 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -25,6 +25,7 @@ import {
useRef,
useState,
useSyncExternalStore,
+ type CSSProperties,
type ReactNode,
} from 'react';
import { createPortal } from 'react-dom';
@@ -355,7 +356,9 @@ interface MessageStreamProps {
/** Content width — shared with the input overlay so chat stream + input
* box stay horizontally aligned (same width, same center, symmetric
* padding when the main area is compressed). */
- contentWidth?: number;
+ contentWidth?: CSSProperties['maxWidth'];
+ /** Returns the current numeric content width for geometry consumers without rerendering. */
+ getContentWidth?: () => number;
/** Message clientId to scroll into view and briefly highlight after search navigation. */
focusMessageClientId?: string | null;
/** Incremented by the parent for each search navigation, including repeated hits. */
@@ -1111,10 +1114,7 @@ function queryFocusElement(root: ParentNode, clientId: string): HTMLElement | nu
}
/** 折叠摘要容器:跳过高度为 0 的精确 child,取仍可见的最内层聚合节点。 */
-function queryVisibleAggregateContainer(
- root: ParentNode,
- clientId: string,
-): HTMLElement | null {
+function queryVisibleAggregateContainer(root: ParentNode, clientId: string): HTMLElement | null {
const matches = root.querySelectorAll<HTMLElement>(
`[data-message-client-ids~="${CSS.escape(clientId)}"]`,
);
@@ -1202,10 +1202,7 @@ export function shouldRefreshExpandedChildViewportAnchor(input: {
snapshotMessageClientId: string | undefined;
viewportTopItemHasVisibleExactChild: boolean;
}): boolean {
- return (
- input.snapshotMessageClientId === undefined &&
- input.viewportTopItemHasVisibleExactChild
- );
+ return input.snapshotMessageClientId === undefined && input.viewportTopItemHasVisibleExactChild;
}
function hasVisibleExactChildAnchor(itemElement: HTMLElement): boolean {
@@ -1446,9 +1443,8 @@ export function buildRenderItems(
if (!hasSubagentInternalMessages) return messages.slice(lo, hi);
const start = originalIndexByVisible[lo];
if (start === undefined) return messages.slice(lo, hi);
- const end = hi < originalIndexByVisible.length
- ? originalIndexByVisible[hi]
- : allMessages.length;
+ const end =
+ hi < originalIndexByVisible.length ? originalIndexByVisible[hi] : allMessages.length;
return allMessages.slice(start, end);
};
@@ -2019,11 +2015,7 @@ export function buildRenderItems(
} else if (msg.role === 'tool_result') {
// Orphan tool_result — skip
i++;
- } else if (
- msg.role === 'assistant'
- && !msg.systemCardType
- && msg.content.trim().length === 0
- ) {
+ } else if (msg.role === 'assistant' && !msg.systemCardType && msg.content.trim().length === 0) {
// A leaked model stop token or other empty wrap-up must not become a bubble.
i++;
} else {
@@ -2941,6 +2933,7 @@ export function MessageStream({
bottomPadding,
composerStackTopOffset,
contentWidth,
+ getContentWidth,
focusMessageClientId,
focusMessageRequestId,
forkOrigin,
@@ -3492,9 +3485,7 @@ export function MessageStream({
return;
}
const vis = visibleRenderItemsRef.current;
- const idx = snapshot
- ? vis.findIndex((item) => item.key === snapshot.viewportTopKey)
- : -1;
+ const idx = snapshot ? vis.findIndex((item) => item.key === snapshot.viewportTopKey) : -1;
const itemElement =
idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;
if (
@@ -3511,33 +3502,39 @@ export function MessageStream({
}, [refreshViewportAnchor]);
// 瞬时把 key 对应 item 的顶边摆到「容器顶边下方 offset 处」;key 不在当前窗口或
// DOM 未就绪则放弃。删除补偿与 focus 落定共用。
- const scrollKeyToViewportTop = useCallback((key: string, offset: number) => {
- const container = scrollRef.current;
- const idx = visibleRenderItemsRef.current.findIndex((item) => item.key === key);
- const child =
- idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;
- if (!container || !child) return;
- const delta =
- child.getBoundingClientRect().top - (container.getBoundingClientRect().top - offset);
- if (Math.abs(delta) < 1) return;
- const generation = beginProgrammaticScroll();
- container.scrollTop += delta;
- requestAnimationFrame(() => finishProgrammaticScroll(generation));
- }, [beginProgrammaticScroll, finishProgrammaticScroll]);
- const scrollMessageToViewportTop = useCallback((clientId: string, offset: number) => {
- const container = scrollRef.current;
- // 视口复位只认已渲染的精确 child。聚合 data-message-client-ids 命中折叠组容器
- // 会让隐藏 child 继续当活锚点,删除后把组滚到顶。focus 跳转仍走 queryFocusElement。
- const target = container ? queryMessageElement(container, clientId) : null;
- if (!container || !target) return false;
- const delta =
- target.getBoundingClientRect().top - (container.getBoundingClientRect().top - offset);
- if (Math.abs(delta) < 1) return true;
- const generation = beginProgrammaticScroll();
- container.scrollTop += delta;
- requestAnimationFrame(() => finishProgrammaticScroll(generation));
- return true;
- }, [beginProgrammaticScroll, finishProgrammaticScroll]);
+ const scrollKeyToViewportTop = useCallback(
+ (key: string, offset: number) => {
+ const container = scrollRef.current;
+ const idx = visibleRenderItemsRef.current.findIndex((item) => item.key === key);
+ const child =
+ idx >= 0 ? (itemsRef.current?.children[idx] as HTMLElement | undefined) : undefined;
+ if (!container || !child) return;
+ const delta =
+ child.getBoundingClientRect().top - (container.getBoundingClientRect().top - offset);
+ if (Math.abs(delta) < 1) return;
+ const generation = beginProgrammaticScroll();
+ container.scrollTop += delta;
+ requestAnimationFrame(() => finishProgrammaticScroll(generation));
+ },
+ [beginProgrammaticScroll, finishProgrammaticScroll],
+ );
+ const scrollMessageToViewportTop = useCallback(
+ (clientId: string, offset: number) => {
+ const container = scrollRef.current;
+ // 视口复位只认已渲染的精确 child。聚合 data-message-client-ids 命中折叠组容器
+ // 会让隐藏 child 继续当活锚点,删除后把组滚到顶。focus 跳转仍走 queryFocusElement。
+ const target = container ? queryMessageElement(container, clientId) : null;
+ if (!container || !target) return false;
+ const delta =
+ target.getBoundingClientRect().top - (container.getBoundingClientRect().top - offset);
+ if (Math.abs(delta) < 1) return true;
+ const generation = beginProgrammaticScroll();
+ container.scrollTop += delta;
+ requestAnimationFrame(() => finishProgrammaticScroll(generation));
+ return true;
+ },
+ [beginProgrammaticScroll, finishProgrammaticScroll],
+ );
const restoreViewportSnapshot = useCallback(
(snapshot: ViewportTopSnapshot, itemOffset = snapshot.offset): boolean => {
if (
@@ -3692,11 +3689,7 @@ export function MessageStream({
const replayingDelete = finishProgrammaticScroll(jump.scrollGeneration);
if (!snapshotPinned && replayingDelete === false) refreshViewportAnchor();
});
- }, [
- finishProgrammaticScroll,
- refreshViewportAnchor,
- restoreViewportSnapshotOrRebuildWindow,
- ]);
+ }, [finishProgrammaticScroll, refreshViewportAnchor, restoreViewportSnapshotOrRebuildWindow]);
// 接管 / 落定监听挂载级注册一次,读 focusJumpRef 判定,无活跃跳转时空转。挂在下面
// 的 reactive effect 里会被流式重渲染的 cleanup 拆掉且早退分支不再重挂,导致接管
// 失灵、兜底 timer 落定时把用户拽回目标。
@@ -4260,46 +4253,53 @@ export function MessageStream({
// 正常落定:删除 / 流式更新可能让 smooth 开始时算出的像素落点失效。必须按本次
// generation 保存的目标标识重新查 DOM、瞬时校正后,才能让确定落点消费延期删除补偿。
// 目标已被删 / DOM 不可用时不消费,交给通用删除补偿重放。
- const settleChipJump = useCallback((expectedGeneration?: number) => {
- const generation = expectedGeneration ?? chipJumpGenerationRef.current;
- if (generation === null || chipJumpGenerationRef.current !== generation) return;
- const target = chipJumpTargetRef.current;
- let targetResolved = false;
- const root = scrollRef.current;
- if (root && target?.generation === generation) {
- const selectorAttribute =
- target.selector === 'user-message' ? 'data-user-msg-id' : 'data-message-client-id';
- const element = root.querySelector<HTMLElement>(
- `[${selectorAttribute}="${CSS.escape(target.clientId)}"]`,
- );
- if (element) {
- const correctedScrollTop = resolveChipJumpTargetScrollTop({
- scrollTop: root.scrollTop,
- containerTop: root.getBoundingClientRect().top,
- targetTop: element.getBoundingClientRect().top,
- topOffset: target.topOffset,
- });
- if (Math.abs(correctedScrollTop - root.scrollTop) >= 1) root.scrollTop = correctedScrollTop;
- targetResolved = true;
+ const settleChipJump = useCallback(
+ (expectedGeneration?: number) => {
+ const generation = expectedGeneration ?? chipJumpGenerationRef.current;
+ if (generation === null || chipJumpGenerationRef.current !== generation) return;
+ const target = chipJumpTargetRef.current;
+ let targetResolved = false;
+ const root = scrollRef.current;
+ if (root && target?.generation === generation) {
+ const selectorAttribute =
+ target.selector === 'user-message' ? 'data-user-msg-id' : 'data-message-client-id';
+ const element = root.querySelector<HTMLElement>(
+ `[${selectorAttribute}="${CSS.escape(target.clientId)}"]`,
+ );
+ if (element) {
+ const correctedScrollTop = resolveChipJumpTargetScrollTop({
+ scrollTop: root.scrollTop,
+ containerTop: root.getBoundingClientRect().top,
+ targetTop: element.getBoundingClientRect().top,
+ topOffset: target.topOffset,
+ });
+ if (Math.abs(correctedScrollTop - root.scrollTop) >= 1)
+ root.scrollTop = correctedScrollTop;
+ targetResolved = true;
+ }
}
- }
- // 只消费校正前已观察到的删除;校正后、下一帧 finish 前新到的删除会重新置位,
- // 仍由 finish 触发重放,不能被这次导航一并吞掉。
- if (targetResolved) deferredDeleteCompensationRef.current = false;
- requestAnimationFrame(() => finishChipJump(generation, { refreshAnchor: true }));
- }, [finishChipJump]);
- const beginChipJump = useCallback((target: Omit<ChipJumpTarget, 'generation'>) => {
- if (chipJumpClearTimerRef.current !== null) {
- window.clearTimeout(chipJumpClearTimerRef.current);
- }
- chipJumpInProgressRef.current = true;
- const generation = beginProgrammaticScroll();
- chipJumpGenerationRef.current = generation;
- chipJumpTargetRef.current = { ...target, generation };
- chipJumpClearTimerRef.current = window.setTimeout(() => {
- settleChipJump(generation);
- }, CHIP_JUMP_SAFETY_MS);
- }, [beginProgrammaticScroll, settleChipJump]);
+ // 只消费校正前已观察到的删除;校正后、下一帧 finish 前新到的删除会重新置位,
+ // 仍由 finish 触发重放,不能被这次导航一并吞掉。
+ if (targetResolved) deferredDeleteCompensationRef.current = false;
+ requestAnimationFrame(() => finishChipJump(generation, { refreshAnchor: true }));
+ },
+ [finishChipJump],
+ );
+ const beginChipJump = useCallback(
+ (target: Omit<ChipJumpTarget, 'generation'>) => {
+ if (chipJumpClearTimerRef.current !== null) {
+ window.clearTimeout(chipJumpClearTimerRef.current);
+ }
+ chipJumpInProgressRef.current = true;
+ const generation = beginProgrammaticScroll();
+ chipJumpGenerationRef.current = generation;
+ chipJumpTargetRef.current = { ...target, generation };
+ chipJumpClearTimerRef.current = window.setTimeout(() => {
+ settleChipJump(generation);
+ }, CHIP_JUMP_SAFETY_MS);
+ },
+ [beginProgrammaticScroll, settleChipJump],
+ );
useEffect(() => {
const root = scrollRef.current;
if (!root) return;
@@ -4524,7 +4524,13 @@ export function MessageStream({
window.setTimeout(() => {
if (finishProgrammaticScroll(generation) === false) refreshViewportAnchor();
}, CHIP_JUMP_SAFETY_MS);
- }, [beginProgrammaticScroll, cancelFocusJump, finishChipJump, finishProgrammaticScroll, refreshViewportAnchor]);
+ }, [
+ beginProgrammaticScroll,
+ cancelFocusJump,
+ finishChipJump,
+ finishProgrammaticScroll,
+ refreshViewportAnchor,
+ ]);
// ── Codex Micro 摇杆:按住持续滚动 ──
// 摇杆推住时主进程持续送 { type:'scroll', intensity },这里逐帧按速度改
@@ -4945,8 +4951,7 @@ export function MessageStream({
}
if (landing === 'container' && root && fallback) {
// 折叠摘要行可见,隐藏 child 没有精确 DOM。滚摘要到视口顶,不要复用外层旧 offset。
- const delta =
- fallback.getBoundingClientRect().top - root.getBoundingClientRect().top;
+ const delta = fallback.getBoundingClientRect().top - root.getBoundingClientRect().top;
if (Math.abs(delta) >= 1) {
const generation = beginProgrammaticScroll();
root.scrollTop += delta;
@@ -5389,14 +5394,17 @@ export function MessageStream({
const railJumpSeqRef = useRef(0);
const [railJumpRequest, setRailJumpRequest] = useState<{ id: string; seq: number } | null>(null);
const lastAppliedRailJumpRef = useRef(0);
- const handleNavRailJump = useCallback((clientId: string) => {
- // 先废弃旧搜索 focus;目标即使需要下一轮扩窗,旧 scrollend/timer 也不能抢回视口。
- // 导航条目标要到 layout effect 才能确认仍存在且 DOM 已就绪,因此这里不能提前消费
- // focus 期间延期的删除补偿:先重放补偿,目标有效时后续导航再覆盖最终落点。
- cancelFocusJump();
- railJumpSeqRef.current += 1;
- setRailJumpRequest({ id: clientId, seq: railJumpSeqRef.current });
- }, [cancelFocusJump]);
+ const handleNavRailJump = useCallback(
+ (clientId: string) => {
+ // 先废弃旧搜索 focus;目标即使需要下一轮扩窗,旧 scrollend/timer 也不能抢回视口。
+ // 导航条目标要到 layout effect 才能确认仍存在且 DOM 已就绪,因此这里不能提前消费
+ // focus 期间延期的删除补偿:先重放补偿,目标有效时后续导航再覆盖最终落点。
+ cancelFocusJump();
+ railJumpSeqRef.current += 1;
+ setRailJumpRequest({ id: clientId, seq: railJumpSeqRef.current });
+ },
+ [cancelFocusJump],
+ );
useLayoutEffect(() => {
if (!railJumpRequest) return;
@@ -5484,9 +5492,7 @@ export function MessageStream({
// 知道"是不是最后一条"来跳过重复渲染。走可见序列:尾部挂着子代理内部行时,
// 真实的最后一条可见 error 会因为"不是最后一条"而在流内重复渲染一遍。
const lastMessageClientId =
- visibleMessages.length > 0
- ? visibleMessages[visibleMessages.length - 1].clientId
- : undefined;
+ visibleMessages.length > 0 ? visibleMessages[visibleMessages.length - 1].clientId : undefined;
const previousLocalFileRefsRef = useRef<readonly KnownLocalFileRef[]>([]);
const localFileRefs = useMemo<readonly KnownLocalFileRef[]>(() => {
return collectStableLocalFileRefs(messages, previousLocalFileRefsRef.current);
@@ -5966,7 +5972,8 @@ export function MessageStream({
<MessageNavRail
entries={navRailEntries}
scrollRef={scrollRef}
- contentMaxWidth={contentWidth ?? 880}
+ contentMaxWidth={getContentWidth?.() || 880}
+ getContentMaxWidth={getContentWidth}
bottomOffset={resolvedBottomPadding}
onJump={handleNavRailJump}
onNavCoverageChange={setNavRailCoversNav}
diff --git a/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx b/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx
index 54bfb7480b..df216d3432 100644
--- a/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx
+++ b/apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx
@@ -13,7 +13,14 @@
* Esc / ⌘A 都应生效。本组件只在选择模式挂载,所以无需额外的 active 判断。
*/
-import { useCallback, useEffect, useRef, useState } from 'react';
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type CSSProperties,
+} from 'react';
import { Check } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -39,18 +46,24 @@ const log = createLogger('ShareSelectionBar');
interface ShareSelectionBarProps {
sessionId: string;
- /** 聊天内容宽度,透传给光栅化以保证换行与流里一致。 */
- contentWidth: number;
+ /** 按下导出时读取最新聊天内容宽度,保证光栅化换行与流里一致。 */
+ getContentWidth: () => number;
/** 操作条自身宽度,与 ChatInput 对齐。 */
- barWidth: number;
+ barWidth: CSSProperties['width'];
}
type BusyKind = 'copy' | 'download';
-export function ShareSelectionBar({ sessionId, contentWidth, barWidth }: ShareSelectionBarProps) {
+export function ShareSelectionBar({
+ sessionId,
+ getContentWidth,
+ barWidth,
+}: ShareSelectionBarProps) {
const { t } = useTranslation();
const count = useShareSelectionCount();
const [busy, setBusy] = useState<BusyKind | null>(null);
+ const [compactLayout, setCompactLayout] = useState(false);
+ const barRef = useRef<HTMLDivElement | null>(null);
const mountedRef = useRef(true);
const selectionBeforeSelectAllRef = useRef<string[] | null>(null);
// 页脚使用产品指定的 Cindy 主视觉;wordmark 仍跟随当前主题。
@@ -64,7 +77,18 @@ export function ShareSelectionBar({ sessionId, contentWidth, barWidth }: ShareSe
shareableMessageIds.length > 0 &&
selectedVisibleCount === shareableMessageIds.length &&
selectedVisibleCount === count;
- const compactLayout = barWidth < 640;
+ useLayoutEffect(() => {
+ const bar = barRef.current;
+ if (!bar) return;
+ const update = () => {
+ const nextCompact = bar.getBoundingClientRect().width < 640;
+ setCompactLayout((current) => (current === nextCompact ? current : nextCompact));
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(bar);
+ return () => observer.disconnect();
+ }, []);
// 全选与产物顺序都以「已渲染的消息」为准(见 queryShareableMessageIds 注释:
// render-window 外的消息克隆不到,按 messages 全集全选会静默丢内容)。
@@ -95,11 +119,11 @@ export function ShareSelectionBar({ sessionId, contentWidth, barWidth }: ShareSe
return buildShareImageBlob({
sessionId,
orderedSelectedIds,
- contentWidth,
+ contentWidth: getContentWidth() || 880,
logoSrc,
characterSrc: shareCharacterSrc,
});
- }, [contentWidth, logoSrc, sessionId]);
+ }, [getContentWidth, logoSrc, sessionId]);
const run = useCallback(
async (kind: BusyKind) => {
@@ -172,6 +196,7 @@ export function ShareSelectionBar({ sessionId, contentWidth, barWidth }: ShareSe
return (
<div
+ ref={barRef}
{...{ [SHARE_EXCLUDE_ATTR]: '' }}
style={{ width: barWidth }}
className={cn(
diff --git a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
index 3d1646e93a..5055cbbefe 100644
--- a/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TodoListCard.tsx
@@ -20,7 +20,7 @@
* --msg-tool-card-chevron: secondary(completed 置灰)
*/
-import { useEffect, useId, useRef, useState } from 'react';
+import { useEffect, useId, useRef, useState, type CSSProperties } from 'react';
import {
ChevronDown,
ChevronRight,
@@ -248,7 +248,7 @@ export function TodoListCard({
*/
animated?: boolean;
/** Composer/chat column width. Keeps the flyout inside clipped compact panes. */
- maxWidth?: number;
+ maxWidth?: CSSProperties['maxWidth'];
/** Hide the current rendered snapshot without mutating the agent's plan state. */
onDismiss?: () => void;
}) {
@@ -301,7 +301,9 @@ export function TodoListCard({
const flyoutMaxWidth =
typeof maxWidth === 'number' && Number.isFinite(maxWidth) && maxWidth > 0
? `${Math.floor(maxWidth)}px`
- : null;
+ : typeof maxWidth === 'string' && maxWidth.length > 0
+ ? maxWidth
+ : null;
return (
<div className="pointer-events-none flex w-auto shrink-0 justify-center">
@@ -417,56 +419,55 @@ export function TodoListCard({
>
{todos.map((todo, i) => (
<div key={i} className="flex h-[30px] items-center gap-[10px]">
- {/* Icon */}
- {todo.status === 'completed' && (
- <CircleCheck
- size={18}
- strokeWidth={1.5}
- className="shrink-0 text-[var(--msg-tool-card-chevron)]"
- />
- )}
- {todo.status === 'in_progress' && (
- // 呼吸表达"正在干活":挂侧栏运行态同款动画。按 SVG 常驻
- // 动画红线,动画在 span wrapper 上,SVG 本体保持静态。
- // 会话空闲(停止/失败/中断后计划仍留屏)时静止:动画只在
- // 确有 running 语义时挂载,否则等于谎报该步骤仍在执行。
- <span
- data-plan-step-active="true"
- data-plan-step-breathing={animated ? 'true' : 'false'}
- className={cn(
- 'inline-flex shrink-0',
- animated && 'session-status-breathing',
- )}
- >
- <CircleDot
- size={18}
- strokeWidth={1.5}
- className="shrink-0 text-[var(--msg-tool-card-text)]"
- />
- </span>
- )}
- {todo.status === 'pending' && (
- <Circle
- size={18}
- strokeWidth={1.5}
- className="shrink-0 text-[var(--msg-tool-card-text)]"
- />
- )}
-
- {/* Text — 对齐 Codex:completed 置灰,in_progress 高亮,pending 正常。 */}
+ {/* Icon */}
+ {todo.status === 'completed' && (
+ <CircleCheck
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-chevron)]"
+ />
+ )}
+ {todo.status === 'in_progress' && (
+ // 呼吸表达"正在干活":挂侧栏运行态同款动画。按 SVG 常驻
+ // 动画红线,动画在 span wrapper 上,SVG 本体保持静态。
+ // 会话空闲(停止/失败/中断后计划仍留屏)时静止:动画只在
+ // 确有 running 语义时挂载,否则等于谎报该步骤仍在执行。
<span
+ data-plan-step-active="true"
+ data-plan-step-breathing={animated ? 'true' : 'false'}
className={cn(
- 'mt-px truncate text-13',
- todo.status === 'completed' &&
- 'font-normal text-[var(--msg-tool-card-chevron)]',
- todo.status === 'in_progress' &&
- 'font-semibold text-[var(--msg-tool-card-text)]',
- todo.status === 'pending' &&
- 'font-normal text-[var(--msg-tool-card-text)]',
+ 'inline-flex shrink-0',
+ animated && 'session-status-breathing',
)}
>
- {todo.content}
+ <CircleDot
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
</span>
+ )}
+ {todo.status === 'pending' && (
+ <Circle
+ size={18}
+ strokeWidth={1.5}
+ className="shrink-0 text-[var(--msg-tool-card-text)]"
+ />
+ )}
+
+ {/* Text — 对齐 Codex:completed 置灰,in_progress 高亮,pending 正常。 */}
+ <span
+ className={cn(
+ 'mt-px truncate text-13',
+ todo.status === 'completed' &&
+ 'font-normal text-[var(--msg-tool-card-chevron)]',
+ todo.status === 'in_progress' &&
+ 'font-semibold text-[var(--msg-tool-card-text)]',
+ todo.status === 'pending' && 'font-normal text-[var(--msg-tool-card-text)]',
+ )}
+ >
+ {todo.content}
+ </span>
</div>
))}
</div>
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 914cfa61df..76e88bf254 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -16,7 +16,6 @@ import { LayoutRoot } from '@/layout/LayoutRoot';
import { PanelDragController } from '@/layout/PanelDragController';
import { GhostMediaLightboxHost } from '@/cindy-brain/GhostMediaLightboxHost';
import { GhostPanelBubbleLayer } from '@/cindy-brain/GhostPanelBubbleLayer';
-import { ContentAvailableWidthProvider } from '@/layout/paneWidths';
import {
migrateLegacySidebarCollapsed,
readPanelCollapsed,
@@ -60,10 +59,7 @@ import { useSidebarResize } from '@/hooks/useSidebarResize';
import { useSidebarCardMode } from '@/hooks/useSidebarCardMode';
import { useSidebarPeek } from '@/hooks/useSidebarPeek';
import { useMacFullscreen } from '@/hooks/useMacFullscreen';
-import {
- useRightSidebarResize,
- RIGHT_SIDEBAR_AVAILABLE_WIDTH_FALLBACK,
-} from '@/hooks/useRightSidebarResize';
+import { useRightSidebarResize } from '@/hooks/useRightSidebarResize';
import { isSecondaryWindow } from '@/lib/secondaryWindow';
import { useUpdateNotice } from '@/hooks/useUpdateNotice';
import { syncNotificationsEnabledToMain } from '@/hooks/useNotificationSettings';
@@ -328,22 +324,17 @@ export function MainLayout() {
),
[],
);
- // 右栏 + 中间聊天区可分配的总宽(= 窗口宽 − 左栏宽)。首帧用 fallback,挂载后
- // 由下方 useLayoutEffect 按实际布局测出。右栏按 fraction × 此值算像素宽,实现
- // 两栏按比例缩放(见 useRightSidebarResize)。
- const [rightAvailableWidth, setRightAvailableWidth] = useState(
- RIGHT_SIDEBAR_AVAILABLE_WIDTH_FALLBACK,
- );
const rowRef = useRef<HTMLDivElement>(null);
const mainRef = useRef<HTMLElement>(null);
- // B1a(去方位化):左侧占位块(pinning spacer + Sidebar)的 wrapper,
- // 可用宽度测量的唯一观测目标 —— 见下方 useLayoutEffect 注释。
+ // B1a(去方位化):左侧占位块(pinning spacer + Sidebar)的 wrapper。
+ // row/sidebar refs 仅供面板拖放命中区测量,不再驱动 live-resize React state。
const sidebarBlockRef = useRef<HTMLDivElement>(null);
// B1b-1:宽度全局一份、持久化在布局树里(不再 per-session),hook 不再收 sessionId。
// 拖宽把手已统一为引擎分割线(LayoutRoot RootDivider),hook 只剩宽度兜底 +
// 所在侧推导(rightSidebarSide 供折叠 toggle 落角)。
- const { width: rightSidebarWidth, resizeEdge: rightResizeEdge } =
- useRightSidebarResize(rightAvailableWidth);
+ // 像素宽主权在 LayoutRoot → PaneWidthContext;这里仅保留引擎缺席时的稳定
+ // fallback + 面板所在侧推导,不再让 MainLayout 订阅连续窗口宽度。
+ const { width: rightSidebarWidth, resizeEdge: rightResizeEdge } = useRightSidebarResize();
// B2b:工具面板当前贴哪条边(把手在面板朝聊天区那侧,取反即面板所在侧)。
// 经 Outlet context 下发给聊天视图 —— 折叠态的展开入口要留守面板消失的那一侧。
const rightSidebarSide: 'left' | 'right' = rightResizeEdge === 'left' ? 'right' : 'left';
@@ -393,32 +384,6 @@ export function MainLayout() {
const isSettingsRoute = location.pathname === '/settings';
const hasInlineControlledBanner = hasInlineControlledBannerPath(location.pathname);
- // 可用总宽 = 窗口宽 − 左侧占位块宽(pinning spacer + Sidebar 的 wrapper)。
- // 布局去方位化(docs/dev-rules/architecture-invariants.md):
- // 旧实现用「main 左边界」推左栏占宽,隐含"工具面板在 main 右侧"的方位假设 ——
- // 布局树把工具面板换到 main 左侧后,其展开动画每帧推动 main 左边界,
- // ResizeObserver 每帧触发 → 整个 MainLayout 每帧重渲染(实测明显卡顿),
- // 且重新引入了刻意规避的「右栏宽 → 可用宽 → 右栏宽」反馈环。
- // 现改为直接观测左侧占位块自身:窗口 / 左栏变化(折叠、rail、peek、拖宽)照常
- // 触发重算,而任何内容区 pane 的动画都不再反哺测量,与面板停靠位置彻底解耦。
- // 设置页整块不渲染(wrapper 为 null)→ 左侧占宽按 0 计,与旧行为一致。
- useLayoutEffect(() => {
- const row = rowRef.current;
- if (!row) return;
- const recompute = () => {
- const rowWidth = row.clientWidth;
- const leftWidth = sidebarBlockRef.current?.getBoundingClientRect().width ?? 0;
- setRightAvailableWidth(Math.max(0, rowWidth - leftWidth));
- };
- recompute();
- const ro = new ResizeObserver(recompute);
- ro.observe(row);
- const sidebarBlock = sidebarBlockRef.current;
- if (sidebarBlock) ro.observe(sidebarBlock);
- return () => ro.disconnect();
- // isSettingsRoute 切换会挂载 / 卸载左侧占位块,需要重绑观测目标。
- }, [isSettingsRoute]);
-
// 完全隐藏态 hover 临时浮出(peek)状态机 —— hover 折叠按钮抽屉滑出预览,
// 点击/⌘B 固定展开(pin)。rail 态(isCollapsed=false)不触发。见 useSidebarPeek。
const sidebarPeek = useSidebarPeek({
@@ -874,8 +839,7 @@ export function MainLayout() {
}, [rsbWindow]);
// RSB Maximize(Phase 6):侧栏接管整个内容区。
- // - true:`<main>` 加 hidden(display:none),RSB style width 强制 = rightAvailableWidth
- // (即"窗口宽 − 左栏宽"),RSB 占满整个非左栏区
+ // - true:`<main>` 加 hidden(display:none),RSB 走 flex-1 占满整个非左栏区
// - 全局 Esc 拦截退出 maximize(只在 maximize 态绑监听,避免抢占其它 Esc 行为)
// - 折叠 RSB 时自动退出(否则 maximize 状态下点折叠会导致主区 hidden + RSB 也 0 宽 → 全黑)
// - 不持久化:刷新 / 切 session 默认非 maximize,跟"临时聚焦视图"语义一致
@@ -1011,9 +975,7 @@ export function MainLayout() {
writeCollapsedFor(rightSidebarSessionId, false);
const snapshot = getTabSnapshot(rightSidebarSessionId);
const handoff = snapshot ? { snapshots: [snapshot] } : undefined;
- void window.electronAPI.rightSidebarWindow
- .setDetached(true, handoff)
- .catch(() => undefined);
+ void window.electronAPI.rightSidebarWindow.setDetached(true, handoff).catch(() => undefined);
}, [rightSidebarSessionId]);
const handlePageZoomIn = useCallback(() => {
@@ -1380,7 +1342,7 @@ export function MainLayout() {
)}
>
{/* 左侧占位块 wrapper(B1a):透传容器,包住 pinning spacer + Sidebar,
- 作为可用宽度测量的唯一观测目标(见上方 useLayoutEffect 注释)。
+ 作为可用宽度测量的唯一观测目标(见 paneWidths 的测量 Provider)。
flex + shrink-0 与 aside 原有的 flex child 行为一致,不改变布局;
peek 期 aside 变 fixed 出流,wrapper 宽度自然等于流内 spacer 宽。 */}
{!isSettingsRoute && (
@@ -1420,8 +1382,8 @@ export function MainLayout() {
(renderer/panels)。两大块 JSX 原样保留在 bridge 里 —— 构造与状态
所有权仍在 MainLayout(绞杀式重构 Step A:只换骨架不动组件;尺寸/
折叠仍由既有 props 驱动,树上 fraction 暂不参与渲染)。LayoutRoot 的
- root split 扁平化保证 DOM 与重构前一致(pane 无额外包装 div,flex
- 上下文与 ResizeObserver 测量逻辑不变)。 */}
+ root split 在专属内容区 flex 容器内扁平化;稳态窗口 resize 的 pane 宽度
+ 由 CSS 百分比相对剩余内容宽直接响应,不再把连续窗口宽度发布进 React)。 */}
<BuiltinPanelBridgeProvider
value={{
// 会话列表是树外全高固定柱,由上方 <Sidebar/> 直接渲染,此槽 Step A 不消费。
@@ -1546,11 +1508,9 @@ export function MainLayout() {
) : null,
}}
>
- {/* 内容区可用总宽下发给引擎(fraction → 像素宽、缝把手夹取都用它)。
- 设置页 = 全屏接管路由,非 chat 面板(右栏之外还有意识面板)统一歇业。 */}
- <ContentAvailableWidthProvider value={rightAvailableWidth}>
- <LayoutRoot suppressNonChatPanels={isSettingsRoute} />
- </ContentAvailableWidthProvider>
+ {/* 面板稳态宽度由 LayoutRoot 输出 CSS 百分比/clamp,BrowserWindow live resize
+ 不再逐像素回灌 React;设置页接管时非 chat 面板统一歇业。 */}
+ <LayoutRoot suppressNonChatPanels={isSettingsRoute} />
</BuiltinPanelBridgeProvider>
{/* 拖面板换位(B3 转正;M3 起 mac 同步开闸——mac 顶栏全部保留窗口拖拽,
手势天然只剩长按窗体)。总开关只管全局语境(内容区路由在场、非
@@ -1602,21 +1562,21 @@ export function MainLayout() {
rightSidebarAvailable &&
rsbWindow.loaded &&
(rsbDetached || isRightSidebarCollapsed) && (
- <div
- className="absolute right-0 top-0 z-50 flex h-[46px] items-center gap-1 pr-2"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- >
- {/* 固定唤起入口只负责显示 / 聚焦。detach / maximize / 收起属于面板自身,
+ <div
+ className="absolute right-0 top-0 z-50 flex h-[46px] items-center gap-1 pr-2"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {/* 固定唤起入口只负责显示 / 聚焦。detach / maximize / 收起属于面板自身,
在 RightSidebarShell 的顶栏内渲染,不再与本入口混用。 */}
- <RightSidebarToggle
- size="toolbar"
- action="show"
- collapsed={rsbDetached ? !rsbWindow.open : isRightSidebarCollapsed}
- onToggle={handleOpenRightSidebar}
- side={rightSidebarSide}
- />
- </div>
- )}
+ <RightSidebarToggle
+ size="toolbar"
+ action="show"
+ collapsed={rsbDetached ? !rsbWindow.open : isRightSidebarCollapsed}
+ onToggle={handleOpenRightSidebar}
+ side={rightSidebarSide}
+ />
+ </div>
+ )}
</div>
{/* Update notice dialog -- mounted inside FeatureSidebarSlotProvider (ThemeProvider scope) */}
{releaseNotes && (
diff --git a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
index a457b613b7..52b7a64338 100644
--- a/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
+++ b/apps/desktop/src/renderer/components/layout/RightSidebar.tsx
@@ -124,7 +124,9 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fu
// 造成"追不上窗口边缘"的橡皮筋滞后。
const [displayCollapsed, setDisplayCollapsed] = useState(isCollapsed);
const [animating, setAnimating] = useState(false);
- const [animationWidthSnapshot, setAnimationWidthSnapshot] = useState<number | null>(null);
+ const [animationWidthSnapshot, setAnimationWidthSnapshot] = useState<
+ CSSProperties['width'] | null
+ >(null);
const animateNextRef = useRef(false);
const asideRef = useRef<HTMLElement | null>(null);
// 宽度优先取引擎实时值(拖引擎缝把手逐帧跟手),未接管回落 prop。
@@ -195,9 +197,8 @@ export const RightSidebar = forwardRef<RightSidebarHandle, RightSidebarProps>(fu
animating &&
'transition-[width] duration-[250ms] ease-[cubic-bezier(0.4,0,0.2,1)] motion-reduce:duration-0',
// maximize 态:用 flex-1 撑满 row 内 sidebar 之后的剩余空间,不传 fixed
- // width —— 否则 MainLayout 的 rightAvailableWidth(基于 main rect)在 main
- // hidden 后算成"窗口宽"漏算 sidebar,RSB 被算多一个 sidebar 宽度,推 tree
- // pane 出视口(2026-07-01 用户实测 bug:maximize 后文件树消失)。
+ // width —— 否则普通态的引擎 pane width 在 main hidden 后仍会留下固定宽,
+ // 无法接管全部剩余空间(2026-07-01 用户实测 bug:maximize 后文件树消失)。
// 非 maximize:width prop 只作为 preferred width。允许 flex shrink,配合 main
// 的 min-w-[400px] 让极窄窗口下 RSB 温和变窄,避免 280px 目标宽硬顶出窗口。
isMaximized ? 'flex-1' : 'shrink',
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 99740a6c09..909e3b6240 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -151,7 +151,12 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { PermissionSelector } from './PermissionSelector';
import { ExtraDirsButton, type CollaborationMenuConfig } from './ExtraDirsButton';
import { expandHostCapabilityInvocation } from '../../cindy-brain/hostCapabilityInvocation';
-import { focusComposerEndNextFrame, hostCapabilityForGhost, placeGhostAtComposerStart, placeHostCapabilityAtComposerStart } from './ghostComposerPlacement';
+import {
+ focusComposerEndNextFrame,
+ hostCapabilityForGhost,
+ placeGhostAtComposerStart,
+ placeHostCapabilityAtComposerStart,
+} from './ghostComposerPlacement';
import { NewGoalDialog } from './NewGoalDialog';
import { PlanModeIndicator } from './PlanModeIndicator';
import {
@@ -392,6 +397,18 @@ const ComposerHardBreak = HardBreak.extend({
// 自然宽度(permission + model + voice + send 等)估,实测可微调。
const TOOLBAR_DENSE_MAX_WIDTH = 520;
const TOOLBAR_COMPACT_MAX_WIDTH = 448;
+const TOOLBAR_NARROW_MAX_WIDTH = 600;
+const TOOLBAR_ULTRA_COMPACT_MAX_WIDTH = 420;
+
+type ToolbarWidthMode = 'unmeasured' | 'wide' | 'narrow' | 'dense' | 'compact' | 'ultra';
+
+function resolveToolbarWidthMode(width: number): ToolbarWidthMode {
+ if (width < TOOLBAR_ULTRA_COMPACT_MAX_WIDTH) return 'ultra';
+ if (width < TOOLBAR_COMPACT_MAX_WIDTH) return 'compact';
+ if (width < TOOLBAR_DENSE_MAX_WIDTH) return 'dense';
+ if (width < TOOLBAR_NARROW_MAX_WIDTH) return 'narrow';
+ return 'wide';
+}
function isVoiceInputIdleLike(state: VoiceInputState): boolean {
return state === 'idle' || state === 'done' || state === 'error';
@@ -1340,20 +1357,30 @@ export function ChatInput({
// ── 工具行宽度自适应 ────────────────────────────────────────────────
// 测 input card(mergedCardRef)实际宽度,窄宽时自动收紧工具行。主会话被右栏
// 拖宽压窄时据此折叠,行为对齐 doc rail(doc rail 仍按 denseToolbar 强制收紧,
- // 二者取 OR)。ResizeObserver 只读宽度、值不变时 React 跳过 setState,不影响
- // 输入热路径。
- const [toolbarWidth, setToolbarWidth] = useState<number | null>(null);
+ // 二者取 OR)。窗口连续 resize 时只在跨越离散断点后更新 React;同一档位内的
+ // 逐像素变化完全交给 CSS 布局,不再重渲染整棵 ChatInput。
+ const [toolbarWidthMode, setToolbarWidthMode] = useState<ToolbarWidthMode>('unmeasured');
useLayoutEffect(() => {
const el = mergedCardRef.current;
if (!el) return;
- const update = () => setToolbarWidth(el.clientWidth);
+ const update = () => {
+ const nextMode = resolveToolbarWidthMode(el.clientWidth);
+ setToolbarWidthMode((currentMode) => (currentMode === nextMode ? currentMode : nextMode));
+ };
update();
const ro = new ResizeObserver(update);
ro.observe(el);
return () => ro.disconnect();
}, []);
- const autoDenseToolbar = toolbarWidth != null && toolbarWidth < TOOLBAR_DENSE_MAX_WIDTH;
- const autoCompactToolbar = toolbarWidth != null && toolbarWidth < TOOLBAR_COMPACT_MAX_WIDTH;
+ const toolbarWidthMeasured = toolbarWidthMode !== 'unmeasured';
+ const autoNarrowToolbar =
+ toolbarWidthMode === 'narrow' ||
+ toolbarWidthMode === 'dense' ||
+ toolbarWidthMode === 'compact' ||
+ toolbarWidthMode === 'ultra';
+ const autoDenseToolbar =
+ toolbarWidthMode === 'dense' || toolbarWidthMode === 'compact' || toolbarWidthMode === 'ultra';
+ const autoCompactToolbar = toolbarWidthMode === 'compact' || toolbarWidthMode === 'ultra';
const effectiveDenseToolbar = denseToolbar || autoDenseToolbar;
const effectiveCompactToolbar = compactToolbar || autoCompactToolbar;
@@ -2861,52 +2888,49 @@ export function ChatInput({
);
// 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或
// Host 入口或未生效项保留展示但置灰(entry 级 disabled + 原因)。
- const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(
- () => {
- // device-link 会话的插件运行在被控端;控制端清单既不代表远端已安装
- // 状态,选择后也无法用本地 InstalledGhost 解析并插入命令。fail-closed:
- // 仅 deviceLinkDeviceId === null(已确认本机)才展示;undefined(所有权
- // 尚未解析)与 string(远程)一律隐藏,避免 bootstrap/重连窗口期把控制端
- // 本地插件项泄漏进可能落为远程的会话。
- if (deviceLinkDeviceId !== null) return [];
- return pluginsForMenu.map((ghost) => {
- const hasCommand = !!ghost.manifest.command;
- const hostCapability = remoteHostId ? null : hostCapabilityForGhost(ghost);
- const hasComposerEntry = hasCommand || hostCapability !== null;
- const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;
- const entryKey = ghost.manifest.command ?? hostCapability ?? '';
- return {
- item: {
- type: 'plugin-command' as const,
- name: ghost.manifest.name,
- relPath:
- ghost.manifest.command ??
- (hostCapability
- ? `cindy://host-capability/${hostCapability}`
- : `cindy://plugin/${ghost.manifest.id}`),
- pluginId: ghost.manifest.id,
- ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
- sourceLabel: entryKey,
- _nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),
- _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),
- },
- ...(selectable
- ? {}
- : {
- disabled: true,
- disabledReason: t(
- !pluginAvailableIds.has(ghost.manifest.id)
- ? 'extraDirs.pluginDisabled'
- : ghost.manifest.slots.includes('skill')
- ? 'extraDirs.pluginAgentInvoked'
- : 'extraDirs.pluginNoCommand',
- ),
- }),
- };
- });
- },
- [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t],
- );
+ const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(() => {
+ // device-link 会话的插件运行在被控端;控制端清单既不代表远端已安装
+ // 状态,选择后也无法用本地 InstalledGhost 解析并插入命令。fail-closed:
+ // 仅 deviceLinkDeviceId === null(已确认本机)才展示;undefined(所有权
+ // 尚未解析)与 string(远程)一律隐藏,避免 bootstrap/重连窗口期把控制端
+ // 本地插件项泄漏进可能落为远程的会话。
+ if (deviceLinkDeviceId !== null) return [];
+ return pluginsForMenu.map((ghost) => {
+ const hasCommand = !!ghost.manifest.command;
+ const hostCapability = remoteHostId ? null : hostCapabilityForGhost(ghost);
+ const hasComposerEntry = hasCommand || hostCapability !== null;
+ const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;
+ const entryKey = ghost.manifest.command ?? hostCapability ?? '';
+ return {
+ item: {
+ type: 'plugin-command' as const,
+ name: ghost.manifest.name,
+ relPath:
+ ghost.manifest.command ??
+ (hostCapability
+ ? `cindy://host-capability/${hostCapability}`
+ : `cindy://plugin/${ghost.manifest.id}`),
+ pluginId: ghost.manifest.id,
+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),
+ sourceLabel: entryKey,
+ _nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),
+ _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),
+ },
+ ...(selectable
+ ? {}
+ : {
+ disabled: true,
+ disabledReason: t(
+ !pluginAvailableIds.has(ghost.manifest.id)
+ ? 'extraDirs.pluginDisabled'
+ : ghost.manifest.slots.includes('skill')
+ ? 'extraDirs.pluginAgentInvoked'
+ : 'extraDirs.pluginNoCommand',
+ ),
+ }),
+ };
+ });
+ }, [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t]);
useEffect(() => {
setGhostCommandRoster(editor, ghostsForCommand);
}, [editor, ghostsForCommand]);
@@ -2996,10 +3020,7 @@ export function ChatInput({
persistKey &&
persistKey === editorStorageKey
) {
- armDetachedVoiceDraftPersist(
- persistKey,
- voiceDraftTextRef.current.trim(),
- );
+ armDetachedVoiceDraftPersist(persistKey, voiceDraftTextRef.current.trim());
}
};
}, [editor]);
@@ -3824,8 +3845,7 @@ export function ChatInput({
// 阻塞用户发送正文。仅已确认本机(deviceLinkDeviceId === null 且无
// remoteHostId)才恢复,否则静默丢弃芯片意图。
const dlDeviceId = deviceLinkDeviceIdRef.current;
- const canPlaceHostCapability =
- !remoteHostIdRef.current && dlDeviceId === null;
+ const canPlaceHostCapability = !remoteHostIdRef.current && dlDeviceId === null;
// 归属未解析(deviceLinkDeviceId === undefined)且非 SSH 时延后决定:不清除
// pendingHostCapabilityGhostId,等归属解析后 effect 重跑。若此时清除,
// 后续解析成本机也无法恢复芯片,Host 插件(如 iOS Simulator)的"使用"
@@ -4096,9 +4116,13 @@ export function ChatInput({
useEffect(() => {
reloadSlashCommands();
}, [reloadSlashCommands]);
- useEffect(() => window.electronAPI.maker.onPiPackagesChanged(() => {
- reloadSlashCommands({ forceReload: true });
- }), [reloadSlashCommands]);
+ useEffect(
+ () =>
+ window.electronAPI.maker.onPiPackagesChanged(() => {
+ reloadSlashCommands({ forceReload: true });
+ }),
+ [reloadSlashCommands],
+ );
// Slash 指令与 $意识一致:doc 保持可逐字编辑的普通文本,完整命中当前 roster
// 时才由 decoration 显示确认胶囊。异步 roster 刷新不进入 keystroke 热路径。
useEffect(() => {
@@ -4635,13 +4659,7 @@ export function ChatInput({
tr.replaceWith(from, runEnd, editor.schema.text(`$${cmd.name} `));
} else {
// 展示层写入人类名(`/git`);Pi 线路名(`/skill:git`)只在发送期改写。
- replaceSlashCommandRunWithText(
- tr,
- editor.schema,
- from,
- runEnd,
- cmd.name,
- );
+ replaceSlashCommandRunWithText(tr, editor.schema, from, runEnd, cmd.name);
}
return true;
})
@@ -4794,13 +4812,7 @@ export function ChatInput({
.run();
closeAtPanel();
},
- [
- closeAtPanel,
- editor,
- effectiveAt,
- resolveEffectiveAtRange,
- setSyntheticAtAnchor,
- ],
+ [closeAtPanel, editor, effectiveAt, resolveEffectiveAtRange, setSyntheticAtAnchor],
);
const handleComposerSuggestionSelect = useCallback(
@@ -4899,8 +4911,7 @@ export function ChatInput({
// click-time snapshot is cleared. A background source send after a
// session switch must not lock the newly restored composer.
const lockCurrentComposer =
- !optimisticallyClearRemoteComposer &&
- storageKeyForDraftRef.current === sourceStorageKey;
+ !optimisticallyClearRemoteComposer && storageKeyForDraftRef.current === sourceStorageKey;
if (lockCurrentComposer) {
captureSendFocusForRestore();
setSendDispatchInFlight(true);
@@ -5505,10 +5516,7 @@ export function ChatInput({
]);
} finally {
if (timeoutId !== undefined) clearTimeout(timeoutId);
- if (
- lockComposerForEffort &&
- storageKeyForDraftRef.current === sourceStorageKey
- ) {
+ if (lockComposerForEffort && storageKeyForDraftRef.current === sourceStorageKey) {
setSendDispatchInFlight(false);
}
}
@@ -5567,10 +5575,7 @@ export function ChatInput({
if (!optimisticallyClearRemoteComposer) clearSentComposer();
} finally {
dispatchSendInFlightKeysRef.current.delete(sendInFlightKey);
- if (
- lockCurrentComposer &&
- storageKeyForDraftRef.current === sourceStorageKey
- ) {
+ if (lockCurrentComposer && storageKeyForDraftRef.current === sourceStorageKey) {
setSendDispatchInFlight(false);
}
finishAgentSendDispatch();
@@ -5820,19 +5825,12 @@ export function ChatInput({
opts.remoteDeviceId ?? getSessionDeviceId(sessionId) ?? deviceLinkDeviceId;
const markModelChoice = opts.markModelChoice === true;
if (!remoteDeviceId) {
- const vendor =
- agentKind === 'codex'
- ? 'codex'
- : agentKind === 'pi'
- ? 'pi'
- : 'cc';
+ const vendor = agentKind === 'codex' ? 'codex' : agentKind === 'pi' ? 'pi' : 'cc';
const persistPrefs = markModelChoice ? patchVendorPrefs : patchVendorPrefsPreservingModelChoice;
persistPrefs(vendor, {
// 换模才带配对并打标记。本机只改思考档 / Fast 不写回活动模型,
// 避免未打标用户把区域默认改成当前任务模型。
- ...(markModelChoice
- ? { model: modelId, providerId: activeProviderId ?? null }
- : {}),
+ ...(markModelChoice ? { model: modelId, providerId: activeProviderId ?? null } : {}),
...(patch.effort !== undefined ? { effort: patch.effort } : {}),
});
if (memoryProviderId) {
@@ -5914,9 +5912,9 @@ export function ChatInput({
})) !== false
);
}
- const sourceRemoteDeviceId = (sessionId
- ? (deviceLinkDeviceId ?? getSessionDeviceId(sessionId))
- : deviceLinkDeviceId) ?? undefined;
+ const sourceRemoteDeviceId =
+ (sessionId ? (deviceLinkDeviceId ?? getSessionDeviceId(sessionId)) : deviceLinkDeviceId) ??
+ undefined;
const persisted = await persistFastModeChange(enabled, {
remoteDeviceId: sourceRemoteDeviceId,
});
@@ -6035,7 +6033,9 @@ export function ChatInput({
// 真源必须用 `runtimeAgentKind`,绝不能用 vendorKey / 意图目标 —— 那两个在意图期
// 会翻到目标引擎,把「继续切到意图目标」错判成同引擎、把确认框跳过。
hasSwitchIntent:
- !!sessionId && !!targetAgent && runtimeAgentKind != null && runtimeAgentKind === targetAgent,
+ !!sessionId &&
+ !!targetAgent &&
+ runtimeAgentKind != null && runtimeAgentKind === targetAgent,
confirm: confirmDialog,
copy: {
title: t('newChat.chatInput.agentSwitch.confirmation.title'),
@@ -6721,9 +6721,13 @@ export function ChatInput({
// 默认 success 1200ms 读不完这句;拉长到 4s。
toast.success(t('newChat.chatInput.credentialSwitchDeferred'), { duration: 4000 });
}
- syncSessionDraftModelPrefs(newModelId, { effort: newEffort, fast: restoredFast }, {
- markModelChoice: true,
- });
+ syncSessionDraftModelPrefs(
+ newModelId,
+ { effort: newEffort, fast: restoredFast },
+ {
+ markModelChoice: true,
+ },
+ );
if (currentModelAgentKind && effectiveSourceId) {
modelMemory?.setFast(
currentModelAgentKind,
@@ -7488,8 +7492,7 @@ export function ChatInput({
const hasMessage = !isEditorEmpty(editor);
renderSnapshotRef.current = composerRenderSnapshot(trigger, hasMessage);
const canSend = hasMessage || hasAttachments || browserComments.length > 0;
- const hasVoiceDraftText =
- voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0;
+ const hasVoiceDraftText = voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0;
// 推荐 overlay 的可见判据:开关开启 + 有推荐词 + 输入框空 + 无附件/浏览器评论/语音草稿 + 输入框未锁定。
// composerMutationLocked 涵盖 disabled、sendDispatchInFlight、当前输入框所属语音及远程只读/锁定状态。
const showRecommendationOverlay = shouldShowComposerPromptRecommendation({
@@ -7580,10 +7583,11 @@ export function ChatInput({
// split-pane 同时打开侧栏 / 会话 / 浏览器时,普通会话 composer 也会落到窄容器。
// 这里必须按 card 实际宽度统一切 compact,而不是只照顾 create-agent;否则普通
// 会话仍走两组 max-content flex,长模型名会把权限入口挤进语音 / 发送固定动作区。
- const useNarrowToolbar = narrowToolbar || (toolbarWidth != null && toolbarWidth < 600);
+ const useNarrowToolbar = narrowToolbar || autoNarrowToolbar;
const useCompactMiddleToolbar =
- isCreateAgentVariant && (toolbarWidth == null ? narrowToolbar : toolbarWidth < 600);
- const useUltraCompactToolbar = useNarrowToolbar && (toolbarWidth == null || toolbarWidth < 420);
+ isCreateAgentVariant && (toolbarWidthMeasured ? autoNarrowToolbar : narrowToolbar);
+ const useUltraCompactToolbar =
+ useNarrowToolbar && (!toolbarWidthMeasured || toolbarWidthMode === 'ultra');
return (
<div className="relative flex w-full flex-col items-center gap-4" data-chat-input-root>
diff --git a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
index 80ebe5069a..7fd98bd88d 100644
--- a/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx
@@ -19,7 +19,7 @@
* 继续留在聊天记录里,但胶囊立即永久退场。
*/
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
import {
getLatestMessageTodoState,
isPlanUserBoundary,
@@ -50,7 +50,7 @@ export function PinnedPlanPanel({
*/
animated: boolean;
/** 与 composer 同宽(inputWidth),胶囊在该宽度内居中,浮层不超出。 */
- width: number;
+ width: CSSProperties['width'];
taskHistoryMayBeIncomplete?: boolean;
/** 交互卡接管底部区域时只隐藏视图,保留完成后的计时与已收起状态。 */
visible?: boolean;
@@ -146,7 +146,8 @@ export function PinnedPlanPanel({
useEffect(() => {
if (completionDeadlineMs === null || !completionIdentity) return;
const current = deadlineFloorRef.current;
- if (current?.identity === completionIdentity && current.deadlineMs >= completionDeadlineMs) return;
+ if (current?.identity === completionIdentity && current.deadlineMs >= completionDeadlineMs)
+ return;
deadlineFloorRef.current = { identity: completionIdentity, deadlineMs: completionDeadlineMs };
}, [completionDeadlineMs, completionIdentity]);
const snapshotIdentity = insertion
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 76c9dbe016..d17cf162a5 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -202,10 +202,7 @@ import { useSessionHardwareTaskActions } from './lib/sessionHardwareTaskActions'
import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';
import { getModelById, getDefaultModelForVendor, getModelsForVendor } from '@/lib/modelDefinitions';
import { resolveDisplayContextWindow } from '@/lib/contextWindow';
-import {
- formatRunningTokenCount,
- resolveRunningUsageMeta,
-} from './lib/runningTokenUsage';
+import { formatRunningTokenCount, resolveRunningUsageMeta } from './lib/runningTokenUsage';
import { matchNavigationCommandName, tryHandleNavigationCommand } from '@/lib/navigationCommands';
import { extractIpcError } from '@/utils/ipcError';
import { listActiveRunsForSession } from '@/features/learn/useLearnRun';
@@ -706,14 +703,19 @@ export function CCAgentSessionView({
// 历史 caveat(已不再适用):早期尝试过按 `rightSidebarCollapsed` 布尔即时切 compact,
// 右栏 250ms transition 期间 parent 还是 stale 宽度,messageWidth 先扩出去顶过
// parent → mx-auto 失效 → padding 被压成 0 → 视觉上消息"先顶到最左再缩回来"。
- // 现在的方案由 hook 内 ResizeObserver 回调驱动 compact 切换,只在父宽**已经收敛**
- // 的那一帧切, 该跳变彻底没有触发面。所以这里继续只传 isCompactRail,不要再叠
+ // 现在的方案由 hook 内 ResizeObserver 直接更新继承 CSS 宽度变量;React 只在
+ // compact 阈值跨越时切换一次。这里继续只传 isCompactRail,不要再叠
// rightSidebarCollapsed 进来。
- const { containerRef, messageWidth, inputWidth, inputPad, isCompact } = useProportionalWidth(
- 914,
- { compact: isCompactRail },
- );
- const controlledBannerMaxWidth = getControlledBannerMaxWidth(inputWidth);
+ const {
+ containerRef,
+ messageWidth,
+ inputWidth,
+ inputPad,
+ inputHalfWidth,
+ isCompact,
+ getMessageWidth,
+ } = useProportionalWidth(914, { compact: isCompactRail });
+ const controlledBannerMaxWidth = `min(${inputHalfWidth}, ${CONTROLLED_BANNER_MAX_WIDTH}px)`;
const { sessions: allSessions, refreshSessions, patchLocal: patchLocalSession } = useCCSessions();
// /ctr 接管态: attached=true 时把 ChatInput 替换为 TakeoverMask, 防止 desktop
// 用户跟 IM 端 race; permission/ask/plan 三个 prompt 不替换 — 它们是 SDK 反向触
@@ -4012,6 +4014,7 @@ export function CCAgentSessionView({
bottomPadding={overlayHeight}
composerStackTopOffset={composerStackTopOffset}
contentWidth={messageWidth}
+ getContentWidth={getMessageWidth}
focusMessageClientId={focusedMessageTarget?.clientId ?? null}
focusMessageRequestId={focusedMessageTarget?.requestId ?? 0}
forkOrigin={forkOrigin}
@@ -4615,8 +4618,8 @@ export function CCAgentSessionView({
) : shareSelectionActive && sessionId ? (
<ShareSelectionBar
sessionId={sessionId}
- contentWidth={messageWidth}
barWidth={inputWidth}
+ getContentWidth={getMessageWidth}
/>
) : (
<ChatInput
@@ -5014,15 +5017,6 @@ function HandoffSourcePill({
const STATUS_BAR_FADE_MS = 400;
const CONTROLLED_BANNER_MAX_WIDTH = 420;
-const CONTROLLED_BANNER_WIDTH_RATIO = 0.5;
-
-function getControlledBannerMaxWidth(inputWidth?: number): number {
- if (inputWidth == null) return CONTROLLED_BANNER_MAX_WIDTH;
- return Math.max(
- 0,
- Math.min((inputWidth - 16) * CONTROLLED_BANNER_WIDTH_RATIO, CONTROLLED_BANNER_MAX_WIDTH),
- );
-}
function RunningStatusBar({
status,
@@ -5049,7 +5043,7 @@ function RunningStatusBar({
generationReliable?: boolean;
startedAt: number | null;
visible: boolean;
- inputWidth?: number;
+ inputWidth?: CSSProperties['width'];
/**
* 当前是否处于 side-task (mivo MJ 按钮等不走 LLM 的后台任务) 运行态。
* true 时隐藏右侧的 elapsed · rate 行 —— mivo 不消耗 token, 显示上一轮
@@ -5196,9 +5190,7 @@ function RunningStatusBar({
tokens: formatRunningTokenCount(animatedTokens),
});
const rateText =
- usageMeta.kind === 'rate'
- ? t('chat.runningStatus.tokenRate', { rate: usageMeta.rate })
- : null;
+ usageMeta.kind === 'rate' ? t('chat.runningStatus.tokenRate', { rate: usageMeta.rate }) : null;
// 淡入淡出/隐藏占位样式 —— 同时作用于左(状态)、右(elapsed/tokens)两段。
// visibility:hidden 只隐藏不收高,让 linger / fade 阶段稳定;淡出结束后整个
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index d89d579a6d..507e3113c0 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -302,21 +302,21 @@ function parseDraftWorktreeBranchSnapshot(
if (!value || typeof value !== 'object') return null;
const candidate = value as Partial<NewMakerWorktreeBranchPreferenceSnapshot>;
if (
- typeof candidate.baseRepo !== 'string'
- || candidate.baseRepo.length === 0
- || typeof candidate.sourceBranch !== 'string'
- || candidate.sourceBranch.length === 0
- || typeof candidate.revision !== 'number'
- || !Number.isSafeInteger(candidate.revision)
- || candidate.revision < 0
- ) return null;
+ typeof candidate.baseRepo !== 'string' ||
+ candidate.baseRepo.length === 0 ||
+ typeof candidate.sourceBranch !== 'string' ||
+ candidate.sourceBranch.length === 0 ||
+ typeof candidate.revision !== 'number' ||
+ !Number.isSafeInteger(candidate.revision) ||
+ candidate.revision < 0
+ )
+ return null;
return candidate as NewMakerWorktreeBranchPreferenceSnapshot;
}
function isWorktreeBranchPreferenceChannelUnsupported(error: unknown): boolean {
if (extractIpcError(error)?.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') return true;
- return error instanceof Error
- && /\[(?:DEVICE_LINK_)?CHANNEL_NOT_ALLOWED\]/.test(error.message);
+ return error instanceof Error && /\[(?:DEVICE_LINK_)?CHANNEL_NOT_ALLOWED\]/.test(error.message);
}
// F-COLLAB (2026-05): 老的 vendor='orca' 入口已退役,OrcaHeaderStrip 组件随之
// 删除(它是给 isOrca 分支的 ChatInput.topSlot 用的)。Lead/Worker 协作组合现在
@@ -351,6 +351,7 @@ export { NEW_MAKER_DRAFT_KEY };
/** 草稿命名空间图片缓存 URL 前缀(浏览器页面评论截图等草稿期缓存落这里)。 */
const DRAFT_IMAGE_URL_PREFIX = `xdt-image://${NEW_MAKER_DRAFT_KEY}/`;
+const DRAFT_INPUT_WIDTH_BREAKPOINTS = [560, 600, 700] as const;
/**
* 「创建即发送」路径的乐观标题 —— 让侧边栏 / 会话头 / tab 从第一帧就显示用户刚写下的
@@ -621,17 +622,19 @@ export function NewMakerDraftRoute() {
// 与进行中对话页(CCAgentSessionView 同传 914)一致,发送首条消息时输入框宽度不跳变。
// minWidth=640:小屏兜一个体面下限(与对话页对称);窄于下限时 hook 自动回落成
// "填满容器",不溢出。
- const { containerRef, inputWidth } = useProportionalWidth(914, { minWidth: 640 });
+ const { containerRef, inputWidth, inputWidthBand } = useProportionalWidth(914, {
+ minWidth: 640,
+ responsiveBreakpoints: DRAFT_INPUT_WIDTH_BREAKPOINTS,
+ });
// The available rail can shrink when either sidebar opens while the
// viewport itself remains wide. Keep the draft layout responsive to that
// actual content width rather than relying on viewport breakpoints.
- const draftContentWidth = inputWidth ?? 800;
- const isDraftNarrow = draftContentWidth < 560;
- const isDraftMedium = draftContentWidth < 700;
+ const isDraftNarrow = inputWidthBand === 0;
+ const isDraftMedium = inputWidthBand <= 2;
// Keep the full vendor switcher while the composer still has room for it.
// Icon-only mode is reserved for the tighter toolbar state, not merely a
// moderately narrow content rail (for example, when attachments are present).
- const isDraftToolbarNarrow = draftContentWidth < 600;
+ const isDraftToolbarNarrow = inputWidthBand <= 1;
const { createSession, error: createSessionError } = useCCSessions();
const vendorAuthGate = useVendorAuthGate();
const refreshWorktrees = useRefreshWorktrees();
@@ -648,16 +651,16 @@ export function NewMakerDraftRoute() {
? 'ccAgent.draft.remoteProviderUnsupported'
: code === 'REMOTE_NATIVE_OAUTH_UNAVAILABLE'
? 'ccAgent.draft.remoteNativeOauthUnavailable'
- // 轮 40-w4-t3 HIGH:远端 Pi 会话启动时 Cindy AI gateway endpoint
- // 未就绪 —— main 侧已映射同名 IPC code, 这里走已存在 5 语言的
- // logic.errors.remoteError.REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE
- // (引导去 Settings → Model Providers), 不再显示 raw 英文。
- : code === 'REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE'
+ : // 轮 40-w4-t3 HIGH:远端 Pi 会话启动时 Cindy AI gateway endpoint
+ // 未就绪 —— main 侧已映射同名 IPC code, 这里走已存在 5 语言的
+ // logic.errors.remoteError.REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE
+ // (引导去 Settings → Model Providers), 不再显示 raw 英文。
+ code === 'REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE'
? 'logic.errors.remoteError.REMOTE_GATEWAY_ENDPOINT_UNAVAILABLE'
- // 轮 42 P2(codex-connector):远端 Pi + loopback-only BYOM 被 main
- // 映射成 REMOTE_LOCAL_ONLY_PROVIDER —— 这里不映射会落通用失败
- // toast, 隐藏「换网关/远端可达 BYOM」的行动指引。
- : code === 'REMOTE_LOCAL_ONLY_PROVIDER'
+ : // 轮 42 P2(codex-connector):远端 Pi + loopback-only BYOM 被 main
+ // 映射成 REMOTE_LOCAL_ONLY_PROVIDER —— 这里不映射会落通用失败
+ // toast, 隐藏「换网关/远端可达 BYOM」的行动指引。
+ code === 'REMOTE_LOCAL_ONLY_PROVIDER'
? 'logic.errors.remoteError.REMOTE_LOCAL_ONLY_PROVIDER'
: code === 'LOCAL_OLLAMA_NOT_READY'
? 'logic.errors.remoteError.LOCAL_OLLAMA_NOT_READY'
@@ -887,19 +890,19 @@ export function NewMakerDraftRoute() {
baseRepo: wtBaseRepo,
};
wtBranchTargetRef.current = wtBranchTarget;
- const wtBranchPreferenceReady = wtBaseRepo != null
- && wtBranchSync?.deviceId === wtBranchTarget.deviceId
- && wtBranchSync.baseRepo === wtBaseRepo
- && wtBranchSync.status !== 'loading'
- && !wtBranchPreferenceError;
- const wtBranchPreferenceLoading = wtBaseRepo != null
- && !wtBranchPreferenceError
- && (
- wtBranchSync == null
- || (wtBranchSync.deviceId === wtBranchTarget.deviceId
- && wtBranchSync.baseRepo === wtBaseRepo
- && wtBranchSync.status === 'loading')
- );
+ const wtBranchPreferenceReady =
+ wtBaseRepo != null &&
+ wtBranchSync?.deviceId === wtBranchTarget.deviceId &&
+ wtBranchSync.baseRepo === wtBaseRepo &&
+ wtBranchSync.status !== 'loading' &&
+ !wtBranchPreferenceError;
+ const wtBranchPreferenceLoading =
+ wtBaseRepo != null &&
+ !wtBranchPreferenceError &&
+ (wtBranchSync == null ||
+ (wtBranchSync.deviceId === wtBranchTarget.deviceId &&
+ wtBranchSync.baseRepo === wtBaseRepo &&
+ wtBranchSync.status === 'loading'));
const wtBranchPreferenceLoadingRef = useRef(false);
wtBranchPreferenceLoadingRef.current = wtBranchPreferenceLoading;
@@ -908,38 +911,39 @@ export function NewMakerDraftRoute() {
* 设备/repo 必须仍是当前 target;同 target 只接受不小于已接收 host revision 的值。
* APPLY response 与它的 push echo revision 相等是合法的幂等重复。
*/
- const acceptWtBranchSnapshot = useCallback((
- requestTarget: DraftWorktreeBranchTarget,
- rawSnapshot: unknown,
- ): boolean => {
- const snapshot = parseDraftWorktreeBranchSnapshot(rawSnapshot);
- if (!snapshot || !requestTarget.baseRepo) return false;
- const currentTarget = wtBranchTargetRef.current;
- if (!sameDraftWorktreeBranchTarget(requestTarget, currentTarget)) return false;
- if (snapshot.baseRepo !== currentTarget.baseRepo) return false;
+ const acceptWtBranchSnapshot = useCallback(
+ (requestTarget: DraftWorktreeBranchTarget, rawSnapshot: unknown): boolean => {
+ const snapshot = parseDraftWorktreeBranchSnapshot(rawSnapshot);
+ if (!snapshot || !requestTarget.baseRepo) return false;
+ const currentTarget = wtBranchTargetRef.current;
+ if (!sameDraftWorktreeBranchTarget(requestTarget, currentTarget)) return false;
+ if (snapshot.baseRepo !== currentTarget.baseRepo) return false;
- const previous = wtBranchSyncRef.current;
- if (
- previous
- && previous.deviceId === currentTarget.deviceId
- && previous.baseRepo === snapshot.baseRepo
- && snapshot.revision < previous.revision
- ) return false;
+ const previous = wtBranchSyncRef.current;
+ if (
+ previous &&
+ previous.deviceId === currentTarget.deviceId &&
+ previous.baseRepo === snapshot.baseRepo &&
+ snapshot.revision < previous.revision
+ )
+ return false;
- const next: DraftWorktreeBranchSync = {
- deviceId: currentTarget.deviceId,
- baseRepo: snapshot.baseRepo,
- revision: snapshot.revision,
- status: 'ready',
- sourceBranch: snapshot.sourceBranch,
- };
- wtBranchSyncRef.current = next;
- setWtBranchSync(next);
- wtBranchPreferenceErrorRef.current = false;
- setWtBranchPreferenceError(false);
- setWtSourceBranch(snapshot.sourceBranch);
- return true;
- }, []);
+ const next: DraftWorktreeBranchSync = {
+ deviceId: currentTarget.deviceId,
+ baseRepo: snapshot.baseRepo,
+ revision: snapshot.revision,
+ status: 'ready',
+ sourceBranch: snapshot.sourceBranch,
+ };
+ wtBranchSyncRef.current = next;
+ setWtBranchSync(next);
+ wtBranchPreferenceErrorRef.current = false;
+ setWtBranchPreferenceError(false);
+ setWtSourceBranch(snapshot.sourceBranch);
+ return true;
+ },
+ [],
+ );
/** GET 返回 null / 明确的旧工作端不支持 channel 时才允许兼容降级。 */
const markWtBranchTargetReady = useCallback((target: DraftWorktreeBranchTarget) => {
@@ -947,11 +951,12 @@ export function NewMakerDraftRoute() {
if (!sameDraftWorktreeBranchTarget(target, wtBranchTargetRef.current)) return;
const previous = wtBranchSyncRef.current;
if (
- previous
- && previous.deviceId === target.deviceId
- && previous.baseRepo === target.baseRepo
- && previous.status !== 'loading'
- ) return;
+ previous &&
+ previous.deviceId === target.deviceId &&
+ previous.baseRepo === target.baseRepo &&
+ previous.status !== 'loading'
+ )
+ return;
const next: DraftWorktreeBranchSync = {
deviceId: target.deviceId,
baseRepo: target.baseRepo,
@@ -1208,11 +1213,9 @@ export function NewMakerDraftRoute() {
// 旧面板是「先选引擎再选模型」,所以只要没真正启用统一面板,就必须把工具条上的引擎下拉
// 还回来 —— 否则那条链路上根本换不了引擎(只按 capable 撤掉时,默认形态下的新建草稿
// 就彻底没有换引擎入口)。统一面板真启用时不注入(引擎跟着模型走)。
- const unifiedModelPanelEnabled =
- !effectiveDeviceLinkDeviceId || !deviceProvidersUnsupported;
+ const unifiedModelPanelEnabled = !effectiveDeviceLinkDeviceId || !deviceProvidersUnsupported;
const modelPickerLayoutPref = useModelPickerLayout();
- const unifiedModelPanelActive =
- unifiedModelPanelEnabled && modelPickerLayoutPref !== 'original';
+ const unifiedModelPanelActive = unifiedModelPanelEnabled && modelPickerLayoutPref !== 'original';
const remoteModelListStatus = !isDeviceLinkDraft
? 'idle'
: capabilitiesError || (deviceProvidersError && !deviceProvidersUnsupported)
@@ -1618,11 +1621,12 @@ export function NewMakerDraftRoute() {
useEffect(() => {
const transaction = wtPreferenceTransactionRef.current;
if (
- !transaction
- || !isDeviceLinkDraft
- || transaction.deviceId !== effectiveDeviceLinkDeviceId
- || remoteDraftState.status !== 'ready'
- ) return;
+ !transaction ||
+ !isDeviceLinkDraft ||
+ transaction.deviceId !== effectiveDeviceLinkDeviceId ||
+ remoteDraftState.status !== 'ready'
+ )
+ return;
const authoritative = remoteDraftState.value?.worktreeEnabled;
if (typeof authoritative !== 'boolean') return;
if (authoritative === transaction.enabled) {
@@ -1636,11 +1640,7 @@ export function NewMakerDraftRoute() {
wtPreferenceAuthorityUnknownRef.current = true;
wtPreferenceSavingRef.current = false;
setWtPreferenceSaving(false);
- }, [
- isDeviceLinkDraft,
- effectiveDeviceLinkDeviceId,
- remoteDraftState,
- ]);
+ }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId, remoteDraftState]);
// Do not release the synchronous create fence until React has committed the
// authoritative checkbox value into wtRef. This closes the APPLY-resolved →
@@ -1721,10 +1721,11 @@ export function NewMakerDraftRoute() {
// already-accepted snapshot or turn the target back into an error.
const current = wtBranchSyncRef.current;
if (
- current?.status === 'ready'
- && current.deviceId === target.deviceId
- && current.baseRepo === target.baseRepo
- ) return;
+ current?.status === 'ready' &&
+ current.deviceId === target.deviceId &&
+ current.baseRepo === target.baseRepo
+ )
+ return;
// A non-null response that cannot be parsed/accepted is not the same
// as "no saved preference". Treat malformed, wrong-repo or stale
// snapshots as an unavailable authority and keep Worktree ON closed.
@@ -1737,10 +1738,11 @@ export function NewMakerDraftRoute() {
if (cancelled || seq !== wtBranchReadSeqRef.current) return;
const current = wtBranchSyncRef.current;
if (
- current?.status === 'ready'
- && current.deviceId === target.deviceId
- && current.baseRepo === target.baseRepo
- ) return;
+ current?.status === 'ready' &&
+ current.deviceId === target.deviceId &&
+ current.baseRepo === target.baseRepo
+ )
+ return;
// 只有被控端明确声明 channel 不存在时才走旧端兼容;超时、断链、
// malformed response 等其它错误都保持未就绪,Worktree ON 创建必须阻塞。
// 这条边界不能用「catch 全部都 ready」表达,否则一次瞬时断链就会
@@ -1766,21 +1768,29 @@ export function NewMakerDraftRoute() {
]);
// 当前电脑其它窗口 / mobile 控制端改分支后,本地 main 广播权威 snapshot。
- useEffect(() => window.electronAPI.onNewMakerWorktreeBranchChanged((snapshot) => {
- const target = wtBranchTargetRef.current;
- if (target.deviceId !== null || !target.baseRepo) return;
- acceptWtBranchSnapshot(target, snapshot);
- }), [acceptWtBranchSnapshot]);
+ useEffect(
+ () =>
+ window.electronAPI.onNewMakerWorktreeBranchChanged((snapshot) => {
+ const target = wtBranchTargetRef.current;
+ if (target.deviceId !== null || !target.baseRepo) return;
+ acceptWtBranchSnapshot(target, snapshot);
+ }),
+ [acceptWtBranchSnapshot],
+ );
// device-link 草稿只接收当前目标设备转发的同名广播;payload 内 baseRepo + host
// revision 仍交统一接受器校验,不能只凭 channel 就覆盖当前 UI。
- useEffect(() => window.electronAPI.deviceLink.onRemotePush((push) => {
- const target = wtBranchTargetRef.current;
- if (!target.deviceId || !target.baseRepo) return;
- if (push.deviceId !== target.deviceId) return;
- if (push.channel !== 'maker:new-maker-worktree-branch:changed') return;
- acceptWtBranchSnapshot(target, push.payload);
- }), [acceptWtBranchSnapshot]);
+ useEffect(
+ () =>
+ window.electronAPI.deviceLink.onRemotePush((push) => {
+ const target = wtBranchTargetRef.current;
+ if (!target.deviceId || !target.baseRepo) return;
+ if (push.deviceId !== target.deviceId) return;
+ if (push.channel !== 'maker:new-maker-worktree-branch:changed') return;
+ acceptWtBranchSnapshot(target, push.payload);
+ }),
+ [acceptWtBranchSnapshot],
+ );
// Keep the branch transaction fence until the accepted host source has
// actually reached wtRef through a committed render.
@@ -2986,219 +2996,221 @@ export function NewMakerDraftRoute() {
// 用户点击 checkbox 是唯一改动路径。本地草稿直接写工作端偏好;
// device-link 草稿先把操作交给被控端,只有被控端接受后才更新控制端
// 显示镜像。分支、项目和资格变化都不能调用此回调。
- const handleWtEnabledChange = useCallback((enabled: boolean) => {
- if (sendInFlightRef.current) return;
- const writeSeq = ++wtPreferenceWriteSeqRef.current;
- wtPreferenceAuthorityUnknownRef.current = false;
- wtPreferenceCommittedValueRef.current = null;
- wtPreferenceSavingRef.current = true;
- setWtPreferenceSaving(true);
- if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {
- remoteDraftRevisionRef.current += 1;
- wtPreferenceTransactionRef.current = {
- seq: writeSeq,
- deviceId: effectiveDeviceLinkDeviceId,
- enabled,
- status: 'writing',
- };
- // Serialize host writes so A → B clicks cannot arrive at the host in the
- // opposite order. The sequence fence then ignores an old completion that
- // races a newer remote push.
- const invoke = () => window.electronAPI.deviceLink.invoke(
- effectiveDeviceLinkDeviceId,
- 'maker:apply-new-maker-worktree-pref',
- [{ worktreeEnabled: enabled }],
- );
- const write = wtPreferenceWriteChainRef.current
- .catch(() => undefined)
- .then(invoke);
- wtPreferenceWriteChainRef.current = write.catch(() => undefined);
- void write
- .then(() => {
- const transaction = wtPreferenceTransactionRef.current;
+ const handleWtEnabledChange = useCallback(
+ (enabled: boolean) => {
+ if (sendInFlightRef.current) return;
+ const writeSeq = ++wtPreferenceWriteSeqRef.current;
+ wtPreferenceAuthorityUnknownRef.current = false;
+ wtPreferenceCommittedValueRef.current = null;
+ wtPreferenceSavingRef.current = true;
+ setWtPreferenceSaving(true);
+ if (isDeviceLinkDraft && effectiveDeviceLinkDeviceId) {
+ remoteDraftRevisionRef.current += 1;
+ wtPreferenceTransactionRef.current = {
+ seq: writeSeq,
+ deviceId: effectiveDeviceLinkDeviceId,
+ enabled,
+ status: 'writing',
+ };
+ // Serialize host writes so A → B clicks cannot arrive at the host in the
+ // opposite order. The sequence fence then ignores an old completion that
+ // races a newer remote push.
+ const invoke = () =>
+ window.electronAPI.deviceLink.invoke(
+ effectiveDeviceLinkDeviceId,
+ 'maker:apply-new-maker-worktree-pref',
+ [{ worktreeEnabled: enabled }],
+ );
+ const write = wtPreferenceWriteChainRef.current.catch(() => undefined).then(invoke);
+ wtPreferenceWriteChainRef.current = write.catch(() => undefined);
+ void write
+ .then(() => {
+ const transaction = wtPreferenceTransactionRef.current;
+ if (wtPreferenceWriteSeqRef.current !== writeSeq || transaction?.seq !== writeSeq)
+ return;
+ // Main accepted the invoke, but the controlled renderer persists the
+ // preference after receiving a broadcast. Invalidate overlapping
+ // defaults GETs and keep the bidirectional create gate until a push
+ // or a fresh GET observes the requested boolean.
+ transaction.status = 'reconciling-success';
+ remoteDraftRevisionRef.current += 1;
+ setRemoteDraftState((previous) => ({
+ status: 'loading',
+ value: previous.value,
+ }));
+ setRemoteDraftRetryEpoch((value) => value + 1);
+ })
+ .catch((error) => {
+ const transaction = wtPreferenceTransactionRef.current;
+ if (wtPreferenceWriteSeqRef.current !== writeSeq || transaction?.seq !== writeSeq)
+ return;
+ if (isWorktreeBranchPreferenceChannelUnsupported(error)) {
+ // Old endpoints cannot persist this preference. Preserve the old
+ // value for ON, but still provide an explicit OFF escape from a
+ // remembered ON mirror (same compatibility boundary as mobile).
+ if (!enabled) {
+ transaction.status = 'committed';
+ wtPreferenceCommittedValueRef.current = false;
+ setWtEnabled(false);
+ } else {
+ wtPreferenceTransactionRef.current = null;
+ wtPreferenceSavingRef.current = false;
+ setWtPreferenceSaving(false);
+ }
+ return;
+ }
+ // Timeout/disconnect may have committed remotely. Re-read host
+ // authority after the invoke settles; until then both ON→OFF and
+ // OFF→ON remain blocked from Send/Goal.
+ transaction.status = 'reconciling-unknown';
+ wtPreferenceAuthorityUnknownRef.current = true;
+ wtPreferenceSavingRef.current = false;
+ setWtPreferenceSaving(false);
+ remoteDraftRevisionRef.current += 1;
+ setRemoteDraftState((previous) => ({
+ status: 'loading',
+ value: previous.value,
+ }));
+ setRemoteDraftRetryEpoch((value) => value + 1);
+ });
+ return;
+ }
+ wtPreferenceCommittedValueRef.current = enabled;
+ setWtEnabled(enabled);
+ setWorktreePreference(enabled);
+ },
+ [isDeviceLinkDraft, effectiveDeviceLinkDeviceId],
+ );
+ const handleWtSourceBranchChange = useCallback(
+ (sourceBranch: string) => {
+ if (sendInFlightRef.current) return;
+ const normalized = sourceBranch.trim();
+ const target = wtBranchTargetRef.current;
+ // GET 尚未完成时分支区会被禁用,但 React 提交 disabled 前的同一 tick 仍可能送达旧事件;
+ // 同步忽略,避免它抢在权威 repo 偏好返回前覆盖已保存的选择。
+ if (!normalized || !target.baseRepo || wtBranchPreferenceLoadingRef.current) {
+ return;
+ }
+ wtBranchCommittedValueRef.current = null;
+ const branchSyncAtStart = wtBranchSyncRef.current;
+ const revisionAtStart =
+ branchSyncAtStart &&
+ branchSyncAtStart.deviceId === target.deviceId &&
+ branchSyncAtStart.baseRepo === target.baseRepo
+ ? branchSyncAtStart.revision
+ : -1;
+
+ const writeSeq = ++wtBranchWriteSeqRef.current;
+ wtBranchPreferenceSavingRef.current = true;
+ setWtBranchPreferenceSaving(true);
+ wtBranchPreferenceErrorRef.current = false;
+ setWtBranchPreferenceError(false);
+
+ const invoke = () =>
+ target.deviceId
+ ? window.electronAPI.deviceLink.invoke(
+ target.deviceId,
+ 'maker:apply-new-maker-worktree-branch-pref',
+ [{ baseRepo: target.baseRepo, sourceBranch: normalized }],
+ )
+ : window.electronAPI.applyNewMakerWorktreeBranchPreference(target.baseRepo!, normalized);
+ const apply = wtBranchWriteChainRef.current.catch(() => undefined).then(invoke);
+ wtBranchWriteChainRef.current = apply.catch(() => undefined);
+ void apply
+ .then((snapshot) => {
+ if (writeSeq !== wtBranchWriteSeqRef.current) return;
+ const parsedSnapshot = parseDraftWorktreeBranchSnapshot(snapshot);
+ const accepted = acceptWtBranchSnapshot(target, snapshot);
if (
- wtPreferenceWriteSeqRef.current !== writeSeq
- || transaction?.seq !== writeSeq
- ) return;
- // Main accepted the invoke, but the controlled renderer persists the
- // preference after receiving a broadcast. Invalidate overlapping
- // defaults GETs and keep the bidirectional create gate until a push
- // or a fresh GET observes the requested boolean.
- transaction.status = 'reconciling-success';
- remoteDraftRevisionRef.current += 1;
- setRemoteDraftState((previous) => ({
- status: 'loading',
- value: previous.value,
- }));
- setRemoteDraftRetryEpoch((value) => value + 1);
+ accepted &&
+ parsedSnapshot!.sourceBranch === normalized &&
+ parsedSnapshot!.revision > revisionAtStart
+ ) {
+ armWtBranchCommittedValue(normalized);
+ return;
+ }
+ const current = wtBranchSyncRef.current;
+ if (
+ current?.status === 'ready' &&
+ current.deviceId === target.deviceId &&
+ current.baseRepo === target.baseRepo &&
+ current.revision > revisionAtStart &&
+ current.sourceBranch === normalized
+ ) {
+ armWtBranchCommittedValue(normalized);
+ return;
+ }
+ // A newer snapshot for another branch is still useful as the next
+ // retry's revision floor, but it cannot confirm this write. Keep the
+ // requested value visible and Worktree ON fail-closed until the user
+ // explicitly retries and host authority observes this exact branch.
+ setWtSourceBranch(normalized);
+ wtBranchPreferenceErrorRef.current = true;
+ setWtBranchPreferenceError(true);
})
.catch((error) => {
- const transaction = wtPreferenceTransactionRef.current;
+ if (writeSeq !== wtBranchWriteSeqRef.current) return;
+ const current = wtBranchSyncRef.current;
if (
- wtPreferenceWriteSeqRef.current !== writeSeq
- || transaction?.seq !== writeSeq
- ) return;
+ current?.status === 'ready' &&
+ current.deviceId === target.deviceId &&
+ current.baseRepo === target.baseRepo &&
+ current.revision > revisionAtStart &&
+ current.sourceBranch === normalized
+ ) {
+ armWtBranchCommittedValue(normalized);
+ return;
+ }
+ // 只有结构化 CHANNEL_NOT_ALLOWED 才允许旧端兼容:本次选择留在
+ // 当前草稿内存中,不冒充 host 已持久化。其它错误保持 fail-closed,
+ // Worktree ON 的 Send/Goal 会继续阻塞并允许用户重试。
if (isWorktreeBranchPreferenceChannelUnsupported(error)) {
- // Old endpoints cannot persist this preference. Preserve the old
- // value for ON, but still provide an explicit OFF escape from a
- // remembered ON mirror (same compatibility boundary as mobile).
- if (!enabled) {
- transaction.status = 'committed';
- wtPreferenceCommittedValueRef.current = false;
- setWtEnabled(false);
- } else {
- wtPreferenceTransactionRef.current = null;
- wtPreferenceSavingRef.current = false;
- setWtPreferenceSaving(false);
+ if (sameDraftWorktreeBranchTarget(target, wtBranchTargetRef.current)) {
+ setWtSourceBranch(normalized);
+ markWtBranchTargetReady(target);
+ armWtBranchCommittedValue(normalized);
}
return;
}
- // Timeout/disconnect may have committed remotely. Re-read host
- // authority after the invoke settles; until then both ON→OFF and
- // OFF→ON remain blocked from Send/Goal.
- transaction.status = 'reconciling-unknown';
- wtPreferenceAuthorityUnknownRef.current = true;
- wtPreferenceSavingRef.current = false;
- setWtPreferenceSaving(false);
- remoteDraftRevisionRef.current += 1;
- setRemoteDraftState((previous) => ({
- status: 'loading',
- value: previous.value,
- }));
- setRemoteDraftRetryEpoch((value) => value + 1);
+ setWtSourceBranch(normalized);
+ wtBranchPreferenceErrorRef.current = true;
+ setWtBranchPreferenceError(true);
+ })
+ .finally(() => {
+ if (writeSeq !== wtBranchWriteSeqRef.current) return;
+ if (wtBranchCommittedValueRef.current !== null) return;
+ wtBranchPreferenceSavingRef.current = false;
+ setWtBranchPreferenceSaving(false);
});
- return;
- }
- wtPreferenceCommittedValueRef.current = enabled;
- setWtEnabled(enabled);
- setWorktreePreference(enabled);
- }, [isDeviceLinkDraft, effectiveDeviceLinkDeviceId]);
- const handleWtSourceBranchChange = useCallback((sourceBranch: string) => {
- if (sendInFlightRef.current) return;
- const normalized = sourceBranch.trim();
- const target = wtBranchTargetRef.current;
- // GET 尚未完成时分支区会被禁用,但 React 提交 disabled 前的同一 tick 仍可能送达旧事件;
- // 同步忽略,避免它抢在权威 repo 偏好返回前覆盖已保存的选择。
- if (!normalized || !target.baseRepo || wtBranchPreferenceLoadingRef.current) {
- return;
- }
- wtBranchCommittedValueRef.current = null;
- const branchSyncAtStart = wtBranchSyncRef.current;
- const revisionAtStart = branchSyncAtStart
- && branchSyncAtStart.deviceId === target.deviceId
- && branchSyncAtStart.baseRepo === target.baseRepo
- ? branchSyncAtStart.revision
- : -1;
-
- const writeSeq = ++wtBranchWriteSeqRef.current;
- wtBranchPreferenceSavingRef.current = true;
- setWtBranchPreferenceSaving(true);
- wtBranchPreferenceErrorRef.current = false;
- setWtBranchPreferenceError(false);
-
- const invoke = () => target.deviceId
- ? window.electronAPI.deviceLink.invoke(
- target.deviceId,
- 'maker:apply-new-maker-worktree-branch-pref',
- [{ baseRepo: target.baseRepo, sourceBranch: normalized }],
+ },
+ [acceptWtBranchSnapshot, armWtBranchCommittedValue, markWtBranchTargetReady],
+ );
+ const handleWtBaseRepoChange = useCallback(
+ (baseRepo: string | null) => {
+ const nextTarget: DraftWorktreeBranchTarget = {
+ deviceId: effectiveDeviceLinkDeviceId ?? null,
+ baseRepo,
+ };
+ if (
+ wtBaseRepo === baseRepo &&
+ sameDraftWorktreeBranchTarget(nextTarget, wtBranchTargetRef.current)
)
- : window.electronAPI.applyNewMakerWorktreeBranchPreference(
- target.baseRepo!,
- normalized,
- );
- const apply = wtBranchWriteChainRef.current
- .catch(() => undefined)
- .then(invoke);
- wtBranchWriteChainRef.current = apply.catch(() => undefined);
- void apply
- .then((snapshot) => {
- if (writeSeq !== wtBranchWriteSeqRef.current) return;
- const parsedSnapshot = parseDraftWorktreeBranchSnapshot(snapshot);
- const accepted = acceptWtBranchSnapshot(target, snapshot);
- if (
- accepted
- && parsedSnapshot!.sourceBranch === normalized
- && parsedSnapshot!.revision > revisionAtStart
- ) {
- armWtBranchCommittedValue(normalized);
- return;
- }
- const current = wtBranchSyncRef.current;
- if (
- current?.status === 'ready'
- && current.deviceId === target.deviceId
- && current.baseRepo === target.baseRepo
- && current.revision > revisionAtStart
- && current.sourceBranch === normalized
- ) {
- armWtBranchCommittedValue(normalized);
- return;
- }
- // A newer snapshot for another branch is still useful as the next
- // retry's revision floor, but it cannot confirm this write. Keep the
- // requested value visible and Worktree ON fail-closed until the user
- // explicitly retries and host authority observes this exact branch.
- setWtSourceBranch(normalized);
- wtBranchPreferenceErrorRef.current = true;
- setWtBranchPreferenceError(true);
- })
- .catch((error) => {
- if (writeSeq !== wtBranchWriteSeqRef.current) return;
- const current = wtBranchSyncRef.current;
- if (
- current?.status === 'ready'
- && current.deviceId === target.deviceId
- && current.baseRepo === target.baseRepo
- && current.revision > revisionAtStart
- && current.sourceBranch === normalized
- ) {
- armWtBranchCommittedValue(normalized);
- return;
- }
- // 只有结构化 CHANNEL_NOT_ALLOWED 才允许旧端兼容:本次选择留在
- // 当前草稿内存中,不冒充 host 已持久化。其它错误保持 fail-closed,
- // Worktree ON 的 Send/Goal 会继续阻塞并允许用户重试。
- if (isWorktreeBranchPreferenceChannelUnsupported(error)) {
- if (sameDraftWorktreeBranchTarget(target, wtBranchTargetRef.current)) {
- setWtSourceBranch(normalized);
- markWtBranchTargetReady(target);
- armWtBranchCommittedValue(normalized);
- }
- return;
- }
- setWtSourceBranch(normalized);
- wtBranchPreferenceErrorRef.current = true;
- setWtBranchPreferenceError(true);
- })
- .finally(() => {
- if (writeSeq !== wtBranchWriteSeqRef.current) return;
- if (wtBranchCommittedValueRef.current !== null) return;
- wtBranchPreferenceSavingRef.current = false;
- setWtBranchPreferenceSaving(false);
- });
- }, [acceptWtBranchSnapshot, armWtBranchCommittedValue, markWtBranchTargetReady]);
- const handleWtBaseRepoChange = useCallback((baseRepo: string | null) => {
- const nextTarget: DraftWorktreeBranchTarget = {
- deviceId: effectiveDeviceLinkDeviceId ?? null,
- baseRepo,
- };
- if (
- wtBaseRepo === baseRepo
- && sameDraftWorktreeBranchTarget(nextTarget, wtBranchTargetRef.current)
- ) return;
- wtBranchReadSeqRef.current += 1;
- wtBranchWriteSeqRef.current += 1;
- wtBranchCommittedValueRef.current = null;
- wtBranchPreferenceSavingRef.current = false;
- setWtBranchPreferenceSaving(false);
- wtBranchTargetRef.current = nextTarget;
- wtBranchSyncRef.current = null;
- setWtBranchSync(null);
- wtBranchPreferenceErrorRef.current = false;
- setWtBranchPreferenceError(false);
- setWtSourceBranch('');
- setWtBaseRepo(baseRepo);
- }, [effectiveDeviceLinkDeviceId, wtBaseRepo]);
+ return;
+ wtBranchReadSeqRef.current += 1;
+ wtBranchWriteSeqRef.current += 1;
+ wtBranchCommittedValueRef.current = null;
+ wtBranchPreferenceSavingRef.current = false;
+ setWtBranchPreferenceSaving(false);
+ wtBranchTargetRef.current = nextTarget;
+ wtBranchSyncRef.current = null;
+ setWtBranchSync(null);
+ wtBranchPreferenceErrorRef.current = false;
+ setWtBranchPreferenceError(false);
+ setWtSourceBranch('');
+ setWtBaseRepo(baseRepo);
+ },
+ [effectiveDeviceLinkDeviceId, wtBaseRepo],
+ );
const handleWtRecoveryKeyDiscardSupportChange = useCallback((supported: boolean | null) => {
setWtSupportsRecoveryKeyDiscard(supported);
}, []);
@@ -3350,12 +3362,10 @@ export function NewMakerDraftRoute() {
// 确认不合格(2026-08-07 裁决)时控件隐藏、勾选不生效,偏好写入在途不应
// 卡住普通会话创建——确认不合格目录永远不会创建 worktree。
if (
- selectedWorktree.confirmedIneligible !== true
- && (
- wtPreferenceSavingRef.current
- || wtPreferenceAuthorityUnknownRef.current
- || (selectedWorktree.enabled && wtBranchPreferenceSavingRef.current)
- )
+ selectedWorktree.confirmedIneligible !== true &&
+ (wtPreferenceSavingRef.current ||
+ wtPreferenceAuthorityUnknownRef.current ||
+ (selectedWorktree.enabled && wtBranchPreferenceSavingRef.current))
) {
toast.warning(t('ccAgent.draft.deviceStillLoading'));
return false;
@@ -3374,8 +3384,8 @@ export function NewMakerDraftRoute() {
return false;
}
if (
- !selectedWorktree.branchPreferenceReady
- || (isDeviceLinkDraft && selectedWorktree.supportsRecoveryKeyDiscard !== true)
+ !selectedWorktree.branchPreferenceReady ||
+ (isDeviceLinkDraft && selectedWorktree.supportsRecoveryKeyDiscard !== true)
) {
toast.error(t('ccAgent.draft.deviceStillLoading'));
return false;
@@ -3449,11 +3459,11 @@ export function NewMakerDraftRoute() {
// 上面的发送门已阻止不完整状态;这里仍保留完整条件作副作用前的防御。
// 旧 Desktop 可能接受未知 recoveryKey 却不持久化,不能把它当成支持端发起预创建。
if (
- effectiveWorkingDir &&
- wt.enabled &&
- wt.confirmedIneligible !== true &&
- wt.baseRepo &&
- wt.supportsRecoveryKeyDiscard === true
+ effectiveWorkingDir
+ && wt.enabled
+ && wt.confirmedIneligible !== true
+ && wt.baseRepo
+ && wt.supportsRecoveryKeyDiscard === true
) {
// 账本必须绑定发起时的账号/本地数据 owner。账号在后续 await
// 期间切换时,Main 会拒绝把这笔义务落入新 owner 的命名空间。
@@ -3959,7 +3969,11 @@ export function NewMakerDraftRoute() {
ranges: readonly T[] | undefined,
): T[] | undefined => {
if (!ranges) return undefined;
- return rebaseInlineRangesAfterSlashCommandRewrite(ranges, message, dispatchedMessage);
+ return rebaseInlineRangesAfterSlashCommandRewrite(
+ ranges,
+ message,
+ dispatchedMessage,
+ );
};
const accepted = await makerChatStore.sendMessage(
newSession.id,
@@ -4077,10 +4091,7 @@ export function NewMakerDraftRoute() {
!localProvidersLoading,
true,
);
- const result = await window.electronAPI.maker.enableOrca(
- newSession.id,
- orcaOptions,
- );
+ const result = await window.electronAPI.maker.enableOrca(newSession.id, orcaOptions);
deferredUiAssignment = createDeferredUiAssignment({
options: orcaOptions,
workerSessionId: result.workerSessionId,
@@ -4238,12 +4249,10 @@ export function NewMakerDraftRoute() {
// independent branch preference transaction is still settling.
// 确认不合格(2026-08-07 裁决)时跳过偏好写入守卫,与 Send 同口径。
if (
- selectedWorktree.confirmedIneligible !== true
- && (
- wtPreferenceSavingRef.current
- || wtPreferenceAuthorityUnknownRef.current
- || (selectedWorktree.enabled && wtBranchPreferenceSavingRef.current)
- )
+ selectedWorktree.confirmedIneligible !== true &&
+ (wtPreferenceSavingRef.current ||
+ wtPreferenceAuthorityUnknownRef.current ||
+ (selectedWorktree.enabled && wtBranchPreferenceSavingRef.current))
) {
throw new Error(t('ccAgent.draft.deviceStillLoading'));
}
@@ -4259,17 +4268,17 @@ export function NewMakerDraftRoute() {
throw new Error(t('ccAgent.draft.worktreeMissingRepo'));
}
if (
- !selectedWorktree.branchPreferenceReady
- || wtBranchPreferenceErrorRef.current
- || (isDeviceLinkDraft && selectedWorktree.supportsRecoveryKeyDiscard !== true)
+ !selectedWorktree.branchPreferenceReady ||
+ wtBranchPreferenceErrorRef.current ||
+ (isDeviceLinkDraft && selectedWorktree.supportsRecoveryKeyDiscard !== true)
) {
throw new Error(t('ccAgent.draft.deviceStillLoading'));
}
}
const dataOwnerAtGoal = getDataOwnerGeneration();
const isCurrentDataOwner = () =>
- dataOwnerAtGoal.dataOwnerId === dataOwnerId
- && isDataOwnerGenerationCurrent(dataOwnerAtGoal);
+ dataOwnerAtGoal.dataOwnerId === dataOwnerId &&
+ isDataOwnerGenerationCurrent(dataOwnerAtGoal);
let policyEnabled = collabPolicy.enabled;
if (effectiveCollab.enabled && collabPolicyEligible) {
if (collabPolicy.loading) {
@@ -4338,8 +4347,7 @@ export function NewMakerDraftRoute() {
let remoteWorkingDir = selectedWorkingDir;
let presetSessionId: string | undefined;
let precreatedWorktree:
- | { path: string; recoveryKey: string; createdAt: number }
- | undefined;
+ { path: string; recoveryKey: string; createdAt: number } | undefined;
if (
selectedWorkingDir
&& selectedWorktree.enabled
@@ -4439,27 +4447,28 @@ export function NewMakerDraftRoute() {
capabilityAgentKind,
});
let created: { sessionId?: string; workDir?: string } | null = null;
- const remoteSessionId = await (presetSessionId && precreatedWorktree
- ? createRemoteSessionWithPrecreatedWorktree({
- deviceId,
- sessionId: presetSessionId,
- path: precreatedWorktree.path,
- recoveryKey: precreatedWorktree.recoveryKey,
- ...(ownerAtGoal ? { dataOwnerId: ownerAtGoal } : {}),
- createdAt: precreatedWorktree.createdAt,
- createArgs,
- invoke: invokeRemote,
- isCurrent: isCurrentDataOwner,
- })
- : invokeRemote('maker:create-session', [createArgs]).then((result) => {
- created = result as { sessionId?: string; workDir?: string } | null;
- return created?.sessionId;
- }))
- .catch((err) => {
- const remoteWorkdirMessage = getRemoteWorkingDirErrorMessage(err, t);
- if (remoteWorkdirMessage) throw new Error(remoteWorkdirMessage);
- throw err;
- });
+ const remoteSessionId = await (
+ presetSessionId && precreatedWorktree
+ ? createRemoteSessionWithPrecreatedWorktree({
+ deviceId,
+ sessionId: presetSessionId,
+ path: precreatedWorktree.path,
+ recoveryKey: precreatedWorktree.recoveryKey,
+ ...(ownerAtGoal ? { dataOwnerId: ownerAtGoal } : {}),
+ createdAt: precreatedWorktree.createdAt,
+ createArgs,
+ invoke: invokeRemote,
+ isCurrent: isCurrentDataOwner,
+ })
+ : invokeRemote('maker:create-session', [createArgs]).then((result) => {
+ created = result as { sessionId?: string; workDir?: string } | null;
+ return created?.sessionId;
+ })
+ ).catch((err) => {
+ const remoteWorkdirMessage = getRemoteWorkingDirErrorMessage(err, t);
+ if (remoteWorkdirMessage) throw new Error(remoteWorkdirMessage);
+ throw err;
+ });
if (presetSessionId && precreatedWorktree) {
created = { sessionId: remoteSessionId, workDir: remoteWorkingDir };
}
@@ -4470,7 +4479,11 @@ export function NewMakerDraftRoute() {
{
const optimisticGoalTitle = normalizeAutoTitle(objective);
if (optimisticGoalTitle) {
- remoteProjectsStore.setPendingTitlePreview(remoteSessionId, optimisticGoalTitle, true);
+ remoteProjectsStore.setPendingTitlePreview(
+ remoteSessionId,
+ optimisticGoalTitle,
+ true,
+ );
}
}
// 与发送路径共用同一段交接收尾(钉归属 → 补临时行 → 触发回流)。三条不变量对目标路径
@@ -4668,15 +4681,15 @@ export function NewMakerDraftRoute() {
initialBranchName: goalWorktreeBranchName,
sourceBranch: selectedWorktree.sourceBranch.trim() || 'HEAD',
createWorktree: (request) => window.electronAPI.worktreeCreate(request),
- updateWorkingDir: (managedDir) => (
- sessionService.update(newSession.id, { workingDir: managedDir }).then(() => undefined)
- ),
+ updateWorkingDir: (managedDir) =>
+ sessionService
+ .update(newSession.id, { workingDir: managedDir })
+ .then(() => undefined),
patchWorkingDir: (managedDir) => {
sessionsStore.patchLocal(newSession.id, { workingDir: managedDir });
},
- rollbackSession: () => (
- sessionService.setStatus(newSession.id, 'deleted').then(() => undefined)
- ),
+ rollbackSession: () =>
+ sessionService.setStatus(newSession.id, 'deleted').then(() => undefined),
patchDeleted: () => {
sessionsStore.patchLocal(newSession.id, { status: 'deleted' });
},
@@ -4707,10 +4720,7 @@ export function NewMakerDraftRoute() {
!localProvidersLoading,
true,
);
- const result = await window.electronAPI.maker.enableOrca(
- newSession.id,
- orcaOptions,
- );
+ const result = await window.electronAPI.maker.enableOrca(newSession.id, orcaOptions);
deferredUiAssignment = createDeferredUiAssignment({
options: orcaOptions,
workerSessionId: result.workerSessionId,
@@ -4951,9 +4961,9 @@ export function NewMakerDraftRoute() {
// 与进行中对话页同源:内容列宽度跟随 useProportionalWidth 算出的
// inputWidth(封顶 914+20=934px,见 hook 首参),不再死锁 800——大屏留出
// 左右呼吸空间、窄屏自适应收窄,且发送后同一个 ChatInput 无宽度跳变。
- // inputWidth 由 useLayoutEffect 同步量出
- // (paint 前已就绪);极端未量到(0)时回落旧默认 800,不放大到全宽。
- style={{ maxWidth: inputWidth || 800 }}
+ // inputWidth 由 useLayoutEffect 在 paint 前写入继承 CSS 变量;后续窗口缩放
+ // 直接更新变量,不经过整页 React render。
+ style={{ maxWidth: inputWidth }}
>
{/* mode pill + worktree 高级入口同排(齿轮在 pill 右侧,对齐旧 F1-E 布局)。
2026-07-19 修复:488cb33 对齐 Figma 重排时把 WorktreeChipsRow 注入删丢,
diff --git a/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx b/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
index 26995c9ba1..4b752773f6 100644
--- a/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
+++ b/apps/desktop/src/renderer/features/remote-device/ControlledBanner.tsx
@@ -14,7 +14,7 @@
* 完整设备名 + 远程控制逻辑说明。
*/
-import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
+import { useCallback, useEffect, useState, useSyncExternalStore, type CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { Eye, MonitorOff, X } from 'lucide-react';
@@ -122,7 +122,7 @@ export function useControlledBy(): Controller[] {
*/
interface ControlledBannerProps {
placement?: 'floating' | 'inline' | 'composer';
- maxWidth?: number;
+ maxWidth?: CSSProperties['maxWidth'];
/** composer placement 的任务 ID,用于隔离完整 / 呼吸灯折叠态。 */
sessionId?: string | null;
}
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useProportionalWidth.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useProportionalWidth.test.tsx
new file mode 100644
index 0000000000..e2fe0c8077
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useProportionalWidth.test.tsx
@@ -0,0 +1,105 @@
+// @vitest-environment jsdom
+import { act, cleanup, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useProportionalWidth } from '../useProportionalWidth';
+
+const BREAKPOINTS = [560, 600, 700] as const;
+
+describe('useProportionalWidth resize hot path', () => {
+ let measuredWidth = 1_000;
+ let notifyResize: ResizeObserverCallback | null = null;
+
+ beforeEach(() => {
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ () =>
+ ({
+ width: measuredWidth,
+ height: 0,
+ top: 0,
+ right: measuredWidth,
+ bottom: 0,
+ left: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }) as DOMRect,
+ );
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ notifyResize = callback;
+ }
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+ },
+ );
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('updates inherited CSS widths continuously but rerenders only across discrete bands', () => {
+ let renders = 0;
+ let latestBand = -1;
+ let latestCompact = false;
+
+ function Harness() {
+ const width = useProportionalWidth(914, { responsiveBreakpoints: BREAKPOINTS });
+ renders += 1;
+ latestBand = width.inputWidthBand;
+ latestCompact = width.isCompact;
+ return <div ref={width.containerRef} data-testid="container" />;
+ }
+
+ const view = render(<Harness />);
+ const container = view.getByTestId('container');
+ const initialRenderCount = renders;
+ expect(container.style.getPropertyValue('--cindy-message-width')).toBe('900px');
+ expect(container.style.getPropertyValue('--cindy-input-width')).toBe('920px');
+ expect(container.style.getPropertyValue('--cindy-input-half-width')).toBe('452px');
+ expect(latestBand).toBe(3);
+ expect(latestCompact).toBe(false);
+
+ measuredWidth = 900;
+ act(() => {
+ notifyResize?.(
+ [{ contentRect: { width: measuredWidth } } as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+ expect(container.style.getPropertyValue('--cindy-message-width')).toBe('800px');
+ expect(container.style.getPropertyValue('--cindy-input-width')).toBe('820px');
+ expect(renders).toBe(initialRenderCount);
+
+ measuredWidth = 650;
+ act(() => {
+ notifyResize?.(
+ [{ contentRect: { width: measuredWidth } } as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+ expect(container.style.getPropertyValue('--cindy-message-width')).toBe('610px');
+ expect(container.style.getPropertyValue('--cindy-input-width')).toBe('630px');
+ expect(container.style.getPropertyValue('--cindy-input-pad')).toBe('10px');
+ expect(latestBand).toBe(2);
+ expect(latestCompact).toBe(true);
+ expect(renders).toBeGreaterThan(initialRenderCount);
+ const renderCountAfterBreakpoint = renders;
+
+ measuredWidth = 640;
+ act(() => {
+ notifyResize?.(
+ [{ contentRect: { width: measuredWidth } } as ResizeObserverEntry],
+ {} as ResizeObserver,
+ );
+ });
+ expect(container.style.getPropertyValue('--cindy-input-width')).toBe('620px');
+ expect(renders).toBe(renderCountAfterBreakpoint);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useTheme.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/useTheme.test.tsx
index 09390bc5d3..1de8fa0fec 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useTheme.test.tsx
+++ b/apps/desktop/src/renderer/hooks/__tests__/useTheme.test.tsx
@@ -12,11 +12,20 @@ import { act, renderHook } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { themeService } from '../../themes/theme-service';
-import { ThemeProvider, useTheme } from '../useTheme';
+import {
+ __resetLoginFirstLaunchLightGateForTest,
+ endLoginFirstLaunchLightGate,
+ getInitialThemeVariant,
+ ThemeProvider,
+ useTheme,
+} from '../useTheme';
+
+const applyVibrancyMock = vi.fn();
+let systemPrefersDark = false;
// jsdom 无 matchMedia,ThemeProvider 初始化与 system 模式需要它。
vi.stubGlobal('matchMedia', (q: string) => ({
- matches: false,
+ matches: systemPrefersDark,
media: q,
addEventListener: () => {},
removeEventListener: () => {},
@@ -26,6 +35,10 @@ function wrapper({ children }: { children: ReactNode }) {
return createElement(ThemeProvider, null, children);
}
+function utilityWindowWrapper({ children }: { children: ReactNode }) {
+ return createElement(ThemeProvider, { children, syncWindowVibrancy: false });
+}
+
// 构造 storage 事件:用普通 Event + 显式 key/newValue,避免依赖 jsdom 对
// StorageEvent 构造函数第二参数(init)的重载支持(CodeQL: superfluous trailing arguments)。
// useTheme 的 storage 监听只读 event.key / event.newValue,语义完全等价。
@@ -38,10 +51,50 @@ function dispatchStorage(key: string, newValue: string | null) {
describe('useTheme 跨窗口主题同步(D2-3)', () => {
beforeEach(() => {
+ __resetLoginFirstLaunchLightGateForTest();
+ systemPrefersDark = false;
localStorage.clear();
delete document.documentElement.dataset.theme;
document.documentElement.classList.remove('dark');
vi.spyOn(themeService, 'applyTheme').mockImplementation(() => {});
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ theme: { applyVibrancy: applyVibrancyMock },
+ };
+ applyVibrancyMock.mockClear();
+ });
+
+ it('把应用主题模式同步给 main 作为下次 Windows 创建期 backing 镜像', () => {
+ localStorage.setItem('theme', 'dark');
+ renderHook(() => useTheme(), { wrapper });
+
+ expect(applyVibrancyMock).toHaveBeenCalledWith('cindy', true, 'dark', true);
+ });
+
+ it('utility 窗口复用 ThemeProvider 时不写全局窗口材质快照', () => {
+ localStorage.setItem('theme', 'dark');
+ renderHook(() => useTheme(), { wrapper: utilityWindowWrapper });
+
+ expect(applyVibrancyMock).not.toHaveBeenCalled();
+ });
+
+ it('把单变体家族标记为不随系统模式切换', () => {
+ localStorage.setItem('theme.familyId', 'eclipse');
+ renderHook(() => useTheme(), { wrapper });
+
+ expect(applyVibrancyMock).toHaveBeenCalledWith('eclipse', true, 'system', false);
+ });
+
+ it('系统深色下真首启按亮色门的实际主题上报 backing,门结束后恢复深色', () => {
+ systemPrefersDark = true;
+ expect(getInitialThemeVariant().theme.type).toBe('light');
+
+ renderHook(() => useTheme(), { wrapper });
+ expect(applyVibrancyMock).toHaveBeenLastCalledWith('cindy', false, 'system', true);
+
+ act(() => {
+ endLoginFirstLaunchLightGate();
+ });
+ expect(applyVibrancyMock).toHaveBeenLastCalledWith('cindy', true, 'system', true);
});
it('其他窗口切 theme → storage 事件 → 本窗口 theme state 跟随并重应用', () => {
diff --git a/apps/desktop/src/renderer/hooks/useProportionalWidth.ts b/apps/desktop/src/renderer/hooks/useProportionalWidth.ts
index fa86e48bcb..9d6c7e4ce5 100644
--- a/apps/desktop/src/renderer/hooks/useProportionalWidth.ts
+++ b/apps/desktop/src/renderer/hooks/useProportionalWidth.ts
@@ -29,10 +29,9 @@ import { useCallback, useLayoutEffect, useRef, useState } from 'react';
* - 主会话:不再依赖宿主显式传 compact 切窄。本 hook 自身按实测容器宽度
* `< AUTO_COMPACT_THRESHOLD` 时自动切 compact,与 `opts.compact` 取 OR。
* 这样右栏打开把主区压窄到阈值之下时,padding 平滑收紧, 既不臃肿也不会
- * 再出现"按 rightSidebarCollapsed 布尔切换"那次尝试的视觉跳变 —— 因为
- * ResizeObserver 量到的是父区**已经收敛后**的宽度,不存在"主区还没缩、
- * messageWidth 先扩出去顶过 parent"的中间帧。doc rail 走显式 `compact: true`
- * 仍恒 compact,行为不变。
+ * 再出现"按 rightSidebarCollapsed 布尔切换"那次尝试的视觉跳变。连续宽度
+ * 由 ResizeObserver 直接写入继承 CSS 变量,不经过会话组件 React render;
+ * compact 只在阈值跨越时更新。doc rail 走显式 `compact: true` 仍恒 compact。
*/
// 内容封顶宽的历史默认值:调用方不传首参时回落到它(旧行为)。
const MAX_MESSAGE_WIDTH = 1200;
@@ -59,24 +58,24 @@ export interface UseProportionalWidthOptions {
* 新建对话页用它保证大屏之外也有一个体面的最小宽度(与对话页同源的 max 对称)。
*/
minWidth?: number;
+ /**
+ * Optional ascending input-width breakpoints. React only updates when the measured input
+ * width crosses one of these boundaries; continuous width changes stay in CSS variables.
+ */
+ responsiveBreakpoints?: readonly number[];
}
-export function useProportionalWidth(
- maxWidth?: number,
- opts: UseProportionalWidthOptions = {},
-) {
+export function useProportionalWidth(maxWidth?: number, opts: UseProportionalWidthOptions = {}) {
const containerRef = useRef<HTMLDivElement>(null);
- const [messageWidth, setMessageWidth] = useState<number>(0);
- const [inputWidth, setInputWidth] = useState<number>(0);
- // inputPad 从恒定派生值改成跟随 effective compact 的 state:
- // 默认 50→40, auto/explicit compact 时 20→10。消费方(overlay 的
- // left-[...]/right-[...] 等)读这个值随容器宽度切换。
- const [inputPad, setInputPad] = useState<number>(DEFAULT_INPUT_PAD);
+ const messageWidthRef = useRef(0);
// effective compact 标志:= opts.compact || containerWidth < AUTO_COMPACT_THRESHOLD。
// 消费方据此挂 `chat-rail-compact` 让字号也跟着 padding 一起在 auto compact
// 时收紧、回到宽态时还原。初始值跟随 opts.compact:doc rail 首帧就是 true,
// 主会话默认 false,真实值在 useLayoutEffect 同步 compute() 时即被覆写,paint 前对齐。
- const [isCompact, setIsCompact] = useState<boolean>(!!opts.compact);
+ const [responsiveState, setResponsiveState] = useState(() => ({
+ isCompact: !!opts.compact,
+ inputWidthBand: opts.responsiveBreakpoints?.length ?? 0,
+ }));
const compute = useCallback(
(containerWidth: number) => {
@@ -96,25 +95,40 @@ export function useProportionalWidth(
// 地板夹到实测容器宽以内:窄窗仍是"填满容器",不会溢出/裁切。
nextInput = Math.min(opts.minWidth, containerWidth);
}
- setMessageWidth(nextMessage);
- setInputWidth(nextInput);
- setInputPad(nextInputPad);
- setIsCompact(useCompact);
+ messageWidthRef.current = nextMessage;
+
+ // These inherited variables update the already-mounted layout directly. Keeping the
+ // continuously changing pixel values out of React avoids a second full session render and
+ // layout pass on every BrowserWindow resize frame.
+ const el = containerRef.current;
+ if (el) {
+ el.style.setProperty('--cindy-message-width', `${nextMessage}px`);
+ el.style.setProperty('--cindy-input-width', `${nextInput}px`);
+ el.style.setProperty('--cindy-input-pad', `${nextInputPad}px`);
+ el.style.setProperty(
+ '--cindy-input-half-width',
+ `${Math.max(0, (nextInput - 16) * 0.5)}px`,
+ );
+ }
+
+ const nextBand = opts.responsiveBreakpoints?.findIndex((limit) => nextInput < limit) ?? -1;
+ const resolvedBand = nextBand === -1 ? (opts.responsiveBreakpoints?.length ?? 0) : nextBand;
+ setResponsiveState((current) =>
+ current.isCompact === useCompact && current.inputWidthBand === resolvedBand
+ ? current
+ : { isCompact: useCompact, inputWidthBand: resolvedBand },
+ );
},
- [maxWidth, opts.compact, opts.minWidth],
+ [maxWidth, opts.compact, opts.minWidth, opts.responsiveBreakpoints],
);
- // useLayoutEffect + 同步量一次:消除 mount 第一帧 width=0 的视觉跳变。
- // 之前用 useEffect + ResizeObserver,顺序是 render(state=0) → DOM commit
- // → paint(用户看到 0 宽:每个汉字单独一行、输入框被压成一条) →
- // observer 回调 → setState → 再 commit/paint。切 session(remount)时
- // 必现一帧。改成 useLayoutEffect 后,同步 getBoundingClientRect 设新宽度
- // 触发同步重渲染,在 paint 前就已经是正确宽度,坏帧吃掉。ResizeObserver
- // 只负责后续窗口缩放等动态变更。
+ // useLayoutEffect + 同步量一次:在首次 paint 前写好 CSS 变量,消除 width=0 的坏帧。
+ // ResizeObserver 后续只直接更新 DOM 变量;除非跨 compact / 调用方断点,否则不触发
+ // React render,避免窗口 resize 时出现“父容器先变、内容宽度下一次 commit 再追上”。
//
// 注:首帧的 compact 判定也走 compute(),所以 mount 进窄容器(<700)时第一
// 帧就直接是 compact padding,不会出现 50→20 闪烁。后续右栏 transition 收敛
- // 会触发 ResizeObserver 回调,在父宽已稳定的那一帧切到对应 padding,无跳变。
+ // 会触发 ResizeObserver 回调;CSS 宽度同帧跟随,compact 仅在阈值处切换。
useLayoutEffect(() => {
const el = containerRef.current;
if (!el) return;
@@ -126,5 +140,16 @@ export function useProportionalWidth(
return () => observer.disconnect();
}, [compute]);
- return { containerRef, messageWidth, inputWidth, inputPad, isCompact };
+ const getMessageWidth = useCallback(() => messageWidthRef.current, []);
+
+ return {
+ containerRef,
+ messageWidth: 'var(--cindy-message-width)',
+ inputWidth: 'var(--cindy-input-width)',
+ inputPad: 'var(--cindy-input-pad)',
+ inputHalfWidth: 'var(--cindy-input-half-width)',
+ isCompact: responsiveState.isCompact,
+ inputWidthBand: responsiveState.inputWidthBand,
+ getMessageWidth,
+ };
}
diff --git a/apps/desktop/src/renderer/hooks/useRightSidebarResize.ts b/apps/desktop/src/renderer/hooks/useRightSidebarResize.ts
index c6f74bc62c..af11928fce 100644
--- a/apps/desktop/src/renderer/hooks/useRightSidebarResize.ts
+++ b/apps/desktop/src/renderer/hooks/useRightSidebarResize.ts
@@ -142,8 +142,8 @@ export interface RightSidebarResizeResult {
}
/**
- * @param availableWidth 中间 + 右栏可分配的总像素宽(窗口宽 − 左栏宽),由
- * MainLayout 实时测量下发;首帧退回 fallback。
+ * @param availableWidth 中间 + 右栏可分配的总像素宽。布局引擎消费者可显式传入;
+ * MainLayout 只读取稳定的像素宽兜底,不再订阅 live resize,因此缺省用 fallback。
*/
export function useRightSidebarResize(
availableWidth: number = RIGHT_SIDEBAR_AVAILABLE_WIDTH_FALLBACK,
diff --git a/apps/desktop/src/renderer/hooks/useTheme.ts b/apps/desktop/src/renderer/hooks/useTheme.ts
index 563a533518..bb9fb3aca6 100644
--- a/apps/desktop/src/renderer/hooks/useTheme.ts
+++ b/apps/desktop/src/renderer/hooks/useTheme.ts
@@ -99,6 +99,19 @@ function resolveActiveTheme(mode: Theme) {
return resolveFamilyVariant(getStoredFamilyId(), isDark ? 'dark' : 'light');
}
+function resolveSessionActiveTheme(mode: Theme) {
+ return resolveActiveTheme(firstLaunchLightSession === true ? 'light' : mode);
+}
+
+function resolveSessionIsDark(mode: Theme): boolean {
+ return resolveSessionActiveTheme(mode).theme.type === 'dark';
+}
+
+function systemModeFollowsSystem(familyId: string): boolean {
+ const family = tryGetFamily(familyId);
+ return Boolean(family?.light && family?.dark);
+}
+
// 切主题时临时禁掉所有 transition,避免带 transition-colors 的元素(顶栏图标、
// 设置侧边活动项、Logout 按钮等)慢 150ms 淡到新色,看起来和瞬间换色的其他部分不同步。
// hover/active 等交互态的 transition 不受影响 —— 注入只在切换那一瞬生效,下一帧就移除。
@@ -119,9 +132,7 @@ export function applyThemeClass(theme: Theme, force = false): void {
const wasDark = root.classList.contains('dark');
// 首启亮色门激活期间(pre-login 会话)一律按亮色解析——ThemeProvider 挂载
// 重放与系统色变化都不会把登录界面翻回暗色;门由登录页卸载时结束。
- const { theme: nextTheme } = resolveActiveTheme(
- firstLaunchLightSession === true ? 'light' : theme,
- );
+ const { theme: nextTheme } = resolveSessionActiveTheme(theme);
const nextDark = nextTheme.type === 'dark';
if (!force && nextDark === wasDark && root.dataset.theme === nextTheme.id) {
@@ -215,10 +226,30 @@ export function loginFirstLaunchLightActive(): boolean {
export function endLoginFirstLaunchLightGate(): void {
if (firstLaunchLightSession !== true) return;
firstLaunchLightSession = false;
- applyThemeClass(getStoredTheme(), true);
+ const mode = getStoredTheme();
+ const familyId = getStoredFamilyId();
+ applyThemeClass(mode, true);
+ // 首启门结束不会改变 ThemeProvider 的 React state,因此对应 effect 不会自动重跑。
+ // 在这里用恢复后的实际主题立即同步 backing,同时保留用户原始模式供下次冷启动解析。
+ window.electronAPI?.theme?.applyVibrancy?.(
+ familyId,
+ resolveSessionIsDark(mode),
+ mode,
+ systemModeFollowsSystem(familyId),
+ );
}
-export function ThemeProvider({ children }: { children: ReactNode }) {
+export function __resetLoginFirstLaunchLightGateForTest(): void {
+ firstLaunchLightSession = null;
+}
+
+export function ThemeProvider({
+ children,
+ syncWindowVibrancy = true,
+}: {
+ children: ReactNode;
+ syncWindowVibrancy?: boolean;
+}) {
const [theme, setThemeState] = useState<Theme>(getStoredTheme);
const [familyId, setFamilyIdState] = useState<string>(getStoredFamilyId);
// 跟踪系统色偏好, 让 fallbackFromType 在 OS theme 变化时也能正确刷新。
@@ -324,8 +355,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
// 通知 main 开关 macOS vibrancy(仅 CINDY family 启用,其他恢复不透明)。覆盖
// setFamily/storage 跨窗口同步/mount 三个场景(任一变化都重应用)。
useEffect(() => {
- window.electronAPI?.theme?.applyVibrancy?.(familyId, resolveIsDark(theme));
- }, [familyId, theme, systemPrefersDark]);
+ if (!syncWindowVibrancy) return;
+ window.electronAPI?.theme?.applyVibrancy?.(
+ familyId,
+ resolveSessionIsDark(theme),
+ theme,
+ systemModeFollowsSystem(familyId),
+ );
+ }, [familyId, localThemeRev, syncWindowVibrancy, theme, systemPrefersDark]);
const fallbackFromType = useMemo<ThemeType | null>(() => {
void localThemeRev;
diff --git a/apps/desktop/src/renderer/layout/LayoutRoot.tsx b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
index ebe70a5245..086395d8bf 100644
--- a/apps/desktop/src/renderer/layout/LayoutRoot.tsx
+++ b/apps/desktop/src/renderer/layout/LayoutRoot.tsx
@@ -1,4 +1,13 @@
-import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
+import {
+ memo,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type ReactNode,
+ type RefObject,
+} from 'react';
import {
MIN_SPLIT_CHILD_FRACTION,
@@ -13,7 +22,7 @@ import { ensureGhostPanelsRegistered, useGhostPanelsSync } from '../cindy-brain/
import { isGhostPanelKindMinimized, useGhostPanelBubbleState } from '../lib/ghostPanelBubbleState';
import { isGhostPanelKindDetached, useGhostPanelWindowsState } from '../lib/ghostPanelWindowState';
import { registerBuiltinPanels } from '../panels/builtinPanels';
-import { getPanelKind } from '../panels/registry';
+import { getPanelKind, type PanelDefinition } from '../panels/registry';
import { installLayoutDevTools } from './layoutDevTools';
import { PanelMaximizeContext, type PanelMaximizeState } from './panelMaximize';
import { PaneAtWindowTopProvider, PaneFillProvider } from './panePlacement';
@@ -41,8 +50,9 @@ import { PaneWidthProvider, useContentAvailableWidth } from './paneWidths';
* fraction 一字不动(位置与宽度记忆保留,重装/合并/恢复即原位复活,
* architecture-invariants §3)。
*
- * 实现细节 —— root split 扁平化:根分割不产生容器 div,children(含分割线)
- * 直接吐进父容器(MainLayout 的 row flex div)。嵌套 split 走通用容器渲染,
+ * 实现细节 —— root split 在专属的内容区 flex 容器内扁平化:根分割自身不再额外
+ * 产生容器 div,children(含分割线)直接作为内容区容器的 flex 子项。该容器把百分比
+ * 解析口径钉在“窗口减去左侧栏”的剩余宽度;嵌套 split 走通用容器渲染,
* 其分割线暂为静态(嵌套布局今天不存在,交互化随真实需求补)。
*/
@@ -50,6 +60,8 @@ import { PaneWidthProvider, useContentAvailableWidth } from './paneWidths';
const AVAILABLE_WIDTH_FALLBACK = 1200;
/** chat-main 的最小像素宽(与 <main> 的 min-w-[400px] 对齐)。 */
const CHAT_MIN_PX = 400;
+/** live resize 停稳后再校正 clamp 与份额账本,避免把连续像素变化回灌 React。 */
+const ROOT_WIDTH_SELF_HEAL_SETTLE_MS = 120;
/**
* 非 chat 面板的兜底最小宽(2026-07-09 Lizi 定案:**只有聊天区有硬下限,
* 其它面板一律自由拉**)。这个值不是产品下限,只防"拖到窄得抓不住把手/
@@ -73,18 +85,21 @@ function isPanelKindVisible(kind: string): boolean {
}
/** 单个 pane 的挂载点:查注册表渲染;不可见 kind = 隐藏(数据保留在树里)。 */
-function PanelHost({
+const PanelHost = memo(function PanelHost({
node,
+ definition,
+ visible,
fill = false,
atWindowTop = true,
}: {
node: PaneNode;
+ definition: PanelDefinition | null;
+ visible: boolean;
fill?: boolean;
atWindowTop?: boolean;
}): ReactNode {
- const def = getPanelKind(node.panelKind);
- if (!def || !isPanelKindVisible(node.panelKind)) return null;
- const Component = def.Component;
+ if (!definition || !visible) return null;
+ const Component = definition.Component;
return (
<PaneAtWindowTopProvider value={atWindowTop}>
<PaneFillProvider value={fill}>
@@ -92,7 +107,7 @@ function PanelHost({
</PaneFillProvider>
</PaneAtWindowTopProvider>
);
-}
+});
interface SplitChildEntry {
treeIndex: number;
@@ -221,17 +236,13 @@ export function normalizeSubMinFractions(
* live 覆盖里存的同样是在场份额(拖动与渲染同一口径)。
*/
interface RootWidthState {
- panelWidths: Record<string, number>;
- splitWidths: Record<string, number>;
+ panelWidths: Record<string, string>;
+ splitWidths: Record<string, string>;
}
-function computeRootWidths(
- layout: Layout,
- live: Record<string, number> | null,
- avail: number,
-): RootWidthState {
- const panelWidths: Record<string, number> = {};
- const splitWidths: Record<string, number> = {};
+function computeRootWidths(layout: Layout, live: Record<string, number> | null): RootWidthState {
+ const panelWidths: Record<string, string> = {};
+ const splitWidths: Record<string, string> = {};
if (layout.content.type !== 'split' || layout.content.direction !== 'row') {
return { panelWidths, splitWidths };
}
@@ -240,8 +251,11 @@ function computeRootWidths(
if (node.type === 'pane' && node.panelKind === 'chat-main') continue;
const share = live?.[node.id] ?? entry.share;
const min = paneMinPx(node);
- const max = Math.max(min, avail - CHAT_MIN_PX);
- const width = Math.min(max, Math.max(min, Math.round(share * avail)));
+ // Resolve every consumer against the dedicated layout-content query container. A plain `%`
+ // would be relative to each consumer's immediate parent, so GhostPanel's inner section would
+ // accidentally apply the root share a second time. cqw keeps the shell and content aligned
+ // without restoring a ResizeObserver → React state round-trip during live window resizing.
+ const width = `clamp(${min}px, ${share * 100}cqw, calc(100cqw - ${CHAT_MIN_PX}px))`;
if (node.type === 'pane') panelWidths[node.panelKind] = width;
else splitWidths[node.id] = width;
}
@@ -287,7 +301,15 @@ function NodeView({
}: NodeViewProps): ReactNode {
const splitRef = useRef<HTMLDivElement>(null);
if (node.type === 'pane') {
- return <PanelHost node={node} fill={fillPane} atWindowTop={atWindowTop} />;
+ return (
+ <PanelHost
+ node={node}
+ definition={getPanelKind(node.panelKind)}
+ visible={isPanelKindVisible(node.panelKind)}
+ fill={fillPane}
+ atWindowTop={atWindowTop}
+ />
+ );
}
const ledger = activeSplitLedger(node.children);
const visible = ledger.entries;
@@ -322,8 +344,7 @@ function NodeView({
const hiddenByMaximize = maximizedKind !== null && !entryHasMaximized;
const childAtWindowTop =
atWindowTop &&
- (node.direction === 'row' ||
- (maximizedKind !== null ? entryHasMaximized : i === 0));
+ (node.direction === 'row' || (maximizedKind !== null ? entryHasMaximized : i === 0));
items.push(
<div
key={entry.node.id}
@@ -365,12 +386,6 @@ function NodeView({
}
interface RootDividerPropsExtra {
- /**
- * chat-main 渲染宽的**账本估值**(px,仅兜底用):可用宽 − 各在场非 chat 面板
- * 宽度之和。起拖时优先实测 chat-main 元素矩形(一次布局读取,符合起拖测量
- * 口径),量不到(测试环境等)才回落本值。
- */
- chatRenderedPx: number;
/**
* 在场份额与树份额的比例尺(Σ在场 fraction)。份额增量写回树时要乘它 ——
* 隐藏面板占着的那份不参与分配,也不该被拖动改写(见文件头「在场份额」)。
@@ -379,12 +394,17 @@ interface RootDividerPropsExtra {
}
interface RootDividerProps extends RootDividerPropsExtra {
+ /** 当前 Renderer 布局快照;起拖时用于同步对齐尚未自愈的 clamp 份额。 */
+ layout: Layout;
splitId: string;
left: SplitChildEntry;
right: SplitChildEntry;
/** 同一分割的全部在场子项(含缝两侧):压缩 chat 的接力出账要按实测宽找出折叠兄弟。 */
visibleSiblings: SplitChildEntry[];
- avail: number;
+ /** 测试/嵌入宿主可提供的可用宽提示;生产起拖时直接测量内容区容器。 */
+ availableWidthHint: number | null;
+ /** 根 split 所在的内容区;生产起拖时以它为像素/份额换算口径。 */
+ availableWidthRootRef: RefObject<HTMLDivElement | null>;
/** 拖动中的瞬时**在场份额**覆盖(paneId → share);null = 结束。 */
onLive: (live: Record<string, number> | null) => void;
/** 提交后的乐观本地树更新(广播随后回声同一棵树)。 */
@@ -430,12 +450,13 @@ function rawPanePx(node: LayoutNode): number | null {
* 松手经 transferSplitFraction 一次性写树;双击 = 两侧份额均分。
*/
function RootDivider({
+ layout,
splitId,
left,
right,
visibleSiblings,
- avail,
- chatRenderedPx,
+ availableWidthHint,
+ availableWidthRootRef,
shareScale,
onLive,
onCommitted,
@@ -444,7 +465,7 @@ function RootDivider({
const draggingRef = useRef(false);
/** amountToLeft:**在场份额**增量(> 0 = 左侧变宽);写树前乘 shareScale 换成树份额。 */
- const commit = (amountToLeft: number, relay: RelayPlan | null) => {
+ const commit = (amountToLeft: number, relay: RelayPlan | null, baseLayout?: Layout) => {
const treeAmount = amountToLeft * shareScale;
if (treeAmount === 0) return;
// 压缩 chat 的提交走接力:chat 先扣到 0.05 下限,差额由折叠兄弟出账 ——
@@ -452,7 +473,7 @@ function RootDivider({
const compressingChat =
relay !== null && (relay.receiver === right.treeIndex ? treeAmount < 0 : treeAmount > 0);
try {
- const current = window.electronAPI.layout.getStateSync().layout;
+ const current = baseLayout ?? window.electronAPI.layout.getStateSync().layout;
const op = compressingChat
? transferSplitFractionRelay(
current,
@@ -487,16 +508,20 @@ function RootDivider({
* 作废,界面弹回原宽(2026-07-29 Lizi 实测右栏拖到最大就回弹的根因:树里
* 躺着一条已卸载插件的残留份额,聊天区吸收了它的地方,账面却还记在它头上)。
*/
- const sideRoomShare = (entry: SplitChildEntry, fallbackPx: number | null): number => {
- if (!(avail > 0)) return 0; // 可用宽异常:不给余量,免得 0/0 产出 NaN 份额
+ const sideRoomShare = (
+ entry: SplitChildEntry,
+ available: number,
+ fallbackPx: number | null,
+ ): number => {
+ if (!(available > 0)) return 0; // 可用宽异常:不给余量,免得 0/0 产出 NaN 份额
const minPx = paneMinPx(entry.node);
- const ledgerPx = entry.share * avail;
+ const ledgerPx = entry.share * available;
const measured = measuredPanePx(entry.node);
// 实测可信直接用;量不到才回退账面/兜底,并保留 min 下限(与历史一致,不扰动)。
const basisPx = measured ?? Math.min(ledgerPx, fallbackPx ?? ledgerPx);
const pxRoom = basisPx - minPx;
const floorRoom = shareScale > 0 ? (entry.fraction - MIN_SPLIT_CHILD_FRACTION) / shareScale : 0;
- return Math.max(0, Math.min(pxRoom / avail, floorRoom));
+ return Math.max(0, Math.min(pxRoom / available, floorRoom));
};
/**
@@ -514,8 +539,9 @@ function RootDivider({
const chatShrinkPlan = (
chatEntry: SplitChildEntry,
otherSide: SplitChildEntry,
+ available: number,
): { room: number; relay: RelayPlan } | null => {
- if (!(avail > 0)) return null;
+ if (!(available > 0)) return null;
const measured = rawPanePx(chatEntry.node);
if (measured === null || measured < CHAT_MIN_PX) return null;
const floorRoom = (entry: SplitChildEntry): number =>
@@ -530,7 +556,7 @@ function RootDivider({
idleSources.push(sibling.treeIndex);
}
}
- const pxRoom = Math.max(0, measured - CHAT_MIN_PX) / avail;
+ const pxRoom = Math.max(0, measured - CHAT_MIN_PX) / available;
return {
room: Math.min(pxRoom, sourcesRoom),
relay: { sources: [chatEntry.treeIndex, ...idleSources], receiver: otherSide.treeIndex },
@@ -542,15 +568,33 @@ function RootDivider({
e.preventDefault();
draggingRef.current = true;
const startX = e.clientX;
- const startL = left.share;
- const startR = right.share;
+ const measuredAvailable = availableWidthRootRef.current?.getBoundingClientRect().width ?? 0;
+ const available =
+ availableWidthHint && availableWidthHint > 0
+ ? availableWidthHint
+ : measuredAvailable > 0
+ ? measuredAvailable
+ : AVAILABLE_WIDTH_FALLBACK;
+ // The settle-time self-heal can still be pending when the user grabs the divider immediately
+ // after a window resize. Align this gesture's baseline synchronously so a pane held up by the
+ // CSS floor responds from the first pixel; persist only if the gesture actually moves.
+ const alignedLayout = normalizeSubMinFractions(layout, available, isPanelKindVisible);
+ const alignedLedger =
+ alignedLayout?.content.type === 'split' && alignedLayout.content.direction === 'row'
+ ? activeSplitLedger(alignedLayout.content.children)
+ : null;
+ const alignedLeft = alignedLedger?.entries.find((entry) => entry.treeIndex === left.treeIndex);
+ const alignedRight = alignedLedger?.entries.find((entry) => entry.treeIndex === right.treeIndex);
+ const dragBaseLayout = alignedLeft && alignedRight ? alignedLayout : undefined;
+ const startL = alignedLeft?.share ?? left.share;
+ const startR = alignedRight?.share ?? right.share;
// 起拖只量一次(拖动期间界面静止,没有失效场景);chat 量不到时回落账本估值。
const chatEntry = isChatPane(left.node) ? left : isChatPane(right.node) ? right : null;
const shrinkPlan = chatEntry
- ? chatShrinkPlan(chatEntry, chatEntry === left ? right : left)
+ ? chatShrinkPlan(chatEntry, chatEntry === left ? right : left, available)
: null;
- let dMin = -sideRoomShare(left, isChatPane(left.node) ? chatRenderedPx : null);
- let dMax = sideRoomShare(right, isChatPane(right.node) ? chatRenderedPx : null);
+ let dMin = -sideRoomShare(left, available, null);
+ let dMax = sideRoomShare(right, available, null);
if (shrinkPlan && chatEntry === left) dMin = -shrinkPlan.room;
if (shrinkPlan && chatEntry === right) dMax = shrinkPlan.room;
const relay: RelayPlan | null = shrinkPlan?.relay ?? null;
@@ -563,7 +607,7 @@ function RootDivider({
document.documentElement.style.cursor = 'col-resize';
const onMove = (me: PointerEvent) => {
- const d = Math.min(dMax, Math.max(dMin, (me.clientX - startX) / avail));
+ const d = Math.min(dMax, Math.max(dMin, (me.clientX - startX) / available));
lastD = d;
onLive({ [left.node.id]: startL + d, [right.node.id]: startR - d });
};
@@ -575,7 +619,7 @@ function RootDivider({
document.removeEventListener('pointermove', onMove);
document.removeEventListener('pointerup', onUp);
document.removeEventListener('pointercancel', onCancel);
- if (commitIt && lastD !== 0) commit(lastD, relay);
+ if (commitIt && lastD !== 0) commit(lastD, relay, dragBaseLayout ?? undefined);
onLive(null);
};
const onUp = () => finish(true);
@@ -590,8 +634,17 @@ function RootDivider({
// 压缩 chat 的方向同样走接力(计划即时按当前实测现算),且不得越过 chat 400px 下限。
const onDoubleClick = () => {
const total = left.share + right.share;
+ const measuredAvailable = availableWidthRootRef.current?.getBoundingClientRect().width ?? 0;
+ const available =
+ availableWidthHint && availableWidthHint > 0
+ ? availableWidthHint
+ : measuredAvailable > 0
+ ? measuredAvailable
+ : AVAILABLE_WIDTH_FALLBACK;
const chatEntry = isChatPane(left.node) ? left : isChatPane(right.node) ? right : null;
- const plan = chatEntry ? chatShrinkPlan(chatEntry, chatEntry === left ? right : left) : null;
+ const plan = chatEntry
+ ? chatShrinkPlan(chatEntry, chatEntry === left ? right : left, available)
+ : null;
let d = total / 2 - left.share;
if (plan) {
// 均分 delta 压缩 chat 侧时,夹取到接力计划的可压余量,防止越过 400px 下限。
@@ -781,6 +834,43 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
() => window.electronAPI.layout.getStateSync().layout,
);
useEffect(() => window.electronAPI.layout.onChanged(({ layout: next }) => setLayout(next)), []);
+ const layoutRootRef = useRef<HTMLDivElement>(null);
+
+ // CSS clamp 负责 live resize 的即时画面;这里不发布连续宽度 state,只在内容区
+ // 停稳后检查一次份额账本。确实有非 chat 面板被 120px floor 托起时才写 React/IPC,
+ // 让下一次分割线起拖从眼前宽度开始,不出现“空拖一段再跳大”。
+ useEffect(() => {
+ const root = layoutRootRef.current;
+ if (!root || suppressNonChatPanels) return;
+ let timer: number | null = null;
+ const heal = () => {
+ timer = null;
+ if (document.body.classList.contains('resizing-pane')) {
+ schedule();
+ return;
+ }
+ const available = root.getBoundingClientRect().width;
+ if (!(available > 0)) return;
+ const fixed = normalizeSubMinFractions(layout, available, isPanelKindVisible);
+ if (fixed === null) return;
+ setLayout(fixed);
+ void window.electronAPI.layout.set(fixed).catch(() => undefined);
+ };
+ const schedule = () => {
+ if (timer !== null) window.clearTimeout(timer);
+ timer = window.setTimeout(heal, ROOT_WIDTH_SELF_HEAL_SETTLE_MS);
+ };
+
+ schedule();
+ const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule);
+ observer?.observe(root);
+ if (observer === null) window.addEventListener('resize', schedule);
+ return () => {
+ observer?.disconnect();
+ if (observer === null) window.removeEventListener('resize', schedule);
+ if (timer !== null) window.clearTimeout(timer);
+ };
+ }, [ghostBubbleState, ghostSyncVersion, ghostWindowsState, layout, suppressNonChatPanels]);
// 撑满态(panelMaximize.tsx):会话级视图态,树账本不动。同 kind 再点还原。
const [maximizedKind, setMaximizedKind] = useState<string | null>(null);
@@ -795,48 +885,14 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
// 分割线拖动中的瞬时**在场份额**覆盖(paneId → share);面板宽度实时跟手,
// 松手清空回落树值 —— 拖动全程不写 IPC。
const [liveFractions, setLiveFractions] = useState<Record<string, number> | null>(null);
- const availCtx = useContentAvailableWidth();
- const avail = availCtx ?? AVAILABLE_WIDTH_FALLBACK;
+ const availableWidthHint = useContentAvailableWidth();
// eslint 会说 ghostWindowsState 没被直接读——它是 computeRootWidths 里
// isPanelKindVisible 的隐式数据源(模块级镜像),必须进 deps 才能感知抽离变化。
const rootWidths = useMemo(
- () => computeRootWidths(layout, liveFractions, avail),
- [layout, liveFractions, avail, ghostBubbleState, ghostSyncVersion, ghostWindowsState],
- );
- // chat 实际渲染宽 ≈ 可用宽 − 各在场非 chat 面板宽度之和(拖缝余量的兜底估值,
- // 见 RootDividerPropsExtra;起拖优先实测元素矩形)。
- const chatRenderedPx = Math.max(
- CHAT_MIN_PX,
- avail -
- [...Object.values(rootWidths.panelWidths), ...Object.values(rootWidths.splitWidths)].reduce(
- (sum, width) => sum + width,
- 0,
- ),
+ () => computeRootWidths(layout, liveFractions),
+ [layout, liveFractions, ghostBubbleState, ghostSyncVersion, ghostWindowsState],
);
- // 布局自愈:份额吃不饱最小宽 → 抬到位、chat 捐差额并写回树(画面与账本一致,
- // 拖缝零跳变;详见 normalizeSubMinFractions)。250ms 防抖合并连续变化(装入
- // 广播、窗口缩放);拖动中不打扰;可用宽未测得(context null)时不动账本。
- useEffect(() => {
- // 接管态下可用宽是接管方的(设置页全宽),按它改账本会失真 —— 不自愈。
- if (suppressNonChatPanels || availCtx === null || liveFractions !== null) return;
- const timer = setTimeout(() => {
- const fixed = normalizeSubMinFractions(layout, availCtx, isPanelKindVisible);
- if (!fixed) return;
- setLayout(fixed);
- void window.electronAPI.layout.set(fixed).catch(() => undefined);
- }, 250);
- return () => clearTimeout(timer);
- }, [
- availCtx,
- ghostBubbleState,
- ghostSyncVersion,
- ghostWindowsState,
- layout,
- liveFractions,
- suppressNonChatPanels,
- ]);
-
// 撑满目标失效自动还原:面板被卸下/停用(kind 注销)、抽离进独立窗口或
// pane 离开树时清态,免得下次回来以陈年撑满态惊回。接管态(设置页)只是
// 暂不渲染,不清 —— 退出接管原样恢复。
@@ -902,7 +958,16 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
);
return (
<PanelMaximizeContext.Provider value={maximizeCtx}>
- <PaneWidthProvider value={rootWidths.panelWidths}>{body}</PaneWidthProvider>
+ <PaneWidthProvider value={rootWidths.panelWidths}>
+ <div
+ ref={layoutRootRef}
+ data-testid="layout-root-content"
+ className="flex min-w-0 flex-1 overflow-hidden"
+ style={{ containerType: 'inline-size' }}
+ >
+ {body}
+ </div>
+ </PaneWidthProvider>
</PanelMaximizeContext.Provider>
);
}
@@ -914,12 +979,13 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
items.push(
<RootDivider
key={`divider-${entry.node.id}`}
+ layout={layout}
splitId={content.id}
left={prev}
right={entry}
visibleSiblings={visible}
- avail={avail}
- chatRenderedPx={chatRenderedPx}
+ availableWidthHint={availableWidthHint}
+ availableWidthRootRef={layoutRootRef}
shareScale={ledger.scale}
onLive={setLiveFractions}
onCommitted={setLayout}
@@ -980,7 +1046,16 @@ export function LayoutRoot({ suppressNonChatPanels = false }: LayoutRootProps =
}
return (
<PanelMaximizeContext.Provider value={maximizeCtx}>
- <PaneWidthProvider value={rootWidths.panelWidths}>{body}</PaneWidthProvider>
+ <PaneWidthProvider value={rootWidths.panelWidths}>
+ <div
+ ref={layoutRootRef}
+ data-testid="layout-root-content"
+ className="flex min-w-0 flex-1 overflow-hidden"
+ style={{ containerType: 'inline-size' }}
+ >
+ {body}
+ </div>
+ </PaneWidthProvider>
</PanelMaximizeContext.Provider>
);
}
diff --git a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
index bb8ccec020..7f4e622dbd 100644
--- a/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
+++ b/apps/desktop/src/renderer/layout/__tests__/LayoutRoot.test.tsx
@@ -26,6 +26,7 @@ vi.mock('../../cindy-brain/ghostPanels', async (importOriginal) => {
/** stub electronAPI.layout:同步返回给定树 + 可手动触发 onChanged。 */
let currentLayout: Layout;
let changedListeners: Array<(payload: { layout: Layout }) => void>;
+const setLayoutMock = vi.fn<(layout: Layout) => Promise<void>>(async () => undefined);
function stubElectronLayoutApi(): void {
changedListeners = [];
@@ -38,6 +39,7 @@ function stubElectronLayoutApi(): void {
changedListeners = changedListeners.filter((l) => l !== cb);
};
},
+ set: setLayoutMock,
},
};
}
@@ -67,22 +69,36 @@ function renderLayoutRoot() {
/** row 容器 direct children 的 testid 顺序 —— 断言"顺序由树驱动"。 */
function rowChildTestIds(): string[] {
- return [...screen.getByTestId('row').children].map((el) => el.getAttribute('data-testid') ?? '?');
+ return [...screen.getByTestId('layout-root-content').children].map(
+ (el) => el.getAttribute('data-testid') ?? '?',
+ );
}
beforeEach(() => {
ghostPanelSyncMock.version = 0;
currentLayout = createDefaultLayout();
+ setLayoutMock.mockClear();
stubElectronLayoutApi();
});
afterEach(() => {
cleanup();
+ document.body.classList.remove('resizing-pane');
+ vi.useRealTimers();
__resetPanelRegistryForTest();
__resetBuiltinPanelsForTest();
});
describe('LayoutRoot · 树驱动的顺序与在场', () => {
+ it('用独立 flex-1 内容区承载根 split,让百分比不包含左侧栏宽度', () => {
+ renderLayoutRoot();
+ const row = screen.getByTestId('row');
+ const content = screen.getByTestId('layout-root-content');
+ expect([...row.children]).toEqual([content]);
+ expect(content.className).toContain('flex-1');
+ expect(rowChildTestIds()).toEqual(['p-chat', 'layout-divider', 'p-right']);
+ });
+
it('默认树:chat 在前、right 在后,相邻可见面板之间有引擎分割线', () => {
renderLayoutRoot();
expect(rowChildTestIds()).toEqual(['p-chat', 'layout-divider', 'p-right']);
@@ -124,12 +140,110 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
</div>
</BuiltinPanelBridgeProvider>,
);
- const ids = [...screen.getByTestId('row-suppressed').children].map(
+ const ids = [...screen.getByTestId('layout-root-content').children].map(
(el) => el.getAttribute('data-testid') ?? '?',
);
expect(ids).toEqual(['p-chat']);
});
+ it('live resize 停稳后只在 120px clamp 命中时自愈份额账本', async () => {
+ vi.useFakeTimers();
+ currentLayout = {
+ ...createDefaultLayout(),
+ content: {
+ type: 'split',
+ id: 'root',
+ direction: 'row',
+ children: [
+ {
+ fraction: 0.9,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
+ {
+ fraction: 0.1,
+ node: { type: 'pane', id: 'right', panelKind: 'right-tabs', minWidth: 120 },
+ },
+ ],
+ },
+ };
+ renderLayoutRoot();
+ const content = screen.getByTestId('layout-root-content');
+ content.getBoundingClientRect = () =>
+ ({
+ width: 800,
+ height: 600,
+ top: 0,
+ right: 800,
+ bottom: 600,
+ left: 0,
+ x: 0,
+ y: 0,
+ toJSON() {},
+ }) as DOMRect;
+
+ await act(async () => {
+ vi.advanceTimersByTime(120);
+ await Promise.resolve();
+ });
+
+ expect(setLayoutMock).toHaveBeenCalledTimes(1);
+ const fixed = setLayoutMock.mock.calls[0][0];
+ expect(fixed.content.type).toBe('split');
+ if (fixed.content.type !== 'split') throw new Error('expected split layout');
+ expect(fixed.content.children[0].fraction).toBeCloseTo(0.85);
+ expect(fixed.content.children[1].fraction).toBeCloseTo(0.15);
+ });
+
+ it('分割线拖动期间暂停 120px clamp 自愈,松手后再执行', async () => {
+ vi.useFakeTimers();
+ currentLayout = {
+ ...createDefaultLayout(),
+ content: {
+ type: 'split',
+ id: 'root',
+ direction: 'row',
+ children: [
+ {
+ fraction: 0.9,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
+ {
+ fraction: 0.1,
+ node: { type: 'pane', id: 'right', panelKind: 'right-tabs', minWidth: 120 },
+ },
+ ],
+ },
+ };
+ renderLayoutRoot();
+ const content = screen.getByTestId('layout-root-content');
+ content.getBoundingClientRect = () =>
+ ({
+ width: 800,
+ height: 600,
+ top: 0,
+ right: 800,
+ bottom: 600,
+ left: 0,
+ x: 0,
+ y: 0,
+ toJSON() {},
+ }) as DOMRect;
+
+ document.body.classList.add('resizing-pane');
+ await act(async () => {
+ vi.advanceTimersByTime(240);
+ await Promise.resolve();
+ });
+ expect(setLayoutMock).not.toHaveBeenCalled();
+
+ document.body.classList.remove('resizing-pane');
+ await act(async () => {
+ vi.advanceTimersByTime(120);
+ await Promise.resolve();
+ });
+ expect(setLayoutMock).toHaveBeenCalledTimes(1);
+ });
+
it('卸载后重新 mount 不泄漏 onChanged 订阅', () => {
const { unmount } = renderLayoutRoot();
expect(changedListeners).toHaveLength(1);
@@ -193,7 +307,7 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
expect(screen.getAllByTestId('layout-divider')).toHaveLength(3);
});
- it('插件重新注册但布局树未变化时,恢复 grid 列的持久宽度', () => {
+ it('插件重新注册但布局树未变化时,恢复 grid 列', () => {
currentLayout = {
...createDefaultLayout(),
content: {
@@ -241,13 +355,60 @@ describe('LayoutRoot · 树驱动的顺序与在场', () => {
</BuiltinPanelBridgeProvider>,
);
- const grid = document.querySelector<HTMLElement>(
- '[data-layout-root-child-id="grid-restored"]',
- );
+ const grid = document.querySelector<HTMLElement>('[data-layout-root-child-id="grid-restored"]');
expect(grid).not.toBeNull();
- expect(grid?.style.width).toBe('360px');
expect(screen.getByTestId('restored-panel')).not.toBeNull();
});
+
+ it('插件 manifest 更新但布局树未变化时,刷新已挂载面板定义', () => {
+ registerPanelKind({
+ kind: 'ghost:updated',
+ Component: () => <div data-testid="updated-panel">before</div>,
+ collapseMemory: 'global',
+ });
+ currentLayout = {
+ ...createDefaultLayout(),
+ content: {
+ type: 'split',
+ id: 'root',
+ direction: 'row',
+ children: [
+ {
+ fraction: 0.7,
+ node: { type: 'pane', id: 'chat', panelKind: 'chat-main', minWidth: 400 },
+ },
+ {
+ fraction: 0.3,
+ node: { type: 'pane', id: 'updated', panelKind: 'ghost:updated' },
+ },
+ ],
+ },
+ };
+
+ const rendered = renderLayoutRoot();
+ expect(screen.getByTestId('updated-panel').textContent).toBe('before');
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ registerPanelKind({
+ kind: 'ghost:updated',
+ Component: () => <div data-testid="updated-panel">after</div>,
+ collapseMemory: 'global',
+ });
+ expect(warn).toHaveBeenCalledWith(
+ '[panels] duplicate registration overwrites kind: ghost:updated',
+ );
+ warn.mockRestore();
+ ghostPanelSyncMock.version += 1;
+ rendered.rerender(
+ <BuiltinPanelBridgeProvider value={bridge}>
+ <div data-testid="row">
+ <LayoutRoot />
+ </div>
+ </BuiltinPanelBridgeProvider>,
+ );
+
+ expect(screen.getByTestId('updated-panel').textContent).toBe('after');
+ });
});
describe('normalizeSubMinFractions', () => {
diff --git a/apps/desktop/src/renderer/layout/__tests__/rootDividerDrag.test.tsx b/apps/desktop/src/renderer/layout/__tests__/rootDividerDrag.test.tsx
index 719641bfe2..50784ce3e4 100644
--- a/apps/desktop/src/renderer/layout/__tests__/rootDividerDrag.test.tsx
+++ b/apps/desktop/src/renderer/layout/__tests__/rootDividerDrag.test.tsx
@@ -3,7 +3,10 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createDefaultLayout, type Layout, type SplitNode } from '../../../shared/layoutTree';
-import { BuiltinPanelBridgeProvider, type BuiltinPanelBridge } from '../../panels/BuiltinPanelBridge';
+import {
+ BuiltinPanelBridgeProvider,
+ type BuiltinPanelBridge,
+} from '../../panels/BuiltinPanelBridge';
import { __resetBuiltinPanelsForTest } from '../../panels/builtinPanels';
import { __resetPanelRegistryForTest, registerPanelKind } from '../../panels/registry';
import { LayoutRoot } from '../LayoutRoot';
@@ -49,7 +52,12 @@ function treeWithUninstalledResidue(): Layout {
split.children[1].fraction = 0.32108649782155757; // right-tabs
split.children.unshift({
fraction: 0.22,
- node: { type: 'pane', id: 'ghost-project-opener', panelKind: 'ghost:project-opener', minWidth: 240 },
+ node: {
+ type: 'pane',
+ id: 'ghost-project-opener',
+ panelKind: 'ghost:project-opener',
+ minWidth: 240,
+ },
});
return layout;
}
@@ -70,10 +78,10 @@ const bridge: BuiltinPanelBridge = {
),
};
-function renderLayoutRoot() {
+function renderLayoutRoot(availableWidth = AVAIL) {
return render(
<BuiltinPanelBridgeProvider value={bridge}>
- <ContentAvailableWidthProvider value={AVAIL}>
+ <ContentAvailableWidthProvider value={availableWidth}>
<div data-testid="row">
<LayoutRoot />
</div>
@@ -82,6 +90,31 @@ function renderLayoutRoot() {
);
}
+function renderLayoutRootWithoutWidthHint() {
+ return render(
+ <BuiltinPanelBridgeProvider value={bridge}>
+ <div data-testid="row">
+ <LayoutRoot />
+ </div>
+ </BuiltinPanelBridgeProvider>,
+ );
+}
+
+function mockElementWidth(element: HTMLElement, width: number): void {
+ element.getBoundingClientRect = () =>
+ ({
+ width,
+ height: 0,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }) as DOMRect;
+}
+
/**
* 覆盖 jsdom 恒为 0 的矩形:给某 panelKind 的元素钉死一个实测宽,让起拖时
* measuredPanePx 拿到真机口径的宽度(而非回落账面)。
@@ -89,8 +122,7 @@ function renderLayoutRoot() {
function mockPaneWidth(kind: string, width: number): void {
const el = document.querySelector(`[data-panel-drag-root="${kind}"]`) as HTMLElement | null;
expect(el).not.toBeNull();
- el!.getBoundingClientRect = () =>
- ({ width, height: 0, top: 0, left: 0, right: width, bottom: 0, x: 0, y: 0, toJSON: () => ({}) }) as DOMRect;
+ mockElementWidth(el!, width);
}
/** 把缝一路拖向左(右侧面板变宽)到抓不动为止,松手。 */
@@ -138,11 +170,31 @@ afterEach(() => {
});
describe('RootDivider 拖宽 · 在场份额口径', () => {
+ it('生产路径没有宽度提示时按内容区宽度换算拖动份额', () => {
+ const { container } = renderLayoutRootWithoutWidthHint();
+ mockElementWidth(screen.getByTestId('layout-root-content'), AVAIL);
+ const divider = screen.getByTestId('layout-divider');
+ mockElementWidth(divider, 1);
+
+ dragDividerLeft(container, AVAIL * 0.1);
+
+ expect(setCalls).toHaveLength(1);
+ const children = (setCalls[0].content as SplitNode).children;
+ expect(children[0].fraction).toBeCloseTo(0.4, 6);
+ expect(children[1].fraction).toBeCloseTo(0.6, 6);
+ });
+
it('已卸载插件的残留份额不参与分配:右栏宽按在场份额算', () => {
currentLayout = treeWithUninstalledResidue();
renderLayoutRoot();
// 在场份额 0.3211 / 0.78 = 0.4117 → 683px。按树上原始 fraction 只有 533px。
- expect(Number(screen.getByTestId('w-right-tabs').textContent)).toBe(683);
+ const width = screen.getByTestId('w-right-tabs').textContent ?? '';
+ const preferredPercent = width.match(
+ /^clamp\(120px, ([\d.]+)cqw, calc\(100cqw - 400px\)\)$/,
+ )?.[1];
+ expect(preferredPercent).toBeDefined();
+ expect((Number(preferredPercent) / 100) * AVAIL).toBeCloseTo(683, 0);
+ expect(screen.getByTestId('layout-root-content').style.containerType).toBe('inline-size');
});
it('有卸载残留时把右栏拖到最大:松手后写树成功(不回弹),聊天流正好落在最小宽', () => {
@@ -161,6 +213,34 @@ describe('RootDivider 拖宽 · 在场份额口径', () => {
expect(sum).toBeCloseTo(1, 6);
});
+ it('120px clamp 自愈尚未执行时起拖,也从眼前宽度第一像素跟手', () => {
+ const layout = createDefaultLayout();
+ const split = layout.content as SplitNode;
+ split.children[0].fraction = 0.9;
+ split.children[1].fraction = 0.1;
+ currentLayout = layout;
+ const { container } = renderLayoutRoot(800);
+ mockPaneWidth('chat-main', 680);
+ mockPaneWidth('right-tabs', 120);
+
+ const grab = container.querySelector('[data-testid="layout-divider"] > div');
+ expect(grab).not.toBeNull();
+ fireEvent.pointerDown(grab!, { button: 0, pointerId: 1, clientX: 1000 });
+ fireEvent.pointerMove(document, { pointerId: 1, clientX: 992 });
+
+ const liveWidth = screen.getByTestId('w-right-tabs').textContent ?? '';
+ const liveShare = liveWidth.match(
+ /^clamp\(120px, ([\d.]+)cqw, calc\(100cqw - 400px\)\)$/,
+ )?.[1];
+ expect(Number(liveShare)).toBeCloseTo(16, 6);
+
+ fireEvent.pointerUp(document, { pointerId: 1, clientX: 992 });
+ expect(setCalls).toHaveLength(1);
+ const committed = (setCalls[0].content as SplitNode).children;
+ expect(committed[0].fraction).toBeCloseTo(0.84, 6);
+ expect(committed[1].fraction).toBeCloseTo(0.16, 6);
+ });
+
it('干净的两栏树:同样能把聊天流拖到最小宽,且写树成功', () => {
currentLayout = createDefaultLayout(); // chat 0.5 / right 0.5
const { container } = renderLayoutRoot();
diff --git a/apps/desktop/src/renderer/layout/paneWidths.tsx b/apps/desktop/src/renderer/layout/paneWidths.tsx
index 3160eb8774..f2de446fd1 100644
--- a/apps/desktop/src/renderer/layout/paneWidths.tsx
+++ b/apps/desktop/src/renderer/layout/paneWidths.tsx
@@ -4,9 +4,9 @@ import { createContext, useContext } from 'react';
* paneWidths —— 引擎面板宽度通道(缝即把手,宽度主权归引擎)。
*
* 两个 context:
- * - ContentAvailableWidthContext:内容区可分配总宽(窗口宽 − 左栏宽),由
- * MainLayout 的既有测量(B1a 的 sidebarBlock 观测)下发给 LayoutRoot;
- * - PaneWidthContext:LayoutRoot 按树上 fraction × 可用宽算出的**各面板像素宽**
+ * - ContentAvailableWidthContext:仅为分割线交互 / 测试提供可用宽提示;生产布局
+ * 不再逐像素发布窗口宽度,起拖时直接测量容器;
+ * - PaneWidthContext:LayoutRoot 按树上 fraction 生成各面板的 CSS 响应式宽度
* (按 panelKind 索引;chat-main 弹性吸收剩余,不在表内)。拖动引擎分割线
* 期间为临时值(实时跟手),松手后回落到树的持久化值。
*
@@ -21,11 +21,13 @@ export function useContentAvailableWidth(): number | null {
return useContext(ContentAvailableWidthContext);
}
-export const PaneWidthContext = createContext<Record<string, number> | null>(null);
+export type PaneWidth = number | string;
+
+export const PaneWidthContext = createContext<Record<string, PaneWidth> | null>(null);
export const PaneWidthProvider = PaneWidthContext.Provider;
-/** 读取引擎为某 panelKind 计算的像素宽;null = 引擎未接管,面板自行回落。 */
-export function usePanelWidth(kind: string): number | null {
+/** 读取引擎为某 panelKind 计算的响应式宽度;null = 引擎未接管,面板自行回落。 */
+export function usePanelWidth(kind: string): PaneWidth | null {
const widths = useContext(PaneWidthContext);
return widths?.[kind] ?? null;
}
diff --git a/apps/desktop/src/renderer/main-entry.tsx b/apps/desktop/src/renderer/main-entry.tsx
index 043e7bb4dc..901f1d2f4d 100644
--- a/apps/desktop/src/renderer/main-entry.tsx
+++ b/apps/desktop/src/renderer/main-entry.tsx
@@ -84,6 +84,13 @@ const isComputerPermissionView = isComputerPermissionGuide || isComputerPermissi
const isAppearanceUtilityView =
isVoiceInputOverlay || isVoiceInputDictionaryToast || isComputerPermissionView;
document.documentElement.dataset.platform = window.electronAPI.platform;
+document.documentElement.dataset.windowBackdropMaterial =
+ window.electronAPI.windowBackdropMaterial ?? 'none';
+const disposeWindowBackdropMaterialChanged =
+ window.electronAPI.onWindowBackdropMaterialChanged?.((material) => {
+ document.documentElement.dataset.windowBackdropMaterial = material;
+ }) ?? (() => {});
+import.meta.hot?.dispose(disposeWindowBackdropMaterialChanged);
if (isVoiceInputOverlay || isVoiceInputDictionaryToast) {
document.documentElement.dataset.voiceInputOverlay = 'true';
}
@@ -150,7 +157,7 @@ void (async () => {
'./components/settings/ComputerPermissionGuideWindow'
);
root.render(
- <ThemeProvider>
+ <ThemeProvider syncWindowVibrancy={false}>
<ComputerPermissionBackdrop />
</ThemeProvider>,
);
@@ -162,7 +169,7 @@ void (async () => {
'./components/settings/ComputerPermissionGuideWindow'
);
root.render(
- <ThemeProvider>
+ <ThemeProvider syncWindowVibrancy={false}>
<LocaleProvider>
<ComputerPermissionGuideWindow />
</LocaleProvider>
@@ -174,7 +181,7 @@ void (async () => {
if (isVoiceInputDictionaryToast) {
const { VoiceInputDictionaryToast } = await import('./voice-input/VoiceInputDictionaryToast');
root.render(
- <ThemeProvider>
+ <ThemeProvider syncWindowVibrancy={false}>
<LocaleProvider>
<VoiceInputDictionaryToast />
</LocaleProvider>
@@ -186,7 +193,7 @@ void (async () => {
if (isVoiceInputOverlay) {
const { VoiceInputOverlay } = await import('./voice-input/VoiceInputOverlay');
root.render(
- <ThemeProvider>
+ <ThemeProvider syncWindowVibrancy={false}>
<LocaleProvider>
<ConfirmDialogProvider>
<VoiceInputOverlay />
diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.css
index f6f408c5ba..6fca73563a 100644
--- a/apps/desktop/src/renderer/styles/globals.css
+++ b/apps/desktop/src/renderer/styles/globals.css
@@ -2147,6 +2147,15 @@ body.resizing-pane [data-ghost-webview] {
background: var(--surface-translucent-sidebar);
/* backdrop-filter 移除:CSS blur 采样不到窗外壁纸,且已知会把透明窗背衬渲染成黑;壁纸模糊由原生 vibrancy 材质提供 */
}
+/* Windows Acrylic 的 BrowserWindow backing 已在创建期铺同一份 85% 侧栏染色,确保快速
+ 扩窗时原生新区域先显示正确颜色。常规侧栏让 backing 直接透出,避免 CSS 再叠一遍导致
+ 颜色变重;peek drawer 覆盖的是应用内容,仍保留下方独立的染色 + blur。 */
+[data-platform='win32'][data-window-backdrop-material='acrylic'][data-theme='cindy-light']
+ aside.bg-sidebar:not([data-sidebar-peek-drawer]),
+[data-platform='win32'][data-window-backdrop-material='acrylic'][data-theme='cindy-dark']
+ aside.bg-sidebar:not([data-sidebar-peek-drawer]) {
+ background: transparent;
+}
/* Sidebar peek 抽屉是 fixed overlay,它覆盖的是应用内容而不是窗外壁纸;这里需要
单独 blur 被覆盖的应用 UI,避免 hover 预览时正文直接透出来。常规展开态仍交给
原生 vibrancy,非 CINDY family 不命中。 */
diff --git a/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts b/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
index 78e0b8f34e..4f0581d899 100644
--- a/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
+++ b/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
@@ -1,5 +1,6 @@
import type { Theme } from '../types';
import cindyLogoDark from '../../assets/cindy-logo-dark.png';
+import { CINDY_ACRYLIC_WINDOW_BACKING } from '../../../shared/windowBackdrop';
/*
* CINDY Dark — 品牌红 CTA + 中性近黑底(#181818)+ AA 正文;U2 二级信息色忠于 Figma 原值。
@@ -140,7 +141,7 @@ const overrides = {
'sidebar-search-bg': '0 0% 9.4%', // 页底 -> HSL
'sidebar-search-input-bg': 'rgba(0, 0, 0, 0.25)', // 玻璃面搜索输入框 2026-07-21:黑 25% 下陷字段感(与 hover 白 9% 方向相反,可区分"可输入")
'sidebar-muted': '0 0% 43.5%', // E1D 侧栏层级:二级暗灰 #6F6F6F(行首图标普通态)
- 'surface-translucent-sidebar': 'rgba(5, 5, 5, 0.85)', // 侧栏玻璃: 用户调参 2026-08-11(黑 5 度 85%)
+ 'surface-translucent-sidebar': CINDY_ACRYLIC_WINDOW_BACKING.dark, // 侧栏玻璃: 用户调参 2026-08-11(黑 5 度 85%)
'surface-translucent-main': '#181818', // 直映: 页底(纯中性)
'surface-translucent-overlay': 'rgba(21, 21, 21, 0.80)', // 浮层玻璃: 平移
'composer-pill-bg': '#272727', // composer pill
diff --git a/apps/desktop/src/renderer/themes/builtin/cindy-light.ts b/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
index e024942d1a..43dce127a6 100644
--- a/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
+++ b/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
@@ -1,5 +1,6 @@
import type { Theme } from '../types';
import cindyLogoLight from '../../assets/cindy-logo-light.png';
+import { CINDY_ACRYLIC_WINDOW_BACKING } from '../../../shared/windowBackdrop';
/*
* CINDY Light — 品牌红 CTA + 暖象牙底(#F2F2ED)+ AA 正文。
@@ -136,7 +137,7 @@ const overrides = {
'sidebar-search-bg': '60.0 12.8% 92.4%', // 侧栏搜索区: 同侧栏面
'sidebar-search-input-bg': 'rgba(255, 255, 250, 0.55)', // 暖化
'sidebar-muted': '60.0 2.1% 52.4%', // 侧栏灰字: 同上
- 'surface-translucent-sidebar': 'rgba(238, 238, 233, 0.85)', // 侧栏面: 独立压暗一档+85% 遮盖(用户调参 2026-08-17, 与深色对齐)
+ 'surface-translucent-sidebar': CINDY_ACRYLIC_WINDOW_BACKING.light, // 侧栏面: 独立压暗一档+85% 遮盖(用户调参 2026-08-17, 与深色对齐)
'surface-translucent-main': '#F2F2ED', // 直映: 页底(暖象牙)
'surface-translucent-overlay': 'rgba(251, 251, 246, 0.90)', // 浮层玻璃: 暖化
'composer-pill-bg': '#FFFFFA', // 近白档
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 7557282023..ee0c13483a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1104,6 +1104,10 @@ type CindyMediaPreferenceKind = {
interface ElectronAPI {
platform: string;
+ windowBackdropMaterial: import('../shared/windowBackdrop').WindowsBackdropMaterial;
+ onWindowBackdropMaterialChanged?: (
+ cb: (material: import('../shared/windowBackdrop').WindowsBackdropMaterial) => void,
+ ) => () => void;
osRelease: string;
appVersion: string;
/** 运行期端点清单(main 启动时远程 → 缓存 → 烘焙解析;重启生效)。 */
@@ -3503,7 +3507,14 @@ interface ElectronAPI {
) => () => void;
setUpdateRelaunchTheme: (theme: 'light' | 'dark') => void;
// E4D 毛玻璃:family 切换/启动通知 main 开关 vibrancy(仅 CINDY 透壁纸)
- theme: { applyVibrancy: (familyId: string, isDark: boolean) => void };
+ theme: {
+ applyVibrancy: (
+ familyId: string,
+ isDark: boolean,
+ mode: 'system' | 'light' | 'dark',
+ systemModeFollowsSystem: boolean,
+ ) => void;
+ };
/**
* Manually trigger an update check. Returns the resolved state so the
* renderer can show the appropriate toast:
diff --git a/apps/desktop/src/shared/__tests__/windowBackdrop.test.ts b/apps/desktop/src/shared/__tests__/windowBackdrop.test.ts
new file mode 100644
index 0000000000..e240757a54
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/windowBackdrop.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createWindowBackdropMaterialArgument,
+ readWindowBackdropMaterialFromArgv,
+} from '../windowBackdrop';
+
+describe('window backdrop material renderer argument', () => {
+ it('round-trips every supported material', () => {
+ for (const material of ['acrylic', 'mica', 'tabbed', 'none'] as const) {
+ expect(
+ readWindowBackdropMaterialFromArgv([
+ '--unrelated=value',
+ createWindowBackdropMaterialArgument(material),
+ ]),
+ ).toBe(material);
+ }
+ });
+
+ it('falls back to none when the argument is absent or invalid', () => {
+ expect(readWindowBackdropMaterialFromArgv([])).toBe('none');
+ expect(
+ readWindowBackdropMaterialFromArgv(['--cindy-window-backdrop-material=glass']),
+ ).toBe('none');
+ });
+
+ it('prefers the BrowserWindow-injected trailing value', () => {
+ expect(
+ readWindowBackdropMaterialFromArgv([
+ '--cindy-window-backdrop-material=mica',
+ '--cindy-window-backdrop-material=acrylic',
+ ]),
+ ).toBe('acrylic');
+ });
+});
diff --git a/apps/desktop/src/shared/windowBackdrop.ts b/apps/desktop/src/shared/windowBackdrop.ts
new file mode 100644
index 0000000000..52c62de062
--- /dev/null
+++ b/apps/desktop/src/shared/windowBackdrop.ts
@@ -0,0 +1,33 @@
+export const WINDOWS_BACKDROP_MATERIALS = ['acrylic', 'mica', 'tabbed', 'none'] as const;
+
+export type WindowsBackdropMaterial = (typeof WINDOWS_BACKDROP_MATERIALS)[number];
+
+export const CINDY_ACRYLIC_WINDOW_BACKING = {
+ light: 'rgba(238, 238, 233, 0.85)',
+ dark: 'rgba(5, 5, 5, 0.85)',
+} as const;
+
+export const WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL =
+ 'window-backdrop-material:changed';
+
+const WINDOW_BACKDROP_MATERIAL_ARGUMENT = '--cindy-window-backdrop-material=';
+
+export function isWindowsBackdropMaterial(value: string): value is WindowsBackdropMaterial {
+ return WINDOWS_BACKDROP_MATERIALS.some((material) => material === value);
+}
+
+export function createWindowBackdropMaterialArgument(material: WindowsBackdropMaterial): string {
+ return `${WINDOW_BACKDROP_MATERIAL_ARGUMENT}${material}`;
+}
+
+export function readWindowBackdropMaterialFromArgv(
+ argv: readonly string[],
+): WindowsBackdropMaterial {
+ for (let index = argv.length - 1; index >= 0; index -= 1) {
+ const argument = argv[index];
+ if (!argument?.startsWith(WINDOW_BACKDROP_MATERIAL_ARGUMENT)) continue;
+ const raw = argument.slice(WINDOW_BACKDROP_MATERIAL_ARGUMENT.length);
+ return isWindowsBackdropMaterial(raw) ? raw : 'none';
+ }
+ return 'none';
+}
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index a1a5577973..51950fe352 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -35,20 +35,18 @@ What makes this system distinctive is the combination of a single geometric sans
The interface is built from a three-tier layer system that applies symmetrically to both modes — **Surface** as the base, **Card** as the elevated layer, and **Board** as the hairline divider. This is the foundation of every page in every mode.
-
| Role | Light Mode | Dark Mode | Usage |
| ----------- | ---------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Surface** | `#f8f8f6` | `#1f1f1e` | The primary page background — every page starts here. In full-window app layouts, this is the single flat background. In centered-card layouts, this is the page beneath the card. |
| **Card** | `#ffffff` | `#2c2c2a` | The elevated layer sitting on top of Surface — login cards, modals, panels, raised containers, and any element that needs to visually lift off the page. |
| **Board** | `#d7d7d4` | `#3c3c3a` | The hairline divider color — 1px borders between sections, card outlines, and any separator line within the same layer. |
-
**Layer rule — flat vs. elevated:**
- **Full-window applications** (e.g. main workspace, chat interface, dashboards): use **Surface** as a single flat background for the entire window — no Card layer at the page-structure level. Section boundaries (sidebar, toolbar, content area) are drawn with 1px **Board** dividers, never with background color shifts.
- **Centered-card layouts** (e.g. login, modal, empty-state card on a blank page): use **Surface** as the page background and **Card** as the lifted card. The color difference between Surface and Card is what makes the card read as "lifted" — no shadow needed. The card outline is drawn in **Board**.
-> **Important — element-level vs. page-level:** The "flat Surface" rule in full-window layouts applies only to the **overall page structure**, not to individual widgets. Lifted widgets *within* a full-window layout — inputs, chat input boxes, raised cards, modal overlays, panel popups — still use **Card** color per their component rules (see Section 4). A full-window chat interface can have a flat Surface page *and* a Card-colored chat input box at the same time; those are two different scopes. "Surface flat" means "don't split the page into Page+Card layers," not "every element on the page must be Surface color."
+> **Important — element-level vs. page-level:** The "flat Surface" rule in full-window layouts applies only to the **overall page structure**, not to individual widgets. Lifted widgets _within_ a full-window layout — inputs, chat input boxes, raised cards, modal overlays, panel popups — still use **Card** color per their component rules (see Section 4). A full-window chat interface can have a flat Surface page _and_ a Card-colored chat input box at the same time; those are two different scopes. "Surface flat" means "don't split the page into Page+Card layers," not "every element on the page must be Surface color."
### Chip & Button Neutrals
@@ -81,10 +79,10 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
> - **Resource Usage Process Categories** — the Resource Usage table may color only its 14px process-type glyphs so dense rows can be scanned by category (user-requested 2026-08-06). The six category pairs are task Agent blue `#2563EB / #60A5FA`, Agent service purple `#7C3AED / #A78BFA`, main-process pink `#DB2777 / #F472B6`, renderer cyan `#0891B2 / #22D3EE`, GPU amber `#D97706 / #F59E0B`, and utility green `#059669 / #34D399` (Light / Dark). These colors encode process category, **not health or status**; row backgrounds, labels, metrics, selection and actions remain on the neutral system. Scope is strictly `resource-usage` process glyphs and must not be generalized to other tables or process UI. Tokens: `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon`.
> - **ConfirmDialog Danger** — `#EF4444` used ONLY on the confirm button background in the Danger variant. The cancel button and rest of the dialog remain grayscale.
> - **Permission Selector Mode Highlights** — selected risky permission modes may color only the option text/icon/checkmark and the collapsed trigger text/icon. The selected row background remains grayscale. Auto Approval uses `#417CDD` in both modes (finalized 2026-07-17, same value light/dark; replaces light #000050 / dark #00D9C5). Full Access uses Heart Orange `#EA6B17` in both modes (auto-follows warning-accent, finalized 2026-07-17). These hex values are the **default-theme palette only** — other themes may override `--perm-auto-selected-text` and `--perm-bypass-selected-text` with their own accent colors, provided both modes remain color-coded, distinguishable from each other, and visually distinct from neutral text. Tokens: `--perm-auto-selected-text` and `--perm-bypass-selected-text` in `apps/desktop/src/renderer/styles/globals.css`.
-> - **Diff Add Green / Diff Del Red** — GitHub-standard diff syntax colors, used on the `+` / `-` symbol glyph, the changed-line text foreground, **and the full row background** inside code-diff renderings. Applied in three places: (1) the Edit-tool DiffView card (F-MSG-6), (2) markdown ````diff` fenced code blocks in the message stream, and (3) `.diff` / `.patch` files opened in TextLightbox (the document previewer) — there hljs `.hljs-addition` / `.hljs-deletion` are forced `display: block` so the background fills to the right edge instead of stopping at the last glyph. Line-number gutter and ctx (unchanged) lines remain strictly grayscale per the layer system. **Foreground** — Add: `#22863a` Light / `#7ee787` Dark; Del: `#b31d28` Light / `#ff7b72` Dark. **Background** — Add: `#f0fff4` Light / `#033a16` Dark; Del: `#ffeef0` Light / `#67060c` Dark. Tokens: `--diff-add-fg/-bg` and `--diff-del-fg/-bg` in `apps/desktop/src/renderer/styles/globals.css`. Updated 2026-04-21: backgrounds switched from grayscale → GitHub red/green for full-row fill so additions / deletions are unambiguous at a glance.
+> - **Diff Add Green / Diff Del Red** — GitHub-standard diff syntax colors, used on the `+` / `-` symbol glyph, the changed-line text foreground, **and the full row background** inside code-diff renderings. Applied in three places: (1) the Edit-tool DiffView card (F-MSG-6), (2) markdown ````diff`fenced code blocks in the message stream, and (3)`.diff`/`.patch`files opened in TextLightbox (the document previewer) — there hljs`.hljs-addition`/`.hljs-deletion`are forced`display: block`so the background fills to the right edge instead of stopping at the last glyph. Line-number gutter and ctx (unchanged) lines remain strictly grayscale per the layer system. **Foreground** — Add:`#22863a`Light /`#7ee787`Dark; Del:`#b31d28`Light /`#ff7b72`Dark. **Background** — Add:`#f0fff4`Light /`#033a16`Dark; Del:`#ffeef0`Light /`#67060c`Dark. Tokens:`--diff-add-fg/-bg`and`--diff-del-fg/-bg`in`apps/desktop/src/renderer/styles/globals.css`. Updated 2026-04-21: backgrounds switched from grayscale → GitHub red/green for full-row fill so additions / deletions are unambiguous at a glance.
> - **PR Status Colors (session-git-pr-context / sidebar task-info)** — closed = `--error-fg`, merged = `--focus-ring`, draft = `--text-tertiary` (single source: `PR_STATUS_COLOR` in `apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts`). **Open green is split:** the session-header GitContextBadge and sidebar hover tooltip keep `--diff-add-fg` (theme-following GitHub greens). The sidebar task-info icon (registered 2026-08-17) follows the **surface**, not the theme name: it reads HSL lightness of `--sidebar` / `--sidebar-item-active` (Cindy's selected pill is inverse; many community/imported themes are not). Light surfaces use `--pr-open-on-light` `#2EA043`; dark surfaces use `--pr-open-on-dark` `#3FB950`. Both values are theme-invariant. The `#number` stays on the info-slot foreground. Open/draft PRs with `unresolvedCount > 0` add a 5px static `--status-bar-accent` corner dot on the status icon (not an AttentionDot tone). Unknown/unloaded status degrades to `--text-tertiary`. Scope is strictly PR-state surfaces; do not generalize these colors to other status systems.
-*Dark Mode text uses softened neutrals to reduce eye strain: **Soft Gray** (`#d4d4d4`) for primary text, **Silver** (`#a3a3a3`) for secondary, **Stone** (`#737373`) for tertiary (per `--text-secondary` / `--text-tertiary` in `colors.ts` — the two swap between modes). Pure White (`#ffffff`) is reserved for button labels and high-contrast UI elements on dark backgrounds.*
+_Dark Mode text uses softened neutrals to reduce eye strain: **Soft Gray** (`#d4d4d4`) for primary text, **Silver** (`#a3a3a3`) for secondary, **Stone** (`#737373`) for tertiary (per `--text-secondary` / `--text-tertiary` in `colors.ts` — the two swap between modes). Pure White (`#ffffff`) is reserved for button labels and high-contrast UI elements on dark backgrounds._
### Gradient System
@@ -98,28 +96,26 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
- **Display / Body / UI**: `Inter`, with fallbacks: `system-ui, -apple-system, "Segoe UI", sans-serif`
- **Monospace**: `JetBrains Mono`, with fallbacks: `ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`
-*Note: The entire interface uses a single sans font — Inter — for both display headlines and body text. Inter is chosen for (a) its neutral, geometric character that stays out of the way, (b) its excellent legibility at small sizes, and (c) its wide availability in both web and design tooling. A single font keeps the hierarchy clean — separation comes from size and weight, not typeface contrast.*
+_Note: The entire interface uses a single sans font — Inter — for both display headlines and body text. Inter is chosen for (a) its neutral, geometric character that stays out of the way, (b) its excellent legibility at small sizes, and (c) its wide availability in both web and design tooling. A single font keeps the hierarchy clean — separation comes from size and weight, not typeface contrast._
### Hierarchy
-
-| Role | Font | Size | Weight | Line Height | Letter Spacing | Notes |
-| --------------- | -------------- | -------------- | ------- | ------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Display / Hero | Inter | 48px (3rem) | 500 | 1.00 (tight) | normal | Maximum impact headline |
-| Section Heading | Inter | 36px (2.25rem) | 500 | 1.11 (tight) | normal | Feature section titles |
+| Role | Font | Size | Weight | Line Height | Letter Spacing | Notes |
+| --------------- | -------------- | -------------- | --------- | ------------ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Display / Hero | Inter | 48px (3rem) | 500 | 1.00 (tight) | normal | Maximum impact headline |
+| Section Heading | Inter | 36px (2.25rem) | 500 | 1.11 (tight) | normal | Feature section titles |
| Sub-heading | Inter | 30px (1.88rem) | 400 / 500 | 1.20 (tight) | normal | Card headings, feature names |
-| Card Title | Inter | 24px (1.5rem) | 400 | 1.33 | normal | Medium emphasis headings |
+| Card Title | Inter | 24px (1.5rem) | 400 | 1.33 | normal | Medium emphasis headings |
| Body Large | Inter | 18px (1.13rem) | 400 / 500 | 1.56 | normal | Hero descriptions, button text |
| Body / Link | Inter | 16px (1rem) | 400 / 500 | 1.50 | normal | Standard body text, navigation |
-| Caption | Inter | 14px (0.88rem) | 400 | 1.43 | normal | Metadata, descriptions |
-| Small | Inter | 12px (0.75rem) | 400 | 1.33 | normal | Smallest reading-text size (auxiliary Micro Label may go smaller, floor 10px) |
+| Caption | Inter | 14px (0.88rem) | 400 | 1.43 | normal | Metadata, descriptions |
+| Small | Inter | 12px (0.75rem) | 400 | 1.33 | normal | Smallest reading-text size (auxiliary Micro Label may go smaller, floor 10px) |
| Micro Label | Inter | 10–13px | 400 / 500 | 1.20–1.40 | optional 0.5–1px tracking on uppercase | **Auxiliary / non-reading** labels only — sidebar tree section heads (13px), tree row counts, frontmatter field names, scope chips, tag pills, status badges, breadcrumb segments. Never used for body text or anything the user reads sentence-by-sentence. |
-| Code Body | JetBrains Mono | 16px (1rem) | 400 | 1.50 | normal | Inline code, commands |
-| Code Caption | JetBrains Mono | 14px (0.88rem) | 400 | 1.43 | normal | Code snippets, secondary |
+| Code Body | JetBrains Mono | 16px (1rem) | 400 | 1.50 | normal | Inline code, commands |
+| Code Caption | JetBrains Mono | 14px (0.88rem) | 400 | 1.43 | normal | Code snippets, secondary |
| Code Small | JetBrains Mono | 11–12px | 400 / 500 | 1.40–1.63 | normal | Tags, labels, in-tree paths |
-
-*Positioning note: the Display / Section Heading / Sub-heading rows are conceptual role targets for **brand canvases only** (the §16 login / splash family and its self-contained pages). Their concrete values live in canvas constants and §16 tables, not in app code. The 「排版豁免登记表」 below only registers exemption domains. Everything else — everyday chrome **and** in-app empty states — lives in the Body / Caption / Small / Micro rows, and for `apps/desktop` code the normative size set is the 「桌面 UI 字号白名单」 below: this table describes roles, the whitelist constrains values.*
+_Positioning note: the Display / Section Heading / Sub-heading rows are conceptual role targets for **brand canvases only** (the §16 login / splash family and its self-contained pages). Their concrete values live in canvas constants and §16 tables, not in app code. The 「排版豁免登记表」 below only registers exemption domains. Everything else — everyday chrome **and** in-app empty states — lives in the Body / Caption / Small / Micro rows, and for `apps/desktop` code the normative size set is the 「桌面 UI 字号白名单」 below: this table describes roles, the whitelist constrains values._
### Principles
@@ -132,12 +128,12 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
全站字重只允许以下四档整百值,禁止一切中间值(550/650…)与 800 及以上:
-| 档 | 名称 | 用途 |
-| --- | --- | --- |
-| 400 | Regular | 长文阅读正文、代码 |
-| 500 | Medium | UI 默认强调、标题 —— 日常 chrome 的主力档 |
+| 档 | 名称 | 用途 |
+| --- | -------- | --------------------------------------------------------------------------- |
+| 400 | Regular | 长文阅读正文、代码 |
+| 500 | Medium | UI 默认强调、标题 —— 日常 chrome 的主力档 |
| 600 | Semibold | 限量强调(徽标、表头、选中态等局部加重)。新增使用要能说出「为什么 500 不够」 |
-| 700 | Bold | **仅限下方豁免登记表中的域**,禁止出现在普通 UI chrome |
+| 700 | Bold | **仅限下方豁免登记表中的域**,禁止出现在普通 UI chrome |
- 与手机端 `apps/mobile/src/theme/tokens.ts` 的 `fontWeight` token(regular / medium / semibold / bold)一一对应 —— 两端一张梯子。
- **两端 700 口径**:手机端 UI chrome 的上限仍是 600(正本为 `apps/mobile/docs/mobile-design-guide.md`,该文已同步登记本例外)。`bold` / 700 在手机端**只允许**出现在下表登记的域——原生 Markdown strong 与登录品牌画布。也就是说「四档梯子」是两端共用的**档位定义**,不等于两端 chrome 都可用 700。
@@ -155,18 +151,18 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
以下是**登记过的刻意分歧**,不要当 bug「修」;新增豁免必须先改本表:
-| 域 | 范围 | 允许 | 理由 |
-| --- | --- | --- | --- |
-| 登录 / Splash 品牌画布 | 桌面 `LoginControls.tsx`、`loginDesignTokens.ts`(Splash 借用同族面板)、`LegacyMigrationDialog.tsx`(仅字重)、`oauthResultPage.ts`(自包含品牌页生成器,raw CSS 为其常量载体);手机 `apps/mobile/app/(auth)/login.tsx`(登录页本体)、`apps/mobile/src/components/LoginSkinControls.tsx` 与 `apps/mobile/src/auth/loginSkinLayout.ts` | 700 + 设计 px 字号 | §16 已登记 Bold,两端共用同源登录画布与 figma 坐标系;桌面守卫只扫描 `apps/desktop/src/renderer`,手机端由自身守卫体系负责,本登记不扩展 PR #1553 的扫描范围 |
-| markdown 内容 | **仅 Markdown 渲染路径**:桌面 Markdown 渲染器输出的 DOM `<strong>`(`MarkdownRenderer` 及其消费方;必须解析为绝对 700;嵌套 strong 仍封顶 700)、CodeMirror strong 语法节点(`codemirrorGithubTheme.ts` 的 `t.strong` → `fontWeight: 'bold'`)、移动端原生 Markdown strong(`apps/mobile/src/session/MessageRenderer.tsx` 的 `markdownStrong` → `fontWeight.bold`) | 700 / `bold` | 用户内容语义,非 UI chrome;编辑器内 strong 与两端渲染后的 strong 同权。当前桌面 Tailwind preflight 的相对 `bolder` 会使嵌套 strong 计算到更高档位,是已知实现缺口;规则不把该结果视为合规,待独立施工。**本行不覆盖普通 UI chrome 里直接写的 `<strong>`**(如 `MakerExperimentalView.tsx` 会话状态与事件列表)——它们同样被 preflight 的相对 `bolder` 渲染成 700,但不属豁免域,是已登记缺口,待归一为 `font-medium` / `font-semibold`。 |
-| hljs 主题移植 | `globals.css` 内 hljs 规则 | `bold` | 第三方主题移植,保真优先 |
-| 第三方查看器(用户内容) | `apps/desktop/src/renderer/vendor/drawio/viewer-static.min.js`(由 `DrawioPreview.tsx` 加载)及 `vendor/` 下其他上游产物 | 上游自带字重与字号 | 上游压缩产物,渲染的是用户绘图内容而非本产品 chrome;不改上游、不逐行归一。**守卫边界**:整个 `vendor/` 目录不纳入扫描(PR #1553 已在守卫盲区中显式登记该排除,不是未登记的漏扫)。 |
-| CodeMirror / Markdown 内容字号 | `codemirrorGithubTheme.ts` 的标题等内容层级(`2.15em` / `1.62em` 等相对值,CSS-in-JS 路径) | 相对字号(`em` 派生) | 内容标题层级必须随编辑器基础字号等比缩放,固定 token 会打断这个比例关系;相对值本身不脱离缩放链,故不要求落在 numeric 白名单。**守卫边界**:`em` / `rem` / `%` 相对值不参与 numeric 白名单判定。 |
-| 命令式第三方 API(非 DOM class 路径) | xterm 的 `ITerminalOptions.fontSize`(`features/right-sidebar/plugins/terminal/lib/xtermPool.ts`)等只接受**数值字段**、无法挂 class 的第三方配置入口;SVG 的 `fontSize="N"` 属性同理 | 数值字面量 | 这类 API 不消费 DOM class,Tailwind token 类挂不上去,只能传数字。**取值规则**:数值必须取自本白名单档位,或取自用户代码字号设置(`--app-code-font-size` / `appearanceSettings.codeSize`)解析出的运行期值 —— 不允许凭手感另取一个数。**守卫边界**:按精确签名放行(文件 + 字段 + 期望次数),不做整文件豁免,新增此类入口须先改本表。 |
-| 用户可配置代码字号(变量路径) | `--app-code-font-size` 及其派生写法(`text-[length:var(--app-code-font-size)]`、`text-[length:calc(var(--app-code-font-size)_-_1px)]` 等,消费方含 Markdown / DiffView / ToolCallCard 等约 19 个文件) | 变量与其 `calc` 派生 | 该字号是**用户设置项**,`appearanceSettings.ts` 的 `codeSize` 允许 10–24 逐整数取值,因此运行期可落在 17 / 19 / 21 / 22 / 23 等 numeric 白名单外的值;这是刻意的可配置能力,不是漏归一。本白名单约束的是**开发者写死的档位**,不约束用户设置的运行期取值。**守卫边界**:`--app-code-font-size` 的变量与 `calc` 派生写法按精确签名登记豁免(见 PR #1553 守卫的豁免表),不按 numeric 白名单判定。 |
-| 外部页注入 | `browserCommentPreload.ts` | 系统字体族 | 注入他人网页,不强加 Inter |
-| 手机 WebView HTML 生成器 | `selectableMarkdownHtml.ts` 等 | CSS 语法字面量 | 手机守卫已自登记盲区,值仍须守本阶梯 |
-| 紧凑模式派生值 | `globals.css` `.chat-rail-compact` 段 | calc / -1px 派生 | 机制本体 |
+| 域 | 范围 | 允许 | 理由 |
+| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 登录 / Splash 品牌画布 | 桌面 `LoginControls.tsx`、`loginDesignTokens.ts`(Splash 借用同族面板)、`LegacyMigrationDialog.tsx`(仅字重)、`oauthResultPage.ts`(自包含品牌页生成器,raw CSS 为其常量载体);手机 `apps/mobile/app/(auth)/login.tsx`(登录页本体)、`apps/mobile/src/components/LoginSkinControls.tsx` 与 `apps/mobile/src/auth/loginSkinLayout.ts` | 700 + 设计 px 字号 | §16 已登记 Bold,两端共用同源登录画布与 figma 坐标系;桌面守卫只扫描 `apps/desktop/src/renderer`,手机端由自身守卫体系负责,本登记不扩展 PR #1553 的扫描范围 |
+| markdown 内容 | **仅 Markdown 渲染路径**:桌面 Markdown 渲染器输出的 DOM `<strong>`(`MarkdownRenderer` 及其消费方;必须解析为绝对 700;嵌套 strong 仍封顶 700)、CodeMirror strong 语法节点(`codemirrorGithubTheme.ts` 的 `t.strong` → `fontWeight: 'bold'`)、移动端原生 Markdown strong(`apps/mobile/src/session/MessageRenderer.tsx` 的 `markdownStrong` → `fontWeight.bold`) | 700 / `bold` | 用户内容语义,非 UI chrome;编辑器内 strong 与两端渲染后的 strong 同权。当前桌面 Tailwind preflight 的相对 `bolder` 会使嵌套 strong 计算到更高档位,是已知实现缺口;规则不把该结果视为合规,待独立施工。**本行不覆盖普通 UI chrome 里直接写的 `<strong>`**(如 `MakerExperimentalView.tsx` 会话状态与事件列表)——它们同样被 preflight 的相对 `bolder` 渲染成 700,但不属豁免域,是已登记缺口,待归一为 `font-medium` / `font-semibold`。 |
+| hljs 主题移植 | `globals.css` 内 hljs 规则 | `bold` | 第三方主题移植,保真优先 |
+| 第三方查看器(用户内容) | `apps/desktop/src/renderer/vendor/drawio/viewer-static.min.js`(由 `DrawioPreview.tsx` 加载)及 `vendor/` 下其他上游产物 | 上游自带字重与字号 | 上游压缩产物,渲染的是用户绘图内容而非本产品 chrome;不改上游、不逐行归一。**守卫边界**:整个 `vendor/` 目录不纳入扫描(PR #1553 已在守卫盲区中显式登记该排除,不是未登记的漏扫)。 |
+| CodeMirror / Markdown 内容字号 | `codemirrorGithubTheme.ts` 的标题等内容层级(`2.15em` / `1.62em` 等相对值,CSS-in-JS 路径) | 相对字号(`em` 派生) | 内容标题层级必须随编辑器基础字号等比缩放,固定 token 会打断这个比例关系;相对值本身不脱离缩放链,故不要求落在 numeric 白名单。**守卫边界**:`em` / `rem` / `%` 相对值不参与 numeric 白名单判定。 |
+| 命令式第三方 API(非 DOM class 路径) | xterm 的 `ITerminalOptions.fontSize`(`features/right-sidebar/plugins/terminal/lib/xtermPool.ts`)等只接受**数值字段**、无法挂 class 的第三方配置入口;SVG 的 `fontSize="N"` 属性同理 | 数值字面量 | 这类 API 不消费 DOM class,Tailwind token 类挂不上去,只能传数字。**取值规则**:数值必须取自本白名单档位,或取自用户代码字号设置(`--app-code-font-size` / `appearanceSettings.codeSize`)解析出的运行期值 —— 不允许凭手感另取一个数。**守卫边界**:按精确签名放行(文件 + 字段 + 期望次数),不做整文件豁免,新增此类入口须先改本表。 |
+| 用户可配置代码字号(变量路径) | `--app-code-font-size` 及其派生写法(`text-[length:var(--app-code-font-size)]`、`text-[length:calc(var(--app-code-font-size)_-_1px)]` 等,消费方含 Markdown / DiffView / ToolCallCard 等约 19 个文件) | 变量与其 `calc` 派生 | 该字号是**用户设置项**,`appearanceSettings.ts` 的 `codeSize` 允许 10–24 逐整数取值,因此运行期可落在 17 / 19 / 21 / 22 / 23 等 numeric 白名单外的值;这是刻意的可配置能力,不是漏归一。本白名单约束的是**开发者写死的档位**,不约束用户设置的运行期取值。**守卫边界**:`--app-code-font-size` 的变量与 `calc` 派生写法按精确签名登记豁免(见 PR #1553 守卫的豁免表),不按 numeric 白名单判定。 |
+| 外部页注入 | `browserCommentPreload.ts` | 系统字体族 | 注入他人网页,不强加 Inter |
+| 手机 WebView HTML 生成器 | `selectableMarkdownHtml.ts` 等 | CSS 语法字面量 | 手机守卫已自登记盲区,值仍须守本阶梯 |
+| 紧凑模式派生值 | `globals.css` `.chat-rail-compact` 段 | calc / -1px 派生 | 机制本体 |
### 排版 non-goals(2026-08 登记)
@@ -294,20 +290,18 @@ Three tiers — **these three only**:
- **Container (12px)**: box radius — code blocks, cards, panels, dialogs. Implemented as Tailwind `rounded-xl` (12px).
- **Pill (9999px)**: every interactive element that can wear the pill — buttons, tabs, single-line inputs, tags, badges.
-*No 4px / 6px / 10px, and no arbitrary radii. Most elements still pick between the 12px container and the pill; 8px is a narrow exception for controls that don't fit the pill. Mind nesting: an 8px row highlight inside a 12px panel must stay smaller than its container to nest cleanly (hence 8, not 12) — a pill there becomes a lozenge, 12px looks bloated.*
+_No 4px / 6px / 10px, and no arbitrary radii. Most elements still pick between the 12px container and the pill; 8px is a narrow exception for controls that don't fit the pill. Mind nesting: an 8px row highlight inside a 12px panel must stay smaller than its container to nest cleanly (hence 8, not 12) — a pill there becomes a lozenge, 12px looks bloated._
> **Narrow exception — status micro-cells (2px)** (registered 2026-07-28): non-interactive status squares of 8×8px or smaller keep a 2px radius — the workflow agent status strip's cells (background-tasks panel detail + workflow chat card) and the equivalent per-category square in SystemCard. At that size any tier radius rounds the square into a dot and destroys the "block strip" read that lets a large agent fleet be scanned at a glance. Scope is exactly this: **non-interactive, ≤8px, status-only**. Do NOT generalize to buttons, tags, rows, badges or containers — those still pick a tier.
## 6. Depth & Elevation
-
| Level | Treatment | Use |
| ------------------ | ------------------------------------------------------------------------- | ---------------------------------------------- |
| Flat (Level 0) | No shadow, no border | Surface background, most content |
| Bordered (Level 1) | `1px solid` Board (`#d7d7d4` Light / `#3c3c3a` Dark) | Cards, code blocks, dividers, section outlines |
| Lifted (Card) | Card fill (`#ffffff` Light / `#2c2c2a` Dark) + optional 1px Board outline | Login cards, modals, raised panels |
-
**Shadow Philosophy**: Cindy's base visual language uses **zero shadows**. This is not an oversight — it's a deliberate design decision. The flat, shadowless approach creates a paper-like experience where elements are distinguished purely by background color and single-pixel borders. Depth is communicated through **content hierarchy and typography weight**, not visual layering. (The only shadows in the system are the token-gated floating-layer exceptions registered in §10 — `--shadow-menu` / `--cmd-palette-shadow` / `--confirm-shadow`; never add ad-hoc shadows to in-page elements. A Switch-knob shadow was trialed and explicitly rejected — user ruling 2026-08-05: the legacy `shadow-lg` on the 16px thumb was invisible in practice, and a visible replacement read as noise; the knob is flat by decision, don't re-add it.)
## 7. Do's and Don'ts
@@ -390,13 +384,14 @@ Cindy Mobile (React Native) has its own device-class rules (phone / pad portrait
- **Every UI must be implemented for both Light and Dark modes.** When adding or changing any page, component, layout, style, motion, or UI copy, both modes must be designed and built within the same piece of work; designing or implementing only one mode counts as incomplete. **Visual QA in both modes is expected effort, not a blocking gate** — see the last bullet.
- Both modes must cover every state actually touched by the change — default, hover, pressed, selected, focus, disabled, loading, empty, error, overlays and scrims. States the change does not touch need not be retrofitted just to tick a box.
- Colors must be consumed through semantic tokens; hardcoded values or conditional patches that only fit one mode are forbidden. When the design mock provides only one mode, the other mode must still be filled in through the existing token system; if a clear semantic mapping is missing, request a design ruling first — never ship with a mode omitted.
-- **Verification is best-effort and must be reported honestly.** Eyeballing the affected surfaces in both Light and Dark before delivery is the preferred path, but skipping it does not block the change — say plainly in the commit / PR verification notes which mode was actually checked and which was not. Never upgrade "reused existing themed styles / added no raw color values" into a claim that both modes were verified. If a mode *is* checked and comes back unreadable, indistinguishable, missing states, or visibly regressed, that is a real defect and must be fixed before delivery.
+- **Verification is best-effort and must be reported honestly.** Eyeballing the affected surfaces in both Light and Dark before delivery is the preferred path, but skipping it does not block the change — say plainly in the commit / PR verification notes which mode was actually checked and which was not. Never upgrade "reused existing themed styles / added no raw color values" into a claim that both modes were verified. If a mode _is_ checked and comes back unreadable, indistinguishable, missing states, or visibly regressed, that is a real defect and must be fixed before delivery.
### Architecture
Cindy Desktop manages color with a **VSCode-style ColorRegistry + theme-override** model. Every color reaches components as a CSS-variable token; **hardcoding hex / rgba inside a component is never allowed** (it makes the component un-themeable outside the default theme).
Source: `apps/desktop/src/renderer/themes/`
+
- `color-registry.ts` — the `ColorRegistry` singleton and the `registerColor(id, defaults, description)` API
- `colors.ts` — registers every token, organized "semantic slots first, aliases and singletons after" (counts drift constantly — **`colors.ts` itself is the only authoritative inventory**; this document does not track totals)
- `theme-service.ts` — `applyTheme(theme)` serializes all tokens into `:root{}` and injects `<style id="theme-vars">`
@@ -409,45 +404,45 @@ Theme switching: `useTheme.ts` provides `theme` (System / Light / Dark mode) plu
**Tier 1 — Semantic slots**: the core cross-context slots; when adding a theme, this tier is the main override battleground. The table below lists every slot exhaustively — it IS the Tier-1 registry.
-| Category | Slot | Default Light | Default Dark | Primary use |
-|---|---|---|---|---|
-| **Surface** | `--surface` | `#f8f8f6` | `#1f1f1e` | Page Surface (hex form) |
-| | `--surface-hsl` | `60 12.5% 97%` | `60 2% 12%` | Same, HSL triplet — consume via `hsl(var(--xxx))` |
-| | `--surface-elevated` | `#ffffff` | `#2c2c2a` | Card lift / dialogs / popovers |
-| | `--surface-elevated-soft` | `#e5e5e5` | `#2c2c2a` | Disabled-state Card |
-| | `--surface-card-ivory` | `#faf9f5` | `#2c2c2a` | Slightly warm ivory Card (Settings) |
-| | `--surface-chip` | `#e5e5e5` | `#3c3c3a` | Chips / pills / selected rows |
-| | `--surface-chip-alt` | `#e5e5e5` | `#2c2c2a` | Chip variant that collapses to Card in Dark |
-| | `--surface-hover` | `#e5e5e5` | `#3c3c3a` | General hover bg |
-| | `--surface-hover-soft` | `#f8f8f6` | `#3c3c3a` | Soft hover bg |
-| | `--surface-hover-hsl` | `0 0% 90%` | `60 2% 17%` | Hover, HSL form |
-| | `--surface-on-card` | `#ffffff` | `#1f1f1e` | Dark foreground on CTAs / checked icons |
-| **Border** | `--border-default` | `#d7d7d4` | `#3c3c3a` | This spec's Board 1px border |
-| | `--border-default-hsl` | `60 3% 84%` | `60 2% 23%` | Board, HSL form |
-| | `--border-shadcn-hsl` | `0 0% 90%` | `30 4% 28%` | shadcn input/border HSL |
-| | `--border-transparent-mixed` | `transparent` | `#3c3c3a` | Single-side borders (progress track etc.) |
-| **Text** | `--text-primary` | `#262626` | `#d4d4d4` | Primary headings / body |
-| | `--text-primary-hsl` | `0 0% 9%` | `0 0% 83%` | Primary, HSL form |
-| | `--text-primary-on-dark` | `#262626` | `#ffffff` | Inverse text (stop-button icon etc.) |
-| | `--text-primary-emphasis` | `#1a1a1a` | `#d4d4d4` | Plan emphasized primary text |
-| | `--text-primary-inv` | `#1a1a1a` | `#ffffff` | Plan-action approve text |
-| | `--text-primary-body-strong` | `#525252` | `#d4d4d4` | Plan content body, strong |
-| | `--text-secondary` | `#737373` | `#a3a3a3` | Secondary text / icons |
-| | `--text-secondary-cross` | `#a3a3a3` | `#a3a3a3` | Lighter cross-theme secondary |
-| | `--text-secondary-mid` | `#525252` | `#a3a3a3` | Muted body text |
-| | `--text-tertiary` | `#a3a3a3` | `#737373` | Placeholder / tertiary |
-| | `--text-tertiary-stone` | `#737373` | `#737373` | Cross-theme Stone tertiary |
-| | `--text-tertiary-mid` | `#525252` | `#737373` | Mid-gray tertiary |
-| | `--text-tertiary-hsl` | `0 0% 45%` | `0 0% 45%` | Tertiary, HSL form |
-| | `--text-disabled` | `#d4d4d4` | `#525252` | Disabled / failed |
-| | `--text-disabled-tertiary` | `#a3a3a3` | `#737373` | Disabled placeholder variant |
-| | `--text-placeholder` | `#c4c4c4` | `#525252` | Unified placeholder slot (lighter than tertiary — reads as empty); chat/ask/settings/plan-action-fb inputs all resolve here |
-| **Accent** | `--accent-cta-bg` | `#262626` | `#ffffff` | Inverse CTA bg |
-| | `--accent-cta-bg-pure` | `#000000` | `#ffffff` | Pure CTA bg |
-| | `--accent-emphasis` | `#262626` | `#d4d4d4` | Settings primary button etc. |
-| | `--accent-soft` | `#262626` | `#ffffff` | Soft accent (folder button etc.) |
-| | `--accent-hover` | `#262626` | `#e5e5e5` | CTA pressed/hover |
-| | `--accent-pure-cta-fg` | `#ffffff` | `#000000` | Pure-inverse CTA text |
+| Category | Slot | Default Light | Default Dark | Primary use |
+| ----------- | ---------------------------- | -------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------- |
+| **Surface** | `--surface` | `#f8f8f6` | `#1f1f1e` | Page Surface (hex form) |
+| | `--surface-hsl` | `60 12.5% 97%` | `60 2% 12%` | Same, HSL triplet — consume via `hsl(var(--xxx))` |
+| | `--surface-elevated` | `#ffffff` | `#2c2c2a` | Card lift / dialogs / popovers |
+| | `--surface-elevated-soft` | `#e5e5e5` | `#2c2c2a` | Disabled-state Card |
+| | `--surface-card-ivory` | `#faf9f5` | `#2c2c2a` | Slightly warm ivory Card (Settings) |
+| | `--surface-chip` | `#e5e5e5` | `#3c3c3a` | Chips / pills / selected rows |
+| | `--surface-chip-alt` | `#e5e5e5` | `#2c2c2a` | Chip variant that collapses to Card in Dark |
+| | `--surface-hover` | `#e5e5e5` | `#3c3c3a` | General hover bg |
+| | `--surface-hover-soft` | `#f8f8f6` | `#3c3c3a` | Soft hover bg |
+| | `--surface-hover-hsl` | `0 0% 90%` | `60 2% 17%` | Hover, HSL form |
+| | `--surface-on-card` | `#ffffff` | `#1f1f1e` | Dark foreground on CTAs / checked icons |
+| **Border** | `--border-default` | `#d7d7d4` | `#3c3c3a` | This spec's Board 1px border |
+| | `--border-default-hsl` | `60 3% 84%` | `60 2% 23%` | Board, HSL form |
+| | `--border-shadcn-hsl` | `0 0% 90%` | `30 4% 28%` | shadcn input/border HSL |
+| | `--border-transparent-mixed` | `transparent` | `#3c3c3a` | Single-side borders (progress track etc.) |
+| **Text** | `--text-primary` | `#262626` | `#d4d4d4` | Primary headings / body |
+| | `--text-primary-hsl` | `0 0% 9%` | `0 0% 83%` | Primary, HSL form |
+| | `--text-primary-on-dark` | `#262626` | `#ffffff` | Inverse text (stop-button icon etc.) |
+| | `--text-primary-emphasis` | `#1a1a1a` | `#d4d4d4` | Plan emphasized primary text |
+| | `--text-primary-inv` | `#1a1a1a` | `#ffffff` | Plan-action approve text |
+| | `--text-primary-body-strong` | `#525252` | `#d4d4d4` | Plan content body, strong |
+| | `--text-secondary` | `#737373` | `#a3a3a3` | Secondary text / icons |
+| | `--text-secondary-cross` | `#a3a3a3` | `#a3a3a3` | Lighter cross-theme secondary |
+| | `--text-secondary-mid` | `#525252` | `#a3a3a3` | Muted body text |
+| | `--text-tertiary` | `#a3a3a3` | `#737373` | Placeholder / tertiary |
+| | `--text-tertiary-stone` | `#737373` | `#737373` | Cross-theme Stone tertiary |
+| | `--text-tertiary-mid` | `#525252` | `#737373` | Mid-gray tertiary |
+| | `--text-tertiary-hsl` | `0 0% 45%` | `0 0% 45%` | Tertiary, HSL form |
+| | `--text-disabled` | `#d4d4d4` | `#525252` | Disabled / failed |
+| | `--text-disabled-tertiary` | `#a3a3a3` | `#737373` | Disabled placeholder variant |
+| | `--text-placeholder` | `#c4c4c4` | `#525252` | Unified placeholder slot (lighter than tertiary — reads as empty); chat/ask/settings/plan-action-fb inputs all resolve here |
+| **Accent** | `--accent-cta-bg` | `#262626` | `#ffffff` | Inverse CTA bg |
+| | `--accent-cta-bg-pure` | `#000000` | `#ffffff` | Pure CTA bg |
+| | `--accent-emphasis` | `#262626` | `#d4d4d4` | Settings primary button etc. |
+| | `--accent-soft` | `#262626` | `#ffffff` | Soft accent (folder button etc.) |
+| | `--accent-hover` | `#262626` | `#e5e5e5` | CTA pressed/hover |
+| | `--accent-pure-cta-fg` | `#ffffff` | `#000000` | Pure-inverse CTA text |
**Tier 2 — Aliases**: the many component-scoped tokens (`--cmd-palette-bg`, `--msg-tool-card-text`, `--settings-input-border`, …) whose defaults resolve to `var(--slot)`. The browser forward-resolves automatically; components are unaware — **keep consuming the alias names directly**.
@@ -455,29 +450,29 @@ Theme switching: `useTheme.ts` provides `theme` (System / Light / Dark mode) plu
### Semantic Exemption Colors (theme-invariant)
-| Token | Light | Dark | Use |
-|---|---|---|---|
-| `--destructive` (HSL) | `0 84% 60%` | `0 72% 63%` | Generic destructive text/border |
-| `--error-flat` | `#ef4444` | `#ef4444` | Flat danger foreground |
-| `--login-error-fg` | `#D91F37` | `#D91F37` | Login error text/border (see §16.1) |
-| `--error-bg/-border/-fg/-fg-strong` | (red) | (red) | Error alert card subsystem |
-| `--diff-add-fg/-bg`, `--diff-del-fg/-bg` | GitHub palette | GitHub palette | Diff rendering |
-| `--pr-open-on-light` | `#2EA043` | `#2EA043` | Sidebar task-info PR open on light surfaces (2026-08-17) |
-| `--pr-open-on-dark` | `#3FB950` | `#3FB950` | Sidebar task-info PR open on dark surfaces (2026-08-17) |
-| `--status-bar-accent` | `#EA6B17` | `#EA6B17` | Thinking Orange, theme-invariant (finalized 2026-07-17) |
-| `--plan-action-approve-icon-bg` | `#EA6B17` | `#EA6B17` | Plan approve — same thinking semantics (follows warning-accent, finalized 2026-07-17) |
-| `--perm-bypass-selected-text` | `#EA6B17` | `#EA6B17` | Heart Orange, permission semantics (auto-follows `var(--warning-accent)`, finalized 2026-07-17) |
-| `--settings-integration-warning` | `#EA6B17` | `#EA6B17` | Warning semantics (auto-follows `var(--warning-accent)`, finalized 2026-07-17) |
-| `--warning-bg-soft` | rgba(234,107,23,0.12) | rgba(234,107,23,0.18) | Warning alpha surface (alpha recomputed against `#EA6B17`, 2026-07-17) |
-| `--warning-fg` | `#F3A115` | `#F3A115` | Warning text/icons, including the update-restart busy-turn interruption hint |
-| `--focus-ring` / `--focus-ring-soft` | `#417CDD` / @50% | same | A11y focus ring, finalized 2026-07-17 (replaces #3b82f6), theme-invariant |
-| `--text-selection-bg` | `var(--focus-ring-soft)` | same | Selected text background; remains visible when focus moves into an embedded webview |
-| `--shadow-menu` / `--cmd-palette-shadow` / `--confirm-shadow` | rgba | rgba (deeper) | Shadows, theme-invariant |
-| `--overlay-modal` / `--overlay-lightbox` | rgba | rgba (deeper) | Modal / lightbox backdrop |
-| `--perm-auto-selected-text` | `#417CDD` | `#417CDD` | Auto Approval accent, finalized 2026-07-17 (same value both modes; replaces #000050/#00D9C5) |
-| Toast `#417CDD / #2AAE5B / #F3A115 / #D91F37` | (hardcoded in Toast.tsx, VARIANT_MAP exported) | same | Finalized 2026-07-17 (Toast exemption lifted, merged into the status-color family) |
-| `--file-badge-pdf/-doc/-sheet/-slide/-code` + `--file-badge-fg` | `#B23A26` / `#2C5CA8` / `#2E7D4F` / `#A25A12` / `#5B49A8`, fg `#FFFFFF` | same | File-type badges on the self-drawn attachment icon (2026-07-27). Bound to *what the file is*, not to the theme, so both modes share one value. Each accent is picked for ≥4.5:1 against `--file-badge-fg` (5.96 / 6.56 / 5.05 / 5.24 / 7.09) — the badge label renders at 10px (Micro Label floor, §3), so AA small-text applies. `--file-badge-fg` is a standalone white: `--accent-pure-cta-fg` flips to black in Dark and cannot be borrowed. |
-| `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon` | `#2563EB` / `#7C3AED` / `#DB2777` / `#0891B2` / `#D97706` / `#059669` | `#60A5FA` / `#A78BFA` / `#F472B6` / `#22D3EE` / `#F59E0B` / `#34D399` | Resource Usage 14px process-category glyphs only (2026-08-06). Category cue, not status; all surrounding UI stays neutral. Protected from automatic external-theme import so category identity does not drift. |
+| Token | Light | Dark | Use |
+| ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `--destructive` (HSL) | `0 84% 60%` | `0 72% 63%` | Generic destructive text/border |
+| `--error-flat` | `#ef4444` | `#ef4444` | Flat danger foreground |
+| `--login-error-fg` | `#D91F37` | `#D91F37` | Login error text/border (see §16.1) |
+| `--error-bg/-border/-fg/-fg-strong` | (red) | (red) | Error alert card subsystem |
+| `--diff-add-fg/-bg`, `--diff-del-fg/-bg` | GitHub palette | GitHub palette | Diff rendering |
+| `--pr-open-on-light` | `#2EA043` | `#2EA043` | Sidebar task-info PR open on light surfaces (2026-08-17) |
+| `--pr-open-on-dark` | `#3FB950` | `#3FB950` | Sidebar task-info PR open on dark surfaces (2026-08-17) |
+| `--status-bar-accent` | `#EA6B17` | `#EA6B17` | Thinking Orange, theme-invariant (finalized 2026-07-17) |
+| `--plan-action-approve-icon-bg` | `#EA6B17` | `#EA6B17` | Plan approve — same thinking semantics (follows warning-accent, finalized 2026-07-17) |
+| `--perm-bypass-selected-text` | `#EA6B17` | `#EA6B17` | Heart Orange, permission semantics (auto-follows `var(--warning-accent)`, finalized 2026-07-17) |
+| `--settings-integration-warning` | `#EA6B17` | `#EA6B17` | Warning semantics (auto-follows `var(--warning-accent)`, finalized 2026-07-17) |
+| `--warning-bg-soft` | rgba(234,107,23,0.12) | rgba(234,107,23,0.18) | Warning alpha surface (alpha recomputed against `#EA6B17`, 2026-07-17) |
+| `--warning-fg` | `#F3A115` | `#F3A115` | Warning text/icons, including the update-restart busy-turn interruption hint |
+| `--focus-ring` / `--focus-ring-soft` | `#417CDD` / @50% | same | A11y focus ring, finalized 2026-07-17 (replaces #3b82f6), theme-invariant |
+| `--text-selection-bg` | `var(--focus-ring-soft)` | same | Selected text background; remains visible when focus moves into an embedded webview |
+| `--shadow-menu` / `--cmd-palette-shadow` / `--confirm-shadow` | rgba | rgba (deeper) | Shadows, theme-invariant |
+| `--overlay-modal` / `--overlay-lightbox` | rgba | rgba (deeper) | Modal / lightbox backdrop |
+| `--perm-auto-selected-text` | `#417CDD` | `#417CDD` | Auto Approval accent, finalized 2026-07-17 (same value both modes; replaces #000050/#00D9C5) |
+| Toast `#417CDD / #2AAE5B / #F3A115 / #D91F37` | (hardcoded in Toast.tsx, VARIANT_MAP exported) | same | Finalized 2026-07-17 (Toast exemption lifted, merged into the status-color family) |
+| `--file-badge-pdf/-doc/-sheet/-slide/-code` + `--file-badge-fg` | `#B23A26` / `#2C5CA8` / `#2E7D4F` / `#A25A12` / `#5B49A8`, fg `#FFFFFF` | same | File-type badges on the self-drawn attachment icon (2026-07-27). Bound to _what the file is_, not to the theme, so both modes share one value. Each accent is picked for ≥4.5:1 against `--file-badge-fg` (5.96 / 6.56 / 5.05 / 5.24 / 7.09) — the badge label renders at 10px (Micro Label floor, §3), so AA small-text applies. `--file-badge-fg` is a standalone white: `--accent-pure-cta-fg` flips to black in Dark and cannot be borrowed. |
+| `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon` | `#2563EB` / `#7C3AED` / `#DB2777` / `#0891B2` / `#D97706` / `#059669` | `#60A5FA` / `#A78BFA` / `#F472B6` / `#22D3EE` / `#F59E0B` / `#34D399` | Resource Usage 14px process-category glyphs only (2026-08-06). Category cue, not status; all surrounding UI stays neutral. Protected from automatic external-theme import so category identity does not drift. |
Never freestyle these semantic colors as hardcoded hex — always go through the corresponding token.
@@ -490,14 +485,14 @@ The implementation truth is `builtinThemes` in `apps/desktop/src/renderer/themes
1. Create `apps/desktop/src/renderer/themes/builtin/<id>.ts` exporting a `Theme` object:
```ts
export const myTheme: Theme = {
- id: 'my-theme',
- name: 'My Theme',
- type: 'light' | 'dark',
+ id: "my-theme",
+ name: "My Theme",
+ type: "light" | "dark",
colors: {
// Override only the tokens that differ from the base theme;
// an empty object {} is also valid (identical to base).
- 'surface': '#xxx',
- 'text-primary': '#xxx',
+ surface: "#xxx",
+ "text-primary": "#xxx",
// ... most themes only need to override 30–90 tokens
},
};
@@ -612,16 +607,16 @@ Applies to submit-on-Enter fields: the chat composer, goal input, ask input, etc
Global tokens live in `:root` of `apps/desktop/src/renderer/styles/globals.css`; mobile (`apps/mobile`) mirrors same-name same-value constants in `src/theme/tokens.ts` (dual-platform isomorphism, same policy as color tokens, landing with the mobile motion overhaul). **New transitions/animations must reference tokens — no hardcoded durations or cubic-beziers**; 5 interaction-duration tiers + 3 curves, the same philosophy as the §5 three-tier radius. Values outside the tiers require design review first. Narrow semantic exceptions are recorded directly below.
-| Token | Value | Use |
-|---|---|---|
-| `--motion-instant` | 80ms | Instant hover feedback; light-overlay exit |
-| `--motion-fast` | 150ms | Color/opacity state changes (`transition-colors` = this tier); light-overlay enter |
-| `--motion-base` | 200ms | Size changes: expand/collapse, panel open/close |
-| `--motion-enter` | 250ms | Heavy-overlay (dialog) enter |
-| `--motion-exit` | 150ms | Heavy-overlay (dialog) exit |
-| `--motion-ease-out` | `cubic-bezier(0.16, 1, 0.3, 1)` | Enter / expand |
-| `--motion-ease-in` | `cubic-bezier(0.4, 0, 1, 1)` | Exit |
-| `--motion-ease-move` | `cubic-bezier(0.4, 0, 0.2, 1)` | Position/size interpolation |
+| Token | Value | Use |
+| -------------------- | ------------------------------- | ---------------------------------------------------------------------------------- |
+| `--motion-instant` | 80ms | Instant hover feedback; light-overlay exit |
+| `--motion-fast` | 150ms | Color/opacity state changes (`transition-colors` = this tier); light-overlay enter |
+| `--motion-base` | 200ms | Size changes: expand/collapse, panel open/close |
+| `--motion-enter` | 250ms | Heavy-overlay (dialog) enter |
+| `--motion-exit` | 150ms | Heavy-overlay (dialog) exit |
+| `--motion-ease-out` | `cubic-bezier(0.16, 1, 0.3, 1)` | Enter / expand |
+| `--motion-ease-in` | `cubic-bezier(0.4, 0, 1, 1)` | Exit |
+| `--motion-ease-move` | `cubic-bezier(0.4, 0, 0.2, 1)` | Position/size interpolation |
**Semantic loop-cycle exception:** `--motion-spinner-cycle` = `1000ms` is the
full-turn duration for functional loading spinners. It is not a sixth interaction
@@ -644,20 +639,20 @@ long duration to leak into any other hover or transition.
#### Semantics → motion prototypes (one semantic, one motion, app-wide)
-| Semantic | Spec | Reference implementation |
-|---|---|---|
-| Light overlay (menu / popover / tooltip) | In: `animate-float-in` (opacity + scale 0.97→1, fast/ease-out; pure-opacity tooltips use `animate-fade-in`). Out: `animate-float-out` (opacity only, instant/ease-in). **Exit is always faster than enter, and never scales** (a scaling exit reads as "sucked away" — paper fades in place) | `components/ui/dropdown-menu.tsx` |
-| Heavy overlay (modal / confirm) | In: 250ms fade + scale 0.95→1; out: 150ms | `components/ui/confirm-dialog.tsx` |
-| Expand / collapse | base/ease-move, grid `0fr↔1fr` height + opacity | `features/cc-agent/sidebar/SectionCollapse.tsx` |
-| List reorder | FLIP, transform translation | `components/ui/toast/ToastContainer.tsx` |
-| Press | `active:scale-[0.98]` (all interactive pills/buttons) | ConfirmDialog buttons |
-| Done | **the app's only sanctioned overshoot** (`status-done-pop`) | `globals.css` |
-| Running | Opacity breathing; must sit on an HTML wrapper (`docs/dev-rules/engineering-conventions.md` §7) | `session-breathing` |
-| Loading spinner | `animate-spinner` (`--motion-spinner-cycle`, linear full turn); HTML wrapper only, static under reduced motion | `tailwind.config.ts` |
-| Hover / state colors | `transition-colors`, ≤ fast (150ms) | App-wide status quo |
-| Container transform (chip grows into panel) | 220ms — see the dedicated category below (explicit exception) | Composer permission/model selectors |
-
-*Reference-implementation paths in this table are relative to `apps/desktop/src/renderer/`.*
+| Semantic | Spec | Reference implementation |
+| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
+| Light overlay (menu / popover / tooltip) | In: `animate-float-in` (opacity + scale 0.97→1, fast/ease-out; pure-opacity tooltips use `animate-fade-in`). Out: `animate-float-out` (opacity only, instant/ease-in). **Exit is always faster than enter, and never scales** (a scaling exit reads as "sucked away" — paper fades in place) | `components/ui/dropdown-menu.tsx` |
+| Heavy overlay (modal / confirm) | In: 250ms fade + scale 0.95→1; out: 150ms | `components/ui/confirm-dialog.tsx` |
+| Expand / collapse | base/ease-move, grid `0fr↔1fr` height + opacity | `features/cc-agent/sidebar/SectionCollapse.tsx` |
+| List reorder | FLIP, transform translation | `components/ui/toast/ToastContainer.tsx` |
+| Press | `active:scale-[0.98]` (all interactive pills/buttons) | ConfirmDialog buttons |
+| Done | **the app's only sanctioned overshoot** (`status-done-pop`) | `globals.css` |
+| Running | Opacity breathing; must sit on an HTML wrapper (`docs/dev-rules/engineering-conventions.md` §7) | `session-breathing` |
+| Loading spinner | `animate-spinner` (`--motion-spinner-cycle`, linear full turn); HTML wrapper only, static under reduced motion | `tailwind.config.ts` |
+| Hover / state colors | `transition-colors`, ≤ fast (150ms) | App-wide status quo |
+| Container transform (chip grows into panel) | 220ms — see the dedicated category below (explicit exception) | Composer permission/model selectors |
+
+_Reference-implementation paths in this table are relative to `apps/desktop/src/renderer/`._
#### Red lines (performance & restraint)
@@ -666,7 +661,7 @@ long duration to leak into any other hover or transition.
- Every new `@keyframes` / `animate-*` class must be registered in the `prefers-reduced-motion` whitelist in `globals.css` (the global `* { transition: none }` does not catch keyframes).
- Real-time direct-manipulation interactions (resizer drag, drag-follow) get **no easing** — following the hand IS the feedback.
- Forbidden: pointless displacement, bouncing, parallax, looping decoration, `transition-all`, and typewriter per-character animation on streamed text (streaming already is the motion). Interactions stay fast and direct. (Per-**word** opacity fade-in on streamed text is **not** the typewriter — see the sanctioned stream-word-fade class below: the word is fully laid out and only its opacity ramps; ruled distinct on 2026-08-07.)
-- **Cadenced running shimmer (2026-08-07)**: the running status bar's breathing (`status-bar-shimmer`) is **event-driven, not an infinite loop** — one 1.5s dip (1 → 0.45 → 1, `steps(18)`) plays per real sign of progress (status text change / token count advance; re-triggered via keyed remount in `RunningStatusBar`, back-to-back plays merge through an animation-end pending flag). Silence (long thinking, tool wait) holds steady full opacity. Semantics: *breathing = producing*, not *heartbeat = alive*. New loading/working indicators should prefer this cadenced pattern over a new infinite loop.
+- **Cadenced running shimmer (2026-08-07)**: the running status bar's breathing (`status-bar-shimmer`) is **event-driven, not an infinite loop** — one 1.5s dip (1 → 0.45 → 1, `steps(18)`) plays per real sign of progress (status text change / token count advance; re-triggered via keyed remount in `RunningStatusBar`, back-to-back plays merge through an animation-end pending flag). Silence (long thinking, tool wait) holds steady full opacity. Semantics: _breathing = producing_, not _heartbeat = alive_. New loading/working indicators should prefer this cadenced pattern over a new infinite loop.
#### Exception category: container transform (chip lifts off and grows)
@@ -743,12 +738,11 @@ long duration to leak into any other hover or transition.
两端都必须**按来源 + label 形态分三档**(判定口径同源:桌面
`shouldRenderCodeReferenceLabel`、移动 `chatPathLabelReadsAsFileReference`):
- | 来源 | label | 点亮后 |
- |---|---|---|
- | 正文裸写的路径 | (无独立 label) | 正文字体 + 下划线,**不套等宽** |
- | 作者手写 `[README.md](path)` | 读起来是文件引用 | 等宽 chip + 下划线 |
- | 作者手写 `[看这份规则](path)` | 散文 | 正文字体 + 下划线 |
-
+ | 来源 | label | 点亮后 |
+ | ----------------------------- | ---------------- | ------------------------------ |
+ | 正文裸写的路径 | (无独立 label) | 正文字体 + 下划线,**不套等宽** |
+ | 作者手写 `[README.md](path)` | 读起来是文件引用 | 等宽 chip + 下划线 |
+ | 作者手写 `[看这份规则](path)` | 散文 | 正文字体 + 下划线 |
- 桌面端:`remarkLocalPathLinks` 给切出的 link 节点打 `data-bare-path` 标记
(走 mdast `data.hProperties`),`MarkdownTargetLink` 见到它就跳过
`shouldRenderCodeReferenceLabel`、直接走 `ResolvedLocalLink`。
@@ -757,6 +751,7 @@ long duration to leak into any other hover or transition.
再过一遍 label 形态判定。**不得无条件去掉 `markdownInlineCode`** —— 那会把
作者手写的文件名链接一起降级(2026-07-31 PR #1144 review 实捉)。
- 作者手写的文件名链接保留 chip 是刻意的:那是作者的排版意图,与桌面一致。
+
2. **外链与本地文件不做外观区分**,只表达「可点」;去哪由文本自身可读性承担(斜杠路径
vs `https://` 前缀)。
3. **聊天正文不使用 `--msg-link`。** 该 token 是主题契约(10 个内置主题各自定义,
@@ -789,12 +784,12 @@ long duration to leak into any other hover or transition.
> 时全部不点亮,那个错更醒目也更常见;要为它收紧就得在词法层区分正则与路径,又回到
> 规则 4 「靠形状排除必然连真的一起砍」的老问题。两端都有用例把它钉成**显式已知项**。
- | 形状 | 例 | `unknown`(链路断)时 |
- |---|---|---|
- | 绝对路径(**含无扩展名**) | `/abs/a.png`、`/etc/hosts`、`C:\Windows\System32`、`file:///a.md` | **乐观点亮**(不因断链把整条消息的 chip 全灭) |
- | 尾斜杠目录 / 分隔符+扩展名 | `src/x/`、`src/App.tsx` | 同上 |
- | 无分隔符裸名 | `package.json`、`array.map` | 必须远端明确回 `file` / `directory` |
- | 有分隔符但无扩展名 | `src/components`、`and/or` | 同上 |
+ | 形状 | 例 | `unknown`(链路断)时 |
+ | -------------------------- | ----------------------------------------------------------------- | -------------------------------------------- |
+ | 绝对路径(**含无扩展名**) | `/abs/a.png`、`/etc/hosts`、`C:\Windows\System32`、`file:///a.md` | **乐观点亮**(不因断链把整条消息的 chip 全灭) |
+ | 尾斜杠目录 / 分隔符+扩展名 | `src/x/`、`src/App.tsx` | 同上 |
+ | 无分隔符裸名 | `package.json`、`array.map` | 必须远端明确回 `file` / `directory` |
+ | 有分隔符但无扩展名 | `src/components`、`and/or` | 同上 |
> ⚠️ **「带分隔符」本身不足以乐观点亮**,必须**同时带扩展名**。`src/components` 与
> `and/or` / `n/a` / `read/write` / `text/plain` 词法**完全同形**,词法层分不开;只按
@@ -814,11 +809,11 @@ PR #1144 的第 8、11、12、14 轮 review 各捉到这条规格的一个缺口
字符 / 空格中段 / `( ) # %` 等未支持字符 + 行号后缀)。**逐个补字符类注定一轮补一个**,
故收敛成一条判据(两端 `startsMidPathToken` + `endsMidPathToken`,逐字同形):
-| 侧 | 判据 |
-|---|---|
-| 左 | 命中点前是同一 run 内的字符时,只有**白名单**字符可以紧邻路径:开括号 / 引号 / 冒号 / 列表分隔符 / `>`。其余一律拒绝 |
-| 左 | 命中点前是空白时,看空白前那个 run:含分隔符**且不以扩展名收尾** → 拒绝(只跨空格/制表符,不跨换行) |
-| 右 | 命中之后紧跟 token 字符 → 拒绝;`.` 与 `:` 本身放过(句末标点),但**跳过整串 `.`/`:` 之后仍跟 token 字符**时同样拒绝 |
+| 侧 | 判据 |
+| --- | ------------------------------------------------------------------------------------------------------------------ |
+| 左 | 命中点前是同一 run 内的字符时,只有**白名单**字符可以紧邻路径:开括号 / 引号 / 冒号 / 列表分隔符 / `>`。其余一律拒绝 |
+| 左 | 命中点前是空白时,看空白前那个 run:含分隔符**且不以扩展名收尾** → 拒绝(只跨空格/制表符,不跨换行) |
+| 右 | 命中之后紧跟 token 字符 → 拒绝;`.` 与 `:` 本身放过(句末标点),但**跳过整串 `.`/`:` 之后仍跟 token 字符**时同样拒绝 |
关键收益:`( ) # % [ ] =` 之类**不需要枚举** —— 白名单之外一律拒绝,以后出现别的未支持
字符自动覆盖,不必再来一轮。
@@ -837,6 +832,7 @@ PR #1144 的第 8、11、12、14 轮 review 各捉到这条规格的一个缺口
> 之后没有 token 字符。
两处刻意的例外,改动它们会让真实用法退化,均有用例钉住:
+
- **`.` 与 `:` 不进右边界字符类**:句末英文句点(`见 src/a.ts.`)与句末冒号
(`见 src/a.ts:`)是最常见的紧随字符;把 `.` 加进去会让整条失配(SEG 含 `.`,回溯救
不回来)。
@@ -849,10 +845,10 @@ PR #1144 的第 8、11、12、14 轮 review 各捉到这条规格的一个缺口
#### 落点
-| 端 | 位置 |
-|---|---|
-| 桌面 | `MarkdownRenderer.tsx` 的 `MARKDOWN_LINK_CLASS` / `FileTargetChip`;`UserMessage.tsx` + `UserMessageUrlLink.tsx`;候选判定在 `lib/markdownTarget.ts` |
-| 移动 | `MessageRenderer.tsx` 的 `markdownLink` / `markdownPathChip` / `sessionLinkChipText` 与 `ChatPathChipSpan` 的点亮门槛;候选判定在 `session/chatPathCandidate.ts` |
+| 端 | 位置 |
+| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 桌面 | `MarkdownRenderer.tsx` 的 `MARKDOWN_LINK_CLASS` / `FileTargetChip`;`UserMessage.tsx` + `UserMessageUrlLink.tsx`;候选判定在 `lib/markdownTarget.ts` |
+| 移动 | `MessageRenderer.tsx` 的 `markdownLink` / `markdownPathChip` / `sessionLinkChipText` 与 `ChatPathChipSpan` 的点亮门槛;候选判定在 `session/chatPathCandidate.ts` |
| 文件阅读器 | `session/selectableMarkdownHtml.ts`。**该面只有 http(s) 真的可点**,故规则在这里的落地是反过来的:只有 `a` 带下划线,`.xdt-image-chip` / `.xdt-session-chip` 一律不带下划线也不带 `cursor: pointer`,非 http(s) 目标(本地路径 / 会话深链 / mailto)不出 `<a>` |
> **文件阅读器为什么反过来**:`MarkdownFileReader.interceptNavigation` 只把 http(s) 交给
@@ -876,18 +872,18 @@ PR #1144 的两轮 review 各捉到一个**同族**缺陷:「有下划线却点
> 凭记忆写的,漏掉了「远程会话 unknown 乐观点亮」与「引用 chip 无下划线」两条,下一轮
> review 又各捉到一个。
-| 面 | 元素 | 可点? | 下划线 |
-|---|---|---|---|
-| 桌面聊天正文 | 外链 / anchor / 本地图片 URL | ✅ | ✅ `MARKDOWN_LINK_CLASS` |
-| 桌面聊天正文 | 已解析本地文件(chip / 散文 label) | ✅ | ✅ |
-| 桌面聊天正文 | 未解析路径、行内 code | ❌ | ❌ |
-| 桌面聊天正文 | **远程**会话里 stat 回 `unknown` 的引用 | 仅非歧义形状 | 由 `isAmbiguousPathShape` 门槛裁决 |
-| 桌面聊天正文 / 用户气泡 | 会话 / 项目深链 chip(`InlineReferenceChip`) | 取决于是否注入 onClick / onContextMenu | **与 `interactive` 同源** |
-| 桌面用户气泡 | URL / 图片路径 | ✅ | ✅(改前只有 hover 下划线) |
-| 手机聊天正文 | 外链 / 图片 chip / 会话 chip | 取决于 handler 是否注入 | **与 handler 同源**(`clickableInlineStyle`) |
-| 手机聊天正文 | 路径 chip | 取决于远端 verdict | 由 `ChatPathChipSpan.lit` 单点裁决 |
-| 手机文件阅读器 | http(s) | ✅ | ✅ |
-| 手机文件阅读器 | 会话 chip / 图片 chip / 本地路径 / mailto | ❌(无 bridge、只放行 http(s)) | ❌ |
+| 面 | 元素 | 可点? | 下划线 |
+| ----------------------- | ------------------------------------------- | -------------------------------------- | ------------------------------------------- |
+| 桌面聊天正文 | 外链 / anchor / 本地图片 URL | ✅ | ✅ `MARKDOWN_LINK_CLASS` |
+| 桌面聊天正文 | 已解析本地文件(chip / 散文 label) | ✅ | ✅ |
+| 桌面聊天正文 | 未解析路径、行内 code | ❌ | ❌ |
+| 桌面聊天正文 | **远程**会话里 stat 回 `unknown` 的引用 | 仅非歧义形状 | 由 `isAmbiguousPathShape` 门槛裁决 |
+| 桌面聊天正文 / 用户气泡 | 会话 / 项目深链 chip(`InlineReferenceChip`) | 取决于是否注入 onClick / onContextMenu | **与 `interactive` 同源** |
+| 桌面用户气泡 | URL / 图片路径 | ✅ | ✅(改前只有 hover 下划线) |
+| 手机聊天正文 | 外链 / 图片 chip / 会话 chip | 取决于 handler 是否注入 | **与 handler 同源**(`clickableInlineStyle`) |
+| 手机聊天正文 | 路径 chip | 取决于远端 verdict | 由 `ChatPathChipSpan.lit` 单点裁决 |
+| 手机文件阅读器 | http(s) | ✅ | ✅ |
+| 手机文件阅读器 | 会话 chip / 图片 chip / 本地路径 / mailto | ❌(无 bridge、只放行 http(s)) | ❌ |
**颜色也归这条不变量管**:可点态只多一条下划线,所以链接**不得写死颜色**,必须继承所在
上下文 —— 表头(`markdownTableHeaderCell` 用 `textSecondary`)、引用块等非正文色上下文里
@@ -913,9 +909,9 @@ PR #1144 的两轮 review 各捉到一个**同族**缺陷:「有下划线却点
peek 有值 → 调用方跳过重验 → 链路恢复后也不再问。两端一律「确定态无 TTL 缓存 + `unknown`
落 30s 负缓存且不进 peek」:
-| 端 | 确定态 | `unknown` |
-|---|---|---|
-| 桌面 `lib/remoteFileOpen.ts` | `verdictCache`,无 TTL | `unknownUntil`,30s,**不进 `peek`** |
+| 端 | 确定态 | `unknown` |
+| ----------------------------------- | --------------------- | ---------------------------------- |
+| 桌面 `lib/remoteFileOpen.ts` | `verdictCache`,无 TTL | `unknownUntil`,30s,**不进 `peek`** |
| 移动 `session/remotePathVerdict.ts` | `verdictCache`,无 TTL | `unknownUntil`,30s,**不进 `peek`** |
代价是断链期间乐观点亮的引用每次重挂会先画一帧纯文本。刻意取舍:让「peek 有值」严格等价于
@@ -938,7 +934,7 @@ peek 有值 → 调用方跳过重验 → 链路恢复后也不再问。两端
>
> **重验结论必须无条件覆盖旧结论,不许按 verdict 早返回。** 有了 TTL 到期重验之后,凭空多出
> 一条状态迁移:「先按 `unknown` 乐观点亮 → 链路恢复后确认 `nonfile`」。`if (verdict ===
-> 'nonfile') return;` 这种早返回写法漏掉它,不存在的路径会一直带着下划线可点。桌面已把判据
+'nonfile') return;` 这种早返回写法漏掉它,不存在的路径会一直带着下划线可点。桌面已把判据
> 抽成纯函数 `decideRemoteLit(verdict, href, originalHref)` —— **每个 verdict 都有返回值,
> 没有「什么都不做」这个分支**,调用方拿结果无条件 `setAsyncResolved`,于是「忘了撤销」在结构
> 上不可表达;sync / async 两条分支共用它,判据也随之单点化。
@@ -952,11 +948,11 @@ peek 有值 → 调用方跳过重验 → 链路恢复后也不再问。两端
> 第 8、9、10 三轮 review 各捉到一条缺口,根因是同一个:**组件自己存了一份结论,而真值在一个
> 可变的模块缓存里,组件只在自己的依赖变化时去看一眼**。于是每出现一条新的状态迁移就漏一条:
>
-> | 轮次 | 漏掉的那条边 |
-> |---|---|
-> | 8 | TTL 到期没有通道通知(长挂载视图永远停在纯文本) |
-> | 9 | 派生值没跟着新结论被覆盖(确认 `nonfile` 后仍点亮) |
-> | 10 | **另一个挂载点**写入的确定态传不过来(同一路径出现在多处时) |
+> | 轮次 | 漏掉的那条边 |
+> | ---- | ---------------------------------------------------------- |
+> | 8 | TTL 到期没有通道通知(长挂载视图永远停在纯文本) |
+> | 9 | 派生值没跟着新结论被覆盖(确认 `nonfile` 后仍点亮) |
+> | 10 | **另一个挂载点**写入的确定态传不过来(同一路径出现在多处时) |
>
> 逐条补边补不完 —— 每补一条,下一条新迁移又会漏。故按硬止损线做结构收敛:
>
@@ -990,13 +986,13 @@ peek 有值 → 调用方跳过重验 → 链路恢复后也不再问。两端
所有入口都调它,**不得按来源硬写 `true` / `false`**(移动端曾对链接入口恒 `false`,与桌面
不对称,review 实捉)。
-| 候选来源 | 桌面入口 | 移动入口 | 走门槛? |
-|---|---|---|---|
-| 行内 code | `classifyInlineCodeTarget` | `classifyInlineCodePathCandidate` | ✅ |
-| 显式 markdown 链接 | `classifyMarkdownLinkTarget` | `classifyChatPathLinkTarget` | ✅ |
-| 正文裸写路径 | `remarkLocalPathLinks` → 同上 | `matchBareFilePathLink` → 同上 | ✅(词法强制带扩展名 → 恒非歧义,实际无影响) |
-| 尾斜杠目录 | 回看 `originalHref` → 非歧义 | 同左 | ✅ |
-| `file://` 绝对路径 | 单列为非歧义 | 同左 | ✅ |
+| 候选来源 | 桌面入口 | 移动入口 | 走门槛? |
+| ------------------ | ----------------------------- | --------------------------------- | ------------------------------------------ |
+| 行内 code | `classifyInlineCodeTarget` | `classifyInlineCodePathCandidate` | ✅ |
+| 显式 markdown 链接 | `classifyMarkdownLinkTarget` | `classifyChatPathLinkTarget` | ✅ |
+| 正文裸写路径 | `remarkLocalPathLinks` → 同上 | `matchBareFilePathLink` → 同上 | ✅(词法强制带扩展名 → 恒非歧义,实际无影响) |
+| 尾斜杠目录 | 回看 `originalHref` → 非歧义 | 同左 | ✅ |
+| `file://` 绝对路径 | 单列为非歧义 | 同左 | ✅ |
> `file://` 必须在判据里**单列**:`looksLikeFilePath` 会被 `URL_SCHEME_RE` 挡掉而回 `false`
> (那条排除是为「别把 `https://` 当本地路径」服务的),照抄它会把最明确的形态判成最可疑的。
@@ -1051,16 +1047,16 @@ peek 有值 → 调用方跳过重验 → 链路恢复后也不再问。两端
### 15.1 Palette (extracted from Figma text nodes)
-| Semantic | Light | Dark |
-|---|---|---|
-| Brand red | `#DF0C27` | `#DF0C27` |
-| Deep brand red (hover/pressed) | `#A61629` | `#A61629` |
-| Background | `#F2F2ED` (warm ivory — 2026-08 revision, see 15.16) | `#181818` (pure neutral — 2026-08 revision) |
-| Card / input | `#FDFDF8` | `#1F1F1F` |
-| Border | `#E4E4DF` (desktop, warm; mobile light keeps its own exception `#C6C9CE` pending the mobile follow-up — see 15.13) | `#313131` |
-| Secondary info | `#888883` (2026-08 ruling: warmed + raised to ≥3.0, supersedes the 2026-07-20 `#8C8E94`; history in 15.5) | `#6F6F6F` |
-| Body text | `#1A1A1A` (near-black neutral; emphasis tier `#0C0C0C`) | `#D4D4D4` |
-| Pure white | `#FFFFFF` | `#FFFFFF` |
+| Semantic | Light | Dark |
+| ------------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------- |
+| Brand red | `#DF0C27` | `#DF0C27` |
+| Deep brand red (hover/pressed) | `#A61629` | `#A61629` |
+| Background | `#F2F2ED` (warm ivory — 2026-08 revision, see 15.16) | `#181818` (pure neutral — 2026-08 revision) |
+| Card / input | `#FDFDF8` | `#1F1F1F` |
+| Border | `#E4E4DF` (desktop, warm; mobile light keeps its own exception `#C6C9CE` pending the mobile follow-up — see 15.13) | `#313131` |
+| Secondary info | `#888883` (2026-08 ruling: warmed + raised to ≥3.0, supersedes the 2026-07-20 `#8C8E94`; history in 15.5) | `#6F6F6F` |
+| Body text | `#1A1A1A` (near-black neutral; emphasis tier `#0C0C0C`) | `#D4D4D4` |
+| Pure white | `#FFFFFF` | `#FFFFFF` |
### 15.2 Red-Boundary Test Maps(品牌红边界)
@@ -1165,15 +1161,15 @@ The splash wordmark is a separate asset pair (`assets/splash/wordmark.png`, whit
- Do not alias the caret to `--focus-ring` even though the values match: the semantics differ, and `--caret-accent` must stay independently adjustable.
- Mobile parity: `inputCaret` in `apps/mobile/src/theme/tokens.ts` carries the same value in both modes, consumed via TextInput `cursorColor` / `selectionColor`; `themeTokens.test.ts` locks it.
-*(Finalized 2026-07-18 after two same-day revisions — earlier "brand-red caret" wording anywhere is void; see design-decision-log.md.)*
+_(Finalized 2026-07-18 after two same-day revisions — earlier "brand-red caret" wording anywhere is void; see design-decision-log.md.)_
-### 15.12 Vibrancy (frosted glass) System (macOS; finalized 2026-07-18)
+### 15.12 Vibrancy (frosted glass) System (macOS / Windows; finalized 2026-07-18, Windows resize backing updated 2026-08-21)
-- **The only translucent-surface token**: `surface-translucent-sidebar` — CINDY light `rgba(255, 255, 255, 0.85)` / dark `rgba(18, 15, 15, 0.75)` (defaults to opaque `var(--surface)` in the default theme; zero effect on non-CINDY themes). Consumer: the left sidebar (`aside.bg-sidebar`); any future translucent surface **reuses this token by default** — no new ad-hoc rgba. The splash root is opaque `--surface` (it must fully cover the mounted UI until loading completes — ruling 2026-07-19).
+- **The only translucent-surface token**: `surface-translucent-sidebar` — CINDY light `rgba(238, 238, 233, 0.85)` / dark `rgba(5, 5, 5, 0.85)` (defaults to opaque `var(--surface)` in the default theme; zero effect on non-CINDY themes). Consumer: the left sidebar (`aside.bg-sidebar`); any future translucent surface **reuses this token by default** — no new ad-hoc rgba. The splash root is opaque `--surface` (it must fully cover the mounted UI until loading completes — ruling 2026-07-19).
- **Wallpaper-through triple pipeline — missing any one yields dead black** (verified by on-device A/B, 2026-07-18):
- 1. Set `backgroundColor: '#00000000'` + vibrancy **at window creation** (`bootstrap-electron.ts` / `vibrancyConfig.ts`); changing alpha via `setBackgroundColor` at runtime is unreliable.
+ 1. Set the vibrancy backing **at window creation** (`bootstrap-electron.ts` / `vibrancyConfig.ts`); changing alpha via `setBackgroundColor` at runtime is unreliable. macOS uses `backgroundColor: '#00000000'`. Windows Acrylic uses the current `surface-translucent-sidebar` RGBA as its steady-state BrowserWindow backing, and the ordinary sidebar CSS is transparent on that exact platform/material combination to avoid double tinting. The material remains stable during live resize; Renderer layout must follow the changing window through CSS rather than switching the native backdrop per gesture.
2. Under CINDY themes the **root container steps aside**: globals.css sets `.h-screen.bg-content-area` (and the splash backing layer while present) to transparent — otherwise the opaque root blocks everything.
- 3. **No CSS `backdrop-filter`** — it renders the transparent window backing as a black box; wallpaper blur is entirely the native vibrancy material's job, CSS only lays the translucent tint.
+ 3. **No CSS `backdrop-filter` on the ordinary sidebar** — it renders the transparent window backing as a black box; wallpaper blur is entirely the native vibrancy material's job. macOS CSS lays the translucent tint; Windows Acrylic gets that same tint from the creation-time native backing. The sidebar peek drawer is the intentional exception because it covers application content rather than wallpaper.
- Material selected via the `XDT_VIBRANCY_MATERIAL` env knob, **code default `hud`** (user-tested). Windows: Win11+ uses `backgroundMaterial` (default `acrylic`, `XDT_BACKDROP_MATERIAL` knob — not yet device-verified); Win10 / non-CINDY fall back to opaque `--surface`.
- **No gradient overlays on translucent surfaces** — the light-red gradient layer was confirmed absent from the design and removed wholesale (2026-07-18); the splash gradient glow is likewise unimplemented (backlog, awaiting a ruling).
- The `surface-translucent-sidebar` alpha is the **only open look-and-feel knob** in the theme-frozen zone; adjusting it requires synchronized changes in three places (`cindy-light.ts` / `cindy-dark.ts` / `cindyDecisionData.ts`) with the themes suite green.
@@ -1201,19 +1197,19 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
- **`colors.border` light is a mobile-wide exception, not a homepage-scoped token** (ruling 2026-07-21, PR #266): mobile light `border` / `borderTranslucent` = `#C6C9CE` / `rgba(198,201,206,0.62)`, deviating from desktop `#DCDFE3` — desktop borders usually sit on `#F8F8F8` cards, while mobile hairlines sit directly on the `#EDEDED` background, where `#DCDFE3` reads at a nearly invisible 1.14:1; the darkened 1.42:1 is device-verified legible. The value lives in `apps/mobile/src/theme/tokens.ts` global `lightColors.border`, applying to every mobile-light hairline; dark stays `#434343`, isomorphic with desktop. `chatCodeBorder` / `sheetActionBorder` / `sheetGrabber` keep independent values and do not follow this exception.
- Mobile-only tokens carry only mobile-specific layers or geometry:
-| Mobile token | Light | Dark | Use |
-|---|---|---|---|
-| `surfaceListRow` | `#F6F6F6` | `#312F2F` | List project/task rows |
-| `surfaceListExpanded` | `#EAEAEA` | `#2A2828` | Expanded list block |
-| `activeGlyph` | `#DF0C27` | `#A61629` | Leading active glyph in lists |
-| `chatCodeSurface` | `#F8F8F8` | `#353333` | Chat / task code card |
-| `chatCodeBorder` | `#DCDFE3` | `#3C3C3C` | Chat / task code card border |
-| `inputCaret` | `#417CDD` | `#417CDD` | All input carets |
-| `sheetSurface` | `rgba(248,248,248,0.95)` | `rgba(59,59,59,0.95)` | Bottom-sheet root |
-| `sheetActionSurface` | `#F6F6F6` | `rgba(59,59,59,0.5)` | Sheet action group / row |
-| `sheetActionBorder` | `#DCDFE3` | `#505050` | Sheet action group / row border |
-| `sheetActionText` | `#3C3F43` | `#C1C1C1` | Sheet action row label |
-| `sheetGrabber` | `#DCDFE3` | `#6F6F6F` | Sheet / composer grabber |
+| Mobile token | Light | Dark | Use |
+| --------------------- | ------------------------ | --------------------- | ------------------------------- |
+| `surfaceListRow` | `#F6F6F6` | `#312F2F` | List project/task rows |
+| `surfaceListExpanded` | `#EAEAEA` | `#2A2828` | Expanded list block |
+| `activeGlyph` | `#DF0C27` | `#A61629` | Leading active glyph in lists |
+| `chatCodeSurface` | `#F8F8F8` | `#353333` | Chat / task code card |
+| `chatCodeBorder` | `#DCDFE3` | `#3C3C3C` | Chat / task code card border |
+| `inputCaret` | `#417CDD` | `#417CDD` | All input carets |
+| `sheetSurface` | `rgba(248,248,248,0.95)` | `rgba(59,59,59,0.95)` | Bottom-sheet root |
+| `sheetActionSurface` | `#F6F6F6` | `rgba(59,59,59,0.5)` | Sheet action group / row |
+| `sheetActionBorder` | `#DCDFE3` | `#505050` | Sheet action group / row border |
+| `sheetActionText` | `#3C3F43` | `#C1C1C1` | Sheet action row label |
+| `sheetGrabber` | `#DCDFE3` | `#6F6F6F` | Sheet / composer grabber |
#### Iconography
@@ -1281,33 +1277,34 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
- **品牌红 `#DF0C27` 只用于区域徽标(旧称 Global pill,见 §16.3)与字标红元素等品牌 accent,跨模式不变**;**禁止作页面背景**(wave4 改判,见 `token-decision-table §3` 对 `#df0c27` 的语义判定),不渗入面板内部(呼应 §15.10 红色边界)。画布底走 `--login-bg-base`(亮 `#EDEDED` / 深 `#1F1F1E`),红只经 `--login-brand-accent` 消费。错误红 `#D91F37` 同样跨模式不变(语义豁免,呼应 §10 豁免族)。
- **`--login-*` 调色板双态目标值** —— token 已注册于 `apps/desktop/src/renderer/themes/colors.ts`(dark 槽位当前为 light 占位值)。下表为深色实现的目标规格,经 Figma 组件库 Dark symbol 逐个核验;实现 PR 须将 dark 槽位更新为本表 dark 列的值:
-| token | light | dark | 核验源 |
-|---|---|---|---|
-| `--login-panel-bg` | `#FBFBFB` | `#312F2F` | callback-card dark(as-built)|
-| `--login-panel-border` | `#D4D4D4` | `#434343` | callback-card dark |
-| `--login-control-bg`(输入框底) | `#EEEEEE` | `#2C2A2A` | figma `Dark_normal` 输入 symbol |
-| `--login-action-control-bg`(方式行 / 返回钮底) | `#EEEEEE` | `#2A2828` | figma 549:850 / 549:897(暗色与输入框底分化,组件库更新 2026-07-23) |
-| `--login-back-border`(返回钮描边) | `#FFFFFF` | `#434343` | figma 549:897 |
-| `--login-control-border` | `#D4D4D4` | `#434343` | figma `Dark_normal` |
-| `--login-control-border-active`(focus / filled) | `#2A2828` | `#EEEEEE` | figma `Dark_highlight` |
-| `--login-control-text`(输入填充字,Bold) | `#252222` | `#EEEEEE` | figma Dark 填充 / error 态 |
-| `--login-control-placeholder`(空态字) | `#D4D4D4` | `#6F6F6F` | figma Dark 空态 |
-| `--login-title-text` | `#252222` | `#D4D4D4` | callback-title dark |
-| `--login-secondary-text`(副标题 / 倒计时) | `#6F6F6F` | `#6F6F6F` | 两模式同值 |
-| `--login-primary-button-bg` | `#2A2828` | `#EEEEEE` | figma `white_button` / callback-cta dark |
-| `--login-primary-button-border` | `#434343` | `#FFFFFF` | 同上 |
-| `--login-primary-button-text`(Bold) | `#D4D4D4` | `#2A2828` | 同上 |
-| `--login-link-text`(重发链接) | `#2A2828` | `#EEEEEE` | figma `dark_重新发送` symbol |
-| `--login-link-hover` | `#4A4848` | `#A8A8A8` | 推导值(无独立 dark hover symbol) |
-| `--login-link-pressed` | `#1A1818` | `#C0BEBE` | 推导值 |
-| `--login-disabled-button-overlay` | `rgba(255,255,255,0.7)` | 同 light | figma `white_button` Disable:disabled 两模式同构(见 §16.5) |
-| `--login-splash-progress-track` / `--login-splash-progress-fill` | `#D9D9D9` / `#252222` | `#434343` / `#D4D4D4` | figma Dark symbol 核验 |
-| `--login-loading-ring-track`(loading 环轨道) | `rgba(42,40,40,0.18)` | `rgba(212,212,212,0.18)` | 18% 半透明环轨二态;登录页 LoginLoadingRing 与 Splash 转圈环共用(Splash 侧自暗色实现 PR 起由字面 rgba 收敛至本 token) |
-| `--login-error-fg` | `#D91F37` | `#D91F37` | 语义豁免不变 |
-| `--login-brand-accent` / `--login-brand-accent-pressed` | `#DF0C27` / `#A61629` | 同 light | 品牌红不变 |
-| `--login-bg-base`(画布底) | `#EDEDED` | `#1F1F1E` | figma 532:585 暗色帧实测;两模式纯平定稿——暗色帧的双红晕层(532:588/589)曾按 1:1 几何落地,2026-07-24 实机走查拍板去除(亮色撤渐变=PR#104 拍板,两条决策相互独立) |
-
- 余下 token(`-control-border-disabled` / `-inverted-button-border` / `-callback-*` 等)的**亮色**值与 callback 族**双态**值见 `token-decision-table §3`、`figma-component-spec §1.1`(注意:这两份外部 spec 只覆盖亮色 + callback 族 dark,**登录主皮 dark 值以本表为权威**,原※推导值已经 Figma 组件库核验确认,本表为目标规格);深色反相机制与 3 处组件改动见 §16.5。
+| token | light | dark | 核验源 |
+| ---------------------------------------------------------------- | ----------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `--login-panel-bg` | `#FBFBFB` | `#312F2F` | callback-card dark(as-built) |
+| `--login-panel-border` | `#D4D4D4` | `#434343` | callback-card dark |
+| `--login-control-bg`(输入框底) | `#EEEEEE` | `#2C2A2A` | figma `Dark_normal` 输入 symbol |
+| `--login-action-control-bg`(方式行 / 返回钮底) | `#EEEEEE` | `#2A2828` | figma 549:850 / 549:897(暗色与输入框底分化,组件库更新 2026-07-23) |
+| `--login-back-border`(返回钮描边) | `#FFFFFF` | `#434343` | figma 549:897 |
+| `--login-control-border` | `#D4D4D4` | `#434343` | figma `Dark_normal` |
+| `--login-control-border-active`(focus / filled) | `#2A2828` | `#EEEEEE` | figma `Dark_highlight` |
+| `--login-control-text`(输入填充字,Bold) | `#252222` | `#EEEEEE` | figma Dark 填充 / error 态 |
+| `--login-control-placeholder`(空态字) | `#D4D4D4` | `#6F6F6F` | figma Dark 空态 |
+| `--login-title-text` | `#252222` | `#D4D4D4` | callback-title dark |
+| `--login-secondary-text`(副标题 / 倒计时) | `#6F6F6F` | `#6F6F6F` | 两模式同值 |
+| `--login-primary-button-bg` | `#2A2828` | `#EEEEEE` | figma `white_button` / callback-cta dark |
+| `--login-primary-button-border` | `#434343` | `#FFFFFF` | 同上 |
+| `--login-primary-button-text`(Bold) | `#D4D4D4` | `#2A2828` | 同上 |
+| `--login-link-text`(重发链接) | `#2A2828` | `#EEEEEE` | figma `dark_重新发送` symbol |
+| `--login-link-hover` | `#4A4848` | `#A8A8A8` | 推导值(无独立 dark hover symbol) |
+| `--login-link-pressed` | `#1A1818` | `#C0BEBE` | 推导值 |
+| `--login-disabled-button-overlay` | `rgba(255,255,255,0.7)` | 同 light | figma `white_button` Disable:disabled 两模式同构(见 §16.5) |
+| `--login-splash-progress-track` / `--login-splash-progress-fill` | `#D9D9D9` / `#252222` | `#434343` / `#D4D4D4` | figma Dark symbol 核验 |
+| `--login-loading-ring-track`(loading 环轨道) | `rgba(42,40,40,0.18)` | `rgba(212,212,212,0.18)` | 18% 半透明环轨二态;登录页 LoginLoadingRing 与 Splash 转圈环共用(Splash 侧自暗色实现 PR 起由字面 rgba 收敛至本 token) |
+| `--login-error-fg` | `#D91F37` | `#D91F37` | 语义豁免不变 |
+| `--login-brand-accent` / `--login-brand-accent-pressed` | `#DF0C27` / `#A61629` | 同 light | 品牌红不变 |
+| `--login-bg-base`(画布底) | `#EDEDED` | `#1F1F1E` | figma 532:585 暗色帧实测;两模式纯平定稿——暗色帧的双红晕层(532:588/589)曾按 1:1 几何落地,2026-07-24 实机走查拍板去除(亮色撤渐变=PR#104 拍板,两条决策相互独立) |
+
+余下 token(`-control-border-disabled` / `-inverted-button-border` / `-callback-*` 等)的**亮色**值与 callback 族**双态**值见 `token-decision-table §3`、`figma-component-spec §1.1`(注意:这两份外部 spec 只覆盖亮色 + callback 族 dark,**登录主皮 dark 值以本表为权威**,原※推导值已经 Figma 组件库核验确认,本表为目标规格);深色反相机制与 3 处组件改动见 §16.5。
+
- **社交圆钮深色 = 白圆**:与主按钮共用 `--login-primary-button-bg / -border`,深色自动反相为白圆 `#EEEEEE` + 白边,**圆内图标保持品牌色**(Google 彩 / WeChat 绿 / SSO),非反相(figma `white apple/google/wechat/SSO` symbol 核验)。
### 16.2 设计规则
@@ -1337,10 +1334,10 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
**移动端 stage 几何(2026-07-27 换品牌簇基准;2026-07-29 修正:功能区落位同步取新稿标注值)**:手机的**品牌簇**(立绘 / SLOGAN / 字标)**与功能区落位 `loginY` 一并取新稿逐字段值**——两者是同一份稿的两半,必须同源。短屏 / 长屏两档之间仍走既有线性插值体系(`loginSkinLayout.resolveLoginStage`),**不另造缩放规则**。下表为设计单位(750 设计px 基准),消费时一律 × `surface.scale`(设计单位 ≠ 物理 pt,见 §16.4「几何」条):
-| 档 | 立绘 | SLOGAN(可见图形框) | 字标(图像框) | 登录组顶 `loginY` | 溯源 |
-|---|---|---|---|---|---|
-| 短屏 `designHeight=1334` | 599×720 @(75,**60**) | 254.01×72.8 @(462.55,408.37) | 335×115 @(208,487) | **622**(新稿标注值;字标底 602 → 面板顶间距 **20** = 稿内值。组高 560 + 协议行溢出 62 → 内容底 1244,底部留白 90,比稿内 30 多 60,见下「面板 500→440 的 60 去向」) | 品牌簇 + `loginY` 同源 = 新稿 `705:915`(Log_in 组 @(35,622))+ 避脸拍板 |
-| 长屏 `designHeight=1624` | 750×902 @(0,106) | 269.66×77.29 @(444.9,**568**) | 387×132.18 @(182,669.17) | **827**(新稿标注值;字标底 801.35 → 间距 **25.65** = 稿内值。内容底 1449,底部留白 175,比稿内 115 多 60,同上) | 品牌簇 + `loginY` 同源 = 新稿 `705:799`(Log_in 组 @(35,827))+ 避脸拍板 |
+| 档 | 立绘 | SLOGAN(可见图形框) | 字标(图像框) | 登录组顶 `loginY` | 溯源 |
+| ------------------------ | -------------------- | ----------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
+| 短屏 `designHeight=1334` | 599×720 @(75,**60**) | 254.01×72.8 @(462.55,408.37) | 335×115 @(208,487) | **622**(新稿标注值;字标底 602 → 面板顶间距 **20** = 稿内值。组高 560 + 协议行溢出 62 → 内容底 1244,底部留白 90,比稿内 30 多 60,见下「面板 500→440 的 60 去向」) | 品牌簇 + `loginY` 同源 = 新稿 `705:915`(Log_in 组 @(35,622))+ 避脸拍板 |
+| 长屏 `designHeight=1624` | 750×902 @(0,106) | 269.66×77.29 @(444.9,**568**) | 387×132.18 @(182,669.17) | **827**(新稿标注值;字标底 801.35 → 间距 **25.65** = 稿内值。内容底 1449,底部留白 175,比稿内 115 多 60,同上) | 品牌簇 + `loginY` 同源 = 新稿 `705:799`(Log_in 组 @(35,827))+ 避脸拍板 |
- **面板 500→440 少掉的 60 去向(2026-07-29 审图拍板「方案 B」)**:新稿手机帧的面板是 **500 高**(含面板内「跳过登录」栏),而手机端已按产品决定剥离该入口、面板回 **440**、组回 **560**。少掉的 60 必须有个去处,两个候选经实机比例图审图:
- **方案 B(采纳)**:`loginY` 取稿值 622 / 827,60 全部落到**底部留白**(90 / 175,比稿内多 60)。品牌簇的稿内顶部构图与间距完全保真。
@@ -1376,14 +1373,14 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
- **原则:登录链路里截断与省略号不可作为可见结果**。登录面板是 680×500 冻结几何(2026-07-27 改版后值)、槽位不撑高,长文案没有退路——所以约束加在**文案侧**:所有 `login.*` 文案(含 agent 代写 / 补翻的五语文本)必须言简意赅、按槽位长度预算写作。线上出现可见省略号 = 该语言文案超预算 = **文案 bug(P1,修文案,不改布局)**。
- **长度预算自检**(写 / 翻文案时逐语言过一遍):估宽公式——汉字 / 假名 / 谚文 ≈ 1×字号 px,拉丁字母 / 数字 / 空格 ≈ 0.5×字号 px;估宽 ≤ 槽宽 × 0.95 才算过。常用槽预算:
- | 槽 | 宽×字号 | ≈汉字上限 | ≈拉丁字符上限 |
- |---|---|---:|---:|
- | 标题 | 680 @32 Bold(徽标变体为 inline 组:标题 shrink-to-fit + 2px 间隔 + 区域徽标,徽标宽随文案自适应,按现役最宽的 `Dev`(实测 51.7,非本表估宽公式的 46——公式是文案自检用的保守估算,徽标宽度以实测为准)算可用宽 680−54=626;v3 2026-07-27,原「固定 70px 徽标」几何随 Global 徽标撤除一并作废) | 20(徽标变体 18) | 40(徽标变体 37) |
- | 副标题(≤2 行,2026-07-24 拍板) | 540 @20 × 2 行 | 50 | 102 |
- | Text_link / hint / 倒计时 | 540 @20 | 25 | 51 |
- | 「跳过登录」文字按钮(2026-07-27) | 620 @24(= 槽 680 − 双侧 30 命中区扩张;移动端命中区扩 50 时可用宽 580) | 24(移动 22) | 49(移动 45) |
- | 主按钮 CTA | 448 @24 Bold(540 − 双侧 46 padding) | 17 | 35 |
- | 方式行标题 / 副题 | 409 @24 / @20 | 16 / 19 | 32 / 38 |
+ | 槽 | 宽×字号 | ≈汉字上限 | ≈拉丁字符上限 |
+ | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------: | ----------------: |
+ | 标题 | 680 @32 Bold(徽标变体为 inline 组:标题 shrink-to-fit + 2px 间隔 + 区域徽标,徽标宽随文案自适应,按现役最宽的 `Dev`(实测 51.7,非本表估宽公式的 46——公式是文案自检用的保守估算,徽标宽度以实测为准)算可用宽 680−54=626;v3 2026-07-27,原「固定 70px 徽标」几何随 Global 徽标撤除一并作废) | 20(徽标变体 18) | 40(徽标变体 37) |
+ | 副标题(≤2 行,2026-07-24 拍板) | 540 @20 × 2 行 | 50 | 102 |
+ | Text_link / hint / 倒计时 | 540 @20 | 25 | 51 |
+ | 「跳过登录」文字按钮(2026-07-27) | 620 @24(= 槽 680 − 双侧 30 命中区扩张;移动端命中区扩 50 时可用宽 580) | 24(移动 22) | 49(移动 45) |
+ | 主按钮 CTA | 448 @24 Bold(540 − 双侧 46 padding) | 17 | 35 |
+ | 方式行标题 / 副题 | 409 @24 / @20 | 16 / 19 | 32 / 38 |
- **agent 翻译硬约束**:为 `login.*` 生成或修改任何语言文案时,必须按上表逐语言自检;超预算就换更短表述(ja / ko 往往比 zh 长,优先压缩语序与敬语冗余),**禁止**靠布局手段(缩字号 / 加折行 / 依赖截断)吸收超长文案。
- **折行与对齐机制分级**:
@@ -1395,34 +1392,34 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
桌面 `apps/desktop/src/renderer/components/login/LoginControls.tsx`(11 组件),手机 `apps/mobile/src/components/LoginSkinControls.tsx`(13 组件)。两端同名组件同参数源。逐组件契约(逐参数规格见 `figma-component-spec §4`):
-| 组件 | 端 | 用途 | 关键 props | token / 几何 |
-|---|---|---|---|---|
-| `LoginPanel` | 双 | 白面板容器 | `children`, `testId`, `height?`(**桌面,仅 Splash 使用**) | 680×**500** r36 `--login-panel-bg` + inset 1px border;桌面由 `LoginStage` 承载缩放。`height` 默认 = 面板 500 且登录侧一律用默认值;**Splash 五帧传 440**(无「跳过登录」入口、设计稿未改版,跟随 500 会在启动态凭空多出 50 CSS px 空白;两者不同 stage、不同缩放,拆开不破坏 handoff 连续性) |
-| `LoginStage` | 桌面 | 1819×2098 画布「面板宿主」层,等比缩放 + z 序 | `children`, `ssoOrgGroupY`, `groupStyle` | 登录组 @(570, 1229 / 1227) 680×**620**;品牌层在 `LoginBrandStage` |
-| `LoginTitleBlock` | 双 | 标题 + 副标题 | `title`, `subtitle`, `regionPill?`(桌面) | 标题 y=31 h=38 32 Bold `--login-title-text`;副标题 @(70,75) 540 宽 ≤2 行顶对齐 20 Regular `--login-secondary-text`(2026-07-24 拍板,原 599×23 单行作废)。区域徽标见下方专条 |
-| `LoginInput` / `LoginSkinInput` | 桌 / 手 | 通用输入框 | `value`, `onChange`, `placeholder`, `center?`, `error?`, `prefix?` | @(70,158) 540×80 r40 `--login-control-bg`;边 placeholder→active;`center`=验证码居中变体 |
-| `LoginSkinPhoneInput` | 手机 | 手机号 + 固定国家码前缀 | `prefix`, … | 同 `LoginSkinInput` 几何,前缀不可点 |
-| `LoginPrimaryButton` | 双 | 主按钮(五态) | `label / children`, `onClick / onPress`, `disabled`, `loading / busy` | @(70,300) 540×80 r40 `--login-primary-button-bg / -border / -text`;disabled 白 70% 叠层 + 边 `--login-control-border-disabled` + 文字 opacity 0.8;loading spinner 24@(487,27) |
-| `LoginSocialRow` | 双 | 第三方圆钮行 | `children`, `count` | y=**540** 行内水平居中,80×80 gap 70;`count` 随 provider 动态(**不含游客圆钮**,2026-07-27 起该入口改为面板内文字按钮) |
-| `LoginSocialButton` | 双 | 第三方 / SSO 圆钮 | `label`, `onClick`, `children`, `isLoading / busy` | 80×80 r50 `--login-primary-button-bg / -border`;icon 48 居中;仅 normal + hover(桌面)+ pressed,**无 disabled / loading 视觉态** |
-| `LoginSocialGlyph` | 手机 | 社交图标矢量(Apple / Google / WeChat / SSO;**apple 分支仅非 iOS 场景**——iOS 走官方按钮不进圆钮行,见 §16.2) | 内部 | Google / WeChat 品牌色不变;Apple / SSO 单色随圆钮底反相(暗色白圆上 `#2A2828`) |
-| `LoginBackButton` | 双 | 返回 | `label`, `onClick`, `disabled` | @(20,20) 60×60 r40 `--login-action-control-bg` / `--login-back-border`;chevron 24 |
-| `LoginTextLink`(桌)/ `LoginTextLinkSlot`(手) | 桌 / 手 | 重发链接 / 提示文案(**文字链接**,不承载「跳过登录」) | `variant`(link / countdown,桌), `tone`, `children` | @(70,238) 540×50 20;link 变体 `--login-link-text` 下划线可点、hover / pressed 变色;countdown / slot `--login-control-placeholder` 不可点 |
-| `LoginSkipEntry`(桌)/ `LoginSkipLoginLink`(手) | 桌 / 手 | 「跳过登录」入口(**文字按钮**,与上一行的文字链接是两种组件) | 桌:`children`, `onClick`, `disabled`, `testId`;手:`label`, `onPress`, `testID` | 槽 @(0,430) 680×60,文字 24 Regular + 下划线、`--login-secondary-text`(双模同值),**hover / pressed 不变色**;命中区 = 文字实宽 + 左右各扩(桌 30 / 手 50 设计px)、高占满 60 槽,容器不可点 —— 逐条口径见下方「登录文字按钮」 |
-| `LoginResendCountdown` | 手机 | 验证码重发(倒计时 / 重发二态) | `deadline`, `countdownTemplate`, `resendLabel`, `onResend` | @(70,238);`deadline=null` → 常驻可点无倒计时(SSO 验证码屏用) |
-| `LoginMethodRow` | 双 | 方式选择行(企业 / 个人) | `top`, `title`, `subtitle`, `icon`(enterprise / person), `onClick` | 540×100 r60 `--login-action-control-bg` / `--login-control-border`;左图标 24@(27,37) / person 18×20@(30,39);右 share 18@(490,40);文字 @(67) 垂直居中 |
-| `LoginErrorText` | 双 | 错误提示 | `children` | @(0,380) 680×50 20 `--login-error-fg` |
-| `LoginLoadingRing` | 双 | 大 loading 环(浏览器 / 准备态) | `y`, `label` | 64×64 @(308, 158 / 193);轨道 `--login-loading-ring-track`,内弧 `--login-primary-button-bg`(Splash 转圈环 64×64@(308,188) 同轨道 token,内弧为 `--login-secondary-text`) |
+| 组件 | 端 | 用途 | 关键 props | token / 几何 |
+| -------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `LoginPanel` | 双 | 白面板容器 | `children`, `testId`, `height?`(**桌面,仅 Splash 使用**) | 680×**500** r36 `--login-panel-bg` + inset 1px border;桌面由 `LoginStage` 承载缩放。`height` 默认 = 面板 500 且登录侧一律用默认值;**Splash 五帧传 440**(无「跳过登录」入口、设计稿未改版,跟随 500 会在启动态凭空多出 50 CSS px 空白;两者不同 stage、不同缩放,拆开不破坏 handoff 连续性) |
+| `LoginStage` | 桌面 | 1819×2098 画布「面板宿主」层,等比缩放 + z 序 | `children`, `ssoOrgGroupY`, `groupStyle` | 登录组 @(570, 1229 / 1227) 680×**620**;品牌层在 `LoginBrandStage` |
+| `LoginTitleBlock` | 双 | 标题 + 副标题 | `title`, `subtitle`, `regionPill?`(桌面) | 标题 y=31 h=38 32 Bold `--login-title-text`;副标题 @(70,75) 540 宽 ≤2 行顶对齐 20 Regular `--login-secondary-text`(2026-07-24 拍板,原 599×23 单行作废)。区域徽标见下方专条 |
+| `LoginInput` / `LoginSkinInput` | 桌 / 手 | 通用输入框 | `value`, `onChange`, `placeholder`, `center?`, `error?`, `prefix?` | @(70,158) 540×80 r40 `--login-control-bg`;边 placeholder→active;`center`=验证码居中变体 |
+| `LoginSkinPhoneInput` | 手机 | 手机号 + 固定国家码前缀 | `prefix`, … | 同 `LoginSkinInput` 几何,前缀不可点 |
+| `LoginPrimaryButton` | 双 | 主按钮(五态) | `label / children`, `onClick / onPress`, `disabled`, `loading / busy` | @(70,300) 540×80 r40 `--login-primary-button-bg / -border / -text`;disabled 白 70% 叠层 + 边 `--login-control-border-disabled` + 文字 opacity 0.8;loading spinner 24@(487,27) |
+| `LoginSocialRow` | 双 | 第三方圆钮行 | `children`, `count` | y=**540** 行内水平居中,80×80 gap 70;`count` 随 provider 动态(**不含游客圆钮**,2026-07-27 起该入口改为面板内文字按钮) |
+| `LoginSocialButton` | 双 | 第三方 / SSO 圆钮 | `label`, `onClick`, `children`, `isLoading / busy` | 80×80 r50 `--login-primary-button-bg / -border`;icon 48 居中;仅 normal + hover(桌面)+ pressed,**无 disabled / loading 视觉态** |
+| `LoginSocialGlyph` | 手机 | 社交图标矢量(Apple / Google / WeChat / SSO;**apple 分支仅非 iOS 场景**——iOS 走官方按钮不进圆钮行,见 §16.2) | 内部 | Google / WeChat 品牌色不变;Apple / SSO 单色随圆钮底反相(暗色白圆上 `#2A2828`) |
+| `LoginBackButton` | 双 | 返回 | `label`, `onClick`, `disabled` | @(20,20) 60×60 r40 `--login-action-control-bg` / `--login-back-border`;chevron 24 |
+| `LoginTextLink`(桌)/ `LoginTextLinkSlot`(手) | 桌 / 手 | 重发链接 / 提示文案(**文字链接**,不承载「跳过登录」) | `variant`(link / countdown,桌), `tone`, `children` | @(70,238) 540×50 20;link 变体 `--login-link-text` 下划线可点、hover / pressed 变色;countdown / slot `--login-control-placeholder` 不可点 |
+| `LoginSkipEntry`(桌)/ `LoginSkipLoginLink`(手) | 桌 / 手 | 「跳过登录」入口(**文字按钮**,与上一行的文字链接是两种组件) | 桌:`children`, `onClick`, `disabled`, `testId`;手:`label`, `onPress`, `testID` | 槽 @(0,430) 680×60,文字 24 Regular + 下划线、`--login-secondary-text`(双模同值),**hover / pressed 不变色**;命中区 = 文字实宽 + 左右各扩(桌 30 / 手 50 设计px)、高占满 60 槽,容器不可点 —— 逐条口径见下方「登录文字按钮」 |
+| `LoginResendCountdown` | 手机 | 验证码重发(倒计时 / 重发二态) | `deadline`, `countdownTemplate`, `resendLabel`, `onResend` | @(70,238);`deadline=null` → 常驻可点无倒计时(SSO 验证码屏用) |
+| `LoginMethodRow` | 双 | 方式选择行(企业 / 个人) | `top`, `title`, `subtitle`, `icon`(enterprise / person), `onClick` | 540×100 r60 `--login-action-control-bg` / `--login-control-border`;左图标 24@(27,37) / person 18×20@(30,39);右 share 18@(490,40);文字 @(67) 垂直居中 |
+| `LoginErrorText` | 双 | 错误提示 | `children` | @(0,380) 680×50 20 `--login-error-fg` |
+| `LoginLoadingRing` | 双 | 大 loading 环(浏览器 / 准备态) | `y`, `label` | 64×64 @(308, 158 / 193);轨道 `--login-loading-ring-track`,内弧 `--login-primary-button-bg`(Splash 转圈环 64×64@(308,188) 同轨道 token,内弧为 `--login-secondary-text`) |
**登录文字按钮(新组件类别,2026-07-27 拍板)**:登录域现在有**两种**纯文字操作组件,语义与视觉都不通用,**不得互相复用**:
-| | **文字链接**(`LoginTextLink` / `LoginTextLinkSlot`) | **文字按钮**(`LoginSkipEntry` / `LoginSkipLoginLink`) |
-|---|---|---|
-| 语义 | 链接:跳转 / 重试 / 次要说明(重发验证码、sso-org 帮助行) | 按钮:触发一次产品级动作(跳过登录 → 进入本地模式) |
-| 色 | `--login-link-text` 族(light `#2A2828` / dark `#EEEEEE`) | `--login-secondary-text`(`#6F6F6F`,**light / dark 同值**,零新增 token) |
-| hover / pressed | 变色(`--login-link-hover` / `-pressed`) | **不变色**——只靠下划线常显 + 指针形状(桌面 `cursor:pointer`)给反馈 |
-| 字号 / 槽 | 20,槽 540×50 @(70,238) | 24,槽 680×60 @(0,430) |
-| 命中区 | 槽内整块 | **文字实宽 + 左右各扩**(桌面 30 / 移动 50 设计px),高度占满 60 槽;680×60 容器只做居中定位、自身不可点(桌面 `pointer-events:none` + 内层 button `auto`;移动 `pointerEvents="box-none"` + 内层 `Pressable`) |
+| | **文字链接**(`LoginTextLink` / `LoginTextLinkSlot`) | **文字按钮**(`LoginSkipEntry` / `LoginSkipLoginLink`) |
+| --------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 语义 | 链接:跳转 / 重试 / 次要说明(重发验证码、sso-org 帮助行) | 按钮:触发一次产品级动作(跳过登录 → 进入本地模式) |
+| 色 | `--login-link-text` 族(light `#2A2828` / dark `#EEEEEE`) | `--login-secondary-text`(`#6F6F6F`,**light / dark 同值**,零新增 token) |
+| hover / pressed | 变色(`--login-link-hover` / `-pressed`) | **不变色**——只靠下划线常显 + 指针形状(桌面 `cursor:pointer`)给反馈 |
+| 字号 / 槽 | 20,槽 540×50 @(70,238) | 24,槽 680×60 @(0,430) |
+| 命中区 | 槽内整块 | **文字实宽 + 左右各扩**(桌面 30 / 移动 50 设计px),高度占满 60 槽;680×60 容器只做居中定位、自身不可点(桌面 `pointer-events:none` + 内层 button `auto`;移动 `pointerEvents="box-none"` + 内层 `Pressable`) |
- **为什么命中区随语言自适应**:文字实际渲染宽度按语言不同(zh「跳过登录」96 设计px vs en `Skip Sign-In` 更宽),固定宽热区会在某些语言下偏窄或越界;扩张量固定、宽度 shrink-to-fit,热区随语言同步。
- **为什么放大 bounds 而不是用 hitSlop**:RN 的 `hitSlop` 不越父 View 边界(Android 界外触摸不派发),与协议 radio 同一套仓内约定(§16.4 hitSlop clamp 契约)。移动端命中区高度占满 60 槽(phone ~0.5 缩放 ≈30pt,与返回钮 60 设计px 同档),向上不侵入主按钮下沿、向下不越面板底。
@@ -1438,6 +1435,7 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
- **手机端无此变体**:`apps/mobile` 的 `LoginTitleBlock` 不接 `regionPill`(移动端未做区域徽标)。
**组件库新增(2026-07-24 登记;协议 UI 已随 consent PR 落地,游客圆钮方案已由上述「跳过登录」文字按钮取代)**:
+
- **协议勾选 radio**(figma `radiobutton 600:627`,四态双模式):24×24 命中区,圈 20×20 r9 + 2px 描边,选中为**对勾**(非圆点)。亮:未选 `#F1F0F1` 底 / `#434343` 边 → 选中 `#2A2828` 实底 + 白勾;暗:未选 `#2A2828` 底 / `#F1F0F1` 边 → 选中 `#F1F0F1` 底 + `#2A2828` 勾——选中反色与登录黑白反色体系同构。用于登录页 `服务条款` 协议行。
- **服务条款弹窗小按钮**(figma `light_button_*` / `Dark_button_*` 四母版,`602:846/863/1297/1311`):260×80 r40 文字 Bold 24;强调钮 = 模式反色(亮强调深底 `#2A2828`、暗强调浅底 `#EEEEEE`),暗模式普通钮引入新灰 `#434141` 底 / `#565454` 边。逐态值见 `figma-component-spec §11.3`。
- 既有组件扩容:`SSO 登录_企业` 与 `back` 均扩为含 Dark 三态的六态集(值已并入 §16.1 `--login-action-control-bg` / `--login-back-border` 口径),`white_button` 增 loading 五态。
@@ -1446,27 +1444,27 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
登录状态机权威 = `packages/auth-client` 源码(`AuthFlowState` / `LoginOutcome` 判别联合;`flow-map` 为辅助导航,个别 UI 段落滞后于区域定形态改版)。共享 step ∈ {`identifier`, `method-choice`, `verification-code`, `sso-verification`, `browser-redirect`, `account-selection`, `binding`, `completed`, `error`}(`sso-org` **不是**共享 step,是 `identifier` 下的页面局部 `ssoOrgMode` 子视图);其中 `account-selection` / `binding` / `sso-verification` / `completed` 由服务端 `LoginOutcome.status`(`ok` / `select_account` / `binding_required` / `sso_verification_required`)分支决定,**不是固定步骤**——任意 outcome 调用都可能命中。逐屏职责与关键组件(逐屏坐标 / 文案见 `DESIGN-login §3` 国区 / `§4` 国际区 / `§5` 移动):
-| 屏(step) | 职责 | 关键组件 |
-|---|---|---|
-| `identifier` | 输入手机号 / 邮箱(国区 phone / 国际区 email),含 social 圆钮行(Apple / Google / SSO,**无游客圆钮**)+ SSO 入口 + 协议同意行;**面板内常驻「跳过登录」入口**(2026-07-27 起,**仅桌面**;手机端 2026-07-28 剥离) | `LoginInput` / `LoginSkinPhoneInput` + `LoginPrimaryButton` + `LoginSocialRow` + `LoginConsentRow` + `LoginSkipEntry` / `LoginSkipLoginLink` |
-| `method-choice` | 存在真正选择时:企业 SSO / 个人邮箱验证码,或多条 SSO 连接。探测结果只剩唯一 SSO 或唯一邮箱验证码时不展示本屏——前者投影 `browser-redirect`,后者直接发码进入 `verification-code`(跨区确认窗随 step 离开一并关掉) | `LoginMethodRow`×2(top 158 / 278)+ `LoginTitleBlock`(`chooseMethod`) |
-| `verification-code` | 输入 6 位验证码,42s 重发倒计时 | `LoginInput`(center) / `CodeInput` + `LoginTextLink` / `LoginResendCountdown` + `LoginPrimaryButton` |
-| `sso-verification` | SSO 登录后验证企业联系方式,两子态(`codeRequested` false = 只发码 / true = 输码 + 常驻重发,**无倒计时**) | `LoginPrimaryButton`(sendCode) → `LoginInput`(center) + `LoginPrimaryButton`(completeSignIn / signIn) + `LoginTextLink` / `LoginResendCountdown`(deadline=null) |
-| `sso-org`(`identifier` 局部子视图,非共享 step) | 输入企业 ID / 组织 slug / 已验证域名跳转 SSO(`ssoOrgMode`) | `LoginInput` + `LoginPrimaryButton` + `LoginTextLinkSlot`(ssoOrgHint) |
-| `account-selection` | 服务端返回 ≥2 membership,用户选一个 | account row + `LoginTitleBlock`(`chooseAccount`) |
-| `binding` | 身份未绑 membership,补绑 phone / email(`codeRequested` 两子态;**无重发钮**,桌面 harness 锁定) | `LoginInput` / `LoginSkinPhoneInput` → `LoginInput`(center) + `LoginPrimaryButton` |
-| `account-deletion`(状态浮层) | 账号删除**状态展示**(发起流程在 Settings 的 `AccountDeletionSection`;登录页仅在存在删除回执时以**根层浮层气泡**展示 status,非主状态机 step;详见下方「注销状态浮层气泡」) | `AccountDeletionStatusPanel`(**登录皮容器外**的根层浮层,非面板内) |
-| `browser-redirect` | 社交 / SSO 跳浏览器验证,等待回调 | `LoginLoadingRing` + `LoginPrimaryButton`(取消)+ `LoginTitleBlock` |
-| `completed` / `error` | 登录成功 / 失败(含 browser 回调终态页);`error` 步桌面另有面板下方 footer 的「跳过登录」**逃生入口**(登录服务不可用时仍能进未登录状态,与面板内入口同口径**过协议门**——2026-07-29 拍板) | 成功无面板(进主界面);error = `LoginTitleBlock` + `LoginPrimaryButton`(重试)+ `LoginErrorText` + footer「跳过登录」按钮(桌面);browser 回调页 `oauthResultPage`(系统浏览器独立 HTML,main 侧内联常量,色值与 `--login-callback-*` token 同源——renderer CSS var 不可达,改值需两处同步) |
+| 屏(step) | 职责 | 关键组件 |
+| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `identifier` | 输入手机号 / 邮箱(国区 phone / 国际区 email),含 social 圆钮行(Apple / Google / SSO,**无游客圆钮**)+ SSO 入口 + 协议同意行;**面板内常驻「跳过登录」入口**(2026-07-27 起,**仅桌面**;手机端 2026-07-28 剥离) | `LoginInput` / `LoginSkinPhoneInput` + `LoginPrimaryButton` + `LoginSocialRow` + `LoginConsentRow` + `LoginSkipEntry` / `LoginSkipLoginLink` |
+| `method-choice` | 存在真正选择时:企业 SSO / 个人邮箱验证码,或多条 SSO 连接。探测结果只剩唯一 SSO 或唯一邮箱验证码时不展示本屏——前者投影 `browser-redirect`,后者直接发码进入 `verification-code`(跨区确认窗随 step 离开一并关掉) | `LoginMethodRow`×2(top 158 / 278)+ `LoginTitleBlock`(`chooseMethod`) |
+| `verification-code` | 输入 6 位验证码,42s 重发倒计时 | `LoginInput`(center) / `CodeInput` + `LoginTextLink` / `LoginResendCountdown` + `LoginPrimaryButton` |
+| `sso-verification` | SSO 登录后验证企业联系方式,两子态(`codeRequested` false = 只发码 / true = 输码 + 常驻重发,**无倒计时**) | `LoginPrimaryButton`(sendCode) → `LoginInput`(center) + `LoginPrimaryButton`(completeSignIn / signIn) + `LoginTextLink` / `LoginResendCountdown`(deadline=null) |
+| `sso-org`(`identifier` 局部子视图,非共享 step) | 输入企业 ID / 组织 slug / 已验证域名跳转 SSO(`ssoOrgMode`) | `LoginInput` + `LoginPrimaryButton` + `LoginTextLinkSlot`(ssoOrgHint) |
+| `account-selection` | 服务端返回 ≥2 membership,用户选一个 | account row + `LoginTitleBlock`(`chooseAccount`) |
+| `binding` | 身份未绑 membership,补绑 phone / email(`codeRequested` 两子态;**无重发钮**,桌面 harness 锁定) | `LoginInput` / `LoginSkinPhoneInput` → `LoginInput`(center) + `LoginPrimaryButton` |
+| `account-deletion`(状态浮层) | 账号删除**状态展示**(发起流程在 Settings 的 `AccountDeletionSection`;登录页仅在存在删除回执时以**根层浮层气泡**展示 status,非主状态机 step;详见下方「注销状态浮层气泡」) | `AccountDeletionStatusPanel`(**登录皮容器外**的根层浮层,非面板内) |
+| `browser-redirect` | 社交 / SSO 跳浏览器验证,等待回调 | `LoginLoadingRing` + `LoginPrimaryButton`(取消)+ `LoginTitleBlock` |
+| `completed` / `error` | 登录成功 / 失败(含 browser 回调终态页);`error` 步桌面另有面板下方 footer 的「跳过登录」**逃生入口**(登录服务不可用时仍能进未登录状态,与面板内入口同口径**过协议门**——2026-07-29 拍板) | 成功无面板(进主界面);error = `LoginTitleBlock` + `LoginPrimaryButton`(重试)+ `LoginErrorText` + footer「跳过登录」按钮(桌面);browser 回调页 `oauthResultPage`(系统浏览器独立 HTML,main 侧内联常量,色值与 `--login-callback-*` token 同源——renderer CSS var 不可达,改值需两处同步) |
**~~配置错误屏同样承载「跳过登录」逃生入口(移动端)~~〔已作废 2026-07-28:手机端整体剥离,配置错误屏无该入口〕**:`getMobileConfigIssues()` 命中(如 auth base URL 非法)时面板切到 config 提示态,该面板内仍渲染同一个 `LoginSkipLoginLink`(同槽 @(0,430)、同 handler、同 in-flight 门)——跳过登录不发任何网络请求,配置坏掉时恰恰最需要这个入口。
**协议门(consent gate)过门点与豁免(2026-07-29 更新)**:`identifier` 屏的协议同意行是一道**发起前拦截**——未勾选时点过门入口先弹服务条款 / 隐私协议弹窗,同意后续接原动作;同意即写入统计采集同意。
-| | 入口 |
-|---|---|
+| | 入口 |
+| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **过门**(个人链路一律先同意) | 手机号提交、邮箱提交(含仅查方式的 discover)、`method-choice` 个人行发码、社交圆钮(Apple / Google / 未来微信)、**「跳过登录」**(面板内常驻入口 + 桌面 `error` 步 footer 逃生口)——2026-07-29 拍板 |
-| **豁免** | 显式企业 SSO 入口(SSO 圆钮、组织标识提交、`method-choice` sso 行) |
+| **豁免** | 显式企业 SSO 入口(SSO 圆钮、组织标识提交、`method-choice` sso 行) |
「跳过登录」过门的口径(2026-07-29 拍板,**推翻 07-27 的免门结论**):不登录账号也是在使用 Cindy 客户端,因此与个人账号登录同口径——未勾选时先弹协议弹窗,同意后才进未登录状态,并写入统计采集同意(是否真的上报另由 main 侧闸决定:`analyticsSettingsService` 对本地会话一律 `!isLocalMode()` 不放行)。协议 UI(radio 四态、弹窗小按钮)与企业 SSO 豁免均不变。
@@ -1500,6 +1498,7 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
**大部分组件纯 token 驱动**(补 §16.1 双态表的 dark 值即自动深色,组件不动):`LoginPanel` / `LoginInput` / `LoginPrimaryButton`(底 / 边 / 字 + spinner)/ `LoginSocialButton`(随主按钮 token 自动反相白圆)/ `LoginBackButton` / `LoginTitleBlock` / `LoginTextLink` / `LoginMethodRow` / `LoginErrorText` / `LoginLoadingRing`。
**3 处非纯 token、需组件改动**:
+
1. **hover / pressed 叠层二态**:叠层原为组件内 figma 实测 rgba 字面值,暗色起 token 化为 `--login-overlay-*` 二态。**〔2026-07-24 组件库更新改判〕hover 统一「叠白变亮」**:全按钮族 hover = normal 底上叠白色半透明(深底 `#2A2828`/`#434141` 族 +白 8%;浅底 `#EEEEEE` 族 +白 10%;**唯一例外**:`back` 亮色 hover 维持既有白 70%),两模式同向——旧「白底钮 hover = 黑 5% 变暗」口径作废(figma `white_button 347:2529`、SSO `549:779` 已按新值改稿)。pressed 维持叠黑,alpha 分档:**深底强调钮 50%**(`log_in_button` 与亮模式强调小钮 `light_button_highlight`,不论尺寸)/ 暗普通小钮 `Dark_button_Normal` 20% / 浅底钮 10%(边 `#E5E5E5`)/ 方式行与返回钮 8%。归纳仅作速记,**落码逐组件对拍 `figma-component-spec §11.1` 的状态矩阵,不按类别名推断**。**〔落码状态〕本改判当前仅在文档层生效**:as-built 组件(含回调页 dark CTA / `oauthResultPage`)仍消费改判前的旧叠层值(浅底 hover 黑 5%、pressed 黑 10% 等),与新口径的同步随暗色实现 PR 的 `--login-overlay-*` token 化一并落地——在那之前「文档新口径 vs 代码旧值」的差异是已知且有意的,不构成实现缺陷;落地后以本段口径为准。hover 方向不再随底色反转,但 alpha 档位随组件底色深浅取值,`--login-overlay-*` 系列 light / dark 二态 token 照常承载,组件把字面 rgba 改为 `var(--login-overlay-*)`(机械替换,零行为变化)。
2. **`--login-bg-base` 前提变更**:画布底原为「跨主题恒定白 `#EDEDED`」,深色为 `#1F1F1E`(figma 532:585 帧实测)——即 `--login-*` 从「跨主题恒定」改为「随 light / dark 二态」(见 §16.2)。
3. **`LoginBrandStage` 资产按模式切**:深色画布用**登录专用**白字版字标 / slogan 资产(`assets/login/wordmark-dark*.png` / `slogan-dark*.png`,源自 figma 532:585 `CINDY_Standard_White` 与 SLOGAN `#FBFBFB`,由暗色实现 PR 新增;**不是** §15.7 的新页横版 `cindy-logo-dark.png`——落位与尺寸不同);立绘两模式同资产。