Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): improve unchecked switch contrast (#1464)

jiajiayao11fc8fb87bbc
diff --git a/apps/desktop/src/main/local-themes/__tests__/importer.test.ts b/apps/desktop/src/main/local-themes/__tests__/importer.test.ts
index fc55c9a86e..3231cf4322 100644
--- a/apps/desktop/src/main/local-themes/__tests__/importer.test.ts
+++ b/apps/desktop/src/main/local-themes/__tests__/importer.test.ts
@@ -43,6 +43,20 @@ const VSCODE_THEME = JSON.stringify({
tokenColors: [{ scope: 'comment', settings: { foreground: '#7f848e' } }],
});
+const UNSATISFIABLE_SWITCH_CONTRAST_THEME = JSON.stringify({
+ name: 'Impossible Contrast',
+ type: 'dark',
+ colors: {
+ 'editor.background': '#000000',
+ 'editor.foreground': '#dddddd',
+ 'sideBar.background': '#ffffff',
+ 'list.hoverBackground': '#777777',
+ 'panel.border': '#555555',
+ 'button.background': '#666666',
+ },
+ tokenColors: [{ scope: 'comment', settings: { foreground: '#777777' } }],
+});
+
const OBSIDIAN_THEME = `
/* Dual mode theme */
.theme-dark {
@@ -262,6 +276,13 @@ describe('外部主题导入(main 侧编排)', () => {
await expect(importExternalTheme()).rejects.toThrow('THEME_UNSUPPORTED_FILE');
});
+ it('主题无法派生可辨认的 Switch 关闭态时返回专用错误且不落盘', async () => {
+ pickFile(writeSource('impossible.json', UNSATISFIABLE_SWITCH_CONTRAST_THEME));
+
+ await expect(importExternalTheme()).rejects.toThrow('THEME_CONTRAST_UNSUPPORTED');
+ expect(loadLocalThemesSync().themes).toEqual([]);
+ });
+
it('超大文件报 THEME_FILE_TOO_LARGE 而不读进内存', async () => {
const big = `{"colors":{"editor.background":"#000000"},"_pad":"${'x'.repeat(4 * 1024 * 1024 + 16)}"}`;
pickFile(writeSource('huge.json', big));
diff --git a/apps/desktop/src/main/local-themes/importer.ts b/apps/desktop/src/main/local-themes/importer.ts
index d6b726235b..de67cbd609 100644
--- a/apps/desktop/src/main/local-themes/importer.ts
+++ b/apps/desktop/src/main/local-themes/importer.ts
@@ -20,6 +20,7 @@ import {
convertVsCodeTheme,
detectImportSource,
themeFamilyId,
+ UnsupportedThemePaletteError,
} from '../../shared/theme-import';
import type {
ConvertedTheme,
@@ -261,6 +262,13 @@ export async function importExternalTheme(
} catch (error) {
// Re-throw IPC errors from throwIpcError() (already typed and safe for renderer).
if (error instanceof Error && 'code' in error) throw error;
+ if (error instanceof UnsupportedThemePaletteError) {
+ log.warn(`Unsupported theme palette: ${error.message}`);
+ throwIpcError(
+ 'THEME_CONTRAST_UNSUPPORTED',
+ 'theme colors cannot produce a visible unchecked Switch state',
+ );
+ }
const message = normalizeError(error);
log.warn(`Theme import failed: ${message}`);
throwIpcError('THEME_IMPORT_INTERNAL', 'unexpected error during theme import');
diff --git a/apps/desktop/src/renderer/__tests__/ipcErrorThemeCodes.test.ts b/apps/desktop/src/renderer/__tests__/ipcErrorThemeCodes.test.ts
new file mode 100644
index 0000000000..d45362d491
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/ipcErrorThemeCodes.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractIpcError } from '../utils/ipcError';
+
+describe('extractIpcError · 主题导入错误码', () => {
+ it('识别主题色板无法满足 Switch 对比度的专用错误', () => {
+ expect(
+ extractIpcError(
+ new Error('[THEME_CONTRAST_UNSUPPORTED] unchecked Switch contrast is unsatisfiable'),
+ ),
+ ).toEqual({
+ code: 'THEME_CONTRAST_UNSUPPORTED',
+ message: 'unchecked Switch contrast is unsatisfiable',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/localThemeExport.test.ts b/apps/desktop/src/renderer/__tests__/localThemeExport.test.ts
index 9e46fe277e..a419550ca6 100644
--- a/apps/desktop/src/renderer/__tests__/localThemeExport.test.ts
+++ b/apps/desktop/src/renderer/__tests__/localThemeExport.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
+import '../themes/colors';
import {
bootstrapLocalThemesSync,
buildCopyFromTheme,
@@ -8,6 +9,36 @@ import {
} from '../themes/local-themes';
import type { Theme } from '../themes/types';
+const COPY_SOURCE_COLORS = {
+ surface: '#ffffff',
+ 'surface-on-card': '#f5f5f5',
+ 'surface-hover': '#eeeeee',
+ 'surface-secondary': '#e5e5e5',
+ 'text-secondary': '#6b6b6b',
+};
+
+function copyAndLoadTheme(source: Theme): {
+ copied: ReturnType<typeof buildCopyFromTheme>['theme'];
+ loaded: Theme;
+} {
+ const copied = buildCopyFromTheme(source).theme;
+ const payload = {
+ success: true as const,
+ diagnostics: [],
+ themes: [{ ...copied, id: `${copied.id}-loaded` }],
+ };
+ vi.stubGlobal('window', {
+ electronAPI: {
+ localThemes: {
+ listSync: () => payload,
+ },
+ },
+ });
+
+ bootstrapLocalThemesSync();
+ return { copied, loaded: getLocalThemes()[0]! };
+}
+
afterEach(() => {
vi.unstubAllGlobals();
});
@@ -27,6 +58,38 @@ describe('local theme export', () => {
});
});
+ it('复制产生的 Switch registry 默认别名在加载时重新派生', () => {
+ const { copied, loaded } = copyAndLoadTheme({
+ id: 'copy-source',
+ name: 'Copy Source',
+ type: 'light',
+ colors: COPY_SOURCE_COLORS,
+ });
+
+ expect(copied.colors['switch-track-off']).toBe('var(--text-secondary)');
+ expect(copied.colors['switch-thumb-off']).toBe('var(--surface-on-card)');
+ expect(loaded.colors['switch-track-off']).toMatch(/^#[0-9a-f]{6}$/);
+ expect(loaded.colors['switch-thumb-off']).toMatch(/^#[0-9a-f]{6}$/);
+ });
+
+ it('复制后加载不覆盖显式 Switch override', () => {
+ const { copied, loaded } = copyAndLoadTheme({
+ id: 'explicit-source',
+ name: 'Explicit Source',
+ type: 'light',
+ colors: {
+ ...COPY_SOURCE_COLORS,
+ 'switch-track-off': '#765432',
+ 'switch-thumb-off': '#fedcba',
+ },
+ });
+
+ expect(copied.colors['switch-track-off']).toBe('#765432');
+ expect(copied.colors['switch-thumb-off']).toBe('#fedcba');
+ expect(loaded.colors['switch-track-off']).toBe('#765432');
+ expect(loaded.colors['switch-thumb-off']).toBe('#fedcba');
+ });
+
it('刷新同一配置时替换素材对象,并把文件版本加入图片 URL', async () => {
const payload = {
success: true as const,
diff --git a/apps/desktop/src/renderer/__tests__/localThemesNormalize.test.ts b/apps/desktop/src/renderer/__tests__/localThemesNormalize.test.ts
index f4119e03dd..6a49d6481f 100644
--- a/apps/desktop/src/renderer/__tests__/localThemesNormalize.test.ts
+++ b/apps/desktop/src/renderer/__tests__/localThemesNormalize.test.ts
@@ -1,7 +1,21 @@
import { describe, expect, it } from 'vitest';
+import {
+ contrastRatio,
+ parseCssColor,
+ type Rgb,
+} from '../../shared/theme-import/color';
import { normalizeLocalThemeColors } from '../themes/local-themes-normalize';
+function rgb(value: string | undefined): Rgb {
+ if (!value) throw new Error('missing color in normalized local theme');
+ const parsed = parseCssColor(value);
+ if (!parsed) throw new Error(`invalid color in normalized local theme: ${value}`);
+ return parsed;
+}
+
+const SWITCH_DERIVATION_TARGET = 3.2;
+
describe('normalizeLocalThemeColors', () => {
it('迁移旧 connected badge override 并保留原中性色给文字 token', () => {
const out = normalizeLocalThemeColors({
@@ -74,4 +88,90 @@ describe('normalizeLocalThemeColors', () => {
expect(out).toBe(input);
expect(out['text-placeholder']).toBeUndefined();
});
+
+ it.each([
+ [
+ 'light',
+ {
+ surface: '#ffffff',
+ 'surface-elevated': '#ffffff',
+ 'surface-card-ivory': '#ffffff',
+ 'surface-hover': '#f8f8f8',
+ 'surface-hover-soft': '#ffffff',
+ 'surface-on-card': '#ffffff',
+ 'text-secondary': '#f0f0f0',
+ // 迁移不能被已有兼容 token 的提前返回跳过。
+ 'text-placeholder': '#c4c4c4',
+ },
+ ],
+ [
+ 'dark',
+ {
+ surface: '#000000',
+ 'surface-elevated': '#050505',
+ 'surface-card-ivory': '#050505',
+ 'surface-hover': '#0a0a0a',
+ 'surface-hover-soft': '#0a0a0a',
+ 'surface-on-card': '#000000',
+ 'text-secondary': '#101010',
+ 'text-placeholder': '#666666',
+ },
+ ],
+ ])('为升级前保存的 %s 导入主题补齐 Switch 安全 token', (_type, input) => {
+ const out = normalizeLocalThemeColors(input);
+ const track = rgb(out['switch-track-off']);
+ const thumb = rgb(out['switch-thumb-off']);
+
+ expect(out['switch-track-off']).not.toBe(input['text-secondary']);
+ expect(contrastRatio(track, thumb), 'thumb x track')
+ .toBeGreaterThanOrEqual(SWITCH_DERIVATION_TARGET);
+ for (const surfaceId of [
+ 'surface',
+ 'surface-elevated',
+ 'surface-card-ivory',
+ 'surface-hover',
+ 'surface-hover-soft',
+ ]) {
+ expect(
+ contrastRatio(track, rgb(out[surfaceId])),
+ `track x ${surfaceId}`,
+ ).toBeGreaterThanOrEqual(SWITCH_DERIVATION_TARGET);
+ }
+ });
+
+ it('保留用户显式配置的 Switch token,不二次校正', () => {
+ const input = {
+ 'switch-track-off': '#777777',
+ 'switch-thumb-off': '#ffffff',
+ 'text-secondary': '#f0f0f0',
+ };
+ expect(normalizeLocalThemeColors(input)).toBe(input);
+ });
+
+ it('旧语义色不完整或不可解析时保持原样,不让本地主题加载失败', () => {
+ const input = {
+ surface: '#ffffff',
+ 'surface-on-card': 'var(--surface-elevated)',
+ 'text-secondary': '#f0f0f0',
+ };
+ expect(normalizeLocalThemeColors(input)).toBe(input);
+ });
+
+ it('无解的旧导入主题恢复升级前的边框轨道与表面滑块,不静默倒退到默认别名', () => {
+ const input = {
+ surface: '#000000',
+ 'surface-elevated': '#ffffff',
+ 'surface-card-ivory': '#ffffff',
+ 'surface-hover': '#777777',
+ 'surface-hover-soft': '#777777',
+ 'surface-on-card': '#ffffff',
+ 'border-default': '#555555',
+ 'text-secondary': '#777777',
+ };
+
+ const out = normalizeLocalThemeColors(input);
+
+ expect(out['switch-track-off']).toBe('#555555');
+ expect(out['switch-thumb-off']).toBe('#000000');
+ });
});
diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
index 60c7c2b267..6ff7d8d334 100644
--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
@@ -47,6 +47,7 @@ const log = createLogger('settings/AppearanceSection');
/** IPC 错误码 → 专门文案;未列出的码落到通用 importFailed。 */
const IMPORT_ERROR_KEYS: Record<string, string> = {
THEME_UNSUPPORTED_FILE: 'settings.appearance.localThemes.importUnsupported',
+ THEME_CONTRAST_UNSUPPORTED: 'settings.appearance.localThemes.importContrastUnsupported',
THEME_USES_INCLUDE: 'settings.appearance.localThemes.importUsesInclude',
THEME_NOT_A_FILE: 'settings.appearance.localThemes.importNotAFile',
THEME_FILE_TOO_LARGE: 'settings.appearance.localThemes.importTooLarge',
diff --git a/apps/desktop/src/renderer/components/ui/__tests__/switch.test.tsx b/apps/desktop/src/renderer/components/ui/__tests__/switch.test.tsx
new file mode 100644
index 0000000000..ac2ef1115c
--- /dev/null
+++ b/apps/desktop/src/renderer/components/ui/__tests__/switch.test.tsx
@@ -0,0 +1,19 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { Switch } from '../switch';
+
+describe('Switch', () => {
+ afterEach(cleanup);
+
+ it('uses dedicated semantic tokens for the unchecked track and thumb', () => {
+ render(<Switch aria-label="Background updates" />);
+
+ const track = screen.getByRole('switch', { name: 'Background updates' });
+ const thumb = track.firstElementChild as HTMLElement;
+ expect(track.className).toContain('data-[state=unchecked]:bg-[var(--switch-track-off)]');
+ expect(thumb.className).toContain('data-[state=unchecked]:bg-[var(--switch-thumb-off)]');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/ui/switch.tsx b/apps/desktop/src/renderer/components/ui/switch.tsx
index ba12fe1d06..30b168cc5c 100644
--- a/apps/desktop/src/renderer/components/ui/switch.tsx
+++ b/apps/desktop/src/renderer/components/ui/switch.tsx
@@ -2,7 +2,8 @@
* Switch — shadcn/ui new-york 风格的 Radix Switch 包装。
*
* 与 dropdown-menu / popover 同 Radix 包装风格:直接 forwardRef + cn() 拼样式。
- * 颜色全走 token:开启 bg-primary、关闭 bg-input、滑块 bg-background。
+ * 颜色全走 token:开启 bg-primary;关闭态使用 Switch 专用 track/thumb token,
+ * 避免复用 input 边框色后在设置卡片上失去非文字组件所需的轮廓对比度。
*/
import * as React from 'react';
@@ -19,7 +20,7 @@ const Switch = React.forwardRef<
'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
'disabled:cursor-not-allowed disabled:opacity-50',
- 'data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
+ 'data-[state=checked]:bg-primary data-[state=unchecked]:bg-[var(--switch-track-off)]',
className,
)}
{...props}
@@ -27,7 +28,8 @@ const Switch = React.forwardRef<
>
<SwitchPrimitives.Thumb
className={cn(
- 'pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform',
+ 'pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform',
+ 'data-[state=checked]:bg-background data-[state=unchecked]:bg-[var(--switch-thumb-off)]',
'data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
)}
/>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index aaf684c616..cf439a3dec 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -397,6 +397,7 @@
"importPartial": "Imported {{name}} ({{themeCount}} variant(s)). {{skipped}} semantic colors stay unchanged per spec, {{unresolved}} values could not be read, and {{derived}} roles were approximated from nearby colors.",
"importFailed": "Import failed: {{error}}",
"importUnsupported": "This file is not a recognizable VSCode or Obsidian theme.",
+ "importContrastUnsupported": "The theme colors cannot keep unchecked switches visible. Adjust its background or secondary text colors, then import it again.",
"importUsesInclude": "This VSCode theme inherits colors via \"include\" and cannot be imported standalone.",
"importNotAFile": "Select a file, not a folder.",
"importTooLarge": "File is too large to import as a theme.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e25b8e5233..43673d33ce 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -397,6 +397,7 @@
"importPartial": "{{name}}({{themeCount}} 種類)をインポートしました。意味を持つ色 {{skipped}} 件は規約どおり変更せず、{{unresolved}} 件は値を読み取れずスキップ、{{derived}} 件は近似色から推定しました。",
"importFailed": "インポートに失敗しました: {{error}}",
"importUnsupported": "このファイルは VSCode または Obsidian のテーマとして認識できません。",
+ "importContrastUnsupported": "テーマの配色ではオフ状態のスイッチを明瞭に表示できません。背景色またはサブテキストの色を調整してから、もう一度インポートしてください。",
"importUsesInclude": "この VSCode テーマは include で配色を継承しているため、単独ではインポートできません。",
"importNotAFile": "フォルダではなくファイルを選択してください。",
"importTooLarge": "ファイルが大きすぎるため、テーマとしてインポートできません。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b8409e8750..f09bb76172 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -397,6 +397,7 @@
"importPartial": "{{name}}({{themeCount}}개 구성)을 가져왔습니다. 의미가 정해진 색 {{skipped}}개는 규칙대로 그대로 두었고, {{unresolved}}개는 값을 읽을 수 없어 건너뛰었고, {{derived}}개는 인접색에서 추정했습니다.",
"importFailed": "가져오기에 실패했습니다: {{error}}",
"importUnsupported": "이 파일은 VSCode 또는 Obsidian 테마로 인식할 수 없습니다.",
+ "importContrastUnsupported": "테마 색상으로는 꺼진 스위치를 선명하게 표시할 수 없습니다. 배경색이나 보조 텍스트 색상을 조정한 뒤 다시 가져오세요.",
"importUsesInclude": "이 VSCode 테마는 include를 통해 색상을 상속하므로 단독으로 가져올 수 없습니다.",
"importNotAFile": "폴더가 아닌 파일을 선택해 주세요.",
"importTooLarge": "파일이 너무 커서 테마로 가져올 수 없습니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index c34bdfe383..a1455cabd1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -397,6 +397,7 @@
"importPartial": "已导入 {{name}}({{themeCount}} 个方案)。{{skipped}} 项语义色按规范不变,{{unresolved}} 项取值无法识别,{{derived}} 项由邻近色近似推导",
"importFailed": "导入失败:{{error}}",
"importUnsupported": "这个文件不是可识别的 VSCode 或 Obsidian 主题",
+ "importContrastUnsupported": "主题配色无法清晰显示关闭状态的开关,调整背景色或次要文字颜色后重新导入",
"importUsesInclude": "该 VSCode 主题通过 include 继承配色,无法独立导入",
"importNotAFile": "选择一个文件,而非文件夹",
"importTooLarge": "文件太大,无法作为主题导入",
diff --git a/apps/desktop/src/renderer/themes/__tests__/cindyThemes.test.ts b/apps/desktop/src/renderer/themes/__tests__/cindyThemes.test.ts
index 88b85423d8..2a3aeabb51 100644
--- a/apps/desktop/src/renderer/themes/__tests__/cindyThemes.test.ts
+++ b/apps/desktop/src/renderer/themes/__tests__/cindyThemes.test.ts
@@ -109,6 +109,26 @@ const THEMES: ReadonlyArray<readonly [string, CindyTheme]> = [
['cindy-dark', { colors: cindyDark.colors as unknown as Record<string, string> }],
];
+// 决策表生成后已有的字面 override 债务;这里只冻结 ID 边界,不把其值另立为权威。
+// 新 ID 不得扩充这份 baseline,而应进入决策表或引用已治理 token。
+const PREEXISTING_UNFROZEN_LITERAL_IDS: Record<string, ReadonlySet<string>> = {
+ 'cindy-light': new Set([
+ 'ask-option-list-bg',
+ 'model-item-hover',
+ 'update-btn-bg',
+ 'update-btn-hover',
+ ]),
+ 'cindy-dark': new Set([
+ 'ask-header-chip-bg',
+ 'ask-option-hover',
+ 'ask-option-list-bg',
+ 'ask-send-disabled-bg',
+ 'model-item-hover',
+ 'update-btn-bg',
+ 'update-btn-hover',
+ ]),
+};
+
// ===== ① key 合法 =====
describe('CINDY · ① key 合法(每 override key ∈ ColorRegistry)', () => {
for (const [name, theme] of THEMES) {
@@ -148,6 +168,28 @@ describe('CINDY · ③ 值格式按消费契约', () => {
}
});
+ it('baseline 外未列入决策表的新增 override 只能引用已治理 token', () => {
+ const frozenIds = new Set(Object.keys(CINDY_EXPECTED_VALUES));
+ const registeredIds = new Set(colorRegistry.getColors().map((color) => color.id));
+ const tokenReference = /^var\(--([a-z0-9-]+)\)$/;
+ for (const [name, theme] of THEMES) {
+ const preexistingLiteralIds = PREEXISTING_UNFROZEN_LITERAL_IDS[name] ?? new Set();
+ for (const [id, value] of Object.entries(theme.colors)) {
+ if (frozenIds.has(id) || preexistingLiteralIds.has(id)) continue;
+ const referencedId = value.match(tokenReference)?.[1];
+ expect(
+ referencedId,
+ `${name}.${id} 未入决策表且不在 baseline,只能引用已治理 token,实际 ${value}`,
+ ).toBeTruthy();
+ if (!referencedId) continue;
+ expect(
+ registeredIds.has(referencedId),
+ `${name}.${id} 引用了未注册 token: ${referencedId}`,
+ ).toBe(true);
+ }
+ }
+ });
+
it('逐 token override 值 == 决策表冻结期望值(防手改漂移)', () => {
for (const [name, theme] of THEMES) {
for (const [id, expected] of Object.entries(CINDY_EXPECTED_VALUES)) {
diff --git a/apps/desktop/src/renderer/themes/__tests__/switchThemeContrast.test.ts b/apps/desktop/src/renderer/themes/__tests__/switchThemeContrast.test.ts
new file mode 100644
index 0000000000..7f0783330c
--- /dev/null
+++ b/apps/desktop/src/renderer/themes/__tests__/switchThemeContrast.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildThemeColorsFromPalette } from '../../../shared/theme-import/palette';
+import { colorRegistry } from '../color-registry';
+import '../colors';
+import { builtinThemes } from '../registry';
+import { resolveThemeValue } from '../theme-service';
+import type { ColorIdentifier, Theme } from '../types';
+
+type RGB = readonly [number, number, number];
+
+function parseHex(value: string): RGB {
+ if (!/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(value)) {
+ throw new Error(`Unsupported color format in contrast test: ${value}`);
+ }
+ const hex = value.slice(1);
+ const normalized = hex.length === 3 ? [...hex].map((digit) => digit.repeat(2)).join('') : hex;
+ const number = Number.parseInt(normalized, 16);
+ return [(number >> 16) & 255, (number >> 8) & 255, number & 255];
+}
+
+const UNCHECKED_SURFACES = [
+ 'surface',
+ 'surface-elevated',
+ 'surface-card-ivory',
+ 'surface-hover',
+ 'surface-hover-soft',
+] as const;
+
+const importedDarkTheme: Theme = {
+ id: 'imported-dark-fixture',
+ name: 'Imported Dark Fixture',
+ type: 'dark',
+ colors: buildThemeColorsFromPalette({
+ surface: { r: 24, g: 26, b: 30 },
+ elevated: { r: 34, g: 37, b: 42 },
+ elevatedSoft: { r: 34, g: 37, b: 42 },
+ hover: { r: 48, g: 52, b: 58 },
+ chip: { r: 48, g: 52, b: 58 },
+ border: { r: 72, g: 77, b: 86 },
+ textPrimary: { r: 230, g: 232, b: 235 },
+ textSecondary: { r: 180, g: 184, b: 190 },
+ textTertiary: { r: 132, g: 137, b: 145 },
+ textDisabled: { r: 94, g: 99, b: 108 },
+ accentPrimary: { r: 92, g: 157, b: 255 },
+ accentSoft: { r: 137, g: 185, b: 255 },
+ accentDeep: { r: 55, g: 112, b: 205 },
+ }, 'dark'),
+};
+
+function luminance(value: string): number {
+ const channels = parseHex(value).map((channel) => {
+ const normalized = channel / 255;
+ return normalized <= 0.03928
+ ? normalized / 12.92
+ : ((normalized + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
+}
+
+function contrast(first: string, second: string): number {
+ const [lighter, darker] = [luminance(first), luminance(second)].sort((a, b) => b - a);
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+function resolveColor(theme: Theme, id: ColorIdentifier, seen = new Set<string>()): string {
+ if (seen.has(id)) {
+ throw new Error(`Circular color token reference: ${[...seen, id].join(' -> ')}`);
+ }
+ seen.add(id);
+
+ const value = resolveThemeValue(theme, id);
+ if (value === null) {
+ throw new Error(`Theme '${theme.id}' does not resolve --${id}`);
+ }
+
+ const reference = value.match(/^var\(--([^)]+)\)$/);
+ return reference ? resolveColor(theme, reference[1], seen) : value;
+}
+
+describe('unchecked Switch contrast', () => {
+ it('registers dedicated track and thumb tokens', () => {
+ expect(colorRegistry.resolveDefault('switch-track-off', 'light')).toBe('var(--text-secondary)');
+ expect(colorRegistry.resolveDefault('switch-track-off', 'dark')).toBe('var(--text-secondary)');
+ expect(colorRegistry.resolveDefault('switch-thumb-off', 'light')).toBe('var(--surface-on-card)');
+ expect(colorRegistry.resolveDefault('switch-thumb-off', 'dark')).toBe('var(--surface-on-card)');
+ });
+
+ it('fails closed for unsupported color formats', () => {
+ expect(() => parseHex('rgb(130, 130, 130)')).toThrow('Unsupported color format');
+ });
+
+ it('resolves unchecked colors through imported theme palette aliases', () => {
+ const track = resolveColor(importedDarkTheme, 'switch-track-off');
+ const thumb = resolveColor(importedDarkTheme, 'switch-thumb-off');
+
+ expect(track).toBe(importedDarkTheme.colors['text-secondary']);
+ expect(thumb).toBe(importedDarkTheme.colors['surface-on-card']);
+ expect(contrast(thumb, track), 'imported dark: thumb x track').toBeGreaterThanOrEqual(3);
+
+ for (const surface of UNCHECKED_SURFACES) {
+ const background = resolveColor(importedDarkTheme, surface);
+ expect(contrast(track, background), `imported dark: track x ${surface}`).toBeGreaterThanOrEqual(3);
+ }
+ });
+
+ it.each(Object.values(builtinThemes))('$name keeps the unchecked control distinguishable', (theme) => {
+ const track = resolveColor(theme, 'switch-track-off');
+ const thumb = resolveColor(theme, 'switch-thumb-off');
+
+ expect(contrast(thumb, track), `${theme.id}: thumb x track`).toBeGreaterThanOrEqual(3);
+
+ for (const surface of UNCHECKED_SURFACES) {
+ const background = resolveColor(theme, surface);
+ expect(contrast(track, background), `${theme.id}: track x ${surface}`).toBeGreaterThanOrEqual(3);
+ }
+ });
+});
diff --git a/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts b/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
index 94c1ee2237..fa214d1dd9 100644
--- a/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
+++ b/apps/desktop/src/renderer/themes/builtin/cindy-dark.ts
@@ -19,6 +19,8 @@ const overrides = {
'surface-hover-soft': '#2B2929', // 插值: 20%
'surface-hover-hsl': '0.0 2.2% 18.0%', // 插值: hover -> HSL
'surface-on-card': '#2A2828', // 裁决: 中性反相前景,不作红 CTA 专用
+ // 有意引用决策表已冻结的 disabled 灰,与 fast-toggle-track 同源;不新增自由字面值。
+ 'switch-track-off': 'var(--text-disabled)',
'status-badge-fg': '#1F1F1F', // §7 必炸点:值经队列震荡后按 HEAD 冻结(#1F1F1F,5.61:1 × #FF6600 ≥4.5),批准依据:用户亲批方案 2026-07-17
'border-default': '#434343', // 直映: 边框
'border-default-hsl': '0.0 0.0% 26.3%', // 边框 -> HSL
diff --git a/apps/desktop/src/renderer/themes/builtin/cindy-light.ts b/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
index 93398b841c..f65aaf02e5 100644
--- a/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
+++ b/apps/desktop/src/renderer/themes/builtin/cindy-light.ts
@@ -19,6 +19,8 @@ const overrides = {
'surface-hover-soft': '#EFEFEF', // 插值: 20%
'surface-hover-hsl': '0.0 0.0% 94.5%', // 插值: hover -> HSL
'surface-on-card': '#FFFFFF', // 裁决: 中性反相前景,不作红 CTA 专用
+ // 有意引用决策表已冻结的 disabled 灰,与 fast-toggle-track 同源;不新增自由字面值。
+ 'switch-track-off': 'var(--text-disabled)',
'status-badge-fg': '#1F1F1F', // §7 必炸点:值经队列震荡后按 HEAD 冻结(#1F1F1F,5.61:1 × #FF6600 ≥4.5),批准依据:用户亲批方案 2026-07-17
'border-default': '#DCDFE3', // 直映: 边框
'border-default-hsl': '214.3 11.1% 87.6%', // 边框 -> HSL
diff --git a/apps/desktop/src/renderer/themes/colors.ts b/apps/desktop/src/renderer/themes/colors.ts
index 6bf3d4dc96..801c138947 100644
--- a/apps/desktop/src/renderer/themes/colors.ts
+++ b/apps/desktop/src/renderer/themes/colors.ts
@@ -254,6 +254,14 @@ registerColor('input', {
light: 'var(--border-shadcn-hsl)',
dark: 'var(--border-shadcn-hsl)',
}, 'input');
+registerColor('switch-track-off', {
+ light: 'var(--text-secondary)',
+ dark: 'var(--text-secondary)',
+}, '共享 Switch 未选中轨道;跟随主题次要前景,与默认/悬停表面及滑块保持至少 3:1 非文字组件对比度,同时弱于开启态');
+registerColor('switch-thumb-off', {
+ light: 'var(--surface-on-card)',
+ dark: 'var(--surface-on-card)',
+}, '共享 Switch 未选中滑块;跟随主题反相前景,与未选中轨道保持至少 3:1 非文字组件对比度');
registerColor('ring', {
light: 'var(--text-primary-hsl)',
dark: 'var(--text-primary-hsl)',
diff --git a/apps/desktop/src/renderer/themes/local-themes-normalize.ts b/apps/desktop/src/renderer/themes/local-themes-normalize.ts
index 4b04e4433e..ce69fe5c7f 100644
--- a/apps/desktop/src/renderer/themes/local-themes-normalize.ts
+++ b/apps/desktop/src/renderer/themes/local-themes-normalize.ts
@@ -11,9 +11,15 @@
* 这里在**加载期**(renderer 侧 `mapWireTheme`)做兼容归一化,不改写盘上 JSON、幂等:
* 当快照缺 `text-placeholder` 时,从旧 `settings-input-placeholder`(优先——历史上即
* "读着像空"的淡色)或任一 per-surface 值播种出 `text-placeholder`,并丢弃 4 个旧
- * per-surface placeholder override,让四个输入面统一走新 slot。
+ * per-surface placeholder override,让四个输入面统一走新 slot。外部主题导入新增
+ * Switch 安全 token 前保存的完整色板,也会在缺少二者时从旧语义色运行时补齐;
+ * 复制主题固化的 registry 默认别名同样按缺失处理。
*/
+import { parseCssColor, toHex, type Rgb } from '../../shared/theme-import/color';
+import { deriveUncheckedSwitchTrack } from '../../shared/theme-import/palette';
+import { colorRegistry } from './color-registry';
+
/** 旧的 per-surface placeholder alias —— 归一化后由 `--text-placeholder` slot 统一接管。 */
const PER_SURFACE_PLACEHOLDER_KEYS = [
'settings-input-placeholder',
@@ -25,6 +31,84 @@ const PER_SURFACE_PLACEHOLDER_KEYS = [
const CONNECTED_BADGE_KEY = 'settings-badge-connected';
const CONNECTED_BADGE_TEXT_KEY = 'settings-badge-connected-text';
const LEGACY_CONNECTED_BADGE_DEFAULT = 'var(--text-primary)';
+const SWITCH_TRACK_OFF_KEY = 'switch-track-off';
+const SWITCH_THUMB_OFF_KEY = 'switch-thumb-off';
+const LEGACY_SWITCH_TRACK_KEY = 'border-default';
+const LEGACY_SWITCH_THUMB_KEY = 'surface';
+const UNCHECKED_SWITCH_SURFACE_KEYS = [
+ 'surface',
+ 'surface-elevated',
+ 'surface-card-ivory',
+ 'surface-hover',
+ 'surface-hover-soft',
+] as const;
+
+function parseThemeColor(colors: Record<string, string>, key: string): Rgb | null {
+ const value = colors[key];
+ return value === undefined ? null : parseCssColor(value);
+}
+
+function isRegistryDefaultSwitchValue(key: string, value: string): boolean {
+ return (
+ colorRegistry.resolveDefault(key, 'light') === value
+ || colorRegistry.resolveDefault(key, 'dark') === value
+ );
+}
+
+/**
+ * 旧导入产物没有 provenance/version 字段,不能靠文件名猜来源。仅当两个新 token
+ * 都缺失或等于 registry 默认别名、且完整的旧语义色可解析时补齐;任何真正的
+ * 显式新 token 或不完整手写主题原样保留。
+ */
+function normalizeUncheckedSwitchColors(
+ colors: Record<string, string>,
+): Record<string, string> {
+ const track = colors[SWITCH_TRACK_OFF_KEY];
+ const thumbOverride = colors[SWITCH_THUMB_OFF_KEY];
+ const hasExplicitTrack =
+ track !== undefined && !isRegistryDefaultSwitchValue(SWITCH_TRACK_OFF_KEY, track);
+ const hasExplicitThumb =
+ thumbOverride !== undefined
+ && !isRegistryDefaultSwitchValue(SWITCH_THUMB_OFF_KEY, thumbOverride);
+ if (hasExplicitTrack || hasExplicitThumb) {
+ return colors;
+ }
+
+ const preferredTrack = parseThemeColor(colors, 'text-secondary');
+ const thumb = parseThemeColor(colors, 'surface-on-card');
+ if (!preferredTrack || !thumb) return colors;
+
+ const surfaces: Rgb[] = [];
+ for (const key of UNCHECKED_SWITCH_SURFACE_KEYS) {
+ const surface = parseThemeColor(colors, key);
+ if (!surface) return colors;
+ surfaces.push(surface);
+ }
+
+ try {
+ const track = deriveUncheckedSwitchTrack(
+ preferredTrack,
+ [...surfaces, thumb],
+ );
+ return {
+ ...colors,
+ [SWITCH_TRACK_OFF_KEY]: toHex(track),
+ [SWITCH_THUMB_OFF_KEY]: toHex(thumb),
+ };
+ } catch {
+ // 旧导入模板里 unchecked Switch 实际是 bg-input + bg-background;这两者分别
+ // 来自同一色板的 border 与 surface。无解时冻结这对升级前颜色,避免掉到
+ // 未经约束的新 registry alias 后比升级前更差。本地主题 bootstrap 仍 best-effort。
+ const legacyTrack = parseThemeColor(colors, LEGACY_SWITCH_TRACK_KEY);
+ const legacyThumb = parseThemeColor(colors, LEGACY_SWITCH_THUMB_KEY);
+ if (!legacyTrack || !legacyThumb) return colors;
+ return {
+ ...colors,
+ [SWITCH_TRACK_OFF_KEY]: toHex(legacyTrack),
+ [SWITCH_THUMB_OFF_KEY]: toHex(legacyThumb),
+ };
+ }
+}
export function normalizeLocalThemeColors(
colors: Record<string, string>,
@@ -42,26 +126,27 @@ export function normalizeLocalThemeColors(
};
}
- // 新主题 / 已迁移过的快照本就带 text-placeholder,原样返回(幂等)。
- if (normalized['text-placeholder'] !== undefined) return normalized;
-
- // 优先用 settings-input-placeholder 作为种子:它在历史快照里即"淡到读着像空"的
- // 那一档(其余 per-surface 多为 var(--text-tertiary),偏深)。都没有则不迁移,
- // 让 text-placeholder 走 registry 默认值。
- let seed: string | undefined;
- for (const key of PER_SURFACE_PLACEHOLDER_KEYS) {
- if (normalized[key] !== undefined) {
- seed = normalized[key];
- break;
+ if (normalized['text-placeholder'] === undefined) {
+ // 优先用 settings-input-placeholder 作为种子:它在历史快照里即"淡到读着像空"的
+ // 那一档(其余 per-surface 多为 var(--text-tertiary),偏深)。都没有则不迁移,
+ // 让 text-placeholder 走 registry 默认值。
+ let seed: string | undefined;
+ for (const key of PER_SURFACE_PLACEHOLDER_KEYS) {
+ if (normalized[key] !== undefined) {
+ seed = normalized[key];
+ break;
+ }
+ }
+ if (seed !== undefined) {
+ const drop = new Set<string>(PER_SURFACE_PLACEHOLDER_KEYS);
+ const next: Record<string, string> = {};
+ for (const [key, value] of Object.entries(normalized)) {
+ if (!drop.has(key)) next[key] = value;
+ }
+ next['text-placeholder'] = seed;
+ normalized = next;
}
}
- if (seed === undefined) return normalized;
- const drop = new Set<string>(PER_SURFACE_PLACEHOLDER_KEYS);
- const next: Record<string, string> = {};
- for (const [key, value] of Object.entries(normalized)) {
- if (!drop.has(key)) next[key] = value;
- }
- next['text-placeholder'] = seed;
- return next;
+ return normalizeUncheckedSwitchColors(normalized);
}
diff --git a/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts b/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts
index a027180a42..68f7ef8bbe 100644
--- a/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts
+++ b/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts
@@ -54,6 +54,43 @@ body {
}
`;
+const UNSATISFIABLE_MODE_VARS = `
+ --background-primary: #000000;
+ --background-secondary: #ffffff;
+ --background-modifier-hover: #777777;
+ --background-secondary-alt: #666666;
+ --background-modifier-border: #555555;
+ --text-normal: #dddddd;
+ --text-muted: #777777;
+ --text-faint: #777777;
+ --interactive-accent: #666666;
+`;
+
+const VALID_MODE_VARS = {
+ dark: `
+ --background-primary: #1e1e1e;
+ --background-secondary: #252525;
+ --background-modifier-hover: #2a2a2a;
+ --background-secondary-alt: #303030;
+ --background-modifier-border: #333333;
+ --text-normal: #dcddde;
+ --text-muted: #999999;
+ --text-faint: #666666;
+ --interactive-accent: #7b6cd9;
+ `,
+ light: `
+ --background-primary: #ffffff;
+ --background-secondary: #f5f5f5;
+ --background-modifier-hover: #eeeeee;
+ --background-secondary-alt: #e5e5e5;
+ --background-modifier-border: #d7d7d7;
+ --text-normal: #222222;
+ --text-muted: #6b6b6b;
+ --text-faint: #999999;
+ --interactive-accent: #7b6cd9;
+ `,
+} as const;
+
describe('theme-import · CSS 规则扫描', () => {
it('切出顶层规则并递归展开 at-rule', () => {
const rules = collectCssRules(THEME_CSS);
@@ -248,6 +285,25 @@ describe('theme-import · Obsidian 端到端转换', () => {
expect(single!.themes[0].type).toBe('light');
});
+ it.each([
+ ['light', 'dark'],
+ ['dark', 'light'],
+ ] as const)(
+ '%s 模式色板不可满足时保留成功的 %s 模式',
+ (failedMode, successfulMode) => {
+ const css = `
+ .theme-${failedMode} { ${UNSATISFIABLE_MODE_VARS} }
+ .theme-${successfulMode} { ${VALID_MODE_VARS[successfulMode]} }
+ `;
+
+ const partial = convertObsidianTheme(css, 'Partial Theme');
+
+ expect(partial).not.toBeNull();
+ expect(partial!.themes.map((theme) => theme.type)).toEqual([successfulMode]);
+ expect(partial!.report.unresolved).toContain(`mode:${failedMode}`);
+ },
+ );
+
it('没有任何主题变量的 CSS 返回 null', () => {
expect(convertObsidianTheme('.foo { color: red; }', 'X')).toBeNull();
expect(convertObsidianTheme('', 'X')).toBeNull();
diff --git a/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts b/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
index 564e7f26c2..47d36a73d7 100644
--- a/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
+++ b/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
@@ -7,7 +7,13 @@ import { atomOneLight } from '../../renderer/themes/builtin/atom-one-light';
import { githubDark } from '../../renderer/themes/builtin/github-dark';
import { oneDarkPro } from '../../renderer/themes/builtin/one-dark-pro';
import { solarizedLight } from '../../renderer/themes/builtin/solarized-light';
-import { parseCssColor, toHslTriplet, type Rgb } from '../theme-import/color';
+import {
+ contrastRatio,
+ parseCssColor,
+ toHex,
+ toHslTriplet,
+ type Rgb,
+} from '../theme-import/color';
import {
buildThemeColorsFromPalette,
TEMPLATE_TOKEN_IDS,
@@ -36,6 +42,8 @@ function rgb(hex: string): Rgb {
return parsed;
}
+const SWITCH_DERIVATION_TARGET = 3.2;
+
/** one-dark-pro.ts 头部的手写色板(dark 代表)。 */
const ONE_DARK_PRO_PALETTE: ThemePalette = {
surface: rgb('#282c34'),
@@ -127,8 +135,13 @@ function normalize(value: string): string {
}
describe('theme-import 模板 · key 集合与既有 builtin 主题一致', () => {
- it('TEMPLATE_TOKEN_IDS 与 github-dark 的 colors key 集合完全相同', () => {
- expect([...TEMPLATE_TOKEN_IDS].sort()).toEqual(Object.keys(githubDark.colors).sort());
+ it('TEMPLATE_TOKEN_IDS 覆盖 github-dark,并仅追加导入主题专用的 Switch token', () => {
+ const builtinIds = Object.keys(githubDark.colors);
+ expect(builtinIds.filter((id) => !TEMPLATE_TOKEN_IDS.includes(id))).toEqual([]);
+ expect(TEMPLATE_TOKEN_IDS.filter((id) => !builtinIds.includes(id)).sort()).toEqual([
+ 'switch-thumb-off',
+ 'switch-track-off',
+ ]);
});
it('模板 key 无重复', () => {
@@ -154,6 +167,58 @@ describe('theme-import 模板 · key 集合与既有 builtin 主题一致', () =
});
});
+describe.each([
+ [
+ 'light',
+ {
+ ...ATOM_ONE_LIGHT_PALETTE,
+ surface: rgb('#ffffff'),
+ elevated: rgb('#ffffff'),
+ elevatedSoft: rgb('#fafafa'),
+ hover: rgb('#f8f8f8'),
+ chip: rgb('#f7f7f7'),
+ border: rgb('#eeeeee'),
+ textSecondary: rgb('#f0f0f0'),
+ } satisfies ThemePalette,
+ ],
+ [
+ 'dark',
+ {
+ ...ONE_DARK_PRO_PALETTE,
+ surface: rgb('#000000'),
+ elevated: rgb('#050505'),
+ elevatedSoft: rgb('#050505'),
+ hover: rgb('#0a0a0a'),
+ chip: rgb('#0c0c0c'),
+ border: rgb('#111111'),
+ textSecondary: rgb('#101010'),
+ } satisfies ThemePalette,
+ ],
+] as const)('theme-import 模板 · %s 低对比度输入', (type, palette) => {
+ it('为关闭态 Switch 派生带余量的轨道与滑块色', () => {
+ const out = buildThemeColorsFromPalette(palette, type);
+ const track = rgb(out['switch-track-off']);
+ const thumb = rgb(out['switch-thumb-off']);
+
+ expect(out['switch-track-off']).not.toBe(normalize(toHex(palette.textSecondary)));
+ expect(contrastRatio(track, thumb), 'thumb x track')
+ .toBeGreaterThanOrEqual(SWITCH_DERIVATION_TARGET);
+
+ for (const surfaceId of [
+ 'surface',
+ 'surface-elevated',
+ 'surface-card-ivory',
+ 'surface-hover',
+ 'surface-hover-soft',
+ ]) {
+ expect(
+ contrastRatio(track, rgb(out[surfaceId])),
+ `track x ${surfaceId}`,
+ ).toBeGreaterThanOrEqual(SWITCH_DERIVATION_TARGET);
+ }
+ });
+});
+
describe.each([
['One Dark Pro', ONE_DARK_PRO_PALETTE, 'dark' as const, oneDarkPro],
['Atom One Light', ATOM_ONE_LIGHT_PALETTE, 'light' as const, atomOneLight],
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 36affb5e1f..c9a73c7319 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -153,6 +153,7 @@ export type IpcErrorCode =
| 'THEME_NOT_A_FILE' // 选中路径不是普通文件
| 'THEME_FILE_TOO_LARGE' // 超 4MB 上限
| 'THEME_UNSUPPORTED_FILE' // 无法识别为 VSCode / Obsidian 主题
+ | 'THEME_CONTRAST_UNSUPPORTED' // 主题色板无法满足控件对比度约束
| 'THEME_USES_INCLUDE' // VSCode 主题含 include(需基底才能完整解析)
| 'THEME_WRITE_ERROR' // 落盘失败(权限/磁盘)
| 'THEME_IMPORT_INTERNAL'; // 意外异常
@@ -280,6 +281,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'THEME_NOT_A_FILE',
'THEME_FILE_TOO_LARGE',
'THEME_UNSUPPORTED_FILE',
+ 'THEME_CONTRAST_UNSUPPORTED',
'THEME_USES_INCLUDE',
'THEME_WRITE_ERROR',
'THEME_IMPORT_INTERNAL',
diff --git a/apps/desktop/src/shared/theme-import/errors.ts b/apps/desktop/src/shared/theme-import/errors.ts
new file mode 100644
index 0000000000..0486bd3579
--- /dev/null
+++ b/apps/desktop/src/shared/theme-import/errors.ts
@@ -0,0 +1,10 @@
+/**
+ * 主题色板能够被解析,但无法满足 Cindy 导入契约时抛出的领域错误。
+ * Main adapter 会将它映射为稳定的 IPC 错误码;纯转换层不依赖 Electron/Main。
+ */
+export class UnsupportedThemePaletteError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'UnsupportedThemePaletteError';
+ }
+}
diff --git a/apps/desktop/src/shared/theme-import/index.ts b/apps/desktop/src/shared/theme-import/index.ts
index 9df72d5722..5919ceb7bc 100644
--- a/apps/desktop/src/shared/theme-import/index.ts
+++ b/apps/desktop/src/shared/theme-import/index.ts
@@ -6,6 +6,7 @@
*/
import { buildThemeColorsFromPalette } from './palette';
+import { UnsupportedThemePaletteError } from './errors';
import { stripProtectedTokens } from './protected-tokens';
import type {
ConvertedTheme,
@@ -16,6 +17,7 @@ import { collectObsidianVars, extractObsidianPalette } from './obsidian';
import { extractVsCodePalette, parseVsCodeThemeJson } from './vscode';
export type { ConvertedTheme, ThemeConversionResult } from './types';
+export { UnsupportedThemePaletteError };
export { TEMPLATE_TOKEN_IDS, buildThemeColorsFromPalette } from './palette';
export { isProtectedToken, stripProtectedTokens } from './protected-tokens';
@@ -114,11 +116,18 @@ export function convertObsidianTheme(
unresolved.push(`mode:${mode.type}`);
continue;
}
- const built = buildThemeColorsFromPalette(
- extracted.palette,
- extracted.type,
- extracted.markdown,
- );
+ let built: Record<string, string>;
+ try {
+ built = buildThemeColorsFromPalette(
+ extracted.palette,
+ extracted.type,
+ extracted.markdown,
+ );
+ } catch (error) {
+ if (!(error instanceof UnsupportedThemePaletteError)) throw error;
+ unresolved.push(`mode:${mode.type}`);
+ continue;
+ }
const { colors, skipped } = stripProtectedTokens(built);
themes.push({ name, type: extracted.type, colors });
resolvedRoles = Math.max(resolvedRoles, extracted.resolvedRoles);
diff --git a/apps/desktop/src/shared/theme-import/palette.ts b/apps/desktop/src/shared/theme-import/palette.ts
index a4d233dbe5..0bd4e32091 100644
--- a/apps/desktop/src/shared/theme-import/palette.ts
+++ b/apps/desktop/src/shared/theme-import/palette.ts
@@ -16,8 +16,9 @@
*
* ## 为什么用 allow-list
*
- * 模板产出这 108 个基础 key(源主题提供 Markdown 色时额外追加 `md-h1-fg`…
- * `md-h6-fg` / `md-strong-fg`)。这 7 个主题都没有 override `--login-*`、品牌红、
+ * 模板产出这 108 个 builtin 基础 key,并为不受约束的外部色板追加 2 个 Switch
+ * 安全 key(源主题提供 Markdown 色时再追加 `md-h1-fg`…`md-h6-fg` / `md-strong-fg`)。
+ * 这 7 个主题都没有 override `--login-*`、品牌红、
* `--destructive`、`--warning-accent`、`--status-bar-accent`、`--focus-ring`、
* `--diff-*`(DESIGN.md §10 / §16 的语义豁免族),照抄它们的 key 列表就自动守住了
* 豁免边界——比"先大量产出再过滤"安全。`protected-tokens.ts` 只作为回归断言的
@@ -26,11 +27,13 @@
import {
contrastRatio,
+ mix,
toHex,
toHslTriplet,
toRgbaString,
type Rgb,
} from './color';
+import { UnsupportedThemePaletteError } from './errors';
export type ThemeTypeName = 'light' | 'dark';
@@ -80,8 +83,8 @@ const MARKDOWN_HEADING_TOKENS = [
] as const;
/**
- * 模板产出的 108 个 token id。导出供测试断言"与 builtin 主题 key 集合一致",
- * 以及供 importer 统计命中数量。
+ * 模板产出的 108 个 builtin 基础 token,加 2 个导入主题专用的 Switch 安全 token。
+ * 导出供测试断言 allow-list 边界,以及供 importer 统计命中数量。
*/
export const TEMPLATE_TOKEN_IDS: readonly string[] = [
// ── Tier1 语义 slot(35) ──
@@ -183,6 +186,8 @@ export const TEMPLATE_TOKEN_IDS: readonly string[] = [
'settings-menu-bg-selected',
'settings-source-link',
'settings-theme-auto-dark',
+ 'switch-thumb-off',
+ 'switch-track-off',
'sidebar-action-icon',
'sidebar-item-active',
'splash-bg',
@@ -198,6 +203,48 @@ export const TEMPLATE_TOKEN_IDS: readonly string[] = [
const WHITE: Rgb = { r: 255, g: 255, b: 255 };
const BLACK: Rgb = { r: 0, g: 0, b: 0 };
+// 3:1 是非文字组件的合规底线;自动派生多留 0.2,避免表面微调或 hex 量化后掉线。
+const UNCHECKED_SWITCH_DERIVATION_TARGET = 3.2;
+const RGB_SEARCH_STEPS = 255;
+
+function minimumContrast(color: Rgb, against: readonly Rgb[]): number {
+ return Math.min(...against.map((other) => contrastRatio(color, other)));
+}
+
+/**
+ * 外部主题的 muted/comment 色不受 Cindy 约束,不能直接拿来当关闭态轨道。
+ * 保留已经合格的源色;否则分别向黑、白搜索首个合格的整数 RGB 色,并选择
+ * 改动更小的一侧。整数步进与最终 hex 精度一致,也避免多背景约束下的非单调误判。
+ */
+export function deriveUncheckedSwitchTrack(preferred: Rgb, against: readonly Rgb[]): Rgb {
+ if (minimumContrast(preferred, against) >= UNCHECKED_SWITCH_DERIVATION_TARGET) return preferred;
+
+ let best: { color: Rgb; distance: number; contrast: number } | null = null;
+ for (const target of [BLACK, WHITE]) {
+ for (let step = 1; step <= RGB_SEARCH_STEPS; step += 1) {
+ const candidate = mix(preferred, target, step / RGB_SEARCH_STEPS);
+ const candidateContrast = minimumContrast(candidate, against);
+ if (candidateContrast < UNCHECKED_SWITCH_DERIVATION_TARGET) continue;
+
+ const distance = (candidate.r - preferred.r) ** 2
+ + (candidate.g - preferred.g) ** 2
+ + (candidate.b - preferred.b) ** 2;
+ if (
+ best === null
+ || distance < best.distance
+ || (distance === best.distance && candidateContrast > best.contrast)
+ ) {
+ best = { color: candidate, distance, contrast: candidateContrast };
+ }
+ break;
+ }
+ }
+
+ if (best) return best.color;
+ throw new UnsupportedThemePaletteError(
+ 'Unable to derive unchecked Switch colors with 3.2:1 contrast',
+ );
+}
/**
* 把色板展开成 Cindy token map。`type` 决定 22 处 light / dark 分支——取值依据
@@ -263,6 +310,14 @@ export function buildThemeColorsFromPalette(
const quickIconBg = liftsOffSurface
? toHex(palette.surface)
: pick(toHex(palette.border), toHex(palette.chip));
+ const switchThumbOffRgb = pick(palette.surface, palette.elevated);
+ const switchTrackOff = toHex(deriveUncheckedSwitchTrack(palette.textSecondary, [
+ palette.surface,
+ palette.elevated,
+ palette.hover,
+ switchThumbOffRgb,
+ ]));
+ const switchThumbOff = toHex(switchThumbOffRgb);
const colors: Record<string, string> = {
// ── Tier1 语义 slot ──
@@ -373,6 +428,8 @@ export function buildThemeColorsFromPalette(
'settings-menu-bg-selected': chip,
'settings-source-link': linkColor,
'settings-theme-auto-dark': surface,
+ 'switch-thumb-off': switchThumbOff,
+ 'switch-track-off': switchTrackOff,
'sidebar-action-icon': textTertiaryHsl,
'sidebar-item-active': chipHsl,
'splash-bg': surfaceHsl,
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index f13fee504e..0e6d72a9fa 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -473,7 +473,7 @@ This section is the authoritative token-usage text; i18n rules for UI copy live
Settings → Appearance can import a VSCode color theme (`*.json` / jsonc) or an Obsidian `theme.css` and convert it into a local theme. Implementation: `apps/desktop/src/shared/theme-import/` (pure conversion) + `apps/desktop/src/main/local-themes/importer.ts` (dialog / read / write). Rules that govern it:
-- **One template, taken from the hand-ported community themes.** The seven ported themes under `apps/desktop/src/renderer/themes/builtin/` (one-dark-pro, github-dark, eclipse, material-ocean-hc, monokai-pro, atom-one-light, solarized-light) share a byte-identical key set of 108 tokens derived from 13 palette roles plus the optional light-only `inputBg` role (CREATE AGENT card/input background, e.g. Solarized base2; absent ⇒ collapses to `surface`). Within the template, when a light palette supplies an `inputBg` distinct from `surface` (e.g. Solarized base2 cards), CREATE AGENT `*-hover` and the resting `quick-card-icon-bg` lift to `surface` (icon drops back to `chip` on hover); otherwise `*-hover`=`hover` and `quick-card-icon-bg` is `border` in dark / `chip` in light — keeping default/hover/icon visually distinct in every theme. `control-bg-pressed` is `chip` in dark and `hover` in light. `send-btn-bg`/`send-btn-icon` use the inverse-neutral pair (`textPrimary`/`surface`), not the accent, because the shared send tokens also render 10–12px text that must clear 4.5:1. `apps/desktop/src/shared/theme-import/palette.ts` is that derivation, code-ified; `one-dark-pro.ts`'s header comment is the source-of-truth for which VSCode key feeds which role. The template is **allow-list only** — it emits exactly those 108 base ids, plus optional Markdown tokens (`md-h1-fg`…`md-h6-fg` / `md-strong-fg`) when the source theme provides heading or bold colors.
+- **One template, taken from the hand-ported community themes.** The seven ported themes under `apps/desktop/src/renderer/themes/builtin/` (one-dark-pro, github-dark, eclipse, material-ocean-hc, monokai-pro, atom-one-light, solarized-light) share a byte-identical key set of 108 tokens derived from 13 palette roles plus the optional light-only `inputBg` role (CREATE AGENT card/input background, e.g. Solarized base2; absent ⇒ collapses to `surface`). Within the template, when a light palette supplies an `inputBg` distinct from `surface` (e.g. Solarized base2 cards), CREATE AGENT `*-hover` and the resting `quick-card-icon-bg` lift to `surface` (icon drops back to `chip` on hover); otherwise `*-hover`=`hover` and `quick-card-icon-bg` is `border` in dark / `chip` in light — keeping default/hover/icon visually distinct in every theme. `control-bg-pressed` is `chip` in dark and `hover` in light. `send-btn-bg`/`send-btn-icon` use the inverse-neutral pair (`textPrimary`/`surface`), not the accent, because the shared send tokens also render 10–12px text that must clear 4.5:1. `apps/desktop/src/shared/theme-import/palette.ts` is that derivation, code-ified; `one-dark-pro.ts`'s header comment is the source-of-truth for which VSCode key feeds which role. The template is **allow-list only** — it emits those 108 base ids plus the imported-theme-only `switch-track-off` / `switch-thumb-off` safety pair. Because external muted/comment colors are unconstrained, the track keeps the source `textSecondary` only when it clears the 3.2:1 derivation target (above the 3:1 non-text floor) against the relevant surfaces and thumb; otherwise the converter takes the smaller passing correction along the source-to-black/source-to-white paths, or rejects the palette with the dedicated contrast error rather than reporting it as an unrecognized file or internal error. Existing local snapshots created before this pair existed are backfilled with the same 3.2:1 target at renderer load time only when both tokens are absent and the complete legacy semantic palette is parseable; if no track can satisfy the target, the runtime restores the pre-upgrade `border-default` track and `surface` thumb instead of falling through to unchecked aliases. Disk JSON and explicit user overrides are never changed. Optional Markdown tokens (`md-h1-fg`…`md-h6-fg` / `md-strong-fg`) are added when the source theme provides heading or bold colors.
- **Exemption families are never imported.** `--login-*`, brand red, `--destructive`, `--error-*`, `--warning-accent`, `--status-bar-accent`, `--focus-ring*`, `--diff-*`, shadows and overlays stay at their spec values under every imported theme (see the exemption table above and §16). `apps/desktop/src/shared/theme-import/protected-tokens.ts` enforces it as a second gate; the import report tells the user how many tokens were held back.
- **`-hsl` tokens are computed, not copied.** Both forms of a color must denote the same color, so the converter derives every HSL triplet from its hex via `toHslTriplet()`. (Note: a few hand-written builtin themes carry approximate HSL values — `github-dark`'s `SURFACE_BG_HSL` was copied off one-dark-pro. Those are left as-is; new imports are exact.)
- **Markdown text colors go through `--md-h1-fg`…`--md-h6-fg` / `--md-strong-fg`, and default to `inherit`.** Before these tokens existed, Markdown headings and bold text inherited their color from the container (`baseComponents` sets size/weight only). Defaulting to `var(--text-primary)` would have repainted headings inside blockquotes, tool cards and secondary-text regions, so the defaults are `inherit` — every built-in theme renders exactly as before. Imported themes fill them from Obsidian `--hN-color` / `--bold-color` or VSCode `markup.heading` / `markup.bold`. Guard: `themes/__tests__/markdownColorTokens.test.ts`.