Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): pick a light theme and a dark theme (PRD-7628) (#3130)
serafin-garcia5824c18f379a
diff --git a/.changeset/color-theme-light-dark-pair.md b/.changeset/color-theme-light-dark-pair.mdnew file mode 100644index 000000000..7b7c259d1--- /dev/null+++ b/.changeset/color-theme-light-dark-pair.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++You can now pick one color theme for light mode and a different one for dark mode. Every tile in **Settings → Plugins → Themes** carries a sun and a moon: press the sun to make that palette your light theme, the moon to make it your dark theme, or both to use it either way. Whichever mode you're in — including when your theme setting is **System** and your OS decides — the matching palette applies, and it swaps as the appearance changes without touching your config.++Any palette can sit in either slot; it still forces its own light/dark variant, so choosing a dark scheme as your light-mode theme does what it says. Existing setups are unchanged: a single palette chosen before this release applies to both modes until you pick a new one.++Switching themes is also faster than it was. Repainting the terminal palette used to re-measure each color separately against styles the switch had just invalidated, which stalled the window for a moment on every change; the whole palette is now measured in one pass and refreshed once per frame.diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 9b9c5cdce..2107a2261 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -37,7 +37,9 @@ A key set in a file more specific than its scope (a user-scope key in `.ok/confi| `contentRules.frontmatter.enabled` | boolean | `false` | project | Enable the [Frontmatter schemas](/docs/advanced/content-rules/frontmatter) content-rules plugin for this project (shared via git). Off by default — turn it on in **Settings → This project → Plugins**. || `contentRules.frontmatter.schemas` | array | `[]` | project | Frontmatter schema mappings: each entry scopes one JSON Schema file to a set of docs — `file` (project-root-relative path), optional `appliesTo` (glob or list; leading `!` excludes; absent means every doc), optional `enabled: false` to park a mapping. Schema content lives in the mapped files, not here. See [Frontmatter schemas](/docs/advanced/content-rules/frontmatter). || `appearance.theme` | `"light" \| "dark" \| "system"` | (unset) | user | Editor light/dark theme. |-| `appearance.colorTheme` | `"default" \| "dracula" \| "catppuccin-frappe" \| "catppuccin-latte" \| "monokai" \| "gruvbox" \| "solarized" \| "custom"` | (unset) | user | IDE color palette layered on top of the light/dark `theme`. `default` (the effective value when unset) follows `theme`; the named palettes are self-contained schemes that force their own light/dark mode; `custom` applies `appearance.customTheme`. Pick it in **Settings → Plugins → Themes**. |+| `appearance.colorThemeLight` | `"default" \| "dracula" \| "catppuccin-frappe" \| "catppuccin-latte" \| "monokai" \| "gruvbox" \| "solarized" \| "custom"` | (unset) | user | IDE color palette applied while the resolved mode is light. `default` (the effective value when unset) means no palette — the base stylesheet shows through. `custom` applies `appearance.customTheme`. Pick it in **Settings → Plugins → Themes** with the tile's sun. |+| `appearance.colorThemeDark` | `"default" \| "dracula" \| "catppuccin-frappe" \| "catppuccin-latte" \| "monokai" \| "gruvbox" \| "solarized" \| "custom"` | (unset) | user | IDE color palette applied while the resolved mode is dark — the tile's moon. `appearance.theme` chooses between the two; on `system` your OS does, so the palette follows the OS appearance. Any palette may sit in either slot, and it keeps forcing its own light/dark variant. |+| `appearance.colorTheme` | `"default" \| "dracula" \| "catppuccin-frappe" \| "catppuccin-latte" \| "monokai" \| "gruvbox" \| "solarized" \| "custom"` | (unset) | user | Legacy single-palette field, superseded by `colorThemeLight` / `colorThemeDark` above. When set, it supplies the palette for whichever of those two slots is unset, so one palette applies in both modes. Writing either slot from **Settings → Plugins → Themes** removes this key. || `appearance.colorThemeEnabled` | boolean | `true` | user | Whether the Themes plugin appears in **Settings → Plugins**. On by default (absent = enabled). || `appearance.customTheme` | object | (unset) | user | The `custom` palette's [base16](https://github.com/tinted-theming/schemes) scheme: sixteen `base00`–`base0F` `#rrggbb` slots, plus optional `name`, `author` (a credit line carried through from an imported scheme), and `variant` (`"dark" \| "light"`, auto-detected from the tonal ramp when absent). A config written before base16 carried six semantic seed colors (`background`/`surface`/`foreground`/`primary`/`accent`/`border`) instead; that shape still parses and is upgraded to the sixteen slots automatically on read. Edit in **Settings → Plugins → Themes**. || `appearance.sidebar.showHiddenFiles` | boolean | `false` | project-local | Show files whose path segments start with `.`. The sidebar otherwise lists every file on disk under the content directory; tooling internals (`.git/`, `.ok/`, `node_modules/`) stay hidden regardless. Toggled from the sidebar's right-click menu or the macOS **View → Show Hidden Files** item. |diff --git a/packages/app/index.html b/packages/app/index.htmlindex 511ce2994..ef4e01ef9 100644--- a/packages/app/index.html+++ b/packages/app/index.html@@ -43,20 +43,32 @@so the BrowserWindow's vibrancy material shows through. Web mode(no `window.okDesktop`) skips the class so chrome stays solid.- The IDE color palette is read from `ok-color-theme-v1` and applied as- the `data-color-theme` attribute consumed by- `color-themes.generated.css`. Each named IDE palette carries its own mode, so- a present value forces the `dark` class (or clears it for a light palette like- `catppuccin-latte`) regardless of `ok-theme-v1`. The `custom`- palette is replayed from `ok-custom-theme-v1` (`{ css, dark }`): its prebuilt- stylesheet is injected as a `<style>` and its `dark` flag drives the class.- Paired consumers: `src/lib/use-apply-config-color-theme.ts` (writes the- caches) + `src/lib/color-themes.ts` (the id allowlist — keep it in sync).+ The IDE color palette comes from `ok-color-theme-pair-v1`, which holds one+ palette per mode plus the mode preference that chooses between them:+ `{ pref, light: { id, dark }, dark: { id, dark } }`. The script resolves+ `pref` (asking the OS for `system`), reads that slot, applies its `id` as+ the `data-color-theme` attribute consumed by `color-themes.generated.css`,+ and takes the `dark` class straight from the slot's own flag — a palette+ forces its own variant, so the flag is precomputed rather than re-derived+ here. That is what keeps this script free of any theme-id knowledge.++ A build that predates the pair wrote a single id to `ok-color-theme-v1`,+ read only as a fallback: it applied to whatever mode was active, and+ `ok-theme-v1` already carried the mode that palette forced. The app deletes+ that key as soon as it writes the pair, so this branch runs at most once+ per install.++ The `custom` palette is replayed from `ok-custom-theme-v1`+ (`{ css, dark }`): its prebuilt stylesheet is injected as a `<style>` and+ its `dark` flag drives the class. Paired consumer:+ `src/lib/use-apply-config-color-theme.ts` — it writes the+ `ok-color-theme-pair-v1` and `ok-custom-theme-v1` caches and clears the legacy+ `ok-color-theme-v1`; `ok-theme-v1` is next-themes' (see above).Single-line script body — same biome HTML-formatter constraint asthe editor-mode FOUC above.-->- <script>(() => { let t = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (r === 'light' || r === 'dark' || r === 'system') t = r; } catch {} let ct = null; try { const c = localStorage.getItem('ok-color-theme-v1'); if (c && ['dracula', 'catppuccin-frappe', 'catppuccin-latte', 'monokai', 'gruvbox', 'solarized', 'custom'].includes(c)) ct = c; } catch {} let dark = t === 'dark'; if (t === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } let customCss = null; if (ct === 'custom') { try { const raw = localStorage.getItem('ok-custom-theme-v1'); if (raw) { const o = JSON.parse(raw); if (o?.css) { customCss = o.css; dark = !!o.dark; } } } catch {} if (!customCss) ct = null; } else if (ct) { dark = !['catppuccin-latte'].includes(ct); } if (dark) document.documentElement.classList.add('dark'); if (ct) document.documentElement.setAttribute('data-color-theme', ct); if (customCss) { const s = document.createElement('style'); s.id = 'ok-custom-theme'; s.textContent = customCss; document.head.appendChild(s); } if (window.okDesktop) { document.documentElement.classList.add('electron-mode'); document.documentElement.classList.add(`electron-platform-${window.okDesktop.platform}`); } })();</script>+ <script>(() => { const isMode = (v) => v === 'light' || v === 'dark' || v === 'system'; const isThemeId = (v) => typeof v === 'string' && /^[a-z0-9-]{1,32}$/.test(v); let pref = 'system'; try { const r = localStorage.getItem('ok-theme-v1'); if (isMode(r)) pref = r; } catch {} let slots = null; try { const raw = localStorage.getItem('ok-color-theme-pair-v1'); if (raw) { const o = JSON.parse(raw); if (o?.light && o?.dark) { slots = o; if (isMode(o.pref)) pref = o.pref; } } } catch {} let dark = pref === 'dark'; if (pref === 'system') { try { dark = window.matchMedia('(prefers-color-scheme: dark)').matches; } catch {} } let ct = null; if (slots) { const slot = dark ? slots.dark : slots.light; if (isThemeId(slot?.id)) { dark = !!slot.dark; if (slot.id !== 'default') ct = slot.id; } } else { try { const c = localStorage.getItem('ok-color-theme-v1'); if (isThemeId(c) && c !== 'default') ct = c; } catch {} } let customCss = null; if (ct === 'custom') { try { const raw = localStorage.getItem('ok-custom-theme-v1'); if (raw) { const o = JSON.parse(raw); if (o?.css) { customCss = o.css; dark = !!o.dark; } } } catch {} if (!customCss) ct = null; } if (dark) document.documentElement.classList.add('dark'); if (ct) document.documentElement.setAttribute('data-color-theme', ct); if (customCss) { const s = document.createElement('style'); s.id = 'ok-custom-theme'; s.textContent = customCss; document.head.appendChild(s); } if (window.okDesktop) { document.documentElement.classList.add('electron-mode'); document.documentElement.classList.add(`electron-platform-${window.okDesktop.platform}`); } })();</script><style>html { background-color: __OK_CHROME_BG_LIGHT__ } html.dark { background-color: __OK_CHROME_BG_DARK__ }</style></head>diff --git a/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsxindex 8b5b89ff8..821794e38 100644--- a/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx+++ b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx@@ -1,7 +1,7 @@import { cleanup, fireEvent, render, screen } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, describe, expect, test, vi } from 'vitest';-import { COLOR_THEMES, defaultThemeTokens } from '@/lib/color-themes';+import { COLOR_THEMES, type ColorThemeSelection, defaultThemeTokens } from '@/lib/color-themes';import { renderLinguiTemplate } from '@/test-utils/lingui-mock';vi.doMock('@lingui/react/macro', () => ({@@ -9,26 +9,32 @@ vi.doMock('@lingui/react/macro', () => ({useLingui: () => ({ t: renderLinguiTemplate }),}));+type Assignment = [slot: 'light' | 'dark', id: string];+async function renderPicker(- value: string,- onSelect: (id: string) => void,- defaultMode?: 'light' | 'dark',+ selection: ColorThemeSelection,+ onAssign: (slot: 'light' | 'dark', id: string) => void = () => {},+ slotMode?: 'light' | 'dark',) {const { ColorThemePicker } = await import('./ColorThemePicker');return render(<ColorThemePicker- value={value}- onSelect={onSelect}- defaultMode={defaultMode}+ selection={selection}+ onAssign={onAssign}+ slotMode={slotMode}aria-label="Color theme"/>,);}+const DEFAULTS: ColorThemeSelection = { light: 'default', dark: 'default' };+/** Every inline `style` attribute inside a tile's preview, concatenated. */function swatchStyles(themeLabel: RegExp): string {- const tile = screen.getByRole('radio', { name: themeLabel });- return Array.from(tile.querySelectorAll<HTMLElement>('[style]'))+ const tile = screen.getByRole('group', { name: themeLabel });+ return Array.from(+ tile.querySelectorAll<HTMLElement>('[data-theme-swatch] [style], [data-theme-swatch]'),+ ).map((el) => el.getAttribute('style') ?? '').join(' ');}@@ -36,41 +42,101 @@ function swatchStyles(themeLabel: RegExp): string {describe('ColorThemePicker', () => {afterEach(cleanup);- test('renders one radio tile per registered theme, labelled by name', async () => {- await renderPicker('default', () => {});- const radios = screen.getAllByRole('radio');- expect(radios.length).toBe(COLOR_THEMES.length);+ test('renders one tile per registered theme, each with a sun and a moon', async () => {+ await renderPicker(DEFAULTS);for (const theme of COLOR_THEMES) {expect(screen.getByText(theme.label)).toBeDefined();+ expect(screen.getByLabelText(`Use ${theme.label} as the light theme`)).toBeDefined();+ expect(screen.getByLabelText(`Use ${theme.label} as the dark theme`)).toBeDefined();}});- test('marks the selected theme as checked', async () => {- await renderPicker('dracula', () => {});- const dracula = screen.getByRole('radio', { name: /Dracula/ });- expect(dracula.getAttribute('data-state')).toBe('checked');- const mocha = screen.getByRole('radio', { name: /Catppuccin Frappé/ });- expect(mocha.getAttribute('data-state')).toBe('unchecked');+ test('presses the sun on the light palette and the moon on the dark one', async () => {+ await renderPicker({ light: 'catppuccin-latte', dark: 'dracula' });+ expect(+ screen.getByLabelText('Use Catppuccin Latte as the light theme').getAttribute('data-state'),+ ).toBe('on');+ expect(+ screen.getByLabelText('Use Catppuccin Latte as the dark theme').getAttribute('data-state'),+ ).toBe('off');+ expect(screen.getByLabelText('Use Dracula as the dark theme').getAttribute('data-state')).toBe(+ 'on',+ );+ expect(screen.getByLabelText('Use Dracula as the light theme').getAttribute('data-state')).toBe(+ 'off',+ );+ });++ test('an assigned icon is visually distinct from an unassigned one, not just data-state', async () => {+ // The regression this pins: the icons carried the correct `data-state`+ // while rendering identically, because the stock Toggle pressed state is a+ // `bg-muted` wash that disappears against a themed tile. Assigning the mode+ // you are not currently in changes nothing else on screen, so if the icon+ // does not visibly change, the control reads as dead.+ await renderPicker({ light: 'catppuccin-latte', dark: 'dracula' });+ const on = screen.getByLabelText('Use Catppuccin Latte as the light theme');+ const off = screen.getByLabelText('Use Dracula as the light theme');+ expect(on.className).not.toBe(off.className);+ expect(on.className).toContain('border-primary');+ expect(off.className).not.toContain('border-primary');+ // The glyph itself fills in, so the state survives at icon size.+ expect(on.querySelector('svg')?.getAttribute('class')).toContain('fill-current');+ expect(off.querySelector('svg')?.getAttribute('class')).not.toContain('fill-current');+ });++ test('one palette can hold both modes at once', async () => {+ await renderPicker({ light: 'gruvbox', dark: 'gruvbox' });+ expect(screen.getByLabelText('Use Gruvbox as the light theme').getAttribute('data-state')).toBe(+ 'on',+ );+ expect(screen.getByLabelText('Use Gruvbox as the dark theme').getAttribute('data-state')).toBe(+ 'on',+ );+ });++ test('clicking the tile body assigns only the mode on screen', async () => {+ // The old picker made the whole tile the target; a click still has to do+ // something. It must NOT set both slots — that would drop the other mode's+ // palette without the user asking.+ const calls: Assignment[] = [];+ await renderPicker(+ { light: 'catppuccin-latte', dark: 'monokai' },+ (slot, id) => calls.push([slot, id]),+ 'dark',+ );+ const swatch = screen+ .getByRole('group', { name: /Dracula/ })+ .querySelector('[data-theme-swatch]');+ expect(swatch).not.toBeNull();+ fireEvent.click(swatch as Element);+ expect(calls).toEqual([['dark', 'dracula']]);});- test('falls back to default when value is empty or unknown', async () => {- await renderPicker('', () => {});- const def = screen.getByRole('radio', { name: /Default/ });- expect(def.getAttribute('data-state')).toBe('checked');+ test('fires onAssign with the slot the pressed icon owns', async () => {+ const calls: Assignment[] = [];+ await renderPicker(DEFAULTS, (slot, id) => calls.push([slot, id]));+ fireEvent.click(screen.getByLabelText('Use Catppuccin Frappé as the dark theme'));+ fireEvent.click(screen.getByLabelText('Use Catppuccin Latte as the light theme'));+ expect(calls).toEqual([+ ['dark', 'catppuccin-frappe'],+ ['light', 'catppuccin-latte'],+ ]);});- test('fires onSelect with the theme id when a tile is activated', async () => {- const picks: string[] = [];- await renderPicker('default', (id) => picks.push(id));- fireEvent.click(screen.getByRole('radio', { name: /Catppuccin Frappé/ }));- expect(picks).toEqual(['catppuccin-frappe']);+ test('re-pressing the icon of an already-assigned palette does not clear the slot', async () => {+ // Every mode must resolve to some palette — "no palette" is the `default`+ // tile, not an empty slot — so an un-press is ignored rather than written.+ const calls: Assignment[] = [];+ await renderPicker({ light: 'default', dark: 'dracula' }, (slot, id) => calls.push([slot, id]));+ fireEvent.click(screen.getByLabelText('Use Dracula as the dark theme'));+ expect(calls).toEqual([]);});test('paints the Default tile from literal base tokens, not cascaded CSS vars', async () => {// The regression: the preview used to read `var(--sidebar)` & co. Those are// exactly the properties a selected palette overrides on <html>, so the// Default tile inherited the override and mirrored the chosen theme.- await renderPicker('default', () => {});+ await renderPicker(DEFAULTS);const styles = swatchStyles(/Default/);expect(styles).not.toContain('var(--');const tokens = defaultThemeTokens('light');@@ -79,25 +145,25 @@ describe('ColorThemePicker', () => {expect(styles).toContain(tokens['syntax-keyword']);});- test('follows defaultMode for the Default tile only', async () => {- await renderPicker('default', () => {}, 'light');+ test('follows slotMode for the Default tile only', async () => {+ await renderPicker(DEFAULTS, () => {}, 'light');const lightDefault = swatchStyles(/Default/);const lightDracula = swatchStyles(/Dracula/);cleanup();- await renderPicker('default', () => {}, 'dark');- // The base palette flips with the user's light/dark mode; an authored- // palette is mode-independent.+ await renderPicker(DEFAULTS, () => {}, 'dark');+ // The base palette flips with the mode on screen; an authored palette is+ // mode-independent.expect(swatchStyles(/Default/)).not.toBe(lightDefault);expect(swatchStyles(/Default/)).toContain(defaultThemeTokens('dark').background);expect(swatchStyles(/Dracula/)).toBe(lightDracula);});- test('tags themes by their forced mode: default is Auto, Latte is Light, the rest Dark', async () => {- await renderPicker('default', () => {});- // Default is the only Auto; Catppuccin Latte is the only Light palette; every- // other palette (the dark IDE themes + the default-seed custom) is Dark.- expect(screen.getAllByText('Auto').length).toBe(1);- expect(screen.getAllByText('Light').length).toBe(1);- expect(screen.getAllByText('Dark').length).toBe(COLOR_THEMES.length - 2);+ test('rings the palette in effect for the mode on screen, not the other slot', async () => {+ const selection: ColorThemeSelection = { light: 'catppuccin-latte', dark: 'dracula' };+ await renderPicker(selection, () => {}, 'dark');+ expect(screen.getByRole('group', { name: /Dracula/ }).className).toContain('border-primary');+ expect(screen.getByRole('group', { name: /Catppuccin Latte/ }).className).not.toContain(+ 'border-primary',+ );});});diff --git a/packages/app/src/components/settings/ColorThemePicker.tsx b/packages/app/src/components/settings/ColorThemePicker.tsxindex 7f89f2d03..031140bfe 100644--- a/packages/app/src/components/settings/ColorThemePicker.tsx+++ b/packages/app/src/components/settings/ColorThemePicker.tsx@@ -1,33 +1,40 @@import { useLingui } from '@lingui/react/macro';-import { RadioGroup as RadioGroupPrimitive } from 'radix-ui';+import { Moon, Sun } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Toggle } from '@/components/ui/toggle';import {base16ToTokens,COLOR_THEMES,type ColorTheme,- customThemeKind,+ type ColorThemeSelection,defaultThemeTokens,resolveCustomScheme,+ type ThemePluginId,} from '@/lib/color-themes';import { cn } from '@/lib/utils';type SeedInput = Record<string, unknown> | undefined;interface ColorThemePickerProps {- /** Currently-selected theme id (the `appearance.colorTheme` value; `''`/unknown → default). */- value: string;- /** Fired with the chosen theme id when a tile is activated. */- onSelect: (id: string) => void;- /** The user's custom-theme seed (partial), used to paint the Custom tile preview. */+ /** The palette assigned to each mode (`appearance.colorThemeLight` / `…Dark`). */+ selection: ColorThemeSelection;+ /** Fired with the mode slot and the theme id when a tile's sun/moon is pressed. */+ onAssign: (slot: 'light' | 'dark', id: ThemePluginId) => void;+ /**+ * The mode on screen right now — the one `appearance.theme` resolves to. Rings+ * the tile currently in effect, and paints the Default tile: that tile has no+ * palette of its own, so it advertises the base stylesheet in the live mode.+ */+ slotMode?: 'light' | 'dark';+ /** The user's custom-theme scheme (partial), used to paint the Custom tile preview. */customSeed?: SeedInput;/**- * Light or dark for the Default tile — the mode `appearance.theme` resolves to,- * NOT the mode the active palette forces. Picking a dark IDE palette must not- * repaint the Default preview dark: the tile advertises what switching back to- * `default` would look like.+ * The form label's `htmlFor` target. It lands on the first sun toggle, not on+ * the grid root: a `<fieldset>` is not a labelable element, so `<label for>`+ * pointing at it would never move focus. Same treatment the enum-toggle+ * control gives its first ToggleGroupItem.*/- defaultMode?: 'light' | 'dark';- /** Forwarded id (from the settings form's `<FormControl>` Slot) onto the radio group root. */- id?: string;+ firstItemId?: string;'aria-label'?: string;'aria-describedby'?: string;}@@ -54,7 +61,7 @@ function swatchFromTokens(t: Record<string, string>): SwatchColors {function swatchColors(theme: ColorTheme,customSeed: SeedInput,- defaultMode: 'light' | 'dark',+ slotMode: 'light' | 'dark',): SwatchColors {if (theme.id === 'custom') {return swatchFromTokens(base16ToTokens(resolveCustomScheme(customSeed)));@@ -63,7 +70,7 @@ function swatchColors(// `default` has no authored palette — it IS the base stylesheet. Reading the// cascaded `var(--…)` here would inherit whichever palette is currently// applied to `<html>`, so paint the base tokens as literals instead.- return swatchFromTokens(defaultThemeTokens(defaultMode));+ return swatchFromTokens(defaultThemeTokens(slotMode));}return swatchFromTokens(base16ToTokens(theme.scheme));}@@ -72,16 +79,17 @@ function swatchColors(function ThemeSwatch({theme,customSeed,- defaultMode,+ slotMode,}: {theme: ColorTheme;customSeed: SeedInput;- defaultMode: 'light' | 'dark';+ slotMode: 'light' | 'dark';}) {- const c = swatchColors(theme, customSeed, defaultMode);+ const c = swatchColors(theme, customSeed, slotMode);return (<divaria-hidden+ data-theme-swatch=""className="aspect-[4/3] w-full overflow-hidden rounded-md border"style={{ backgroundColor: c.surface, borderColor: c.line }}>@@ -125,59 +133,118 @@ function ThemeSwatch({}/**- * Tile grid for `appearance.colorTheme`. Radix `RadioGroup` gives single-select- * semantics + roving-focus arrow-key navigation; each item renders as a button,- * so no raw interactive element is introduced. The `default` tile follows the- * light/dark mode toggle above it; the IDE tiles are self-contained dark- * palettes; the `custom` tile previews the user's own seed.+ * A slot icon has to read as on/off at a glance across every palette — it sits+ * on the tile, so the surrounding color is whatever scheme that tile previews.+ * The shadcn Toggle's stock pressed state is a `bg-muted` wash, which against a+ * themed tile is close to invisible; an accent ring plus a filled, accent-tinted+ * glyph survives any background.+ */+function slotToggleClass(pressed: boolean): string {+ return cn(+ 'size-6 min-w-6 rounded-md border p-0 transition-colors',+ pressed+ ? 'border-primary bg-primary/15 text-primary hover:bg-primary/20 data-[state=on]:bg-primary/15'+ : 'border-border/70 text-muted-foreground/70 hover:text-foreground',+ );+}++function slotIconClass(pressed: boolean): string {+ return cn('size-3.5', pressed && 'fill-current');+}++/**+ * Tile grid for the light/dark palette pair. Every tile carries a sun and a+ * moon, so a palette can be the light theme, the dark theme, or both — which is+ * also why the grid is not a radio group: the two assignments are independent+ * single-selects that happen to share a row of tiles.+ *+ * Pressing the icon for the mode you are NOT currently in changes nothing on+ * screen by design, so the icon's own on/off state is the only feedback that+ * the assignment landed — it has to be unmistakable.+ *+ * Pressing an already-pressed icon is ignored rather than clearing the slot.+ * Each mode must resolve to some palette, and "none" is spelled `default`,+ * which is a tile of its own.*/export function ColorThemePicker({- value,- onSelect,+ selection,+ onAssign,+ slotMode = 'light',customSeed,- defaultMode = 'light',- id,+ firstItemId,'aria-label': ariaLabel,'aria-describedby': ariaDescribedby,}: ColorThemePickerProps) {const { t } = useLingui();- const selected = COLOR_THEMES.some((theme) => theme.id === value) ? value : 'default';return (- <RadioGroupPrimitive.Root- id={id}+ // `fieldset` rather than a div: the grid is a set of related controls, and+ // the UA border/padding are reset by the utilities below.+ <fieldsetaria-label={ariaLabel}aria-describedby={ariaDescribedby}- value={selected}- onValueChange={onSelect}- className="grid w-full grid-cols-2 gap-2 sm:grid-cols-3"+ className="grid w-full min-w-0 grid-cols-2 gap-2 sm:grid-cols-3">- {COLOR_THEMES.map((theme) => (- <RadioGroupPrimitive.Item- key={theme.id}- value={theme.id}- className={cn(- 'group/tile flex flex-col gap-1.5 rounded-lg border-2 border-transparent p-1 text-left outline-none',- 'hover:bg-accent/50 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40',- 'data-checked:border-primary',- )}- >- <ThemeSwatch theme={theme} customSeed={customSeed} defaultMode={defaultMode} />- <div className="flex items-center justify-between px-0.5">- <span className="text-1sm font-medium text-foreground">{theme.label}</span>- <span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">- {theme.id === 'custom'- ? customThemeKind(resolveCustomScheme(customSeed)) === 'dark'- ? t`Dark`- : t`Light`- : theme.kind === 'system'- ? t`Auto`- : theme.kind === 'light'- ? t`Light`- : t`Dark`}- </span>- </div>- </RadioGroupPrimitive.Item>- ))}- </RadioGroupPrimitive.Root>+ {COLOR_THEMES.map((theme, index) => {+ const isLight = selection.light === theme.id;+ const isDark = selection.dark === theme.id;+ return (+ <fieldset+ key={theme.id}+ aria-label={theme.label}+ className={cn(+ 'flex min-w-0 flex-col gap-1.5 rounded-lg border-2 p-1 text-left',+ selection[slotMode] === theme.id ? 'border-primary' : 'border-transparent',+ )}+ >+ {/*+ * Pointer-only convenience: the old picker made the whole tile the+ * selection target, so a click on the swatch has to keep doing+ * something. It assigns the mode on screen — never both slots — so+ * a click can't silently drop the other mode's palette.+ *+ * Hidden from the a11y tree (and out of the tab order) because it+ * duplicates an action the named sun/moon toggles already expose;+ * surfacing it would announce two controls with one behavior.+ */}+ <Button+ type="button"+ variant="ghost"+ aria-hidden+ tabIndex={-1}+ onClick={() => onAssign(slotMode, theme.id)}+ className="h-auto w-full cursor-pointer p-0 transition-opacity hover:bg-transparent hover:opacity-90"+ >+ <ThemeSwatch theme={theme} customSeed={customSeed} slotMode={slotMode} />+ </Button>+ <div className="flex items-center justify-between gap-1 px-0.5">+ <span className="truncate text-1sm font-medium text-foreground">{theme.label}</span>+ <div className="flex shrink-0 items-center gap-1">+ <Toggle+ id={index === 0 ? firstItemId : undefined}+ className={slotToggleClass(isLight)}+ pressed={isLight}+ onPressedChange={(pressed) => {+ if (pressed) onAssign('light', theme.id);+ }}+ aria-label={t`Use ${theme.label} as the light theme`}+ >+ <Sun className={slotIconClass(isLight)} />+ </Toggle>+ <Toggle+ className={slotToggleClass(isDark)}+ pressed={isDark}+ onPressedChange={(pressed) => {+ if (pressed) onAssign('dark', theme.id);+ }}+ aria-label={t`Use ${theme.label} as the dark theme`}+ >+ <Moon className={slotIconClass(isDark)} />+ </Toggle>+ </div>+ </div>+ </fieldset>+ );+ })}+ </fieldset>);}diff --git a/packages/app/src/components/settings/CustomThemeEditor.tsx b/packages/app/src/components/settings/CustomThemeEditor.tsxindex bdac86daa..48ef8c93c 100644--- a/packages/app/src/components/settings/CustomThemeEditor.tsx+++ b/packages/app/src/components/settings/CustomThemeEditor.tsx@@ -24,7 +24,9 @@ import {DEFAULT_CUSTOM_SCHEME,hasLegacyCustomSeed,isHexColor,+ resolveColorThemeSelection,resolveCustomScheme,+ resolveModePreference,} from '@/lib/color-themes';import { useConfigContextOptional } from '@/lib/config-context';import { dispatchExternalLinkClick } from '@/lib/external-link';@@ -52,10 +54,15 @@ const SCHEMES_URL = 'https://github.com/tinted-theming/schemes';*/export function CustomThemeEditor({ userBinding }: { userBinding: ConfigBinding }) {const { t } = useLingui();- const { setTheme } = useTheme();+ const { setTheme, systemTheme } = useTheme();const merged = useConfigContextOptional()?.merged ?? null;const committed = resolveCustomScheme(merged?.appearance?.customTheme);- const isActive = merged?.appearance?.colorTheme === 'custom';+ const modePreference = merged?.appearance?.theme;+ const selection = resolveColorThemeSelection(merged?.appearance);+ const slotMode = resolveModePreference(modePreference, systemTheme === 'dark');+ // Live preview only when the custom scheme is the palette actually on screen —+ // it may be assigned to the other mode's slot, where an edit shouldn't repaint.+ const isActive = selection[slotMode] === 'custom';// Local working copy for smooth live editing; re-sync when committed config// changes underneath us (another window, a reset, a hand-edit).@@ -76,7 +83,12 @@ export function CustomThemeEditor({ userBinding }: { userBinding: ConfigBindingfunction preview(next: Base16Scheme) {if (!isActive) return;- applyColorThemeToDom('custom', customThemeWritePatch(next));+ applyColorThemeToDom({+ selection,+ modePreference,+ slotMode,+ customSeed: customThemeWritePatch(next),+ });setTheme(customThemeKind(next) === 'dark' ? 'dark' : 'light');}@@ -159,7 +171,7 @@ export function CustomThemeEditor({ userBinding }: { userBinding: ConfigBinding<p className="text-1sm text-muted-foreground">{isActive? t`Edits apply live. Light or dark comes from the scheme.`- : t`Pick “Custom” above to use this scheme.`}+ : t`Press the sun or moon on “Custom” above to use this scheme.`}</p></div><div className="flex shrink-0 items-center gap-1">diff --git a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsxindex 954538609..08b3195ff 100644--- a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx+++ b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx@@ -17,6 +17,16 @@ import { emitConfigValidationRejected } from '@/lib/config-validation-events';import { expectVisualClassTokens } from '@/test-utils/visual-contract';import { SettingsDialogBody } from './SettingsDialogBody';+/** Drop every `null` leaf — the patch spelling for "delete this key". */+function stripNulls(value: unknown): unknown {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>)+ .filter(([, v]) => v !== null)+ .map(([k, v]) => [k, stripNulls(v)]),+ );+}+function makeBinding(config: Config = ConfigSchema.parse({})): {binding: ConfigBinding;patches: ConfigPatch[];@@ -28,7 +38,9 @@ function makeBinding(config: Config = ConfigSchema.parse({})): {patches.push(patch);return {ok: true,- effective: ConfigSchema.parse({ ...config, ...patch }),+ // `null` means "clear this key" in a real patch (the binding deletes it+ // before validating), so drop nulls rather than handing them to Zod.+ effective: ConfigSchema.parse({ ...config, ...stripNulls(patch) }),appliedPaths: ['editor.wordWrap'],};},@@ -43,10 +55,35 @@ function makeBinding(config: Config = ConfigSchema.parse({})): {return { binding, patches };}-function makeConfigContextValue(projectBinding: ConfigBinding = makeBinding().binding) {+/** A binding that rejects every write, for the error-routing path. */+function makeRejectingBinding(config: Config = ConfigSchema.parse({})): ConfigBinding {+ return {+ current: () => config,+ patch: () => ({+ ok: false,+ error: {+ code: 'SCHEMA_INVALID',+ message: 'config rejected',+ issues: [{ path: ['appearance', 'colorThemeLight'], message: 'palette write rejected' }],+ },+ }),+ subscribe: () => () => {},+ hasSynced: () => true,+ subscribeSynced: (listener) => {+ queueMicrotask(listener);+ return () => {};+ },+ dispose: () => {},+ } as unknown as ConfigBinding;+}++function makeConfigContextValue(+ projectBinding: ConfigBinding = makeBinding().binding,+ userBinding: ConfigBinding | null = null,+) {const config = ConfigSchema.parse({});return {- userBinding: null,+ userBinding,userSynced: true,projectBinding,projectLocalBinding: null,@@ -61,8 +98,16 @@ function makeConfigContextValue(projectBinding: ConfigBinding = makeBinding().bi} satisfies ConfigContextValue;}-function SettingsContextProvider({ children }: { children: ReactNode }) {- return <ConfigContext value={makeConfigContextValue()}>{children}</ConfigContext>;+function SettingsContextProvider({+ children,+ userBinding = null,+}: {+ children: ReactNode;+ userBinding?: ConfigBinding | null;+}) {+ return (+ <ConfigContext value={makeConfigContextValue(undefined, userBinding)}>{children}</ConfigContext>+ );}function renderPreferences(binding: ConfigBinding) {@@ -346,7 +391,7 @@ function renderThemePluginWithTheme(binding: ConfigBinding) {enableSystemstorageKey={`ok-theme-v1-test-${themeStorageKeySeq}`}>- <SettingsContextProvider>+ <SettingsContextProvider userBinding={binding}><TooltipProvider><SettingsDialogBodyactiveId="plugin:theme"@@ -373,29 +418,139 @@ describe('SettingsDialogBody color-palette picker — optimistic mode flip', ()expect(screen.queryByTestId('settings-scope-badge-project')).toBeNull();});- test('selecting a light palette (Catppuccin Latte) flips next-themes to light', async () => {+ test('assigning a palette to the mode on screen applies it immediately', async () => {+ // jsdom reports no dark preference, so the mode on screen is light and the+ // sun is the icon that changes what the user sees right now.const user = userEvent.setup();const { binding } = makeBinding();renderThemePluginWithTheme(binding);expect(screen.getByTestId('theme-probe').textContent).toBe('system');- await user.click(screen.getByRole('radio', { name: /Catppuccin Latte/ }));+ await user.click(screen.getByLabelText('Use Catppuccin Latte as the light theme'));await waitFor(() => {expect(screen.getByTestId('theme-probe').textContent).toBe('light');});});- test('selecting a dark palette (Catppuccin Frappé) flips next-themes to dark', async () => {+ test('a cross-variant palette in the on-screen slot forces its own mode', async () => {+ // Dracula is a dark-kind palette. Assigned to the LIGHT slot while the mode+ // on screen is light, it still forces its own dark variant, so the flip has+ // to drive next-themes to `dark` immediately (Tailwind `dark:` variants would+ // otherwise render dark-on-light until the config round-trip). The+ // Latte-into-light case above only exercises a same-variant assignment.const user = userEvent.setup();const { binding } = makeBinding();renderThemePluginWithTheme(binding);- await user.click(screen.getByRole('radio', { name: /Catppuccin Frappé/ }));+ expect(screen.getByTestId('theme-probe').textContent).toBe('system');++ await user.click(screen.getByLabelText('Use Dracula as the light theme'));await waitFor(() => {expect(screen.getByTestId('theme-probe').textContent).toBe('dark');});});++ test('assigning a palette to the OTHER mode leaves the current appearance alone', async () => {+ // The whole point of the pair: staging a dark palette while working in+ // light must not drag the app into dark mode.+ const user = userEvent.setup();+ const { binding } = makeBinding();+ renderThemePluginWithTheme(binding);++ await user.click(screen.getByLabelText('Use Catppuccin Frappé as the dark theme'));++ await waitFor(() => {+ expect(screen.getByTestId('theme-probe').textContent).toBe('system');+ });+ });++ test('reset clears BOTH slots, not just the path the row is keyed by', async () => {+ // The row is anchored to colorThemeLight but speaks for both modes, so a+ // per-path reset would strand the dark palette under a "reset to default"+ // label.+ const user = userEvent.setup();+ const { binding, patches } = makeBinding(+ ConfigSchema.parse({ appearance: { colorThemeLight: 'dracula' } }),+ );+ renderThemePluginWithTheme(binding);++ const resetButton = await screen.findByRole('button', {+ name: /Reset Color theme to default/i,+ });+ await user.click(resetButton);++ await waitFor(() => {+ expect(patches).toEqual([+ { appearance: { colorThemeLight: null, colorThemeDark: null, colorTheme: null } },+ ]);+ });+ });++ test('a rejected write surfaces an inline error instead of failing silently', async () => {+ // Writing through the binding directly skips the form commit that every+ // other field uses to route rejections into its own FormMessage.+ const user = userEvent.setup();+ renderThemePluginWithTheme(makeRejectingBinding());++ // Assign the slot that is actually on screen (jsdom reports no dark+ // preference, so the sun is the live one). Assigning the other slot paints+ // nothing, which would make the revert a no-op and the assertion vacuous.+ expect(document.documentElement.hasAttribute('data-color-theme')).toBe(false);++ await user.click(screen.getByLabelText('Use Catppuccin Latte as the light theme'));++ await waitFor(() => {+ expect(screen.getByText('palette write rejected')).toBeDefined();+ });+ // The optimistic paint set the attribute before the write; the rejection+ // has to undo it, or the user is left looking at a palette that was never+ // persisted next to an error saying so.+ expect(document.documentElement.hasAttribute('data-color-theme')).toBe(false);+ });++ test('a rejected cross-variant pick also reverts the forced light/dark mode', async () => {+ // Assigning a dark palette to the light slot forces dark mode optimistically.+ // Reverting only the palette attribute would strand that mode on the+ // previous palette, so the revert has to undo both effects.+ const user = userEvent.setup();+ renderThemePluginWithTheme(makeRejectingBinding());++ expect(screen.getByTestId('theme-probe').textContent).toBe('system');++ await user.click(screen.getByLabelText('Use Dracula as the light theme'));++ await waitFor(() => {+ expect(screen.getByText('palette write rejected')).toBeDefined();+ });+ // Back to the user's own preference, not Dracula's forced dark.+ await waitFor(() => {+ expect(screen.getByTestId('theme-probe').textContent).toBe('system');+ });+ // Both halves of the optimistic apply have to come back, so check the+ // attribute here too rather than leaving it to the same-variant sibling.+ expect(document.documentElement.hasAttribute('data-color-theme')).toBe(false);+ });++ test('one patch writes both slots and retires the pre-pair key', async () => {+ const user = userEvent.setup();+ const { binding, patches } = makeBinding();+ renderThemePluginWithTheme(binding);++ await user.click(screen.getByLabelText('Use Catppuccin Frappé as the dark theme'));++ await waitFor(() => {+ expect(patches).toEqual([+ {+ appearance: {+ colorThemeLight: 'default',+ colorThemeDark: 'catppuccin-frappe',+ colorTheme: null,+ },+ },+ ]);+ });+ });});diff --git a/packages/app/src/components/settings/field-controls.tsx b/packages/app/src/components/settings/field-controls.tsxindex 20e3eeda3..ad81e837a 100644--- a/packages/app/src/components/settings/field-controls.tsx+++ b/packages/app/src/components/settings/field-controls.tsx@@ -38,7 +38,15 @@ import { Switch } from '@/components/ui/switch';import { Textarea } from '@/components/ui/textarea';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';-import { colorThemeMode, customThemeKind, resolveCustomScheme } from '@/lib/color-themes';+import {+ colorThemeMode,+ colorThemeResetPatch,+ colorThemeWritePatch,+ customThemeKind,+ resolveColorThemeSelection,+ resolveCustomScheme,+ resolveModePreference,+} from '@/lib/color-themes';import { useConfigContextOptional } from '@/lib/config-context';import { applyColorThemeToDom } from '@/lib/use-apply-config-color-theme';import { cn } from '@/lib/utils';@@ -51,6 +59,7 @@ import {} from './schema-walker';import type { FieldDef } from './settings-fields';import type { SlotForwardedProps } from './slot-forwarded-props';+import { pickFirstIssueForPath } from './use-config-form';/*** Internal scope tag for routing each section to its config binding.@@ -95,6 +104,7 @@ export function SettingsField({ field, scope, commitField, isFlashed }: Settings'use no memo';const { t } = useLingui();const form = useFormContext<Config>();+ const configContext = useConfigContextOptional();const leafSchema = resolveLeafSchema(ConfigSchema, field.path);const typeTag = leafSchema ? getLeafTypeTag(leafSchema) : undefined;const defaultValue = leafSchema ? getFieldDefault(leafSchema) : undefined;@@ -170,6 +180,23 @@ export function SettingsField({ field, scope, commitField, isFlashed }: Settings* field doesn't end up flagged as dirty after reset.*/const reset = () => {+ // The theme row is anchored to a single path but represents both slots, so+ // the generic per-path reset would clear the light palette and silently+ // leave the dark one assigned, under a label that says "reset to default".+ if (field.control === 'theme-tiles') {+ const binding = configContext?.userBinding;+ if (!binding) return;+ const result = binding.patch({ appearance: colorThemeResetPatch() });+ if (result.ok) {+ flashSavedTick();+ } else {+ form.setError(dottedName, {+ type: 'manual',+ message: pickFirstIssueForPath(result.error, dottedName),+ });+ }+ return;+ }const target = defaultValue === undefined ? null : defaultValue;form.setValue(dottedName, target as never, { shouldDirty: false });runCommit();@@ -224,6 +251,13 @@ export function SettingsField({ field, scope, commitField, isFlashed }: SettingstypeTag={typeTag}enumOptions={enumOptions}onCommit={runCommitIfDirty}+ onSavedOutsideForm={flashSavedTick}+ onWriteRejected={(error) => {+ form.setError(dottedName, {+ type: 'manual',+ message: pickFirstIssueForPath(error, dottedName),+ });+ }}/></FormControl><SavedIndicator visible={savedTick} srOnly={field.control === 'theme-tiles'} />@@ -247,6 +281,18 @@ interface FieldControlBodyProps {* `ctl.onChange` BEFORE invoking — the commit reads from form state.*/onCommit: () => boolean;+ /**+ * Flash the saved indicator for a control that writes through the binding+ * directly instead of the form's per-field commit. `onCommit` is not usable+ * there: it re-reads the form value for this field's single path, which for a+ * multi-path atomic write is both stale and narrower than what was written.+ */+ onSavedOutsideForm: () => void;+ /**+ * Surface a rejected binding write on this row, the same way `runCommit`+ * surfaces one for a form-committed field.+ */+ onWriteRejected: (error: ConfigValidationError) => void;}/**@@ -270,6 +316,8 @@ function FieldControlBody({typeTag,enumOptions,onCommit,+ onSavedOutsideForm,+ onWriteRejected,...slotForwarded}: FieldControlBodyProps & SlotForwardedProps) {'use no memo';@@ -284,47 +332,73 @@ function FieldControlBody({const { setTheme, systemTheme } = useTheme();// Optional: the theme-tiles control reads the custom-theme seed from config,// but FieldControlBody also renders in provider-less unit harnesses.- const merged = useConfigContextOptional()?.merged ?? null;+ const config = useConfigContextOptional();+ const merged = config?.merged ?? null;if (field.control === 'theme-tiles') {const { id: forwardedId, ...wrapperSlotProps } = slotForwarded;const customSeed = merged?.appearance?.customTheme;- // The Default tile previews the base palette in the user's own light/dark- // mode. Source it from `appearance.theme` (falling back to the OS for- // 'system'/unset), never from next-themes' resolved mode — that one carries- // whatever the selected palette forced.- const configuredMode = merged?.appearance?.theme;- const defaultMode =- configuredMode === 'light' || configuredMode === 'dark'- ? configuredMode- : systemTheme === 'dark'- ? 'dark'- : 'light';+ // The mode on screen — read from `appearance.theme` (falling back to the OS+ // for 'system'/unset), never from next-themes' resolved mode, which carries+ // whatever the applied palette forced.+ const modePreference = merged?.appearance?.theme;+ const slotMode = resolveModePreference(modePreference, systemTheme === 'dark');+ const selection = resolveColorThemeSelection(merged?.appearance);return (<ColorThemePicker{...wrapperSlotProps}- id={forwardedId}- value={typeof ctl.value === 'string' ? ctl.value : 'default'}+ firstItemId={forwardedId}+ selection={selection}customSeed={customSeed}- defaultMode={defaultMode}+ slotMode={slotMode}aria-label={t(field.label)}- onSelect={(next) => {+ onAssign={(slot, id) => {+ // Paint first, persist second — but only when there is somewhere to+ // persist to. Without the binding the optimistic apply would leave+ // the screen showing a palette no config carries, which the next+ // ConfigProvider pass silently reverts.+ const binding = config?.userBinding;+ if (!binding) return;+ const next = { ...selection, [slot]: id };// Optimistic apply: paint the palette overlay synchronously and flip// next-themes to the palette's forced mode so `dark:` variants land- // immediately. A built-in palette forces light (Catppuccin Latte) or- // dark; `custom` follows its seed. `default` is system-kind, so- // `colorThemeMode` returns undefined — no flip, and the ConfigProvider- // effect restores the user's saved light/dark mode on the round-trip.- applyColorThemeToDom(next, customSeed);- if (next === 'custom') {- setTheme(- customThemeKind(resolveCustomScheme(customSeed)) === 'dark' ? 'dark' : 'light',- );- } else {- const mode = colorThemeMode(next);- if (mode) setTheme(mode);+ // immediately. Assigning the slot the user is NOT currently in changes+ // nothing on screen — `applyColorThemeToDom` still runs, to refresh+ // the pre-paint cache for the next time that mode comes around.+ // The mode a selection forces, or undefined for a palette-less+ // `default`, which leaves the user's own light/dark preference alone.+ const forcedMode = (candidate: typeof selection): 'light' | 'dark' | undefined => {+ const palette = candidate[slotMode];+ return palette === 'custom'+ ? customThemeKind(resolveCustomScheme(customSeed))+ : colorThemeMode(palette);+ };+ applyColorThemeToDom({ selection: next, modePreference, slotMode, customSeed });+ const nextMode = forcedMode(next);+ if (nextMode) setTheme(nextMode);+ // Both slots are written in ONE patch (and the pre-pair `colorTheme`+ // retired) rather than through the form's per-field commit, which+ // carries a single path. RHF re-syncs from the binding subscription;+ // neither field is dirty here, so nothing of the user's is stomped.+ const result = binding.patch({ appearance: colorThemeWritePatch(next) });+ if (result.ok) {+ onSavedOutsideForm();+ return;}- ctl.onChange(next);- onCommit();+ // Every other field routes a rejected write into its own+ // <FormMessage> through `runCommit`. Writing through the binding+ // directly skipped that, so a rejection (a hand-edited config that+ // no longer parses, say) left the palette painted with nothing+ // persisted and nothing said. Repaint the committed selection and+ // surface the error on this row.+ applyColorThemeToDom({ selection, modePreference, slotMode, customSeed });+ // The optimistic apply flipped two things, so the revert has to undo+ // both. Restoring only the palette attribute leaves a cross-variant+ // pick's forced `.dark` class on the previous palette.+ // Falls back to 'system' the way ConfigProvider does: an unset+ // `appearance.theme` still has a mode to go back to, and without it a+ // failed pick would strand the flip it made on the way in.+ setTheme(forcedMode(selection) ?? modePreference ?? 'system');+ onWriteRejected(result.error);}}/>);diff --git a/packages/app/src/components/settings/settings-fields.ts b/packages/app/src/components/settings/settings-fields.tsindex a1ba51d17..e47a44d54 100644--- a/packages/app/src/components/settings/settings-fields.ts+++ b/packages/app/src/components/settings/settings-fields.ts@@ -59,11 +59,14 @@ export const FIELDS_USER_PREFERENCES: FieldDef[] = [// The color-theme picker is a theme "plugin": it lives in the Plugins menu// (Settings → Plugins → Themes) as a peer of the lint plugins, not in// Preferences. `appearance.theme` (light/dark/system) stays in Preferences.+// One control writes both palette slots, so it is declared against the light+// one — the path is what the search index navigates to and what the field row+// is keyed by, not a per-slot rendering hint.export const FIELDS_THEME_PLUGIN: FieldDef[] = [{- path: ['appearance', 'colorTheme'],+ path: ['appearance', 'colorThemeLight'],label: msg`Color theme`,- description: msg`Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences.`,+ description: msg`Pick a palette for light mode and one for dark mode. The theme setting in Preferences chooses between them — on “System”, so does your OS.`,control: 'theme-tiles',},];diff --git a/packages/app/src/components/settings/settings-search-index.test.ts b/packages/app/src/components/settings/settings-search-index.test.tsindex 3fab29fab..4e91bd4c9 100644--- a/packages/app/src/components/settings/settings-search-index.test.ts+++ b/packages/app/src/components/settings/settings-search-index.test.ts@@ -67,13 +67,13 @@ describe('buildSettingsSearchIndex', () => {groups: groupsFixture({ themeVisible: true }),translate,});- expect(withTheme.some((e) => e.targetField === 'appearance.colorTheme')).toBe(true);+ expect(withTheme.some((e) => e.targetField === 'appearance.colorThemeLight')).toBe(true);const withoutTheme = buildSettingsSearchIndex({groups: groupsFixture({ themeVisible: false }),translate,});- expect(withoutTheme.some((e) => e.targetField === 'appearance.colorTheme')).toBe(false);+ expect(withoutTheme.some((e) => e.targetField === 'appearance.colorThemeLight')).toBe(false);});test('markdownlint rules indexed only when the panel is visible (disabled plugin excluded)', () => {diff --git a/packages/app/src/components/terminal-theme.dom.test.ts b/packages/app/src/components/terminal-theme.dom.test.tsnew file mode 100644index 000000000..e33b9efed--- /dev/null+++ b/packages/app/src/components/terminal-theme.dom.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { computeLiveXtermTheme } from './terminal-theme';++/**+ * The default token reader probes the live palette through the DOM. Attaching a+ * probe re-dirties style, so reading one token at a time costs a forced style+ * recalculation per token, against styles a theme switch has just invalidated.+ * These pin the batched shape: one attach for the whole palette, then the+ * reads. The sibling `terminal-theme.test.ts` covers slot mapping and+ * fallbacks through an injected reader, which never touches this path.+ */+describe('computeLiveXtermTheme default token reader', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ document.body.innerHTML = '';+ });++ /** Probe spans live in <body> for the duration of the batch. */+ const spansInBody = () => document.body.getElementsByTagName('span').length;++ it('attaches every probe before reading any of them', () => {+ const attachedAtRead: number[] = [];+ const real = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(((el: Element) => {+ attachedAtRead.push(spansInBody());+ return real(el);+ }) as typeof window.getComputedStyle);++ computeLiveXtermTheme('dark');++ // Sanity: the palette is read token-by-token, so there is more than one read.+ expect(attachedAtRead.length).toBeGreaterThan(1);+ // The whole batch is already attached at the FIRST read, and stays attached+ // for all of them. A probe-per-token loop would report 1 every time, so the+ // count-equals-reads check is what fails if the batching regresses.+ expect(attachedAtRead[0]).toBe(attachedAtRead.length);+ expect(new Set(attachedAtRead).size).toBe(1);+ });++ it('removes every probe once the batch is read', () => {+ computeLiveXtermTheme('dark');+ expect(spansInBody()).toBe(0);+ });+});diff --git a/packages/app/src/components/terminal-theme.test.ts b/packages/app/src/components/terminal-theme.test.tsindex e77a1f43a..2f5698052 100644--- a/packages/app/src/components/terminal-theme.test.ts+++ b/packages/app/src/components/terminal-theme.test.ts@@ -156,4 +156,16 @@ describe('computeLiveXtermTheme', () => {expect(theme.foreground).toBe(XTERM_LIGHT_THEME.foreground);expect(theme.selectionBackground).toBe(XTERM_LIGHT_THEME.selectionBackground);});++ // This file runs off-DOM, so omitting the reader exercises the real default+ // one against a genuinely absent `document` — the SSR path, not a simulation+ // of it. Nothing catches on that path, so the structural guard is the only+ // thing standing between an absent DOM and a ReferenceError reaching the+ // caller's render.+ test('the default reader yields the curated palette when there is no DOM', () => {+ expect(typeof document).toBe('undefined');+ expect(() => computeLiveXtermTheme('dark')).not.toThrow();+ expect(computeLiveXtermTheme('dark')).toEqual(XTERM_DARK_THEME);+ expect(computeLiveXtermTheme('light')).toEqual(XTERM_LIGHT_THEME);+ });});diff --git a/packages/app/src/components/terminal-theme.ts b/packages/app/src/components/terminal-theme.tsindex 6bb7531e3..dab6d096f 100644--- a/packages/app/src/components/terminal-theme.ts+++ b/packages/app/src/components/terminal-theme.ts@@ -71,35 +71,61 @@ export function xtermThemeForMode(resolvedTheme: string | undefined): ITheme {/** Resolve one design token (`--background`, …) to a concrete color, or null. */export type TokenColorReader = (token: string) => string | null;+/** Classify one probe's `backgroundColor` readback as a color, or absent. */+function normalizeProbedColor(resolved: string | undefined): string | null {+ // An unset token computes to the transparent initial value — treat as+ // absent rather than skinning the terminal invisible. A value still+ // containing `var(` means the environment didn't resolve custom+ // properties (happy-dom in tests) — also absent.+ if (!resolved || resolved === 'rgba(0, 0, 0, 0)' || resolved === 'transparent') return null;+ if (resolved.includes('var(')) return null;+ return resolved;+}+/**- * Default token reader: a detached-then-attached probe span whose- * `backgroundColor` is `var(<token>)`, read back through `getComputedStyle`.- * The round-trip makes the browser resolve `var()` chains and relative color- * syntax (`oklch(from var(--primary) …)`) to a concrete color string, which- * xterm's browser build can parse via its canvas litmus. Returns null when the- * token is unset or the environment can't resolve it (tests, SSR).+ * Default token reader: probe spans whose `backgroundColor` is `var(<token>)`,+ * read back through `getComputedStyle`. The round-trip makes the browser+ * resolve `var()` chains and relative color syntax (`oklch(from var(--primary)+ * …)`) to a concrete color string, which xterm's browser build can parse via+ * its canvas litmus. Absent tokens map to null so each slot falls back on its+ * own; an environment with no DOM at all (SSR) yields an empty map.+ *+ * Every probe is attached in ONE insertion and read only once all of them are+ * in the tree. Appending re-dirties style, so a probe-per-token loop pays a+ * forced style recalculation per token, and a recompute is triggered by a theme+ * switch that has just invalidated every computed style in the document, which+ * is exactly when that recalculation is most expensive. Batching holds the+ * whole palette to a single one.*/-function readTokenColor(token: string): string | null {- try {+function readTokenColors(tokens: readonly string[]): Map<string, string | null> {+ const resolved = new Map<string, string | null>();+ // Off-DOM (SSR, node-environment tests) is an expected caller, not an+ // exceptional one, so it reads as a condition rather than as a thrown+ // ReferenceError caught after the fact. The empty map reads downstream as+ // "every token absent", which falls each slot back to the curated palette.+ if (typeof document === 'undefined' || !document.body) return resolved;++ const fragment = document.createDocumentFragment();+ const probes = tokens.map((token) => {const probe = document.createElement('span');probe.style.display = 'none';probe.style.backgroundColor = `var(${token})`;- document.body.appendChild(probe);- try {- const resolved = getComputedStyle(probe).backgroundColor;- // An unset token computes to the transparent initial value — treat as- // absent rather than skinning the terminal invisible. A value still- // containing `var(` means the environment didn't resolve custom- // properties (happy-dom in tests) — also absent.- if (!resolved || resolved === 'rgba(0, 0, 0, 0)' || resolved === 'transparent') return null;- if (resolved.includes('var(')) return null;- return resolved;- } finally {- probe.remove();+ fragment.appendChild(probe);+ return { token, probe };+ });+ document.body.appendChild(fragment);+ // finally, not catch: the probes must never outlive the read, but a throw+ // here would mean the style engine failed on this document's own same-origin+ // nodes. Nothing in this palette is worth swallowing that, and a silent+ // fallback to curated colors would hide it.+ try {+ for (const { token, probe } of probes) {+ resolved.set(token, normalizeProbedColor(getComputedStyle(probe).backgroundColor));}- } catch {- return null;+ } finally {+ for (const { probe } of probes) probe.remove();}+ return resolved;}/** xterm ANSI slot → the `--ansi-*` custom property carrying its color. */@@ -122,6 +148,20 @@ const ANSI_TOKEN_BY_SLOT: Record<AnsiSlotName, string> = {brightWhite: '--ansi-bright-white',};+/** Every token one recompute needs, so they can be probed in a single batch. */+const LIVE_THEME_TOKENS: readonly string[] = [+ '--background',+ '--foreground',+ '--selection-soft',+ ...Object.values(ANSI_TOKEN_BY_SLOT),+];++/** Probe the whole palette once, then serve each slot from the result. */+function createBatchedTokenReader(): TokenColorReader {+ const batch = readTokenColors(LIVE_THEME_TOKENS);+ return (token) => batch.get(token) ?? null;+}+/*** The live theme as an xterm palette — surfaces and all sixteen ANSI slots read* from the app's tokens, so a color theme repaints program output and not just@@ -138,7 +178,7 @@ const ANSI_TOKEN_BY_SLOT: Record<AnsiSlotName, string> = {*/export function computeLiveXtermTheme(resolvedTheme: string | undefined,- readToken: TokenColorReader = readTokenColor,+ readToken: TokenColorReader = createBatchedTokenReader(),): ITheme {const base = xtermThemeForMode(resolvedTheme);const background = readToken('--background') ?? base.background;diff --git a/packages/app/src/components/use-live-xterm-theme.dom.test.tsx b/packages/app/src/components/use-live-xterm-theme.dom.test.tsxnew file mode 100644index 000000000..bcca51f6e--- /dev/null+++ b/packages/app/src/components/use-live-xterm-theme.dom.test.tsx@@ -0,0 +1,130 @@+import { render } from '@testing-library/react';+import { act } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { COLOR_THEME_ATTRIBUTE } from '@/lib/use-apply-config-color-theme';+import { computeLiveXtermTheme } from './terminal-theme';+import { useLiveXtermTheme } from './use-live-xterm-theme';++/**+ * One theme switch lands as several watched mutations arriving across separate+ * tasks, and each recompute probes the whole palette against styles the switch+ * just invalidated. These pin the frame-coalescing that keeps that burst to a+ * single recompute.+ *+ * A recompute is counted by the probe reads it performs rather than by render+ * count: the palette resolves to the same colors either way, so the hook holds+ * theme identity stable and a coalescing regression would be invisible in+ * renders while still doing the work N times over.+ *+ * MutationObserver delivers on a microtask, so each burst is followed by an+ * awaited flush before the frame is advanced — a synchronous act() returns+ * before the observer has run and the recompute would look like it never+ * scheduled.+ */+describe('useLiveXtermTheme frame coalescing', () => {+ let reads = 0;++ function Probe() {+ useLiveXtermTheme('dark');+ return null;+ }++ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] });+ const real = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(((el: Element) => {+ reads += 1;+ return real(el);+ }) as typeof window.getComputedStyle);+ reads = 0;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ // restoreAllMocks leaves stubGlobal in place, and this config sets no+ // unstubGlobals, so an assertion that throws mid-test would strand an+ // undefined requestAnimationFrame on every test after it.+ vi.unstubAllGlobals();+ vi.useRealTimers();+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ document.documentElement.classList.remove('dark');+ document.getElementById('coalescing-probe-style')?.remove();+ });++ /** Reads one recompute performs, measured off the shared palette reader. */+ function readsPerRecompute(): number {+ reads = 0;+ computeLiveXtermTheme('dark');+ expect(reads).toBeGreaterThan(0);+ return reads;+ }++ it('collapses a burst of watched mutations into one recompute per frame', async () => {+ const perRecompute = readsPerRecompute();+ const view = render(<Probe />);+ reads = 0;++ // Three watched mutations of the kind a theme switch produces: the palette+ // attribute, the forced light/dark class, and the custom-palette <style>.+ // Each is flushed separately so it arrives as its OWN observer callback.+ // Mutating them in one go is what the real burst does NOT do, and would+ // leave MutationObserver's own same-microtask batching to collapse them+ // before this hook ever sees three of anything.+ await act(async () => {+ document.documentElement.setAttribute(COLOR_THEME_ATTRIBUTE, 'gruvbox');+ await Promise.resolve();+ document.documentElement.classList.add('dark');+ await Promise.resolve();+ const style = document.createElement('style');+ style.id = 'coalescing-probe-style';+ document.head.appendChild(style);+ await Promise.resolve();+ });++ // All three landed before the frame ran, so the frame owes exactly one+ // recompute no matter how many callbacks asked for it.+ await act(async () => {+ vi.advanceTimersToNextFrame();+ });++ expect(reads).toBe(perRecompute);+ view.unmount();+ });++ it('does not recompute after unmount for a frame already scheduled', async () => {+ const view = render(<Probe />);+ document.documentElement.setAttribute(COLOR_THEME_ATTRIBUTE, 'nord');+ await act(async () => {+ await Promise.resolve();+ });++ reads = 0;+ view.unmount();+ await act(async () => {+ vi.advanceTimersToNextFrame();+ });++ // The pending frame was cancelled on teardown, so the scheduled recompute+ // never ran against the unmounted hook's closure.+ expect(reads).toBe(0);+ });++ it('recomputes synchronously where requestAnimationFrame is unavailable', async () => {+ // Real timers, so the absence below is the branch's own condition rather+ // than an artefact of rAF being faked.+ vi.useRealTimers();+ vi.stubGlobal('requestAnimationFrame', undefined);+ const perRecompute = readsPerRecompute();++ const view = render(<Probe />);+ reads = 0;+ document.documentElement.setAttribute(COLOR_THEME_ATTRIBUTE, 'gruvbox');+ await act(async () => {+ await Promise.resolve();+ });++ // No frame to wait for, so the observer callback recomputes in line.+ expect(reads).toBe(perRecompute);+ view.unmount();+ });+});diff --git a/packages/app/src/components/use-live-xterm-theme.ts b/packages/app/src/components/use-live-xterm-theme.tsindex ab6a7214a..2f8e92818 100644--- a/packages/app/src/components/use-live-xterm-theme.ts+++ b/packages/app/src/components/use-live-xterm-theme.ts@@ -30,7 +30,26 @@ export function useLiveXtermTheme(resolvedTheme: string | undefined): ITheme {// The mount/prop-change recompute also covers the first client render// (initial state may have computed before the FOUC script's tokens won).recompute();- const observer = new MutationObserver(recompute);+ // One theme switch lands as several watched mutations (the palette+ // attribute, the forced light/dark class, the custom-palette <style>), and+ // they arrive across separate tasks, so MutationObserver's own+ // same-microtask batching does not merge them. Each recompute probes the+ // whole palette against styles the switch just invalidated, so coalescing+ // to one recompute per frame is worth the deferral; reading after the+ // frame's style flush is what consumers want anyway. A hidden window parks+ // the frame until it is shown, which is the right place to skip the work.+ let scheduled = 0;+ const schedule =+ typeof requestAnimationFrame === 'function'+ ? () => {+ if (scheduled) return;+ scheduled = requestAnimationFrame(() => {+ scheduled = 0;+ recompute();+ });+ }+ : recompute;+ const observer = new MutationObserver(schedule);observer.observe(document.documentElement, {attributes: true,attributeFilter: [COLOR_THEME_ATTRIBUTE, 'class'],@@ -38,7 +57,10 @@ export function useLiveXtermTheme(resolvedTheme: string | undefined): ITheme {// The custom theme's palette lives in a <style> tag upserted into <head>;// watch its insertion/removal and text swaps.observer.observe(document.head, { childList: true, subtree: true, characterData: true });- return () => observer.disconnect();+ return () => {+ if (scheduled) cancelAnimationFrame(scheduled);+ observer.disconnect();+ };}, [resolvedTheme]);return theme;diff --git a/packages/app/src/lib/color-themes.test.ts b/packages/app/src/lib/color-themes.test.tsindex 524b2fe61..bcfa7e005 100644--- a/packages/app/src/lib/color-themes.test.ts+++ b/packages/app/src/lib/color-themes.test.ts@@ -8,6 +8,7 @@ import {base16ToTokens,buildCustomThemeCss,COLOR_THEMES,+ colorThemeWritePatch,customThemeKind,customThemeWritePatch,DEFAULT_CUSTOM_SCHEME,@@ -18,8 +19,15 @@ import {isHexColor,relativeLuminance,resolveColorTheme,+ resolveColorThemeSelection,resolveCustomScheme,} from './color-themes';+import {+ COLOR_THEME_PAIR_STORAGE_KEY,+ COLOR_THEME_STORAGE_KEY,+ CUSTOM_THEME_STORAGE_KEY,+ CUSTOM_THEME_STYLE_ID,+} from './use-apply-config-color-theme';const here = dirname(fileURLToPath(import.meta.url));const HEX = /^#[0-9a-f]{6}$/;@@ -176,39 +184,38 @@ describe('generated stylesheet', () => {});describe('registry stays in sync with its consumers', () => {- test('ids match the appearance.colorTheme enum in ConfigSchema', () => {- const leaf = resolveLeafSchema(ConfigSchema, ['appearance', 'colorTheme']);- const enumOptions = leaf ? getEnumOptions(leaf) : undefined;- expect([...(enumOptions ?? [])].sort()).toEqual(COLOR_THEMES.map((t) => t.id).sort());+ test('ids match every appearance palette enum in ConfigSchema', () => {+ for (const field of ['colorTheme', 'colorThemeLight', 'colorThemeDark']) {+ const leaf = resolveLeafSchema(ConfigSchema, ['appearance', field]);+ const enumOptions = leaf ? getEnumOptions(leaf) : undefined;+ expect([...(enumOptions ?? [])].sort(), field).toEqual(COLOR_THEMES.map((t) => t.id).sort());+ }});- test('every static IDE id appears in the index.html FOUC allowlist', () => {- // The pre-paint script in index.html can't import this module, so it- // hardcodes the id allowlist. `default` (no overlay) and `custom` (replayed- // from a cached <style>, not the static allowlist) are handled separately.+ test('the pre-paint FOUC script reads exactly the caches the apply path writes', () => {+ // index.html can't import a module, so its script hardcodes the key names.+ // A rename on either side would silently cost the flash-free first paint.const html = readFileSync(resolve(here, '../../index.html'), 'utf8');- for (const theme of COLOR_THEMES) {- if (theme.id === 'default' || theme.id === 'custom') continue;- expect(html, theme.id).toContain(`'${theme.id}'`);+ for (const key of [+ COLOR_THEME_PAIR_STORAGE_KEY,+ COLOR_THEME_STORAGE_KEY,+ CUSTOM_THEME_STORAGE_KEY,+ CUSTOM_THEME_STYLE_ID,+ ]) {+ expect(html, key).toContain(`'${key}'`);}});- test('the index.html FOUC light-theme set matches the registry light themes', () => {- // The pre-paint script decides the `dark` class before any bundle loads, so- // it can't import the registry — it carries its own light-id array- // (`[...].includes(ct)`). Adding a light theme must update that array too, or- // the new theme would flash dark on first paint. This asserts the two stay in- // lockstep (the light-kind analog of the allowlist-presence check above).+ test('the pre-paint FOUC script carries no palette-id knowledge', () => {+ // Each cached slot ships its own resolved `dark` flag, so the script never+ // has to know which palettes are light — the enumeration that used to live+ // here (and had to be edited alongside every new theme) is gone. `default`+ // and `custom` are structural cases, not palettes, so they stay.const html = readFileSync(resolve(here, '../../index.html'), 'utf8');- const match = html.match(/\[([^\]]*)\]\.includes\(ct\)/);- expect(match, 'FOUC light-theme array (`[...].includes(ct)`) not found in index.html').not.toBe(- null,- );- const scriptLightIds = [...(match?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]).sort();- const registryLightIds = COLOR_THEMES.filter((t) => t.kind === 'light')- .map((t) => t.id)- .sort();- expect(scriptLightIds).toEqual(registryLightIds);+ for (const theme of COLOR_THEMES) {+ if (NON_STATIC.has(theme.id)) continue;+ expect(html, theme.id).not.toContain(theme.id);+ }});test('custom is registered as a tile and accepted by the schema enum', () => {@@ -401,3 +408,24 @@ describe('hasLegacyCustomSeed', () => {expect(lightCss).toContain('color-scheme: light;');});});++describe('colorThemeWritePatch', () => {+ test('writes both slots and retires the pre-pair key', () => {+ const selection = resolveColorThemeSelection({ colorTheme: 'dracula' });+ expect(colorThemeWritePatch({ ...selection, light: 'catppuccin-latte' })).toEqual({+ colorThemeLight: 'catppuccin-latte',+ colorThemeDark: 'dracula',+ colorTheme: null,+ });+ });++ test('assigning the same palette to both modes is a supported end state', () => {+ const selection = resolveColorThemeSelection({+ colorThemeLight: 'catppuccin-latte',+ colorThemeDark: 'dracula',+ });+ const patch = colorThemeWritePatch({ ...selection, dark: 'catppuccin-latte' });+ expect(patch.colorThemeLight).toBe('catppuccin-latte');+ expect(patch.colorThemeDark).toBe('catppuccin-latte');+ });+});diff --git a/packages/app/src/lib/color-themes.ts b/packages/app/src/lib/color-themes.tsindex b8c032858..afe461da1 100644--- a/packages/app/src/lib/color-themes.ts+++ b/packages/app/src/lib/color-themes.ts@@ -17,6 +17,7 @@ import {base16ToTokens,CHROME_BG_DARK,CHROME_BG_LIGHT,+ type ColorThemeSelection,colorThemeMode,generateColorThemesCss,isBase16Hex,@@ -25,12 +26,15 @@ import {PREVIEW_THEME_TOKENS,relativeLuminance,renderThemeBlock,+ resolveColorThemeSelection,+ resolveModePreference,resolveThemePlugin,THEME_PLUGINS,type ThemePlugin,+ type ThemePluginId,} from '@inkeep/open-knowledge-core';-export type { Base16Scheme };+export type { Base16Scheme, ColorThemeSelection, ThemePluginId };// Re-export the core registry + pure token logic under the app's existing names.export {base16ToTokens,@@ -38,11 +42,43 @@ export {generateColorThemesCss,isDarkTheme as isDarkColorTheme,relativeLuminance,+ resolveColorThemeSelection,+ resolveModePreference,resolveThemePlugin as resolveColorTheme,THEME_PLUGINS as COLOR_THEMES,};export type ColorTheme = ThemePlugin;+/**+ * The `appearance` patch that writes the light/dark palette pair.+ *+ * Both slots are always written, and the pre-pair `colorTheme` retired (`null`+ * deletes a key in a config patch), so the first pick in the Themes pane+ * normalizes a legacy config in one transaction instead of leaving a+ * half-format behind that later reads as a seed for whichever slot is missing.+ */+export function colorThemeWritePatch(next: ColorThemeSelection): {+ colorThemeLight: ThemePluginId;+ colorThemeDark: ThemePluginId;+ colorTheme: null;+} {+ return { colorThemeLight: next.light, colorThemeDark: next.dark, colorTheme: null };+}++/**+ * The `appearance` patch that returns both modes to the base stylesheet.+ *+ * The mirror of `colorThemeWritePatch`: clearing one slot would leave the other+ * palette assigned while the control that offers it speaks for both.+ */+export function colorThemeResetPatch(): {+ colorThemeLight: null;+ colorThemeDark: null;+ colorTheme: null;+} {+ return { colorThemeLight: null, colorThemeDark: null, colorTheme: null };+}+// ---------------------------------------------------------------------------// Default theme — the base `:root` / `.dark` palette (`colorTheme: 'default'`).//diff --git a/packages/app/src/lib/config-provider.tsx b/packages/app/src/lib/config-provider.tsxindex 12d94ec4a..19d7af477 100644--- a/packages/app/src/lib/config-provider.tsx+++ b/packages/app/src/lib/config-provider.tsx@@ -38,11 +38,18 @@ import {type OkignoreBinding,type WriteScope,} from '@inkeep/open-knowledge-core';+import { useTheme } from 'next-themes';import { type ReactNode, useEffect, useState } from 'react';import * as Y from 'yjs';import { useThemeBridge } from '@/hooks/use-theme-bridge';import { buildAuthToken } from './auth-token';-import { colorThemeMode, customThemeKind, resolveCustomScheme } from './color-themes';+import {+ colorThemeMode,+ customThemeKind,+ resolveColorThemeSelection,+ resolveCustomScheme,+ resolveModePreference,+} from './color-themes';import { ConfigContext, type ConfigContextValue } from './config-context';import { useServerInstanceId } from './server-instance-store';import { useApplyConfigColorTheme } from './use-apply-config-color-theme';@@ -155,6 +162,13 @@ export function ConfigProvider({// (which owns `__system__`) co-mounts with this provider at the App level, so// the epoch-delivery channel stays alive as long as these providers do.const serverInstanceId = useServerInstanceId();+ // The OS appearance, tracked live and independently of the active theme —+ // next-themes keeps `systemTheme` current from its own media-query listener+ // even while `theme` is forced to a palette's variant, which is exactly the+ // signal `appearance.theme: 'system'` needs to choose a palette slot.+ // Provider-less harnesses get `undefined`, i.e. light.+ const { systemTheme } = useTheme();+ const systemPrefersDark = systemTheme === 'dark';const [userState, setUserState] = useState<{binding: ConfigBinding;config: Config;@@ -278,34 +292,45 @@ export function ConfigProvider({: null;const themeValue = merged?.appearance?.theme;- const colorThemeValue = merged?.appearance?.colorTheme;const customSeed = merged?.appearance?.customTheme;// The Themes plugin toggle. Disabled means the effect stops: the default- // palette applies and the saved `colorTheme` is ignored (not cleared — it- // comes back when the plugin is re-enabled). Default on (absent → enabled).+ // palette applies and the saved pair is ignored (not cleared — it comes back+ // when the plugin is re-enabled). Default on (absent → enabled).const colorThemeEnabled = merged?.appearance?.colorThemeEnabled !== false;- // A non-`default` palette takes over the appearance: it forces next-themes- // into its own light/dark mode so Tailwind `dark:` variants resolve against- // the themed tokens. Most IDE palettes are dark (Dracula, Catppuccin Frappé,- // …); a light palette (Catppuccin Latte) forces light. `custom` derives its- // mode from the seed background's luminance. `default` (and a disabled Themes- // plugin) defers to the user's light/dark/system `appearance.theme`. We never- // patch `appearance.theme` here — switching back to `default` restores the- // saved mode from config.- const effectiveMode = !colorThemeEnabled- ? themeValue- : colorThemeValue === 'custom'+ // One palette per mode. `slotMode` picks between them and is derived from the+ // user's OWN preference — `appearance.theme`, with the OS deciding for+ // 'system' — never from next-themes' resolved value. That distinction is+ // load-bearing: a palette still forces its own variant below, so feeding the+ // resolved value back in would let a cross-variant pick (a dark scheme chosen+ // as the light palette) flip the app into the other slot, then back.+ const selection = resolveColorThemeSelection(merged?.appearance);+ const slotMode = resolveModePreference(themeValue, systemPrefersDark);+ const activePalette = colorThemeEnabled ? selection[slotMode] : 'default';+ // The applied palette takes over the appearance: it forces next-themes into+ // its own light/dark mode so Tailwind `dark:` variants resolve against the+ // themed tokens. `custom` derives its mode from its scheme's variant.+ // `default` (and a disabled Themes plugin) carries no palette, so the mode+ // preference passes through untouched — including 'system', which is what+ // keeps the palette following the OS. We never patch `appearance.theme` here.+ const effectiveMode =+ activePalette === 'custom'? customThemeKind(resolveCustomScheme(customSeed))- : (colorThemeMode(colorThemeValue) ?? themeValue);+ : (colorThemeMode(activePalette) ?? themeValue);// Bridge the effective mode from the merged config into next-themes app-wide.// The hook owns the dependency discipline that prevents a cross-window// light/dark flicker storm across open project windows — see// `useApplyConfigTheme`.useApplyConfigTheme(effectiveMode);- // Apply the palette overlay (`data-color-theme` attribute + FOUC cache; for- // `custom`, the runtime `<style>` built from the seed). Honors the plugin+ // Apply the palette overlay (`data-color-theme` attribute + FOUC caches; for+ // `custom`, the runtime `<style>` built from the scheme). Honors the plugin// toggle: disabled clears the overlay and its FOUC caches.- useApplyConfigColorTheme(colorThemeValue, customSeed, colorThemeEnabled);+ useApplyConfigColorTheme({+ selection,+ modePreference: themeValue,+ slotMode,+ customSeed,+ enabled: colorThemeEnabled,+ });// Push `appearance.theme` to Electron main's `nativeTheme.themeSource`// and signal the cold-launch show-gate via the shared `useThemeBridge`@@ -332,9 +357,7 @@ export function ConfigProvider({useThemeBridge(typeof window !== 'undefined' ? window.okDesktop : undefined,effectiveMode ?? 'system',- `${colorThemeEnabled ? colorThemeValue : 'default'}:${- colorThemeValue === 'custom' ? JSON.stringify(customSeed ?? null) : ''- }`,+ `${activePalette}:${activePalette === 'custom' ? JSON.stringify(customSeed ?? null) : ''}`,);const value: ConfigContextValue = {diff --git a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx b/packages/app/src/lib/config-provider.user-synced.dom.test.tsxindex 5c813781c..f0ff96897 100644--- a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx+++ b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx@@ -191,6 +191,12 @@ vi.doMock('@inkeep/open-knowledge-core', () => ({// re-exports fail to resolve (a hard named-import error for `colorThemeMode`,// which SettingsDialogBody imports statically).colorThemeMode: (id?: string) => (id && id !== 'default' && id !== 'custom' ? 'dark' : undefined),+ resolveColorThemeSelection: (appearance?: { colorTheme?: string }) => ({+ light: appearance?.colorTheme ?? 'default',+ dark: appearance?.colorTheme ?? 'default',+ }),+ resolveModePreference: (preference?: string, prefersDark?: boolean) =>+ preference === 'light' || preference === 'dark' ? preference : prefersDark ? 'dark' : 'light',expandPalette: () => ({}),generateColorThemesCss: () => '',isDarkTheme: (id?: string) => Boolean(id) && id !== 'default' && id !== 'custom',diff --git a/packages/app/src/lib/fouc-prepaint.dom.test.ts b/packages/app/src/lib/fouc-prepaint.dom.test.tsnew file mode 100644index 000000000..814835657--- /dev/null+++ b/packages/app/src/lib/fouc-prepaint.dom.test.ts@@ -0,0 +1,194 @@+/**+ * Executes the real pre-paint FOUC script out of `index.html` against seeded+ * localStorage, and asserts the `<html>` state it produces.+ *+ * This is the only coverage of that path. The script cannot import anything —+ * it runs before any bundle — so it reads the cache's field names (`pref`,+ * `light`/`dark`, `.id`, `.dark`) as string literals with no compile-time link+ * to the writer in `use-apply-config-color-theme.ts`. Renaming a field there+ * updates every TypeScript consumer while this script silently reads+ * `undefined` and paints the wrong mode on every reload, with nothing else in+ * the suite going red. Feeding real writer output through the real script is+ * what couples the two.+ */++import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { beforeAll, beforeEach, describe, expect, test } from 'vitest';+import type { ColorThemeSelection } from './color-themes';+import {+ applyColorThemeToDom,+ COLOR_THEME_PAIR_STORAGE_KEY,+ COLOR_THEME_STORAGE_KEY,+ CUSTOM_THEME_STORAGE_KEY,+ CUSTOM_THEME_STYLE_ID,+} from './use-apply-config-color-theme';++const here = dirname(fileURLToPath(import.meta.url));++/**+ * The theme pre-paint script, lifted verbatim from `index.html`. Identified by+ * the cache key it reads rather than by position, so an added `<script>` can't+ * silently shift which one is under test.+ */+function prePaintScript(): string {+ const html = readFileSync(resolve(here, '../../index.html'), 'utf8');+ const body = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]+ .map((m) => m[1])+ .find((s) => s.includes(COLOR_THEME_PAIR_STORAGE_KEY));+ if (!body) throw new Error('pre-paint theme script not found in index.html');+ return body;+}++let script: string;++beforeAll(() => {+ if (typeof localStorage === 'undefined') {+ (globalThis as { localStorage?: Storage }).localStorage = window.localStorage;+ }+ script = prePaintScript();+});++/** Run the pre-paint script against the current DOM + localStorage. */+function runPrePaint(prefersDark: boolean): void {+ window.matchMedia = ((query: string) =>+ ({+ matches: prefersDark && query.includes('dark'),+ media: query,+ addEventListener() {},+ removeEventListener() {},+ addListener() {},+ removeListener() {},+ onchange: null,+ dispatchEvent: () => false,+ }) as unknown as MediaQueryList) as typeof window.matchMedia;+ new Function(script)();+}++function reset(): void {+ document.documentElement.className = '';+ document.documentElement.removeAttribute('data-color-theme');+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+ localStorage.clear();+}++/** Seed the caches exactly as the app writes them — no hand-built JSON. */+function seed(+ selection: ColorThemeSelection,+ modePreference: 'light' | 'dark' | 'system',+ slotMode: 'light' | 'dark',+ customSeed?: Record<string, unknown>,+): void {+ applyColorThemeToDom({ selection, modePreference, slotMode, customSeed });+ // Only the caches survive a reload; the live DOM does not.+ document.documentElement.className = '';+ document.documentElement.removeAttribute('data-color-theme');+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+}++const state = () => ({+ attr: document.documentElement.getAttribute('data-color-theme'),+ dark: document.documentElement.classList.contains('dark'),+});++describe('pre-paint FOUC script', () => {+ beforeEach(reset);++ test('reads the writer’s own cache — the field-name contract holds end to end', () => {+ seed({ light: 'catppuccin-latte', dark: 'dracula' }, 'system', 'dark');+ runPrePaint(true);+ expect(state()).toEqual({ attr: 'dracula', dark: true });+ });++ test('follows the OS for a system preference, picking the other slot', () => {+ seed({ light: 'catppuccin-latte', dark: 'dracula' }, 'system', 'dark');+ runPrePaint(false);+ // The cache was written while dark was on screen, but the OS is light now:+ // the light slot must win, which is the whole point of caching both.+ expect(state()).toEqual({ attr: 'catppuccin-latte', dark: false });+ });++ test('an explicit preference ignores the OS', () => {+ seed({ light: 'catppuccin-latte', dark: 'dracula' }, 'light', 'light');+ runPrePaint(true);+ expect(state()).toEqual({ attr: 'catppuccin-latte', dark: false });+ });++ test('a cross-variant palette paints its own variant, not the slot’s', () => {+ // Dracula assigned to the light slot still forces dark, so `dark:` variants+ // resolve against the tokens actually on screen.+ seed({ light: 'dracula', dark: 'dracula' }, 'light', 'light');+ runPrePaint(false);+ expect(state()).toEqual({ attr: 'dracula', dark: true });+ });++ test('a default slot sets no attribute and takes the slot’s own mode', () => {+ seed({ light: 'default', dark: 'dracula' }, 'system', 'dark');+ runPrePaint(false);+ expect(state()).toEqual({ attr: null, dark: false });+ });++ test('replays the custom stylesheet and its variant', () => {+ seed({ light: 'catppuccin-latte', dark: 'custom' }, 'dark', 'dark', {+ base00: '#0a0a0a',+ base05: '#eeeeee',+ });+ runPrePaint(true);+ expect(state()).toEqual({ attr: 'custom', dark: true });+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)?.textContent).toContain(+ '--background: #0a0a0a;',+ );+ });++ test('falls back to the pre-pair single-palette cache exactly once', () => {+ // Written by a build that predates the pair; `ok-theme-v1` already carried+ // the mode that palette forced.+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, 'monokai');+ localStorage.setItem('ok-theme-v1', 'dark');+ runPrePaint(false);+ expect(state()).toEqual({ attr: 'monokai', dark: true });+ });++ test('legacy fallback with no mode cache leaves the dark class to the OS', () => {+ // Pins a bounded limitation rather than a desirable behavior: the legacy+ // branch has no palette-to-variant table (removing it is the point), so it+ // leans on `ok-theme-v1` carrying the mode the old build's palette forced.+ // With that key gone, a dark palette on a light OS paints dark tokens+ // without the dark class. It survives one pre-paint at most, because the+ // app rewrites the pair cache on mount.+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, 'monokai');+ runPrePaint(false);+ expect(state()).toEqual({ attr: 'monokai', dark: false });+ });++ test('a custom slot with no CSS cache applies no palette at all', () => {+ // Storage eviction can drop the stylesheet while the pair survives.+ // Setting `data-color-theme="custom"` with no matching rule would paint an+ // unstyled frame, so the script drops the palette instead.+ seed({ light: 'default', dark: 'custom' }, 'dark', 'dark', { base00: '#0a0a0a' });+ localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);+ runPrePaint(true);+ expect(state()).toEqual({ attr: null, dark: true });+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();+ });++ test('the pair wins over a stale pre-pair key', () => {+ seed({ light: 'catppuccin-latte', dark: 'dracula' }, 'light', 'light');+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, 'monokai');+ runPrePaint(false);+ expect(state()).toEqual({ attr: 'catppuccin-latte', dark: false });+ });++ test('no cache at all paints the base theme in the OS mode', () => {+ runPrePaint(true);+ expect(state()).toEqual({ attr: null, dark: true });+ });++ test('survives corrupt cache JSON without throwing or painting a palette', () => {+ localStorage.setItem(COLOR_THEME_PAIR_STORAGE_KEY, '{not json');+ localStorage.setItem(CUSTOM_THEME_STORAGE_KEY, '{also not json');+ expect(() => runPrePaint(false)).not.toThrow();+ expect(state()).toEqual({ attr: null, dark: false });+ });+});diff --git a/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsxindex 626bedf04..07790b5a1 100644--- a/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx+++ b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx@@ -1,8 +1,11 @@import { cleanup, render } from '@testing-library/react';import { afterEach, beforeAll, describe, expect, test } from 'vitest';+import type { ColorThemeSelection } from './color-themes';import {+ type ApplyColorThemeInput,applyColorThemeToDom,COLOR_THEME_ATTRIBUTE,+ COLOR_THEME_PAIR_STORAGE_KEY,COLOR_THEME_STORAGE_KEY,CUSTOM_THEME_STORAGE_KEY,CUSTOM_THEME_STYLE_ID,@@ -18,41 +21,125 @@ beforeAll(() => {}});-function Harness({ colorTheme, enabled }: { colorTheme: string | undefined; enabled?: boolean }) {- useApplyConfigColorTheme(colorTheme, undefined, enabled ?? true);+/** A selection with the same palette in both slots — the pre-pair shape. */+function both(id: ColorThemeSelection['light']): ColorThemeSelection {+ return { light: id, dark: id };+}++function apply(input: Partial<ApplyColorThemeInput> & { selection: ColorThemeSelection }): void {+ applyColorThemeToDom({ modePreference: 'dark', slotMode: 'dark', ...input });+}++function readSelectionCache(): {+ pref?: string;+ light?: { id: string; dark: boolean };+ dark?: { id: string; dark: boolean };+} {+ return JSON.parse(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY) ?? '{}');+}++function Harness({+ selection,+ slotMode = 'dark',+ enabled,+}: {+ selection: ColorThemeSelection;+ slotMode?: 'light' | 'dark';+ enabled?: boolean;+}) {+ useApplyConfigColorTheme({+ selection,+ modePreference: slotMode,+ slotMode,+ enabled: enabled ?? true,+ });return null;}function CustomHarness({ enabled }: { enabled: boolean }) {- useApplyConfigColorTheme('custom', { background: '#101014' }, enabled);+ useApplyConfigColorTheme({+ selection: both('custom'),+ modePreference: 'dark',+ slotMode: 'dark',+ customSeed: { background: '#101014' },+ enabled,+ });return null;}+function resetDom(): void {+ document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);+ document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();+ try {+ localStorage.removeItem(COLOR_THEME_PAIR_STORAGE_KEY);+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);+ } catch {}+}+describe('useApplyConfigColorTheme', () => {afterEach(() => {cleanup();- document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);- try {- localStorage.removeItem(COLOR_THEME_STORAGE_KEY);- } catch {}+ resetDom();});- test('sets the attribute + FOUC cache for an IDE theme', () => {- render(<Harness colorTheme="dracula" />);+ test('applies the palette assigned to the mode on screen', () => {+ render(<Harness selection={{ light: 'catppuccin-latte', dark: 'dracula' }} slotMode="dark" />);expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBe('dracula');});- test('clears the attribute + cache when switched back to default', () => {- const { rerender } = render(<Harness colorTheme="catppuccin-frappe" />);+ test('an OS-driven mode flip swaps the palette with no config change', () => {+ const selection: ColorThemeSelection = { light: 'catppuccin-latte', dark: 'dracula' };+ const { rerender } = render(<Harness selection={selection} slotMode="dark" />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');+ rerender(<Harness selection={selection} slotMode="light" />);+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('catppuccin-latte');+ });++ test('caches BOTH slots, so a reload landing in the other mode still pre-paints', () => {+ render(<Harness selection={{ light: 'catppuccin-latte', dark: 'dracula' }} slotMode="dark" />);+ const cached = readSelectionCache();+ expect(cached.light).toEqual({ id: 'catppuccin-latte', dark: false });+ expect(cached.dark).toEqual({ id: 'dracula', dark: true });+ });++ test("caches the mode preference, not next-themes' possibly-forced value", () => {+ // A palette forces its own variant through `setTheme`, so `ok-theme-v1` can+ // read 'dark' while the user's preference is still 'system'. Picking a slot+ // from that would strand the app in one mode.+ render(+ <Harness+ selection={{ light: 'catppuccin-latte', dark: 'dracula' }}+ slotMode="dark"+ enabled+ />,+ );+ expect(readSelectionCache().pref).toBe('dark');+ });++ test('clears the attribute + cache when both slots are back to default', () => {+ const { rerender } = render(<Harness selection={both('catppuccin-frappe')} />);expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('catppuccin-frappe');- rerender(<Harness colorTheme="default" />);+ rerender(<Harness selection={both('default')} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY)).toBeNull();+ });++ test('keeps the cache when only the OTHER slot carries a palette', () => {+ render(<Harness selection={{ light: 'default', dark: 'dracula' }} slotMode="light" />);+ expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);+ expect(readSelectionCache().dark).toEqual({ id: 'dracula', dark: true });+ });++ test('a dark palette assigned to light mode still paints dark', () => {+ // Any palette may sit in either slot; it keeps forcing its own variant so+ // Tailwind `dark:` variants resolve against the tokens actually on screen.+ render(<Harness selection={{ light: 'dracula', dark: 'dracula' }} slotMode="light" />);+ expect(readSelectionCache().light).toEqual({ id: 'dracula', dark: true });});test('treats an unknown id as default (clears the overlay)', () => {- render(<Harness colorTheme="not-a-real-theme" />);+ render(<Harness selection={both('not-a-real-theme' as ColorThemeSelection['light'])} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);});});@@ -60,29 +147,24 @@ describe('useApplyConfigColorTheme', () => {describe('useApplyConfigColorTheme — Themes plugin disabled', () => {afterEach(() => {cleanup();- document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);- document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();- try {- localStorage.removeItem(COLOR_THEME_STORAGE_KEY);- localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);- } catch {}+ resetDom();});test('disabling reverts an active named palette to the default', () => {- const { rerender } = render(<Harness colorTheme="catppuccin-frappe" enabled />);+ const { rerender } = render(<Harness selection={both('catppuccin-frappe')} enabled />);expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('catppuccin-frappe');- rerender(<Harness colorTheme="catppuccin-frappe" enabled={false} />);+ rerender(<Harness selection={both('catppuccin-frappe')} enabled={false} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);// The FOUC mirror carries the disabled state — a reload's pre-paint script// finds no cached palette, so it cannot flash the palette back.- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY)).toBeNull();});test('mounting disabled never applies the saved palette', () => {- render(<Harness colorTheme="dracula" enabled={false} />);+ render(<Harness selection={both('dracula')} enabled={false} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY)).toBeNull();});test('disabling removes the custom <style> and both FOUC mirror entries', () => {@@ -93,48 +175,57 @@ describe('useApplyConfigColorTheme — Themes plugin disabled', () => {rerender(<CustomHarness enabled={false} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ expect(localStorage.getItem(COLOR_THEME_PAIR_STORAGE_KEY)).toBeNull();expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).toBeNull();});test('re-enabling brings the saved palette back', () => {- const { rerender } = render(<Harness colorTheme="dracula" enabled={false} />);+ const { rerender } = render(<Harness selection={both('dracula')} enabled={false} />);expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);- rerender(<Harness colorTheme="dracula" enabled />);+ rerender(<Harness selection={both('dracula')} enabled />);expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');- expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBe('dracula');+ expect(readSelectionCache().dark).toEqual({ id: 'dracula', dark: true });});});describe('applyColorThemeToDom', () => {- afterEach(() => {- document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);- try {- localStorage.removeItem(COLOR_THEME_STORAGE_KEY);- } catch {}- });+ afterEach(resetDom);- test('is idempotent and clears on undefined', () => {- applyColorThemeToDom('gruvbox');+ test('is idempotent and clears when the slot holds default', () => {+ apply({ selection: both('gruvbox') });expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('gruvbox');- applyColorThemeToDom(undefined);+ apply({ selection: both('default') });expect(document.documentElement.hasAttribute(COLOR_THEME_ATTRIBUTE)).toBe(false);});++ test('retires the pre-pair single-palette cache', () => {+ // Left behind, it would shadow a reset back to `default` on the next+ // pre-paint — the fallback branch only runs when the pair is absent.+ localStorage.setItem(COLOR_THEME_STORAGE_KEY, 'monokai');+ apply({ selection: both('gruvbox') });+ expect(localStorage.getItem(COLOR_THEME_STORAGE_KEY)).toBeNull();+ });++ test('a default slot caches the mode it resolves to, so pre-paint needs no palette table', () => {+ // `default` carries no palette, so its cached flag is just the slot's own+ // mode — which is what lets the pre-paint script set the `dark` class+ // without knowing a single theme id.+ apply({ selection: { light: 'default', dark: 'dracula' } });+ expect(readSelectionCache().light).toEqual({ id: 'default', dark: false });+ apply({ selection: { light: 'dracula', dark: 'default' } });+ expect(readSelectionCache().dark).toEqual({ id: 'default', dark: true });+ });});describe('applyColorThemeToDom — custom palette', () => {- afterEach(() => {- document.documentElement.removeAttribute(COLOR_THEME_ATTRIBUTE);- document.getElementById(CUSTOM_THEME_STYLE_ID)?.remove();- try {- localStorage.removeItem(COLOR_THEME_STORAGE_KEY);- localStorage.removeItem(CUSTOM_THEME_STORAGE_KEY);- } catch {}- });+ afterEach(resetDom);- test('injects a <style> built from the seed and caches it for FOUC', () => {- applyColorThemeToDom('custom', { background: '#0a0a0a', primary: '#abcdef' });+ test('injects a <style> built from the scheme and caches it for FOUC', () => {+ apply({+ selection: both('custom'),+ customSeed: { background: '#0a0a0a', primary: '#abcdef' },+ });expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('custom');const style = document.getElementById(CUSTOM_THEME_STYLE_ID);@@ -148,17 +239,33 @@ describe('applyColorThemeToDom — custom palette', () => {expect(cached.dark).toBe(true);});- test('switching away from custom removes the <style> and the cache', () => {- applyColorThemeToDom('custom', { background: '#0a0a0a' });+ test('caches the custom CSS while custom sits in the OTHER slot, without injecting it', () => {+ // The OS can flip while the app is closed, so the reload that lands in the+ // custom slot has to be able to replay the stylesheet pre-paint.+ apply({+ selection: { light: 'custom', dark: 'dracula' },+ slotMode: 'dark',+ customSeed: { background: '#0a0a0a' },+ });+ expect(document.documentElement.getAttribute(COLOR_THEME_ATTRIBUTE)).toBe('dracula');+ expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();+ expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).not.toBeNull();+ });++ test('dropping custom from both slots removes the <style> and the cache', () => {+ apply({ selection: both('custom'), customSeed: { background: '#0a0a0a' } });expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).not.toBeNull();- applyColorThemeToDom('dracula');+ apply({ selection: both('dracula') });expect(document.getElementById(CUSTOM_THEME_STYLE_ID)).toBeNull();expect(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY)).toBeNull();});test('a light background yields a light color-scheme + dark:false cache', () => {- applyColorThemeToDom('custom', { background: '#fafafa', foreground: '#111111' });+ apply({+ selection: both('custom'),+ customSeed: { background: '#fafafa', foreground: '#111111' },+ });const style = document.getElementById(CUSTOM_THEME_STYLE_ID);expect(style?.textContent).toContain('color-scheme: light;');const cached = JSON.parse(localStorage.getItem(CUSTOM_THEME_STORAGE_KEY) ?? '{}');diff --git a/packages/app/src/lib/use-apply-config-color-theme.ts b/packages/app/src/lib/use-apply-config-color-theme.tsindex 30b3e8dba..c3393d62e 100644--- a/packages/app/src/lib/use-apply-config-color-theme.ts+++ b/packages/app/src/lib/use-apply-config-color-theme.ts@@ -1,12 +1,32 @@import { useEffect } from 'react';import {buildCustomThemeCss,+ type ColorThemeSelection,+ colorThemeMode,customThemeKind,resolveColorTheme,resolveCustomScheme,} from './color-themes';-/** localStorage key the FOUC script in `index.html` reads pre-paint. Keep both in sync. */+/**+ * localStorage key the FOUC script in `index.html` reads pre-paint: the light ++ * dark palette pair, each already resolved to the `dark`-class state it applies,+ * plus the mode preference that chooses between them. Keep both in sync.+ *+ * Named `...-pair-...` rather than a plural of the legacy `ok-color-theme-v1`:+ * the pre-paint script reads both keys a few statements apart, and a+ * one-character difference between two caches of different shapes is a+ * footgun.+ *+ * The pair carries its own copy of the mode preference rather than reusing+ * next-themes' `ok-theme-v1`: a palette forces its own variant, so `setTheme`+ * can leave `dark` in that key while the user's preference is still `system`.+ * Reading it to pick a slot would then lock the app to one slot after the first+ * cross-variant pick.+ */+export const COLOR_THEME_PAIR_STORAGE_KEY = 'ok-color-theme-pair-v1';++/** The single-palette FOUC cache written before the light/dark pair existed. */export const COLOR_THEME_STORAGE_KEY = 'ok-color-theme-v1';/** localStorage key holding the active custom theme's prebuilt CSS + kind, for flash-free reload. */@@ -20,6 +40,25 @@ export const CUSTOM_THEME_STYLE_ID = 'ok-custom-theme';type SeedInput = Record<string, unknown> | undefined;+/** One slot of the FOUC cache: which palette, and whether it paints dark. */+interface CachedSlot {+ id: string;+ dark: boolean;+}++export interface ApplyColorThemeInput {+ /** The light + dark palette pair from merged config. */+ selection: ColorThemeSelection;+ /** The user's `appearance.theme` preference. */+ modePreference: 'light' | 'dark' | 'system' | undefined;+ /** Which slot that preference resolves to right now (the OS decides for `'system'`). */+ slotMode: 'light' | 'dark';+ /** The user's custom-theme scheme (partial); only consulted for the `custom` palette. */+ customSeed?: SeedInput;+ /** The Themes plugin toggle. Off applies exactly like `default`. */+ enabled?: boolean;+}+function upsertCustomStyle(css: string): void {let style = document.getElementById(CUSTOM_THEME_STYLE_ID) as HTMLStyleElement | null;if (!style) {@@ -35,53 +74,86 @@ function removeCustomStyle(): void {}/**- * Apply a color theme to the DOM now: set (or clear, for `default`) the- * `data-color-theme` attribute on `<html>`, inject/remove the runtime custom- * palette `<style>`, and mirror everything into the localStorage caches the- * pre-paint FOUC script reads on the next reload. Idempotent. Shared by the- * config effect below and the Settings picker's optimistic on-click apply so- * both paths stay byte-identical.+ * The `dark`-class state a palette produces in a given slot. A palette carries+ * its own variant and keeps forcing it — a dark scheme picked as the light-mode+ * palette still paints dark, so Tailwind `dark:` variants resolve against the+ * tokens actually on screen. Only a palette-less `default` defers to the slot.+ */+function slotIsDark(id: string, slot: 'light' | 'dark', customSeed: SeedInput): boolean {+ if (id === 'custom') return customThemeKind(resolveCustomScheme(customSeed)) === 'dark';+ return (colorThemeMode(id) ?? slot) === 'dark';+}++/** Which palette applies right now, and whether it paints dark. */+function activeColorTheme(input: ApplyColorThemeInput): CachedSlot {+ const { selection, slotMode, customSeed, enabled = true } = input;+ const id = resolveColorTheme(enabled ? selection[slotMode] : 'default').id;+ return { id, dark: slotIsDark(id, slotMode, customSeed) };+}++/**+ * Apply the mode-selected color theme to the DOM now: set (or clear, for+ * `default`) the `data-color-theme` attribute on `<html>`, inject/remove the+ * runtime custom palette `<style>`, and mirror the whole pair into the+ * localStorage caches the pre-paint FOUC script reads on the next reload.+ * Idempotent. Shared by the config effect below and the Settings picker's+ * optimistic on-click apply so both paths stay byte-identical.*- * `customSeed` is only consulted for the `custom` theme; pass the merged-config- * `appearance.customTheme` (a partial seed — missing/invalid fields fall back- * to the default palette).+ * The cache holds BOTH slots, not just the active one, because the OS+ * appearance can change while the app is closed — the pre-paint script has to+ * be able to pick the other slot without loading a bundle.** `enabled: false` (the Themes plugin toggled off) applies exactly like- * `default`: the attribute clears, no custom `<style>` is injected, and BOTH- * FOUC caches are removed — the mirror is how pre-paint learns the disabled+ * `default`: the attribute clears, no custom `<style>` is injected, and every+ * FOUC cache is removed — the mirror is how pre-paint learns the disabled* state, so a reload can't flash the palette back.*/-export function applyColorThemeToDom(- colorThemeValue: string | undefined,- customSeed?: SeedInput,- enabled = true,-): void {+export function applyColorThemeToDom(input: ApplyColorThemeInput): void {if (typeof document === 'undefined') return;- const theme = resolveColorTheme(enabled ? colorThemeValue : 'default');+ const { selection, modePreference, customSeed, enabled = true } = input;+ const active = activeColorTheme(input);const root = document.documentElement;- if (theme.id === 'default') {+ if (active.id === 'default') {root.removeAttribute(COLOR_THEME_ATTRIBUTE);} else {- root.setAttribute(COLOR_THEME_ATTRIBUTE, theme.id);+ root.setAttribute(COLOR_THEME_ATTRIBUTE, active.id);}+ // The custom scheme's stylesheet is cached whenever `custom` sits in EITHER+ // slot, so a reload that lands in the other mode can still replay it; the+ // <style> itself is only injected while `custom` is the palette on screen.+ const customInSelection =+ enabled && (selection.light === 'custom' || selection.dark === 'custom');let customCacheEntry: string | null = null;- if (theme.id === 'custom') {+ if (customInSelection) {const scheme = resolveCustomScheme(customSeed);const css = buildCustomThemeCss(scheme);- upsertCustomStyle(css);customCacheEntry = JSON.stringify({ css, dark: customThemeKind(scheme) === 'dark' });+ if (active.id === 'custom') upsertCustomStyle(css);+ else removeCustomStyle();} else {removeCustomStyle();}+ const bothDefault = selection.light === 'default' && selection.dark === 'default';try {- if (theme.id === 'default') {- localStorage.removeItem(COLOR_THEME_STORAGE_KEY);+ if (!enabled || bothDefault) {+ localStorage.removeItem(COLOR_THEME_PAIR_STORAGE_KEY);} else {- localStorage.setItem(COLOR_THEME_STORAGE_KEY, theme.id);+ localStorage.setItem(+ COLOR_THEME_PAIR_STORAGE_KEY,+ JSON.stringify({+ pref: modePreference === 'light' || modePreference === 'dark' ? modePreference : 'system',+ light: { id: selection.light, dark: slotIsDark(selection.light, 'light', customSeed) },+ dark: { id: selection.dark, dark: slotIsDark(selection.dark, 'dark', customSeed) },+ }),+ );}+ // The pre-paint script falls back to the single-palette key only when the+ // pair is absent, so a stale one left by an older build would shadow a+ // deliberate reset back to `default`.+ localStorage.removeItem(COLOR_THEME_STORAGE_KEY);if (customCacheEntry) {localStorage.setItem(CUSTOM_THEME_STORAGE_KEY, customCacheEntry);} else {@@ -94,30 +166,32 @@ export function applyColorThemeToDom(}/**- * Bridge the merged-config `appearance.colorTheme` (+ `appearance.customTheme`- * seed) into the DOM app-wide.+ * Bridge the merged-config color-theme pair (+ the `appearance.customTheme`+ * scheme) into the DOM app-wide.*- * The dark/light *mode* that a palette forces is handled separately by- * `useApplyConfigTheme` (next-themes owns the `.dark` class) — this hook only- * toggles which palette overlay is active. `default` (and any unknown value)- * clears the attribute so the base `:root` / `.dark` theme shows through.+ * `slotMode` is what makes the pair live: it tracks `appearance.theme`, and for+ * `'system'` the OS preference, so an OS appearance change swaps the palette+ * without a config write. The `.dark` class itself is handled separately by+ * `useApplyConfigTheme` (next-themes owns it) — this hook only toggles which+ * palette overlay is active. `default` (and any unknown value) clears the+ * attribute so the base `:root` / `.dark` theme shows through.** Unlike the mode flip there is no cross-window storm risk here: nothing- * listens for the `ok-color-theme-v1` `storage` event, so a write doesn't- * re-enter this effect in other windows.+ * listens for the color-theme `storage` events, so a write doesn't re-enter+ * this effect in other windows.*/-export function useApplyConfigColorTheme(- colorThemeValue: string | undefined,- customSeed?: SeedInput,- enabled = true,-): void {- // Serialize the seed so the effect re-runs on a live color edit while the- // custom theme is active, without depending on object identity. `seedKey` is+export function useApplyConfigColorTheme(input: ApplyColorThemeInput): void {+ const { selection, modePreference, slotMode, customSeed, enabled = true } = input;+ // Serialize the scheme so the effect re-runs on a live color edit while the+ // custom theme is in play, without depending on object identity. `seedKey` is// the value-stable proxy for `customSeed`; depending on the object directly// would churn on every render, and biome can't see the proxy relationship.- const seedKey = enabled && colorThemeValue === 'custom' ? JSON.stringify(customSeed ?? null) : '';+ const seedKey =+ enabled && (selection.light === 'custom' || selection.dark === 'custom')+ ? JSON.stringify(customSeed ?? null)+ : '';// biome-ignore lint/correctness/useExhaustiveDependencies: seedKey is the value-stable proxy for customSeed (see above).useEffect(() => {- applyColorThemeToDom(colorThemeValue, customSeed, enabled);- }, [colorThemeValue, seedKey, enabled]);+ applyColorThemeToDom({ selection, modePreference, slotMode, customSeed, enabled });+ }, [selection.light, selection.dark, modePreference, slotMode, seedKey, enabled]);}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 19035ea3b..5403e2de2 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -146,7 +146,6 @@"1di5fu": ["Document not found"],"1hvhf0": ["The folder on disk and the id agents use to invoke this skill."],"1jym2J": ["Don't send this comment"],- "1njn7W": ["Light"],"1nke1r": ["Open ", ["0"], " on GitHub (opens in a new tab)"],"1oSHI0": ["Couldn't install ", ["skillName"], ": ", ["0"]],"1oawp3": [["failed"], " of ", ["0"], " comments could not be cleared."],@@ -261,6 +260,7 @@"3jod3l": ["Connect GitHub"],"3l32hp": ["Part of the ", ["plugin"], " plugin"],"3l_cXP": ["Take a look if you'd like. This exact file is what we receive."],+ "3l_knd": ["Press the sun or moon on “Custom” above to use this scheme."],"3m2GBo": ["Searching docs"],"3mFsc3": ["Restore with remote changes"],"3o3tur": ["Starter content"],@@ -1576,9 +1576,6 @@"PZn2LP": ["Keep source"],"PZtgO0": ["Opening worktree"],"P_bX4O": ["How to set up"],- "Pck6eI": [- "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."- ],"PdA9NZ": [["ahead"], " ahead"],"Pg83C9": ["Uploaded \"", ["0"], "\"."],"Pgu10b": ["Saved as <0>", ["slug"], ".md</0>"],@@ -1665,7 +1662,6 @@"A real shell is off for this project. Turning it on runs commands with the full access of your macOS user account."],"R9IDFz": ["Renames the folder on disk and the id agents use to invoke it."],- "R9Khdg": ["Auto"],"RDjuBN": ["Setup"],"RDrXh4": ["Configure user, project, and integration settings."],"RG4XHV": ["Copy ", ["0"], " prompt"],@@ -2643,7 +2639,6 @@"gyHDWC": ["Fix all with AI (", ["count"], ")"],"gyWc8_": ["Accents"],"h-AdvS": ["The folders and templates are already here, so there's nothing to add."],- "h-Y9pw": ["Pick “Custom” above to use this scheme."],"h06R3C": ["No pages are missing outgoing graph links."],"h16FyT": ["Lists"],"h2N-1n": ["Installed in ", ["0"]],@@ -2975,6 +2970,7 @@"lXKZGw": ["Heading 1"],"lY27jj": [["0"], "y ago"],"lZAiSP": ["Backlinks response did not match expected shape."],+ "lZvQrY": ["Use ", ["0"], " as the dark theme"],"l_FAT6": ["Use letters, digits, <0>-</0> or <1>_</1> only."],"l_UFPv": ["Properties"],"lb_UU4": ["Sync now"],@@ -3056,6 +3052,9 @@"mk2poV": ["e.g. server.ts"],"mlvM8g": ["Couldn't re-place that comment."],"mmpzAq": ["Wrap long lines in the markdown source editor."],+ "mnpsVn": [+ "Pick a palette for light mode and one for dark mode. The theme setting in Preferences chooses between them — on “System”, so does your OS."+ ],"mo22UP": ["Toggle inline code formatting."],"mqSwZH": ["<0>Mirror anchor not found.</0> No <1>",@@ -3246,7 +3245,6 @@"psfGPX": ["MCP connections"],"psl2Sj": ["Your change is still being saved — run the test again in a moment."],"ptQ3_N": ["unlink"],- "pvnfJD": ["Dark"],"pzutoc": ["Italic"],"q2cLM6": ["Stop fixing files"],"q2kXMG": ["Inline Math"],@@ -3416,6 +3414,7 @@" · crash dump not redacted"],"snrVQ7": ["probe failed"],+ "sq4WQH": ["Use ", ["0"], " as the light theme"],"sqUrlK": ["Musing…"],"ssk6rl": ["The skill's own folder (",diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex d2511491a..9047de1cd 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1528,10 +1528,6 @@ msgstr "Authoritative content; mirrored verbatim everywhere it's referenced."msgid "Authorize in browser"msgstr "Authorize in browser"-#: src/components/settings/ColorThemePicker.tsx-msgid "Auto"-msgstr "Auto"-#: src/components/settings/TerminalSection.tsxmsgid "Auto-approve settings not yet loaded — try again in a moment"msgstr "Auto-approve settings not yet loaded — try again in a moment"@@ -3488,10 +3484,6 @@ msgstr "Customize how the editor looks and behaves."msgid "Cut"msgstr "Cut"-#: src/components/settings/ColorThemePicker.tsx-msgid "Dark"-msgstr "Dark"-#: src/components/ExploreSkills.tsxmsgid "Data"msgstr "Data"@@ -6035,10 +6027,6 @@ msgstr "Let us follow up by email"msgid "Level"msgstr "Level"-#: src/components/settings/ColorThemePicker.tsx-msgid "Light"-msgstr "Light"-#: src/components/settings/settings-fields.tsmsgid "Light, dark, or follow the OS."msgstr "Light, dark, or follow the OS."@@ -7978,10 +7966,6 @@ msgstr "Personal access token"msgid "Personal to this device — stored in your user config, not shared."msgstr "Personal to this device — stored in your user config, not shared."-#: src/components/settings/CustomThemeEditor.tsx-msgid "Pick “Custom” above to use this scheme."-msgstr "Pick “Custom” above to use this scheme."-#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."msgstr "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."@@ -7990,10 +7974,6 @@ msgstr "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enmsgid "Pick a built-in IDE color palette, or define your own."msgstr "Pick a built-in IDE color palette, or define your own."-#: src/components/settings/settings-fields.ts-msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."-msgstr "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."-#: src/components/settings/SkillTargetsPicker.tsxmsgid "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."msgstr "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."@@ -8002,6 +7982,10 @@ msgstr "Pick a folder to merge INTO {display}. That folder becomes a symlink tomsgid "Pick a name"msgstr "Pick a name"+#: src/components/settings/settings-fields.ts+msgid "Pick a palette for light mode and one for dark mode. The theme setting in Preferences chooses between them — on “System”, so does your OS."+msgstr "Pick a palette for light mode and one for dark mode. The theme setting in Preferences chooses between them — on “System”, so does your OS."+#: src/editor/slash-command/items.tsxmsgid "Pick an emoji to insert at the cursor."msgstr "Pick an emoji to insert at the cursor."@@ -8085,6 +8069,10 @@ msgstr "Preparing share URL..."msgid "Preparing to uninstall OpenKnowledge"msgstr "Preparing to uninstall OpenKnowledge"+#: src/components/settings/CustomThemeEditor.tsx+msgid "Press the sun or moon on “Custom” above to use this scheme."+msgstr "Press the sun or moon on “Custom” above to use this scheme."+#: src/components/PublishToGitHubDialog.tsxmsgid "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."msgstr "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."@@ -11624,6 +11612,16 @@ msgstr "Uploading securely"msgid "Upstream sync"msgstr "Upstream sync"+#. placeholder {0}: theme.label+#: src/components/settings/ColorThemePicker.tsx+msgid "Use {0} as the dark theme"+msgstr "Use {0} as the dark theme"++#. placeholder {0}: theme.label+#: src/components/settings/ColorThemePicker.tsx+msgid "Use {0} as the light theme"+msgstr "Use {0} as the light theme"+#: src/components/SkillForkDialog.tsxmsgid "Use {editor} version"msgstr "Use {editor} version"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex d5dba07f6..18c34b868 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -146,7 +146,6 @@"1di5fu": ["Ďōćũḿēńţ ńōţ ƒōũńď"],"1hvhf0": ["Ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ţĥĩś śķĩĺĺ."],"1jym2J": ["Ďōń'ţ śēńď ţĥĩś ćōḿḿēńţ"],- "1njn7W": ["Ĺĩĝĥţ"],"1nke1r": ["Ōƥēń ", ["0"], " ōń ĜĩţĤũƀ (ōƥēńś ĩń à ńēŵ ţàƀ)"],"1oSHI0": ["Ćōũĺďń'ţ ĩńśţàĺĺ ", ["skillName"], ": ", ["0"]],"1oawp3": [["failed"], " ōƒ ", ["0"], " ćōḿḿēńţś ćōũĺď ńōţ ƀē ćĺēàŕēď."],@@ -261,6 +260,7 @@"3jod3l": ["Ćōńńēćţ ĜĩţĤũƀ"],"3l32hp": ["Ƥàŕţ ōƒ ţĥē ", ["plugin"], " ƥĺũĝĩń"],"3l_cXP": ["Ţàķē à ĺōōķ ĩƒ ŷōũ'ď ĺĩķē. Ţĥĩś ēxàćţ ƒĩĺē ĩś ŵĥàţ ŵē ŕēćēĩvē."],+ "3l_knd": ["Ƥŕēśś ţĥē śũń ōŕ ḿōōń ōń “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś śćĥēḿē."],"3m2GBo": ["Śēàŕćĥĩńĝ ďōćś"],"3mFsc3": ["Ŕēśţōŕē ŵĩţĥ ŕēḿōţē ćĥàńĝēś"],"3o3tur": ["Śţàŕţēŕ ćōńţēńţ"],@@ -1576,9 +1576,6 @@"PZn2LP": ["Ķēēƥ śōũŕćē"],"PZtgO0": ["Ōƥēńĩńĝ ŵōŕķţŕēē"],"P_bX4O": ["Ĥōŵ ţō śēţ ũƥ"],- "Pck6eI": [- "Ƥĩćķ à ƀũĩĺţ-ĩń ĨĎĒ ƥàĺēţţē. Ţĥē ďàŕķ ĨĎĒ ţĥēḿēś ōvēŕŕĩďē ţĥē ĺĩĝĥţ/ďàŕķ śēţţĩńĝ ĩń Ƥŕēƒēŕēńćēś."- ],"PdA9NZ": [["ahead"], " àĥēàď"],"Pg83C9": ["Ũƥĺōàďēď \"", ["0"], "\"."],"Pgu10b": ["Śàvēď àś <0>", ["slug"], ".ḿď</0>"],@@ -1665,7 +1662,6 @@"À ŕēàĺ śĥēĺĺ ĩś ōƒƒ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕńĩńĝ ĩţ ōń ŕũńś ćōḿḿàńďś ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ."],"R9IDFz": ["Ŕēńàḿēś ţĥē ƒōĺďēŕ ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ĩńvōķē ĩţ."],- "R9Khdg": ["Àũţō"],"RDjuBN": ["Śēţũƥ"],"RDrXh4": ["Ćōńƒĩĝũŕē ũśēŕ, ƥŕōĴēćţ, àńď ĩńţēĝŕàţĩōń śēţţĩńĝś."],"RG4XHV": ["Ćōƥŷ ", ["0"], " ƥŕōḿƥţ"],@@ -2643,7 +2639,6 @@"gyHDWC": ["Ƒĩx àĺĺ ŵĩţĥ ÀĨ (", ["count"], ")"],"gyWc8_": ["Àććēńţś"],"h-AdvS": ["Ţĥē ƒōĺďēŕś àńď ţēḿƥĺàţēś àŕē àĺŕēàďŷ ĥēŕē, śō ţĥēŕē'ś ńōţĥĩńĝ ţō àďď."],- "h-Y9pw": ["Ƥĩćķ “Ćũśţōḿ” àƀōvē ţō ũśē ţĥĩś śćĥēḿē."],"h06R3C": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ōũţĝōĩńĝ ĝŕàƥĥ ĺĩńķś."],"h16FyT": ["Ĺĩśţś"],"h2N-1n": ["Ĩńśţàĺĺēď ĩń ", ["0"]],@@ -2975,6 +2970,7 @@"lXKZGw": ["Ĥēàďĩńĝ 1"],"lY27jj": [["0"], "ŷ àĝō"],"lZAiSP": ["ßàćķĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],+ "lZvQrY": ["Ũśē ", ["0"], " àś ţĥē ďàŕķ ţĥēḿē"],"l_FAT6": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>-</0> ōŕ <1>_</1> ōńĺŷ."],"l_UFPv": ["Ƥŕōƥēŕţĩēś"],"lb_UU4": ["Śŷńć ńōŵ"],@@ -3056,6 +3052,9 @@"mk2poV": ["ē.ĝ. śēŕvēŕ.ţś"],"mlvM8g": ["Ćōũĺďń'ţ ŕē-ƥĺàćē ţĥàţ ćōḿḿēńţ."],"mmpzAq": ["Ŵŕàƥ ĺōńĝ ĺĩńēś ĩń ţĥē ḿàŕķďōŵń śōũŕćē ēďĩţōŕ."],+ "mnpsVn": [+ "Ƥĩćķ à ƥàĺēţţē ƒōŕ ĺĩĝĥţ ḿōďē àńď ōńē ƒōŕ ďàŕķ ḿōďē. Ţĥē ţĥēḿē śēţţĩńĝ ĩń Ƥŕēƒēŕēńćēś ćĥōōśēś ƀēţŵēēń ţĥēḿ — ōń “Śŷśţēḿ”, śō ďōēś ŷōũŕ ŌŚ."+ ],"mo22UP": ["Ţōĝĝĺē ĩńĺĩńē ćōďē ƒōŕḿàţţĩńĝ."],"mqSwZH": ["<0>Ḿĩŕŕōŕ àńćĥōŕ ńōţ ƒōũńď.</0> Ńō <1>",@@ -3246,7 +3245,6 @@"psfGPX": ["ḾĆƤ ćōńńēćţĩōńś"],"psl2Sj": ["Ŷōũŕ ćĥàńĝē ĩś śţĩĺĺ ƀēĩńĝ śàvēď — ŕũń ţĥē ţēśţ àĝàĩń ĩń à ḿōḿēńţ."],"ptQ3_N": ["ũńĺĩńķ"],- "pvnfJD": ["Ďàŕķ"],"pzutoc": ["Ĩţàĺĩć"],"q2cLM6": ["Śţōƥ ƒĩxĩńĝ ƒĩĺēś"],"q2kXMG": ["Ĩńĺĩńē Ḿàţĥ"],@@ -3416,6 +3414,7 @@" · ćŕàśĥ ďũḿƥ ńōţ ŕēďàćţēď"],"snrVQ7": ["ƥŕōƀē ƒàĩĺēď"],+ "sq4WQH": ["Ũśē ", ["0"], " àś ţĥē ĺĩĝĥţ ţĥēḿē"],"sqUrlK": ["Ḿũśĩńĝ…"],"ssk6rl": ["Ţĥē śķĩĺĺ'ś ōŵń ƒōĺďēŕ (",diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex cc041d3d7..a17692a6a 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1524,10 +1524,6 @@ msgstr ""msgid "Authorize in browser"msgstr ""-#: src/components/settings/ColorThemePicker.tsx-msgid "Auto"-msgstr ""-#: src/components/settings/TerminalSection.tsxmsgid "Auto-approve settings not yet loaded — try again in a moment"msgstr ""@@ -3484,10 +3480,6 @@ msgstr ""msgid "Cut"msgstr ""-#: src/components/settings/ColorThemePicker.tsx-msgid "Dark"-msgstr ""-#: src/components/ExploreSkills.tsxmsgid "Data"msgstr ""@@ -6031,10 +6023,6 @@ msgstr ""msgid "Level"msgstr ""-#: src/components/settings/ColorThemePicker.tsx-msgid "Light"-msgstr ""-#: src/components/settings/settings-fields.tsmsgid "Light, dark, or follow the OS."msgstr ""@@ -7974,10 +7962,6 @@ msgstr ""msgid "Personal to this device — stored in your user config, not shared."msgstr ""-#: src/components/settings/CustomThemeEditor.tsx-msgid "Pick “Custom” above to use this scheme."-msgstr ""-#: src/components/InstallInClaudeDesktopDialog.tsxmsgid "Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."msgstr ""@@ -7986,10 +7970,6 @@ msgstr ""msgid "Pick a built-in IDE color palette, or define your own."msgstr ""-#: src/components/settings/settings-fields.ts-msgid "Pick a built-in IDE palette. The dark IDE themes override the light/dark setting in Preferences."-msgstr ""-#: src/components/settings/SkillTargetsPicker.tsxmsgid "Pick a folder to merge INTO {display}. That folder becomes a symlink to this one, so its agent reads everything placed here. This folder stays real. Conflicting skills abort the merge."msgstr ""@@ -7998,6 +7978,10 @@ msgstr ""msgid "Pick a name"msgstr ""+#: src/components/settings/settings-fields.ts+msgid "Pick a palette for light mode and one for dark mode. The theme setting in Preferences chooses between them — on “System”, so does your OS."+msgstr ""+#: src/editor/slash-command/items.tsxmsgid "Pick an emoji to insert at the cursor."msgstr ""@@ -8081,6 +8065,10 @@ msgstr ""msgid "Preparing to uninstall OpenKnowledge"msgstr ""+#: src/components/settings/CustomThemeEditor.tsx+msgid "Press the sun or moon on “Custom” above to use this scheme."+msgstr ""+#: src/components/PublishToGitHubDialog.tsxmsgid "Preview browsers can't auto-copy. Use Cmd/Ctrl+C on the URL above, or open OK in the desktop app."msgstr ""@@ -11620,6 +11608,16 @@ msgstr ""msgid "Upstream sync"msgstr ""+#. placeholder {0}: theme.label+#: src/components/settings/ColorThemePicker.tsx+msgid "Use {0} as the dark theme"+msgstr ""++#. placeholder {0}: theme.label+#: src/components/settings/ColorThemePicker.tsx+msgid "Use {0} as the light theme"+msgstr ""+#: src/components/SkillForkDialog.tsxmsgid "Use {editor} version"msgstr ""diff --git a/packages/app/tests/stress/prd-7627-default-swatch.e2e.ts b/packages/app/tests/stress/prd-7627-default-swatch.e2e.tsindex c4dc3df81..d76d981da 100644--- a/packages/app/tests/stress/prd-7627-default-swatch.e2e.ts+++ b/packages/app/tests/stress/prd-7627-default-swatch.e2e.ts@@ -11,7 +11,7 @@* guard the structural half (no `var(--` in the tile).** The palette is applied by setting the attribute directly rather than by- * clicking a tile: `appearance.colorTheme` is USER-scoped config, and the dev+ * clicking a tile: the palette pair is USER-scoped config, and the dev* server resolves user scope against the real `~/.ok/global.yml`, so a click* here would rewrite the developer's own theme. Poking the attribute drives the* identical cascade with no write and no dependence on incoming config.@@ -31,12 +31,12 @@ test('the Default tile does not inherit the applied palette', async ({ page }) =const surfaceOf = (label: RegExp) =>page- .getByRole('radio', { name: label })- .locator('[aria-hidden]')+ .getByRole('group', { name: label })+ .locator('[data-theme-swatch]').first().evaluate((el) => getComputedStyle(el).backgroundColor);- await expect(page.getByRole('radio', { name: /Default/ })).toBeVisible({ timeout: 10_000 });+ await expect(page.getByRole('group', { name: /Default/ })).toBeVisible({ timeout: 10_000 });await page.evaluate(() => document.documentElement.setAttribute('data-color-theme', 'dracula'));// The palette really is cascading — the Dracula tile paints Dracula's canvas.diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.tsindex 9b330e743..ab85c9e3a 100644--- a/packages/core/src/config/field-registry.test.ts+++ b/packages/core/src/config/field-registry.test.ts@@ -143,7 +143,7 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'expect(allowlisted).toEqual([]);});- test('user-strict fields cover agents.autoApproveOkTools + appearance.{colorTheme,colorThemeEnabled,customTheme.*,preview.autoOpen,theme} + editor.{previewTabs,wordWrap}', () => {+ test('user-strict fields cover agents.autoApproveOkTools + appearance.{colorTheme*,customTheme.*,preview.autoOpen,theme} + editor.{previewTabs,wordWrap}', () => {const leaves: { path: string[]; schema: unknown }[] = [];walkLeaves(ConfigSchema, [], leaves);const userStrict = leaves@@ -152,8 +152,12 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'.sort();expect(userStrict).toEqual(['agents.autoApproveOkTools',+ // One palette per light/dark mode, plus the single pre-pair palette they+ // superseded — still read as the seed for both slots on an older config.'appearance.colorTheme',+ 'appearance.colorThemeDark','appearance.colorThemeEnabled',+ 'appearance.colorThemeLight',// The custom theme is a base16 scheme: sixteen palette slots plus the// three metadata fields an imported scheme carries.'appearance.customTheme.author',diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 1afcf7a0f..09339d2cf 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -31,8 +31,8 @@ function base16SlotFields() {/*** The self-contained palettes, quoted for prose — every theme id except the two* that defer to something else (`default` → the light/dark mode, `custom` → the- * user's own scheme). Derived so the `colorTheme` description can't fall out of- * step with the registry the enum itself comes from.+ * user's own scheme). Derived so the palette-field descriptions can't fall+ * out of step with the registry the enums themselves come from.*/function namedThemeIds() {return THEME_PLUGIN_IDS.filter((id) => id !== 'default' && id !== 'custom')@@ -248,20 +248,46 @@ export const ConfigSchema = z.looseObject({}).optional(),// The IDE color palette layered on top of the light/dark `theme` mode- // above. `default` defers entirely to `theme`; the named palettes- // (Dracula, Catppuccin Frappé, Catppuccin Latte, …) are self-contained- // themes that force their own light/dark mode; `custom` applies the- // user's own `appearance.customTheme` seed below. A personal preference- // (user scope). The id list is DERIVED from the `THEME_PLUGINS` registry+ // above. There is one palette per mode: `colorThemeLight` applies while+ // the resolved mode is light, `colorThemeDark` while it is dark, so the+ // palette follows the OS as `theme: 'system'` flips. `default` carries no+ // palette (the base stylesheet shows through); `custom` applies the user's+ // own `appearance.customTheme` scheme below. Any palette may sit in either+ // slot — a dark scheme chosen as the light-mode palette still forces its+ // own variant, so the app renders it dark. Personal preferences (user+ // scope). The id list is DERIVED from the `THEME_PLUGINS` registry// (`packages/core/src/theme/theme-plugins.ts`) via `THEME_PLUGIN_IDS` — add- // a theme there and this enum follows, with no edit here.+ // a theme there and these enums follow, with no edit here.+ colorThemeLight: z+ .enum(THEME_PLUGIN_IDS)+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description: `IDE color palette applied in light mode: 'default' (no palette), 'custom' (your own colors from appearance.customTheme), or one of ${namedThemeIds()}. A personal preference (user scope) — not shared with the project.`,+ })+ .optional(),+ colorThemeDark: z+ .enum(THEME_PLUGIN_IDS)+ .register(fieldRegistry, {+ scope: 'user',+ agentSettable: false,+ defaultScope: 'user',+ description: `IDE color palette applied in dark mode: 'default' (no palette), 'custom' (your own colors from appearance.customTheme), or one of ${namedThemeIds()}. A personal preference (user scope) — not shared with the project.`,+ })+ .optional(),+ // The single palette written before the light/dark pair existed. Read only+ // as the seed for BOTH slots when neither is set, so an older config keeps+ // rendering what it always did; the first pick in the Themes pane writes+ // the pair and retires this key.colorTheme: z.enum(THEME_PLUGIN_IDS).register(fieldRegistry, {scope: 'user',agentSettable: false,defaultScope: 'user',- description: `IDE color palette: 'default' (follows the light/dark theme), 'custom' (your own colors from appearance.customTheme), or one of ${namedThemeIds()}. A personal preference (user scope) — not shared with the project.`,+ description:+ 'Superseded by appearance.colorThemeLight / appearance.colorThemeDark. Read as the palette for both modes while neither of those is set. A personal preference (user scope) — not shared with the project.',}).optional(),// Whether the Themes plugin appears under Settings → Plugins. The theme isdiff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex b49d023bf..1c18b39b0 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1289,12 +1289,19 @@ export {parseBase16Scheme,relativeLuminance,} from './theme/base16.ts';-export type { ThemePlugin, ThemePluginId } from './theme/theme-plugins.ts';+export type {+ ColorThemeSelection,+ ColorThemeSelectionInput,+ ThemePlugin,+ ThemePluginId,+} from './theme/theme-plugins.ts';export {colorThemeMode,generateColorThemesCss,isDarkTheme,renderThemeBlock,+ resolveColorThemeSelection,+ resolveModePreference,resolveThemePlugin,THEME_PLUGIN_IDS,THEME_PLUGINS,diff --git a/packages/core/src/theme/theme-plugins.test.ts b/packages/core/src/theme/theme-plugins.test.tsindex c98a29efd..19d733813 100644--- a/packages/core/src/theme/theme-plugins.test.ts+++ b/packages/core/src/theme/theme-plugins.test.ts@@ -5,6 +5,8 @@ import {generateColorThemesCss,isDarkTheme,renderThemeBlock,+ resolveColorThemeSelection,+ resolveModePreference,resolveThemePlugin,THEME_PLUGIN_IDS,THEME_PLUGINS,@@ -109,3 +111,60 @@ describe('token mapping + generateColorThemesCss', () => {}});});++describe('resolveColorThemeSelection', () => {+ test('reads the light/dark pair when set', () => {+ expect(+ resolveColorThemeSelection({+ colorThemeLight: 'catppuccin-latte',+ colorThemeDark: 'dracula',+ }),+ ).toEqual({ light: 'catppuccin-latte', dark: 'dracula' });+ });++ test('a legacy single palette seeds both slots, so the pre-pair config renders unchanged', () => {+ expect(resolveColorThemeSelection({ colorTheme: 'dracula' })).toEqual({+ light: 'dracula',+ dark: 'dracula',+ });+ });++ test('a half-written pair falls back to the legacy palette per slot, not to default', () => {+ expect(+ resolveColorThemeSelection({ colorTheme: 'monokai', colorThemeDark: 'gruvbox' }),+ ).toEqual({ light: 'monokai', dark: 'gruvbox' });+ });++ test('an empty or unknown selection resolves to default in both slots', () => {+ expect(resolveColorThemeSelection(undefined)).toEqual({ light: 'default', dark: 'default' });+ expect(resolveColorThemeSelection({})).toEqual({ light: 'default', dark: 'default' });+ expect(+ resolveColorThemeSelection({ colorTheme: 'nope', colorThemeLight: 'also-nope' }),+ ).toEqual({ light: 'default', dark: 'default' });+ });++ test('any palette is admissible in either slot', () => {+ // A dark scheme as the light-mode palette is a supported choice — the+ // picker offers both icons on every tile.+ expect(+ resolveColorThemeSelection({+ colorThemeLight: 'dracula',+ colorThemeDark: 'catppuccin-latte',+ }),+ ).toEqual({ light: 'dracula', dark: 'catppuccin-latte' });+ });+});++describe('resolveModePreference', () => {+ test('an explicit preference ignores the OS', () => {+ expect(resolveModePreference('light', true)).toBe('light');+ expect(resolveModePreference('dark', false)).toBe('dark');+ });++ test("'system', an absent value, and junk all follow the OS", () => {+ expect(resolveModePreference('system', true)).toBe('dark');+ expect(resolveModePreference('system', false)).toBe('light');+ expect(resolveModePreference(undefined, true)).toBe('dark');+ expect(resolveModePreference('nope', false)).toBe('light');+ });+});diff --git a/packages/core/src/theme/theme-plugins.ts b/packages/core/src/theme/theme-plugins.tsindex 036d46661..510dd3a0b 100644--- a/packages/core/src/theme/theme-plugins.ts+++ b/packages/core/src/theme/theme-plugins.ts@@ -1,7 +1,8 @@/*** IDE color-theme plugin registry — the single source of truth for the built-in* palettes the Settings → Preferences picker offers, and the source the- * `appearance.colorTheme` config enum is DERIVED from (`THEME_PLUGIN_IDS`, see+ * `appearance.colorThemeLight` / `colorThemeDark` config enums (and the retired+ * single `colorTheme`) are DERIVED from (`THEME_PLUGIN_IDS`, see* `config/schema.ts`). Lives in `core` (not `app`) precisely so the config* schema can derive its enum from the registry — `core` can't import `app`.*@@ -266,6 +267,59 @@ export function colorThemeMode(id: string | undefined): 'light' | 'dark' | undefreturn kind === 'system' ? undefined : kind;}+/** The palette to apply in each light/dark mode — one theme id per mode. */+export interface ColorThemeSelection {+ light: ThemePluginId;+ dark: ThemePluginId;+}++/** Narrow an arbitrary config value to a known theme id. */+function isThemePluginId(value: unknown): value is ThemePluginId {+ return typeof value === 'string' && THEME_PLUGIN_BY_ID.has(value);+}++/** The `appearance` fields the selection is resolved from. */+export interface ColorThemeSelectionInput {+ colorTheme?: string | undefined;+ colorThemeLight?: string | undefined;+ colorThemeDark?: string | undefined;+}++/**+ * Resolve the light/dark palette pair from config.+ *+ * `colorThemeLight`/`colorThemeDark` are the live fields. A config that predates+ * them carries the single `colorTheme` instead, and seeding BOTH slots from it+ * is what makes the upgrade invisible: the one palette applies in either mode,+ * and — because a palette still forces its own variant — the app renders exactly+ * what it rendered before the pair existed. A half-written pair (one slot only)+ * falls back per-slot rather than discarding the other.+ */+export function resolveColorThemeSelection(+ appearance: ColorThemeSelectionInput | undefined,+): ColorThemeSelection {+ const legacy = appearance?.colorTheme;+ const fallback: ThemePluginId = isThemePluginId(legacy) ? legacy : THEME_PLUGINS[0].id;+ const pick = (value: string | undefined): ThemePluginId =>+ isThemePluginId(value) ? value : fallback;+ return {+ light: pick(appearance?.colorThemeLight),+ dark: pick(appearance?.colorThemeDark),+ };+}++/**+ * The light/dark mode a mode PREFERENCE resolves to. `system` defers to the OS,+ * which the caller supplies — core has no DOM.+ */+export function resolveModePreference(+ preference: string | undefined,+ prefersDark: boolean,+): 'light' | 'dark' {+ if (preference === 'light' || preference === 'dark') return preference;+ return prefersDark ? 'dark' : 'light';+}+/*** Render one `html[data-color-theme="<id>"]` block. The attribute selector* out-specifies the base `:root` / `.dark` blocks, so a single block per theme