A desktop coding agent with free access to frontier models.
TypeScript
feat: more appearance options
ogsamratbf0a174aa889
diff --git a/apps/app/index.html b/apps/app/index.htmlindex ae7df0af..d8767b0e 100644--- a/apps/app/index.html+++ b/apps/app/index.html@@ -46,6 +46,23 @@}}}+ // Density/wallpaper switches and font stacks saved by app/theme.ts (same checks as readBootVars).+ var attrs = (boot && boot.attrs) || {};+ for (var attr in attrs) {+ if ((attr === "density" || attr === "wallpaper") && typeof attrs[attr] === "string" && /^[a-z-]{1,20}$/.test(attrs[attr])) {+ document.documentElement.dataset[attr] = attrs[attr];+ }+ }+ var fonts = (boot && boot.fonts) || {};+ for (var font in fonts) {+ if (+ (font === "--omnirush-ui-font" || font === "--omnirush-code-font" || font === "--omnirush-panel-blur") &&+ typeof fonts[font] === "string" &&+ /^[\w\s",.-]{1,300}$/.test(fonts[font])+ ) {+ document.documentElement.style.setProperty(font, fonts[font]);+ }+ }document.documentElement.dataset.theme = resolved;document.documentElement.style.colorScheme = resolved;} catch (e) {diff --git a/apps/app/src/app/index.css b/apps/app/src/app/index.cssindex 514d5b2f..f304d6ee 100644--- a/apps/app/src/app/index.css+++ b/apps/app/src/app/index.css@@ -181,6 +181,32 @@ body {overflow: hidden;}+/* Compact density: every Tailwind spacing step is 12.5% tighter. */+html[data-density="compact"] {+ --spacing: 0.21875rem;+}++/* Wallpaper: the picture sits on body under a wash of the page colour; page and sidebar are+ see-through (alpha set in app/themes/palette.ts) and the sidebar blurs what is behind it. */+html[data-wallpaper] body {+ background:+ linear-gradient(var(--omnirush-wallpaper-wash), var(--omnirush-wallpaper-wash)),+ var(--omnirush-wallpaper-image, none) center / cover no-repeat,+ var(--omnirush-wallpaper-base);+}++html[data-wallpaper] [data-slot="sidebar-inner"],+html[data-wallpaper] [data-slot="sidebar-inset"] {+ backdrop-filter: blur(var(--omnirush-panel-blur, 0px));+}++@media (prefers-reduced-transparency: reduce) {+ html[data-wallpaper] [data-slot="sidebar-inner"],+ html[data-wallpaper] [data-slot="sidebar-inset"] {+ backdrop-filter: none;+ }+}+html {/* --omnirush-theme-font-scale: custom theme text size (app/themes/palette.ts). */font-size: calc(var(--omnirush-font-size, 16px) * var(--omnirush-theme-font-scale, 1));@@ -188,7 +214,9 @@ html {body {margin: 0;- font-family:+ /* --omnirush-ui-font: Settings > Appearance > Fonts (app/themes/appearance-prefs.ts). */+ font-family: var(+ --omnirush-ui-font,-apple-system,BlinkMacSystemFont,system-ui,@@ -199,7 +227,8 @@ body {Arial,"Noto Sans","Apple Color Emoji",- "Segoe UI Emoji";+ "Segoe UI Emoji"+ );font-size: 13px;line-height: 1.5;color: var(--dls-text-primary);@@ -796,8 +825,9 @@ select:disabled {}@theme inline {- --font-sans: -apple-system, BlinkMacSystemFont, system-ui, ui-sans-serif, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;- --font-heading: -apple-system, BlinkMacSystemFont, system-ui, ui-sans-serif, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ --font-sans: var(--omnirush-ui-font, -apple-system, BlinkMacSystemFont, system-ui, ui-sans-serif, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif);+ --font-heading: var(--omnirush-ui-font, -apple-system, BlinkMacSystemFont, system-ui, ui-sans-serif, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif);+ --font-mono: var(--omnirush-code-font, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);--text-sm: 0.8125rem;--color-sidebar-ring: var(--sidebar-ring);--color-sidebar-border: var(--sidebar-border);diff --git a/apps/app/src/app/theme.ts b/apps/app/src/app/theme.tsindex 7bda61ae..6d42329b 100644--- a/apps/app/src/app/theme.ts+++ b/apps/app/src/app/theme.ts@@ -9,6 +9,15 @@ import {type ActiveTheme,type ThemeSelection,} from "./themes/palette";+import {+ APPEARANCE_PREFS_KEY,+ codeFontStack,+ parseAppearancePrefs,+ sanitizeAppearancePrefs,+ uiFontStack,+ withAccent,+ type AppearancePrefs,+} from "./themes/appearance-prefs";import { parseThemeJson, serializeTheme } from "./themes/share";import type { CustomTheme, ThemeVariantMode } from "./themes/types";@@ -19,7 +28,14 @@ export type { ActiveTheme, ThemeSelection } from "./themes/palette";const THEME_PREF_KEY = "omnirush.react.settings.theme-mode";const LEGACY_THEME_PREF_KEYS = ["omnirush.themePref"];export const THEME_PRESET_KEY = "omnirush.react.settings.theme-preset";+/** The single custom theme of older builds; read once to seed THEME_CUSTOMS_KEY, never written. */export const THEME_CUSTOM_KEY = "omnirush.react.settings.theme-custom";+export const THEME_CUSTOMS_KEY = "omnirush.react.settings.theme-customs";+export const MAX_CUSTOM_THEMES = 20;+const LEGACY_CUSTOM_ID = "custom";+const CUSTOM_ID = /^[a-z0-9-]{1,40}$/;++export type SavedCustomTheme = { id: string; theme: CustomTheme };/** Variables for both modes, read by the inline script in index.html before the bundle loads. */export const THEME_BOOT_KEY = "omnirush.react.settings.theme-boot";@@ -27,7 +43,8 @@ const mediaQuery = "(prefers-color-scheme: dark)";const listeners = new Set<() => void>();let currentMode: ThemeMode | null = null;let currentSelection: ThemeSelection | null = null;-let customTheme: CustomTheme | null | undefined;+let customThemes: SavedCustomTheme[] | undefined;+let appearancePrefs: AppearancePrefs | null = null;let previewTheme: CustomTheme | null = null;let activeTheme: ActiveTheme | null = null;let systemThemeCleanup: (() => void) | null = null;@@ -74,6 +91,7 @@ const readStoredSelection = (): ThemeSelection => {try {const stored = storage()?.getItem(THEME_PRESET_KEY);if (stored === CUSTOM_THEME_ID) return { kind: "custom" };+ if (stored?.startsWith(`${CUSTOM_THEME_ID}:`)) return { kind: "custom", id: stored.slice(CUSTOM_THEME_ID.length + 1) };if (stored && findPreset(stored)) return { kind: "preset", id: stored };} catch {// ignore@@ -81,14 +99,28 @@ const readStoredSelection = (): ThemeSelection => {return { kind: "preset", id: DEFAULT_PRESET_ID };};-const readStoredCustomTheme = (): CustomTheme | null => {+/** Saved custom themes; each entry is re-validated, bad ones are dropped. */+const readStoredCustomThemes = (): SavedCustomTheme[] => {try {- const stored = storage()?.getItem(THEME_CUSTOM_KEY);- if (!stored) return null;- const parsed = parseThemeJson(stored);- return parsed.ok ? parsed.theme : null;+ const stored = storage()?.getItem(THEME_CUSTOMS_KEY);+ if (stored) {+ const list: unknown = JSON.parse(stored);+ if (!Array.isArray(list)) return [];+ const out: SavedCustomTheme[] = [];+ for (const entry of list.slice(0, MAX_CUSTOM_THEMES)) {+ const id = (entry as { id?: unknown })?.id;+ if (typeof id !== "string" || !CUSTOM_ID.test(id) || out.some((item) => item.id === id)) continue;+ const parsed = parseThemeJson(JSON.stringify((entry as { theme?: unknown }).theme ?? null));+ if (parsed.ok) out.push({ id, theme: parsed.theme });+ }+ return out;+ }+ const legacy = storage()?.getItem(THEME_CUSTOM_KEY);+ if (!legacy) return [];+ const parsed = parseThemeJson(legacy);+ return parsed.ok ? [{ id: LEGACY_CUSTOM_ID, theme: parsed.theme }] : [];} catch {- return null;+ return [];}};@@ -109,15 +141,78 @@ const getCurrentSelection = () => {return currentSelection;};+export const getCustomThemes = (): SavedCustomTheme[] => {+ if (customThemes === undefined) customThemes = readStoredCustomThemes();+ return customThemes;+};++const findCustom = (id: string | undefined): SavedCustomTheme | null => {+ const list = getCustomThemes();+ return (id === undefined ? list[0] : list.find((item) => item.id === id)) ?? null;+};++/** The custom theme in use (or the first saved one when a preset is in use). */export const getCustomTheme = (): CustomTheme | null => {- if (customTheme === undefined) customTheme = readStoredCustomTheme();- return customTheme;+ const selection = getCurrentSelection();+ return (selection.kind === "custom" ? findCustom(selection.id) : findCustom(undefined))?.theme ?? null;+};++/** Id of the custom theme in use, or null when a preset is in use. */+export const getSelectedCustomId = (): string | null => {+ const selection = getCurrentSelection();+ return selection.kind === "custom" ? (findCustom(selection.id)?.id ?? null) : null;+};++/** Font stack for code views (Monaco, terminal), from Settings > Appearance. */+export const getCodeFontStack = () => codeFontStack(getAppearancePrefs());++export const getAppearancePrefs = (): AppearancePrefs => {+ if (!appearancePrefs) {+ let raw: string | null = null;+ try {+ raw = storage()?.getItem(APPEARANCE_PREFS_KEY) ?? null;+ } catch {+ raw = null;+ }+ appearancePrefs = parseAppearancePrefs(raw);+ }+ return appearancePrefs;+};++const matches = (query: string) => {+ try {+ return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(query).matches;+ } catch {+ return false;+ }+};++/** The OS asks for less transparency: panels stay solid over a wallpaper, no blur. */+const REDUCED_TRANSPARENCY = "(prefers-reduced-transparency: reduce)";++/** The user's accent, radius, text size and wallpaper on top of the theme. An edit preview shows the theme as-is. */+const withPrefs = (active: ActiveTheme, preview: boolean): ActiveTheme => {+ const prefs = getAppearancePrefs();+ const solid = matches(REDUCED_TRANSPARENCY);+ const glass = prefs.wallpaper+ ? { opacity: solid ? 1 : prefs.panelOpacity / 100, dim: prefs.wallpaperDim / 100 }+ : null;+ if (preview) return { ...active, glass };+ return {+ ...active,+ variant: withAccent(active.variant, prefs.accent),+ accentOverride: Boolean(prefs.accent),+ themeAccent: active.variant.accent,+ radiusPx: prefs.radiusPx ?? active.radiusPx,+ fontSizePx: prefs.fontSizePx ?? active.fontSizePx,+ glass,+ };};/** The theme to show: the preview being edited/imported, else the saved choice. */const computeActiveTheme = (wanted: ResolvedThemeMode): ActiveTheme => {- if (previewTheme) return resolveActiveTheme({ kind: "custom" }, wanted, previewTheme);- return resolveActiveTheme(getCurrentSelection(), wanted, getCustomTheme());+ if (previewTheme) return withPrefs(resolveActiveTheme({ kind: "custom" }, wanted, previewTheme), true);+ return withPrefs(resolveActiveTheme(getCurrentSelection(), wanted, getCustomTheme()), false);};const darkVariantOf = (active: ActiveTheme) => {@@ -125,6 +220,31 @@ const darkVariantOf = (active: ActiveTheme) => {return findPreset(active.selection.id)?.variants.dark ?? null;};+/** Font, density and wallpaper switches that are not colours (data-* on <html>, fixed font stacks). */+const prefAttrs = (prefs: AppearancePrefs) => ({+ attrs: {+ density: prefs.density === "compact" ? "compact" : null,+ wallpaper: prefs.wallpaper ? "on" : null,+ },+ fonts: {+ "--omnirush-ui-font": uiFontStack(prefs),+ "--omnirush-code-font": prefs.codeFont === "system" ? null : codeFontStack(prefs),+ "--omnirush-panel-blur": prefs.wallpaper && !matches(REDUCED_TRANSPARENCY) ? `${prefs.panelBlur}px` : null,+ } as Record<string, string | null>,+});++const applyPrefAttrs = (root: HTMLElement) => {+ const { attrs, fonts } = prefAttrs(getAppearancePrefs());+ for (const [name, value] of Object.entries(attrs)) {+ if (value) root.dataset[name] = value;+ else delete root.dataset[name];+ }+ for (const [name, value] of Object.entries(fonts)) {+ if (value) root.style.setProperty(name, value);+ else root.style.removeProperty(name);+ }+};+/** Saves both modes' variables so the next start can paint them before the bundle runs. */const persistBootVars = () => {if (previewTheme) return;@@ -138,6 +258,7 @@ const persistBootVars = () => {only,light: paletteVars(light, darkVariantOf(light)),dark: paletteVars(dark, darkVariantOf(dark)),+ ...prefAttrs(getAppearancePrefs()),};store.setItem(THEME_BOOT_KEY, JSON.stringify(boot));} catch {@@ -155,6 +276,7 @@ const applyTheme = (mode: ThemeMode) => {if (active.legacy) delete root.dataset.omnirushPalette;else root.dataset.omnirushPalette = active.selection.kind === "custom" ? CUSTOM_THEME_ID : active.selection.id;applyPaletteVars(root.style, paletteVars(active, darkVariantOf(active)));+ if (typeof root.style.removeProperty === "function") applyPrefAttrs(root);syncThemeColorMeta(active);};@@ -195,7 +317,14 @@ const ensureSystemThemeSubscription = () => {if (!list) return;list.addEventListener("change", handleSystemThemeChange);- systemThemeCleanup = () => list.removeEventListener("change", handleSystemThemeChange);+ // Turning "reduce transparency" on or off in the OS updates the wallpaper look at once.+ const transparency = window.matchMedia(REDUCED_TRANSPARENCY);+ const onTransparency = () => reapply();+ transparency.addEventListener?.("change", onTransparency);+ systemThemeCleanup = () => {+ list.removeEventListener("change", handleSystemThemeChange);+ transparency.removeEventListener?.("change", onTransparency);+ };};const reapply = () => {@@ -258,7 +387,8 @@ export const setThemeSelection = (selection: ThemeSelection) => {selection.kind === "preset" && !findPreset(selection.id) ? { kind: "preset", id: DEFAULT_PRESET_ID } : selection;currentSelection = next;try {- storage()?.setItem(THEME_PRESET_KEY, next.kind === "custom" ? CUSTOM_THEME_ID : next.id);+ const stored = next.kind === "preset" ? next.id : next.id ? `${CUSTOM_THEME_ID}:${next.id}` : CUSTOM_THEME_ID;+ storage()?.setItem(THEME_PRESET_KEY, stored);} catch {// ignore}@@ -266,13 +396,57 @@ export const setThemeSelection = (selection: ThemeSelection) => {persistBootVars();};-/** Stores the custom theme ("My theme"). Callers select it with setThemeSelection. */-export const saveCustomTheme = (theme: CustomTheme) => {+const persistCustomThemes = (list: SavedCustomTheme[]) => {+ customThemes = list;+ try {+ storage()?.setItem(THEME_CUSTOMS_KEY, JSON.stringify(list));+ } catch {+ // ignore+ }+ reapply();+ persistBootVars();+};++const newCustomId = () => {+ const taken = new Set(getCustomThemes().map((item) => item.id));+ let id = `t-${Date.now().toString(36)}`;+ for (let n = 2; taken.has(id); n += 1) id = `t-${Date.now().toString(36)}-${n}`;+ return id;+};++/**+ * Stores a custom theme, validated. With an id it replaces that theme, otherwise it is added+ * (up to MAX_CUSTOM_THEMES). Returns the id; callers select it with setThemeSelection.+ */+export const saveCustomTheme = (theme: CustomTheme, id?: string): string => {const checked = parseThemeJson(serializeTheme(theme));if (!checked.ok) throw new Error(checked.error);- customTheme = checked.theme;+ const list = getCustomThemes();+ const index = id === undefined ? -1 : list.findIndex((item) => item.id === id);+ if (index >= 0) {+ persistCustomThemes(list.map((item, i) => (i === index ? { id: item.id, theme: checked.theme } : item)));+ return list[index]!.id;+ }+ if (list.length >= MAX_CUSTOM_THEMES) {+ throw new Error(`You can keep up to ${MAX_CUSTOM_THEMES} custom themes. Delete one first.`);+ }+ const nextId = id !== undefined && CUSTOM_ID.test(id) ? id : newCustomId();+ persistCustomThemes([...list, { id: nextId, theme: checked.theme }]);+ return nextId;+};++/** Deletes a saved custom theme; if it was in use, Default takes over. */+export const deleteCustomTheme = (id: string) => {+ const inUse = getSelectedCustomId() === id;+ persistCustomThemes(getCustomThemes().filter((item) => item.id !== id));+ if (inUse) setThemeSelection({ kind: "preset", id: DEFAULT_PRESET_ID });+};++/** Changes accent, fonts, density, sizes or wallpaper look; applied at once and kept on this device. */+export const setAppearancePrefs = (patch: Partial<AppearancePrefs>) => {+ appearancePrefs = sanitizeAppearancePrefs({ ...getAppearancePrefs(), ...patch });try {- storage()?.setItem(THEME_CUSTOM_KEY, serializeTheme(checked.theme));+ storage()?.setItem(APPEARANCE_PREFS_KEY, JSON.stringify(appearancePrefs));} catch {// ignore}@@ -301,19 +475,34 @@ export const modeSwitchFor = (return mode === only ? null : only;};+const isRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === "object" && !Array.isArray(value);+// Same patterns as the inline script in index.html: plain words, font names and px only (no url(), no ;).+const BOOT_ATTR = /^[a-z-]{1,20}$/;+const BOOT_FONT = /^[\w\s",.-]{1,300}$/;+const BOOT_FONT_VARS = new Set(["--omnirush-ui-font", "--omnirush-code-font", "--omnirush-panel-blur"]);+/** Values for the early inline script; exported for tests. */export const readBootVars = (raw: string | null, resolved: ResolvedThemeMode) => {if (!raw) return null;try {- const boot = JSON.parse(raw) as { only?: unknown; light?: unknown; dark?: unknown };+ const boot = JSON.parse(raw) as { only?: unknown; light?: unknown; dark?: unknown; attrs?: unknown; fonts?: unknown };const mode: ResolvedThemeMode = boot.only === "dark" || boot.only === "light" ? boot.only : resolved;const vars = boot[mode];- if (!vars || typeof vars !== "object") return { mode, vars: {} };const safe: Record<string, string> = {};- for (const [name, value] of Object.entries(vars as Record<string, unknown>)) {- if (typeof value === "string" && isSafeVar(name, value)) safe[name] = value;+ if (vars && typeof vars === "object") {+ for (const [name, value] of Object.entries(vars as Record<string, unknown>)) {+ if (typeof value === "string" && isSafeVar(name, value)) safe[name] = value;+ }+ }+ const attrs: Record<string, string> = {};+ for (const [name, value] of Object.entries(isRecord(boot.attrs) ? boot.attrs : {})) {+ if ((name === "density" || name === "wallpaper") && typeof value === "string" && BOOT_ATTR.test(value)) attrs[name] = value;+ }+ for (const [name, value] of Object.entries(isRecord(boot.fonts) ? boot.fonts : {})) {+ if (BOOT_FONT_VARS.has(name) && typeof value === "string" && BOOT_FONT.test(value)) safe[name] = value;}- return { mode, vars: safe };+ return { mode, vars: safe, attrs };} catch {return null;}@@ -322,7 +511,8 @@ export const readBootVars = (raw: string | null, resolved: ResolvedThemeMode) =>export const resetThemeStateForTests = () => {currentMode = null;currentSelection = null;- customTheme = undefined;+ customThemes = undefined;+ appearancePrefs = null;previewTheme = null;activeTheme = null;listeners.clear();diff --git a/apps/app/src/app/themes/appearance-prefs.ts b/apps/app/src/app/themes/appearance-prefs.tsnew file mode 100644index 00000000..9f89fd7b--- /dev/null+++ b/apps/app/src/app/themes/appearance-prefs.ts@@ -0,0 +1,179 @@+/**+ * Per-device appearance choices that sit on top of any theme: accent colour,+ * fonts, density, corner radius, text size and the wallpaper look. Stored in+ * localStorage as JSON; every field is validated on read, so a hand-edited or+ * damaged value falls back to the default instead of reaching CSS.+ */+import { contrastRatio, suggestColour, TEXT_TARGET, UI_TARGET } from "./contrast";+import { FONT_SIZE_RANGE, RADIUS_RANGE, type ThemeVariant } from "./types";++export const APPEARANCE_PREFS_KEY = "omnirush.react.settings.appearance";+export const MAX_PREFS_BYTES = 4 * 1024;++const SYSTEM_MONO = 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';++/** Interface fonts. Font stacks are fixed strings; stored prefs only ever hold an id. */+export const UI_FONTS = [+ { id: "system", label: "System default", stack: null },+ { id: "geist", label: "Geist", stack: '"Geist Variable", system-ui, sans-serif' },+ { id: "plex", label: "IBM Plex Sans", stack: '"IBM Plex Sans Variable", system-ui, sans-serif' },+ { id: "humanist", label: "Verdana / DejaVu Sans", stack: 'Verdana, "DejaVu Sans", "Bitstream Vera Sans", sans-serif' },+ { id: "serif", label: "Serif (Charter / Georgia)", stack: 'Charter, "Bitstream Charter", Georgia, "Times New Roman", serif' },+ { id: "mono", label: "Same as code font", stack: null },+] as const;++/** Code fonts. Named ones are used when installed; the system monospace font fills in otherwise. */+export const CODE_FONTS = [+ { id: "system", label: "System monospace", stack: SYSTEM_MONO },+ { id: "jetbrains", label: "JetBrains Mono", stack: `"JetBrains Mono", ${SYSTEM_MONO}` },+ { id: "fira", label: "Fira Code", stack: `"Fira Code", "Fira Mono", ${SYSTEM_MONO}` },+ { id: "cascadia", label: "Cascadia Code", stack: `"Cascadia Code", "Cascadia Mono", ${SYSTEM_MONO}` },+ { id: "sf", label: "SF Mono / Menlo", stack: `"SF Mono", Menlo, Monaco, ${SYSTEM_MONO}` },+ { id: "courier", label: "Courier / Liberation Mono", stack: `"Courier New", Courier, "Liberation Mono", monospace` },+] as const;++export type UiFontId = (typeof UI_FONTS)[number]["id"];+export type CodeFontId = (typeof CODE_FONTS)[number]["id"];+export type Density = "comfortable" | "compact";++/** Accent swatches offered next to the custom colour field. */+export const ACCENT_SWATCHES = [+ { name: "Blue", hex: "#3b6fe0" },+ { name: "Violet", hex: "#7c4ddb" },+ { name: "Pink", hex: "#d52d86" },+ { name: "Red", hex: "#d83737" },+ { name: "Orange", hex: "#ba5a0d" },+ { name: "Green", hex: "#208459" },+ { name: "Teal", hex: "#13808c" },+ { name: "Graphite", hex: "#55595f" },+] as const;++export const WALLPAPER_DIM_RANGE = { min: 0, max: 80 } as const;+/** Panels never go below 55% so text over a busy picture stays readable. */+export const PANEL_OPACITY_RANGE = { min: 55, max: 100 } as const;+export const PANEL_BLUR_RANGE = { min: 0, max: 24 } as const;++export type AppearancePrefs = {+ /** #rrggbb, or null for the theme's own accent. */+ accent: string | null;+ uiFont: UiFontId;+ codeFont: CodeFontId;+ density: Density;+ /** Null follows the theme. */+ radiusPx: number | null;+ /** Null follows the theme. */+ fontSizePx: number | null;+ /** A wallpaper image is stored on this device (IndexedDB). */+ wallpaper: boolean;+ wallpaperDim: number;+ panelOpacity: number;+ panelBlur: number;+};++export const DEFAULT_APPEARANCE_PREFS: Readonly<AppearancePrefs> = Object.freeze({+ accent: null,+ uiFont: "system",+ codeFont: "system",+ density: "comfortable",+ radiusPx: null,+ fontSizePx: null,+ wallpaper: false,+ wallpaperDim: 30,+ panelOpacity: 82,+ panelBlur: 12,+});++const HEX = /^#[0-9a-f]{6}$/;++export function normalizeHex(value: unknown): string | null {+ if (typeof value !== "string") return null;+ let text = value.trim().toLowerCase();+ if (!text.startsWith("#")) text = `#${text}`;+ if (/^#[0-9a-f]{3}$/.test(text)) text = `#${text[1]}${text[1]}${text[2]}${text[2]}${text[3]}${text[3]}`;+ return HEX.test(text) ? text : null;+}++const clampInt = (value: unknown, range: { min: number; max: number }, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? Math.min(range.max, Math.max(range.min, Math.round(value))) : fallback;++const nullableInRange = (value: unknown, range: { min: number; max: number }) =>+ typeof value === "number" && Number.isFinite(value) ? Math.min(range.max, Math.max(range.min, value)) : null;++const oneOf = <T extends string>(value: unknown, ids: readonly { id: T }[], fallback: T): T =>+ ids.some((item) => item.id === value) ? (value as T) : fallback;++/** Field-by-field read: unknown keys are dropped, bad values become defaults. */+export function sanitizeAppearancePrefs(input: unknown): AppearancePrefs {+ const d = DEFAULT_APPEARANCE_PREFS;+ if (!input || typeof input !== "object" || Array.isArray(input)) return { ...d };+ const raw = input as Record<string, unknown>;+ return {+ accent: normalizeHex(raw.accent),+ uiFont: oneOf(raw.uiFont, UI_FONTS, d.uiFont),+ codeFont: oneOf(raw.codeFont, CODE_FONTS, d.codeFont),+ density: raw.density === "compact" ? "compact" : "comfortable",+ radiusPx: nullableInRange(raw.radiusPx, RADIUS_RANGE),+ fontSizePx: nullableInRange(raw.fontSizePx, FONT_SIZE_RANGE),+ wallpaper: raw.wallpaper === true,+ wallpaperDim: clampInt(raw.wallpaperDim, WALLPAPER_DIM_RANGE, d.wallpaperDim),+ panelOpacity: clampInt(raw.panelOpacity, PANEL_OPACITY_RANGE, d.panelOpacity),+ panelBlur: clampInt(raw.panelBlur, PANEL_BLUR_RANGE, d.panelBlur),+ };+}++export function parseAppearancePrefs(text: string | null): AppearancePrefs {+ if (!text || text.length > MAX_PREFS_BYTES) return { ...DEFAULT_APPEARANCE_PREFS };+ try {+ return sanitizeAppearancePrefs(JSON.parse(text));+ } catch {+ return { ...DEFAULT_APPEARANCE_PREFS };+ }+}++export function uiFontStack(prefs: Pick<AppearancePrefs, "uiFont" | "codeFont">): string | null {+ if (prefs.uiFont === "mono") return codeFontStack(prefs);+ return UI_FONTS.find((font) => font.id === prefs.uiFont)?.stack ?? null;+}++export function codeFontStack(prefs: Pick<AppearancePrefs, "codeFont">): string {+ return CODE_FONTS.find((font) => font.id === prefs.codeFont)?.stack ?? SYSTEM_MONO;+}++/** Black or white text on an accent fill, whichever reads better. */+export function textOnAccent(accent: string): string {+ return contrastRatio("#ffffff", accent) >= contrastRatio("#000000", accent) ? "#ffffff" : "#000000";+}++/** The theme variant with the chosen accent (button text picked for contrast). */+export function withAccent(variant: ThemeVariant, accent: string | null): ThemeVariant {+ if (!accent) return variant;+ return { ...variant, accent, accentText: textOnAccent(accent), highlight: variant.highlight ? accent : variant.highlight };+}++export type AccentCheck = {+ /** Accent against the page and raised surfaces (UI target 3:1). */+ uiRatio: number;+ /** Button text on the accent (text target 4.5:1). */+ textRatio: number;+ ok: boolean;+ /** Nearest colour that passes both, when this one does not. */+ suggestion: string | null;+};++/** WCAG check for an accent on a theme variant: buttons, focus rings and selection must stay visible. */+export function checkAccent(variant: ThemeVariant, accent: string): AccentCheck {+ const backgrounds = [variant.background, variant.surfaceRaised];+ const uiRatio = Math.min(...backgrounds.map((bg) => contrastRatio(accent, bg)));+ const textRatio = contrastRatio(textOnAccent(accent), accent);+ const ok = uiRatio >= UI_TARGET && textRatio >= TEXT_TARGET;+ if (ok) return { uiRatio, textRatio, ok, suggestion: null };+ // Walk the visible-colour fix until the button text also reaches AA.+ let candidate = suggestColour(accent, backgrounds, UI_TARGET);+ for (let step = 0; step < 40 && contrastRatio(textOnAccent(candidate), candidate) < TEXT_TARGET; step += 1) {+ candidate = suggestColour(candidate, backgrounds, UI_TARGET + 0.25 * (step + 1));+ }+ const passes =+ Math.min(...backgrounds.map((bg) => contrastRatio(candidate, bg))) >= UI_TARGET &&+ contrastRatio(textOnAccent(candidate), candidate) >= TEXT_TARGET;+ return { uiRatio, textRatio, ok, suggestion: passes ? candidate : null };+}diff --git a/apps/app/src/app/themes/palette.ts b/apps/app/src/app/themes/palette.tsindex 2f859811..e28108d8 100644--- a/apps/app/src/app/themes/palette.ts+++ b/apps/app/src/app/themes/palette.ts@@ -21,7 +21,8 @@ import {export const DEFAULT_PRESET_ID = "default";export const CUSTOM_THEME_ID = "custom";-export type ThemeSelection = { kind: "preset"; id: string } | { kind: "custom" };+/** A custom selection without an id means the first saved custom theme (older saves had one slot). */+export type ThemeSelection = { kind: "preset"; id: string } | { kind: "custom"; id?: string };export type ActiveTheme = {selection: ThemeSelection;@@ -37,6 +38,12 @@ export type ActiveTheme = {fontSizePx: number;/** High contrast: secondary text steps aim for 7:1. */aaa?: boolean;+ /** The user's accent replaces the theme's (also on Default). */+ accentOverride?: boolean;+ /** The theme's own accent, before the user's accent replaced it. */+ themeAccent?: string;+ /** Wallpaper on: page and sidebar become see-through by `opacity`, the picture is washed by `dim` (0-1). */+ glass?: { opacity: number; dim: number } | null;};export function findPreset(id: string): ThemePreset | undefined {@@ -159,10 +166,14 @@ const DEFAULT_PRESET_FIXES: Record<ThemeVariantMode, Record<string, string>> = {/** CSS custom property name -> value for an active theme. */export function paletteVars(- active: Pick<ActiveTheme, "variant" | "mode" | "legacy" | "radiusPx" | "fontSizePx" | "aaa">,+ active: Pick<ActiveTheme, "variant" | "mode" | "legacy" | "radiusPx" | "fontSizePx" | "aaa" | "accentOverride" | "glass">,darkVariant?: ThemeVariant | null,): Record<string, string> {- if (active.legacy) return { ...DEFAULT_PRESET_FIXES[active.mode] };+ if (active.legacy) {+ const vars: Record<string, string> = { ...DEFAULT_PRESET_FIXES[active.mode] };+ if (active.accentOverride) Object.assign(vars, accentVars(active.variant));+ return Object.assign(vars, sizingVars(active), glassVars(active));+ }const v = active.variant;const dark = isDarkColour(v.background);const scale = neutralScale(v, Boolean(active.aaa));@@ -191,10 +202,7 @@ export function paletteVars(v.text,);set(["--muted-foreground", "--dls-text-secondary"], v.textMuted);- set(["--primary", "--dls-accent", "--sidebar-primary", "--ring", "--sidebar-ring"], v.accent);- set(["--primary-foreground", "--dls-accent-fg", "--sidebar-primary-foreground"], v.accentText);- set(["--dls-accent-hover"], mix(v.accent, dark ? "#ffffff" : "#000000", 0.12));- set(["--dls-accent-rgb"], rgbTriplet(v.accent));+ Object.assign(vars, accentVars(v));set(["--dls-secondary-rgb"], rgbTriplet(v.textMuted));set(["--accent", "--sidebar-accent", "--dls-hover"], scale[2]!);set(["--dls-active"], scale[4]!);@@ -204,9 +212,6 @@ export function paletteVars(// Decorative highlight (connected dot, usage bar, ".ai" in the logo): at least 3:1 on light pages.const highlight = v.highlight ?? v.accent;set(["--omnirush-highlight"], dark ? highlight : suggestColour(highlight, [v.background, v.surface], 3));- const link = textSafeAccent(v);- set(["--omnirush-link"], link);- set(["--omnirush-link-hover"], mix(link, v.text, 0.3));set(["--omnirush-terminal-bg"], v.terminal.bg);set(["--omnirush-terminal-fg"], v.terminal.fg);set(["--omnirush-terminal-header"], mix(v.terminal.bg, v.terminal.fg, 0.06));@@ -217,6 +222,25 @@ export function paletteVars(if (darkVariant) set(["--omnirush-gate-bg"], darkVariant.background);scale.forEach((value, index) => set([`--gray-${index + 1}`, `--slate-${index + 1}`], value));NEUTRAL_ALPHA.forEach((alpha, index) => set([`--gray-a${index + 1}`, `--slate-a${index + 1}`], withAlpha(v.text, alpha)));+ return Object.assign(vars, sizingVars(active), glassVars(active));+}++/** Buttons, focus rings, selection and links from the accent (links keep 4.5:1 on every background). */+function accentVars(v: ThemeVariant): Record<string, string> {+ const dark = isDarkColour(v.background);+ const link = textSafeAccent(v);+ const vars: Record<string, string> = {};+ for (const name of ["--primary", "--dls-accent", "--sidebar-primary", "--ring", "--sidebar-ring"]) vars[name] = v.accent;+ for (const name of ["--primary-foreground", "--dls-accent-fg", "--sidebar-primary-foreground"]) vars[name] = v.accentText;+ vars["--dls-accent-hover"] = mix(v.accent, dark ? "#ffffff" : "#000000", 0.12);+ vars["--dls-accent-rgb"] = rgbTriplet(v.accent);+ vars["--omnirush-link"] = link;+ vars["--omnirush-link-hover"] = mix(link, v.text, 0.3);+ return vars;+}++function sizingVars(active: Pick<ActiveTheme, "radiusPx" | "fontSizePx">): Record<string, string> {+ const vars: Record<string, string> = {};const radius = Math.min(RADIUS_RANGE.max, Math.max(RADIUS_RANGE.min, active.radiusPx));if (radius !== DEFAULT_RADIUS_PX) vars["--radius"] = `${radius}px`;const fontSize = Math.min(FONT_SIZE_RANGE.max, Math.max(FONT_SIZE_RANGE.min, active.fontSizePx));@@ -224,6 +248,21 @@ export function paletteVars(return vars;}+/** Wallpaper: the page and sidebar let the picture through; the wash keeps text readable over it. */+function glassVars(active: Pick<ActiveTheme, "variant" | "glass">): Record<string, string> {+ const glass = active.glass;+ if (!glass) return {};+ const v = active.variant;+ const opacity = Math.min(1, Math.max(0, glass.opacity));+ const vars: Record<string, string> = {+ "--omnirush-wallpaper-base": v.background,+ "--omnirush-wallpaper-wash": withAlpha(v.background, Math.min(1, Math.max(0, glass.dim))),+ };+ for (const name of ["--background", "--dls-background", "--dls-app-bg"]) vars[name] = withAlpha(v.background, opacity);+ for (const name of ["--sidebar", "--dls-sidebar"]) vars[name] = withAlpha(v.surface, opacity);+ return vars;+}+const VAR_NAME = /^--[a-z0-9-]+$/;const VAR_VALUE = /^(#[0-9a-f]{6}([0-9a-f]{2})?|\d{1,3} \d{1,3} \d{1,3}|\d+(\.\d+)?(px)?)$/;@@ -254,7 +293,14 @@ export function allPaletteVarNames(): string[] {const preset = findPreset("fjord")!;const names = Object.keys(paletteVars(- { variant: preset.variants.light!, mode: "light", legacy: false, radiusPx: 0, fontSizePx: FONT_SIZE_RANGE.max },+ {+ variant: preset.variants.light!,+ mode: "light",+ legacy: false,+ radiusPx: 0,+ fontSizePx: FONT_SIZE_RANGE.max,+ glass: { opacity: 0.5, dim: 0.5 },+ },preset.variants.dark,),);diff --git a/apps/app/src/app/themes/presets.ts b/apps/app/src/app/themes/presets.tsindex 33699267..5fd01760 100644--- a/apps/app/src/app/themes/presets.ts+++ b/apps/app/src/app/themes/presets.ts@@ -295,4 +295,120 @@ export const THEME_PRESETS: readonly ThemePreset[] = [},},},+ {+ id: "graphite",+ name: "Graphite",+ description: "Plain neutral greys with a quiet ink accent.",+ target: "AA",+ variants: {+ light: {+ background: "#ffffff",+ surface: "#f7f7f7",+ surfaceRaised: "#ffffff",+ border: "#e5e5e5",+ text: "#0d0d0d",+ textMuted: "#5d5d5d",+ accent: "#0d0d0d",+ accentText: "#ffffff",+ success: "#1a7f45",+ warn: "#9a5b00",+ danger: "#c4262e",+ code: { bg: "#f7f7f7", fg: "#0d0d0d", keyword: "#b3245c", string: "#1a6b3c", number: "#a14d00", function: "#3c55b8", type: "#7a3fb0", variable: "#0d0d0d", comment: "#6b6b6b", punctuation: "#4d4d4d" },+ terminal: { bg: "#ffffff", fg: "#0d0d0d", cursor: "#0d0d0d", black: "#0d0d0d", red: "#c4262e", green: "#1a7f45", yellow: "#9a5b00", blue: "#2f5bc4", magenta: "#8a3fb0", cyan: "#1a6f80", white: "#9a9a9a", brightBlack: "#5d5d5d", brightRed: "#d23a41", brightGreen: "#1e864b", brightYellow: "#a36200", brightBlue: "#3a66d0", brightMagenta: "#9447bb", brightCyan: "#1d7889", brightWhite: "#d4d4d4" },+ highlight: "#10a37f",+ },+ dark: {+ background: "#181818",+ surface: "#212121",+ surfaceRaised: "#2a2a2a",+ border: "#333333",+ text: "#ececec",+ textMuted: "#a3a3a3",+ accent: "#ececec",+ accentText: "#181818",+ success: "#4cc38a",+ warn: "#e8b44c",+ danger: "#f28b82",+ code: { bg: "#1e1e1e", fg: "#e3e3e3", keyword: "#f07ab0", string: "#8fd6a3", number: "#f2a65a", function: "#8fb4ff", type: "#c9a2ff", variable: "#e3e3e3", comment: "#9a9a9a", punctuation: "#bdbdbd" },+ terminal: { bg: "#181818", fg: "#e3e3e3", cursor: "#ececec", black: "#2a2a2a", red: "#f28b82", green: "#4cc38a", yellow: "#e8b44c", blue: "#8fb4ff", magenta: "#d4a2ff", cyan: "#6fd0dc", white: "#cfcfcf", brightBlack: "#8e8e8e", brightRed: "#ffa8a0", brightGreen: "#7ad9a8", brightYellow: "#f3cd7a", brightBlue: "#afc8ff", brightMagenta: "#e2bfff", brightCyan: "#96e0e8", brightWhite: "#f5f5f5" },+ highlight: "#10a37f",+ },+ },+ },+ {+ id: "paper",+ name: "Paper",+ description: "Warm sepia paper and ink, easy on the eyes.",+ target: "AA",+ variants: {+ light: {+ background: "#f6efe2",+ surface: "#efe6d5",+ surfaceRaised: "#fbf6ec",+ border: "#ddd0b8",+ text: "#3b2f22",+ textMuted: "#6e5d48",+ accent: "#9c4a1a",+ accentText: "#fbf6ec",+ success: "#4d6b1f",+ warn: "#8a5a00",+ danger: "#a8322a",+ code: { bg: "#efe6d5", fg: "#3b2f22", keyword: "#9c3a52", string: "#4d6b1f", number: "#8a4a12", function: "#2e5f7a", type: "#6d4a8c", variable: "#3b2f22", comment: "#75654e", punctuation: "#5a4a38" },+ terminal: { bg: "#f6efe2", fg: "#3b2f22", cursor: "#9c4a1a", black: "#3b2f22", red: "#a8322a", green: "#4d6b1f", yellow: "#8a5a00", blue: "#2e5f7a", magenta: "#8a3a6a", cyan: "#2a6b66", white: "#a89a80", brightBlack: "#6e5d48", brightRed: "#b13e35", brightGreen: "#567625", brightYellow: "#946200", brightBlue: "#346b88", brightMagenta: "#964476", brightCyan: "#307570", brightWhite: "#d8ccb4" },+ },+ dark: {+ background: "#221c16",+ surface: "#2a231c",+ surfaceRaised: "#332b22",+ border: "#463a2d",+ text: "#eadfcb",+ textMuted: "#b7a68d",+ accent: "#e09a5a",+ accentText: "#221c16",+ success: "#a9c47a",+ warn: "#e6bc6a",+ danger: "#ef9a8a",+ code: { bg: "#272019", fg: "#e3d7c2", keyword: "#e595a8", string: "#b5cc85", number: "#e8a86a", function: "#8fbfd6", type: "#c9a8e0", variable: "#e3d7c2", comment: "#a8977e", punctuation: "#c9bba3" },+ terminal: { bg: "#221c16", fg: "#e3d7c2", cursor: "#e09a5a", black: "#332b22", red: "#ef9a8a", green: "#a9c47a", yellow: "#e6bc6a", blue: "#8fbfd6", magenta: "#d9a0c4", cyan: "#8ccfc4", white: "#d6c9b0", brightBlack: "#9c8b72", brightRed: "#f5b0a2", brightGreen: "#bdd496", brightYellow: "#f0cd8a", brightBlue: "#a9d0e2", brightMagenta: "#e4b6d2", brightCyan: "#a6dcd2", brightWhite: "#f3ead9" },+ },+ },+ },+ {+ id: "nocturne",+ name: "Nocturne",+ description: "Dusky violet with bright candy syntax.",+ target: "AA",+ variants: {+ light: {+ background: "#f8f7fc",+ surface: "#efedf7",+ surfaceRaised: "#ffffff",+ border: "#dcd8ea",+ text: "#22212e",+ textMuted: "#5c5874",+ accent: "#7a3fd1",+ accentText: "#ffffff",+ success: "#1d7a3e",+ warn: "#8a6400",+ danger: "#c42b3a",+ code: { bg: "#efedf7", fg: "#22212e", keyword: "#b0247a", string: "#6b6a00", number: "#7a3fd1", function: "#1d7a3e", type: "#1b6a8a", variable: "#22212e", comment: "#686482", punctuation: "#4a475e" },+ terminal: { bg: "#f8f7fc", fg: "#22212e", cursor: "#7a3fd1", black: "#22212e", red: "#c42b3a", green: "#1d7a3e", yellow: "#8a6400", blue: "#5a3fd1", magenta: "#b0247a", cyan: "#1b6a8a", white: "#a8a4bc", brightBlack: "#5c5874", brightRed: "#cf3746", brightGreen: "#218244", brightYellow: "#916a00", brightBlue: "#6448d6", brightMagenta: "#bb2c84", brightCyan: "#207393", brightWhite: "#d5d2e2" },+ },+ dark: {+ background: "#1e1f29",+ surface: "#252632",+ surfaceRaised: "#2d2f3d",+ border: "#3c3e51",+ text: "#f4f4ef",+ textMuted: "#a7abc6",+ accent: "#c39bff",+ accentText: "#1e1f29",+ success: "#5ff08c",+ warn: "#f3f88f",+ danger: "#ff6b6b",+ code: { bg: "#21222c", fg: "#f4f4ef", keyword: "#ff7ac6", string: "#f3f88f", number: "#c39bff", function: "#5ff08c", type: "#8be9fd", variable: "#f4f4ef", comment: "#8f97c4", punctuation: "#c8cadb" },+ terminal: { bg: "#1e1f29", fg: "#f4f4ef", cursor: "#f4f4ef", black: "#2d2f3d", red: "#ff6b6b", green: "#5ff08c", yellow: "#f3f88f", blue: "#c39bff", magenta: "#ff7ac6", cyan: "#8be9fd", white: "#e6e6e0", brightBlack: "#8f97c4", brightRed: "#ff8f8f", brightGreen: "#7ff7a4", brightYellow: "#f8fbaf", brightBlue: "#d5b6ff", brightMagenta: "#ff97d4", brightCyan: "#a8eefe", brightWhite: "#ffffff" },+ },+ },+ },];diff --git a/apps/app/src/app/wallpaper.ts b/apps/app/src/app/wallpaper.tsnew file mode 100644index 00000000..3217262b--- /dev/null+++ b/apps/app/src/app/wallpaper.ts@@ -0,0 +1,83 @@+/**+ * Wallpaper picture for Settings > Appearance: kept on this device in IndexedDB+ * (too big for localStorage) and shown through a blob: URL in a CSS variable.+ */+import { getAppearancePrefs, setAppearancePrefs } from "./theme";++const DB_NAME = "omnirush-appearance";+const STORE = "files";+const KEY = "wallpaper";+const IMAGE_VAR = "--omnirush-wallpaper-image";++export const WALLPAPER_TYPES = ["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"] as const;+export const MAX_WALLPAPER_BYTES = 8 * 1024 * 1024;++let currentUrl: string | null = null;++/** Null when the file can be used, else a sentence for the user. */+export function checkWallpaperFile(file: { type: string; size: number }): string | null {+ if (!(WALLPAPER_TYPES as readonly string[]).includes(file.type)) return "Choose a PNG, JPEG, WebP, AVIF or GIF image.";+ if (file.size <= 0) return "That file is empty.";+ if (file.size > MAX_WALLPAPER_BYTES) return "Choose an image under 8 MB.";+ return null;+}++function openDb(): Promise<IDBDatabase> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.open(DB_NAME, 1);+ request.onupgradeneeded = () => request.result.createObjectStore(STORE);+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+}++async function run<T>(mode: IDBTransactionMode, action: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {+ const db = await openDb();+ try {+ return await new Promise<T>((resolve, reject) => {+ const request = action(db.transaction(STORE, mode).objectStore(STORE));+ request.onsuccess = () => resolve(request.result);+ request.onerror = () => reject(request.error);+ });+ } finally {+ db.close();+ }+}++function showImage(blob: Blob | null) {+ if (typeof document === "undefined") return;+ if (currentUrl) URL.revokeObjectURL(currentUrl);+ currentUrl = blob ? URL.createObjectURL(blob) : null;+ const style = document.documentElement.style;+ if (currentUrl) style.setProperty(IMAGE_VAR, `url("${currentUrl}")`);+ else style.removeProperty(IMAGE_VAR);+}++/** Checks, decodes and stores the picture, then turns the wallpaper on. Throws a readable Error. */+export async function setWallpaperFromFile(file: File): Promise<void> {+ const problem = checkWallpaperFile(file);+ if (problem) throw new Error(problem);+ try {+ // Decoding proves it is a real picture, not just a file with an image name.+ (await createImageBitmap(file)).close();+ } catch {+ throw new Error("That image could not be opened.");+ }+ await run("readwrite", (store) => store.put(file, KEY));+ showImage(file);+ setAppearancePrefs({ wallpaper: true });+}++export async function removeWallpaper(): Promise<void> {+ setAppearancePrefs({ wallpaper: false });+ showImage(null);+ await run("readwrite", (store) => store.delete(KEY)).catch(() => undefined);+}++/** At start: shows the saved picture, or turns the wallpaper off if the picture is gone. */+export async function restoreWallpaper(): Promise<void> {+ if (!getAppearancePrefs().wallpaper || typeof indexedDB === "undefined") return;+ const blob = await run<unknown>("readonly", (store) => store.get(KEY)).catch(() => null);+ if (blob instanceof Blob) showImage(blob);+ else setAppearancePrefs({ wallpaper: false });+}diff --git a/apps/app/src/index.react.tsx b/apps/app/src/index.react.tsxindex 7544748a..3c7b60b3 100644--- a/apps/app/src/index.react.tsx+++ b/apps/app/src/index.react.tsx@@ -9,6 +9,7 @@ import { initializeDenBootstrapConfig } from "./app/lib/den";import { startWebErrorMonitoring } from "./app/lib/error-monitoring";import { getOmniRushDeployment } from "./app/lib/omnirush-deployment";import { bootstrapTheme } from "./app/theme";+import { restoreWallpaper } from "./app/wallpaper";import { isDesktopRuntime } from "./app/utils";import { initLocale } from "./i18n";import { getReactQueryClient } from "./react-app/infra/query-client";@@ -24,6 +25,7 @@ import "./app/index.css";startWebErrorMonitoring();bootstrapTheme();+void restoreWallpaper();initLocale();startDeepLinkBridge();await initializeDenBootstrapConfig();diff --git a/apps/app/src/react-app/domains/session/artifacts/artifact-code-view.tsx b/apps/app/src/react-app/domains/session/artifacts/artifact-code-view.tsxindex 56c14e74..c3cca092 100644--- a/apps/app/src/react-app/domains/session/artifacts/artifact-code-view.tsx+++ b/apps/app/src/react-app/domains/session/artifacts/artifact-code-view.tsx@@ -5,7 +5,7 @@ import { Editor } from "@pierre/diffs/edit";const OMNIRUSH_CODE_CSS = `:host {- --diffs-font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ --diffs-font-family: var(--omnirush-code-font, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);--diffs-font-size: 12px;--diffs-line-height: 20px;display: block;diff --git a/apps/app/src/react-app/domains/session/artifacts/artifact-text-editor.tsx b/apps/app/src/react-app/domains/session/artifacts/artifact-text-editor.tsxindex fc4482d9..be96c71c 100644--- a/apps/app/src/react-app/domains/session/artifacts/artifact-text-editor.tsx+++ b/apps/app/src/react-app/domains/session/artifacts/artifact-text-editor.tsx@@ -95,7 +95,7 @@ export function ArtifactTextEditor(props: ArtifactTextEditorProps) {}): EditorView.theme({"&": { height: "100%", background: "transparent" },- ".cm-scroller": { fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" },+ ".cm-scroller": { fontFamily: "var(--omnirush-code-font, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)" },".cm-content": { minHeight: "100%", padding: "12px 0", fontSize: "12px", lineHeight: "20px" },".cm-gutters": { background: "transparent", borderRight: "1px solid hsl(var(--border))" },".cm-lineNumbers .cm-gutterElement": { padding: "0 8px", color: "hsl(var(--muted-foreground))" },diff --git a/apps/app/src/react-app/domains/session/artifacts/markdown-live-preview.ts b/apps/app/src/react-app/domains/session/artifacts/markdown-live-preview.tsindex af9f4a29..5b694eed 100644--- a/apps/app/src/react-app/domains/session/artifacts/markdown-live-preview.ts+++ b/apps/app/src/react-app/domains/session/artifacts/markdown-live-preview.ts@@ -358,7 +358,7 @@ const livePreviewTheme = EditorView.baseTheme({".cm-md-emphasis": { fontStyle: "italic" },".cm-md-strike": { textDecoration: "line-through" },".cm-md-code": {- fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",+ fontFamily: "var(--omnirush-code-font, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)",backgroundColor: "hsl(var(--muted) / 0.6)",borderRadius: "4px",padding: "0.1em 0.3em",@@ -372,7 +372,7 @@ const livePreviewTheme = EditorView.baseTheme({},".cm-md-codeblock": {backgroundColor: "hsl(var(--muted) / 0.4)",- fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",+ fontFamily: "var(--omnirush-code-font, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace)",},".cm-md-bullet": { paddingRight: "0.4em", color: "hsl(var(--muted-foreground))" },// `contain: inline-size` keeps a wide table from stretching the editor (whichdiff --git a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx b/apps/app/src/react-app/domains/session/editor/editor-surface.tsxindex 47de1c2f..8436c970 100644--- a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx+++ b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx@@ -8,7 +8,7 @@import { useEffect, useRef, useState } from "react";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";-import { subscribeToTheme } from "@/app/theme";+import { getCodeFontStack, subscribeToTheme } from "@/app/theme";import { addGroupKeys, applyMonacoTheme, monacoThemeName, scopeEditor, type Monaco } from "./monaco";import type { FileDoc } from "./editor-models";import { hunkCounts, type LineHunk } from "./hunk-ops";@@ -54,7 +54,6 @@ export type SurfaceHandle = {const BASE_OPTIONS: MonacoApi.editor.IStandaloneEditorConstructionOptions = {automaticLayout: true,- fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",scrollBeyondLastLine: false,renderLineHighlight: "line",smoothScrolling: false,@@ -133,9 +132,10 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, naviif (!codeHostRef.current || !diffHostRef.current) return;const themeName = monacoThemeName();const settingsOptions = monacoOptionsFor(useEditorSettings.getState());- const code = monaco.editor.create(codeHostRef.current, { ...BASE_OPTIONS, ...settingsOptions, model: null, theme: themeName });+ const code = monaco.editor.create(codeHostRef.current, { ...BASE_OPTIONS, fontFamily: getCodeFontStack(), ...settingsOptions, model: null, theme: themeName });const diff = monaco.editor.createDiffEditor(diffHostRef.current, {...BASE_OPTIONS,+ fontFamily: getCodeFontStack(),...settingsOptions,theme: themeName,renderSideBySide: false,@@ -205,6 +205,9 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navi// Follows the app theme: light/dark, presets and custom themes (app/theme.ts).const unsubscribeTheme = subscribeToTheme(() => {applyMonacoTheme();+ // Monaco ignores an unchanged option, so this only re-lays out when the code font changed.+ code.updateOptions({ fontFamily: getCodeFontStack() });+ diff.updateOptions({ fontFamily: getCodeFontStack() });// Repaint now: a composited editor layer can otherwise keep the old background until it scrolls.code.render(true);diff.getModifiedEditor().render(true);diff --git a/apps/app/src/react-app/domains/session/editor/group2-editor.tsx b/apps/app/src/react-app/domains/session/editor/group2-editor.tsxindex 7b14c3ab..20ddfb2c 100644--- a/apps/app/src/react-app/domains/session/editor/group2-editor.tsx+++ b/apps/app/src/react-app/domains/session/editor/group2-editor.tsx@@ -5,6 +5,7 @@*/import { useEffect, useRef } from "react";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";+import { getCodeFontStack } from "@/app/theme";import { monacoOptionsFor, useEditorSettings } from "./editor-settings";import type { AgentAction } from "./editor-surface";@@ -29,7 +30,7 @@ export function Group2Editor(props: {const monaco = props.monaco;const editor = monaco.editor.create(host, {automaticLayout: true,- fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",+ fontFamily: getCodeFontStack(),scrollBeyondLastLine: false,renderLineHighlight: "line",padding: { top: 6, bottom: 6 },diff --git a/apps/app/src/react-app/domains/session/terminal/terminal-runtime.ts b/apps/app/src/react-app/domains/session/terminal/terminal-runtime.tsindex 0a7b1108..52f0096f 100644--- a/apps/app/src/react-app/domains/session/terminal/terminal-runtime.ts+++ b/apps/app/src/react-app/domains/session/terminal/terminal-runtime.ts@@ -5,7 +5,7 @@import { FitAddon } from "@xterm/addon-fit";import { Terminal } from "@xterm/xterm";import { create } from "zustand";-import { getActiveTheme, subscribeToTheme } from "@/app/theme";+import { getActiveTheme, getCodeFontStack, subscribeToTheme } from "@/app/theme";import { xtermThemeFor } from "@/app/themes/editor-themes";import { useTerminalTabsStore } from "./terminal-tabs-store";@@ -53,8 +53,11 @@ function followAppTheme() {themeSubscribed = true;subscribeToTheme(() => {const theme = xtermThemeFor(getActiveTheme());+ const fontFamily = getCodeFontStack();for (const entry of live.values()) {- if (!entry.disposed) entry.term.options.theme = theme;+ if (entry.disposed) continue;+ entry.term.options.theme = theme;+ if (entry.term.options.fontFamily !== fontFamily) entry.term.options.fontFamily = fontFamily;}});}@@ -90,7 +93,7 @@ function makeLive(tabId: string, bridge: TerminalBridge, options: Live["options"cursorBlink: true,convertEol: true,scrollback: 5000,- fontFamily: "'SFMono-Regular', 'Cascadia Code', 'Liberation Mono', Menlo, monospace",+ fontFamily: getCodeFontStack(),fontSize: 12,theme: xtermThemeFor(getActiveTheme()),});diff --git a/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx b/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsxindex d789926d..934c5afa 100644--- a/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx+++ b/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx@@ -208,8 +208,6 @@ export type CustomThemeEditorProps = {startedFrom: string;/** Whether Apply should be enabled without edits (new or imported theme). */unsavedFromStart: boolean;- /** Applying replaces an existing custom theme (one slot). */- replaces?: boolean;preferredMode: ThemeVariantMode;onPreview: (theme: CustomTheme) => void;onApply: (theme: CustomTheme) => void;@@ -430,7 +428,6 @@ export function CustomThemeEditor(props: CustomThemeEditorProps) {{changed > 0 ? ` · ${changed} colour${changed === 1 ? "" : "s"} changed in the ${mode} version` : ""}{changedOther > 0 ? ` · ${changedOther} in the ${otherMode} version` : ""}{allWarnings > 0 ? ` · ${allWarnings} contrast warning${allWarnings === 1 ? "" : "s"}` : ""}- {props.replaces ? " · Apply replaces your current custom theme" : ""}</span><Button variant="outline" size="sm" onClick={props.onRevert} data-testid="theme-revert">Revertdiff --git a/apps/app/src/react-app/domains/settings/appearance/customise-sections.tsx b/apps/app/src/react-app/domains/settings/appearance/customise-sections.tsxnew file mode 100644index 00000000..04af5c56--- /dev/null+++ b/apps/app/src/react-app/domains/settings/appearance/customise-sections.tsx@@ -0,0 +1,424 @@+/** @jsxImportSource react */+import { AlertTriangle, Check, ImagePlus, Trash2 } from "lucide-react";+import { useEffect, useId, useRef, useState, type ReactNode } from "react";+import { setAppearancePrefs } from "@/app/theme";+import {+ ACCENT_SWATCHES,+ CODE_FONTS,+ PANEL_BLUR_RANGE,+ PANEL_OPACITY_RANGE,+ UI_FONTS,+ WALLPAPER_DIM_RANGE,+ checkAccent,+ codeFontStack,+ normalizeHex,+ textOnAccent,+ uiFontStack,+ type AppearancePrefs,+} from "@/app/themes/appearance-prefs";+import { FONT_SIZE_RANGE, RADIUS_RANGE } from "@/app/themes/types";+import { removeWallpaper, setWallpaperFromFile, WALLPAPER_TYPES } from "@/app/wallpaper";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";+import { cn } from "@/lib/utils";+import {+ LayoutSectionItem,+ LayoutSectionItemDescription,+ LayoutSectionItemHeader,+ LayoutSectionItemTitle,+} from "../settings-layout";+import { useActiveTheme, useAppearancePrefs } from "./theme-state";++type SectionProps = { busy: boolean };++function Section(props: { title: string; description: string; children: ReactNode; testId: string }) {+ return (+ <LayoutSectionItem data-testid={props.testId}>+ <LayoutSectionItemHeader className="w-full">+ <LayoutSectionItemTitle>{props.title}</LayoutSectionItemTitle>+ <LayoutSectionItemDescription>{props.description}</LayoutSectionItemDescription>+ </LayoutSectionItemHeader>+ <div className="flex flex-col gap-1">{props.children}</div>+ </LayoutSectionItem>+ );+}++function Row(props: { label: string; htmlFor?: string; children: ReactNode }) {+ return (+ <div className="grid grid-cols-1 items-center gap-2 py-1.5 @md/settings:grid-cols-[9rem_1fr]">+ <label htmlFor={props.htmlFor} className="text-sm text-foreground">+ {props.label}+ </label>+ <div className="flex min-w-0 flex-wrap items-center gap-3">{props.children}</div>+ </div>+ );+}++/** A range input with its value and an optional "Theme default" reset. */+function Slider(props: {+ label: string;+ value: number;+ range: { min: number; max: number };+ unit: string;+ disabled: boolean;+ onChange: (value: number) => void;+ onReset?: () => void;+ resetLabel?: string;+ testId: string;+}) {+ const id = useId();+ return (+ <Row label={props.label} htmlFor={id}>+ <input+ id={id}+ type="range"+ min={props.range.min}+ max={props.range.max}+ step={1}+ value={props.value}+ disabled={props.disabled}+ onChange={(event) => props.onChange(Number(event.target.value))}+ className="w-44 accent-primary focus-visible:outline-2 focus-visible:outline-ring"+ data-testid={props.testId}+ />+ <span className="font-mono text-xs text-muted-foreground tabular-nums">+ {Math.round(props.value)}+ {props.unit}+ </span>+ {props.onReset ? (+ <Button variant="ghost" size="sm" onClick={props.onReset} disabled={props.disabled}>+ {props.resetLabel ?? "Reset"}+ </Button>+ ) : null}+ </Row>+ );+}++const ratio = (value: number) => `${value.toFixed(1)}:1`;++/** Accent colour: theme default, a swatch or any hex. Buttons, focus rings, selection and links follow it. */+export function AccentSection(props: SectionProps) {+ const prefs = useAppearancePrefs();+ const active = useActiveTheme();+ const [draft, setDraft] = useState(prefs.accent ?? "");+ const inputId = useId();+ useEffect(() => setDraft(prefs.accent ?? ""), [prefs.accent]);++ const setAccent = (accent: string | null) => setAppearancePrefs({ accent });+ const check = prefs.accent ? checkAccent(active.variant, prefs.accent) : null;+ const themeAccent = active.themeAccent ?? active.variant.accent;+ const pickerValue = prefs.accent ?? normalizeHex(themeAccent) ?? "#000000";++ const swatch = (label: string, hex: string | null, fill: string) => {+ const selected = prefs.accent === hex;+ return (+ <button+ key={label}+ type="button"+ role="radio"+ aria-checked={selected}+ aria-label={label}+ title={label}+ disabled={props.busy}+ onClick={() => setAccent(hex)}+ data-testid={`accent-${hex ?? "theme"}`}+ className={cn(+ "flex size-7 items-center justify-center rounded-full border border-border outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",+ selected && "ring-2 ring-foreground ring-offset-2 ring-offset-background",+ )}+ style={{ background: fill }}+ >+ {selected ? <Check className="size-3.5" style={{ color: textOnAccent(fill) }} /> : null}+ </button>+ );+ };++ return (+ <Section+ title="Accent colour"+ description="Colours buttons, selection, focus rings and links in every theme. Checked for contrast against the current theme."+ testId="appearance-accent"+ >+ <div role="radiogroup" aria-label="Accent colour" className="flex flex-wrap items-center gap-2 py-1">+ {swatch("Theme accent", null, themeAccent)}+ {ACCENT_SWATCHES.map((item) => swatch(item.name, item.hex, item.hex))}+ </div>+ <Row label="Custom colour" htmlFor={inputId}>+ <label className="relative size-7 shrink-0 overflow-hidden rounded-md border border-border" style={{ background: pickerValue }}>+ <input+ type="color"+ aria-label="Pick a custom accent colour"+ value={pickerValue}+ disabled={props.busy}+ onChange={(event) => setAccent(event.target.value.toLowerCase())}+ className="absolute inset-0 size-full cursor-pointer opacity-0"+ data-testid="accent-picker"+ />+ </label>+ <Input+ id={inputId}+ value={draft}+ placeholder="#3b6fe0"+ spellCheck={false}+ maxLength={7}+ disabled={props.busy}+ className="h-8 w-28 font-mono"+ aria-invalid={draft !== "" && !normalizeHex(draft)}+ onChange={(event) => {+ setDraft(event.target.value);+ const hex = normalizeHex(event.target.value);+ if (hex && event.target.value.replace("#", "").length === 6) setAccent(hex);+ }}+ onBlur={() => setDraft(prefs.accent ?? "")}+ data-testid="accent-hex"+ />+ </Row>+ {check && !check.ok ? (+ <div role="status" className="flex flex-wrap items-center gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs" data-testid="accent-warning">+ <AlertTriangle className="size-3.5 shrink-0 text-warning" />+ <span className="min-w-0 flex-1 text-foreground">+ {check.uiRatio < 3 ? `Hard to see on this theme: ${ratio(check.uiRatio)} (needs 3:1). ` : ""}+ {check.textRatio < 4.5 ? `Button text on it is ${ratio(check.textRatio)} (needs 4.5:1). ` : ""}+ Links already use a readable shade.+ </span>+ {check.suggestion ? (+ <Button size="sm" variant="outline" onClick={() => setAccent(check.suggestion)} data-testid="accent-use-suggestion">+ <span className="size-3 rounded-full border border-border" style={{ background: check.suggestion }} />+ Use {check.suggestion}+ </Button>+ ) : null}+ </div>+ ) : null}+ </Section>+ );+}++function FontSelect(props: {+ label: string;+ value: string;+ options: readonly { id: string; label: string }[];+ stackOf: (id: string) => string | undefined;+ disabled: boolean;+ onChange: (id: string) => void;+ testId: string;+}) {+ const items = props.options.map((option) => ({ value: option.id, label: option.label }));+ return (+ <Row label={props.label}>+ <div className="w-64 max-w-full">+ <Select value={props.value} items={items} onValueChange={(value) => value && props.onChange(value)} disabled={props.disabled}>+ <SelectTrigger className="w-full" aria-label={props.label} data-testid={props.testId}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {props.options.map((option) => (+ <SelectItem key={option.id} value={option.id} style={{ fontFamily: props.stackOf(option.id) }}>+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ </Row>+ );+}++/** Interface font, code font and text size. */+export function FontsSection(props: SectionProps) {+ const prefs = useAppearancePrefs();+ const active = useActiveTheme();+ const set = (patch: Partial<AppearancePrefs>) => setAppearancePrefs(patch);+ return (+ <Section+ title="Fonts and text"+ description="Pick the interface and code fonts separately. Named code fonts are used when installed on this computer."+ testId="appearance-fonts"+ >+ <FontSelect+ label="Interface font"+ value={prefs.uiFont}+ options={UI_FONTS}+ stackOf={(id) => uiFontStack({ uiFont: id as AppearancePrefs["uiFont"], codeFont: prefs.codeFont }) ?? undefined}+ disabled={props.busy}+ onChange={(id) => set({ uiFont: id as AppearancePrefs["uiFont"] })}+ testId="appearance-ui-font"+ />+ <FontSelect+ label="Code font"+ value={prefs.codeFont}+ options={CODE_FONTS}+ stackOf={(id) => codeFontStack({ codeFont: id as AppearancePrefs["codeFont"] })}+ disabled={props.busy}+ onChange={(id) => set({ codeFont: id as AppearancePrefs["codeFont"] })}+ testId="appearance-code-font"+ />+ <Slider+ label="Text size"+ value={prefs.fontSizePx ?? active.fontSizePx}+ range={FONT_SIZE_RANGE}+ unit=" px"+ disabled={props.busy}+ onChange={(fontSizePx) => set({ fontSizePx })}+ onReset={prefs.fontSizePx === null ? undefined : () => set({ fontSizePx: null })}+ resetLabel="Theme default"+ testId="appearance-text-size"+ />+ <p className="rounded-lg border border-border bg-muted/30 px-3 py-2 text-sm text-foreground" data-testid="appearance-font-sample">+ The agent replied: <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.92em]">npm run build</code> finished in 4.2 s.+ </p>+ </Section>+ );+}++/** Density and corner radius. */+export function LayoutLookSection(props: SectionProps) {+ const prefs = useAppearancePrefs();+ const active = useActiveTheme();+ return (+ <Section title="Layout" description="Spacing and how rounded panels, buttons and cards are." testId="appearance-layout">+ <Row label="Density">+ <ToggleGroup+ value={[prefs.density]}+ onValueChange={(value) => value[0] && setAppearancePrefs({ density: value[0] as AppearancePrefs["density"] })}+ disabled={props.busy}+ aria-label="Density"+ className="w-fit gap-0.5 rounded-lg border border-border bg-muted/40 p-0.5"+ >+ {(["comfortable", "compact"] as const).map((value) => (+ <ToggleGroupItem+ key={value}+ value={value}+ data-testid={`appearance-density-${value}`}+ className="h-7 rounded-md border border-transparent px-3 text-sm text-muted-foreground capitalize aria-pressed:border-foreground/70 aria-pressed:bg-background aria-pressed:font-medium aria-pressed:text-foreground aria-pressed:shadow-xs"+ >+ {value}+ </ToggleGroupItem>+ ))}+ </ToggleGroup>+ </Row>+ <Slider+ label="Corner radius"+ value={prefs.radiusPx ?? active.radiusPx}+ range={RADIUS_RANGE}+ unit=" px"+ disabled={props.busy}+ onChange={(radiusPx) => setAppearancePrefs({ radiusPx })}+ onReset={prefs.radiusPx === null ? undefined : () => setAppearancePrefs({ radiusPx: null })}+ resetLabel="Theme default"+ testId="appearance-radius"+ />+ </Section>+ );+}++function useReducedTransparency() {+ const query = "(prefers-reduced-transparency: reduce)";+ const [reduced, setReduced] = useState(() => typeof window !== "undefined" && window.matchMedia?.(query).matches === true);+ useEffect(() => {+ const list = window.matchMedia?.(query);+ if (!list) return;+ const onChange = () => setReduced(list.matches);+ list.addEventListener?.("change", onChange);+ return () => list.removeEventListener?.("change", onChange);+ }, []);+ return reduced;+}++/** A picture behind the window, how much it is dimmed, and how see-through the panels over it are. */+export function WallpaperSection(props: SectionProps) {+ const prefs = useAppearancePrefs();+ const reduced = useReducedTransparency();+ const fileRef = useRef<HTMLInputElement>(null);+ const [error, setError] = useState<string | null>(null);+ const [working, setWorking] = useState(false);++ const choose = async (file: File | undefined) => {+ if (!file) return;+ setWorking(true);+ setError(null);+ try {+ await setWallpaperFromFile(file);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "That image could not be used.");+ } finally {+ setWorking(false);+ if (fileRef.current) fileRef.current.value = "";+ }+ };++ return (+ <Section+ title="Wallpaper"+ description="Put a picture of your own behind the workspace. It stays on this computer."+ testId="appearance-wallpaper"+ >+ <div className="flex flex-wrap items-center gap-2 py-1">+ <input+ ref={fileRef}+ type="file"+ accept={WALLPAPER_TYPES.join(",")}+ className="hidden"+ onChange={(event) => void choose(event.target.files?.[0])}+ data-testid="wallpaper-file"+ />+ <Button size="sm" variant="outline" disabled={props.busy || working} onClick={() => fileRef.current?.click()} data-testid="wallpaper-choose">+ <ImagePlus className="size-3.5" />+ {prefs.wallpaper ? "Change image…" : "Choose image…"}+ </Button>+ {prefs.wallpaper ? (+ <Button size="sm" variant="ghost" disabled={props.busy || working} onClick={() => void removeWallpaper()} data-testid="wallpaper-remove">+ <Trash2 className="size-3.5" />+ Remove+ </Button>+ ) : (+ <span className="text-xs text-muted-foreground">PNG, JPEG, WebP, AVIF or GIF, up to 8 MB.</span>+ )}+ </div>+ {error ? (+ <p role="alert" className="text-xs text-destructive" data-testid="wallpaper-error">+ {error}+ </p>+ ) : null}+ {prefs.wallpaper ? (+ <>+ <Slider+ label="Dim picture"+ value={prefs.wallpaperDim}+ range={WALLPAPER_DIM_RANGE}+ unit="%"+ disabled={props.busy}+ onChange={(wallpaperDim) => setAppearancePrefs({ wallpaperDim })}+ testId="wallpaper-dim"+ />+ <Slider+ label="Panel opacity"+ value={reduced ? 100 : prefs.panelOpacity}+ range={PANEL_OPACITY_RANGE}+ unit="%"+ disabled={props.busy || reduced}+ onChange={(panelOpacity) => setAppearancePrefs({ panelOpacity })}+ testId="wallpaper-opacity"+ />+ <Slider+ label="Sidebar blur"+ value={reduced ? 0 : prefs.panelBlur}+ range={PANEL_BLUR_RANGE}+ unit=" px"+ disabled={props.busy || reduced}+ onChange={(panelBlur) => setAppearancePrefs({ panelBlur })}+ testId="wallpaper-blur"+ />+ {reduced ? (+ <p className="text-xs text-muted-foreground" data-testid="wallpaper-reduced">+ Your system asks for less transparency, so panels stay solid and nothing is blurred.+ </p>+ ) : null}+ </>+ ) : null}+ </Section>+ );+}diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsxindex 0a9cdc8b..ec20b09f 100644--- a/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx+++ b/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx@@ -1,10 +1,11 @@/** @jsxImportSource react */-import { Check, Moon, Pencil, Plus } from "lucide-react";+import { Check, Moon, Pencil, Plus, Trash2 } from "lucide-react";import type { ReactNode } from "react";import { cn } from "@/lib/utils";import { THEME_PRESETS } from "@/app/themes/presets";import { presetModes } from "@/app/themes/palette";-import type { CustomTheme, ThemeVariant } from "@/app/themes/types";+import type { SavedCustomTheme } from "@/app/theme";+import type { ThemeVariant } from "@/app/themes/types";import {LayoutSectionItem,LayoutSectionItemDescription,@@ -15,13 +16,15 @@ import { ThemeVariantThumb } from "./theme-preview";type Props = {busy: boolean;- /** Selected preset id, or "custom" for My theme. */+ /** Selected preset id, or `custom:<id>` for a saved custom theme. */selectedId: string;- customTheme: CustomTheme | null;+ customThemes: SavedCustomTheme[];+ maxCustomThemes: number;note: string | null;onPickPreset: (id: string) => void;- onPickCustom: () => void;- onEditCustom: () => void;+ onPickCustom: (id: string) => void;+ onEditCustom: (id: string) => void;+ onDeleteCustom: (id: string) => void;onNewCustom: () => void;};@@ -106,40 +109,54 @@ export function ThemePresetsSection(props: Props) {<Thumbs light={preset.variants.light} dark={preset.variants.dark} /></Card>))}- {props.customTheme ? (+ {props.customThemes.map(({ id, theme }) => (<Card- testId="theme-preset-custom"- selected={props.selectedId === "custom"}- label={props.customTheme.name}- meta={modesLabel(props.customTheme.modes)}+ key={id}+ testId={`theme-custom-${id}`}+ selected={props.selectedId === `custom:${id}`}+ label={theme.name}+ meta={modesLabel(theme.modes)}disabled={props.busy}- onClick={props.onPickCustom}+ onClick={() => props.onPickCustom(id)}action={- <button- type="button"- onClick={props.onEditCustom}- aria-label="Edit custom theme"- data-testid="theme-edit-custom"- className="absolute right-3 top-3 flex size-6 items-center justify-center rounded-md border border-border bg-popover text-foreground shadow-xs hover:bg-muted"- >- <Pencil className="size-3" />- </button>+ <div className="absolute right-3 top-3 flex gap-1">+ <button+ type="button"+ onClick={() => props.onEditCustom(id)}+ aria-label={`Edit ${theme.name}`}+ data-testid={`theme-edit-${id}`}+ className="flex size-6 items-center justify-center rounded-md border border-border bg-popover text-foreground shadow-xs outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Pencil className="size-3" />+ </button>+ <button+ type="button"+ onClick={() => props.onDeleteCustom(id)}+ aria-label={`Delete ${theme.name}`}+ data-testid={`theme-delete-${id}`}+ className="flex size-6 items-center justify-center rounded-md border border-border bg-popover text-foreground shadow-xs outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Trash2 className="size-3" />+ </button>+ </div>}>- <Thumbs light={props.customTheme.light} dark={props.customTheme.dark} />+ <Thumbs light={theme.light} dark={theme.dark} /></Card>- ) : null}+ ))}<buttontype="button"onClick={props.onNewCustom}- disabled={props.busy}+ disabled={props.busy || props.customThemes.length >= props.maxCustomThemes}data-testid="theme-new-custom"className="flex flex-col gap-2 rounded-xl border border-dashed border-border p-1.5 text-left text-xs text-muted-foreground outline-none hover:border-foreground/25 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"><span className="flex h-16 w-full items-center justify-center rounded-lg border border-dashed border-border"><Plus className="size-4" /></span>- <span className="px-1 pb-0.5 font-medium">{props.customTheme && props.selectedId === "custom" ? "Edit custom theme" : "New custom theme"}</span>+ <span className="px-1 pb-0.5 font-medium">+ {props.customThemes.length >= props.maxCustomThemes ? `Up to ${props.maxCustomThemes} custom themes` : "New custom theme"}+ </span></button></div><p className="flex items-center gap-1.5 text-xs text-muted-foreground" data-testid="theme-mode-note" role="status">diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsxindex 857707b8..20f2f4a0 100644--- a/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx+++ b/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx@@ -49,7 +49,7 @@ export function themeContrastSummary(theme: CustomTheme) {return { checked, failing };}-function ImportPreviewCard(props: Pick<Props, "onKeep" | "onEditFirst" | "onCancelImport"> & { theme: CustomTheme; source: string; replaces: boolean }) {+function ImportPreviewCard(props: Pick<Props, "onKeep" | "onEditFirst" | "onCancelImport"> & { theme: CustomTheme; source: string }) {const summary = themeContrastSummary(props.theme);const modes = props.theme.modes.join(" + ");return (@@ -109,7 +109,7 @@ function ImportPreviewCard(props: Pick<Props, "onKeep" | "onEditFirst" | "onCancCancel</Button></div>- {props.replaces ? <p className="text-xs text-muted-foreground">Keeping it replaces your current custom theme.</p> : null}+ <p className="text-xs text-muted-foreground">Keeping it adds it to your custom themes.</p></div>);}@@ -274,7 +274,6 @@ export function ThemeShareSection(props: Props) {<ImportPreviewCardtheme={props.importing.theme}source={props.importing.source}- replaces={Boolean(props.customTheme)}onKeep={props.onKeep}onEditFirst={props.onEditFirst}onCancelImport={props.onCancelImport}diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-state.ts b/apps/app/src/react-app/domains/settings/appearance/theme-state.tsindex fb9d9b04..eae17a36 100644--- a/apps/app/src/react-app/domains/settings/appearance/theme-state.ts+++ b/apps/app/src/react-app/domains/settings/appearance/theme-state.ts@@ -2,7 +2,9 @@ import { useSyncExternalStore } from "react";import { captureAnalyticsEvent } from "@/app/lib/analytics";import {getActiveTheme,- getCustomTheme,+ getAppearancePrefs,+ getCustomThemes,+ getSelectedCustomId,getThemeSelection,subscribeToTheme,type ThemeMode,@@ -18,8 +20,16 @@ export function useThemeSelection() {return useSyncExternalStore(subscribeToTheme, getThemeSelection, getThemeSelection);}-export function useSavedCustomTheme() {- return useSyncExternalStore(subscribeToTheme, getCustomTheme, getCustomTheme);+export function useCustomThemes() {+ return useSyncExternalStore(subscribeToTheme, getCustomThemes, getCustomThemes);+}++export function useSelectedCustomId() {+ return useSyncExternalStore(subscribeToTheme, getSelectedCustomId, getSelectedCustomId);+}++export function useAppearancePrefs() {+ return useSyncExternalStore(subscribeToTheme, getAppearancePrefs, getAppearancePrefs);}/**diff --git a/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx b/apps/app/src/react-app/domains/settings/pages/appearance-view.tsxindex 4699fc0d..d15c6eb9 100644--- a/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx@@ -4,6 +4,8 @@ import { isDesktopRuntime } from "@/app/utils";import type { Language } from "@/i18n";import { Separator } from "@/components/ui/separator";import {+ deleteCustomTheme,+ MAX_CUSTOM_THEMES,modeSwitchFor,saveCustomTheme,setThemePreview,@@ -12,6 +14,7 @@ import {import { findPreset, presetModes } from "@/app/themes/palette";import type { CustomTheme } from "@/app/themes/types";import { CustomThemeEditor } from "../appearance/custom-theme-editor";+import { AccentSection, FontsSection, LayoutLookSection, WallpaperSection } from "../appearance/customise-sections";import { LanguageSection } from "../appearance/language-section";import { ThemePresetsSection } from "../appearance/theme-presets-section";import { ThemeSection } from "../appearance/theme-section";@@ -21,7 +24,8 @@ import {presetName,trackThemeChanged,useActiveTheme,- useSavedCustomTheme,+ useCustomThemes,+ useSelectedCustomId,useThemeSelection,} from "../appearance/theme-state";import { WindowSection } from "../appearance/window-section";@@ -37,11 +41,16 @@ export type AppearanceViewProps = {toggleHideTitlebar: () => void;};-type EditorState = { initial: CustomTheme; startedFrom: string; unsavedFromStart: boolean; key: number };+/** `id` is the saved custom theme being edited, or null for a new one. */+type EditorState = { initial: CustomTheme; startedFrom: string; unsavedFromStart: boolean; key: number; id: string | null };export function AppearanceView(props: AppearanceViewProps) {const selection = useThemeSelection();- const customTheme = useSavedCustomTheme();+ const customThemes = useCustomThemes();+ const selectedCustomId = useSelectedCustomId();+ const selectedCustom = customThemes.find((item) => item.id === selectedCustomId) ?? null;+ /** The theme Share offers: the one in use, else the first saved one. */+ const customTheme = (selectedCustom ?? customThemes[0])?.theme ?? null;const active = useActiveTheme();const [editor, setEditor] = useState<EditorState | null>(null);const [importing, setImporting] = useState<{ theme: CustomTheme; source: string } | null>(null);@@ -50,7 +59,7 @@ export function AppearanceView(props: AppearanceViewProps) {// Leaving Appearance ends any unsaved preview.useEffect(() => () => setThemePreview(null), []);- const selectedId = selection.kind === "custom" ? "custom" : selection.id;+ const selectedId = selectedCustomId ? `custom:${selectedCustomId}` : selection.kind === "preset" ? selection.id : "default";/** Single-mode themes (Midnight) switch Mode instead of silently showing the other mode. */const followModes = (name: string, modes: readonly ("light" | "dark")[]) => {@@ -79,39 +88,57 @@ export function AppearanceView(props: AppearanceViewProps) {trackThemeChanged({ kind: "preset", preset: id, mode });};- const pickCustom = () => {- if (!customTheme) return;+ const pickCustom = (id: string) => {+ const saved = customThemes.find((item) => item.id === id);+ if (!saved) return;closeEditing();- const mode = followModes(customTheme.name, customTheme.modes);- setThemeSelection({ kind: "custom" });+ const mode = followModes(saved.theme.name, saved.theme.modes);+ setThemeSelection({ kind: "custom", id });trackThemeChanged({ kind: "custom", mode });};- const openEditor = (initial: CustomTheme, startedFrom: string, unsavedFromStart: boolean) => {+ const openEditor = (initial: CustomTheme, startedFrom: string, unsavedFromStart: boolean, id: string | null = null) => {setImporting(null);- setEditor({ initial, startedFrom, unsavedFromStart, key: Date.now() });+ setEditor({ initial, startedFrom, unsavedFromStart, key: Date.now(), id });setThemePreview(initial);};- const editCustom = () => {- if (customTheme) openEditor(customTheme, "your saved theme", false);+ const editCustom = (id: string) => {+ const saved = customThemes.find((item) => item.id === id);+ if (saved) openEditor(saved.theme, `“${saved.theme.name}”`, false, id);};+ /** A new theme starts as a copy of what is in use (a preset or a custom theme). */const newCustom = () => {- if (customTheme && selection.kind === "custom") {- editCustom();+ if (selectedCustom) {+ const copy = { ...selectedCustom.theme, name: `${selectedCustom.theme.name} copy`.slice(0, 40) };+ openEditor(copy, `“${selectedCustom.theme.name}”`, true);return;}const baseId = selection.kind === "preset" ? selection.id : "default";const preset = findPreset(baseId) ?? findPreset("default")!;- openEditor(customThemeFromPreset(preset), presetName(preset.id), true);+ const name = customThemes.length ? `My theme ${customThemes.length + 1}` : "My theme";+ openEditor(customThemeFromPreset(preset, name), presetName(preset.id), true);};- const keepTheme = (theme: CustomTheme) => {- saveCustomTheme(theme);+ const deleteCustom = (id: string) => {+ const saved = customThemes.find((item) => item.id === id);+ if (!saved || !window.confirm(`Delete the theme “${saved.theme.name}”? This cannot be undone.`)) return;+ if (editor?.id === id) closeEditing();+ deleteCustomTheme(id);+ };++ const keepTheme = (theme: CustomTheme, id: string | null) => {+ let savedId: string;+ try {+ savedId = saveCustomTheme(theme, id ?? undefined);+ } catch (cause) {+ setNote(cause instanceof Error ? cause.message : "The theme could not be saved.");+ return;+ }setThemePreview(null);const mode = followModes(theme.name, theme.modes);- setThemeSelection({ kind: "custom" });+ setThemeSelection({ kind: "custom", id: savedId });trackThemeChanged({ kind: "custom", mode });setEditor(null);setImporting(null);@@ -124,11 +151,13 @@ export function AppearanceView(props: AppearanceViewProps) {<ThemePresetsSectionbusy={props.busy}selectedId={selectedId}- customTheme={customTheme}+ customThemes={customThemes}+ maxCustomThemes={MAX_CUSTOM_THEMES}note={note}onPickPreset={pickPreset}onPickCustom={pickCustom}onEditCustom={editCustom}+ onDeleteCustom={deleteCustom}onNewCustom={newCustom}/>{editor ? (@@ -139,15 +168,22 @@ export function AppearanceView(props: AppearanceViewProps) {initial={editor.initial}startedFrom={editor.startedFrom}unsavedFromStart={editor.unsavedFromStart}- replaces={Boolean(customTheme) && editor.unsavedFromStart}preferredMode={active.mode}onPreview={(theme) => setThemePreview(theme)}- onApply={keepTheme}+ onApply={(theme) => keepTheme(theme, editor.id)}onRevert={closeEditing}/></>) : null}<Separator />+ <AccentSection busy={props.busy} />+ <Separator />+ <FontsSection busy={props.busy} />+ <Separator />+ <LayoutLookSection busy={props.busy} />+ <Separator />+ <WallpaperSection busy={props.busy} />+ <Separator /><ThemeShareSectioncustomTheme={customTheme}importing={importing}@@ -156,7 +192,7 @@ export function AppearanceView(props: AppearanceViewProps) {setImporting({ theme, source });setThemePreview(theme);}}- onKeep={() => importing && keepTheme(importing.theme)}+ onKeep={() => importing && keepTheme(importing.theme, null)}onEditFirst={() => importing && openEditor(importing.theme, importing.source, true)}onCancelImport={closeEditing}/>diff --git a/apps/app/src/react-app/domains/whats-new/PARITY.sha256 b/apps/app/src/react-app/domains/whats-new/PARITY.sha256index 5c3e5171..383e9a34 100644--- a/apps/app/src/react-app/domains/whats-new/PARITY.sha256+++ b/apps/app/src/react-app/domains/whats-new/PARITY.sha256@@ -1,3 +1,3 @@# whats-new.json is the same file in omnirush-cli (src/whats-new/) and omnirush-gui (apps/app/src/react-app/domains/whats-new/).# A change to one must be ported to the other and this list updated in both.-d07c2529276cface3f64118e169f42fb4a8e7bb3b11c1df9d9cc477f16ae1ea4 whats-new.json+3d7dd92963d27e842d8bbd0d077b33c5d7d5cee322d82955cb9ceaa2c43875b2 whats-new.jsondiff --git a/apps/app/src/react-app/domains/whats-new/whats-new.json b/apps/app/src/react-app/domains/whats-new/whats-new.jsonindex 1ac84ab3..36237799 100644--- a/apps/app/src/react-app/domains/whats-new/whats-new.json+++ b/apps/app/src/react-app/domains/whats-new/whats-new.json@@ -242,6 +242,19 @@}],"desktop": [+ {+ "version": "3.7.4",+ "date": "2026-10-22",+ "new": [+ "More ways to make the app yours in Settings > Appearance: three new themes (Graphite, Paper and Nocturne), an accent colour of your choice on any theme, separate interface and code fonts, compact spacing, and your own corner radius and text size.",+ "Wallpaper: put a picture of your own behind the workspace, dim it, and choose how see-through and blurred the panels over it are. Panels stay solid when your computer is set to reduce transparency."+ ],+ "improved": [+ "Keep up to 20 custom themes, each with its own name, instead of one. Pick, edit, delete, share or import each of them.",+ "The accent colour is checked for contrast: you see a warning and a nearby readable colour when buttons or focus rings would be hard to see."+ ],+ "fixed": []+ },{"version": "3.7.3","date": "2026-10-22",diff --git a/apps/app/tests/appearance-prefs.test.ts b/apps/app/tests/appearance-prefs.test.tsnew file mode 100644index 00000000..3208650f--- /dev/null+++ b/apps/app/tests/appearance-prefs.test.ts@@ -0,0 +1,363 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ ACCENT_SWATCHES,+ DEFAULT_APPEARANCE_PREFS,+ MAX_PREFS_BYTES,+ checkAccent,+ codeFontStack,+ normalizeHex,+ parseAppearancePrefs,+ sanitizeAppearancePrefs,+ textOnAccent,+ uiFontStack,+ withAccent,+} from "../src/app/themes/appearance-prefs";+import { contrastRatio } from "../src/app/themes/contrast";+import { findPreset, presetModes, resetAppliedPaletteForTests } from "../src/app/themes/palette";+import { THEME_PRESETS } from "../src/app/themes/presets";+import type { CustomTheme } from "../src/app/themes/types";+import { checkWallpaperFile, MAX_WALLPAPER_BYTES } from "../src/app/wallpaper";++const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;++class MemoryStorage {+ values = new Map<string, string>();+ getItem(key: string) {+ return this.values.get(key) ?? null;+ }+ setItem(key: string, value: string) {+ this.values.set(key, String(value));+ }+ removeItem(key: string) {+ this.values.delete(key);+ }+}++/** A fake window/document for app/theme.ts; `reduced` answers the reduce-transparency query. */+function fakeWindow() {+ const storage = new MemoryStorage();+ const props = new Map<string, string>();+ const state = { reduced: false };+ const root = {+ dataset: {} as Record<string, string>,+ style: {+ colorScheme: "",+ setProperty: (name: string, value: string) => void props.set(name, value),+ removeProperty: (name: string) => {+ props.delete(name);+ return "";+ },+ getPropertyValue: (name: string) => props.get(name) ?? "",+ },+ };+ const install = () => {+ storage.values.clear();+ props.clear();+ root.dataset = {};+ state.reduced = false;+ Object.defineProperty(globalThis, "window", {+ configurable: true,+ value: {+ localStorage: storage,+ matchMedia: (query: string) => ({+ matches: query.includes("reduced-transparency") ? state.reduced : false,+ addEventListener: () => undefined,+ removeEventListener: () => undefined,+ }),+ },+ });+ Object.defineProperty(globalThis, "document", { configurable: true, value: { documentElement: root } });+ };+ const remove = () => {+ delete (globalThis as Record<string, unknown>).window;+ delete (globalThis as Record<string, unknown>).document;+ };+ return { storage, props, root, state, install, remove };+}++describe("appearance prefs validation", () => {+ test("malformed, oversized or non-object input gives the defaults", () => {+ expect(parseAppearancePrefs(null)).toEqual({ ...DEFAULT_APPEARANCE_PREFS });+ expect(parseAppearancePrefs("{not json")).toEqual({ ...DEFAULT_APPEARANCE_PREFS });+ expect(parseAppearancePrefs("[1,2]")).toEqual({ ...DEFAULT_APPEARANCE_PREFS });+ expect(parseAppearancePrefs("null")).toEqual({ ...DEFAULT_APPEARANCE_PREFS });+ const big = JSON.stringify({ accent: "#123456", pad: "x".repeat(MAX_PREFS_BYTES) });+ expect(parseAppearancePrefs(big)).toEqual({ ...DEFAULT_APPEARANCE_PREFS });+ });++ test("each field is checked on its own; unknown keys are dropped", () => {+ const prefs = sanitizeAppearancePrefs({+ accent: "red;}body{x}",+ uiFont: "Comic Sans",+ codeFont: "jetbrains",+ density: "tiny",+ radiusPx: 99,+ fontSizePx: "14",+ wallpaper: "yes",+ wallpaperDim: -5,+ panelOpacity: 10,+ panelBlur: 1e9,+ extra: "x",+ });+ expect(prefs).toEqual({+ accent: null,+ uiFont: "system",+ codeFont: "jetbrains",+ density: "comfortable",+ radiusPx: 16,+ fontSizePx: null,+ wallpaper: false,+ wallpaperDim: 0,+ panelOpacity: 55,+ panelBlur: 24,+ });+ });++ test("hex colours are normalised", () => {+ expect(normalizeHex("#ABC")).toBe("#aabbcc");+ expect(normalizeHex(" 3b6fe0 ")).toBe("#3b6fe0");+ expect(normalizeHex("#3b6fe0ff")).toBeNull();+ expect(normalizeHex("url(x)")).toBeNull();+ expect(normalizeHex(42)).toBeNull();+ });++ test("font stacks come from fixed lists only", () => {+ expect(uiFontStack({ uiFont: "system", codeFont: "system" })).toBeNull();+ expect(uiFontStack({ uiFont: "geist", codeFont: "system" })).toContain('"Geist Variable"');+ expect(uiFontStack({ uiFont: "mono", codeFont: "fira" })).toBe(codeFontStack({ codeFont: "fira" }));+ expect(codeFontStack({ codeFont: "nope" as never })).toContain("monospace");+ });+});++describe("accent contrast", () => {+ const light = findPreset("default")!.variants.light!;+ const dark = findPreset("default")!.variants.dark!;++ test("button text is whichever of black and white reads better", () => {+ expect(textOnAccent("#3b6fe0")).toBe("#ffffff");+ expect(textOnAccent("#ffe066")).toBe("#000000");+ const v = withAccent(light, "#3b6fe0");+ expect(v.accent).toBe("#3b6fe0");+ expect(v.accentText).toBe("#ffffff");+ expect(withAccent(light, null)).toBe(light);+ });++ test("every swatch passes on Default light, and its button text passes in dark", () => {+ for (const swatch of ACCENT_SWATCHES) {+ expect({ swatch: swatch.name, ok: checkAccent(light, swatch.hex).ok }).toEqual({ swatch: swatch.name, ok: true });+ expect(checkAccent(dark, swatch.hex).textRatio).toBeGreaterThanOrEqual(4.5);+ }+ });++ test("a faint accent is flagged with a fix that passes both checks", () => {+ for (const [variant, accent] of [+ [light, "#ffe066"],+ [light, "#f0f0f0"],+ [dark, "#202022"],+ [dark, "#3a3a8a"],+ ] as const) {+ const check = checkAccent(variant, accent);+ expect(check.ok).toBe(false);+ expect(check.suggestion).not.toBeNull();+ expect(checkAccent(variant, check.suggestion!).ok).toBe(true);+ expect(contrastRatio(textOnAccent(check.suggestion!), check.suggestion!)).toBeGreaterThanOrEqual(4.5);+ }+ });++ test("the fix works on every preset", () => {+ for (const preset of THEME_PRESETS) {+ for (const mode of presetModes(preset)) {+ const variant = preset.variants[mode]!;+ const check = checkAccent(variant, mode === "dark" ? "#1a1a1a" : "#fafafa");+ const fixed = check.ok || Boolean(check.suggestion && checkAccent(variant, check.suggestion).ok);+ expect({ id: `${preset.id}/${mode}`, fixed }).toEqual({ id: `${preset.id}/${mode}`, fixed: true });+ }+ }+ });+});++describe("wallpaper file check", () => {+ test("only pictures under 8 MB", () => {+ expect(checkWallpaperFile({ type: "image/png", size: 1000 })).toBeNull();+ expect(checkWallpaperFile({ type: "image/webp", size: MAX_WALLPAPER_BYTES })).toBeNull();+ expect(checkWallpaperFile({ type: "image/png", size: MAX_WALLPAPER_BYTES + 1 })).toContain("8 MB");+ expect(checkWallpaperFile({ type: "image/svg+xml", size: 10 })).not.toBeNull();+ expect(checkWallpaperFile({ type: "text/html", size: 10 })).not.toBeNull();+ expect(checkWallpaperFile({ type: "image/png", size: 0 })).not.toBeNull();+ });+});++describe("prefs applied to the window", () => {+ const fake = fakeWindow();+ const { storage, props, root } = fake;+ let theme: typeof import("../src/app/theme");++ beforeEach(async () => {+ fake.install();+ theme = await import("../src/app/theme");+ theme.resetThemeStateForTests();+ resetAppliedPaletteForTests();+ });+ afterEach(fake.remove);++ test("an accent drives buttons, focus rings and links on Default and on a preset", () => {+ theme.bootstrapTheme();+ theme.setAppearancePrefs({ accent: "#d52d86" });+ expect(props.get("--primary")).toBe("#d52d86");+ expect(props.get("--ring")).toBe("#d52d86");+ expect(props.get("--primary-foreground")).toBe("#ffffff");+ expect(theme.getActiveTheme().legacy).toBe(true);+ const link = props.get("--omnirush-link")!;+ expect(contrastRatio(link, findPreset("default")!.variants.light!.background)).toBeGreaterThanOrEqual(4.5);+ theme.setThemeSelection({ kind: "preset", id: "paper" });+ expect(props.get("--primary")).toBe("#d52d86");+ expect(theme.getActiveTheme().themeAccent).toBe(findPreset("paper")!.variants.light!.accent);+ theme.setAppearancePrefs({ accent: null });+ expect(props.get("--primary")).toBe(findPreset("paper")!.variants.light!.accent);+ expect(JSON.parse(storage.getItem("omnirush.react.settings.appearance")!).accent).toBeNull();+ });++ test("radius and text size override the theme; null follows it again", () => {+ theme.bootstrapTheme();+ theme.setAppearancePrefs({ radiusPx: 2, fontSizePx: 15 });+ expect(props.get("--radius")).toBe("2px");+ expect(props.get("--omnirush-theme-font-scale")).toBe(String(Math.round((15 / 13) * 10000) / 10000));+ theme.setAppearancePrefs({ radiusPx: null, fontSizePx: null });+ expect(props.has("--radius")).toBe(false);+ expect(props.has("--omnirush-theme-font-scale")).toBe(false);+ });++ test("density, fonts and wallpaper reach <html> and the boot copy; switching off removes them", () => {+ theme.bootstrapTheme();+ theme.setAppearancePrefs({+ density: "compact",+ uiFont: "serif",+ codeFont: "jetbrains",+ wallpaper: true,+ panelOpacity: 70,+ wallpaperDim: 40,+ panelBlur: 8,+ });+ expect(root.dataset.density).toBe("compact");+ expect(root.dataset.wallpaper).toBe("on");+ expect(props.get("--omnirush-ui-font")).toContain("Charter");+ expect(props.get("--omnirush-code-font")).toContain('"JetBrains Mono"');+ expect(props.get("--omnirush-panel-blur")).toBe("8px");+ const bg = findPreset("default")!.variants.light!.background;+ expect(props.get("--background")).toBe(`${bg}b3`);+ expect(props.get("--omnirush-wallpaper-wash")).toBe(`${bg}66`);+ const boot = theme.readBootVars(storage.getItem(theme.THEME_BOOT_KEY), "light")!;+ expect(boot.attrs).toEqual({ density: "compact", wallpaper: "on" });+ expect(boot.vars["--omnirush-code-font"]).toContain("JetBrains");+ expect(boot.vars["--background"]).toBe(`${bg}b3`);+ theme.setAppearancePrefs({ density: "comfortable", uiFont: "system", codeFont: "system", wallpaper: false });+ expect(root.dataset.density).toBeUndefined();+ expect(root.dataset.wallpaper).toBeUndefined();+ expect(props.size).toBe(0);+ });++ test("reduce transparency keeps panels solid and drops the blur", () => {+ fake.state.reduced = true;+ theme.bootstrapTheme();+ theme.setAppearancePrefs({ wallpaper: true, panelOpacity: 60 });+ const bg = findPreset("default")!.variants.light!.background;+ expect(props.get("--background")).toBe(`${bg}ff`);+ expect(props.has("--omnirush-panel-blur")).toBe(false);+ });++ test("an edit preview shows the theme as it is, without the accent override", () => {+ theme.bootstrapTheme();+ theme.setAppearancePrefs({ accent: "#21865a" });+ const custom: CustomTheme = { v: 1, name: "P", modes: ["light"], light: clone(findPreset("rose")!.variants.light!), radiusPx: 4, fontSizePx: 13 };+ theme.setThemePreview(custom);+ expect(props.get("--primary")).toBe(custom.light!.accent);+ theme.setThemePreview(null);+ expect(props.get("--primary")).toBe("#21865a");+ });++ test("boot values with anything but plain names are refused", () => {+ const raw = JSON.stringify({+ only: "light",+ light: {},+ attrs: { density: "compact", wallpaper: "on;x", theme: "dark" },+ fonts: { "--omnirush-ui-font": 'x; background: url("http://e")', "--omnirush-code-font": '"Fira Code", monospace', "--other": "Arial" },+ });+ expect(theme.readBootVars(raw, "light")).toEqual({+ mode: "light",+ vars: { "--omnirush-code-font": '"Fira Code", monospace' },+ attrs: { density: "compact" },+ });+ });+});++describe("several custom themes", () => {+ const fake = fakeWindow();+ const { storage, props, root } = fake;+ let theme: typeof import("../src/app/theme");+ const make = (name: string, from = "forest"): CustomTheme => ({+ v: 1,+ name,+ modes: ["light"],+ light: clone(findPreset(from)!.variants.light!),+ radiusPx: 6,+ fontSizePx: 13,+ });++ beforeEach(async () => {+ fake.install();+ theme = await import("../src/app/theme");+ theme.resetThemeStateForTests();+ resetAppliedPaletteForTests();+ });+ afterEach(fake.remove);++ test("named themes are kept, selected by id, updated in place and deleted", () => {+ theme.bootstrapTheme();+ const a = theme.saveCustomTheme(make("Alpha"));+ const b = theme.saveCustomTheme(make("Beta", "sol"));+ expect(a).not.toBe(b);+ theme.setThemeSelection({ kind: "custom", id: b });+ expect(storage.getItem(theme.THEME_PRESET_KEY)).toBe(`custom:${b}`);+ expect(props.get("--background")).toBe(findPreset("sol")!.variants.light!.background);+ expect(theme.saveCustomTheme(make("Beta 2", "rose"), b)).toBe(b);+ expect(theme.getCustomThemes().map((item) => item.theme.name)).toEqual(["Alpha", "Beta 2"]);+ theme.resetThemeStateForTests();+ theme.bootstrapTheme();+ expect(theme.getSelectedCustomId()).toBe(b);+ expect(theme.getCustomTheme()!.name).toBe("Beta 2");+ theme.deleteCustomTheme(b);+ expect(theme.getThemeSelection()).toEqual({ kind: "preset", id: "default" });+ expect(theme.getCustomThemes().map((item) => item.id)).toEqual([a]);+ });++ test("the limit is enforced", () => {+ for (let i = 0; i < theme.MAX_CUSTOM_THEMES; i += 1) theme.saveCustomTheme(make(`T${i}`));+ expect(() => theme.saveCustomTheme(make("one more"))).toThrow(/up to 20/);+ });++ test("the single theme of older builds becomes the first saved theme", () => {+ storage.setItem(theme.THEME_CUSTOM_KEY, JSON.stringify(make("Old")));+ storage.setItem(theme.THEME_PRESET_KEY, "custom");+ theme.bootstrapTheme();+ expect(theme.getCustomThemes()).toEqual([{ id: "custom", theme: make("Old") }]);+ expect(theme.getSelectedCustomId()).toBe("custom");+ expect(root.dataset.omnirushPalette).toBe("custom");+ });++ test("damaged entries are dropped, good ones kept", () => {+ storage.setItem(+ theme.THEME_CUSTOMS_KEY,+ JSON.stringify([+ { id: "ok", theme: make("Fine") },+ { id: "BAD ID", theme: make("Bad id") },+ { id: "ok", theme: make("Duplicate") },+ { id: "evil", theme: { ...make("Evil"), light: { ...make("Evil").light!, background: "red;}" } } },+ "junk",+ ]),+ );+ expect(theme.getCustomThemes().map((item) => item.theme.name)).toEqual(["Fine"]);+ storage.setItem(theme.THEME_CUSTOMS_KEY, "{oops");+ theme.resetThemeStateForTests();+ expect(theme.getCustomThemes()).toEqual([]);+ });+});diff --git a/apps/app/tests/theme-presets.test.ts b/apps/app/tests/theme-presets.test.tsindex b726cd58..d331c8d3 100644--- a/apps/app/tests/theme-presets.test.ts+++ b/apps/app/tests/theme-presets.test.ts@@ -102,7 +102,7 @@ describe("preset resolution", () => {fontSizePx: 14,};- test("there are 8 presets and 15 variants with the agreed ids", () => {+ test("there are 11 presets and 21 variants with the agreed ids", () => {expect(THEME_PRESETS.map((p) => p.id)).toEqual(["default","midnight",@@ -112,8 +112,11 @@ describe("preset resolution", () => {"forest","high-contrast","omnirush",+ "graphite",+ "paper",+ "nocturne",]);- expect(THEME_PRESETS.reduce((sum, p) => sum + presetModes(p).length, 0)).toBe(15);+ expect(THEME_PRESETS.reduce((sum, p) => sum + presetModes(p).length, 0)).toBe(21);expect(presetModes(findPreset("midnight")!)).toEqual(["dark"]);});@@ -387,7 +390,11 @@ describe("theme state and persistence", () => {expect(theme.getActiveTheme().legacy).toBe(true);expect(root.dataset.omnirushPalette).toBeUndefined();expect(props.get("--muted-foreground")).toBe("#858991");- expect(theme.readBootVars(storage.getItem(theme.THEME_BOOT_KEY), "dark")).toEqual({ mode: "dark", vars: { "--muted-foreground": "#858991" } });+ expect(theme.readBootVars(storage.getItem(theme.THEME_BOOT_KEY), "dark")).toEqual({+ mode: "dark",+ vars: { "--muted-foreground": "#858991" },+ attrs: {},+ });storage.values.clear();props.clear();root.dataset = {};@@ -450,7 +457,7 @@ describe("theme state and persistence", () => {expect(props.get("--radius")).toBe("12px");theme.resetThemeStateForTests();expect(theme.getCustomTheme()).toEqual(custom);- storage.setItem(theme.THEME_CUSTOM_KEY, '{"v":1,"name":"x","modes":["light"],"light":{"background":"red;}"}}');+ storage.setItem(theme.THEME_CUSTOMS_KEY, '[{"id":"custom","theme":{"v":1,"name":"x","modes":["light"],"light":{"background":"red;}"}}}]');theme.resetThemeStateForTests();expect(theme.getCustomTheme()).toBeNull();theme.bootstrapTheme();@@ -497,7 +504,7 @@ describe("theme state and persistence", () => {expect(boot.mode).toBe("dark");expect(boot.vars["--background"]).toBe(findPreset("midnight")!.variants.dark!.background);const tampered = JSON.stringify({ only: null, light: { "--background": "red;}body{x}", "--primary": "#123456", "x": "#ffffff" } });- expect(theme.readBootVars(tampered, "light")).toEqual({ mode: "light", vars: { "--primary": "#123456" } });+ expect(theme.readBootVars(tampered, "light")).toEqual({ mode: "light", vars: { "--primary": "#123456" }, attrs: {} });expect(theme.readBootVars("garbage", "light")).toBeNull();});});