Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持导入 VSCode / Obsidian 主题文件并转换为本地主题 (#532)
Lizie66f05f6c6b8
diff --git a/apps/desktop/src/main/local-themes/__tests__/importer.test.ts b/apps/desktop/src/main/local-themes/__tests__/importer.test.tsnew file mode 100644index 0000000000..fc55c9a86e--- /dev/null+++ b/apps/desktop/src/main/local-themes/__tests__/importer.test.ts@@ -0,0 +1,304 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import fs from 'node:fs';+import path from 'node:path';+import { mkdtempSync, realpathSync } from 'node:fs';+import { tmpdir } from 'node:os';++const osMock = vi.hoisted(() => ({ homedir: '' }));++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:os')>();+ return {+ ...actual,+ default: { ...actual, homedir: () => osMock.homedir },+ homedir: () => osMock.homedir,+ };+});++vi.mock('../../logger', () => ({+ createLogger: () => ({+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ }),+}));++import { dialog } from 'electron';++import { importExternalTheme } from '../importer';+import { loadLocalThemesSync, resetLocalThemesMigrationForTest } from '../loader';++const VSCODE_THEME = JSON.stringify({+ name: 'One Dark Pro',+ type: 'dark',+ colors: {+ 'editor.background': '#282c34',+ 'editor.foreground': '#abb2bf',+ 'sideBar.background': '#21252b',+ 'list.hoverBackground': '#2c313a',+ 'panel.border': '#3e4452',+ 'button.background': '#61afef',+ },+ tokenColors: [{ scope: 'comment', settings: { foreground: '#7f848e' } }],+});++const OBSIDIAN_THEME = `+/* Dual mode theme */+.theme-dark {+ --background-primary: #1e1e1e;+ --background-secondary: #252525;+ --text-normal: #dcddde;+ --interactive-accent: #8b6cef;+}+.theme-light {+ --background-primary: #ffffff;+ --background-secondary: #f5f5f5;+ --text-normal: #222222;+ --interactive-accent: #7b6cd9;+}+`;++describe('外部主题导入(main 侧编排)', () => {+ let home: string;+ let sourceDir: string;++ /** 让下一次文件对话框"选中"给定路径。 */+ function pickFile(filePath: string): void {+ vi.spyOn(dialog, 'showOpenDialog').mockResolvedValue({+ canceled: false,+ filePaths: [filePath],+ } as never);+ }++ function writeSource(name: string, content: string): string {+ const filePath = path.join(sourceDir, name);+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, content, 'utf8');+ return filePath;+ }++ beforeEach(() => {+ home = realpathSync(mkdtempSync(path.join(tmpdir(), 'theme-import-home-')));+ sourceDir = realpathSync(mkdtempSync(path.join(tmpdir(), 'theme-import-src-')));+ osMock.homedir = home;+ resetLocalThemesMigrationForTest();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(home, { recursive: true, force: true });+ fs.rmSync(sourceDir, { recursive: true, force: true });+ });++ it('用户取消对话框时不落盘', async () => {+ vi.spyOn(dialog, 'showOpenDialog').mockResolvedValue({+ canceled: true,+ filePaths: [],+ } as never);++ const result = await importExternalTheme();++ expect(result).toEqual({ canceled: true });+ expect(loadLocalThemesSync().themes).toEqual([]);+ });++ it('VSCode 主题落盘为可被 loader 读回的本地主题', async () => {+ pickFile(writeSource('OneDark-Pro.json', VSCODE_THEME));++ const result = await importExternalTheme();++ if (result.canceled) throw new Error('expected written result');+ expect(result.written).toHaveLength(1);+ expect(result.written[0]).toMatchObject({ name: 'One Dark Pro', type: 'dark' });+ expect(result.report.source).toBe('vscode');++ // 端到端:loader 能把产物解析成一个可用主题。+ const loaded = loadLocalThemesSync();+ expect(loaded.success).toBe(true);+ expect(loaded.diagnostics).toEqual([]);+ expect(loaded.themes).toHaveLength(1);+ expect(loaded.themes[0]).toMatchObject({+ id: 'one-dark-pro-local',+ name: 'One Dark Pro',+ type: 'dark',+ });+ expect(loaded.themes[0].colors.surface).toBe('#282c34');+ // 单产物不写 family(各自成家族,与老本地主题行为一致)。+ expect(loaded.themes[0].family).toBeUndefined();+ });++ it('Obsidian 双态 CSS 产出 light + dark 两个主题并共享 family', async () => {+ pickFile(writeSource('Minimal/theme.css', OBSIDIAN_THEME));++ const result = await importExternalTheme();++ if (result.canceled) throw new Error('expected written result');+ expect(result.written).toHaveLength(2);+ // 目录名兜底成主题名(`<vault>/.obsidian/themes/<名字>/theme.css`)。+ expect(result.written.every((w) => w.name === 'Minimal')).toBe(true);++ const loaded = loadLocalThemesSync();+ expect(loaded.diagnostics).toEqual([]);+ expect(loaded.themes).toHaveLength(2);+ const families = new Set(loaded.themes.map((t) => t.family));+ expect(families.size).toBe(1);+ expect([...families][0]).toBe('minimal');+ expect(loaded.themes.map((t) => t.type).sort()).toEqual(['dark', 'light']);+ });++ it('重复导入同一主题时 family 递增,两组产物都可见', async () => {+ const source = writeSource('Minimal/theme.css', OBSIDIAN_THEME);+ pickFile(source);+ await importExternalTheme();+ pickFile(source);+ await importExternalTheme();++ const loaded = loadLocalThemesSync();+ expect(loaded.themes).toHaveLength(4);+ expect(new Set(loaded.themes.map((t) => t.family))).toEqual(+ new Set(['minimal', 'minimal-2']),+ );+ });++ // 回归:family 判重曾只看显式 family 字段,漏了「无 family 的旧主题各自成家族」+ // 那一类,导致新导入的家族与旧主题撞键、变体被静默隐藏。+ it('已有同名旧本地主题(无 family)时,导入的家族键让位,不与之合并', async () => {+ const dir = path.join(home, '.cindy', 'themes');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'minimal.json'),+ JSON.stringify({ id: 'minimal', name: 'Old Minimal', type: 'dark', colors: {} }),+ 'utf8',+ );+ pickFile(writeSource('Minimal/theme.css', OBSIDIAN_THEME));++ const result = await importExternalTheme();++ if (result.canceled) throw new Error('expected written result');+ const loaded = loadLocalThemesSync();+ // 旧主题隐式家族键是 `minimal`,所以导入的两个产物必须让位到 `minimal-2`。+ const families = new Set(+ loaded.themes.filter((t) => t.family).map((t) => t.family),+ );+ expect(families).toEqual(new Set(['minimal-2']));+ // 旧主题原样保留。+ expect(loaded.themes.find((t) => t.id === 'minimal-local')?.name).toBe('Old Minimal');+ // 双态产物都在,没有被吸进旧主题的家族。+ expect(loaded.themes.filter((t) => t.family === 'minimal-2')).toHaveLength(2);+ });++ it('单产物同样走家族判重(不与已有显式 family 撞键)', async () => {+ const dir = path.join(home, '.cindy', 'themes');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'other.json'),+ JSON.stringify({+ id: 'other',+ name: 'Other',+ type: 'light',+ family: 'one-dark-pro',+ colors: {},+ }),+ 'utf8',+ );+ pickFile(writeSource('OneDark-Pro.json', VSCODE_THEME));++ const result = await importExternalTheme();++ if (result.canceled) throw new Error('expected written result');+ // 已有主题占了 `one-dark-pro` 这个家族键,单产物必须让位。+ expect(result.written[0].id).toBe('one-dark-pro-2');+ });++ // 回归:双态写到一半失败时若不回滚,目录里会留下一个孤立单态主题,与 UI 的+ // 「导入失败」提示矛盾,刷新后还会冒出来。+ it('双态导入第二个文件写失败时回滚第一个,不留孤立产物', async () => {+ pickFile(writeSource('Minimal/theme.css', OBSIDIAN_THEME));+ const realWriteFile = fs.promises.writeFile;+ let calls = 0;+ vi.spyOn(fs.promises, 'writeFile').mockImplementation(async (...args) => {+ calls += 1;+ if (calls === 2) throw new Error('ENOSPC: simulated disk full');+ return realWriteFile(...(args as Parameters<typeof realWriteFile>));+ });++ await expect(importExternalTheme()).rejects.toThrow('THEME_WRITE_ERROR');+ // 关键:第一个产物已被回滚,目录干净。+ expect(loadLocalThemesSync().themes).toEqual([]);+ });++ it('manifest.json 里的名字优先于目录名', async () => {+ const source = writeSource('some-folder/theme.css', OBSIDIAN_THEME);+ fs.writeFileSync(+ path.join(path.dirname(source), 'manifest.json'),+ JSON.stringify({ name: 'Things', version: '1.0.0' }),+ 'utf8',+ );+ pickFile(source);++ const result = await importExternalTheme();++ if (result.canceled) throw new Error('expected written result');+ expect(result.written.every((w) => w.name === 'Things')).toBe(true);+ });++ it('不是主题的 JSON 报 THEME_UNSUPPORTED_FILE 且不落盘', async () => {+ pickFile(writeSource('settings.json', '{"editor.fontSize": 14}'));++ await expect(importExternalTheme()).rejects.toThrow('THEME_UNSUPPORTED_FILE');+ expect(loadLocalThemesSync().themes).toEqual([]);+ });++ it('无法识别的扩展名报 THEME_UNSUPPORTED_FILE', async () => {+ pickFile(writeSource('README.md', '# hello'));++ await expect(importExternalTheme()).rejects.toThrow('THEME_UNSUPPORTED_FILE');+ });++ it('没有主题变量的 CSS 报 THEME_UNSUPPORTED_FILE', async () => {+ pickFile(writeSource('plain.css', '.foo { color: red; }'));++ await expect(importExternalTheme()).rejects.toThrow('THEME_UNSUPPORTED_FILE');+ });++ it('超大文件报 THEME_FILE_TOO_LARGE 而不读进内存', async () => {+ const big = `{"colors":{"editor.background":"#000000"},"_pad":"${'x'.repeat(4 * 1024 * 1024 + 16)}"}`;+ pickFile(writeSource('huge.json', big));++ await expect(importExternalTheme()).rejects.toThrow('THEME_FILE_TOO_LARGE');+ });++ it('选中的是目录时报 THEME_NOT_A_FILE', async () => {+ pickFile(sourceDir);++ await expect(importExternalTheme()).rejects.toThrow('THEME_NOT_A_FILE');+ });++ it('产物不含任何语义豁免族 token', async () => {+ pickFile(writeSource('OneDark-Pro.json', VSCODE_THEME));+ await importExternalTheme();++ const loaded = loadLocalThemesSync();+ const ids = Object.keys(loaded.themes[0].colors);+ expect(ids.filter((id) => id.startsWith('login-'))).toEqual([]);+ expect(ids.filter((id) => id.startsWith('diff-'))).toEqual([]);+ expect(ids).not.toContain('destructive');+ expect(ids).not.toContain('warning-accent');+ expect(ids).not.toContain('status-bar-accent');+ expect(ids).not.toContain('focus-ring');+ });++ it('对话框只放行主题文件扩展名', async () => {+ const spy = vi.spyOn(dialog, 'showOpenDialog').mockResolvedValue({+ canceled: true,+ filePaths: [],+ } as never);++ await importExternalTheme();++ const options = spy.mock.calls[0]?.[0] as Electron.OpenDialogOptions;+ expect(options.properties).toEqual(['openFile']);+ expect(options.filters?.[0]?.extensions).toEqual(['json', 'jsonc', 'css']);+ });+});diff --git a/apps/desktop/src/main/local-themes/importer.ts b/apps/desktop/src/main/local-themes/importer.tsnew file mode 100644index 0000000000..d6b726235b--- /dev/null+++ b/apps/desktop/src/main/local-themes/importer.ts@@ -0,0 +1,268 @@+/**+ * 外部主题导入(VSCode `*.json` / Obsidian `theme.css`)→ 本地主题 JSON。+ *+ * 这里只做 IO 与编排:弹原生文件对话框、读字节、调 `shared/theme-import` 的纯+ * 函数转换、复用 `writeLocalTheme()` 落盘。转换规则本身见+ * `shared/theme-import/palette.ts`。+ *+ * 安全边界:**对话框由 main 自己弹、文件由 main 自己读**,Renderer 全程拿不到+ * 也传不进任何路径(`docs/dev-rules/electron-security-and-process-boundaries.md`+ * §5:不把「Renderer 传来一个绝对路径」视为授权)。+ */++import fs from 'node:fs';+import path from 'node:path';+import { dialog, type BrowserWindow } from 'electron';++import { isLocalThemeId, LOCAL_THEME_SUFFIX } from '../../shared/local-themes';+import {+ convertObsidianTheme,+ convertVsCodeTheme,+ detectImportSource,+ themeFamilyId,+} from '../../shared/theme-import';+import type {+ ConvertedTheme,+ ImportedThemeFile,+ ImportedThemeFileInternal,+ LocalThemeImportResult,+ ThemeConversionResult,+} from '../../shared/theme-import/types';+import { createLogger } from '../logger';+import { throwIpcError } from '../utils/ipcValidate';+import { loadLocalThemesSync } from './loader';+import { writeLocalTheme } from './writer';++const log = createLogger('local-themes/importer');++/**+ * 单文件字节上限。Obsidian 主题 CSS 动辄上百 KB(Minimal 一类含大量选择器),+ * 4MB 足够宽松,同时挡住"选错文件把整个日志/数据库读进内存"。+ */+const MAX_THEME_FILE_BYTES = 4 * 1024 * 1024;++const FAMILY_SUFFIX_LIMIT = 99;++function normalizeError(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/**+ * 已被占用的家族键,**含隐式的「每文件自成家族」那一类**。+ *+ * renderer 侧 `buildLocalFamilies()` 的分组键是 `family ?? theme.id`(都带+ * `-local` 后缀)。所以判重必须把两类都算进来:只收显式 `family` 的话,用户已有+ * 一个 id 为 `minimal` 的旧本地主题时,导入同名双态主题会拿到 family `minimal`+ * → 分组键 `minimal-local` 与旧主题撞车 → 同类型变体只保留先加载的那个,新导入+ * 的方案在「导入成功」提示之后仍然看不见。+ */+function usedFamilyKeys(): Set<string> {+ const used = new Set<string>();+ const payload = loadLocalThemesSync();+ if (!payload.success) return used;+ for (const theme of payload.themes) {+ // 每个主题的 normalized ID 都要保留:即使有 explicit family,其 ID 被复用+ // 仍会导致 writeLocalTheme 的文件名冲突或 loader 的 ID 去重丢弃后者。+ const normalizedId = isLocalThemeId(theme.id)+ ? theme.id.slice(0, -LOCAL_THEME_SUFFIX.length)+ : theme.id;+ used.add(normalizedId);+ // If the ID looks like `<slug>-light` or `<slug>-dark`, also reserve the+ // base slug so paired imports don't generate colliding variant IDs.+ const variantMatch = normalizedId.match(/^(.+)-(light|dark)$/);+ if (variantMatch) used.add(variantMatch[1]);+ if (theme.family) {+ used.add(theme.family);+ }+ }+ return used;+}++/**+ * 挑一个未占用的家族键。重复导入同一个主题时会拿到 `minimal` / `minimal-2`,+ * 两组产物各自成家族、都能在设置里看到。+ */+function pickFamilyId(slug: string, used: Set<string>): string {+ for (let i = 1; i <= FAMILY_SUFFIX_LIMIT; i += 1) {+ const candidate = i === 1 ? slug : `${slug}-${i}`;+ if (!used.has(candidate)) return candidate;+ }+ return `${slug}-${Date.now()}`;+}++/** Obsidian 主题目录里的 manifest.json 带更规范的展示名。 */+function readObsidianManifestName(filePath: string): string | null {+ try {+ const manifestPath = path.join(path.dirname(filePath), 'manifest.json');+ // 先 stat 再读:避免巨大文件、特殊设备文件阻塞主进程。+ const stat = fs.statSync(manifestPath);+ if (!stat.isFile() || stat.size > MAX_THEME_FILE_BYTES) return null;+ const raw = fs.readFileSync(manifestPath, 'utf8');+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {+ const name = (parsed as { name?: unknown }).name;+ if (typeof name === 'string' && name.trim().length > 0) return name.trim();+ }+ } catch {+ // 没有 manifest 或格式不对都无所谓——回退到目录/文件名。+ }+ return null;+}++/** 源文件没有可用名字时的兜底展示名。 */+function fallbackNameFor(filePath: string, source: 'vscode' | 'obsidian'): string {+ const base = path.basename(filePath, path.extname(filePath));+ if (source === 'obsidian' && /^theme(\.dark|\.light)?$/i.test(base)) {+ // `<vault>/.obsidian/themes/<主题名>/theme.css` —— 目录名才是主题名。+ const dirName = path.basename(path.dirname(filePath));+ if (dirName && dirName !== '.' && dirName.toLowerCase() !== 'themes') return dirName;+ }+ return base;+}++function convert(filePath: string, content: string): ThemeConversionResult | null {+ const source = detectImportSource(filePath);+ if (source === null) return null;+ if (source === 'vscode') {+ return convertVsCodeTheme(content, fallbackNameFor(filePath, 'vscode'));+ }+ const name = readObsidianManifestName(filePath) ?? fallbackNameFor(filePath, 'obsidian');+ return convertObsidianTheme(content, name);+}++/**+ * 回滚已落盘的产物。双态导入写到一半失败时必须清干净:否则 UI 报「导入失败」而+ * 目录里留着一个孤立的单态主题,刷新后它会冒出来,用户重试又生成一份,越攒越乱。+ * best-effort——删不掉只 warn,不把回滚失败盖掉原始错误。+ */+async function rollbackWritten(written: ImportedThemeFileInternal[]): Promise<void> {+ for (const item of written) {+ try {+ await fs.promises.unlink(item.path);+ } catch (error) {+ log.warn(`Failed to roll back '${item.path}': ${normalizeError(error)}`);+ }+ }+}++const MAX_DISPLAY_NAME_LENGTH = 100;++function boundDisplayName(name: string): string {+ const trimmed = name.trim();+ if (trimmed.length <= MAX_DISPLAY_NAME_LENGTH) return trimmed;+ return `${trimmed.slice(0, MAX_DISPLAY_NAME_LENGTH).trimEnd()}…`;+}++async function writeConverted(+ themes: ConvertedTheme[],+): Promise<{ written: ImportedThemeFileInternal[]; error?: string }> {+ const pair = themes.length > 1;+ const used = usedFamilyKeys();+ const familyKey = pickFamilyId(themeFamilyId(themes[0].name), used);+ // For paired imports, also reserve the generated variant IDs.+ if (pair) {+ used.add(familyKey);+ used.add(`${familyKey}-light`);+ used.add(`${familyKey}-dark`);+ }+ const written: ImportedThemeFileInternal[] = [];+ for (const theme of themes) {+ const baseId = pair ? `${familyKey}-${theme.type}` : familyKey;+ const displayName = boundDisplayName(theme.name);+ const result = await writeLocalTheme({+ baseId,+ theme: {+ id: baseId,+ name: displayName,+ type: theme.type,+ ...(pair ? { family: familyKey } : {}),+ colors: theme.colors,+ },+ });+ if (!result.success) {+ await rollbackWritten(written);+ return { written: [], error: result.error };+ }+ written.push({+ path: result.path,+ id: result.finalId,+ name: displayName,+ type: theme.type,+ });+ }+ return { written };+}++export interface ImportThemeDeps {+ /** 对话框的父窗口;拿不到时无模态弹出。 */+ parentWindow?: BrowserWindow | null;+}++/**+ * 走完「选文件 → 转换 → 落盘」。返回结构里如实带上转换报告,让 UI 能告诉用户+ * 哪些东西没跟过来。任何一步失败都返回 `success: false` 而不抛。+ */+export async function importExternalTheme(+ deps: ImportThemeDeps = {},+): Promise<LocalThemeImportResult> {+ try {+ const options: Electron.OpenDialogOptions = {+ properties: ['openFile'],+ filters: [+ { name: 'Theme (*.json, *.jsonc, *.css)', extensions: ['json', 'jsonc', 'css'] },+ { name: 'VSCode (*.json, *.jsonc)', extensions: ['json', 'jsonc'] },+ { name: 'Obsidian (*.css)', extensions: ['css'] },+ ],+ };+ const picked = deps.parentWindow+ ? await dialog.showOpenDialog(deps.parentWindow, options)+ : await dialog.showOpenDialog(options);+ if (picked.canceled || picked.filePaths.length === 0) {+ return { canceled: true };+ }+ const filePath = picked.filePaths[0];++ const stat = await fs.promises.stat(filePath);+ if (!stat.isFile()) {+ throwIpcError('THEME_NOT_A_FILE', 'selected path is not a regular file');+ }+ if (stat.size > MAX_THEME_FILE_BYTES) {+ throwIpcError('THEME_FILE_TOO_LARGE', `file exceeds ${MAX_THEME_FILE_BYTES} bytes`);+ }+ const content = await fs.promises.readFile(filePath, 'utf8');++ const converted = convert(filePath, content);+ if (!converted) {+ throwIpcError('THEME_UNSUPPORTED_FILE', 'file is not a recognized VSCode or Obsidian theme');+ }+ if (converted.themes.length === 0) {+ const hasInclude = converted.report.unresolved.some((u) => u.startsWith('include:'));+ if (hasInclude) {+ throwIpcError('THEME_USES_INCLUDE', 'theme uses include and cannot be fully parsed standalone');+ }+ throwIpcError('THEME_UNSUPPORTED_FILE', 'no usable color palette could be extracted');+ }++ const { written, error } = await writeConverted(converted.themes);+ if (error) {+ log.warn(`Failed to write imported theme: ${error}`);+ throwIpcError('THEME_WRITE_ERROR', 'failed to persist theme file');+ }+ log.info(+ `Imported ${written.length} theme(s) from ${converted.report.source}: `+ + written.map((w) => w.id).join(', '),+ );+ const safeWritten: ImportedThemeFile[] = written.map(({ id, name, type }) => ({ id, name, type }));+ return {+ canceled: false,+ written: safeWritten,+ report: converted.report,+ };+ } catch (error) {+ // Re-throw IPC errors from throwIpcError() (already typed and safe for renderer).+ if (error instanceof Error && 'code' in error) throw error;+ 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/main/local-themes/loader.ts b/apps/desktop/src/main/local-themes/loader.tsindex 9d44e26e45..fac7f212c3 100644--- a/apps/desktop/src/main/local-themes/loader.ts+++ b/apps/desktop/src/main/local-themes/loader.ts@@ -22,6 +22,8 @@ interface LocalThemeJson {id: string;name: string;type: 'light' | 'dark';+ /** 可选家族键,见 shared/local-themes.ts 的 LocalThemeWire.family。 */+ family?: string;colors: Record<string, string>;brand?: LocalThemeBrandConfig;}@@ -134,10 +136,16 @@ function parseLocalThemeJson(raw: unknown): LocalThemeJson {}const brand = parseBrand(raw.brand);+ // family 只认非空字符串;缺省/空白一律视为"不配对"(每个文件各自成家族),+ // 保持引入该字段前的行为。+ const family = typeof raw.family === 'string' && raw.family.trim().length > 0+ ? raw.family.trim()+ : undefined;return {id,name,type: raw.type,+ ...(family ? { family } : {}),colors,...(brand ? { brand } : {}),};diff --git a/apps/desktop/src/main/local-themes/register.ts b/apps/desktop/src/main/local-themes/register.tsindex fe06fb9faa..0dc3d0bfa7 100644--- a/apps/desktop/src/main/local-themes/register.ts+++ b/apps/desktop/src/main/local-themes/register.ts@@ -1,6 +1,8 @@-import { ipcMain } from 'electron';+import { BrowserWindow, ipcMain } from 'electron';import type { LocalThemeWriteRequest } from '../../shared/local-themes';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { importExternalTheme } from './importer';import { loadLocalThemes, loadLocalThemesSync } from './loader';import { openLocalThemesDir, writeLocalTheme } from './writer';@@ -13,4 +15,13 @@ export function registerLocalThemesIpc(): void {ipcMain.handle('local-themes:write', async (_event, req: LocalThemeWriteRequest) =>writeLocalTheme(req));ipcMain.handle('local-themes:open-dir', async () => openLocalThemesDir());+ // 导入会弹原生文件对话框并读取用户选中的任意路径,是新增的文件访问能力,+ // 因此显式过来源闸(只允许 Cindy 自有顶层页面发起);对话框与读文件都在 main+ // 侧完成,Renderer 拿不到也传不进路径。+ ipcMain.handle('local-themes:import', async (event) => {+ assertTrustedAppRendererEvent(event);+ return importExternalTheme({+ parentWindow: BrowserWindow.fromWebContents(event.sender),+ });+ });}diff --git a/apps/desktop/src/main/local-themes/writer.ts b/apps/desktop/src/main/local-themes/writer.tsindex c6e10b5a65..5e56693c1e 100644--- a/apps/desktop/src/main/local-themes/writer.ts+++ b/apps/desktop/src/main/local-themes/writer.ts@@ -50,7 +50,17 @@ export async function writeLocalTheme(req: LocalThemeWriteRequest): Promise<Locaconst themeJson = { ...req.theme, id: slot.finalId };const filePath = path.join(dir, slot.filename);- await fs.promises.writeFile(filePath, `${JSON.stringify(themeJson, null, 2)}\n`, 'utf8');+ // Write to a unique temp path then rename — atomic on most filesystems.+ // The random suffix prevents races between concurrent writes to the same slot.+ const tmpPath = `${filePath}.${process.pid}-${Date.now()}.tmp`;+ try {+ await fs.promises.writeFile(tmpPath, `${JSON.stringify(themeJson, null, 2)}\n`, 'utf8');+ await fs.promises.rename(tmpPath, filePath);+ } catch (writeError) {+ // Clean up any partial temp file left behind by a failed write.+ try { await fs.promises.unlink(tmpPath); } catch { /* best-effort */ }+ throw writeError;+ }log.info(`Wrote local theme to ${filePath}`);return { success: true, path: filePath, finalId: slot.finalId };} catch (error) {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 979f93cc4f..a17b9119d7 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -45,6 +45,7 @@ import type {LocalThemeWriteRequest,LocalThemeWriteResult,} from '../shared/local-themes';+import type { LocalThemeImportResult } from '../shared/theme-import/types';import { DEFAULT_LOCALE, SUPPORTED_LOCALES, type SupportedLocale } from '../shared/locale';import {MODEL_ACCESS_STATUS_CHANNEL,@@ -744,6 +745,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('local-themes:write', req),openDir: (): Promise<LocalThemeOpenDirResult> =>ipcRenderer.invoke('local-themes:open-dir'),+ // 导入 VSCode / Obsidian 主题文件。对话框与读文件都在 main 侧,这里不接受+ // 任何路径参数。失败走 IPC 错误协议(reject,renderer 用 extractIpcError 解码)。+ importExternal: (): Promise<LocalThemeImportResult> =>+ ipcRenderer.invoke('local-themes:import') as Promise<LocalThemeImportResult>,},// RSB terminal tab(PTY 后端 + xterm.js)diff --git a/apps/desktop/src/renderer/__tests__/markdownHeadingTokens.test.ts b/apps/desktop/src/renderer/__tests__/markdownHeadingTokens.test.tsnew file mode 100644index 0000000000..9fcb2eba8b--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/markdownHeadingTokens.test.ts@@ -0,0 +1,84 @@+/**+ * markdownHeadingTokens.test.ts+ * ---------------------------------------------------------------------------+ * Markdown 标题 / 加粗接入颜色 token 后的「字体与观感零影响」守卫。+ *+ * 为支持外部主题导入(Obsidian `--hN-color` / VSCode `markup.heading`),+ * `baseComponents` 的 h1–h6 与 strong 接上了 `--md-*-fg` token。风险是有人顺手+ * 在这些 renderer 上加字号 / 字重 / 间距,或把 h1–h3 原有的排版 class 改掉 ——+ * 那会静默改变现有全部主题下的正文观感,typecheck 与 lint 都拦不住。+ *+ * 因此这里做 source-contract 锚定(与 markdownStrikethrough.test.ts 同思路):+ * 1. h1–h3 的排版 class 逐字冻结(只允许追加颜色 token)+ * 2. h4–h6 与 strong 只允许带颜色 class —— 不得出现任何 text-<n> / font-* /+ * my-* / leading-* 排版类+ *+ * 与 `themes/__tests__/markdownColorTokens.test.ts`(token 默认值恒为 `inherit`、+ * 无内置主题 override)合起来即完整证明:默认主题下这些元素的渲染结果与引入+ * token 之前等价。+ */++import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const SOURCE = readFileSync(+ resolve(__dirname, '../components/chat/MarkdownRenderer.tsx'),+ 'utf8',+);++/** 取 `<tag className="...">` 里的 class 串(baseComponents 里每个 tag 只出现一次)。 */+function classNameFor(tag: string): string {+ const match = new RegExp(`<${tag} className="([^"]*)"`).exec(SOURCE);+ if (!match) throw new Error(`no <${tag} className="..."> found in MarkdownRenderer.tsx`);+ return match[1];+}++/** 排版相关的 class(字号 / 字重 / 行高 / 外边距)。 */+const TYPOGRAPHY_CLASS = /^(text-\d|text-\[\d|font-|leading-|my-|mt-|mb-|tracking-)/;++describe('Markdown 标题 · h1–h3 排版 class 冻结', () => {+ it.each([+ ['h1', 'my-3 text-20 leading-[1.4] font-medium', '--md-h1-fg'],+ ['h2', 'my-3 text-18 leading-[1.556] font-medium', '--md-h2-fg'],+ ['h3', 'my-2 text-16 leading-[1.5] font-medium', '--md-h3-fg'],+ ])('%s 保持原排版并只追加颜色 token', (tag, typography, token) => {+ expect(classNameFor(tag)).toBe(`${typography} text-[var(${token})]`);+ });+});++describe('Markdown 标题 · h4–h6 与 strong 只带颜色', () => {+ it.each([+ ['h4', '--md-h4-fg'],+ ['h5', '--md-h5-fg'],+ ['h6', '--md-h6-fg'],+ ['strong', '--md-strong-fg'],+ ])('%s 的 class 只有颜色 token', (tag, token) => {+ expect(classNameFor(tag)).toBe(`text-[var(${token})]`);+ });++ it.each(['h4', 'h5', 'h6', 'strong'])(+ '%s 不引入任何字号 / 字重 / 行高 / 间距 class(引入前它们走原生继承)',+ (tag) => {+ const offenders = classNameFor(tag)+ .split(/\s+/)+ .filter((c) => TYPOGRAPHY_CLASS.test(c));+ expect(offenders).toEqual([]);+ },+ );+});++describe('Markdown 标题 · 颜色一律走 token,不出现硬编码色值', () => {+ it.each(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'strong'])(+ '%s 不出现 hex / rgb 硬编码(DESIGN.md §10 token 规则)',+ (tag) => {+ expect(classNameFor(tag)).not.toMatch(/#[0-9a-fA-F]{3,8}|rgba?\(/);+ },+ );++ it('doc-mode 包装仍覆盖 h1–h6(h4–h6 现在有 base renderer 了)', () => {+ for (const tag of ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) {+ expect(SOURCE).toContain(`${tag}: wrapWithSourceLine('${tag}', baseComponents.${tag})`);+ }+ });+});diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsxindex f2b14fe003..fd6fda3431 100644--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx@@ -563,14 +563,36 @@ const baseComponents: Components = {// components object).// Headings+ //+ // 颜色走 --md-hN-fg token(默认值 `inherit`,见 themes/colors.ts):默认主题下与+ // 引入 token 前逐像素一致,外部导入的主题(Obsidian --hN-color / VSCode+ // markup.heading)才会把它染成分级色。字号字重不受 token 影响。h1({ children, ...props }) {- return <h1 className="my-3 text-20 leading-[1.4] font-medium" {...props}>{children}</h1>;+ return <h1 className="my-3 text-20 leading-[1.4] font-medium text-[var(--md-h1-fg)]" {...props}>{children}</h1>;},h2({ children, ...props }) {- return <h2 className="my-3 text-18 leading-[1.556] font-medium" {...props}>{children}</h2>;+ return <h2 className="my-3 text-18 leading-[1.556] font-medium text-[var(--md-h2-fg)]" {...props}>{children}</h2>;},h3({ children, ...props }) {- return <h3 className="my-2 text-16 leading-[1.5] font-medium" {...props}>{children}</h3>;+ return <h3 className="my-2 text-16 leading-[1.5] font-medium text-[var(--md-h3-fg)]" {...props}>{children}</h3>;+ },+ // h4-h6 此前没有 renderer(走 react-markdown 默认的裸 tag,字号字重由 Tailwind+ // preflight 归一成继承)。这里只补颜色 class,刻意不加字号/字重/间距 —— 保持+ // 原有观感不变。+ h4({ children, ...props }) {+ return <h4 className="text-[var(--md-h4-fg)]" {...props}>{children}</h4>;+ },+ h5({ children, ...props }) {+ return <h5 className="text-[var(--md-h5-fg)]" {...props}>{children}</h5>;+ },+ h6({ children, ...props }) {+ return <h6 className="text-[var(--md-h6-fg)]" {...props}>{children}</h6>;+ },++ // 加粗:同上,只接颜色 token。font-weight 仍由 Tailwind preflight 的+ // `b, strong { font-weight: bolder }` 提供,这里不覆盖。+ strong({ children, ...props }) {+ return <strong className="text-[var(--md-strong-fg)]" {...props}>{children}</strong>;},// Blockquote@@ -601,10 +623,10 @@ const baseComponents: Components = {* chat 调用方不传 prop, 这里整个函数永远不会运行 → chat 路径零开销零行为变化。** 实现:- * - 已有 base renderer (h1-h3 / p / pre / table / ul / ol / blockquote / hr):+ * - 已有 base renderer (h1-h6 / p / pre / table / ul / ol / blockquote / hr):* 把 lineAttr merge 进 props 后透传给 base 函数。base 内部 spread props 时* data-source-line 自然落到对应 DOM 节点上。- * - base 没有的 (h4-h6 / li): 直接 createElement 渲染原生 tag。+ * - base 没有的 (li): 直接 createElement 渲染原生 tag。*/type BlockTag = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p' | 'pre' | 'table' | 'ul' | 'ol' | 'li' | 'blockquote' | 'hr';diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsxindex 128a19ab6e..60c7c2b267 100644--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx@@ -1,6 +1,16 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { Sun, Moon, Monitor, ChevronDown, Check, Copy, FolderOpen, RefreshCw } from 'lucide-react';+import {+ Sun,+ Moon,+ Monitor,+ ChevronDown,+ Check,+ Copy,+ FolderOpen,+ Import as ImportIcon,+ RefreshCw,+} from 'lucide-react';import type { LucideIcon } from 'lucide-react';import { basename, cn } from '@/lib/utils';@@ -29,10 +39,21 @@ import { isLocalThemeId } from '../../../shared/local-themes';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { Tip } from '@/components/ui/tooltip';import { Slider } from '@/components/ui/slider';+import { extractIpcError } from '@/utils/ipcError';import { FontFamilyPicker, type FontPreset } from './FontFamilyPicker';const log = createLogger('settings/AppearanceSection');+/** IPC 错误码 → 专门文案;未列出的码落到通用 importFailed。 */+const IMPORT_ERROR_KEYS: Record<string, string> = {+ THEME_UNSUPPORTED_FILE: 'settings.appearance.localThemes.importUnsupported',+ THEME_USES_INCLUDE: 'settings.appearance.localThemes.importUsesInclude',+ THEME_NOT_A_FILE: 'settings.appearance.localThemes.importNotAFile',+ THEME_FILE_TOO_LARGE: 'settings.appearance.localThemes.importTooLarge',+ THEME_WRITE_ERROR: 'settings.appearance.localThemes.importWriteError',+ THEME_IMPORT_INTERNAL: 'settings.appearance.localThemes.importInternalError',+};+type ThemeOption = 'light' | 'dark' | 'system';const THEME_OPTIONS: ThemeOption[] = ['light', 'dark', 'system'];@@ -376,6 +397,46 @@ export function AppearanceSection() {);}, [familyId, t, theme]);+ const handleImport = useCallback(async () => {+ let result;+ try {+ result = await window.electronAPI.localThemes.importExternal();+ } catch (err) {+ const ipcErr = extractIpcError(err);+ const key = ipcErr ? IMPORT_ERROR_KEYS[ipcErr.code] : undefined;+ toast.error(+ key+ ? t(key)+ : t('settings.appearance.localThemes.importFailed', { error: ipcErr?.code ?? 'UNKNOWN' }),+ );+ return;+ }+ if (result.canceled) return;+ await refreshLocalThemes();+ const name = result.written[0]?.name ?? '';+ const skipped = result.report.skippedProtected;+ const unresolved = result.report.unresolved.length;+ const derived = result.report.derivedRoles.length;+ if (skipped > 0 || unresolved > 0 || derived > 0) {+ toast.success(+ t('settings.appearance.localThemes.importPartial', {+ name,+ themeCount: result.written.length,+ skipped,+ unresolved,+ derived,+ }),+ );+ return;+ }+ toast.success(+ t('settings.appearance.localThemes.importSuccess', {+ name,+ themeCount: result.written.length,+ }),+ );+ }, [t]);+const handleOpenDir = useCallback(async () => {const result = await window.electronAPI.localThemes.openDir();if (!result.success) {@@ -529,6 +590,11 @@ export function AppearanceSection() {label={t('settings.appearance.localThemes.export')}onClick={() => { void handleExport(); }}/>+ <LocalThemeIconButton+ icon={ImportIcon}+ label={t('settings.appearance.localThemes.import')}+ onClick={() => { void handleImport(); }}+ /><LocalThemeIconButtonicon={FolderOpen}label={t('settings.appearance.localThemes.openDir')}diff --git a/apps/desktop/src/renderer/hooks/useTheme.ts b/apps/desktop/src/renderer/hooks/useTheme.tsindex 46084cb7b9..563a533518 100644--- a/apps/desktop/src/renderer/hooks/useTheme.ts+++ b/apps/desktop/src/renderer/hooks/useTheme.ts@@ -1,13 +1,13 @@-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';+import { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useState } from 'react';import { createElement, type ReactNode } from 'react';import {DEFAULT_FAMILY_ID,findFamilyByThemeId,- getFamily,resolveFamilyVariant,tryGetFamily,} from '../themes/families';+import { onLocalThemesChange } from '../themes/local-themes';import { themeService } from '../themes/theme-service';import type { ThemeType } from '../themes/types';@@ -227,6 +227,20 @@ export function ThemeProvider({ children }: { children: ReactNode }) {? false: window.matchMedia(PREFERS_DARK_QUERY).matches,);+ // Invalidate memos that depend on family membership when local themes change.+ // Read latest values from storage to avoid closure staleness races.+ const [localThemeRev, bumpLocalThemeRev] = useReducer((n: number) => n + 1, 0);+ useEffect(() => onLocalThemesChange(() => {+ let rawFamily: string | null = null;+ try { rawFamily = localStorage.getItem(FAMILY_KEY); } catch { /* ok */ }+ if (rawFamily && !tryGetFamily(rawFamily)) {+ const fallback = DEFAULT_FAMILY_ID;+ setFamilyIdState(fallback);+ try { localStorage.setItem(FAMILY_KEY, fallback); } catch { /* ok */ }+ }+ bumpLocalThemeRev();+ applyThemeClass(getStoredTheme(), true);+ }), []);const setTheme = useCallback((next: Theme) => {setThemeState(next);@@ -314,11 +328,13 @@ export function ThemeProvider({ children }: { children: ReactNode }) {}, [familyId, theme, systemPrefersDark]);const fallbackFromType = useMemo<ThemeType | null>(() => {- const family = getFamily(familyId);+ void localThemeRev;+ const family = tryGetFamily(familyId);+ if (!family) return null;const isDarkRequested = theme === 'dark' || (theme === 'system' && systemPrefersDark);const requestedType: ThemeType = isDarkRequested ? 'dark' : 'light';return family[requestedType] === null ? requestedType : null;- }, [familyId, theme, systemPrefersDark]);+ }, [familyId, theme, systemPrefersDark, localThemeRev]);return createElement(ThemeContext.Provider,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 1509beff61..68288b73b2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -356,10 +356,20 @@"localThemes": {"title": "Local themes","export": "Create local copy",+ "import": "Import VSCode / Obsidian theme","openDir": "Open themes folder","refresh": "Refresh","exportSuccess": "Created {{file}}. Replace the example image paths, save, then click \"Refresh\".","exportFailed": "Export failed: {{error}}",+ "importSuccess": "Imported {{name}} ({{themeCount}} variant(s)). Pick it in the theme list above.",+ "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.",+ "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.",+ "importWriteError": "Could not save the theme. Check disk space and permissions.",+ "importInternalError": "The file could not be read or processed. Try selecting it again.","openDirFailed": "Failed to open folder: {{error}}","refreshed": "Local themes refreshed"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c9a97d9954..8a7011964a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -356,10 +356,20 @@"localThemes": {"title": "ローカルテーマ","export": "ローカルコピーを作成",+ "import": "VSCode / Obsidian テーマをインポート","openDir": "テーマフォルダを開く","refresh": "更新","exportSuccess": "{{file}} を生成しました。画像のサンプルパスを書き換えて保存し、「更新」を押してください。","exportFailed": "エクスポートに失敗しました: {{error}}",+ "importSuccess": "{{name}}({{themeCount}} 種類)をインポートしました。上のテーマ一覧から選べます。",+ "importPartial": "{{name}}({{themeCount}} 種類)をインポートしました。意味を持つ色 {{skipped}} 件は規約どおり変更せず、{{unresolved}} 件は値を読み取れずスキップ、{{derived}} 件は近似色から推定しました。",+ "importFailed": "インポートに失敗しました: {{error}}",+ "importUnsupported": "このファイルは VSCode または Obsidian のテーマとして認識できません。",+ "importUsesInclude": "この VSCode テーマは include で配色を継承しているため、単独ではインポートできません。",+ "importNotAFile": "フォルダではなくファイルを選択してください。",+ "importTooLarge": "ファイルが大きすぎるため、テーマとしてインポートできません。",+ "importWriteError": "テーマを保存できませんでした。ディスク容量と権限をご確認ください。",+ "importInternalError": "ファイルを読み込めませんでした。もう一度選択してください。","openDirFailed": "フォルダを開けませんでした: {{error}}","refreshed": "ローカルテーマを更新しました"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ffde6bbb31..13123a3e8c 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -356,10 +356,20 @@"localThemes": {"title": "로컬 테마","export": "로컬 복사본 만들기",+ "import": "VSCode / Obsidian 테마 가져오기","openDir": "테마 폴더 열기","refresh": "새로고침","exportSuccess": "{{file}} 파일을 만들었습니다. 예시 이미지 경로를 바꾸고 저장한 뒤 \"새로고침\"을 누르세요.","exportFailed": "내보내기에 실패했습니다: {{error}}",+ "importSuccess": "{{name}}({{themeCount}}개 구성)을 가져왔습니다. 위 테마 목록에서 선택하세요.",+ "importPartial": "{{name}}({{themeCount}}개 구성)을 가져왔습니다. 의미가 정해진 색 {{skipped}}개는 규칙대로 그대로 두었고, {{unresolved}}개는 값을 읽을 수 없어 건너뛰었고, {{derived}}개는 인접색에서 추정했습니다.",+ "importFailed": "가져오기에 실패했습니다: {{error}}",+ "importUnsupported": "이 파일은 VSCode 또는 Obsidian 테마로 인식할 수 없습니다.",+ "importUsesInclude": "이 VSCode 테마는 include를 통해 색상을 상속하므로 단독으로 가져올 수 없습니다.",+ "importNotAFile": "폴더가 아닌 파일을 선택해 주세요.",+ "importTooLarge": "파일이 너무 커서 테마로 가져올 수 없습니다.",+ "importWriteError": "테마를 저장할 수 없습니다. 디스크 공간과 권한을 확인하세요.",+ "importInternalError": "파일을 읽거나 처리할 수 없습니다. 다시 선택해 보세요.","openDirFailed": "폴더를 열지 못했습니다: {{error}}","refreshed": "로컬 테마를 새로고쳤습니다"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 092e004c05..9475932154 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -356,10 +356,20 @@"localThemes": {"title": "本地主题","export": "新建本地副本",+ "import": "导入 VSCode / Obsidian 主题","openDir": "打开主题目录","refresh": "刷新","exportSuccess": "已生成 {{file}},替换示例图片路径并保存后点\"刷新\"即可生效","exportFailed": "导出失败:{{error}}",+ "importSuccess": "已导入 {{name}}({{themeCount}} 个方案),在上方主题列表里选它即可",+ "importPartial": "已导入 {{name}}({{themeCount}} 个方案)。{{skipped}} 项语义色按规范不变,{{unresolved}} 项取值无法识别,{{derived}} 项由邻近色近似推导",+ "importFailed": "导入失败:{{error}}",+ "importUnsupported": "这个文件不是可识别的 VSCode 或 Obsidian 主题",+ "importUsesInclude": "该 VSCode 主题通过 include 继承配色,无法独立导入",+ "importNotAFile": "选择一个文件,而非文件夹",+ "importTooLarge": "文件太大,无法作为主题导入",+ "importWriteError": "无法保存主题,检查磁盘空间与权限",+ "importInternalError": "无法读取或处理该文件,尝试重新选择","openDirFailed": "打开目录失败:{{error}}","refreshed": "已刷新本地主题"},diff --git a/apps/desktop/src/renderer/themes/__tests__/localThemeFamilies.test.ts b/apps/desktop/src/renderer/themes/__tests__/localThemeFamilies.test.tsnew file mode 100644index 0000000000..6998fb7764--- /dev/null+++ b/apps/desktop/src/renderer/themes/__tests__/localThemeFamilies.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { Theme } from '../types';++const localThemesMock = vi.hoisted(() => ({ themes: [] as Theme[] }));++vi.mock('../local-themes', () => ({+ getLocalThemes: () => localThemesMock.themes,+ onLocalThemesChange: () => () => undefined,+}));++import { getThemeFamilies, resolveFamilyVariant } from '../families';++/**+ * 本地主题的家族分组。+ *+ * 引入可选 `family` 字段的兼容性要求:**没有该字段的老本地主题,家族 id 与行为+ * 必须逐字不变**(家族 id 就是 `<id>-local`),否则用户已持久化的+ * lightThemeId / darkThemeId 会失效、主题选择被重置。+ */++function makeTheme(id: string, type: 'light' | 'dark', family?: string): Theme {+ return {+ id: `${id}-local`,+ name: id,+ type,+ ...(family ? { family } : {}),+ colors: {},+ };+}++describe('本地主题家族 · 无 family 字段时保持旧行为', () => {+ beforeEach(() => {+ localThemesMock.themes = [+ makeTheme('solo-dark', 'dark'),+ makeTheme('solo-light', 'light'),+ ];+ });++ it('每个文件各自成家族,家族 id 就是主题 id', () => {+ const local = getThemeFamilies().filter((f) => f.id.endsWith('-local'));+ expect(local.map((f) => f.id)).toEqual(['solo-dark-local', 'solo-light-local']);+ });++ it('单变体家族只填对应 type', () => {+ const family = getThemeFamilies().find((f) => f.id === 'solo-dark-local')!;+ expect(family.dark?.id).toBe('solo-dark-local');+ expect(family.light).toBeNull();+ });++ it('请求缺失的 type 时 fallback 并标记(沿用既有提示逻辑)', () => {+ const resolved = resolveFamilyVariant('solo-dark-local', 'light');+ expect(resolved.fallback).toBe(true);+ expect(resolved.theme.type).toBe('dark');+ expect(resolved.requestedType).toBe('light');+ });+});++describe('本地主题家族 · 同 family 的 light + dark 合并', () => {+ beforeEach(() => {+ localThemesMock.themes = [+ makeTheme('minimal-dark', 'dark', 'minimal'),+ makeTheme('minimal-light', 'light', 'minimal'),+ ];+ });++ it('合并成一个双变体家族', () => {+ const local = getThemeFamilies().filter((f) => f.id.endsWith('-local'));+ expect(local).toHaveLength(1);+ expect(local[0].id).toBe('minimal-local');+ expect(local[0].dark?.id).toBe('minimal-dark-local');+ expect(local[0].light?.id).toBe('minimal-light-local');+ });++ it('家族 id 带 -local 后缀(设置页据此显示本地 badge、避免撞内置家族 id)', () => {+ expect(getThemeFamilies().find((f) => f.id === 'minimal-local')).toBeTruthy();+ });++ it('两个模式都能解析到自己的变体,不再 fallback', () => {+ expect(resolveFamilyVariant('minimal-local', 'light').fallback).toBe(false);+ expect(resolveFamilyVariant('minimal-local', 'dark').fallback).toBe(false);+ });+});++describe('本地主题家族 · 边界情况', () => {+ it('family 名撞内置家族 id 时不遮蔽内置主题', () => {+ localThemesMock.themes = [makeTheme('fake-github', 'dark', 'github')];+ const families = getThemeFamilies();+ const github = families.filter((f) => f.id === 'github');+ // 内置 github 家族仍是唯一持有该 id 的;本地主题落到 github-local。+ expect(github).toHaveLength(1);+ expect(github[0].dark?.id).toBe('github-dark');+ expect(families.find((f) => f.id === 'github-local')?.dark?.id).toBe('fake-github-local');+ });++ it('同 family 同 type 撞车时保留先出现的(loader 已按文件名排序)', () => {+ localThemesMock.themes = [+ makeTheme('first', 'dark', 'dup'),+ makeTheme('second', 'dark', 'dup'),+ ];+ const family = getThemeFamilies().find((f) => f.id === 'dup-local')!;+ expect(family.dark?.id).toBe('first-local');+ });++ it('混合有/无 family 的本地主题各走各的分组', () => {+ localThemesMock.themes = [+ makeTheme('paired-dark', 'dark', 'paired'),+ makeTheme('paired-light', 'light', 'paired'),+ makeTheme('lonely', 'dark'),+ ];+ const local = getThemeFamilies().filter((f) => f.id.endsWith('-local'));+ expect(local.map((f) => f.id)).toEqual(['paired-local', 'lonely-local']);+ });++ it('没有本地主题时只剩内置家族', () => {+ localThemesMock.themes = [];+ expect(getThemeFamilies().every((f) => !f.id.endsWith('-local'))).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/themes/__tests__/markdownColorTokens.test.ts b/apps/desktop/src/renderer/themes/__tests__/markdownColorTokens.test.tsnew file mode 100644index 0000000000..1eea6503b5--- /dev/null+++ b/apps/desktop/src/renderer/themes/__tests__/markdownColorTokens.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import { colorRegistry } from '../color-registry';+// import 触发整表注册。+import '../colors';+import { builtinThemes } from '../registry';+import { exportThemeColors } from '../theme-service';++/**+ * Markdown 颜色 token 的"零影响"守卫。+ *+ * 这组 token(h1–h6 + strong)是为外部主题导入(Obsidian `--hN-color` /+ * VSCode `markup.heading`)引入的可覆盖槽位。引入它们之前,这些元素的颜色是从+ * 容器继承来的——`baseComponents` 只给字号字重,不给 color。+ *+ * 因此默认值必须是 `inherit` 而不是 `var(--text-primary)`:后者会让+ * blockquote / tool card / secondary 文字区里的 Markdown 标题与加粗从弱化色变回+ * 主色,那是实打实的观感改动。本文件断言这条不变量,任何把默认值改成具体色槽+ * 的改动都会在这里失败。+ *+ * 三条断言合起来构成机械证明:默认值恒为 `inherit` + 没有内置主题 override ++ * 每个内置主题导出后仍解析为 `inherit` ⇒ 所有内置主题渲染出的 `color:+ * var(--md-*)` 都等价于引入前的 `color: inherit`。+ */++const MD_COLOR_TOKENS = [+ 'md-h1-fg',+ 'md-h2-fg',+ 'md-h3-fg',+ 'md-h4-fg',+ 'md-h5-fg',+ 'md-h6-fg',+ 'md-strong-fg',+] as const;++describe('Markdown 颜色 token · 默认保持中性', () => {+ it.each(MD_COLOR_TOKENS)('%s 的 light / dark 默认值都是 inherit', (id) => {+ expect(colorRegistry.resolveDefault(id, 'light')).toBe('inherit');+ expect(colorRegistry.resolveDefault(id, 'dark')).toBe('inherit');+ });++ it('没有任何内置主题 override 这组 token', () => {+ const offenders: string[] = [];+ for (const [themeId, theme] of Object.entries(builtinThemes)) {+ const colors = theme.colors as Record<string, string | undefined>;+ for (const id of MD_COLOR_TOKENS) {+ if (colors[id] !== undefined) offenders.push(`${themeId}.${id}`);+ }+ }+ expect(offenders).toEqual([]);+ });++ it.each(Object.keys(builtinThemes))(+ '主题 %s 导出后这组 token 仍解析为 inherit(渲染结果与引入前等价)',+ (themeId) => {+ const exported = exportThemeColors(builtinThemes[themeId]);+ for (const id of MD_COLOR_TOKENS) {+ expect(exported[id], `${themeId}.${id}`).toBe('inherit');+ }+ },+ );++ it('registry 里 md- 前缀的 token 只有表格底色与这 7 个文字色', () => {+ const mdTokens = colorRegistry+ .getColors()+ .map((c) => c.id)+ .filter((id) => id.startsWith('md-'))+ .sort();+ expect(mdTokens).toEqual(['md-table-bg', ...MD_COLOR_TOKENS].sort());+ });+});diff --git a/apps/desktop/src/renderer/themes/builtin/github-dark.ts b/apps/desktop/src/renderer/themes/builtin/github-dark.tsindex 378f810563..7d5c06ff87 100644--- a/apps/desktop/src/renderer/themes/builtin/github-dark.ts+++ b/apps/desktop/src/renderer/themes/builtin/github-dark.ts@@ -70,6 +70,7 @@ const slotOverrides = {'accent-soft': BLUE_SOFT,'accent-hover': BLUE_DEEP,'accent-pure-cta-fg': '#ffffff',+ 'status-badge-fg': '#1F1F1F',} as const;const singletonOverrides = {diff --git a/apps/desktop/src/renderer/themes/colors.ts b/apps/desktop/src/renderer/themes/colors.tsindex a18988f2e0..22d39fe408 100644--- a/apps/desktop/src/renderer/themes/colors.ts+++ b/apps/desktop/src/renderer/themes/colors.ts@@ -66,6 +66,41 @@ registerColor('md-table-bg', {light: 'rgba(236, 236, 234, 0.55)',dark: 'rgba(44, 44, 42, 0.55)',}, 'Markdown 编辑器表格行 / 表头半透明背景');+// ── Markdown 正文语义色(标题 h1-h6 + 加粗)──+// 默认值刻意是 `inherit` 而不是 var(--text-primary):这些元素在引入 token 之前+// 的颜色就是从容器继承来的(baseComponents 只给字号字重,不给 color)。若默认改成+// 具体色槽,blockquote / tool card / secondary 文字区里的 Markdown 标题与加粗会+// 由弱化色变回主色 —— 那才是真的改动现有观感。`inherit` 让默认主题渲染结果逐+// 像素不变,同时给外部主题导入(VSCode markup.heading / Obsidian --hN-color)留出+// 可覆盖的槽位。详见 docs/design-rules/DESIGN.md §10「外部主题导入」。+registerColor('md-h1-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H1 文字色(默认继承容器文字色)');+registerColor('md-h2-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H2 文字色(默认继承容器文字色)');+registerColor('md-h3-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H3 文字色(默认继承容器文字色)');+registerColor('md-h4-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H4 文字色(默认继承容器文字色)');+registerColor('md-h5-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H5 文字色(默认继承容器文字色)');+registerColor('md-h6-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown H6 文字色(默认继承容器文字色)');+registerColor('md-strong-fg', {+ light: 'inherit',+ dark: 'inherit',+}, 'Markdown 加粗文字色(默认继承容器文字色)');registerColor('border-default', {light: '#d7d7d4',dark: '#3c3c3a',diff --git a/apps/desktop/src/renderer/themes/families.ts b/apps/desktop/src/renderer/themes/families.tsindex 333f72d677..42784ba31e 100644--- a/apps/desktop/src/renderer/themes/families.ts+++ b/apps/desktop/src/renderer/themes/families.ts@@ -9,6 +9,7 @@ import { oneDarkPro } from './builtin/one-dark-pro';import { solarizedLight } from './builtin/solarized-light';import { cindyDark } from './builtin/cindy-dark';import { cindyLight } from './builtin/cindy-light';+import { LOCAL_THEME_SUFFIX } from '../../shared/local-themes';import { getLocalThemes } from './local-themes';import type { Theme, ThemeType } from './types';@@ -49,13 +50,40 @@ const BUILTIN_FAMILIES: ThemeFamily[] = [},];+/**+ * 本地主题 → 家族。+ *+ * 默认每个 JSON 各自成家族(family id = theme.id,已带 `-local` 后缀)。声明了+ * `family` 的文件按该键分组,让一次导入产出的 light + dark 合成一个可跟随模式+ * 切换的主题。分组键同样补 `-local` 后缀:设置页用 `isLocalThemeId(family.id)`+ * 决定「本地」badge 与刷新后的重选,且能避免用户写的 family 名撞上 builtin+ * 家族 id(如 `github`)把内置主题遮蔽掉。+ *+ * 无 `family` 字段的老主题走的还是 `theme.id` 这条路径,家族 id 与行为逐字不变,+ * 已持久化的 lightThemeId / darkThemeId 不会失效。+ */function buildLocalFamilies(): ThemeFamily[] {- return getLocalThemes().map((theme) => ({- id: theme.id,- name: theme.name,- light: theme.type === 'light' ? theme : null,- dark: theme.type === 'dark' ? theme : null,- }));+ const families: ThemeFamily[] = [];+ const byKey = new Map<string, ThemeFamily>();+ for (const theme of getLocalThemes()) {+ const key = theme.family ? `${theme.family}${LOCAL_THEME_SUFFIX}` : theme.id;+ const existing = byKey.get(key);+ if (existing) {+ // 同 family 同 type 撞车时保留先出现的(loader 按文件名排序,结果确定)。+ if (theme.type === 'light') existing.light ??= theme;+ else existing.dark ??= theme;+ continue;+ }+ const family: ThemeFamily = {+ id: key,+ name: theme.name,+ light: theme.type === 'light' ? theme : null,+ dark: theme.type === 'dark' ? theme : null,+ };+ byKey.set(key, family);+ families.push(family);+ }+ return families;}export function getThemeFamilies(): ThemeFamily[] {diff --git a/apps/desktop/src/renderer/themes/local-themes.ts b/apps/desktop/src/renderer/themes/local-themes.tsindex f1268b148b..15356d9b6e 100644--- a/apps/desktop/src/renderer/themes/local-themes.ts+++ b/apps/desktop/src/renderer/themes/local-themes.ts@@ -37,6 +37,7 @@ function mapWireTheme(theme: LocalThemeWire): Theme {id: theme.id,name: theme.name,type: theme.type,+ ...(theme.family ? { family: theme.family } : {}),// 加载期兼容归一化:把 text-placeholder slot 引入前创建的旧本地主题统一收口// 到新 slot(详见 local-themes-normalize.ts / docs/design-rules/cindy-design-system.md §13 G3)。colors: normalizeLocalThemeColors(theme.colors),@@ -47,7 +48,9 @@ function mapWireTheme(theme: LocalThemeWire): Theme {}function signatureOf(themes: Theme[]): string {- return JSON.stringify(themes.map((t) => [t.id, t.type, t.name, t.colors, t.brand]));+ return JSON.stringify(+ themes.map((t) => [t.id, t.type, t.name, t.family, t.colors, t.brand]),+ );}/** Returns true if the cache content actually changed. */diff --git a/apps/desktop/src/renderer/themes/types.ts b/apps/desktop/src/renderer/themes/types.tsindex 9e9f6c6684..9f30dda85a 100644--- a/apps/desktop/src/renderer/themes/types.ts+++ b/apps/desktop/src/renderer/themes/types.ts@@ -31,6 +31,11 @@ export interface Theme {id: string;name: string;type: ThemeType;+ /**+ * 仅本地主题使用的家族键(见 shared/local-themes.ts)。同 family 的 light ++ * dark 会在设置里合并成一个可跟随模式切换的主题;缺省则各自成家族。+ */+ family?: string;colors: Partial<Record<ColorIdentifier, ColorValue>>;/** 新建对话页的方形 icon + 横向 logo;两项缺省时分别回退打包默认素材。 */brand?: ThemeBrand;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 23f9813aae..a8661c9e86 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -972,6 +972,10 @@ interface ElectronAPI {list: () => Promise<LocalThemesResult>;write: (req: LocalThemeWriteRequest) => Promise<LocalThemeWriteResult>;openDir: () => Promise<LocalThemeOpenDirResult>;+ /** 导入 VSCode / Obsidian 主题文件;对话框与读文件都在 main 侧。 */+ importExternal: () => Promise<+ import('../shared/theme-import/types').LocalThemeImportResult+ >;};/** RSB terminal tab —— PTY 后端 + xterm.js,详见 shared/terminal-bridge.ts 注释。 */diff --git a/apps/desktop/src/shared/__tests__/themeImportColor.test.ts b/apps/desktop/src/shared/__tests__/themeImportColor.test.tsnew file mode 100644index 0000000000..754f81ceda--- /dev/null+++ b/apps/desktop/src/shared/__tests__/themeImportColor.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest';++import {+ contrastRatio,+ isDarkBackground,+ mix,+ parseCssColor,+ shade,+ toHex,+ toHslTriplet,+ toRgbaString,+} from '../theme-import/color';++describe('theme-import 颜色解析', () => {+ it.each([+ ['#282c34', { r: 40, g: 44, b: 52 }],+ ['282c34', { r: 40, g: 44, b: 52 }],+ ['#333', { r: 51, g: 51, b: 51 }],+ ['#FFF', { r: 255, g: 255, b: 255 }],+ // 8 位 hex:VSCode 主题里的半透明边框,剥掉 alpha 当实色用。+ ['#30363d80', { r: 48, g: 54, b: 61 }],+ // 4 位简写同理。+ ['#333a', { r: 51, g: 51, b: 51 }],+ ['rgb(97, 175, 239)', { r: 97, g: 175, b: 239 }],+ ['rgba(97, 175, 239, 0.5)', { r: 97, g: 175, b: 239 }],+ ])('解析 %s', (input, expected) => {+ expect(parseCssColor(input)).toEqual(expected);+ });++ // 回归:百分号通道是 0-100% → 0-255,不能当原值用(`rgb(100%,0%,0%)` 是纯红,+ // 按原值会解析成 {r:100} 这个几乎全黑的暗红)。+ it.each([+ ['rgb(100%, 0%, 0%)', { r: 255, g: 0, b: 0 }],+ ['rgb(0%, 100%, 0%)', { r: 0, g: 255, b: 0 }],+ ['rgb(50%, 50%, 50%)', { r: 128, g: 128, b: 128 }],+ ['rgba(100%, 100%, 100%, 0.5)', { r: 255, g: 255, b: 255 }],+ ])('解析百分号通道 %s', (input, expected) => {+ expect(parseCssColor(input)).toEqual(expected);+ });++ it('解析 hsl()(Obsidian 主题常用 hsl(var(--accent-h) ...) 展开后的形态)', () => {+ expect(parseCssColor('hsl(0, 0%, 100%)')).toEqual({ r: 255, g: 255, b: 255 });+ expect(parseCssColor('hsl(0, 0%, 0%)')).toEqual({ r: 0, g: 0, b: 0 });+ // 空格分隔的现代语法也要认。+ expect(parseCssColor('hsl(120 100% 50%)')).toEqual({ r: 0, g: 255, b: 0 });+ });++ it.each([+ ['color-mix(in srgb, #000 12%, transparent)'],+ ['var(--undefined-var)'],+ ['transparent'],+ ['currentColor'],+ [''],+ [' '],+ ])('无法静态求值的 %s 返回 null(绝不猜值)', (input) => {+ expect(parseCssColor(input)).toBeNull();+ });++ it('非字符串输入返回 null', () => {+ expect(parseCssColor(undefined)).toBeNull();+ expect(parseCssColor(null)).toBeNull();+ });+});++describe('theme-import HSL 三元组换算', () => {+ it.each([+ // one-dark-pro.ts 里手写的精确换算样本(该主题的 HSL 与 hex 严格对应)。+ ['#282c34', '220 13% 18%'],+ ['#abb2bf', '219 14% 71%'],+ ['#ffffff', '0 0% 100%'],+ ['#000000', '0 0% 0%'],+ ])('%s → %s', (hex, expected) => {+ const rgb = parseCssColor(hex);+ expect(rgb).not.toBeNull();+ expect(toHslTriplet(rgb!)).toBe(expected);+ });++ it('格式与既有主题一致:三段、带百分号、整数', () => {+ expect(toHslTriplet({ r: 13, g: 17, b: 23 })).toMatch(/^\d+ \d+% \d+%$/);+ });+});++describe('theme-import 输出格式', () => {+ it('toHex 输出小写 6 位', () => {+ expect(toHex({ r: 40, g: 44, b: 52 })).toBe('#282c34');+ expect(toHex({ r: 0, g: 0, b: 0 })).toBe('#000000');+ });++ it('toRgbaString 与既有主题 drop-overlay-bg 的书写形态一致', () => {+ expect(toRgbaString({ r: 97, g: 175, b: 239 }, 0.1)).toBe('rgba(97, 175, 239, 0.1)');+ });+});++describe('theme-import 派生与判定', () => {+ it('shade 正向提亮、负向压暗,且不越界', () => {+ expect(shade({ r: 100, g: 100, b: 100 }, 1)).toEqual({ r: 255, g: 255, b: 255 });+ expect(shade({ r: 100, g: 100, b: 100 }, -1)).toEqual({ r: 0, g: 0, b: 0 });+ const lighter = shade({ r: 40, g: 44, b: 52 }, 0.1);+ expect(lighter.r).toBeGreaterThan(40);+ });++ it('mix 两端取值正确', () => {+ const a = { r: 0, g: 0, b: 0 };+ const b = { r: 100, g: 200, b: 50 };+ expect(mix(a, b, 0)).toEqual(a);+ expect(mix(a, b, 1)).toEqual(b);+ expect(mix(a, b, 0.5)).toEqual({ r: 50, g: 100, b: 25 });+ });++ it('isDarkBackground 判定常见主题底色', () => {+ expect(isDarkBackground({ r: 40, g: 44, b: 52 })).toBe(true); // #282c34+ expect(isDarkBackground({ r: 250, g: 250, b: 250 })).toBe(false); // #FAFAFA+ expect(isDarkBackground({ r: 253, g: 246, b: 227 })).toBe(false); // solarized base3+ });++ it('contrastRatio 黑白为 21:1', () => {+ expect(contrastRatio({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 })).toBeCloseTo(21, 1);+ });+});diff --git a/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts b/apps/desktop/src/shared/__tests__/themeImportObsidian.test.tsnew file mode 100644index 0000000000..a027180a42--- /dev/null+++ b/apps/desktop/src/shared/__tests__/themeImportObsidian.test.ts@@ -0,0 +1,255 @@+import { describe, expect, it } from 'vitest';++import { convertObsidianTheme } from '../theme-import';+import { toHex } from '../theme-import/color';+import {+ collectCssRules,+ collectObsidianVars,+ extractObsidianPalette,+ resolveVarValue,+} from '../theme-import/obsidian';+import { paletteToHex } from '../theme-import/vscode';++/** 覆盖真实 Obsidian 主题里常见的写法:色阶变量、var 解引用、hsl 拼装、color-mix。 */+const THEME_CSS = `+/* Some Theme */+body {+ --color-base-00: #1e1e1e;+ --font-text-theme: Inter, sans-serif;+ /* Obsidian v1 常见写法:accent 拆成 h/s/l 三个变量再拼装 */+ --accent-h: 254;+ --accent-s: 80%;+ --accent-l: 68%;+}+.theme-dark {+ --background-primary: var(--color-base-00);+ --background-secondary: #252525;+ --background-modifier-hover: #2a2a2a;+ --background-secondary-alt: #303030;+ --background-modifier-border: #333;+ --text-normal: #dcddde;+ --text-muted: #999999;+ --text-faint: #666666;+ --interactive-accent: hsl(var(--accent-h), var(--accent-s), var(--accent-l));+ --interactive-accent-hover: #6a5acd;+ --h1-color: #e06c75;+ --h2-color: #61afef;+ --bold-color: #d19a66;+}+.theme-light {+ --background-primary: #ffffff;+ --background-secondary: #f5f5f5;+ --text-normal: #222222;+ --text-muted: #6b6b6b;+ --interactive-accent: #7b6cd9;+ --background-modifier-border: color-mix(in srgb, #000 12%, transparent);+}+@media (min-width: 400px) {+ .theme-dark {+ --divider-color: #444444;+ }+}+.some-plugin-widget {+ --background-primary: #ff0000;+}+`;++describe('theme-import · CSS 规则扫描', () => {+ it('切出顶层规则并递归展开 at-rule', () => {+ const rules = collectCssRules(THEME_CSS);+ const selectors = rules.map((r) => r.selector);+ expect(selectors).toContain('body');+ expect(selectors).toContain('.theme-dark');+ expect(selectors).toContain('.theme-light');+ // @media 内的 .theme-dark 被递归提出来(同名选择器出现两次)。+ expect(selectors.filter((s) => s === '.theme-dark')).toHaveLength(2);+ // @media 自身不作为规则留下。+ expect(selectors.some((s) => s.startsWith('@'))).toBe(false);+ });++ it('落单右括号不会让扫描崩掉', () => {+ expect(() => collectCssRules('} .a { --x: 1; }')).not.toThrow();+ expect(collectCssRules('} .a { --x: 1; }').map((r) => r.selector)).toContain('.a');+ });++ // 回归:块深度曾按裸字符数,字符串里的大括号会让边界错位,把后面的主题块整段吞掉。+ it('字符串字面量里的大括号不算块边界', () => {+ const css = `+ .theme-dark::before { content: "{"; --a: 1; }+ .theme-light { --background-primary: #ffffff; }+ `;+ const selectors = collectCssRules(css).map((r) => r.selector);+ expect(selectors).toContain('.theme-light');+ const light = collectCssRules(css).find((r) => r.selector === '.theme-light');+ expect(light?.body).toContain('--background-primary');+ });++ it('单引号与右大括号字符串同样不破坏边界', () => {+ const css = `+ .x { content: '}'; }+ .theme-dark { --background-primary: #101010; }+ `;+ const dark = collectCssRules(css).find((r) => r.selector === '.theme-dark');+ expect(dark?.body).toContain('--background-primary');+ });++ it('选择器属性值里的大括号也不破坏边界', () => {+ const css = `+ [data-x="{"] { --a: 1; }+ .theme-dark { --background-primary: #101010; }+ `;+ const dark = collectCssRules(css).find((r) => r.selector === '.theme-dark');+ expect(dark?.body).toContain('--background-primary');+ });++ it('带大括号的 data URL 不吞掉后续主题块(端到端)', () => {+ const css = `+ .cm-line { background-image: url("data:image/svg+xml,%3Csvg%3E{}%3C/svg%3E"); }+ .theme-dark { --background-primary: #1e1e1e; --text-normal: #dcddde; }+ .theme-light { --background-primary: #ffffff; --text-normal: #222222; }+ `;+ const result = convertObsidianTheme(css, 'Braced');+ expect(result).not.toBeNull();+ expect(result!.themes.map((t) => t.type).sort()).toEqual(['dark', 'light']);+ });+});++describe('theme-import · var() 解引用', () => {+ const vars = new Map([+ ['--a', 'var(--b)'],+ ['--b', '#123456'],+ ['--loop', 'var(--loop)'],+ ]);++ it('多层引用逐层展开', () => {+ expect(resolveVarValue('var(--a)', vars)).toBe('#123456');+ });++ it('未定义变量走 fallback', () => {+ expect(resolveVarValue('var(--missing, #abcdef)', vars)).toBe('#abcdef');+ });++ it('未定义且无 fallback 时原样保留(由调用方判失败)', () => {+ expect(resolveVarValue('var(--missing)', vars)).toBe('var(--missing)');+ });++ it('自引用不会死循环', () => {+ expect(() => resolveVarValue('var(--loop)', vars)).not.toThrow();+ });+});++describe('theme-import · 变量收集与模式划分', () => {+ const modes = collectObsidianVars(THEME_CSS);++ it('产出 dark 与 light 两套', () => {+ expect(modes.map((m) => m.type).sort()).toEqual(['dark', 'light']);+ });++ it('body/:root 的基底变量并入每个模式', () => {+ const dark = modes.find((m) => m.type === 'dark')!;+ expect(dark.vars.get('--color-base-00')).toBe('#1e1e1e');+ });++ it('@media 里的主题块变量也被收进来', () => {+ const dark = modes.find((m) => m.type === 'dark')!;+ expect(dark.vars.get('--divider-color')).toBe('#444444');+ });++ it('组件局部选择器的同名变量不污染全局色板', () => {+ const dark = modes.find((m) => m.type === 'dark')!;+ // .some-plugin-widget 里的 --background-primary: #ff0000 必须被忽略。+ expect(dark.vars.get('--background-primary')).toBe('var(--color-base-00)');+ });+});++describe('theme-import · Obsidian 色板抽取', () => {+ const modes = collectObsidianVars(THEME_CSS);+ const dark = extractObsidianPalette(modes.find((m) => m.type === 'dark')!)!;+ const light = extractObsidianPalette(modes.find((m) => m.type === 'light')!)!;++ it('dark:var 解引用后拿到正确底色', () => {+ expect(paletteToHex(dark.palette).surface).toBe('#1e1e1e');+ });++ it('dark:官方变量逐项映射', () => {+ const hex = paletteToHex(dark.palette);+ expect(hex.elevated).toBe('#252525');+ expect(hex.hover).toBe('#2a2a2a');+ expect(hex.chip).toBe('#303030');+ expect(hex.border).toBe('#333333');+ expect(hex.textPrimary).toBe('#dcddde');+ expect(hex.textSecondary).toBe('#999999');+ expect(hex.textTertiary).toBe('#666666');+ });++ it('dark:hsl(var(--h), var(--s), var(--l)) 拼装形态能求值', () => {+ // 三个分量先解引用成 254 / 80% / 68%,再按 hsl() 换算成 sRGB。+ expect(paletteToHex(dark.palette).accentPrimary).toBe(toHex({ r: 139, g: 108, b: 239 }));+ expect(paletteToHex(dark.palette).accentDeep).toBe('#6a5acd');+ });++ it('dark:标题色与加粗色被读出(缺席的层级留空)', () => {+ expect(dark.markdown.headings?.[0]).toEqual({ r: 224, g: 108, b: 117 });+ expect(dark.markdown.headings?.[1]).toEqual({ r: 97, g: 175, b: 239 });+ expect(dark.markdown.headings?.[2]).toBeNull();+ expect(dark.markdown.strong).toEqual({ r: 209, g: 154, b: 102 });+ });++ it('light:color-mix() 无法求值时记入 unresolved 并改走派生', () => {+ expect(light.unresolved).toContain('--background-modifier-border');+ expect(light.derivedRoles).toContain('border');+ });++ it('light:没有标题色变量时不产出 Markdown 源', () => {+ expect(light.markdown.headings).toBeUndefined();+ expect(light.markdown.strong).toBeUndefined();+ });++ it('拿不到背景色时返回 null(不硬造主题)', () => {+ const vars = new Map([['--text-normal', '#fff']]);+ expect(extractObsidianPalette({ type: 'dark', vars })).toBeNull();+ });+});++describe('theme-import · Obsidian 端到端转换', () => {+ const result = convertObsidianTheme(THEME_CSS, 'Some Theme');++ it('双态 CSS 产出 light + dark 两个主题,同名', () => {+ expect(result).not.toBeNull();+ expect(result!.themes).toHaveLength(2);+ expect(result!.themes.map((t) => t.type).sort()).toEqual(['dark', 'light']);+ expect(new Set(result!.themes.map((t) => t.name))).toEqual(new Set(['Some Theme']));+ });++ it('每个产物都是完整 token map', () => {+ for (const theme of result!.themes) {+ expect(Object.keys(theme.colors).length).toBeGreaterThan(80);+ expect(theme.colors.surface).toMatch(/^#[0-9a-f]{6}$/);+ expect(theme.colors['surface-hsl']).toMatch(/^\d+ \d+% \d+%$/);+ }+ });++ it('Markdown 标题色只出现在提供了它的那个模式里', () => {+ const dark = result!.themes.find((t) => t.type === 'dark')!;+ const light = result!.themes.find((t) => t.type === 'light')!;+ expect(dark.colors['md-h1-fg']).toBe('#e06c75');+ expect(light.colors['md-h1-fg']).toBeUndefined();+ });++ it('报告合并了两个模式的缺口', () => {+ expect(result!.report.source).toBe('obsidian');+ expect(result!.report.unresolved).toContain('--background-modifier-border');+ expect(result!.report.derivedRoles.length).toBeGreaterThan(0);+ });++ it('单态 CSS 按背景亮度判定模式', () => {+ const single = convertObsidianTheme(':root { --background-primary: #ffffff; }', 'X');+ expect(single!.themes).toHaveLength(1);+ expect(single!.themes[0].type).toBe('light');+ });++ 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.tsnew file mode 100644index 0000000000..f0f68e7d43--- /dev/null+++ b/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts@@ -0,0 +1,205 @@+import { describe, expect, it } from 'vitest';++import { colorRegistry } from '../../renderer/themes/color-registry';+// import 触发整表 registerColor(照 themes/__tests__/tokenRegistry.test.ts 的做法)。+import '../../renderer/themes/colors';+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 {+ buildThemeColorsFromPalette,+ TEMPLATE_TOKEN_IDS,+ type ThemePalette,+} from '../theme-import/palette';+import { isProtectedToken } from '../theme-import/protected-tokens';++/**+ * 模板 golden 对照。+ *+ * `palette.ts` 的模板是从 7 个人工移植的 builtin 社区主题里抽出来的,所以正确性+ * 就该用那些主题本身来证:把某个主题头部的手写色板常量喂进模板,输出必须重现该+ * 主题的 colors。+ *+ * 一处必要的放宽:`-hsl` 类 token 在手写主题里是**人工近似值**(实测+ * one-dark-pro 的 ELEVATED_BG_HSL 写 `220 13% 15%`,而 #21252b 精确换算是+ * `216 13% 15%`;github-dark 的 SURFACE_BG_HSL 更是从 one-dark-pro 复制后只改了+ * L)。转换器必须走精确换算(否则 hex 与 HSL 两种形态会表示不同颜色),因此 HSL+ * token 不与手写值比,而是断言"等于对应色板角色的精确换算"——这验证的是模板把+ * 正确的角色接到了正确的 token 上,强度不降。+ */++function rgb(hex: string): Rgb {+ const parsed = parseCssColor(hex);+ if (!parsed) throw new Error(`bad fixture hex: ${hex}`);+ return parsed;+}++/** one-dark-pro.ts 头部的手写色板(dark 代表)。 */+const ONE_DARK_PRO_PALETTE: ThemePalette = {+ surface: rgb('#282c34'),+ elevated: rgb('#21252b'),+ elevatedSoft: rgb('#21252b'),+ hover: rgb('#2c313a'),+ chip: rgb('#2c313a'),+ border: rgb('#3e4452'),+ textPrimary: rgb('#abb2bf'),+ textSecondary: rgb('#7f848e'),+ textTertiary: rgb('#5c6370'),+ textDisabled: rgb('#495162'),+ accentPrimary: rgb('#61afef'),+ accentSoft: rgb('#82c0ff'),+ accentDeep: rgb('#3d7ec8'),+};++/** atom-one-light.ts 头部的手写色板(light 代表)。 */+const ATOM_ONE_LIGHT_PALETTE: ThemePalette = {+ surface: rgb('#FAFAFA'),+ elevated: rgb('#FFFFFF'),+ elevatedSoft: rgb('#EAEAEB'),+ hover: rgb('#E4E4E5'),+ chip: rgb('#EAEAEB'),+ border: rgb('#D4D4D5'),+ textPrimary: rgb('#383A42'),+ textSecondary: rgb('#696c77'),+ textTertiary: rgb('#A0A1A7'),+ textDisabled: rgb('#C8C8C9'),+ accentPrimary: rgb('#4078F2'),+ // atom-one-light 只声明了 PRIMARY 与 DEEP,soft 槽位用的也是 DEEP。+ accentSoft: rgb('#2050c0'),+ accentDeep: rgb('#2050c0'),+};++/** solarized-light.ts 头部的手写色板(light 第二例)。 */+const SOLARIZED_LIGHT_PALETTE: ThemePalette = {+ surface: rgb('#fdf6e3'),+ elevated: rgb('#eee8d5'),+ elevatedSoft: rgb('#eee8d5'),+ hover: rgb('#eee8d5'),+ chip: rgb('#eee8d5'),+ border: rgb('#e1dcc4'),+ textPrimary: rgb('#757575'),+ textSecondary: rgb('#828282'),+ textTertiary: rgb('#999999'),+ textDisabled: rgb('#bdbdbd'),+ accentPrimary: rgb('#859900'),+ accentSoft: rgb('#5e6a00'),+ accentDeep: rgb('#5e6a00'),+};++/** 值为 HSL 三元组的 token → 它应当换算自哪个色板角色。 */+const HSL_TOKEN_ROLE: Record<string, keyof ThemePalette> = {+ 'surface-hsl': 'surface',+ 'surface-hover-hsl': 'hover',+ 'border-default-hsl': 'border',+ 'border-shadcn-hsl': 'border',+ 'text-primary-hsl': 'textPrimary',+ 'text-tertiary-hsl': 'textTertiary',+ accent: 'hover',+ background: 'surface',+ muted: 'chip',+ 'muted-foreground': 'textSecondary',+ popover: 'elevated',+ 'search-match-fg': 'textPrimary',+ 'sidebar-action-icon': 'textTertiary',+ 'sidebar-item-active': 'chip',+ 'splash-bg': 'surface',+ 'splash-text': 'textSecondary',+ 'splash-text-destructive': 'textPrimary',+ 'splash-text-muted': 'textTertiary',+ 'titlebar-icon': 'textSecondary',+};++/** light / dark 取值不同、且 light 侧是固定字面量的 HSL token。 */+const HSL_TOKEN_ROLE_BY_TYPE: Record<string, { dark: keyof ThemePalette; light: keyof ThemePalette }> = {+ 'primary-foreground': { dark: 'surface', light: 'surface' },+ secondary: { dark: 'elevated', light: 'chip' },+};++function normalize(value: string): string {+ return value.trim().toLowerCase();+}++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('模板 key 无重复', () => {+ expect(new Set(TEMPLATE_TOKEN_IDS).size).toBe(TEMPLATE_TOKEN_IDS.length);+ });++ it.each(['dark', 'light'] as const)('%s 模式输出的 key 就是模板清单', (type) => {+ const palette = type === 'dark' ? ONE_DARK_PRO_PALETTE : ATOM_ONE_LIGHT_PALETTE;+ const out = buildThemeColorsFromPalette(palette, type);+ expect(Object.keys(out).sort()).toEqual([...TEMPLATE_TOKEN_IDS].sort());+ });++ it('模板每个 token 都已在 colorRegistry 注册(防拼错成读不到值的幽灵 token)', () => {+ const unregistered = TEMPLATE_TOKEN_IDS.filter(+ (id) => colorRegistry.resolveDefault(id, 'light') === null+ && colorRegistry.resolveDefault(id, 'dark') === null,+ );+ expect(unregistered).toEqual([]);+ });++ it('模板不产出任何语义豁免族 token(登录/危险/警告/焦点/diff)', () => {+ expect(TEMPLATE_TOKEN_IDS.filter((id) => isProtectedToken(id))).toEqual([]);+ });+});++describe.each([+ ['One Dark Pro', ONE_DARK_PRO_PALETTE, 'dark' as const, oneDarkPro],+ ['Atom One Light', ATOM_ONE_LIGHT_PALETTE, 'light' as const, atomOneLight],+ ['Solarized Light', SOLARIZED_LIGHT_PALETTE, 'light' as const, solarizedLight],+])('theme-import 模板 · golden 重现 %s', (_name, palette, type, expected) => {+ const built = buildThemeColorsFromPalette(palette, type);+ const expectedColors = expected.colors as Record<string, string>;++ it('非 HSL token 与手写主题逐字一致', () => {+ const mismatches: string[] = [];+ for (const id of TEMPLATE_TOKEN_IDS) {+ if (id in HSL_TOKEN_ROLE || id in HSL_TOKEN_ROLE_BY_TYPE) continue;+ const actual = built[id];+ const want = expectedColors[id];+ if (want === undefined) continue;+ if (normalize(actual) !== normalize(want)) {+ mismatches.push(`${id}: got ${actual}, want ${want}`);+ }+ }+ expect(mismatches).toEqual([]);+ });++ it('HSL token 精确换算自对应色板角色', () => {+ for (const [id, role] of Object.entries(HSL_TOKEN_ROLE)) {+ expect(built[id], id).toBe(toHslTriplet(palette[role]));+ }+ for (const [id, roles] of Object.entries(HSL_TOKEN_ROLE_BY_TYPE)) {+ if (id === 'primary-foreground' && type === 'light') {+ expect(built[id]).toBe('0 0% 100%');+ continue;+ }+ expect(built[id], id).toBe(toHslTriplet(palette[roles[type]]));+ }+ });+});++describe('theme-import 模板 · Markdown token 只在源主题提供时才产出', () => {+ it('不传 markdown 时不产出 md-* token', () => {+ const out = buildThemeColorsFromPalette(ONE_DARK_PRO_PALETTE, 'dark');+ expect(Object.keys(out).filter((id) => id.startsWith('md-'))).toEqual([]);+ });++ it('传入标题色与加粗色时逐项产出', () => {+ const out = buildThemeColorsFromPalette(ONE_DARK_PRO_PALETTE, 'dark', {+ headings: [rgb('#e06c75'), null, rgb('#61afef'), undefined, null, null],+ strong: rgb('#d19a66'),+ });+ expect(out['md-h1-fg']).toBe('#e06c75');+ expect(out['md-h2-fg']).toBeUndefined();+ expect(out['md-h3-fg']).toBe('#61afef');+ expect(out['md-h4-fg']).toBeUndefined();+ expect(out['md-strong-fg']).toBe('#d19a66');+ });+});diff --git a/apps/desktop/src/shared/__tests__/themeImportVsCode.test.ts b/apps/desktop/src/shared/__tests__/themeImportVsCode.test.tsnew file mode 100644index 0000000000..cacfe1e292--- /dev/null+++ b/apps/desktop/src/shared/__tests__/themeImportVsCode.test.ts@@ -0,0 +1,237 @@+import { describe, expect, it } from 'vitest';++import { convertVsCodeTheme, detectImportSource } from '../theme-import';+import {+ extractVsCodePalette,+ paletteToHex,+ parseVsCodeThemeJson,+ stripJsonComments,+} from '../theme-import/vscode';++/**+ * fixture 按 One Dark Pro 官方 `OneDark-Pro.json` 的真实结构与色值写(映射依据见+ * `renderer/themes/builtin/one-dark-pro.ts` 顶部的人工移植注释)。+ */+const ONE_DARK_PRO_JSON = JSON.stringify({+ name: 'One Dark Pro',+ type: 'dark',+ colors: {+ 'editor.background': '#282c34',+ 'editor.foreground': '#abb2bf',+ 'sideBar.background': '#21252b',+ 'list.hoverBackground': '#2c313a',+ 'list.activeSelectionBackground': '#2c313a',+ 'panel.border': '#3e4452',+ 'editorLineNumber.foreground': '#495162',+ 'button.background': '#61afef',+ },+ tokenColors: [+ {+ scope: 'comment',+ settings: { foreground: '#7f848e', fontStyle: 'italic' },+ },+ {+ scope: ['markup.heading', 'entity.name.section'],+ settings: { foreground: '#e06c75' },+ },+ {+ scope: 'markup.bold',+ settings: { foreground: '#d19a66' },+ },+ ],+});++describe('theme-import · jsonc 清理', () => {+ it('去掉行注释与块注释,容忍尾逗号', () => {+ const input = `{+ // 行注释+ "type": "dark", /* 块注释 */+ "colors": {+ "editor.background": "#282c34", // 尾注释+ },+ }`;+ expect(JSON.parse(stripJsonComments(input))).toEqual({+ type: 'dark',+ colors: { 'editor.background': '#282c34' },+ });+ });++ it('不误删字符串里的 // 与 /*', () => {+ const input = '{"a": "https://example.com/x", "b": "/* not a comment */"}';+ expect(JSON.parse(stripJsonComments(input))).toEqual({+ a: 'https://example.com/x',+ b: '/* not a comment */',+ });+ });++ it('不被转义引号骗过', () => {+ const input = '{"a": "say \\" // still string", "b": 1}';+ expect(JSON.parse(stripJsonComments(input))).toEqual({+ a: 'say " // still string',+ b: 1,+ });+ });++ // 回归:尾逗号处理曾用一条全局 replace(/,(\s*[}\]])/g),它不认字符串边界,+ // 会把 JSON 值里合法的 `, }` / `, ]` 一起吃掉。+ it.each([+ ['{"a": "x, }y"}', { a: 'x, }y' }],+ ['{"a": "x, ]y"}', { a: 'x, ]y' }],+ ['{"a": "trailing, ", "b": 1}', { a: 'trailing, ', b: 1 }],+ ['{"a": "多个, } ] 逗号"}', { a: '多个, } ] 逗号' }],+ ])('不删字符串字面量里的 %s', (input, expected) => {+ expect(JSON.parse(stripJsonComments(input))).toEqual(expected);+ });++ it('尾逗号后跟行注释时仍能识别(注释先剥、再判尾逗号)', () => {+ const input = `{+ "a": 1, // 说明+ "b": [1, 2,], /* 块注释 */+ }`;+ expect(JSON.parse(stripJsonComments(input))).toEqual({ a: 1, b: [1, 2] });+ });+});++describe('theme-import · VSCode 主题识别', () => {+ it('既无 colors 也无 tokenColors 的 JSON 不是颜色主题', () => {+ expect(parseVsCodeThemeJson('{"foo":1}')).toBeNull();+ });++ it('坏 JSON 返回 null 而不抛', () => {+ expect(parseVsCodeThemeJson('{ not json')).toBeNull();+ });++ it('没有 editor.background 时判不出可用主题', () => {+ const parsed = parseVsCodeThemeJson('{"colors":{"foo.bar":"#fff"}}');+ expect(parsed).not.toBeNull();+ expect(extractVsCodePalette(parsed!, 'x')).toBeNull();+ });++ it('按扩展名判定来源', () => {+ expect(detectImportSource('OneDark-Pro.json')).toBe('vscode');+ expect(detectImportSource('theme.jsonc')).toBe('vscode');+ expect(detectImportSource('theme.css')).toBe('obsidian');+ expect(detectImportSource('readme.md')).toBeNull();+ });+});++describe('theme-import · One Dark Pro 色板抽取', () => {+ const parsed = parseVsCodeThemeJson(ONE_DARK_PRO_JSON);+ const extracted = extractVsCodePalette(parsed!, 'fallback');++ it('直取的角色与官方色值一致(不含派生档)', () => {+ expect(extracted).not.toBeNull();+ const hex = paletteToHex(extracted!.palette);+ expect(hex.surface).toBe('#282c34');+ expect(hex.elevated).toBe('#21252b');+ expect(hex.hover).toBe('#2c313a');+ expect(hex.chip).toBe('#2c313a');+ expect(hex.border).toBe('#3e4452');+ expect(hex.textPrimary).toBe('#abb2bf');+ expect(hex.textSecondary).toBe('#7f848e');+ expect(hex.textDisabled).toBe('#495162');+ expect(hex.accentPrimary).toBe('#61afef');+ });++ it('type 取自源文件声明;name 取自源文件', () => {+ expect(extracted!.type).toBe('dark');+ expect(extracted!.name).toBe('One Dark Pro');+ });++ it('accent soft/deep 是派生档(源主题不提供)', () => {+ expect(extracted!.derivedRoles).not.toContain('surface');+ expect(extracted!.derivedRoles).not.toContain('accentPrimary');+ // dark 下 soft 更亮、deep 更暗。+ const hex = paletteToHex(extracted!.palette);+ expect(hex.accentSoft).not.toBe(hex.accentPrimary);+ expect(hex.accentDeep).not.toBe(hex.accentPrimary);+ });++ it('markup.heading / markup.bold 映射成 Markdown token 源', () => {+ expect(extracted!.markdown.headings).toHaveLength(6);+ expect(extracted!.markdown.headings?.every((c) => c !== null)).toBe(true);+ expect(extracted!.markdown.strong).toEqual({ r: 209, g: 154, b: 102 });+ });+});++describe('theme-import · VSCode 缺键与推导', () => {+ it('只有 editor.background 时其余角色全部推导,且报告如实列出', () => {+ const raw = JSON.stringify({+ name: 'Bare',+ colors: { 'editor.background': '#101010' },+ });+ const parsed = parseVsCodeThemeJson(raw);+ const extracted = extractVsCodePalette(parsed!, 'bare-file');+ expect(extracted).not.toBeNull();+ expect(extracted!.type).toBe('dark'); // 由背景亮度判定+ expect(extracted!.derivedRoles).toEqual(+ expect.arrayContaining([+ 'elevated',+ 'hover',+ 'chip',+ 'border',+ 'textPrimary',+ 'textSecondary',+ 'textTertiary',+ 'textDisabled',+ 'accentPrimary',+ ]),+ );+ expect(extracted!.resolvedRoles).toBe(1);+ });++ it('没有 name 时回退到传入的文件名', () => {+ const parsed = parseVsCodeThemeJson('{"colors":{"editor.background":"#fff"}}');+ expect(extractVsCodePalette(parsed!, 'my-theme')!.name).toBe('my-theme');+ });++ it('浅色背景在未声明 type 时判为 light', () => {+ const parsed = parseVsCodeThemeJson('{"colors":{"editor.background":"#fafafa"}}');+ expect(extractVsCodePalette(parsed!, 'x')!.type).toBe('light');+ });++ it('include 字段计入 unresolved(我们只读单文件)', () => {+ const parsed = parseVsCodeThemeJson(+ '{"include":"./base.json","colors":{"editor.background":"#101010"}}',+ );+ expect(extractVsCodePalette(parsed!, 'x')!.unresolved).toContain('include:./base.json');+ });+});++describe('theme-import · VSCode 端到端转换', () => {+ const result = convertVsCodeTheme(ONE_DARK_PRO_JSON, 'fallback');++ it('产出单个 dark 主题', () => {+ expect(result).not.toBeNull();+ expect(result!.themes).toHaveLength(1);+ expect(result!.themes[0].type).toBe('dark');+ expect(result!.themes[0].name).toBe('One Dark Pro');+ });++ it('token map 里含 Tier1 slot 与 Markdown token,且值来自源主题', () => {+ const colors = result!.themes[0].colors;+ expect(colors.surface).toBe('#282c34');+ expect(colors['text-primary']).toBe('#abb2bf');+ expect(colors['surface-hsl']).toBe('220 13% 18%');+ expect(colors['md-h1-fg']).toBe('#e06c75');+ expect(colors['md-strong-fg']).toBe('#d19a66');+ });++ it('产出里没有任何语义豁免族 token', () => {+ const ids = Object.keys(result!.themes[0].colors);+ expect(ids.filter((id) => id.startsWith('login-'))).toEqual([]);+ expect(ids).not.toContain('destructive');+ expect(ids).not.toContain('warning-accent');+ expect(ids).not.toContain('focus-ring');+ });++ it('报告标注来源为 vscode', () => {+ expect(result!.report.source).toBe('vscode');+ expect(result!.report.resolvedRoles).toBeGreaterThan(5);+ });++ it('非主题 JSON 返回 null', () => {+ expect(convertVsCodeTheme('{"foo":1}', 'x')).toBeNull();+ expect(convertVsCodeTheme('not json at all', 'x')).toBeNull();+ });+});diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex f1e11b09fa..88f579d3f9 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -123,7 +123,14 @@ export type IpcErrorCode =| 'SHARE_EXPORT_FAILED' // 导出编排失败(含超出体积上限)| 'SHARE_IMPORT_FAILED' // 导入编排失败(已回滚)| 'SHARE_WORKTREE_NOT_GIT' // 导入勾选 worktree 但所选目录不在 git 仓库内- | 'SHARE_WORKTREE_FAILED'; // 导入时 worktree 创建失败(已中止导入)+ | 'SHARE_WORKTREE_FAILED' // 导入时 worktree 创建失败(已中止导入)+ // 主题导入(local-themes:import)+ | 'THEME_NOT_A_FILE' // 选中路径不是普通文件+ | 'THEME_FILE_TOO_LARGE' // 超 4MB 上限+ | 'THEME_UNSUPPORTED_FILE' // 无法识别为 VSCode / Obsidian 主题+ | 'THEME_USES_INCLUDE' // VSCode 主题含 include(需基底才能完整解析)+ | 'THEME_WRITE_ERROR' // 落盘失败(权限/磁盘)+ | 'THEME_IMPORT_INTERNAL'; // 意外异常export interface IpcError {code: IpcErrorCode;@@ -226,6 +233,12 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['SHARE_IMPORT_FAILED','SHARE_WORKTREE_NOT_GIT','SHARE_WORKTREE_FAILED',+ 'THEME_NOT_A_FILE',+ 'THEME_FILE_TOO_LARGE',+ 'THEME_UNSUPPORTED_FILE',+ 'THEME_USES_INCLUDE',+ 'THEME_WRITE_ERROR',+ 'THEME_IMPORT_INTERNAL',]);export function isIpcErrorCode(code: unknown): code is IpcErrorCode {diff --git a/apps/desktop/src/shared/local-themes.ts b/apps/desktop/src/shared/local-themes.tsindex fb6d9c4463..a2465b724e 100644--- a/apps/desktop/src/shared/local-themes.ts+++ b/apps/desktop/src/shared/local-themes.ts@@ -27,6 +27,12 @@ export interface LocalThemeWire {id: string;name: string;type: 'light' | 'dark';+ /**+ * 可选的家族键:同一 family 下的 light + dark 两个本地主题会在设置里合并成+ * 一个可跟随模式切换的主题(外部主题导入的双态产物、用户手写的一对主题都用+ * 它配对)。缺省时每个文件各自成家族——老本地主题的行为因此逐字不变。+ */+ family?: string;colors: Record<string, string>;/** 新版品牌区配置;renderer 装载时把路径转成 xdt-file:// URL。 */brand?: LocalThemeBrandConfig;@@ -62,8 +68,13 @@ export interface LocalThemeWriteRequest {id: string;name: string;type: 'light' | 'dark';- /** 品牌素材本地绝对路径;空串表示使用默认素材。 */- brand: {+ /** 见 LocalThemeWire.family;导入的双态产物用它配对。 */+ family?: string;+ /**+ * 品牌素材本地绝对路径;空串表示使用默认素材。「复制主题」会写入示例路径+ * 教用户怎么配;外部主题导入不带品牌素材,此项缺省。+ */+ brand?: {icon: string;logo: string;};diff --git a/apps/desktop/src/shared/theme-import/color.ts b/apps/desktop/src/shared/theme-import/color.tsnew file mode 100644index 0000000000..ad4cf5c92f--- /dev/null+++ b/apps/desktop/src/shared/theme-import/color.ts@@ -0,0 +1,287 @@+/**+ * 外部主题导入的颜色解析与派生工具(纯函数,无 IO / 无 DOM)。+ *+ * 只服务 theme-import:把 VSCode 主题 JSON 与 Obsidian theme.css 里出现的各种+ * 颜色写法归一成 RGB,再按 Cindy token 需要的两种形态输出——hex(`--surface`+ * 一类)与 HSL 三元组(`--surface-hsl` 一类,消费点写 `hsl(var(--xxx))`)。+ *+ * 算法与 `renderer/themes/__tests__/cindyThemes.test.ts` 的 parseHex / hslToRgb+ * 同源(sRGB + WCAG 相对亮度),保证导入产物与既有主题的对比度口径一致。+ */++export interface Rgb {+ r: number;+ g: number;+ b: number;+}++const HEX_RE = /^#?([0-9a-f]{3,8})$/i;++function clamp255(value: number): number {+ return Math.min(255, Math.max(0, Math.round(value)));+}++function clamp01(value: number): number {+ return Math.min(1, Math.max(0, value));+}++/** 展开 3/4/6/8 位 hex,返回 `{ rgb6, alpha }` 对。 */+function expandHexFull(body: string): { rgb6: string; alpha: number } | null {+ if (body.length === 3 || body.length === 4) {+ const rgb = body.slice(0, 3).split('').map((c) => c + c).join('');+ const a = body.length === 4+ ? Number.parseInt(body[3] + body[3], 16) / 255+ : 1;+ return { rgb6: rgb, alpha: a };+ }+ if (body.length === 6) return { rgb6: body, alpha: 1 };+ if (body.length === 8) {+ return { rgb6: body.slice(0, 6), alpha: Number.parseInt(body.slice(6), 16) / 255 };+ }+ return null;+}++/** 展开 hex 并剥离 alpha(向后兼容的快捷路径)。 */+function expandHex(body: string): string | null {+ const result = expandHexFull(body);+ return result ? result.rgb6 : null;+}++function parseHex(raw: string): Rgb | null {+ const m = HEX_RE.exec(raw.trim());+ if (!m) return null;+ const body = expandHex(m[1]);+ if (!body) return null;+ const n = Number.parseInt(body, 16);+ if (!Number.isFinite(n)) return null;+ return { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };+}++/** HSL(0-360, 0-1, 0-1) → RGB。 */+export function hslToRgb(h: number, s: number, l: number): Rgb {+ const c = (1 - Math.abs(2 * l - 1)) * s;+ const hp = (((h % 360) + 360) % 360) / 60;+ const x = c * (1 - Math.abs((hp % 2) - 1));+ let r1 = 0;+ let g1 = 0;+ let b1 = 0;+ if (hp < 1) [r1, g1, b1] = [c, x, 0];+ else if (hp < 2) [r1, g1, b1] = [x, c, 0];+ else if (hp < 3) [r1, g1, b1] = [0, c, x];+ else if (hp < 4) [r1, g1, b1] = [0, x, c];+ else if (hp < 5) [r1, g1, b1] = [x, 0, c];+ else [r1, g1, b1] = [c, 0, x];+ const m = l - c / 2;+ return {+ r: clamp255((r1 + m) * 255),+ g: clamp255((g1 + m) * 255),+ b: clamp255((b1 + m) * 255),+ };+}++/** 单个数值分量;`percent` 必须记住——rgb() 的百分号通道与原值量纲不同。 */+interface NumericComponent {+ value: number;+ percent: boolean;+ unit?: string;+}++const ANGLE_UNIT_RE = /^([+-]?\d*\.?\d+)(deg|rad|grad|turn)?$/i;++function parseAngleComponent(raw: string): NumericComponent {+ const m = ANGLE_UNIT_RE.exec(raw);+ if (!m) return { value: Number.parseFloat(raw), percent: false };+ return { value: Number.parseFloat(m[1]), percent: false, unit: m[2]?.toLowerCase() };+}++function angleToDegrees(comp: NumericComponent): number {+ switch (comp.unit) {+ case 'rad': return (comp.value * 180) / Math.PI;+ case 'grad': return (comp.value * 360) / 400;+ case 'turn': return comp.value * 360;+ default: return comp.value;+ }+}++function parseNumberList(body: string): NumericComponent[] | null {+ const parts = body+ .split(/[,/\s]+/)+ .map((p) => p.trim())+ .filter((p) => p.length > 0);+ if (parts.length < 3) return null;+ return parts.slice(0, 4).map((p) => (+ p.endsWith('%')+ ? { value: Number.parseFloat(p.slice(0, -1)), percent: true }+ : { value: Number.parseFloat(p), percent: false, unit: ANGLE_UNIT_RE.exec(p)?.[2]?.toLowerCase() }+ ));+}++function parseFunctional(raw: string): Rgb | null {+ const m = /^(rgba?|hsla?)\(([^)]*)\)$/i.exec(raw.trim());+ if (!m) return null;+ const fn = m[1].toLowerCase();+ const nums = parseNumberList(m[2]);+ if (!nums || nums.some((n) => !Number.isFinite(n.value))) return null;+ if (fn.startsWith('rgb')) {+ // 百分号通道是 0-100% 映射到 0-255,不能当原值用:`rgb(100%, 0%, 0%)`+ // 是纯红,按原值会解析成 {r:100} 这个几乎全黑的暗红。+ const channel = ({ value, percent }: NumericComponent): number =>+ clamp255(percent ? (value * 255) / 100 : value);+ return { r: channel(nums[0]), g: channel(nums[1]), b: channel(nums[2]) };+ }+ // hsl():色相支持 deg/rad/grad/turn,饱和度与亮度按百分比取值。+ return hslToRgb(+ angleToDegrees(nums[0]),+ clamp01(nums[1].value / 100),+ clamp01(nums[2].value / 100),+ );+}++/**+ * 解析一个 CSS 颜色字面量。支持 hex(3/4/6/8 位)、`rgb()/rgba()`、`hsl()/hsla()`。+ * 不支持 `color-mix()` / `var()` / 命名色等需要上下文或色彩空间转换的写法——+ * 返回 null,由调用方计入「无法解析」报告,绝不猜值。+ */+export function parseCssColor(raw: string | undefined | null): Rgb | null {+ if (typeof raw !== 'string') return null;+ const value = raw.trim();+ if (value.length === 0) return null;+ return parseHex(value) ?? parseFunctional(value);+}++/** alpha-over 合成:将一个带透明度的前景色合成到不透明底色上,产出实色。 */+export function compositeOver(fg: Rgb, alpha: number, bg: Rgb): Rgb {+ const a = clamp01(alpha);+ return {+ r: clamp255(fg.r * a + bg.r * (1 - a)),+ g: clamp255(fg.g * a + bg.g * (1 - a)),+ b: clamp255(fg.b * a + bg.b * (1 - a)),+ };+}++/**+ * 解析颜色并在有 alpha 时合成到 `over`。用于将半透明覆盖色(如+ * `#ffffff0a`)转成实色 token 值。`over` 为 null 时退化为 `parseCssColor`。+ */+export function parseCssColorComposited(+ raw: string | undefined | null,+ over: Rgb | null,+): Rgb | null {+ if (typeof raw !== 'string') return null;+ const value = raw.trim();+ if (value.length === 0) return null;+ // 先尝试 hex(可能带 alpha)。+ const hexMatch = HEX_RE.exec(value);+ if (hexMatch) {+ const full = expandHexFull(hexMatch[1]);+ if (!full) return null;+ const n = Number.parseInt(full.rgb6, 16);+ if (!Number.isFinite(n)) return null;+ const rgb = { r: (n >> 16) & 255, g: (n >> 8) & 255, b: n & 255 };+ if (full.alpha < 1 && over) return compositeOver(rgb, full.alpha, over);+ return rgb;+ }+ // 函数式 rgba/hsla。+ const fnMatch = /^(rgba?|hsla?)\(([^)]*)\)$/i.exec(value);+ if (!fnMatch) return null;+ const fn = fnMatch[1].toLowerCase();+ const nums = parseNumberList(fnMatch[2]);+ if (!nums || nums.some((n) => !Number.isFinite(n.value))) return null;+ let rgb: Rgb;+ if (fn.startsWith('rgb')) {+ const channel = ({ value: v, percent }: NumericComponent): number =>+ clamp255(percent ? (v * 255) / 100 : v);+ rgb = { r: channel(nums[0]), g: channel(nums[1]), b: channel(nums[2]) };+ } else {+ rgb = hslToRgb(+ angleToDegrees(nums[0]),+ clamp01(nums[1].value / 100),+ clamp01(nums[2].value / 100),+ );+ }+ const alpha = nums[3] !== undefined+ ? clamp01(nums[3].percent ? nums[3].value / 100 : nums[3].value)+ : 1;+ if (alpha < 1 && over) return compositeOver(rgb, alpha, over);+ return rgb;+}++/** RGB → 小写 6 位 hex(与 colors.ts 既有默认值的书写形态一致)。 */+export function toHex({ r, g, b }: Rgb): string {+ const hex = ((clamp255(r) << 16) | (clamp255(g) << 8) | clamp255(b))+ .toString(16)+ .padStart(6, '0');+ return `#${hex}`;+}++/**+ * RGB → `"H S% L%"` 三元组(Cindy `-hsl` token 的形态,消费点写+ * `hsl(var(--xxx))`)。分量四舍五入取整,与既有主题里手写的三元组同格式。+ */+export function toHslTriplet({ r, g, b }: Rgb): string {+ const rn = clamp255(r) / 255;+ const gn = clamp255(g) / 255;+ const bn = clamp255(b) / 255;+ const max = Math.max(rn, gn, bn);+ const min = Math.min(rn, gn, bn);+ const l = (max + min) / 2;+ const d = max - min;+ let h = 0;+ let s = 0;+ if (d > 0) {+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);+ if (max === rn) h = ((gn - bn) / d + (gn < bn ? 6 : 0)) * 60;+ else if (max === gn) h = ((bn - rn) / d + 2) * 60;+ else h = ((rn - gn) / d + 4) * 60;+ }+ return `${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;+}++/** `rgba(r, g, b, a)` 形态(既有主题的 drop-overlay-bg 就是这个书写形态)。 */+export function toRgbaString({ r, g, b }: Rgb, alpha: number): string {+ return `rgba(${clamp255(r)}, ${clamp255(g)}, ${clamp255(b)}, ${alpha})`;+}++/** WCAG 相对亮度。 */+export function relativeLuminance({ r, g, b }: Rgb): number {+ const channel = (v: number): number => {+ const n = clamp255(v) / 255;+ return n <= 0.03928 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++/** WCAG 对比度(1–21)。 */+export function contrastRatio(a: Rgb, b: Rgb): number {+ const la = relativeLuminance(a);+ const lb = relativeLuminance(b);+ const hi = Math.max(la, lb);+ const lo = Math.min(la, lb);+ return (hi + 0.05) / (lo + 0.05);+}++/** 背景是否偏暗——用于在源主题没声明 light/dark 时判定主题类型。 */+export function isDarkBackground(rgb: Rgb): boolean {+ return relativeLuminance(rgb) < 0.2;+}++/** 朝白/黑方向线性插值:amount>0 提亮,amount<0 压暗(0–1 比例)。 */+export function shade(rgb: Rgb, amount: number): Rgb {+ const target = amount >= 0 ? 255 : 0;+ const t = Math.abs(clamp01(Math.abs(amount)));+ return {+ r: clamp255(rgb.r + (target - rgb.r) * t),+ g: clamp255(rgb.g + (target - rgb.g) * t),+ b: clamp255(rgb.b + (target - rgb.b) * t),+ };+}++/** 两色线性混合(t=0 取 a,t=1 取 b)。 */+export function mix(a: Rgb, b: Rgb, t: number): Rgb {+ const k = clamp01(t);+ return {+ r: clamp255(a.r + (b.r - a.r) * k),+ g: clamp255(a.g + (b.g - a.g) * k),+ b: clamp255(a.b + (b.b - a.b) * k),+ };+}diff --git a/apps/desktop/src/shared/theme-import/index.ts b/apps/desktop/src/shared/theme-import/index.tsnew file mode 100644index 0000000000..9df72d5722--- /dev/null+++ b/apps/desktop/src/shared/theme-import/index.ts@@ -0,0 +1,153 @@+/**+ * 外部主题导入的纯函数入口(无 IO)。main 侧只负责选文件、读字节、落盘。+ *+ * 详细设计见 `palette.ts`(模板来源)、`vscode.ts` / `obsidian.ts`(抽取规则)、+ * `protected-tokens.ts`(语义豁免族)。+ */++import { buildThemeColorsFromPalette } from './palette';+import { stripProtectedTokens } from './protected-tokens';+import type {+ ConvertedTheme,+ ThemeConversionResult,+ ThemeImportSource,+} from './types';+import { collectObsidianVars, extractObsidianPalette } from './obsidian';+import { extractVsCodePalette, parseVsCodeThemeJson } from './vscode';++export type { ConvertedTheme, ThemeConversionResult } from './types';+export { TEMPLATE_TOKEN_IDS, buildThemeColorsFromPalette } from './palette';+export { isProtectedToken, stripProtectedTokens } from './protected-tokens';++/** 色板角色总数——报告里 "命中 N/13" 的分母。 */+export const PALETTE_ROLE_COUNT = 13;++const WINDOWS_RESERVED_RE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;++// Maximum slug length. Filesystem limit is 255 bytes; we need room for:+// `-dark` (5) + `-99` (3) + `-local` (6) + `.json` (5) = 19 chars overhead.+const MAX_SLUG_LENGTH = 200;++function toSlug(name: string): string {+ let slug = name+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '');+ if (slug.length === 0) return 'imported-theme';+ if (WINDOWS_RESERVED_RE.test(slug)) slug = `theme-${slug}`;+ if (slug.length > MAX_SLUG_LENGTH) {+ slug = slug.slice(0, MAX_SLUG_LENGTH).replace(/-+$/, '');+ }+ return slug;+}++/**+ * 展示名 → slug。既用作单产物的落盘 baseId,也用作双态产物的 family 键+ * (writer 侧还会再消毒一次并处理文件重名)。+ */+export function themeFamilyId(name: string): string {+ return toSlug(name);+}++/** VSCode 颜色主题 JSON → 转换结果。不是可用主题时返回 null。 */+export function convertVsCodeTheme(+ raw: string,+ fallbackName: string,+): ThemeConversionResult | null {+ const parsed = parseVsCodeThemeJson(raw);+ if (!parsed) return null;+ const extracted = extractVsCodePalette(parsed, fallbackName);+ if (!extracted) {+ // 识别为主题 JSON 但无法抽取色板——可能通过 `include` 继承背景。+ // 报告继承限制而非静默失败。+ if (parsed.include) {+ return {+ themes: [],+ report: {+ source: 'vscode',+ resolvedRoles: 0,+ derivedRoles: [],+ unresolved: [`include:${parsed.include}`],+ skippedProtected: 0,+ },+ };+ }+ return null;+ }+ const built = buildThemeColorsFromPalette(+ extracted.palette,+ extracted.type,+ extracted.markdown,+ );+ const { colors, skipped } = stripProtectedTokens(built);+ return {+ themes: [{ name: extracted.name, type: extracted.type, colors }],+ report: {+ source: 'vscode',+ resolvedRoles: extracted.resolvedRoles,+ derivedRoles: extracted.derivedRoles,+ unresolved: extracted.unresolved,+ skippedProtected: skipped.length,+ },+ };+}++/** Obsidian theme.css → 转换结果(双态 CSS 会产出 light + dark 两个主题)。 */+export function convertObsidianTheme(+ css: string,+ name: string,+): ThemeConversionResult | null {+ const modes = collectObsidianVars(css);+ if (modes.length === 0) return null;++ const themes: ConvertedTheme[] = [];+ const derivedRoles: string[] = [];+ const unresolved: string[] = [];+ const skippedIds = new Set<string>();+ let resolvedRoles = 0;++ for (const mode of modes) {+ const extracted = extractObsidianPalette(mode);+ if (!extracted) {+ // Mode advertised by the stylesheet but background unresolvable — report it.+ unresolved.push(`mode:${mode.type}`);+ continue;+ }+ const built = buildThemeColorsFromPalette(+ extracted.palette,+ extracted.type,+ extracted.markdown,+ );+ const { colors, skipped } = stripProtectedTokens(built);+ themes.push({ name, type: extracted.type, colors });+ resolvedRoles = Math.max(resolvedRoles, extracted.resolvedRoles);+ for (const id of skipped) skippedIds.add(id);+ for (const role of extracted.derivedRoles) {+ if (!derivedRoles.includes(role)) derivedRoles.push(role);+ }+ for (const item of extracted.unresolved) {+ if (!unresolved.includes(item)) unresolved.push(item);+ }+ }++ if (themes.length === 0) return null;+ return {+ themes,+ report: {+ source: 'obsidian',+ resolvedRoles,+ derivedRoles,+ unresolved,+ skippedProtected: skippedIds.size,+ },+ };+}++/** 按扩展名判定源格式;`.css` → Obsidian,`.json`/`.jsonc` → VSCode。 */+export function detectImportSource(fileName: string): ThemeImportSource | null {+ const lower = fileName.toLowerCase();+ if (lower.endsWith('.css')) return 'obsidian';+ if (lower.endsWith('.json') || lower.endsWith('.jsonc')) return 'vscode';+ return null;+}diff --git a/apps/desktop/src/shared/theme-import/obsidian.ts b/apps/desktop/src/shared/theme-import/obsidian.tsnew file mode 100644index 0000000000..8eb6ada150--- /dev/null+++ b/apps/desktop/src/shared/theme-import/obsidian.ts@@ -0,0 +1,520 @@+/**+ * Obsidian 主题(`theme.css`)→ Cindy 色板。+ *+ * ## 这是"调色板导入",不是主题移植+ *+ * Obsidian 主题是任意 CSS:除了 CSS 自定义属性,还大量改选择器、布局、圆角、+ * 字体。我们**只取颜色变量**,其余一律丢弃——这是设计约束而不是偷懒:Cindy 的+ * 布局与排版由自己的设计规范(DESIGN.md §3/§5)负责,不接受外部 CSS 接管。+ *+ * ## 解析范围+ *+ * 从 `.theme-dark{}` / `.theme-light{}` / `body{}` / `:root{}` 里收集自定义属性,+ * 做 `var()` 解引用(含 `var(--x, fallback)` 与 Obsidian v1 的 `--color-base-NN`+ * 色阶),再按 Obsidian 官方变量名映射。`color-mix()` 一类无法静态求值的写法会+ * 跳过并计入报告——不猜值。+ *+ * 变量名以 Obsidian 官方 CSS variables 文档为准(`--background-primary` /+ * `--text-normal` / `--interactive-accent` / `--h1-color` 等长期稳定的公开 API)。+ */++import { isDarkBackground, parseCssColor, parseCssColorComposited, shade, type Rgb } from './color';+import type { MarkdownPalette, ThemePalette, ThemeTypeName } from './palette';++type VarMap = Map<string, string>;++interface CssRule {+ selector: string;+ body: string;+}++/**+ * 剥掉 CSS 块注释。必须在切规则之前做:主题文件普遍在规则前写版权/说明注释,+ * 不剥的话选择器会连着前面那段注释一起被切出来(实测 `body` 变成+ * "注释文本 + 换行 + body"),根级选择器判定直接失配,整段基底变量丢失。+ * 字符串字面量里的注释起始符不动。+ */+export function stripCssComments(source: string): string {+ let out = '';+ let quote: string | null = null;+ for (let i = 0; i < source.length; i += 1) {+ const c = source[i];+ if (quote !== null) {+ out += c;+ if (c === '\\') {+ if (i + 1 < source.length) {+ out += source[i + 1];+ i += 1;+ }+ continue;+ }+ if (c === quote) quote = null;+ continue;+ }+ if (c === '"' || c === "'") {+ quote = c;+ out += c;+ continue;+ }+ if (c === '/' && source[i + 1] === '*') {+ const end = source.indexOf('*/', i + 2);+ i = end === -1 ? source.length : end + 1;+ continue;+ }+ out += c;+ }+ return out;+}++const MAX_AT_RULE_DEPTH = 8;++/**+ * 极简 CSS 规则扫描:按大括号深度切出 `selector { body }` 对;at-rule+ * (`@media` 等) 的内容递归处理,让包在 media query 里的主题块也能被读到。+ */+export function collectCssRules(source: string): CssRule[] {+ return scanCssRules(stripCssComments(source), 0);+}++/**+ * 从 `{` 起找配对的 `}`,返回它的下一个位置(找不到则到末尾)。+ *+ * 字符串字面量里的大括号不计入深度——`content: "{"`、带大括号的 data URL 都是+ * 合法 CSS,按裸字符数深度会把后续 `.theme-light` / `.theme-dark` 规则整段吞掉。+ */+function findBlockEnd(source: string, openIndex: number): number {+ let depth = 1;+ let quote: string | null = null;+ let j = openIndex + 1;+ while (j < source.length && depth > 0) {+ const c = source[j];+ if (quote !== null) {+ if (c === '\\') {+ j += 2;+ continue;+ }+ if (c === quote) quote = null;+ j += 1;+ continue;+ }+ if (c === '"' || c === "'") quote = c;+ else if (c === '{') depth += 1;+ else if (c === '}') depth -= 1;+ j += 1;+ }+ return j;+}++const SKIP_AT_RULE_RE = /^@(supports|font-face|keyframes|counter-style|page)\b/i;+const PRINT_MEDIA_RE = /^@media\b[^{]*\bprint\b/i;+const VIEWPORT_MEDIA_RE = /^@media\b[^{]*\b(max-width|max-height)\b/i;++function shouldRecurseAtRule(selector: string): boolean {+ if (SKIP_AT_RULE_RE.test(selector)) return false;+ if (PRINT_MEDIA_RE.test(selector)) return false;+ if (VIEWPORT_MEDIA_RE.test(selector)) return false;+ return true;+}++const NESTED_THEME_SELECTOR_RE = /(?:^|[,\s])&\s*\.theme-(dark|light)/i;++function scanCssRules(source: string, depth: number): CssRule[] {+ if (depth >= MAX_AT_RULE_DEPTH) return [];+ const rules: CssRule[] = [];+ let selectorStart = 0;+ let i = 0;+ let quote: string | null = null;+ while (i < source.length) {+ const ch = source[i];+ if (quote !== null) {+ if (ch === '\\') {+ i += 2;+ continue;+ }+ if (ch === quote) quote = null;+ i += 1;+ continue;+ }+ if (ch === '"' || ch === "'") {+ quote = ch;+ i += 1;+ continue;+ }+ if (ch === ';') {+ const pending = source.slice(selectorStart, i).trim();+ if (pending.startsWith('@')) {+ i += 1;+ selectorStart = i;+ continue;+ }+ i += 1;+ selectorStart = i;+ continue;+ }+ if (ch === '{') {+ const selector = source.slice(selectorStart, i).trim();+ const j = findBlockEnd(source, i);+ const body = source.slice(i + 1, Math.max(i + 1, j - 1));+ if (selector.startsWith('@')) {+ if (shouldRecurseAtRule(selector)) {+ rules.push(...scanCssRules(body, depth + 1));+ }+ } else if (selector.length > 0) {+ rules.push({ selector, body });+ // CSS nesting: `body { &.theme-dark { ... } }` — recurse into the+ // body so nested theme selectors are collected as separate rules.+ // Works at any depth so at-rule-wrapped nesting is also captured.+ // Only emit children whose resolved selector passes selectorMode()+ // as a root-level theme rule — prevents component-scoped descendants+ // (`.theme-dark .modal { ... }`) from overriding global palette.+ const nested = scanCssRules(body, depth + 1);+ for (const child of nested) {+ if (!NESTED_THEME_SELECTOR_RE.test(child.selector)) continue;+ // Expand `&` per comma-separated parent part to avoid generating+ // invalid selectors like `body, html.theme-dark` from `body, html`.+ const parentParts = selector.split(',').map((p) => p.trim()).filter(Boolean);+ const childParts = child.selector.split(',').map((p) => p.trim()).filter(Boolean);+ const expanded = childParts.flatMap((cp) =>+ parentParts.map((pp) => cp.replace(/&/g, pp)),+ );+ const resolved = expanded.join(', ');+ if (selectorMode(resolved) !== null) {+ rules.push({ selector: resolved, body: child.body });+ }+ }+ }+ i = j;+ selectorStart = i;+ continue;+ }+ if (ch === '}') {+ i += 1;+ selectorStart = i;+ continue;+ }+ i += 1;+ }+ return rules;+}++/**+ * 抽一个 declaration block 里的自定义属性。+ * `!important` 声明锁定变量不被后续普通声明覆盖。+ * 跳过嵌套块(CSS nesting `& .child { ... }`)以免把子选择器的声明误收为根级。+ */+function collectCustomProps(body: string, into: VarMap, locked?: Set<string>): void {+ const flat = stripNestedBlocks(body);+ for (const m of flat.matchAll(/(--[A-Za-z0-9_-]+)\s*:\s*([^;]+)(?:;|$)/g)) {+ const name = m[1].trim();+ const rawValue = m[2].trim();+ const isImportant = /!important\s*$/i.test(rawValue);+ const value = rawValue.replace(/!important/gi, '').trim();+ if (value.length === 0) continue;+ if (locked?.has(name) && !isImportant) continue;+ into.set(name, value);+ if (isImportant) locked?.add(name);+ }+}++function stripNestedBlocks(body: string): string {+ let out = '';+ let depth = 0;+ let quote: string | null = null;+ for (let i = 0; i < body.length; i += 1) {+ const c = body[i];+ if (quote !== null) {+ if (c === '\\') {+ if (depth === 0) out += c + (body[i + 1] ?? '');+ i += 1;+ continue;+ }+ if (c === quote) quote = null;+ if (depth === 0) out += c;+ continue;+ }+ if (c === '"' || c === "'") {+ quote = c;+ if (depth === 0) out += c;+ continue;+ }+ if (c === '{') { depth += 1; continue; }+ if (c === '}') { if (depth > 0) depth -= 1; continue; }+ if (depth === 0) out += c;+ }+ return out;+}++const MAX_VAR_DEPTH = 8;+const MAX_EXPANDED_LENGTH = 100_000;++/**+ * 把值里的 `var(--x)` / `var(--x, fallback)` 递归展开成字面量。+ * 展开后仍含 `var(` 或无法求值时由调用方判定失败。+ * 长度超过 MAX_EXPANDED_LENGTH 时中止(防恶意主题指数膨胀阻塞主进程)。+ */+export function resolveVarValue(+ raw: string,+ vars: VarMap,+ depth = 0,+): string {+ if (depth >= MAX_VAR_DEPTH || !raw.includes('var(')) return raw;+ if (raw.length > MAX_EXPANDED_LENGTH) return raw;+ let changed = false;+ let budget = MAX_EXPANDED_LENGTH;+ const replaced = raw.replace(+ /var\(\s*(--[A-Za-z0-9_-]+)\s*(?:,([^()]*(?:\([^()]*\)[^()]*)*))?\)/g,+ (_all, name: string, fallback: string | undefined) => {+ if (budget <= 0) return _all;+ const hit = vars.get(name);+ if (hit !== undefined) {+ budget -= hit.length;+ changed = true;+ return hit;+ }+ if (fallback !== undefined) {+ budget -= fallback.length;+ changed = true;+ return fallback.trim();+ }+ return _all;+ },+ );+ if (!changed || replaced.length > MAX_EXPANDED_LENGTH) return replaced;+ return resolveVarValue(replaced, vars, depth + 1);+}++export interface ObsidianExtraction {+ palette: ThemePalette;+ type: ThemeTypeName;+ markdown: MarkdownPalette;+ derivedRoles: string[];+ resolvedRoles: number;+ unresolved: string[];+}++/** 按模式聚合出的变量表。 */+interface ModeVars {+ type: ThemeTypeName;+ vars: VarMap;+}++function selectorMode(selector: string): ThemeTypeName | 'base' | null {+ // 逗号分隔的选择器列表(`.theme-dark, .theme-light { ... }`)拆开逐条判定。+ const parts = selector.split(',').map((p) => p.toLowerCase().trim()).filter((p) => p.length > 0);+ if (parts.length === 0) return null;+ // 多段选择器中只要有一段是根级 theme class 就算;两种都有视为 base。+ let hasDark = false;+ let hasLight = false;+ let hasBase = false;+ for (const s of parts) {+ if (/^(body|html|:root|\*)?\s*\.theme-(dark|light)\s*$/.test(s)) {+ if (s.includes('.theme-dark')) hasDark = true;+ if (s.includes('.theme-light')) hasLight = true;+ } else if (/^(:root|html|body|\*)$/.test(s)) {+ hasBase = true;+ }+ }+ if (hasDark && hasLight) return 'base';+ // Mixed list containing both a root element and a theme class (e.g.+ // `:root, .theme-dark`) applies in all modes — classify as base.+ if ((hasDark || hasLight) && hasBase) return 'base';+ if (hasDark) return 'dark';+ if (hasLight) return 'light';+ // 纯根选择器(无 theme class)——但必须是 `:root` / `body` / `html` 自身,+ // 不能是 `body .modal` 这种后代组合。+ if (hasBase || (parts.length === 1 && /^(:root|html|body|\*)$/.test(parts[0]))) return 'base';+ return null;+}++/** 从整份 CSS 聚合出 light / dark 两套变量表(缺失的模式不返回)。 */+export function collectObsidianVars(source: string): ModeVars[] {+ const base: VarMap = new Map();+ const dark: VarMap = new Map();+ const light: VarMap = new Map();+ const baseLocked = new Set<string>();+ const darkLocked = new Set<string>();+ const lightLocked = new Set<string>();+ for (const rule of collectCssRules(source)) {+ const mode = selectorMode(rule.selector);+ if (mode === null) continue;+ if (mode === 'base') {+ collectCustomProps(rule.body, base, baseLocked);+ continue;+ }+ collectCustomProps(+ rule.body,+ mode === 'dark' ? dark : light,+ mode === 'dark' ? darkLocked : lightLocked,+ );+ }+ const out: ModeVars[] = [];+ // Merge base into mode. Base !important wins over non-important mode values,+ // but a mode-specific !important overrides the base (higher specificity in CSS).+ const merge = (mode: VarMap, modeLocked: Set<string>): VarMap => {+ const merged = new Map([...base, ...mode]);+ for (const name of baseLocked) {+ if (modeLocked.has(name)) continue;+ const baseVal = base.get(name);+ if (baseVal !== undefined) merged.set(name, baseVal);+ }+ return merged;+ };+ if (dark.size > 0) out.push({ type: 'dark', vars: merge(dark, darkLocked) });+ if (light.size > 0) out.push({ type: 'light', vars: merge(light, lightLocked) });+ // base-only fallback:只有根级声明且无显式模式块时,按背景亮度推断类型。+ if (out.length === 0 && base.size > 0) {+ const bg = readColor(base, ['--background-primary', '--color-base-00']);+ out.push({+ type: bg && isDarkBackground(bg) ? 'dark' : 'light',+ vars: base,+ });+ }+ // 双态补全:如果只有一个显式模式块而 base 有可用色板,base 作为缺失模式的来源。+ // 例如 `:root` 定义 light 色板 + `.theme-dark` 覆盖 → 应同时产出 light 变体。+ if (out.length === 1 && base.size > 0) {+ const existing = out[0].type;+ const bg = readColor(base, ['--background-primary', '--color-base-00']);+ const baseType: ThemeTypeName = bg && isDarkBackground(bg) ? 'dark' : 'light';+ if (baseType !== existing) {+ out.push({ type: baseType, vars: base });+ }+ }+ return out;+}++/** 取首个能求值成颜色的变量。`compositeBg` 不为 null 时,半透明值合成到该底色上。 */+function readColor(vars: VarMap, names: string[], unresolved?: string[], compositeBg?: Rgb | null): Rgb | null {+ for (const name of names) {+ const raw = vars.get(name);+ if (raw === undefined) continue;+ const resolved = resolveVarValue(raw, vars);+ const rgb = compositeBg+ ? parseCssColorComposited(resolved, compositeBg)+ : parseCssColor(resolved);+ if (rgb) return rgb;+ unresolved?.push(name);+ }+ return null;+}++/** 把一套变量表转成 Cindy 色板。背景色都读不到时返回 null。 */+export function extractObsidianPalette({ type, vars }: ModeVars): ObsidianExtraction | null {+ const unresolved: string[] = [];+ const derivedRoles: string[] = [];+ let resolvedRoles = 0;++ const role = (name: string, names: string[], derive: () => Rgb, compositeBg?: Rgb | null): Rgb => {+ const hit = readColor(vars, names, unresolved, compositeBg);+ if (hit) {+ resolvedRoles += 1;+ return hit;+ }+ derivedRoles.push(name);+ return derive();+ };++ const surface = readColor(vars, ['--background-primary', '--color-base-00'], unresolved);+ if (!surface) return null;+ resolvedRoles += 1;++ const dark = type === 'dark';+ const step = (base: Rgb, amount: number): Rgb => shade(base, dark ? amount : -amount);++ const elevated = role(+ 'elevated',+ ['--background-secondary', '--background-primary-alt', '--color-base-10'],+ () => step(surface, 0.05),+ surface,+ );+ const hover = (() => {+ const hit = readColor(vars, ['--background-modifier-hover', '--color-base-20'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('hover');+ return step(surface, 0.08);+ })();+ const chip = (() => {+ const hit = readColor(vars, ['--background-secondary-alt', '--background-modifier-active-hover', '--color-base-25'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('chip');+ return step(hover, 0.04);+ })();+ const border = (() => {+ const hit = readColor(vars, ['--background-modifier-border', '--divider-color', '--color-base-30'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('border');+ return step(surface, 0.2);+ })();++ const textPrimary = (() => {+ const hit = readColor(vars, ['--text-normal', '--color-base-100'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('textPrimary');+ return dark ? { r: 212, g: 212, b: 212 } : { r: 38, g: 38, b: 38 };+ })();+ const textSecondary = (() => {+ const hit = readColor(vars, ['--text-muted', '--color-base-70'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('textSecondary');+ return shade(textPrimary, dark ? -0.28 : 0.28);+ })();+ const textTertiary = (() => {+ const hit = readColor(vars, ['--text-faint', '--color-base-50'], unresolved, surface);+ if (hit) { resolvedRoles += 1; return hit; }+ derivedRoles.push('textTertiary');+ return shade(textSecondary, dark ? -0.16 : 0.16);+ })();+ const textDisabled = role(+ 'textDisabled',+ ['--color-base-40'],+ // Obsidian 没有 disabled 文字概念,从 faint 再弱一档。+ // 注意: --text-selection 是选区背景色而非前景色,不能用在这里。+ () => shade(textTertiary, dark ? -0.25 : 0.25),+ );++ const accentPrimary = role(+ 'accentPrimary',+ ['--interactive-accent', '--color-accent', '--text-accent'],+ () => textPrimary,+ );+ const accentSoftHit = readColor(vars, ['--text-accent-hover', '--color-accent-2']);+ const accentSoft = accentSoftHit ?? shade(accentPrimary, dark ? 0.22 : -0.28);+ if (accentSoftHit) resolvedRoles += 1;+ else derivedRoles.push('accentSoft');+ const accentDeepHit = readColor(vars, ['--interactive-accent-hover', '--color-accent-1']);+ const accentDeep = accentDeepHit ?? shade(accentPrimary, dark ? -0.22 : -0.28);+ if (accentDeepHit) resolvedRoles += 1;+ else derivedRoles.push('accentDeep');+ const elevatedSoft = dark ? elevated : step(elevated, 0.08);+ derivedRoles.push('elevatedSoft');++ const headings = ['--h1-color', '--h2-color', '--h3-color', '--h4-color', '--h5-color', '--h6-color']+ .map((name) => readColor(vars, [name], unresolved));+ const strong = readColor(vars, ['--bold-color', '--text-bold'], unresolved);+ const markdown: MarkdownPalette = {+ ...(headings.some(Boolean) ? { headings } : {}),+ ...(strong ? { strong } : {}),+ };++ return {+ palette: {+ surface,+ elevated,+ elevatedSoft,+ hover,+ chip,+ border,+ textPrimary,+ textSecondary,+ textTertiary,+ textDisabled,+ accentPrimary,+ accentSoft,+ accentDeep,+ },+ type,+ markdown,+ derivedRoles,+ resolvedRoles,+ unresolved,+ };+}diff --git a/apps/desktop/src/shared/theme-import/palette.ts b/apps/desktop/src/shared/theme-import/palette.tsnew file mode 100644index 0000000000..b5ba9c1e61--- /dev/null+++ b/apps/desktop/src/shared/theme-import/palette.ts@@ -0,0 +1,345 @@+/**+ * 色板 → Cindy token 模板(纯函数)。+ *+ * ## 这份模板不是新设计,是把仓库里已有的人工映射抽出来+ *+ * `renderer/themes/builtin/` 下 7 个社区主题(one-dark-pro / github-dark /+ * eclipse / material-ocean-hc / monokai-pro / atom-one-light / solarized-light)+ * 都是人工从 VSCode 主题移植的,它们 `colors` 的 key 集合**逐字相同**(91 个+ * token = 35 个 Tier1 slot + 56 个 alias / singleton),值全部由同一组 13 个色板+ * 常量派生。本文件就是那套派生规则的代码化:+ *+ * - 5 个 dark 主题逐 key 一致(唯一例外:github-dark 把 4 个 on-accent 前景+ * 从 surface 改成纯白,属人工微调)+ * - 2 个 light 主题逐 key 一致+ * - light 与 dark 的差异共 22 处,逐条写在下面的 `pick()` 调用里+ *+ * ## 为什么用 allow-list+ *+ * 模板产出这 91 个基础 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` 只作为回归断言的+ * 第二道闸。+ */++import {+ contrastRatio,+ toHex,+ toHslTriplet,+ toRgbaString,+ type Rgb,+} from './color';++export type ThemeTypeName = 'light' | 'dark';++/** 13 个色板角色——与既有 builtin 主题头部的常量一一对应。 */+export interface ThemePalette {+ /** 页面主背景(VSCode `editor.background` / Obsidian `--background-primary`)。 */+ surface: Rgb;+ /** Card / 弹窗抬起一层(`sideBar.background` / `--background-secondary`)。 */+ elevated: Rgb;+ /** light 专用的"更沉一档"卡片层;dark 主题传 elevated 同值即可。 */+ elevatedSoft: Rgb;+ /** hover 背景(`list.hoverBackground` / `--background-modifier-hover`)。 */+ hover: Rgb;+ /** chip / pill / 选中行背景。 */+ chip: Rgb;+ /** 1px 分界(`panel.border` / `--background-modifier-border`)。 */+ border: Rgb;+ textPrimary: Rgb;+ textSecondary: Rgb;+ textTertiary: Rgb;+ textDisabled: Rgb;+ accentPrimary: Rgb;+ /** accent 提亮档(dark 主题的链接色 / info 色)。 */+ accentSoft: Rgb;+ /** accent 压暗档(pressed;light 主题的链接色也走这档的 primary/deep 组合)。 */+ accentDeep: Rgb;+}++/** Markdown 标题 / 加粗色——源主题提供时才产出对应 token(Obsidian `--hN-color`)。 */+export interface MarkdownPalette {+ /** h1…h6,缺省项传 null / undefined。 */+ headings?: Array<Rgb | null | undefined>;+ strong?: Rgb | null;+}++const MARKDOWN_HEADING_TOKENS = [+ 'md-h1-fg',+ 'md-h2-fg',+ 'md-h3-fg',+ 'md-h4-fg',+ 'md-h5-fg',+ 'md-h6-fg',+] as const;++/**+ * 模板产出的 91 个 token id。导出供测试断言"与 builtin 主题 key 集合一致",+ * 以及供 importer 统计命中数量。+ */+export const TEMPLATE_TOKEN_IDS: readonly string[] = [+ // ── Tier1 语义 slot(35) ──+ 'surface',+ 'surface-hsl',+ 'surface-elevated',+ 'surface-elevated-soft',+ 'surface-card-ivory',+ 'surface-chip',+ 'surface-chip-alt',+ 'surface-hover',+ 'surface-hover-soft',+ 'surface-hover-hsl',+ 'surface-on-card',+ 'border-default',+ 'border-default-hsl',+ 'border-shadcn-hsl',+ 'border-transparent-mixed',+ 'text-primary',+ 'text-primary-on-dark',+ 'text-primary-emphasis',+ 'text-primary-inv',+ 'text-primary-body-strong',+ 'text-primary-hsl',+ 'text-secondary',+ 'text-secondary-cross',+ 'text-secondary-mid',+ 'text-tertiary',+ 'text-tertiary-stone',+ 'text-tertiary-mid',+ 'text-tertiary-hsl',+ 'text-disabled',+ 'text-disabled-tertiary',+ 'accent-cta-bg',+ 'accent-cta-bg-pure',+ 'accent-emphasis',+ 'accent-soft',+ 'accent-hover',+ 'accent-pure-cta-fg',+ 'status-badge-fg',+ // ── alias / singleton(56) ──+ 'accent',+ 'agent-actions-rail',+ 'ask-checkbox-border',+ 'background',+ 'chat-input-chip-border',+ 'chat-input-text',+ 'color-primary',+ 'confirm-bg',+ 'confirm-btn-primary-bg',+ 'confirm-btn-primary-text',+ 'confirm-btn-secondary-border',+ 'confirm-btn-secondary-hover',+ 'confirm-btn-secondary-text',+ 'confirm-title',+ 'drop-overlay-bg',+ 'file-chip-bg',+ 'file-remove-bg',+ 'info-700',+ 'model-trigger-hover',+ 'msg-link',+ 'msg-scrollbar-hover',+ 'muted',+ 'muted-foreground',+ 'perm-allow-btn-bg',+ 'perm-allow-btn-text',+ 'perm-allow-kbd-bg',+ 'perm-allow-kbd-border',+ 'perm-code-bg',+ 'perm-item-selected-bg',+ 'plan-outline-active-bg',+ 'plan-toolbar-btn-hover-bg',+ 'popover',+ 'primary-foreground',+ 'search-match-fg',+ 'secondary',+ 'settings-btn-primary-text',+ 'settings-btn-secondary-hover-bg',+ 'text-placeholder',+ 'settings-integration-avatar-bg',+ 'settings-logout-bg',+ 'settings-menu-bg-hover',+ 'settings-menu-bg-selected',+ 'settings-source-link',+ 'settings-theme-auto-dark',+ 'sidebar-action-icon',+ 'sidebar-item-active',+ 'splash-bg',+ 'splash-text',+ 'splash-text-destructive',+ 'splash-text-muted',+ 'titlebar-icon',+ 'tooltip-bg',+ 'tooltip-text',+ 'update-btn-border',+ 'update-btn-text',+];++const WHITE: Rgb = { r: 255, g: 255, b: 255 };+const BLACK: Rgb = { r: 0, g: 0, b: 0 };++/**+ * 把色板展开成 Cindy token map。`type` 决定 22 处 light / dark 分支——取值依据+ * 全部来自既有 builtin 主题的实测对照,不是自由发挥。+ */+export function buildThemeColorsFromPalette(+ palette: ThemePalette,+ type: ThemeTypeName,+ markdown?: MarkdownPalette,+): Record<string, string> {+ const dark = type === 'dark';+ const pick = <T>(darkValue: T, lightValue: T): T => (dark ? darkValue : lightValue);++ const surface = toHex(palette.surface);+ const elevated = toHex(palette.elevated);+ const elevatedSoft = toHex(palette.elevatedSoft);+ const hover = toHex(palette.hover);+ const chip = toHex(palette.chip);+ const border = toHex(palette.border);+ const textPrimary = toHex(palette.textPrimary);+ const textSecondary = toHex(palette.textSecondary);+ const textTertiary = toHex(palette.textTertiary);+ const textDisabled = toHex(palette.textDisabled);+ const accentPrimary = toHex(palette.accentPrimary);+ const accentSoft = toHex(palette.accentSoft);+ const accentDeep = toHex(palette.accentDeep);+ const white = toHex(WHITE);++ const surfaceHsl = toHslTriplet(palette.surface);+ const elevatedHsl = toHslTriplet(palette.elevated);+ const hoverHsl = toHslTriplet(palette.hover);+ const chipHsl = toHslTriplet(palette.chip);+ const borderHsl = toHslTriplet(palette.border);+ const textPrimaryHsl = toHslTriplet(palette.textPrimary);+ const textSecondaryHsl = toHslTriplet(palette.textSecondary);+ const textTertiaryHsl = toHslTriplet(palette.textTertiary);++ /** accent 底上的前景:优先沿用既有主题的模式惯例(dark=surface, light=white),+ * 但若对比度不足 3:1 则按实际对比度选黑/白。阈值与既有 builtin 主题行为一致+ * (它们在 3:1–4.5:1 区间也使用 white)。 */+ const defaultOnAccent = pick(palette.surface, WHITE);+ const MIN_CONTRAST = 3;+ const onAccent = contrastRatio(palette.accentPrimary, defaultOnAccent) >= MIN_CONTRAST+ ? pick(surface, white)+ : (contrastRatio(palette.accentPrimary, WHITE) >= contrastRatio(palette.accentPrimary, BLACK)+ ? white : toHex(BLACK));+ /** dark 用 accent 提亮档做链接/info,light 用压暗档才够对比度。 */+ const accentReadable = pick(accentSoft, accentDeep);+ /** 链接色:dark 提亮档,light 直接用 primary。 */+ const linkColor = pick(accentSoft, accentPrimary);+ /** 弱化前景:dark 用 disabled 档,light 用 tertiary(浅底上 disabled 太淡)。 */+ const mutedIcon = pick(textDisabled, textTertiary);++ const colors: Record<string, string> = {+ // ── Tier1 语义 slot ──+ surface,+ 'surface-hsl': surfaceHsl,+ 'surface-elevated': elevated,+ 'surface-elevated-soft': pick(elevated, elevatedSoft),+ 'surface-card-ivory': elevated,+ 'surface-chip': chip,+ 'surface-chip-alt': pick(chip, elevatedSoft),+ 'surface-hover': hover,+ 'surface-hover-soft': pick(hover, surface),+ 'surface-hover-hsl': hoverHsl,+ 'surface-on-card': pick(surface, elevated),+ 'border-default': border,+ 'border-default-hsl': borderHsl,+ 'border-shadcn-hsl': borderHsl,+ 'border-transparent-mixed': pick(border, 'transparent'),+ 'text-primary': textPrimary,+ 'text-primary-on-dark': textPrimary,+ 'text-primary-emphasis': textPrimary,+ 'text-primary-inv': textPrimary,+ 'text-primary-body-strong': textPrimary,+ 'text-primary-hsl': textPrimaryHsl,+ 'text-secondary': textSecondary,+ 'text-secondary-cross': textSecondary,+ 'text-secondary-mid': textSecondary,+ 'text-tertiary': textTertiary,+ 'text-tertiary-stone': textTertiary,+ 'text-tertiary-mid': textTertiary,+ 'text-tertiary-hsl': textTertiaryHsl,+ 'text-disabled': textDisabled,+ 'text-disabled-tertiary': textDisabled,+ 'accent-cta-bg': accentPrimary,+ 'accent-cta-bg-pure': accentPrimary,+ 'accent-emphasis': accentPrimary,+ 'accent-soft': pick(accentSoft, accentDeep),+ 'accent-hover': accentDeep,+ 'accent-pure-cta-fg': onAccent,+ 'status-badge-fg': '#1F1F1F',++ // ── alias / singleton ──+ accent: hoverHsl,+ 'agent-actions-rail': border,+ 'ask-checkbox-border': mutedIcon,+ background: surfaceHsl,+ 'chat-input-chip-border': border,+ 'chat-input-text': textPrimary,+ 'color-primary': textPrimary,+ 'confirm-bg': elevated,+ 'confirm-btn-primary-bg': accentPrimary,+ 'confirm-btn-primary-text': onAccent,+ 'confirm-btn-secondary-border': border,+ // 叠层方向随模式反转(深底叠白 / 浅底叠黑),无法用单值表达。+ 'confirm-btn-secondary-hover': pick(+ 'rgba(255, 255, 255, 0.06)',+ 'rgba(0, 0, 0, 0.06)',+ ),+ 'confirm-btn-secondary-text': textPrimary,+ 'confirm-title': textPrimary,+ 'drop-overlay-bg': toRgbaString(palette.accentPrimary, 0.1),+ 'file-chip-bg': pick(border, chip),+ 'file-remove-bg': mutedIcon,+ 'info-700': accentReadable,+ 'model-trigger-hover': hover,+ 'msg-link': linkColor,+ 'msg-scrollbar-hover': mutedIcon,+ muted: chipHsl,+ 'muted-foreground': textSecondaryHsl,+ 'perm-allow-btn-bg': accentPrimary,+ 'perm-allow-btn-text': onAccent,+ 'perm-allow-kbd-bg': chip,+ 'perm-allow-kbd-border': border,+ 'perm-code-bg': pick(surface, elevatedSoft),+ 'perm-item-selected-bg': chip,+ 'plan-outline-active-bg': chip,+ 'plan-toolbar-btn-hover-bg': hover,+ popover: elevatedHsl,+ 'primary-foreground': pick(surfaceHsl, '0 0% 100%'),+ 'search-match-fg': textPrimaryHsl,+ secondary: pick(elevatedHsl, chipHsl),+ 'settings-btn-primary-text': onAccent,+ 'settings-btn-secondary-hover-bg': hover,+ // placeholder 必须"读着像空",两个模式都取比 tertiary 更淡的 disabled 档。+ 'text-placeholder': textDisabled,+ 'settings-integration-avatar-bg': chip,+ 'settings-logout-bg': chip,+ 'settings-menu-bg-hover': hover,+ 'settings-menu-bg-selected': chip,+ 'settings-source-link': linkColor,+ 'settings-theme-auto-dark': surface,+ 'sidebar-action-icon': textTertiaryHsl,+ 'sidebar-item-active': chipHsl,+ 'splash-bg': surfaceHsl,+ 'splash-text': textSecondaryHsl,+ 'splash-text-destructive': textPrimaryHsl,+ 'splash-text-muted': textTertiaryHsl,+ 'titlebar-icon': textSecondaryHsl,+ // tooltip 在 light 下反色(深底浅字),dark 下同底色。+ 'tooltip-bg': pick(surface, textPrimary),+ 'tooltip-text': pick(textPrimary, surface),+ 'update-btn-border': accentPrimary,+ 'update-btn-text': accentPrimary,+ };++ MARKDOWN_HEADING_TOKENS.forEach((token, index) => {+ const value = markdown?.headings?.[index];+ if (value) colors[token] = toHex(value);+ });+ if (markdown?.strong) colors['md-strong-fg'] = toHex(markdown.strong);++ return colors;+}diff --git a/apps/desktop/src/shared/theme-import/protected-tokens.ts b/apps/desktop/src/shared/theme-import/protected-tokens.tsnew file mode 100644index 0000000000..3f6891045f--- /dev/null+++ b/apps/desktop/src/shared/theme-import/protected-tokens.ts@@ -0,0 +1,78 @@+/**+ * 外部主题不得接管的 token(语义豁免族)。+ *+ * 依据 `docs/design-rules/DESIGN.md` §10「Semantic Exemption Colors+ * (theme-invariant)」与 §16(登录链路 `--login-*` 全族「任何 builtin/扩展主题都+ * 不应 override」)。这些色值承载的是**语义而非风格**——危险红、警告橙、焦点蓝、+ * diff 绿红、登录页品牌体系。一个高饱和的外部主题若把它们一起染掉,用户就会+ * 失去"红=危险 / 橙=进行中"这层可依赖的判断。+ *+ * 主保障是 `palette.ts` 的 allow-list(模板压根不产出这些 key);本清单是第二道+ * 闸:importer 落盘前过滤,单测断言「模板输出 ∩ 本清单 == ∅」,防后人往模板里+ * 顺手加豁免色。+ *+ * 注意:手写的 builtin 主题不受本清单约束(例如 solarized-light 有理由地+ * override 了 `perm-auto-selected-text`)。这里只约束**自动导入**的产物。+ */++/** 整族保护的前缀。 */+const PROTECTED_PREFIXES = [+ // 登录链路独立反色体系 + 浏览器回调卡(§16)+ 'login-',+ // diff 渲染走 GitHub 语义色板+ 'diff-',+ // 错误告警卡子系统+ 'error-',+ // 模态 / lightbox 遮罩+ 'overlay-',+] as const;++/** 逐个保护的 token。 */+const PROTECTED_IDS = new Set<string>([+ // 危险语义+ 'destructive',+ // 警告 / 进行中语义(Thinking Orange 全族,跨主题恒定)+ 'warning-accent',+ 'warning-bg-soft',+ 'warning-fg',+ 'status-bar-accent',+ 'settings-integration-warning',+ 'plan-action-approve-icon-bg',+ 'plan-action-approve-icon-fg',+ // 权限语义色(自动审批蓝 / bypass 橙)+ 'perm-auto-selected-text',+ 'perm-bypass-selected-text',+ // 无障碍焦点环+ 'focus-ring',+ 'focus-ring-soft',+ // 阴影:跨主题恒定,不是可换肤的风格项+ 'shadow-menu',+ 'cmd-palette-shadow',+ 'confirm-shadow',+]);++/** 该 token 是否属于语义豁免族(外部主题导入时必须跳过)。 */+export function isProtectedToken(id: string): boolean {+ if (PROTECTED_IDS.has(id)) return true;+ return PROTECTED_PREFIXES.some((prefix) => id.startsWith(prefix));+}++/**+ * 过滤掉豁免族。返回过滤后的 map 与被拦下的 token id——importer 把数量放进+ * 导入报告,让用户知道"有些颜色我们故意没跟着改"。+ */+export function stripProtectedTokens(colors: Record<string, string>): {+ colors: Record<string, string>;+ skipped: string[];+} {+ const out: Record<string, string> = {};+ const skipped: string[] = [];+ for (const [id, value] of Object.entries(colors)) {+ if (isProtectedToken(id)) {+ skipped.push(id);+ continue;+ }+ out[id] = value;+ }+ return { colors: out, skipped };+}diff --git a/apps/desktop/src/shared/theme-import/types.ts b/apps/desktop/src/shared/theme-import/types.tsnew file mode 100644index 0000000000..4fb3b5117a--- /dev/null+++ b/apps/desktop/src/shared/theme-import/types.ts@@ -0,0 +1,56 @@+/** 外部主题导入的跨进程协议类型(main 转换 → renderer 展示报告)。 */++import type { ThemeTypeName } from './palette';++export type ThemeImportSource = 'vscode' | 'obsidian';++/** 一次转换产出的单个主题(Obsidian 双态 CSS 会产出两个)。 */+export interface ConvertedTheme {+ /** 展示名,取自源文件的 name / manifest / 文件名。 */+ name: string;+ type: ThemeTypeName;+ /** 已过滤豁免族的 Cindy token map。 */+ colors: Record<string, string>;+}++/** 转换报告——如实告诉用户哪些东西没跟过来。 */+export interface ThemeConversionReport {+ source: ThemeImportSource;+ /** 直接从源文件读到的色板角色数(13 个角色里命中几个)。 */+ resolvedRoles: number;+ /** 源文件没提供、由我们从已知色推导出来的角色名。 */+ derivedRoles: string[];+ /** 源文件里出现但无法静态求值的项(`color-mix()`、未定义的 var() 等)。 */+ unresolved: string[];+ /** 被语义豁免族拦下的 token 数。 */+ skippedProtected: number;+}++export interface ThemeConversionResult {+ themes: ConvertedTheme[];+ report: ThemeConversionReport;+}++/** 落盘后的单个产物(跨 IPC 返回给 renderer 的部分不含绝对路径)。 */+export interface ImportedThemeFile {+ /** 盘上文件名去掉扩展名后的 id(未含 `-local` 后缀)。 */+ id: string;+ name: string;+ type: ThemeTypeName;+}++/** main 内部用:带文件路径,用于回滚。不跨 IPC。 */+export interface ImportedThemeFileInternal extends ImportedThemeFile {+ path: string;+}++export type LocalThemeImportResult =+ | {+ /** 用户在原生对话框里取消。 */+ canceled: true;+ }+ | {+ canceled: false;+ written: ImportedThemeFile[];+ report: ThemeConversionReport;+ };diff --git a/apps/desktop/src/shared/theme-import/vscode.ts b/apps/desktop/src/shared/theme-import/vscode.tsnew file mode 100644index 0000000000..135eba865d--- /dev/null+++ b/apps/desktop/src/shared/theme-import/vscode.ts@@ -0,0 +1,381 @@+/**+ * VSCode 颜色主题(`*.json` / jsonc)→ Cindy 色板。+ *+ * 映射依据是仓库里已有的人工移植记录:`renderer/themes/builtin/one-dark-pro.ts`+ * 顶部注释逐行写明了 SURFACE ← `editor.background`、ELEVATED ←+ * `sideBar.background`、HOVER ← `list.hoverBackground`、BORDER ←+ * `panel.border`、PRIMARY ← `editor.foreground`、SECONDARY ← comment scope、+ * DISABLED ← `lineNumber.foreground`。本文件把那套判断代码化并补上 fallback 链。+ *+ * 源文件没给的角色一律**推导**而非留空(VSCode 自己也是这么干的:主题只写一部分+ * workbench 色,其余由内建默认派生),并把推导过的角色名放进报告。+ */++import {+ isDarkBackground,+ parseCssColor,+ parseCssColorComposited,+ shade,+ toHex,+ type Rgb,+} from './color';+import type { MarkdownPalette, ThemePalette, ThemeTypeName } from './palette';++function stripBom(input: string): string {+ return input.charCodeAt(0) === 0xFEFF ? input.slice(1) : input;+}++/** 去掉 jsonc 的注释与尾逗号——VSCode 主题文件普遍带注释。 */+export function stripJsonComments(input: string): string {+ let out = '';+ let inString = false;+ let inLineComment = false;+ let inBlockComment = false;+ for (let i = 0; i < input.length; i += 1) {+ const c = input[i];+ const next = input[i + 1];+ if (inLineComment) {+ if (c === '\n') {+ inLineComment = false;+ out += c;+ }+ continue;+ }+ if (inBlockComment) {+ if (c === '*' && next === '/') {+ inBlockComment = false;+ i += 1;+ }+ continue;+ }+ if (inString) {+ out += c;+ if (c === '\\') {+ // 转义序列整体透传,避免把 \" 误判成字符串结束。+ if (next !== undefined) {+ out += next;+ i += 1;+ }+ continue;+ }+ if (c === '"') inString = false;+ continue;+ }+ if (c === '"') {+ inString = true;+ out += c;+ continue;+ }+ if (c === '/' && next === '/') {+ inLineComment = true;+ i += 1;+ continue;+ }+ if (c === '/' && next === '*') {+ inBlockComment = true;+ i += 1;+ continue;+ }+ out += c;+ }+ // 尾逗号必须在注释剥完之后、且带字符串感知地删(`, // 注释\n}` 这种要先没了+ // 注释才看得出是尾逗号)。此前用一条全局 replace(/,(\s*[}\]])/g) 处理,那个+ // 正则不认字符串边界,会把 JSON 值里合法的 `, }` 一起吃掉+ // (`{"a": "x, }y"}` 被改成 `{"a": "x}y"}`)。+ return stripTrailingCommas(out);+}++/** 删掉 `}` / `]` 前的尾逗号;字符串字面量内的逗号原样保留。 */+function stripTrailingCommas(input: string): string {+ let out = '';+ let inString = false;+ for (let i = 0; i < input.length; i += 1) {+ const c = input[i];+ if (inString) {+ out += c;+ if (c === '\\') {+ if (i + 1 < input.length) {+ out += input[i + 1];+ i += 1;+ }+ continue;+ }+ if (c === '"') inString = false;+ continue;+ }+ if (c === '"') {+ inString = true;+ out += c;+ continue;+ }+ if (c === ',' && isTrailingComma(input, i)) continue;+ out += c;+ }+ return out;+}++/** `,` 之后跳过空白,若紧接 `}` 或 `]` 则它是尾逗号。 */+function isTrailingComma(input: string, commaIndex: number): boolean {+ for (let j = commaIndex + 1; j < input.length; j += 1) {+ const c = input[j];+ if (c === '}' || c === ']') return true;+ if (!/\s/.test(c)) return false;+ }+ // 逗号后只剩空白:JSON 本身已经不合法,交给 JSON.parse 报错。+ return false;+}++interface VsCodeTokenColor {+ scope?: string | string[];+ settings?: { foreground?: string; fontStyle?: string };+}++interface VsCodeThemeJson {+ name?: string;+ type?: string;+ include?: string;+ colors?: Record<string, unknown>;+ tokenColors?: VsCodeTokenColor[];+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/** 解析 VSCode 主题文件;不是主题 JSON 时返回 null(由调用方给出可读报错)。 */+export function parseVsCodeThemeJson(raw: string): VsCodeThemeJson | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(stripJsonComments(stripBom(raw)));+ } catch {+ return null;+ }+ if (!isRecord(parsed)) return null;+ const hasColors = isRecord(parsed.colors);+ const hasTokenColors = Array.isArray(parsed.tokenColors);+ // `colors` 与 `tokenColors` 都没有 → 不是颜色主题(可能是 snippets / settings)。+ if (!hasColors && !hasTokenColors) return null;+ return {+ ...(typeof parsed.name === 'string' ? { name: parsed.name } : {}),+ ...(typeof parsed.type === 'string' ? { type: parsed.type } : {}),+ ...(typeof parsed.include === 'string' ? { include: parsed.include } : {}),+ ...(hasColors ? { colors: parsed.colors as Record<string, unknown> } : {}),+ ...(hasTokenColors ? { tokenColors: parsed.tokenColors as VsCodeTokenColor[] } : {}),+ };+}++function scopeList(scope: string | string[] | undefined): string[] {+ if (Array.isArray(scope)) return scope.flatMap((s) => scopeList(s));+ if (typeof scope !== 'string') return [];+ return scope+ .split(',')+ .map((s) => s.trim())+ .filter((s) => s.length > 0);+}++/**+ * 取某个 TextMate scope 的前景色(反向扫描——VSCode 是 last-match-wins)。+ * 精确匹配优先于前缀匹配,避免 `comment.block.documentation` 覆盖 `comment`。+ * 带 alpha 的颜色合成到 `over` 底色上(同 VSCode 渲染行为)。+ */+function tokenColorFor(theme: VsCodeThemeJson, wanted: string, over?: Rgb | null): Rgb | null {+ const entries = theme.tokenColors ?? [];+ let prefixHit: Rgb | null = null;+ for (let i = entries.length - 1; i >= 0; i -= 1) {+ const fg = entries[i].settings?.foreground;+ if (typeof fg !== 'string') continue;+ for (const scope of scopeList(entries[i].scope)) {+ if (scope === wanted) {+ const rgb = over ? parseCssColorComposited(fg, over) : parseCssColor(fg);+ if (rgb) return rgb;+ }+ if (!prefixHit && wanted.startsWith(`${scope}.`)) {+ prefixHit = over ? parseCssColorComposited(fg, over) : parseCssColor(fg);+ }+ }+ }+ return prefixHit;+}++export interface VsCodeExtraction {+ palette: ThemePalette;+ type: ThemeTypeName;+ name: string;+ markdown: MarkdownPalette;+ derivedRoles: string[];+ resolvedRoles: number;+ unresolved: string[];+}++/**+ * 从 VSCode 主题抽 Cindy 色板。+ *+ * `fallbackName` 用于源文件没写 `name` 时(一般传文件名)。+ */+export function extractVsCodePalette(+ theme: VsCodeThemeJson,+ fallbackName: string,+): VsCodeExtraction | null {+ const colors = theme.colors ?? {};+ const unresolved: string[] = [];+ const derivedRoles: string[] = [];+ let resolvedRoles = 0;++ /** 按 key 链取首个可解析的色值;全不命中返回 null。 */+ const pickColor = (keys: string[], compositeBg?: Rgb | null): Rgb | null => {+ for (const key of keys) {+ const raw = colors[key];+ if (typeof raw !== 'string') continue;+ const rgb = compositeBg+ ? parseCssColorComposited(raw, compositeBg)+ : parseCssColor(raw);+ if (rgb) return rgb;+ unresolved.push(key);+ }+ return null;+ };++ /** 命中则计入 resolved,否则用 derive() 推导并计入 derivedRoles。 */+ const role = (name: string, keys: string[], derive: () => Rgb, compositeBg?: Rgb | null): Rgb => {+ const hit = pickColor(keys, compositeBg);+ if (hit) {+ resolvedRoles += 1;+ return hit;+ }+ derivedRoles.push(name);+ return derive();+ };++ const surfaceHit = pickColor(['editor.background', 'editorPane.background']);+ if (!surfaceHit) {+ // 连主背景都没有,判不出这是个可用的颜色主题。包含 `include` 时背景可能来自+ // 被继承的主题,此时如实返回 null 让调用方给出继承限制说明,而非报"不支持"。+ return null;+ }+ resolvedRoles += 1;+ const surface = surfaceHit;++ const declaredType = theme.type?.toLowerCase();+ const type: ThemeTypeName = declaredType === 'light' || declaredType === 'dark'+ ? declaredType+ : isDarkBackground(surface)+ ? 'dark'+ : 'light';+ const dark = type === 'dark';+ /** 层级推导方向:暗色主题往亮走一档,亮色主题往暗走一档。 */+ const step = (base: Rgb, amount: number): Rgb => shade(base, dark ? amount : -amount);++ const elevated = role(+ 'elevated',+ ['sideBar.background', 'editorWidget.background', 'panel.background', 'activityBar.background'],+ () => step(surface, 0.05),+ );+ const hover = role(+ 'hover',+ ['list.hoverBackground', 'toolbar.hoverBackground', 'menu.selectionBackground'],+ () => step(surface, 0.08),+ surfaceHit,+ );+ const chip = role(+ 'chip',+ ['list.activeSelectionBackground', 'editorGroupHeader.tabsBackground', 'badge.background'],+ () => step(hover, 0.04),+ surfaceHit,+ );+ const border = role(+ 'border',+ ['panel.border', 'editorGroup.border', 'input.border', 'contrastBorder', 'widget.border'],+ () => step(surface, 0.2),+ surfaceHit,+ );++ const textPrimary = role(+ 'textPrimary',+ ['editor.foreground', 'foreground'],+ () => (dark ? { r: 212, g: 212, b: 212 } : { r: 38, g: 38, b: 38 }),+ surfaceHit,+ );+ // 二级文字优先取注释色——这是 one-dark-pro.ts 注释里记录的人工判断+ // (SECONDARY ← comments),比 descriptionForeground 更贴近"弱化正文"的观感。+ const commentColor = tokenColorFor(theme, 'comment', surfaceHit);+ if (commentColor) resolvedRoles += 1;+ const textSecondary = commentColor ?? role(+ 'textSecondary',+ ['descriptionForeground', 'editorCodeLens.foreground'],+ () => shade(textPrimary, dark ? -0.28 : 0.28),+ surfaceHit,+ );+ const textDisabled = role(+ 'textDisabled',+ ['editorLineNumber.foreground', 'editorWhitespace.foreground'],+ () => shade(textSecondary, dark ? -0.35 : 0.35),+ surfaceHit,+ );+ const textTertiary = role(+ 'textTertiary',+ ['editorHint.foreground', 'breadcrumb.foreground'],+ () => shade(textSecondary, dark ? -0.16 : 0.16),+ );++ const accentPrimary = role(+ 'accentPrimary',+ [+ 'button.background',+ 'focusBorder',+ 'textLink.foreground',+ 'activityBarBadge.background',+ 'progressBar.background',+ 'statusBarItem.remoteBackground',+ ],+ () => textPrimary,+ );+ const accentSoft = shade(accentPrimary, dark ? 0.22 : -0.28);+ derivedRoles.push('accentSoft');+ const accentDeep = shade(accentPrimary, dark ? -0.22 : -0.28);+ derivedRoles.push('accentDeep');+ const elevatedSoft = dark ? elevated : step(elevated, 0.08);+ derivedRoles.push('elevatedSoft');++ const headingColor = tokenColorFor(theme, 'markup.heading', surfaceHit);+ const boldColor = tokenColorFor(theme, 'markup.bold', surfaceHit);+ const markdown: MarkdownPalette = {+ ...(headingColor ? { headings: Array.from({ length: 6 }, () => headingColor) } : {}),+ ...(boldColor ? { strong: boldColor } : {}),+ };++ if (theme.include) {+ // 我们只读单文件,被 include 的基底主题里的色值拿不到——如实计入报告。+ unresolved.push(`include:${theme.include}`);+ }++ return {+ palette: {+ surface,+ elevated,+ elevatedSoft,+ hover,+ chip,+ border,+ textPrimary,+ textSecondary,+ textTertiary,+ textDisabled,+ accentPrimary,+ accentSoft,+ accentDeep,+ },+ type,+ name: theme.name?.trim() || fallbackName,+ markdown,+ derivedRoles,+ resolvedRoles,+ unresolved,+ };+}++/** 调试用:把色板打成 hex map(测试断言更易读)。 */+export function paletteToHex(palette: ThemePalette): Record<string, string> {+ return Object.fromEntries(+ Object.entries(palette).map(([k, v]) => [k, toHex(v as Rgb)]),+ );+}diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 1c1afc8a36..bf2d8162d5 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -443,7 +443,7 @@ The implementation truth is `builtinThemes` in `apps/desktop/src/renderer/themes2. Register it in `builtinThemes` in `themes/registry.ts`3. The Light/Dark Theme dropdowns in Settings → Appearance pick it up automatically-Use any existing non-default theme under `themes/builtin/` as a template.+Use any existing non-default theme under `apps/desktop/src/renderer/themes/builtin/` as a template.### Token Naming Conventions@@ -463,6 +463,17 @@ CSS variable names are always kebab-case. Dot-style ids (VSCode's `sidebar.itemAThis section is the authoritative token-usage text; i18n rules for UI copy live in `docs/dev-rules/engineering-conventions.md` §5.+### External Theme Import (VSCode / Obsidian)++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 91 tokens derived from 13 palette roles. `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 91 base ids, plus optional Markdown tokens (`md-h1-fg`…`md-h6-fg` / `md-strong-fg`) 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`.+- **Obsidian import is a palette import, not a theme port.** Only CSS custom properties are read; selectors, layout, radii and fonts are discarded — Cindy's layout and typography stay owned by §3/§5. Values that cannot be evaluated statically (`color-mix()`, undefined `var()`) are skipped and reported rather than guessed.+- **Local themes may declare an optional `family`.** Same-family light + dark variants merge into one switchable family (`themes/families.ts`); files without the field keep behaving exactly as before (family id = theme id). Obsidian's dual-mode CSS uses this to land as a single theme that follows Light/Dark mode.+## 11. Voice & Content(微文案规范)> **Status: draft**, introduced 2026-06 (after the Voice & Content section of Vercel Geist's `design.md`). This section governs **how interface copy is written** and pairs with `docs/dev-rules/engineering-conventions.md` §5 (the i18n system) — that side enforces "copy lands via i18n keys, aligned across 4 languages"; this side governs each string's tone and wording. It adds no UI strings, only constraints.diff --git a/docs/design-rules/cindy-design-system.md b/docs/design-rules/cindy-design-system.mdindex 748ad65c2f..e67a204ca0 100644--- a/docs/design-rules/cindy-design-system.md+++ b/docs/design-rules/cindy-design-system.md@@ -15,6 +15,7 @@## 版本记录+- **2026-07-26**:`DESIGN.md §10` 新增「External Theme Import (VSCode / Obsidian)」小节——外部主题导入只映射从 7 个人工移植社区主题抽出的 91-token 模板、语义豁免族(`--login-*` / 危险红 / 警告橙 / 焦点蓝 / `--diff-*`)不参与导入、`-hsl` token 精确换算、新增 `--md-h1-fg`…`--md-h6-fg` / `--md-strong-fg`(默认 `inherit`,内置主题观感不变)、本地主题可选 `family` 字段。决策理由与取舍见 [`design-decision-log.md`](./design-decision-log.md) 2026-07-26 条。- **2026-07-24(梳理批次 1)**:`DESIGN.md` 整体梳理第一批落地——去除 Ollama 官网叙事(标题改 `Cindy Design System`,§1/§4/§5/§8/§9 重写或删除官网内容);focus ring 文档追平代码(`#3b82f6` → `#417CDD`);§2/§9 二级三级文字与 chip 双 slot 表述按 `colors.ts` 修正;§10 移除写死 token 计数与过时豁免行;§12 结构化规格并入 §4(§12 编号留占位);§13 G1–G4 归档至新建 [`design-decision-log.md`](./design-decision-log.md);§14/§15/§16 若干失效指向修正。- **2026-07-24**:目录整编(设计 md 统一归位 `docs/design-rules/`,本文件升级为索引)。同步 Figma 组件库更新:hover 统一「叠白变亮」口径(旧「白底钮 hover 叠黑」作废)、新增协议勾选 `radiobutton` 四态与双色模式小按钮四母版、`SSO 登录_企业` / `back` 扩 Dark 三态、`white_button` 增 loading 五态(`figma-component-spec §11`、`DESIGN.md §16.5`)。`figma-component-spec.md` / `token-decision-table.md` 自迁移前仓库最后版本恢复并更新至 wave5。- **2026-07-23**:`DESIGN.md` 新增 §16 登录链路(登录全链路设计规范、`--login-*` 双态 token 表、深色模式落地机制)。diff --git a/docs/design-rules/design-decision-log.md b/docs/design-rules/design-decision-log.mdindex 3f221cc2b5..6c335a5826 100644--- a/docs/design-rules/design-decision-log.md+++ b/docs/design-rules/design-decision-log.md@@ -12,6 +12,27 @@## 2026-07+- **07-26** 外部主题导入(VSCode / Obsidian)落地,同批引入 Markdown 文字色 token。+ 两条关键决策:+ ① **转换模板不新设计,取自已有的人工移植成果**。+ `apps/desktop/src/renderer/themes/builtin/` 下 7 个从+ VSCode 移植的社区主题,`colors` 的 key 集合逐字相同(91 个 token = 35 个 Tier1+ slot + 56 个 alias/singleton),值全部由同一组 13 个色板角色派生;+ `apps/desktop/src/shared/theme-import/palette.ts` 就是那套派生规则的代码化,并以这些主题自身做+ golden 对照(喂入其手写色板常量应重现其 colors)。选 allow-list(只产出这 91 个+ key)而非"先大量产出再过滤",因为这 7 个主题本来就没碰豁免族,照抄 key 列表即+ 自动守住 §10/§16 边界。+ ② **`--md-h1-fg`…`--md-h6-fg` / `--md-strong-fg` 默认值定为 `inherit`,不是+ `var(--text-primary)`**。这些元素在引入 token 前的颜色就是继承来的+ (`baseComponents` 只给字号字重);若默认接主文字槽,blockquote / tool card /+ secondary 文字区里的标题与加粗会由弱化色变回主色 —— 那是实打实的观感回退。+ `inherit` 让全部内置主题渲染结果不变,同时给导入主题(Obsidian `--hN-color` /+ VSCode `markup.heading`)留出可覆盖槽位。守卫见+ `themes/__tests__/markdownColorTokens.test.ts`。+ 连带扩展:本地主题 JSON 新增可选 `family` 字段,让 Obsidian 双态 CSS 的两个产物+ 合成一个可跟随 Light/Dark 的家族;无该字段的老主题家族 id 与行为逐字不变。+ 已知取舍:Obsidian 侧是**调色板导入**(只取 CSS 变量,布局/圆角/字体一律丢弃,+ `color-mix()` 等动态值跳过并计入报告),还原度低于 VSCode 侧,UI 文案如实说明。- **07-26** §10「双模式交付门槛」放宽为「实现硬性 / 目检尽力」:**实现**两模式(走语义token、禁单模式硬编码、覆盖本次改动涉及的状态)仍是硬性要求;**两模式实机目检**从硬门槛降为尽力项——做不到不阻塞交付,但必须在 commit / PR 验证说明里写明哪种模式