Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): add modular theme library (#5226)

Wout Stiens85b1734d4d49
diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.ts
index be633971b..f1add4c7c 100644
--- a/apps/desktop/src/electron/ElectronDialog.ts
+++ b/apps/desktop/src/electron/ElectronDialog.ts
@@ -23,6 +23,21 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
}
}
+export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
+ "ElectronDialogPickFilesError",
+ {
+ ownerWindowId: Schema.NullOr(Schema.Number),
+ defaultPath: Schema.NullOr(Schema.String),
+ cause: Schema.Defect(),
+ },
+) {
+ override get message(): string {
+ const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
+ const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
+ return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
+ }
+}
+
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
@@ -69,6 +84,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
+ ElectronDialogPickFilesError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
@@ -81,6 +97,12 @@ export interface ElectronDialogPickFolderInput {
readonly defaultPath: Option.Option<string>;
}
+export interface ElectronDialogPickFilesInput {
+ readonly owner: Option.Option<Electron.BrowserWindow>;
+ readonly defaultPath: Option.Option<string>;
+ readonly filters: readonly Electron.FileFilter[];
+}
+
export interface ElectronDialogConfirmInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly message: string;
@@ -92,6 +114,9 @@ export class ElectronDialog extends Context.Service<
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
+ readonly pickFiles: (
+ input: ElectronDialogPickFilesInput,
+ ) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
@@ -137,6 +162,32 @@ export const make = ElectronDialog.of({
}
return Option.fromNullishOr(result.filePaths[0]);
}),
+ pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
+ const ownerWindowId = Option.match(input.owner, {
+ onNone: () => null,
+ onSome: (owner) => owner.id,
+ });
+ const defaultPath = Option.getOrNull(input.defaultPath);
+ const openDialogOptions: Electron.OpenDialogOptions = {
+ properties: ["openFile", "multiSelections"],
+ filters: [...input.filters],
+ ...(defaultPath === null ? {} : { defaultPath }),
+ };
+ const result = yield* Effect.tryPromise({
+ try: () =>
+ Option.match(input.owner, {
+ onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
+ onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
+ }),
+ catch: (cause) =>
+ new ElectronDialogPickFilesError({
+ ownerWindowId,
+ defaultPath,
+ cause,
+ }),
+ });
+ return result.canceled ? [] : result.filePaths;
+ }),
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index e478d0c6e..503a586d9 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -38,6 +38,7 @@ import {
getWindowFullscreenState,
openExternal,
pickFolder,
+ pickThemeFiles,
setTheme,
showContextMenu,
} from "./methods/window.ts";
@@ -79,6 +80,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
+ yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index 5988b1e42..4d8e783d1 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -1,4 +1,5 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
+export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index a4e98aaab..cfa854e7a 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -3,10 +3,15 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
+ PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopEnvironmentBootstrap,
+ type PickedThemeFile,
} from "@t3tools/contracts";
+import * as NodeOS from "node:os";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -268,3 +273,49 @@ export const openExternal = DesktopIpc.makeIpcMethod({
return yield* shell.openExternal(url);
}),
});
+
+/** Theme files are a few KB; anything larger returns empty text and lets the
+ * renderer reject it by size without the contents ever crossing the bridge. */
+const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
+
+export const pickThemeFiles = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
+ payload: Schema.Undefined,
+ result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
+ handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
+ const dialog = yield* ElectronDialog.ElectronDialog;
+ const electronWindow = yield* ElectronWindow.ElectronWindow;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ // The VS Code extensions directory is the same dotfolder on Windows,
+ // macOS, and Linux; when it is missing the picker opens wherever the
+ // platform would by default.
+ const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
+ const defaultPath = yield* fileSystem
+ .exists(extensionsDir)
+ .pipe(Effect.orElseSucceed(() => false));
+ const paths = yield* dialog.pickFiles({
+ owner: yield* electronWindow.focusedMainOrFirst,
+ defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
+ filters: [{ name: "JSON", extensions: ["json"] }],
+ });
+ if (paths.length === 0) {
+ return null;
+ }
+ return yield* Effect.forEach(paths, (filePath) => {
+ const name = path.basename(filePath);
+ return Effect.gen(function* () {
+ const info = yield* fileSystem.stat(filePath);
+ const size = Number(info.size);
+ if (size > PICKED_THEME_FILE_MAX_BYTES) {
+ return { name, size, text: "" } satisfies PickedThemeFile;
+ }
+ const text = yield* fileSystem.readFileString(filePath);
+ return { name, size, text } satisfies PickedThemeFile;
+ }).pipe(
+ // An unreadable file degrades to an entry the renderer reports.
+ Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
+ );
+ });
+ }),
+});
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 9f01baeed..7e8859359 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -97,6 +97,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
+ pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
index 136cf8204..22a24b908 100644
--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts
+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts
@@ -52,6 +52,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
+ pickFiles: () => Effect.succeed([]),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts
index 252819ada..b674688f0 100644
--- a/apps/server/src/keybindings.test.ts
+++ b/apps/server/src/keybindings.test.ts
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
+ assert.equal(defaultsByCommand.get("themeEditor.toggle"), "mod+alt+shift+t");
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
diff --git a/apps/web/index.html b/apps/web/index.html
index 021bcb415..f51d9432d 100644
--- a/apps/web/index.html
+++ b/apps/web/index.html
@@ -6,8 +6,6 @@
name="viewport"
content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"
/>
- <meta name="theme-color" content="#ffffff" media="(prefers-color-scheme: light)" />
- <meta name="theme-color" content="#0a0a0a" media="(prefers-color-scheme: dark)" />
<meta name="theme-color" content="#0a0a0a" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
@@ -15,23 +13,373 @@
(() => {
const LIGHT_BACKGROUND = "#ffffff";
const DARK_BACKGROUND = "#0a0a0a";
- const themeColorMeta = document.querySelector('meta[name="theme-color"]');
+ const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1";
+ const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system";
+ const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode";
+ const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1";
+ const SPLASH_COLORS = {
+ light: {
+ background: "#ffffff",
+ foreground: "#262626",
+ accent: "#4f46e5",
+ },
+ dark: {
+ background: "#0a0a0a",
+ foreground: "#f5f5f5",
+ accent: "#818cf8",
+ },
+ };
+ // These are the runtime defaults used to complete a custom palette
+ // when a stored theme omits a role. Keep them separate from the
+ // unselected splash so a partial custom theme does not flash generic
+ // app colors before React mounts.
+ const DEFAULT_THEME_PALETTES = {
+ light: {
+ background: "#fdf7fd",
+ foreground: "#501854",
+ accent: "#e33f86",
+ chrome: "#fdf7fd",
+ },
+ dark: {
+ background: "#1f1a24",
+ foreground: "#f9f8fb",
+ accent: "#a3004c",
+ chrome: "#1f1a24",
+ },
+ };
+ // Keep this small boot-time copy in sync with the built-in palettes so
+ // the selected theme is visible before the app has mounted.
+ const BUILT_IN_THEME_PALETTES = {
+ "t3-chat": {
+ light: {
+ background: "#fdf7fd",
+ foreground: "#501854",
+ accent: "#e33f86",
+ chrome: "#fdf7fd",
+ },
+ dark: {
+ background: "#1f1a24",
+ foreground: "#f9f8fb",
+ accent: "#a3004c",
+ chrome: "#1f1a24",
+ },
+ },
+ grove: {
+ light: {
+ background: "#f3f7f4",
+ foreground: "#241523",
+ accent: "#1b7d50",
+ chrome: "#f3f7f4",
+ },
+ dark: {
+ background: "#1b2821",
+ foreground: "#fffaff",
+ accent: "#69d69a",
+ chrome: "#1b2821",
+ },
+ },
+ ocean: {
+ light: {
+ background: "#f5f7f8",
+ foreground: "#241523",
+ accent: "#2672af",
+ chrome: "#f5f7f8",
+ },
+ dark: {
+ background: "#17212b",
+ foreground: "#fffaff",
+ accent: "#70b9ee",
+ chrome: "#17212b",
+ },
+ },
+ ember: {
+ light: {
+ background: "#f9f7f5",
+ foreground: "#241523",
+ accent: "#ae552a",
+ chrome: "#f9f7f5",
+ },
+ dark: {
+ background: "#291e1a",
+ foreground: "#fffaff",
+ accent: "#f09a64",
+ chrome: "#291e1a",
+ },
+ },
+ iris: {
+ light: {
+ background: "#f8f7f9",
+ foreground: "#241523",
+ accent: "#7253b9",
+ chrome: "#f8f7f9",
+ },
+ dark: {
+ background: "#1d1929",
+ foreground: "#fffaff",
+ accent: "#9d7df2",
+ chrome: "#1d1929",
+ },
+ },
+ };
+ // Keep the built-in mode list in sync with the runtime so the selected
+ // T3 Chat palette is visible before React has mounted.
+ const BUILT_IN_THEME_MODES = Object.fromEntries(
+ Object.entries(BUILT_IN_THEME_PALETTES).map(([id, palettes]) => [
+ id,
+ Object.keys(palettes),
+ ]),
+ );
+ const RESERVED_THEME_IDS = [
+ "system",
+ "light",
+ "dark",
+ "t3-chat",
+ "grove",
+ "ocean",
+ "ember",
+ "iris",
+ "t3-chat-dark",
+ "t3-grove",
+ "t3-ocean",
+ "t3-ember",
+ "t3-iris",
+ ];
+ // Update every theme-color meta so any element another layer added
+ // carries the resolved color too.
+ const setThemeColor = (color) => {
+ for (const meta of document.querySelectorAll('meta[name="theme-color"]')) {
+ meta.setAttribute("content", color);
+ }
+ };
+
+ const isHexColor = (value) =>
+ typeof value === "string" &&
+ /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
+ const isRecord = (value) =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+ const isThemeId = (value) =>
+ typeof value === "string" && /^[a-z0-9](?:[a-z0-9-]{0,47})$/.test(value);
+ const isThemeLabel = (value) =>
+ typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
+ const isThemePreferenceMode = (value) =>
+ value === "light" || value === "dark" || value === "system";
+ const isThemeAppearance = (value) => value === "light" || value === "dark";
+ const isStoredCustomTheme = (value) => {
+ if (
+ !isRecord(value) ||
+ !isThemeId(value.id) ||
+ RESERVED_THEME_IDS.includes(value.id) ||
+ !isThemeLabel(value.label) ||
+ !isThemeAppearance(value.appearance) ||
+ !isRecord(value.colors)
+ ) {
+ return false;
+ }
+ if (value.variants === undefined) return true;
+ if (!isRecord(value.variants)) return false;
+ return Object.entries(value.variants).every(
+ ([appearance, colors]) =>
+ isThemeAppearance(appearance) &&
+ (appearance === value.appearance || isRecord(colors)),
+ );
+ };
+ const findCustomTheme = (themeId) => {
+ if (RESERVED_THEME_IDS.includes(themeId)) return null;
+ try {
+ const parsed = JSON.parse(
+ window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY) ?? "null",
+ );
+ if (!Array.isArray(parsed)) return null;
+ return (
+ parsed.find((value) => isStoredCustomTheme(value) && value.id === themeId) ?? null
+ );
+ } catch {
+ return null;
+ }
+ };
+
try {
const storedTheme = window.localStorage.getItem("t3code:theme");
- const theme =
- storedTheme === "light" || storedTheme === "dark" || storedTheme === "system"
- ? storedTheme
- : "system";
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
- const isDark = theme === "dark" || (theme === "system" && prefersDark);
+ // Older builds stored the dark T3 Chat palette as its own theme id
+ // and every maintainer theme under a t3- prefix; keep those
+ // preferences readable. Mirrors the runtime's legacy alias table.
+ const LEGACY_THEME_IDS = {
+ "t3-chat-dark": "t3-chat",
+ "t3-grove": "grove",
+ "t3-ocean": "ocean",
+ "t3-ember": "ember",
+ "t3-iris": "iris",
+ };
+ const isLegacyT3ChatDark = storedTheme === "t3-chat-dark";
+ const themeId =
+ storedTheme === null ? "" : (LEGACY_THEME_IDS[storedTheme] ?? storedTheme);
+ const legacyMode = isLegacyT3ChatDark ? "dark" : null;
+ const builtInModes = BUILT_IN_THEME_MODES[themeId] ?? null;
+ const customTheme = builtInModes ? null : findCustomTheme(themeId);
+ const themeModes =
+ builtInModes ??
+ (customTheme
+ ? ["light", "dark"].filter(
+ (mode) => mode === customTheme.appearance || customTheme.variants?.[mode],
+ )
+ : null);
+ // Mirrors the runtime's isKnownThemePreference.
+ const isKnownTheme =
+ storedTheme === "light" ||
+ storedTheme === "dark" ||
+ storedTheme === "system" ||
+ themeModes !== null;
+ const theme = isKnownTheme && storedTheme ? storedTheme : "system";
+ const isThemed = isKnownTheme && themeModes !== null;
+ const baseAppearance = customTheme ? customTheme.appearance : "light";
+ const systemMode = prefersDark ? "dark" : "light";
+ const storedAppearanceMode = window.localStorage.getItem(
+ THEME_APPEARANCE_MODE_STORAGE_KEY,
+ );
+ const storedFollowSystem = window.localStorage.getItem(THEME_FOLLOW_SYSTEM_STORAGE_KEY);
+ // Mirrors the runtime's getThemePreferenceMode fallback: a bare
+ // "light"/"dark" preference names its own mode.
+ const preferenceMode =
+ theme === "light" || theme === "dark" ? theme : (legacyMode ?? baseAppearance);
+ const appearanceMode = isThemePreferenceMode(storedAppearanceMode)
+ ? storedAppearanceMode
+ : storedFollowSystem === "true"
+ ? "system"
+ : storedFollowSystem === "false"
+ ? preferenceMode
+ : theme === "system"
+ ? "system"
+ : preferenceMode;
+ // A valid mix half for the wanted appearance takes over: it decides
+ // light vs dark even when the base theme cannot render that mode.
+ // Mirrors the runtime's halves-aware resolveThemeAppearance.
+ const wantedMode = appearanceMode === "system" ? systemMode : appearanceMode;
+ let halfThemeId = null;
+ let halfCustomTheme = null;
+ try {
+ const halvesRaw = JSON.parse(
+ window.localStorage.getItem(THEME_HALVES_STORAGE_KEY) ?? "null",
+ );
+ const candidate = isRecord(halvesRaw) ? halvesRaw[wantedMode] : null;
+ if (typeof candidate === "string") {
+ const halfId = LEGACY_THEME_IDS[candidate] ?? candidate;
+ const halfBuiltIn = BUILT_IN_THEME_MODES[halfId] ?? null;
+ const halfCustom = halfBuiltIn ? null : findCustomTheme(halfId);
+ const halfModes =
+ halfBuiltIn ??
+ (halfCustom
+ ? ["light", "dark"].filter(
+ (mode) => mode === halfCustom.appearance || halfCustom.variants?.[mode],
+ )
+ : null);
+ if (halfModes && halfModes.includes(wantedMode)) {
+ halfThemeId = halfId;
+ halfCustomTheme = halfCustom;
+ }
+ }
+ } catch {
+ // A malformed mix degrades to the base preference.
+ }
+ const themeMode = !isThemed
+ ? null
+ : appearanceMode === "system"
+ ? themeModes.includes(systemMode)
+ ? systemMode
+ : baseAppearance
+ : themeModes.includes(appearanceMode)
+ ? appearanceMode
+ : baseAppearance;
+ const isDark =
+ halfThemeId !== null
+ ? wantedMode === "dark"
+ : isThemed
+ ? themeMode === "dark"
+ : appearanceMode === "system"
+ ? prefersDark
+ : appearanceMode === "dark";
+ const effectiveIsThemed = halfThemeId !== null || isThemed;
+ const effectiveThemeId = halfThemeId ?? themeId;
+ const effectiveCustomTheme = halfThemeId !== null ? halfCustomTheme : customTheme;
+ const effectiveThemeMode = halfThemeId !== null ? wantedMode : themeMode;
+ const customColors =
+ effectiveIsThemed && effectiveCustomTheme
+ ? effectiveThemeMode === effectiveCustomTheme.appearance
+ ? effectiveCustomTheme.colors
+ : (effectiveCustomTheme.variants?.[effectiveThemeMode] ??
+ effectiveCustomTheme.colors)
+ : null;
+ const customDefaults =
+ effectiveCustomTheme && effectiveThemeMode
+ ? DEFAULT_THEME_PALETTES[effectiveThemeMode]
+ : null;
+ // The runtime tolerates individual malformed colors, so fall back
+ // per role rather than dropping the theme.
+ const builtInSplash =
+ effectiveIsThemed && !effectiveCustomTheme && effectiveThemeMode
+ ? (BUILT_IN_THEME_PALETTES[effectiveThemeId]?.[effectiveThemeMode] ?? null)
+ : null;
+ const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
+ const customSplash = customColors
+ ? {
+ background: isHexColor(customColors.canvas)
+ ? customColors.canvas
+ : (customDefaults?.background ?? fallbackSplash.background),
+ foreground: isHexColor(customColors.text)
+ ? customColors.text
+ : (customDefaults?.foreground ?? fallbackSplash.foreground),
+ accent: isHexColor(customColors.accent)
+ ? customColors.accent
+ : (customDefaults?.accent ?? fallbackSplash.accent),
+ }
+ : null;
+ if (effectiveIsThemed) {
+ document.documentElement.dataset.themeId = effectiveCustomTheme
+ ? effectiveCustomTheme.id
+ : effectiveThemeId;
+ } else {
+ delete document.documentElement.dataset.themeId;
+ }
+ // A resolved half is a selection even when the base theme is gone
+ // (deleting the base leaves the mix pointing at a real theme).
+ const hasSelection = halfThemeId !== null || (isKnownTheme && storedTheme !== null);
+ if (hasSelection) {
+ document.documentElement.dataset.themeSelected = "true";
+ } else {
+ delete document.documentElement.dataset.themeSelected;
+ }
document.documentElement.classList.toggle("dark", isDark);
- const chromeColor = isDark ? DARK_BACKGROUND : LIGHT_BACKGROUND;
+ const chromeColor = customColors
+ ? isHexColor(customColors.chrome)
+ ? customColors.chrome
+ : (customDefaults?.chrome ?? fallbackSplash.background)
+ : builtInSplash
+ ? builtInSplash.chrome
+ : isDark
+ ? DARK_BACKGROUND
+ : LIGHT_BACKGROUND;
document.documentElement.style.backgroundColor = chromeColor;
- themeColorMeta?.setAttribute("content", chromeColor);
+ if (hasSelection) {
+ const splashColors = customSplash ?? builtInSplash ?? fallbackSplash;
+ for (const [name, value] of Object.entries(splashColors)) {
+ document.documentElement.style.setProperty(`--boot-${name}`, value);
+ }
+ }
+ setThemeColor(chromeColor);
} catch {
- document.documentElement.classList.add("dark");
- document.documentElement.style.backgroundColor = DARK_BACKGROUND;
- themeColorMeta?.setAttribute("content", DARK_BACKGROUND);
+ // Mirror the runtime's storage-failure fallback: follow the OS.
+ let prefersDark = true;
+ try {
+ prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
+ } catch {
+ // Keep the dark default when even matchMedia is unavailable.
+ }
+ delete document.documentElement.dataset.themeId;
+ delete document.documentElement.dataset.themeSelected;
+ document.documentElement.classList.toggle("dark", prefersDark);
+ const fallbackColor = prefersDark ? DARK_BACKGROUND : LIGHT_BACKGROUND;
+ document.documentElement.style.backgroundColor = fallbackColor;
+ setThemeColor(fallbackColor);
}
})();
</script>
@@ -56,14 +404,24 @@
}
#boot-shell {
+ position: relative;
+ overflow: hidden;
display: flex;
min-height: 100%;
align-items: center;
justify-content: center;
background: inherit;
+ color: inherit;
+ }
+
+ html[data-theme-selected="true"] #boot-shell {
+ background: var(--boot-background);
+ color: var(--boot-foreground);
}
#boot-shell-card {
+ position: relative;
+ z-index: 1;
display: flex;
align-items: center;
justify-content: center;
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index f0e25e644..c5e4f7abb 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -5842,10 +5842,10 @@ function ChatViewContent(props: ChatViewProps) {
const panelLayoutControls = (
<div
className={cn(
- "workspace-titlebar-controls z-50 gap-1 [-webkit-app-region:no-drag]",
- rightPanelOpen && !shouldUseRightPanelSheet
- ? "right-2 wco:right-[var(--workspace-controls-right)]"
- : "mr-px",
+ // One inset in both states: the controls move between containers when
+ // the right panel opens, and a different right offset made them jump
+ // sideways on every toggle.
+ "workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]",
)}
>
{rightPanelOpen && !shouldUseRightPanelSheet ? (
diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts
index eee6ba588..c9ded5e7e 100644
--- a/apps/web/src/components/CommandPalette.logic.ts
+++ b/apps/web/src/components/CommandPalette.logic.ts
@@ -12,7 +12,7 @@ import { formatRelativeTimeLabel } from "../timestampFormat";
import { type Project, type SidebarThreadSummary, type Thread } from "../types";
export const RECENT_THREAD_LIMIT = 12;
-export const ITEM_ICON_CLASS = "size-4 text-muted-foreground/80";
+export const ITEM_ICON_CLASS = "size-4 text-icon-muted";
export const ADDON_ICON_CLASS = "size-4";
/**
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index 604930636..605127f97 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -35,6 +35,7 @@ import {
FolderPlusIcon,
LinkIcon,
MessageSquareIcon,
+ PaletteIcon,
SettingsIcon,
SquarePenIcon,
TextSearchIcon,
@@ -57,6 +58,7 @@ import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useClientSettings } from "../hooks/useSettings";
+import { useTheme } from "../hooks/useTheme";
import { readLocalApi } from "../localApi";
import { desktopLocalBackendId } from "../connection/desktopLocal";
import { filesystemEnvironment } from "../state/filesystem";
@@ -121,6 +123,7 @@ import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons"
import { ProjectFavicon } from "./ProjectFavicon";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
+import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";
import { resolveDefaultProviderModelSelection } from "../providerInstances";
@@ -386,6 +389,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
const openNewThreadIn = useCallback(() => dispatch({ _tag: "OpenNewThreadIn" }), []);
const clearOpenIntent = useCallback(() => dispatch({ _tag: "ClearOpenIntent" }), []);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
+ const { theme, themeHalves, resolvedTheme } = useTheme();
const composerHandleRef = useRef<ChatComposerHandle | null>(null);
const routeTarget = useParams({
strict: false,
@@ -428,6 +432,16 @@ export function CommandPalette({ children }: { children: ReactNode }) {
previewOpen,
},
});
+ if (command === "themeEditor.toggle") {
+ event.preventDefault();
+ event.stopPropagation();
+ toggleThemeEditorForTheme({
+ theme,
+ themeHalves,
+ initialAppearance: resolvedTheme,
+ });
+ return;
+ }
const mode = overlayModeForCommand(command);
if (mode === null) {
return;
@@ -438,7 +452,7 @@ export function CommandPalette({ children }: { children: ReactNode }) {
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
- }, [keybindings, previewOpen, terminalOpen, toggleMode]);
+ }, [keybindings, previewOpen, resolvedTheme, terminalOpen, theme, themeHalves, toggleMode]);
useEffect(
() =>
@@ -567,6 +581,7 @@ function OpenCommandPaletteDialog(props: {
const projectOrder = useUiStateStore((store) => store.projectOrder);
const threads = useThreadShells();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
+ const { theme, themeHalves, resolvedTheme } = useTheme();
const providers = useAtomValue(primaryServerProvidersAtom);
const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);
const currentView = viewStack.at(-1) ?? null;
@@ -1463,6 +1478,22 @@ function OpenCommandPaletteDialog(props: {
});
}
+ actionItems.push({
+ kind: "action",
+ value: "action:theme-editor",
+ searchTerms: ["theme", "appearance", "colors", "palette", "customize"],
+ title: "Toggle theme editor",
+ icon: <PaletteIcon className={ITEM_ICON_CLASS} />,
+ shortcutCommand: "themeEditor.toggle",
+ run: async () => {
+ toggleThemeEditorForTheme({
+ theme,
+ themeHalves,
+ initialAppearance: resolvedTheme,
+ });
+ },
+ });
+
actionItems.push({
kind: "action",
value: "action:settings",
diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsx
index 67b82388b..0489e8c79 100644
--- a/apps/web/src/components/ComposerPromptEditor.tsx
+++ b/apps/web/src/components/ComposerPromptEditor.tsx
@@ -1765,7 +1765,7 @@ function ComposerPromptEditorInner({
}
placeholder={
terminalContexts.length > 0 ? null : (
- <div className="pointer-events-none absolute inset-0 leading-relaxed text-muted-foreground/35">
+ <div className="pointer-events-none absolute inset-0 leading-relaxed text-placeholder">
{placeholder}
</div>
)
diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx
index a10cdafd7..76191e6d4 100644
--- a/apps/web/src/components/DiffPanel.tsx
+++ b/apps/web/src/components/DiffPanel.tsx
@@ -36,6 +36,7 @@ import {
getRenderablePatch,
resolveDiffThemeName,
resolveFileDiffPath,
+ DIFF_SURFACE_THEME_UNSAFE_CSS,
} from "../lib/diffRendering";
import { areAllDiffFilesCollapsed, toggleAllDiffFiles } from "../lib/diffCollapse";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -86,54 +87,7 @@ interface CollapsedDiffFilesState {
const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
-const DIFF_PANEL_UNSAFE_CSS = `
-[data-diffs-header],
-[data-diff],
-[data-file],
-[data-error-wrapper],
-[data-virtualizer-buffer] {
- --diffs-header-font-family: var(--font-sans) !important;
- --diffs-font-family: var(--font-mono) !important;
- --diffs-bg: var(--background) !important;
- --diffs-light-bg: var(--background) !important;
- --diffs-dark-bg: var(--background) !important;
- --diffs-token-light-bg: transparent;
- --diffs-token-dark-bg: transparent;
-
- --diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
- --diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
- --diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
- --diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
-
- --diffs-bg-addition-override: light-dark(
- color-mix(in srgb, var(--background) 50%, var(--success)),
- color-mix(in srgb, var(--background) 70%, var(--success))
- );
- --diffs-bg-addition-number-override: light-dark(
- color-mix(in srgb, var(--background) 35%, var(--success)),
- color-mix(in srgb, var(--background) 60%, var(--success))
- );
- --diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
- --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
-
- --diffs-bg-deletion-override: light-dark(
- color-mix(in srgb, var(--background) 50%, var(--destructive)),
- color-mix(in srgb, var(--background) 70%, var(--destructive))
- );
- --diffs-bg-deletion-number-override: light-dark(
- color-mix(in srgb, var(--background) 35%, var(--destructive)),
- color-mix(in srgb, var(--background) 60%, var(--destructive))
- );
- --diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
- --diffs-bg-deletion-emphasis-override: color-mix(
- in srgb,
- var(--background) 80%,
- var(--destructive)
- );
-
- background-color: var(--diffs-bg) !important;
-}
-
+const DIFF_PANEL_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS}
:is(
[data-line],
[data-line-annotation],
@@ -144,13 +98,13 @@ const DIFF_PANEL_UNSAFE_CSS = `
--diffs-line-bg: light-dark(
color-mix(
in lab,
- var(--background) 88%,
- color-mix(in srgb, var(--background) 50%, var(--diffs-modified-base))
+ var(--code-background) 88%,
+ color-mix(in srgb, var(--code-background) 50%, var(--diffs-modified-base))
),
color-mix(
in lab,
- var(--background) 80%,
- color-mix(in srgb, var(--background) 70%, var(--diffs-modified-base))
+ var(--code-background) 80%,
+ color-mix(in srgb, var(--code-background) 70%, var(--diffs-modified-base))
)
) !important;
}
@@ -159,13 +113,13 @@ const DIFF_PANEL_UNSAFE_CSS = `
--diffs-line-bg: light-dark(
color-mix(
in lab,
- var(--background) 91%,
- color-mix(in srgb, var(--background) 35%, var(--diffs-modified-base))
+ var(--code-background) 91%,
+ color-mix(in srgb, var(--code-background) 35%, var(--diffs-modified-base))
),
color-mix(
in lab,
- var(--background) 85%,
- color-mix(in srgb, var(--background) 60%, var(--diffs-modified-base))
+ var(--code-background) 85%,
+ color-mix(in srgb, var(--code-background) 60%, var(--diffs-modified-base))
)
) !important;
}
@@ -192,16 +146,16 @@ const DIFF_PANEL_UNSAFE_CSS = `
}
[data-file-info] {
- background-color: var(--background) !important;
+ background-color: var(--code-background) !important;
border-block-color: transparent !important;
- color: var(--foreground) !important;
+ color: var(--code-foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
- background-color: var(--background) !important;
+ background-color: var(--code-background) !important;
border-bottom-color: transparent !important;
align-items: center !important;
font-family: var(--font-sans) !important;
@@ -213,13 +167,13 @@ const DIFF_PANEL_UNSAFE_CSS = `
}
[data-diffs-header]:hover {
- background-color: color-mix(in srgb, var(--background) 97%, var(--foreground)) !important;
+ background-color: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]) {
height: 24px !important;
margin-block: 0 !important;
- background-color: var(--background) !important;
+ background-color: var(--code-background) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])
@@ -233,7 +187,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
gap: 8px;
padding-inline: 0 !important;
background-color: transparent !important;
- color: color-mix(in srgb, var(--foreground) 52%, var(--background)) !important;
+ color: color-mix(in srgb, var(--code-foreground) 52%, var(--code-background)) !important;
font-family: var(--font-sans) !important;
font-size: 11px !important;
text-decoration: none !important;
@@ -257,7 +211,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
height: 1px;
flex: 1 1 auto;
content: "";
- background-color: color-mix(in srgb, var(--background) 92%, var(--foreground));
+ background-color: color-mix(in srgb, var(--code-background) 92%, var(--code-foreground));
}
:is([data-separator="line-info"], [data-separator="line-info-basic"])[data-expand-index]
@@ -286,7 +240,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
[data-expand-button]
):hover
[data-separator-content] {
- color: color-mix(in srgb, var(--foreground) 76%, var(--background)) !important;
+ color: color-mix(in srgb, var(--code-foreground) 76%, var(--code-background)) !important;
}
:is([data-separator="line-info"], [data-separator="line-info-basic"]):has(
@@ -297,7 +251,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
[data-expand-button]
):hover
[data-unmodified-lines]::after {
- background-color: color-mix(in srgb, var(--background) 84%, var(--foreground));
+ background-color: color-mix(in srgb, var(--code-background) 84%, var(--code-foreground));
}
[data-diffs-header] [data-header-content] {
@@ -337,7 +291,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
}
[data-title]:hover {
- color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
+ color: color-mix(in srgb, var(--code-foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
@@ -796,11 +750,11 @@ export default function DiffPanel({
<div className="flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]">
<DropdownMenu>
<DropdownMenuTrigger
- className="inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-muted/70 px-2 text-xs font-medium text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
+ className="inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-accent px-2 text-xs font-medium text-accent-foreground outline-none transition-colors hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Diff scope: ${selectedScopeLabel}`}
>
<span className="truncate">{selectedScopeLabel}</span>
- <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-60">
<DropdownMenuItem
@@ -1120,7 +1074,7 @@ export default function DiffPanel({
)}
{selectedPatchError && !renderablePatch && (
<div className="px-3">
- <p className="mb-2 text-[11px] text-red-500/80">{selectedPatchError}</p>
+ <p className="mb-2 text-[11px] text-error/80">{selectedPatchError}</p>
</div>
)}
{!renderablePatch ? (
diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx
index 1df19a640..66216e10c 100644
--- a/apps/web/src/components/ProjectFavicon.tsx
+++ b/apps/web/src/components/ProjectFavicon.tsx
@@ -47,7 +47,7 @@ function ProjectFaviconFallback({
readonly className?: string | undefined;
readonly icon: ComponentType<{ className?: string }>;
}) {
- return <Icon className={cn("size-3.5 shrink-0 text-muted-foreground/50", className)} />;
+ return <Icon className={cn("size-3.5 shrink-0 text-icon-muted", className)} />;
}
function ProjectFaviconImage({
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index 3a1d71150..7f21177e7 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -343,6 +343,9 @@ export default function ProjectScriptsControl({
variant="outline"
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
aria-label={`Run ${primaryScript.name}`}
+ // The tooltip wrapper replaces data-slot="button", so themed
+ // toolbar styling needs its own hook.
+ data-toolbar-control=""
onClick={() => onRunScript(primaryScript)}
/>
}
@@ -447,6 +450,9 @@ export default function ProjectScriptsControl({
variant="outline"
className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
aria-label="Add action"
+ // The tooltip wrapper replaces data-slot="button", so themed
+ // toolbar styling needs its own hook.
+ data-toolbar-control=""
onClick={openAddDialog}
/>
}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index cffab8bd5..232ea0998 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -225,7 +225,7 @@ const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> =
separate: "Keep separate",
};
const SIDEBAR_ICON_ACTION_BUTTON_CLASS =
- "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring";
+ "inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring";
function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: ScopedThreadRef }) {
useEnvironmentThread(threadRef.environmentId, threadRef.threadId);
@@ -857,9 +857,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
) : (
<span
className={`text-[10px] tabular-nums ${
- isHighlighted
- ? "text-foreground/72 dark:text-foreground/82"
- : "text-muted-foreground/40"
+ isHighlighted ? "text-foreground" : "text-secondary-label"
}`}
>
{formatRelativeTimeLabel(
@@ -2245,7 +2243,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}`}
/>
</span>
- <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-muted-foreground/70 opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
+ <ChevronRightIcon className="absolute inset-0 m-auto size-3.5 text-icon-muted opacity-0 transition-opacity duration-150 group-hover/project-header:opacity-100" />
</TooltipTrigger>
<TooltipPopup side="top">{projectStatus.label}</TooltipPopup>
</Tooltip>
@@ -2262,7 +2260,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
{project.displayName}
</span>
{project.groupedProjectCount > 1 ? (
- <span className="shrink-0 text-[10px] text-muted-foreground/60">
+ <span className="shrink-0 text-secondary-label text-[10px]">
{project.groupedProjectCount} projects
</span>
) : null}
@@ -2281,7 +2279,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
? "Local sandbox project"
: "Remote project"
}
- className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-muted-foreground/60 transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100"
+ className="pointer-events-none absolute top-1 right-1.5 inline-flex size-5 items-center justify-center rounded-md text-icon-muted transition-opacity duration-150 max-sm:right-7 group-hover/project-header:opacity-0 group-focus-within/project-header:opacity-0 max-sm:group-hover/project-header:opacity-100 max-sm:group-focus-within/project-header:opacity-100"
/>
}
>
@@ -2600,7 +2598,7 @@ function ProjectSortMenu({
<Tooltip>
<TooltipTrigger
render={
- <MenuTrigger className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground" />
+ <MenuTrigger className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted transition-colors hover:bg-accent hover:text-foreground" />
}
>
<ArrowUpDownIcon className="size-3.5" />
@@ -2824,7 +2822,9 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
<SidebarContent
className="gap-0"
fixedHeader={
- <SidebarGroup className="px-2 pt-2 pb-1">
+ // Lifted above the stage backdrop, whose fade bleeds below the
+ // header and would otherwise paint across the search row's outline.
+ <SidebarGroup className="relative z-[1] px-2 pt-2 pb-1">
<SidebarMenu>
<SidebarMenuItem>
<CommandDialogTrigger
@@ -2891,7 +2891,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
type="button"
aria-label="Add project"
data-testid="sidebar-add-project-trigger"
- className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
+ className="inline-flex h-6 min-w-6 cursor-pointer items-center justify-center rounded-md px-[calc(--spacing(1)-1px)] text-icon-muted transition-colors hover:bg-accent hover:text-foreground"
onClick={openAddProject}
/>
}
@@ -2977,9 +2977,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
)}
{projectsLength === 0 && (
- <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
- No projects yet
- </div>
+ <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div>
)}
</SidebarGroup>
</SidebarContent>
diff --git a/apps/web/src/components/SidebarStageBackdrop.test.tsx b/apps/web/src/components/SidebarStageBackdrop.test.tsx
index 114fd5f92..c34eec583 100644
--- a/apps/web/src/components/SidebarStageBackdrop.test.tsx
+++ b/apps/web/src/components/SidebarStageBackdrop.test.tsx
@@ -5,7 +5,6 @@ import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
StageBackdropArt,
- StageBackdropButtonArt,
} from "./SidebarStageBackdrop";
describe("SidebarStageBackdrop", () => {
@@ -29,7 +28,7 @@ describe("SidebarStageBackdrop", () => {
const markup = renderToStaticMarkup(
<>
<StageBackdropArt variant={variant} />
- <StageBackdropButtonArt variant={variant} />
+ <StageBackdropArt variant={variant} />
</>,
);
const ids = Array.from(markup.matchAll(/\sid="([^"]+)"/g), (match) => match[1]);
diff --git a/apps/web/src/components/SidebarStageBackdrop.tsx b/apps/web/src/components/SidebarStageBackdrop.tsx
index 9fb448e94..ee669e94b 100644
--- a/apps/web/src/components/SidebarStageBackdrop.tsx
+++ b/apps/web/src/components/SidebarStageBackdrop.tsx
@@ -62,10 +62,6 @@ export function StageBackdropArt({ variant }: { variant: SidebarStageBackdropVar
return variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />;
}
-export function StageBackdropButtonArt({ variant }: { variant: SidebarStageBackdropVariant }) {
- return variant === "nightly" ? <NightlySkyArt compact /> : <DevBlueprintArt compact />;
-}
-
const NIGHTLY_STARS: ReadonlyArray<{
cx: number;
cy: number;
@@ -97,7 +93,7 @@ const NIGHTLY_SPARKLES: ReadonlyArray<{ x: number; y: number }> = [
{ x: 246, y: 26 },
];
-function NightlySkyArt({ compact = false }: { compact?: boolean }) {
+function NightlySkyArt() {
const idPrefix = useId().replaceAll(":", "");
const skyId = `${idPrefix}-stage-night-sky`;
const glowId = `${idPrefix}-stage-night-glow`;
@@ -111,7 +107,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
className="h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
- viewBox={compact ? "96 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
+ viewBox={STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
@@ -195,7 +191,7 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
);
}
-function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
+function DevBlueprintArt() {
const idPrefix = useId().replaceAll(":", "");
const paperId = `${idPrefix}-stage-bp-paper`;
const glowId = `${idPrefix}-stage-bp-glow`;
@@ -212,7 +208,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
className="stage-blueprint h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
- viewBox={compact ? "64 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
+ viewBox={STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx
index f84c54a33..0b1df2f57 100644
--- a/apps/web/src/components/SidebarV2.tsx
+++ b/apps/web/src/components/SidebarV2.tsx
@@ -768,7 +768,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
isUnread || isWoke
? "text-foreground"
: shouldRecede
- ? "text-muted-foreground/80"
+ ? "text-secondary-label"
: status === "failed"
? "text-foreground/95"
: "text-foreground/90",
@@ -779,7 +779,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
? "text-foreground"
: isUnread
? "text-muted-foreground"
- : "text-muted-foreground/70",
+ : "text-secondary-label/70",
),
isRegeneratingTitle && "opacity-[0.55]",
)}
@@ -799,8 +799,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
"shrink-0 text-xs tabular-nums hover:underline",
variant === "slim" && variantAction === "unsettle"
? props.isActive
- ? "text-muted-foreground/70"
- : cn("text-muted-foreground/35 transition-colors", settledPrHoverClass)
+ ? "text-secondary-label"
+ : cn("text-secondary-label transition-colors", settledPrHoverClass)
: prStatus.colorClass,
)}
aria-label={prStatus.tooltip}
@@ -871,7 +871,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
<span className="relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end">
<span
className={cn(
- "inline-flex justify-end tabular-nums text-muted-foreground/55 transition-opacity",
+ "inline-flex justify-end tabular-nums text-secondary-label transition-opacity",
!isWoke && "group-hover/v2-row:opacity-0",
)}
>
@@ -983,7 +983,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
{props.projectTitle ? (
<span
className={cn(
- "min-w-0 flex-1 truncate text-xs text-muted-foreground/85",
+ "min-w-0 flex-1 truncate text-secondary-label text-xs",
shouldRecede ? "font-normal" : "font-medium",
)}
>
@@ -1012,7 +1012,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
isWokeStatus
? "pointer-events-auto"
: "pointer-events-none group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
- "self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity",
+ "self-center justify-self-end tabular-nums text-secondary-label transition-opacity",
snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0",
)}
>
@@ -1101,14 +1101,14 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
</span>
) : null}
</div>
- <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground/75">
+ <div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-secondary-label text-xs">
{/* While working, the current plan step outranks the branch:
it's the one line that says what the thread is doing. */}
{status === "working" && thread.planProgress ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">
{thread.planProgress.step}
{/* Completed count, matching the transcript chip's n/m. */}
- <span className="text-muted-foreground/50 tabular-nums">
+ <span className="text-icon-muted tabular-nums">
{" "}
{thread.planProgress.completedSteps}/{thread.planProgress.totalSteps}
</span>
@@ -2834,7 +2834,9 @@ export default function SidebarV2() {
<SidebarContent
className="gap-0"
fixedHeader={
- <SidebarGroup className="gap-1 p-[var(--sidebar-content-inset)]">
+ // Lifted above the stage backdrop, whose fade bleeds below the
+ // header and would otherwise paint across the search row's outline.
+ <SidebarGroup className="relative z-[1] gap-1 p-[var(--sidebar-content-inset)]">
<div className="flex items-center gap-1">
<div className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
@@ -2969,7 +2971,7 @@ export default function SidebarV2() {
type="button"
aria-label={`Project actions for ${project.displayName}`}
title={`Project actions for ${project.displayName}`}
- className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
void handleProjectActions(event, project);
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 072241426..25b4abb3f 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -135,6 +135,10 @@ function normalizeComputedColor(value: string | null | undefined, fallback: stri
return value ?? fallback;
}
+function readThemeColor(styles: CSSStyleDeclaration, variable: string, fallback: string): string {
+ return normalizeComputedColor(styles.getPropertyValue(variable), fallback);
+}
+
/** The surface treats an omitted family or size as "use the built-in default". */
function terminalFontOptions(family: string, size: number): { family?: string; size: number } {
const trimmed = family.trim();
@@ -151,6 +155,7 @@ export function terminalThemeFromApp(mountElement?: HTMLElement | null): Ghostty
document.body;
const drawerStyles = getComputedStyle(drawerSurface);
const bodyStyles = getComputedStyle(document.body);
+ const themeStyles = getComputedStyle(document.documentElement);
const background = normalizeComputedColor(
drawerStyles.backgroundColor,
normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground),
@@ -159,20 +164,32 @@ export function terminalThemeFromApp(mountElement?: HTMLElement | null): Ghostty
drawerStyles.color,
normalizeComputedColor(bodyStyles.color, fallbackForeground),
);
-
+ const terminalBackground = readThemeColor(themeStyles, "--terminal-background", background);
+ const terminalForeground = readThemeColor(themeStyles, "--terminal-foreground", foreground);
+ const terminalCursor = readThemeColor(
+ themeStyles,
+ "--terminal-cursor",
+ isDark ? "rgb(180, 203, 255)" : "rgb(38, 56, 78)",
+ );
+ const terminalSelection = readThemeColor(
+ themeStyles,
+ "--terminal-selection-background",
+ isDark ? "rgba(180, 203, 255, 0.25)" : "rgba(37, 63, 99, 0.2)",
+ );
return {
background: parseTerminalColor(
- background,
+ terminalBackground,
isDark ? { r: 14, g: 18, b: 24 } : { r: 255, g: 255, b: 255 },
),
foreground: parseTerminalColor(
- foreground,
+ terminalForeground,
isDark ? { r: 237, g: 241, b: 247 } : { r: 28, g: 33, b: 41 },
),
- cursor: isDark ? { r: 180, g: 203, b: 255 } : { r: 38, g: 56, b: 78 },
- // Matches the xterm selection overlays this renderer replaced; the text
- // color underneath is left unchanged for contrast in both themes.
- selectionBackground: isDark ? "rgba(180, 203, 255, 0.25)" : "rgba(37, 63, 99, 0.2)",
+ cursor: parseTerminalColor(
+ terminalCursor,
+ isDark ? { r: 180, g: 203, b: 255 } : { r: 38, g: 56, b: 78 },
+ ),
+ selectionBackground: terminalSelection,
};
}
diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx
index 3a705eef3..0955bd3ab 100644
--- a/apps/web/src/components/chat/ChangedFilesTree.tsx
+++ b/apps/web/src/components/chat/ChangedFilesTree.tsx
@@ -62,6 +62,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
}
>
<div
+ data-changed-files-header=""
className={cn(
"flex items-center justify-between gap-2 rounded-xl px-1",
expanded &&
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 795cb9102..b8bacf4b6 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -318,8 +318,8 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
className={cn(
"shrink-0 whitespace-nowrap",
props.interactionMode === "plan"
- ? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
- : "text-muted-foreground/70 hover:text-foreground/80",
+ ? "bg-accent text-accent-foreground hover:bg-accent/80"
+ : "text-secondary-label hover:text-foreground",
)}
type="button"
onClick={props.onToggleInteractionMode}
@@ -420,7 +420,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
/>
) : null}
{props.isPreparingWorktree ? (
- <span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
+ <span className="text-secondary-label text-xs">Preparing worktree...</span>
) : null}
<ComposerPrimaryActions
compact={props.compact}
@@ -2767,9 +2767,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
type="button"
className={cn(
"min-w-0 flex-1 truncate bg-transparent py-1.5 text-left text-sm",
- activePendingProgress?.customAnswer
- ? "text-foreground"
- : "text-muted-foreground/60",
+ activePendingProgress?.customAnswer ? "text-foreground" : "text-placeholder",
!activePendingProgress?.activeQuestion?.multiSelect && "px-3 py-2",
)}
onPointerDown={(event) => event.preventDefault()}
@@ -2814,7 +2812,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
"min-w-0 flex-1 truncate bg-transparent p-0 text-left text-[14px] focus:outline-none",
(activePendingProgress ? activePendingProgress.customAnswer : prompt.trim())
? "text-foreground"
- : "text-muted-foreground/35",
+ : "text-placeholder",
)}
onPointerDown={(event) => event.preventDefault()}
onClick={expandMobileComposer}
@@ -2828,7 +2826,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
</button>
<button
type="button"
- className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
+ className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-30"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
onPointerDown={(event) => event.preventDefault()}
@@ -2978,7 +2976,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/>
</button>
) : (
- <div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
+ <div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-secondary-label">
{image.name}
</div>
)}
@@ -3116,7 +3114,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
variant="ghost"
disabled
data-chat-provider-unavailable="true"
- className="shrink-0 gap-2 px-2 text-muted-foreground/70 sm:px-3"
+ className="shrink-0 gap-2 px-2 text-secondary-label sm:px-3"
>
<CircleAlertIcon className="size-4" />
No provider available
diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx
index 0adeed6ff..b11e21367 100644
--- a/apps/web/src/components/chat/ChatHeader.tsx
+++ b/apps/web/src/components/chat/ChatHeader.tsx
@@ -114,7 +114,7 @@ export const ChatHeader = memo(function ChatHeader({
</TooltipTrigger>
<TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
</Tooltip>
- <span aria-hidden className="text-muted-foreground/40">
+ <span aria-hidden className="text-icon-muted">
/
</span>
</span>
diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx
index 73fc63489..3ed2a9432 100644
--- a/apps/web/src/components/chat/ComposerCommandMenu.tsx
+++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx
@@ -150,7 +150,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
{groupIndex > 0 ? <CommandSeparator className="my-0.5" /> : null}
<CommandGroup>
{group.label ? (
- <CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
+ <CommandGroupLabel className="px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-secondary-label">
{group.label}
</CommandGroupLabel>
) : null}
@@ -172,10 +172,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
<div className="px-5 py-3.5">
{props.triggerKind === "skill" ? (
<CommandGroup>
- <CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
+ <CommandGroupLabel className="px-0 pt-0 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-secondary-label">
Skills
</CommandGroupLabel>
- <p className="text-muted-foreground/70 text-xs">
+ <p className="text-secondary-label text-xs">
{props.isLoading
? "Searching workspace skills..."
: (props.emptyStateText ??
@@ -183,7 +183,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
</p>
</CommandGroup>
) : (
- <p className="text-muted-foreground/70 text-xs">
+ <p className="text-secondary-label text-xs">
{props.isLoading
? "Searching workspace files..."
: (props.emptyStateText ??
@@ -235,26 +235,26 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
/>
) : null}
{props.item.type === "slash-command" ? (
- <BotIcon className="size-4 shrink-0 text-muted-foreground/80" />
+ <BotIcon className="size-4 shrink-0 text-icon-muted" />
) : null}
{props.item.type === "provider-slash-command" ? (
- <span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
+ <span className="inline-flex size-4 shrink-0 items-center justify-center text-icon-muted">
<SkillGlyph className="size-3.5" />
</span>
) : null}
{props.item.type === "skill" ? (
- <span className="inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground/80">
+ <span className="inline-flex size-4 shrink-0 items-center justify-center text-icon-muted">
<SkillGlyph className="size-3.5" />
</span>
) : null}
<span className="flex min-w-0 flex-1 items-center gap-2">
<span className="shrink-0">{props.item.label}</span>
- <span className="min-w-0 flex-1 truncate text-muted-foreground/70 text-xs">
+ <span className="min-w-0 flex-1 truncate text-secondary-label text-xs">
{props.item.description}
</span>
</span>
{skillSourceLabel ? (
- <span className="shrink-0 pl-2 text-muted-foreground/70 text-xs">{skillSourceLabel}</span>
+ <span className="shrink-0 pl-2 text-secondary-label text-xs">{skillSourceLabel}</span>
) : null}
</CommandItem>
);
diff --git a/apps/web/src/components/chat/ComposerControl.tsx b/apps/web/src/components/chat/ComposerControl.tsx
index 8eab75171..a7ba40581 100644
--- a/apps/web/src/components/chat/ComposerControl.tsx
+++ b/apps/web/src/components/chat/ComposerControl.tsx
@@ -6,7 +6,7 @@ import { Button } from "../ui/button";
import { SelectTrigger } from "../ui/select";
const composerControlClassName =
- "h-7 min-h-7 gap-1.5 px-2.5 text-muted-foreground/70 transition-none hover:text-foreground/80 [&_svg[data-composer-control-icon]]:mx-0 [&_svg[data-composer-control-chevron]]:-mx-0.5";
+ "h-7 min-h-7 gap-1.5 px-2.5 text-secondary-label transition-none hover:text-foreground [&_svg[data-composer-control-icon]]:mx-0 [&_svg[data-composer-control-chevron]]:-mx-0.5";
export function ComposerControl({
className,
@@ -46,7 +46,7 @@ export function ComposerControlChevron() {
return (
<ChevronDownIcon
aria-hidden="true"
- className="-mx-0.5 size-3.5 shrink-0 text-muted-foreground opacity-70"
+ className="-mx-0.5 size-3.5 shrink-0 text-icon-muted"
data-composer-control-chevron
strokeWidth={2.25}
/>
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index bd02a91b2..ceac45c94 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -155,18 +155,18 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
return (
<div className="px-4 py-3 sm:px-5">
<div className="mb-2 flex items-center gap-3">
- <span className="text-[11px] font-semibold tracking-widest text-muted-foreground/55 uppercase">
+ <span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase">
{activeQuestion.header}
</span>
{prompt.questions.length > 1 ? (
- <span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
+ <span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
{questionIndex + 1}/{prompt.questions.length}
</span>
) : null}
</div>
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
{activeQuestion.multiSelect ? (
- <p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
+ <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
) : null}
<div className="mt-3 space-y-1.5">
{activeQuestion.options.map((option, index) => {
@@ -190,7 +190,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
- <span className="text-xs text-muted-foreground">{option.description}</span>
+ <span className="text-secondary-label text-xs">{option.description}</span>
) : null}
</div>
{isSelected ? (
@@ -199,7 +199,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
<kbd
className={cn(
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
- "bg-background/35 text-muted-foreground/70 group-hover:border-border/70 group-hover:text-muted-foreground",
+ "bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
)}
>
{shortcutKey}
diff --git a/apps/web/src/components/chat/ComposerPreviewAnnotationCards.tsx b/apps/web/src/components/chat/ComposerPreviewAnnotationCards.tsx
index 602ad1144..5e9e43dcf 100644
--- a/apps/web/src/components/chat/ComposerPreviewAnnotationCards.tsx
+++ b/apps/web/src/components/chat/ComposerPreviewAnnotationCards.tsx
@@ -63,13 +63,13 @@ export function ComposerPreviewAnnotationCards({
/>
</button>
) : (
- <span className="grid size-10 shrink-0 place-items-center border-r border-border/70 text-blue-500">
+ <span className="grid size-10 shrink-0 place-items-center border-r border-border/70 text-message-action">
<MousePointerClick className="size-3.5" />
</span>
)}
<div className="min-w-0 px-2.5 py-2 pr-8">
{annotation.comment.trim() ? (
- <p className="max-w-80 truncate text-xs font-medium text-foreground/90">
+ <p className="max-w-80 truncate text-foreground text-xs font-medium">
{annotation.comment.trim()}
</p>
) : null}
@@ -84,13 +84,13 @@ export function ComposerPreviewAnnotationCards({
{elementLabels.slice(0, 2).map(({ id, label }) => (
<span
key={id}
- className="max-w-40 truncate font-mono text-[10px] text-foreground/65"
+ className="max-w-40 truncate font-mono text-secondary-label text-[10px]"
>
{label}
</span>
))}
{elementLabels.length > 2 ? (
- <span className="text-[10px] text-muted-foreground">
+ <span className="text-secondary-label text-[10px]">
+{elementLabels.length - 2}
</span>
) : null}
@@ -131,7 +131,7 @@ export function ComposerPreviewAnnotationCards({
<button
type="button"
aria-label="Remove preview annotation"
- className="absolute right-1.5 top-1.5 grid size-5 place-items-center rounded text-muted-foreground/60 transition hover:bg-muted hover:text-foreground"
+ className="absolute right-1.5 top-1.5 grid size-5 place-items-center rounded text-icon-muted transition hover:bg-muted hover:text-foreground"
onClick={() => onRemove(annotation.id)}
>
<X className="size-3" />
diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx
index 504b7e1cc..cc211f318 100644
--- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx
+++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx
@@ -1,8 +1,6 @@
import { memo, type PointerEventHandler } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
-import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
import { cn } from "~/lib/utils";
-import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
import { Button } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Spinner } from "../ui/spinner";
@@ -75,11 +73,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
- const environmentIdentificationMode = useEnvironmentIdentificationMode();
const isSendDisabled = sendDisabledReason !== null;
- const stageBackdropVariant = useSidebarStageBackdropVariant(
- environmentIdentificationMode === "artwork",
- );
if (pendingAction) {
return (
@@ -113,7 +107,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<Button
type="submit"
size="sm"
- className={cn("rounded-full", compact ? "px-3" : "px-4")}
+ className={cn(
+ "rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover",
+ compact ? "px-3" : "px-4",
+ )}
{...pointerFocusProps}
disabled={
isEnvironmentUnavailable ||
@@ -154,7 +151,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<Button
type="submit"
size="sm"
- className={cn("rounded-full", compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8")}
+ className={cn(
+ "rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover",
+ compact ? "h-9 px-3 sm:h-8" : "h-9 px-4 sm:h-8",
+ )}
{...pointerFocusProps}
disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable}
>
@@ -168,7 +168,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<Button
type="submit"
size="sm"
- className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
+ className="h-9 rounded-l-full rounded-r-none bg-message-action px-4 text-message-action-foreground hover:bg-message-action-hover sm:h-8"
{...pointerFocusProps}
disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable}
>
@@ -180,7 +180,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<Button
size="sm"
variant="default"
- className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
+ className="h-9 rounded-l-none rounded-r-full border-l-message-action-foreground/20 bg-message-action px-2 text-message-action-foreground hover:bg-message-action-hover sm:h-8"
aria-label="Implementation actions"
{...pointerFocusProps}
disabled={isSendBusy || isSendDisabled || isConnecting || isEnvironmentUnavailable}
@@ -206,10 +206,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className={cn(
- "relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full text-primary-foreground shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
- stageBackdropVariant
- ? "bg-transparent enabled:shadow-black/24 enabled:hover:brightness-110"
- : "bg-primary/90 enabled:shadow-primary/24 hover:bg-primary",
+ "relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full text-message-action-foreground shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
+ "bg-message-action enabled:shadow-message-action/24 hover:bg-message-action-hover",
)}
{...pointerFocusProps}
disabled={
@@ -233,11 +231,6 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
: "Send message"
}
>
- {stageBackdropVariant ? (
- <span className="absolute inset-0 -z-10" aria-hidden="true">
- <StageBackdropButtonArt variant={stageBackdropVariant} />
- </span>
- ) : null}
{isConnecting || isSendBusy ? (
<Spinner className="size-3.5" aria-hidden="true" />
) : (
diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx
index bfc2d88ba..9e9238515 100644
--- a/apps/web/src/components/chat/ComposerStashMenu.tsx
+++ b/apps/web/src/components/chat/ComposerStashMenu.tsx
@@ -94,12 +94,12 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
<div className="dropdown-glass relative w-full overflow-hidden rounded-[20px]">
<CommandList className="max-h-72">
<CommandGroup>
- <CommandGroupLabel className="flex items-center gap-1.5 px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/55">
+ <CommandGroupLabel className="flex items-center gap-1.5 px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-secondary-label">
<BookmarkIcon className="size-3" aria-hidden="true" />
Stashed prompts
</CommandGroupLabel>
{entries.length === 0 ? (
- <p className="px-3 pb-3 pt-1 text-muted-foreground/70 text-xs">
+ <p className="px-3 pb-3 pt-1 text-secondary-label text-xs">
Nothing stashed yet. Press ⌘S with a prompt in the composer to stash it.
</p>
) : (
@@ -134,23 +134,23 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
))}
</span>
) : (
- <BookmarkIcon className="size-4 shrink-0 text-muted-foreground/60" />
+ <BookmarkIcon className="size-4 shrink-0 text-icon-muted" />
)}
<span className="min-w-0 flex-1 truncate text-sm">
{stashEntrySnippet(entry)}
</span>
{entry.pendingImageCount ? (
- <span className="shrink-0 text-[10px] text-muted-foreground/60">
+ <span className="shrink-0 text-[10px] text-secondary-label">
saving {entry.pendingImageCount} image
{entry.pendingImageCount === 1 ? "" : "s"}…
</span>
) : missingImageCount(entry) > 0 ? (
- <span className="shrink-0 text-[10px] text-amber-600">
+ <span className="shrink-0 text-[10px] text-warning-foreground">
{missingImageCount(entry)} image
{missingImageCount(entry) === 1 ? "" : "s"} dropped
</span>
) : null}
- <span className="shrink-0 text-muted-foreground/60 text-xs">
+ <span className="shrink-0 text-secondary-label text-xs">
{formatRelativeTimeLabel(entry.createdAt)}
</span>
<Button
diff --git a/apps/web/src/components/chat/ContextWindowMeter.tsx b/apps/web/src/components/chat/ContextWindowMeter.tsx
index d23448247..752ec4013 100644
--- a/apps/web/src/components/chat/ContextWindowMeter.tsx
+++ b/apps/web/src/components/chat/ContextWindowMeter.tsx
@@ -26,7 +26,7 @@ export function ContextWindowMeter(props: {
const showTotalProcessed = totalProcessedTokens !== null && totalProcessedTokens > 0;
const isOverloaded = normalizedPercentage > 90;
const usageColor = isOverloaded
- ? "var(--color-red-500)"
+ ? "var(--color-error)"
: "color-mix(in oklab, var(--color-muted-foreground) 72%, transparent)";
return (
@@ -91,7 +91,7 @@ export function ContextWindowMeter(props: {
<div className="flex items-center justify-between gap-3">
<div className="font-medium text-muted-foreground text-xs">Context Window</div>
{usage.maxTokens !== null && usedPercentage ? (
- <div className="text-[11px] tabular-nums text-muted-foreground/70">
+ <div className="text-secondary-label text-[11px] tabular-nums">
<span>{usedPercentage}</span>
<span className="mx-1">·</span>
<span>
@@ -100,7 +100,7 @@ export function ContextWindowMeter(props: {
</span>
</div>
) : (
- <div className="text-[11px] tabular-nums text-muted-foreground/70">
+ <div className="text-secondary-label text-[11px] tabular-nums">
{formatContextWindowTokens(usage.usedTokens)}
</div>
)}
@@ -122,14 +122,14 @@ export function ContextWindowMeter(props: {
) : null}
{showTotalProcessed ? (
<div className="flex items-center justify-between gap-3 text-[11px] leading-4">
- <span className="text-muted-foreground/60">Total processed</span>
- <span className="font-medium tabular-nums text-muted-foreground/80">
+ <span className="text-secondary-label">Total processed</span>
+ <span className="font-medium tabular-nums text-secondary-label">
{formatContextWindowTokens(totalProcessedTokens)}
</span>
</div>
) : null}
{usage.compactsAutomatically ? (
- <div className="mt-1 text-pretty text-[11px] font-medium text-muted-foreground/70">
+ <div className="mt-1 text-pretty text-secondary-label text-[11px] font-medium">
{providerDisplayName ?? "It"} automatically compacts its context when needed.
</div>
) : null}
diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx
index cf055f05b..0f6832f40 100644
--- a/apps/web/src/components/chat/MessagesTimeline.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx
@@ -461,7 +461,7 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("Show full message");
expect(markup).toContain('data-user-message-collapsible="false"');
- expect(markup).toContain("rounded-2xl bg-accent p-3");
+ expect(markup).toContain("rounded-2xl bg-message p-3");
});
it("renders inline terminal labels with the composer chip UI", () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 9e10a8b39..ec9ef1bf7 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -534,9 +534,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
return (
<div className="flex h-full items-center justify-center">
- <p className="text-sm text-muted-foreground/30">
- Send a message to start the conversation.
- </p>
+ <p className="text-placeholder text-sm">Send a message to start the conversation.</p>
</div>
);
}
@@ -965,7 +963,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
return (
<div className="group flex flex-col items-end gap-1">
- <div className="relative max-w-[80%] rounded-2xl bg-accent p-3">
+ <div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
{regularImages.length > 0 && (
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
@@ -991,7 +989,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
/>
</button>
) : (
- <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
+ <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-secondary-label text-[11px]">
{image.name}
</div>
)}
@@ -1270,7 +1268,7 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
const { workingStepLabel } = use(TimelineRowActivityCtx);
return (
<div className="py-0.5 pl-1.5">
- <div className="flex min-w-0 items-center gap-2 pt-1 text-[11px] text-muted-foreground/70 tabular-nums">
+ <div className="flex min-w-0 items-center gap-2 pt-1 text-secondary-label text-[11px] tabular-nums">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:200ms]" />
@@ -1349,9 +1347,7 @@ const WorkGroupSection = memo(function WorkGroupSection({
return (
<section className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
{!onlyToolEntries && (
- <p className="px-0.5 pb-0.5 font-medium text-[11px] text-muted-foreground/65">
- {groupLabel}
- </p>
+ <p className="px-0.5 pb-0.5 font-medium text-secondary-label text-[11px]">{groupLabel}</p>
)}
<div className="space-y-px">
{nonEmptyEntries.map((workEntry) => (
@@ -1391,7 +1387,7 @@ function WorkGroupToggleTimelineRow({
ctx.onToggleWorkGroup(row.groupId, anchorElement);
}}
>
- <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
+ <span className="flex size-5 shrink-0 items-center justify-center text-icon-muted">
<ChevronDownIcon
className={cn(
"size-3.5 shrink-0 opacity-70 transition-transform duration-200",
@@ -1400,11 +1396,11 @@ function WorkGroupToggleTimelineRow({
/>
</span>
{row.expanded ? (
- <span className="font-medium text-foreground/82">
+ <span className="font-medium text-foreground">
Show fewer {row.onlyToolEntries ? "tool calls" : "log entries"}
</span>
) : (
- <span className="font-medium text-foreground/82">
+ <span className="font-medium text-foreground">
+{row.hiddenCount} previous {labelNoun}
</span>
)}
@@ -1509,7 +1505,7 @@ const UserMessageElementContextChip = memo(function UserMessageElementContextChi
<Tooltip>
<TooltipTrigger
render={
- <span className="inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-background/70 px-1.5 py-0.5 text-xs text-foreground/85">
+ <span className="inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-background/70 px-1.5 py-0.5 text-foreground/85 text-xs">
<MousePointerClickIcon className="size-3 shrink-0" />
<span className="truncate">{props.context.header}</span>
</span>
@@ -1549,13 +1545,13 @@ function UserMessagePreviewAnnotationCard(props: {
) : null}
<div className="min-w-0 px-2.5 py-2">
{props.annotation.comment ? (
- <div className="max-w-80 truncate text-xs font-medium text-foreground/90">
+ <div className="max-w-80 truncate text-foreground text-xs font-medium">
{props.annotation.comment}
</div>
) : null}
<div
className={cn(
- "flex items-center gap-2 text-[10px] text-muted-foreground",
+ "flex items-center gap-2 text-secondary-label text-[10px]",
props.annotation.comment && "mt-1",
)}
>
@@ -1644,7 +1640,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
aria-expanded={expanded}
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
- className="-ml-1 h-6 rounded-md px-1.5 text-xs text-muted-foreground/72 hover:bg-muted/55 hover:text-foreground/85"
+ className="-ml-1 h-6 rounded-md px-1.5 text-secondary-label text-xs hover:bg-muted/55 hover:text-message-foreground"
>
{expanded ? "Show less" : "Show full message"}
</Button>
@@ -1683,7 +1679,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
- className="text-foreground"
+ className="text-message-foreground"
lineBreaks
/>
) : null}
@@ -1695,7 +1691,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) {
return (
- <div className="space-y-3 text-sm leading-relaxed text-foreground">
+ <div className="space-y-3 text-message-foreground text-sm leading-relaxed">
{reviewCommentSegments.map((segment) =>
segment.kind === "text" ? (
segment.text.trim().length > 0 ? (
@@ -1705,7 +1701,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
- className="text-foreground"
+ className="text-message-foreground"
lineBreaks
/>
</div>
@@ -1764,7 +1760,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
- <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
+ <div className="whitespace-pre-wrap wrap-break-word text-message-foreground text-sm leading-relaxed">
{inlineNodes}
</div>
);
@@ -1793,7 +1789,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
- className="text-foreground"
+ className="text-message-foreground"
lineBreaks
/>,
);
@@ -1802,7 +1798,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
- <div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
+ <div className="whitespace-pre-wrap wrap-break-word text-message-foreground text-sm leading-relaxed">
{inlineNodes}
</div>
);
@@ -1818,7 +1814,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
- className="text-foreground"
+ className="text-message-foreground"
lineBreaks
/>
);
@@ -1835,10 +1831,10 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
return (
<div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
<div className="space-y-1">
- <div className="text-xs font-medium text-foreground">
+ <div className="text-message-foreground text-xs font-medium">
{formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
</div>
- <div className="text-[11px] text-muted-foreground">
+ <div className="text-secondary-label text-[11px]">
{comment.sectionTitle} · {comment.rangeLabel}
</div>
</div>
@@ -1853,7 +1849,7 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={ctx.skills}
- className="text-foreground"
+ className="text-message-foreground"
/>
)}
{renderablePatch?.kind === "files" &&
@@ -1978,24 +1974,24 @@ function workToneIcon(tone: TimelineWorkEntry["tone"]): {
if (tone === "error") {
return {
iconName: "circle-alert",
- className: "text-foreground/92",
+ className: "text-foreground",
};
}
if (tone === "thinking") {
return {
iconName: "bot",
- className: "text-foreground/92",
+ className: "text-foreground",
};
}
if (tone === "info") {
return {
iconName: "check",
- className: "text-muted-foreground",
+ className: "text-icon-muted",
};
}
return {
iconName: "zap",
- className: "text-foreground/92",
+ className: "text-foreground",
};
}
@@ -2244,14 +2240,14 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
: showDestructiveRowStyle
? "text-destructive"
: workEntry.tone === "tool" || showFailedIndicator
- ? "text-muted-foreground/65"
+ ? "text-icon-muted"
: iconConfig.className,
);
const headingClass = showWarningIndicator
? "font-medium text-warning"
: showDestructiveRowStyle
? "font-medium text-destructive"
- : "font-medium text-foreground/82";
+ : "font-medium text-foreground";
const turnSettled = !activity.activeTurnInProgress;
const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry);
const showSuccessIndicator =
@@ -2293,11 +2289,11 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
<p className="flex min-w-0 w-full items-baseline gap-1.5 text-[12px] leading-5">
<span className={cn("min-w-0 shrink truncate", headingClass)}>{heading}</span>
{preview && (
- <span className="min-w-0 flex-1 truncate text-muted-foreground/55">{preview}</span>
+ <span className="min-w-0 flex-1 truncate text-secondary-label">{preview}</span>
)}
</p>
</div>
- <div className="flex shrink-0 items-center gap-px text-muted-foreground/55">
+ <div className="flex shrink-0 items-center gap-px text-icon-muted">
<span
className="flex size-4 shrink-0 items-center justify-center"
aria-hidden={!canExpand}
@@ -2362,7 +2358,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
onClick={stopRowToggle}
onPointerDown={stopRowToggle}
>
- <pre className="max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed text-muted-foreground select-text">
+ <pre className="max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-[11px] leading-relaxed select-text">
{expandedBody}
</pre>
</div>
diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx
index a74a4ebf8..70475ffd0 100644
--- a/apps/web/src/components/chat/ModelListRow.tsx
+++ b/apps/web/src/components/chat/ModelListRow.tsx
@@ -69,7 +69,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
</div>
{props.showNewBadge ? (
<span
- className="shrink-0 rounded border border-amber-500/35 bg-amber-500/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-amber-800 dark:border-amber-400/30 dark:bg-amber-400/12 dark:text-amber-200"
+ className="shrink-0 rounded border border-update/35 bg-update/15 px-0.5 py-px text-[10px] font-bold uppercase leading-none tracking-wide text-update-foreground"
aria-label="New model"
>
New
diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx
index 24ec66cd6..82ee33615 100644
--- a/apps/web/src/components/chat/ModelPickerSidebar.tsx
+++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx
@@ -29,7 +29,7 @@ const SELECTED_INDICATOR_CLASS =
"pointer-events-none absolute -right-1 top-1/2 z-10 h-5 w-0.75 -translate-y-1/2 rounded-l-full bg-primary";
const BADGE_BASE_CLASS =
"pointer-events-none absolute -right-0.5 top-0.5 z-10 flex size-3.5 items-center justify-center rounded-full bg-transparent shadow-sm ";
-const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-amber-600 dark:text-amber-300 `;
+const NEW_BADGE_CLASS = `${BADGE_BASE_CLASS} text-update `;
/** Opens toward the rail so the list stays readable (not over the model names). */
const PICKER_TOOLTIP_SIDE = "left" as const;
diff --git a/apps/web/src/components/chat/PierreEntryIcon.tsx b/apps/web/src/components/chat/PierreEntryIcon.tsx
index 17dfa8362..df41adb7d 100644
--- a/apps/web/src/components/chat/PierreEntryIcon.tsx
+++ b/apps/web/src/components/chat/PierreEntryIcon.tsx
@@ -73,9 +73,9 @@ export const PierreEntryIcon = memo(function PierreEntryIcon(props: {
if (!icon) {
return props.kind === "directory" ? (
- <FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
+ <FolderIcon className={cn("size-4 text-icon-muted", props.className)} />
) : (
- <FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
+ <FileIcon className={cn("size-4 text-icon-muted", props.className)} />
);
}
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index a736cf96c..090acdb9c 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -23,7 +23,7 @@ import { OpenInPicker } from "~/components/chat/OpenInPicker";
import { useClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
-import { resolveDiffThemeName } from "~/lib/diffRendering";
+import { DIFF_SURFACE_THEME_UNSAFE_CSS, resolveDiffThemeName } from "~/lib/diffRendering";
import { cn } from "~/lib/utils";
import { isPreviewSupportedInRuntime } from "~/previewStateStore";
import { resolvePathLinkTarget } from "~/terminal-links";
@@ -84,6 +84,16 @@ const RENDER_MARKDOWN_STORAGE_KEY = "t3code.renderMarkdown";
const FILE_SAVE_DEBOUNCE_MS = 500;
const FILE_LINK_REVEAL_ATTRIBUTE = "data-file-link-reveal";
const FILE_LINK_REVEAL_UNSAFE_CSS = `
+ ${DIFF_SURFACE_THEME_UNSAFE_CSS}
+
+ diffs-container {
+ --diffs-bg: var(--code-background, var(--background)) !important;
+ --diffs-light-bg: var(--code-background, var(--background)) !important;
+ --diffs-dark-bg: var(--code-background, var(--background)) !important;
+ background-color: var(--code-background, var(--background)) !important;
+ color: var(--code-foreground, var(--foreground)) !important;
+ }
+
[${FILE_LINK_REVEAL_ATTRIBUTE}][data-line] {
background-color: light-dark(
color-mix(
@@ -959,7 +969,7 @@ export default function FilePreviewPanel({
</div>
) : null}
{relativePath && file.data?.truncated ? (
- <div className="shrink-0 border-b border-amber-500/20 bg-amber-500/8 px-3 py-1.5 text-[11px] text-amber-700 dark:text-amber-300">
+ <div className="shrink-0 border-b border-warning/20 bg-warning-surface px-3 py-1.5 text-[11px] text-warning-foreground">
Preview limited to the first 1 MB of a {file.data.byteLength.toLocaleString()} byte file.
</div>
) : null}
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
index 75235a053..22a91b7c1 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -122,6 +122,7 @@ describe("KeybindingsSettings.logic", () => {
it("formats static and project script command labels", () => {
expect(commandLabel("commandPalette.toggle")).toBe("Command Palette: Toggle");
+ expect(commandLabel("themeEditor.toggle")).toBe("Theme Editor: Toggle");
expect(commandLabel("script.setup-db.run")).toBe("Run Script: Setup Db");
});
diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx
index 2a691943d..17b1ebdf3 100644
--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx
+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx
@@ -619,7 +619,7 @@ export function ProviderInstanceCard({
"size-5 rounded-sm p-0",
versionAdvisory.emphasis === "strong"
? "text-warning hover:text-warning"
- : "text-primary hover:text-primary",
+ : "text-update hover:text-update",
)}
aria-label="Update available — view details"
>
diff --git a/apps/web/src/components/settings/SettingsFontPreviews.tsx b/apps/web/src/components/settings/SettingsFontPreviews.tsx
index 9541a0f07..05ea2c9f0 100644
--- a/apps/web/src/components/settings/SettingsFontPreviews.tsx
+++ b/apps/web/src/components/settings/SettingsFontPreviews.tsx
@@ -85,6 +85,26 @@ function loadDiffPreviewHtml(theme: DiffThemeName): Promise<readonly string[]> {
return promise;
}
+// Pierre's prerendered stylesheet bakes its own light/dark surface colors
+// into the shadow root's @layer rules. These unlayered rules win the cascade
+// without !important and re-point the surfaces at the app's code tokens
+// (custom properties inherit across the shadow boundary), so the preview
+// follows the active theme exactly like the real diff panel does.
+const DIFF_PREVIEW_THEME_BRIDGE = `
+ :host {
+ color: var(--code-foreground);
+ background-color: var(--code-background);
+ --diffs-fg: var(--code-foreground);
+ --diffs-bg: var(--code-background);
+ --diffs-light-bg: var(--code-background);
+ --diffs-dark-bg: var(--code-background);
+ }
+ [data-diffs-header] {
+ background-color: var(--code-background);
+ color: var(--code-foreground);
+ }
+`;
+
function StaticDiffHtml({ html }: { html: string }) {
const hostRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
@@ -92,6 +112,9 @@ function StaticDiffHtml({ html }: { html: string }) {
if (host === null) return;
const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
shadow.innerHTML = html;
+ const bridge = document.createElement("style");
+ bridge.textContent = DIFF_PREVIEW_THEME_BRIDGE;
+ shadow.append(bridge);
}, [html]);
return <div ref={hostRef} />;
}
@@ -158,7 +181,7 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
const mountRef = useRef<HTMLDivElement>(null);
const surfaceRef = useRef<GhosttyTerminalSurface | null>(null);
const fontRef = useRef({ family, size });
- const { resolvedTheme } = useTheme();
+ const { theme, resolvedTheme } = useTheme();
useEffect(() => {
const current = fontRef.current;
@@ -167,12 +190,14 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
void surfaceRef.current?.setFont(previewTerminalFont(family, size));
}, [family, size]);
+ // Re-read the terminal tokens on any theme change — switching between two
+ // palettes can leave resolvedTheme (light/dark) untouched.
useEffect(() => {
const mount = mountRef.current;
const surface = surfaceRef.current;
if (!mount || !surface) return;
surface.setTheme(terminalThemeFromApp(mount));
- }, [resolvedTheme]);
+ }, [theme, resolvedTheme]);
useEffect(() => {
const mount = mountRef.current;
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 00d9573a1..5b9347f03 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -52,7 +52,13 @@ import {
} from "../SidebarStageBackdrop";
import { isElectron } from "../../env";
import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";
-import { useTheme } from "../../hooks/useTheme";
+import { useCustomThemes } from "../../hooks/useCustomThemes";
+import {
+ readAppearanceModePreference,
+ readThemeHalves,
+ readThemePreference,
+ useTheme,
+} from "../../hooks/useTheme";
import { useLocalStorage } from "../../hooks/useLocalStorage";
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
import { useThreadActions } from "../../hooks/useThreadActions";
@@ -106,6 +112,7 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../
import { Switch } from "../ui/switch";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { ThemeLibrary } from "./ThemeSettings";
import {
backgroundActivityOverrideSettings,
backgroundActivitySharedPolicySettings,
@@ -131,21 +138,6 @@ import {
import { searchableSetting } from "./settingsSearch";
import { ProjectFavicon } from "../ProjectFavicon";
-const THEME_OPTIONS = [
- {
- value: "system",
- label: "System",
- },
- {
- value: "light",
- label: "Light",
- },
- {
- value: "dark",
- label: "Dark",
- },
-] as const;
-
const ENVIRONMENT_IDENTIFICATION_LABELS: Record<EnvironmentIdentificationMode, string> = {
artwork: "Artwork",
pill: "Version pill",
@@ -432,7 +424,15 @@ function AboutVersionSection() {
}
export function useSettingsRestore(onRestored?: () => void) {
- const { theme, setTheme } = useTheme();
+ const {
+ theme,
+ setTheme,
+ followSystem,
+ setFollowSystem,
+ setThemeHalf,
+ clearThemeHalves,
+ themeHalves,
+ } = useTheme();
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
@@ -445,6 +445,8 @@ export function useSettingsRestore(onRestored?: () => void) {
const changedSettingLabels = useMemo(
() => [
...(theme !== "system" ? ["Theme"] : []),
+ ...(!followSystem ? ["Follow system"] : []),
+ ...(themeHalves !== null ? ["Theme mix"] : []),
...(settings.glassOpacity !== DEFAULT_UNIFIED_SETTINGS.glassOpacity ? ["Glass opacity"] : []),
...(settings.environmentIdentificationMode !==
DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode
@@ -525,6 +527,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
settings.wordWrap,
+ followSystem,
theme,
],
);
@@ -539,7 +542,57 @@ export function useSettingsRestore(onRestored?: () => void) {
);
if (!confirmed) return;
- setTheme("system");
+ // Only touch the theme keys that are actually dirty, so a theme-storage
+ // failure cannot block restoring unrelated settings. Preferences are
+ // re-read after the confirmation dialog: they may have changed (another
+ // tab, an OS flip) while it was open, and rollback must restore the live
+ // values rather than the ones captured at render time.
+ let previousTheme = theme;
+ try {
+ previousTheme = readThemePreference();
+ } catch {
+ // Storage is unreadable; the render-time value is the best rollback.
+ }
+ // The mix may have changed while the confirmation dialog was open; both
+ // the dirty check and the rollback must see the live value.
+ const liveHalves = readThemeHalves();
+ const needsThemeReset = previousTheme !== "system";
+ const needsMixReset = liveHalves !== null;
+ // Same for the appearance mode: trusting the render-time value would skip
+ // the reset and report success while a non-system mode stayed in storage.
+ const needsFollowSystemReset = readAppearanceModePreference(previousTheme) !== "system";
+ const notifyThemeRestoreFailure = () => {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Couldn’t restore theme settings",
+ description: "Try again.",
+ }),
+ );
+ };
+ // Rollback restores the base preference first (which clears any mix) and
+ // then re-applies the captured mix on top, so no failure path can leave
+ // the pair of keys half-restored.
+ const previousHalves = liveHalves;
+ const rollbackThemeState = () => {
+ if (needsThemeReset) setTheme(previousTheme);
+ if (previousHalves?.light) setThemeHalf("light", previousHalves.light);
+ if (previousHalves?.dark) setThemeHalf("dark", previousHalves.dark);
+ };
+ if (needsThemeReset && !setTheme("system")) {
+ notifyThemeRestoreFailure();
+ return;
+ }
+ if (needsMixReset && !clearThemeHalves()) {
+ rollbackThemeState();
+ notifyThemeRestoreFailure();
+ return;
+ }
+ if (needsFollowSystemReset && !setFollowSystem(true)) {
+ rollbackThemeState();
+ notifyThemeRestoreFailure();
+ return;
+ }
updateSettings({
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
@@ -566,7 +619,17 @@ export function useSettingsRestore(onRestored?: () => void) {
fontFamilyTerminal: DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal,
});
onRestored?.();
- }, [changedSettingLabels, onRestored, setTheme, updateSettings]);
+ }, [
+ changedSettingLabels,
+ clearThemeHalves,
+ onRestored,
+ setFollowSystem,
+ setTheme,
+ setThemeHalf,
+ theme,
+ themeHalves,
+ updateSettings,
+ ]);
return {
changedSettingLabels,
@@ -841,7 +904,18 @@ function BackgroundActivityAdvancedDialog({
}
export function AppearanceSettingsPanel() {
- const { theme, setTheme } = useTheme();
+ const {
+ appearanceMode,
+ refreshTheme,
+ resolvedTheme,
+ setAppearanceMode,
+ setTheme,
+ setThemeHalf,
+ theme,
+ themeHalves,
+ } = useTheme();
+ const customThemes = useCustomThemes();
+ const [isImportThemeOpen, setIsImportThemeOpen] = useState(false);
const settings = usePrimarySettings();
const updateSettings = useUpdatePrimarySettings();
const environmentStageLabel = useEnvironmentStageLabel();
@@ -857,38 +931,21 @@ export function AppearanceSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection id="appearance" title="Appearance">
- <SettingsRow
- {...searchableSetting("theme")}
- description="Choose how T3 Code looks across the app."
- resetAction={
- theme !== "system" ? (
- <SettingResetButton label="theme" onClick={() => setTheme("system")} />
- ) : null
- }
- control={
- <Select
- value={theme}
- onValueChange={(value) => {
- if (value === "system" || value === "light" || value === "dark") {
- setTheme(value);
- }
- }}
- >
- <SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
- <SelectValue>
- {THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
- </SelectValue>
- </SelectTrigger>
- <SelectPopup align="end" alignItemWithTrigger={false}>
- {THEME_OPTIONS.map((option) => (
- <SelectItem hideIndicator key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectPopup>
- </Select>
- }
- />
+ <div id={searchableSetting("theme").id}>
+ <ThemeLibrary
+ appearanceMode={appearanceMode}
+ customThemes={customThemes}
+ initialAppearance={resolvedTheme}
+ refreshTheme={refreshTheme}
+ isImportOpen={isImportThemeOpen}
+ setAppearanceMode={setAppearanceMode}
+ setTheme={setTheme}
+ setThemeHalf={setThemeHalf}
+ theme={theme}
+ themeHalves={themeHalves}
+ onImportOpenChange={setIsImportThemeOpen}
+ />
+ </div>
<SettingsRow
{...searchableSetting("setting-glass-opacity")}
diff --git a/apps/web/src/components/settings/ThemeColorPicker.tsx b/apps/web/src/components/settings/ThemeColorPicker.tsx
new file mode 100644
index 000000000..38a72ff5c
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeColorPicker.tsx
@@ -0,0 +1,550 @@
+import type { KeyboardEvent, PointerEvent } from "react";
+import { memo, useCallback, useEffect, useRef, useState } from "react";
+import { isThemeColor, type ThemeColorRole } from "../../themePalette";
+import { cn } from "../../lib/utils";
+import { Input } from "../ui/input";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+export function getThemeRoleLabel(role: ThemeColorRole): string {
+ const labels: Partial<Record<ThemeColorRole, string>> = {
+ canvas: "Background",
+ toolbar: "Toolbar background",
+ toolbarForeground: "Toolbar text",
+ toolbarBorder: "Toolbar border",
+ toolbarControl: "Toolbar control",
+ toolbarControlForeground: "Toolbar control text",
+ toolbarControlHover: "Toolbar control hover",
+ accent: "Accent color",
+ errorForeground: "Error text",
+ errorSurface: "Error background",
+ warningForeground: "Warning text",
+ warningSurface: "Warning background",
+ updateForeground: "Update text",
+ updateSurface: "Update background",
+ };
+ const label = labels[role];
+ if (label) return label;
+ return role.replace(/([A-Z])/g, " $1").replace(/^./, (character) => character.toUpperCase());
+}
+
+type ThemeColorHsv = {
+ h: number;
+ s: number;
+ v: number;
+};
+
+function clampThemeColor(value: number, min = 0, max = 1) {
+ return Math.min(max, Math.max(min, value));
+}
+
+/**
+ * The picker's plane and sliders operate on opaque six-digit hex, but theme
+ * colors may carry alpha. The suffix is preserved separately and re-attached
+ * on commit so adjusting hue or brightness cannot change transparency.
+ */
+function themePickerAlphaSuffix(value: string): string {
+ const trimmed = value.trim().toLowerCase();
+ const alpha = /^#[0-9a-f]{4}$/.test(trimmed)
+ ? trimmed.slice(4).repeat(2)
+ : /^#[0-9a-f]{8}$/.test(trimmed)
+ ? trimmed.slice(7)
+ : "";
+ return alpha === "ff" ? "" : alpha;
+}
+
+function normalizeThemePickerColor(value: string): string {
+ const trimmed = value.trim();
+ if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
+ return `#${trimmed
+ .slice(1)
+ .split("")
+ .map((character) => `${character}${character}`)
+ .join("")}`;
+ }
+ if (/^#[0-9a-f]{4}$/i.test(trimmed)) {
+ return `#${trimmed
+ .slice(1, 4)
+ .split("")
+ .map((character) => `${character}${character}`)
+ .join("")}`;
+ }
+ if (/^#[0-9a-f]{6}$/i.test(trimmed)) return trimmed;
+ if (/^#[0-9a-f]{8}$/i.test(trimmed)) return trimmed.slice(0, 7);
+ return "#000000";
+}
+
+function themeHexToHsv(hex: string): ThemeColorHsv {
+ const normalized = normalizeThemePickerColor(hex);
+ const numeric = Number.parseInt(normalized.slice(1), 16);
+ const red = ((numeric >> 16) & 255) / 255;
+ const green = ((numeric >> 8) & 255) / 255;
+ const blue = (numeric & 255) / 255;
+ const max = Math.max(red, green, blue);
+ const min = Math.min(red, green, blue);
+ const delta = max - min;
+
+ let hue = 0;
+ if (delta !== 0) {
+ if (max === red) {
+ hue = ((green - blue) / delta) % 6;
+ } else if (max === green) {
+ hue = (blue - red) / delta + 2;
+ } else {
+ hue = (red - green) / delta + 4;
+ }
+ hue *= 60;
+ if (hue < 0) hue += 360;
+ }
+
+ return {
+ h: hue,
+ s: max === 0 ? 0 : delta / max,
+ v: max,
+ };
+}
+
+function themeHsvToHex(hue: number, saturation: number, value: number) {
+ const normalizedHue = ((hue % 360) + 360) % 360;
+ const chroma = value * saturation;
+ const x = chroma * (1 - Math.abs(((normalizedHue / 60) % 2) - 1));
+ const match = value - chroma;
+ const [red, green, blue] =
+ normalizedHue < 60
+ ? [chroma, x, 0]
+ : normalizedHue < 120
+ ? [x, chroma, 0]
+ : normalizedHue < 180
+ ? [0, chroma, x]
+ : normalizedHue < 240
+ ? [0, x, chroma]
+ : normalizedHue < 300
+ ? [x, 0, chroma]
+ : [chroma, 0, x];
+
+ return `#${[red, green, blue]
+ .map((channel) =>
+ Math.round((channel + match) * 255)
+ .toString(16)
+ .padStart(2, "0"),
+ )
+ .join("")}`;
+}
+
+function themeHexToRgb(hex: string) {
+ const numeric = Number.parseInt(normalizeThemePickerColor(hex).slice(1), 16);
+ return [numeric >> 16, (numeric >> 8) & 255, numeric & 255] as const;
+}
+
+function themeRgbToHex(value: string): string | null {
+ const normalized = value
+ .trim()
+ .replace(/^rgb\(\s*/i, "")
+ .replace(/\s*\)$/, "");
+ const channels = normalized
+ .split(/[,\s]+/)
+ .filter(Boolean)
+ .map(Number);
+ if (
+ channels.length !== 3 ||
+ channels.some((channel) => !Number.isInteger(channel) || channel < 0 || channel > 255)
+ ) {
+ return null;
+ }
+
+ return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
+}
+
+function themeRgbValue(hex: string) {
+ return themeHexToRgb(hex).join(", ");
+}
+
+function ThemeColorPickerPanel({
+ label,
+ value,
+ onChange,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ const normalizedValue = normalizeThemePickerColor(value);
+ const alphaSuffix = themePickerAlphaSuffix(value);
+ const [hsv, setHsv] = useState(() => themeHexToHsv(normalizedValue));
+ const [hexDraft, setHexDraft] = useState(normalizedValue);
+ const [rgbDraft, setRgbDraft] = useState(() => themeRgbValue(normalizedValue));
+ const [isDragging, setIsDragging] = useState(false);
+ const isEditingTextRef = useRef(false);
+ const currentColor = themeHsvToHex(hsv.h, hsv.s, hsv.v);
+ const currentRgb = themeRgbValue(currentColor);
+
+ useEffect(() => {
+ // While a text field is focused, the incoming value may be the guided
+ // editor's readability-adjusted echo of what is being typed; rewriting the
+ // draft would fight the keystrokes. The swatch still tracks via hsv.
+ if (!isEditingTextRef.current) {
+ setHexDraft(normalizedValue);
+ setRgbDraft(themeRgbValue(normalizedValue));
+ }
+ // Keep the current hue/saturation when the incoming value is just our own
+ // change echoed back; hex → HSV is lossy for greys, white, and black.
+ setHsv((current) =>
+ themeHsvToHex(current.h, current.s, current.v) === normalizedValue
+ ? current
+ : themeHexToHsv(normalizedValue),
+ );
+ }, [normalizedValue]);
+
+ // Local state updates immediately for a smooth thumb; the parent commit
+ // (which can regenerate a whole guided palette) is batched to one call per
+ // animation frame.
+ const onChangeRef = useRef(onChange);
+ onChangeRef.current = onChange;
+ const pendingCommitRef = useRef<string | null>(null);
+ const commitFrameRef = useRef<number | null>(null);
+ // The final drag frame must not be lost when the popover closes or the
+ // pointer lifts before the animation frame fires.
+ const flushPendingCommit = useCallback(() => {
+ if (commitFrameRef.current !== null) {
+ cancelAnimationFrame(commitFrameRef.current);
+ commitFrameRef.current = null;
+ }
+ const pending = pendingCommitRef.current;
+ pendingCommitRef.current = null;
+ if (pending !== null) onChangeRef.current(pending);
+ }, []);
+ useEffect(() => () => flushPendingCommit(), [flushPendingCommit]);
+ const scheduleCommit = useCallback((color: string) => {
+ pendingCommitRef.current = color;
+ commitFrameRef.current ??= requestAnimationFrame(() => {
+ commitFrameRef.current = null;
+ const pending = pendingCommitRef.current;
+ pendingCommitRef.current = null;
+ if (pending !== null) onChangeRef.current(pending);
+ });
+ }, []);
+
+ const commitHsv = useCallback(
+ (nextHsv: ThemeColorHsv) => {
+ setHsv(nextHsv);
+ const nextColor = themeHsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
+ setHexDraft(nextColor);
+ setRgbDraft(themeRgbValue(nextColor));
+ scheduleCommit(nextColor + alphaSuffix);
+ },
+ [alphaSuffix, scheduleCommit],
+ );
+
+ const updateFromPlane = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const saturation = clampThemeColor((event.clientX - bounds.left) / bounds.width);
+ const value = 1 - clampThemeColor((event.clientY - bounds.top) / bounds.height);
+ commitHsv({ ...hsv, s: saturation, v: value });
+ },
+ [commitHsv, hsv],
+ );
+
+ const updateFromHue = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ const bounds = event.currentTarget.getBoundingClientRect();
+ const hue = clampThemeColor((event.clientX - bounds.left) / bounds.width) * 360;
+ commitHsv({ ...hsv, h: hue });
+ },
+ [commitHsv, hsv],
+ );
+
+ const handleHueKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const step = event.shiftKey ? 10 : 1;
+ const direction = event.key === "ArrowRight" || event.key === "ArrowUp" ? 1 : -1;
+ if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return;
+ event.preventDefault();
+ commitHsv({ ...hsv, h: (hsv.h + direction * step + 360) % 360 });
+ };
+
+ const handlePlaneKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return;
+ event.preventDefault();
+ const step = event.shiftKey ? 0.1 : 0.02;
+ const nextHsv = { ...hsv };
+ if (event.key === "ArrowLeft") nextHsv.s = clampThemeColor(hsv.s - step);
+ if (event.key === "ArrowRight") nextHsv.s = clampThemeColor(hsv.s + step);
+ if (event.key === "ArrowUp") nextHsv.v = clampThemeColor(hsv.v + step);
+ if (event.key === "ArrowDown") nextHsv.v = clampThemeColor(hsv.v - step);
+ commitHsv(nextHsv);
+ };
+
+ const handlePointerDown = (handler: (event: PointerEvent<HTMLDivElement>) => void) => {
+ return (event: PointerEvent<HTMLDivElement>) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ setIsDragging(true);
+ handler(event);
+ };
+ };
+
+ const stopDragging = () => {
+ setIsDragging(false);
+ flushPendingCommit();
+ };
+
+ // Thumbs travel inside the control by half their own size so they never
+ // clip at the extremes; movement only animates for keyboard steps and
+ // click-to-jump, never while dragging.
+ const thumbTransition = isDragging
+ ? undefined
+ : "left 80ms linear, top 80ms linear, background-color 80ms linear";
+
+ const handleHexChange = (nextValue: string) => {
+ setHexDraft(nextValue);
+ if (!/^#[0-9a-f]{6}$/i.test(nextValue)) return;
+ const nextHsv = themeHexToHsv(nextValue);
+ setHsv(nextHsv);
+ setRgbDraft(themeRgbValue(nextValue));
+ onChange(nextValue.toLowerCase());
+ };
+
+ const handleRgbChange = (nextValue: string) => {
+ setRgbDraft(nextValue);
+ const nextColor = themeRgbToHex(nextValue);
+ if (!nextColor) return;
+ setHsv(themeHexToHsv(nextColor));
+ setHexDraft(nextColor);
+ // RGB cannot express alpha, so a commit keeps the incoming suffix just
+ // like the plane and hue controls do.
+ onChange(nextColor + alphaSuffix);
+ };
+
+ return (
+ <div className="w-72 bg-popover">
+ <div className="flex items-center justify-between border-b border-border/70 px-4 py-3">
+ <div className="min-w-0">
+ <p className="truncate text-xs font-semibold text-foreground">{label}</p>
+ <p className="text-[11px] text-muted-foreground">Choose a color</p>
+ </div>
+ <span
+ className="size-7 shrink-0 rounded-full shadow-sm"
+ style={{ backgroundColor: currentColor }}
+ />
+ </div>
+ <div className="grid gap-3 px-3 pb-3 pt-3">
+ <div
+ aria-label={`${label} saturation and brightness`}
+ aria-valuetext={`saturation ${Math.round(hsv.s * 100)}%, brightness ${Math.round(hsv.v * 100)}%`}
+ className="relative h-32 cursor-crosshair touch-none overflow-hidden rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover"
+ role="slider"
+ style={{
+ backgroundColor: `hsl(${hsv.h} 100% 50%)`,
+ backgroundImage:
+ "linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)",
+ }}
+ tabIndex={0}
+ onKeyDown={handlePlaneKeyDown}
+ onLostPointerCapture={stopDragging}
+ onPointerDown={handlePointerDown(updateFromPlane)}
+ onPointerMove={(event) => {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) updateFromPlane(event);
+ }}
+ onPointerUp={stopDragging}
+ >
+ <span
+ className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
+ style={{
+ left: `calc(${hsv.s} * (100% - 0.75rem) + 0.375rem)`,
+ top: `calc(${1 - hsv.v} * (100% - 0.75rem) + 0.375rem)`,
+ transition: thumbTransition,
+ }}
+ />
+ </div>
+ <div
+ aria-label={`${label} hue`}
+ aria-valuemax={360}
+ aria-valuemin={0}
+ aria-valuenow={Math.round(hsv.h)}
+ className="relative flex h-6 cursor-pointer touch-none items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover"
+ role="slider"
+ tabIndex={0}
+ onKeyDown={handleHueKeyDown}
+ onLostPointerCapture={stopDragging}
+ onPointerDown={handlePointerDown(updateFromHue)}
+ onPointerMove={(event) => {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) updateFromHue(event);
+ }}
+ onPointerUp={stopDragging}
+ >
+ <span
+ aria-hidden
+ className="h-2.5 w-full rounded-full shadow-[inset_0_0_0_1px_rgb(0_0_0_/_12%)]"
+ style={{
+ background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
+ }}
+ />
+ <span
+ className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
+ style={{
+ left: `calc(${hsv.h / 360} * (100% - 1rem) + 0.5rem)`,
+ // The ball shows the pure hue so it stays visually anchored to
+ // the track; the header swatch carries the full current color.
+ backgroundColor: `hsl(${hsv.h} 100% 50%)`,
+ transition: thumbTransition,
+ }}
+ />
+ </div>
+ <div className="grid grid-cols-[1fr_1.2fr] gap-2">
+ <label className="grid min-w-0 gap-1">
+ <span className="px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ HEX
+ </span>
+ <span className="flex min-w-0 items-center gap-2 rounded-lg border border-input bg-background px-2 focus-within:border-ring">
+ <span
+ className="size-3.5 shrink-0 rounded-full"
+ style={{ backgroundColor: currentColor }}
+ />
+ <input
+ aria-label={`${label} picker hex value`}
+ className="h-8 min-w-0 flex-1 bg-transparent font-mono text-xs text-foreground outline-none"
+ onBlur={() => {
+ isEditingTextRef.current = false;
+ setHexDraft(currentColor);
+ setRgbDraft(currentRgb);
+ }}
+ onChange={(event) => handleHexChange(event.currentTarget.value)}
+ onFocus={() => {
+ isEditingTextRef.current = true;
+ }}
+ spellCheck={false}
+ value={hexDraft}
+ />
+ </span>
+ </label>
+ <label className="grid min-w-0 gap-1">
+ <span className="px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
+ RGB
+ </span>
+ <span className="flex min-w-0 items-center rounded-lg border border-input bg-background px-2 focus-within:border-ring">
+ <input
+ aria-label={`${label} picker RGB value`}
+ className="h-8 min-w-0 flex-1 bg-transparent font-mono text-xs text-foreground outline-none"
+ onBlur={() => {
+ isEditingTextRef.current = false;
+ setHexDraft(currentColor);
+ setRgbDraft(currentRgb);
+ }}
+ onChange={(event) => handleRgbChange(event.currentTarget.value)}
+ onFocus={() => {
+ isEditingTextRef.current = true;
+ }}
+ spellCheck={false}
+ value={rgbDraft}
+ />
+ </span>
+ </label>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ThemeColorPicker({
+ label,
+ value,
+ onChange,
+ onInteract,
+}: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ onInteract?: () => void;
+}) {
+ return (
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ aria-label={`Choose ${label} color`}
+ className="relative flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border border-foreground/30 transition-transform hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
+ onFocus={onInteract}
+ onPointerDown={onInteract}
+ title={`Choose ${label} color`}
+ type="button"
+ >
+ <span
+ className="absolute inset-0 rounded-full shadow-sm"
+ style={{ backgroundColor: value }}
+ />
+ </button>
+ }
+ />
+ <PopoverPopup
+ align="end"
+ className="overflow-hidden rounded-2xl border border-border/70 p-0 shadow-2xl [--viewport-inline-padding:0px] [&_[data-slot=popover-viewport]]:p-0"
+ data-theme-editor-panel=""
+ side="bottom"
+ sideOffset={10}
+ >
+ <ThemeColorPickerPanel label={label} onChange={onChange} value={value} />
+ </PopoverPopup>
+ </Popover>
+ );
+}
+
+export const ThemeColorField = memo(function ThemeColorField({
+ role,
+ value,
+ onChange,
+ onSelect,
+ onToggleSelected,
+ selected = false,
+ label: customLabel,
+}: {
+ role: ThemeColorRole;
+ value: string;
+ onChange: (role: ThemeColorRole, value: string) => void;
+ onSelect?: (role: ThemeColorRole) => void;
+ onToggleSelected?: (role: ThemeColorRole) => void;
+ selected?: boolean;
+ label?: string;
+}) {
+ const label = customLabel ?? getThemeRoleLabel(role);
+ const isColorValue = isThemeColor(value);
+ const swatchValue = isColorValue ? value : "#000000";
+
+ return (
+ <div
+ className={cn(
+ "flex min-h-11 min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 transition-[background-color,box-shadow]",
+ selected && "bg-accent/60 shadow-[inset_0_0_0_1px_var(--ring)]",
+ )}
+ data-theme-color-role={role}
+ >
+ <button
+ aria-label={`${selected ? "Hide" : "Show"} ${label} usage`}
+ aria-pressed={selected}
+ className="flex min-w-0 flex-1 cursor-pointer items-center rounded-md text-left text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => onToggleSelected?.(role)}
+ title={`${selected ? "Hide" : "Show"} where ${label} is used`}
+ type="button"
+ >
+ <span className="min-w-0 flex-1 truncate">{label}</span>
+ </button>
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ <ThemeColorPicker
+ label={label}
+ onChange={(nextValue) => onChange(role, nextValue)}
+ onInteract={() => onSelect?.(role)}
+ value={swatchValue}
+ />
+ <Input
+ aria-invalid={!isColorValue}
+ aria-label={`${label} hex value`}
+ className="w-28 shrink-0 rounded-md border-0 bg-black/10 font-mono text-xs text-foreground shadow-none focus-within:bg-black/15 focus-within:ring-0 dark:bg-black/20 dark:focus-within:bg-black/25 [&_[data-slot=input]]:text-right"
+ id={`${role}-hex`}
+ nativeInput
+ onChange={(event) => onChange(role, event.currentTarget.value)}
+ onFocus={() => onSelect?.(role)}
+ onPointerDown={() => onSelect?.(role)}
+ size="sm"
+ unstyled
+ value={value}
+ />
+ </div>
+ </div>
+ );
+});
diff --git a/apps/web/src/components/settings/ThemeEditorHost.tsx b/apps/web/src/components/settings/ThemeEditorHost.tsx
new file mode 100644
index 000000000..faf2d770e
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeEditorHost.tsx
@@ -0,0 +1,114 @@
+import { useCallback } from "react";
+
+import { useTheme } from "../../hooks/useTheme";
+import { getThemeDefinition, type ThemeAppearance, type ThemeDefinition } from "../../themePalette";
+import { stackedThreadToast, toastManager } from "../ui/toast";
+import { ThemeEditorPanel } from "./ThemeEditorPanel";
+import { useThemeEditorStore } from "./themeEditorStore";
+
+/**
+ * Renders the theme editor above the router. The editor paints its draft on
+ * the live app, so it has to outlive the settings route: the point is to walk
+ * through threads, panels, and pages while the colors are being tuned.
+ */
+export function ThemeEditorHost() {
+ const session = useThemeEditorStore((store) => store.session);
+ const closeThemeEditor = useThemeEditorStore((store) => store.closeThemeEditor);
+ const { theme, setTheme, themeHalves, refreshTheme } = useTheme();
+
+ // The panel reports which path it actually took: a theme removed while its
+ // editor is open resolves to null there, so the save becomes a create even
+ // though the session still names it.
+ const handleSaved = useCallback(
+ (
+ savedTheme: ThemeDefinition,
+ { created, mergedAppearance }: { created: boolean; mergedAppearance?: ThemeAppearance },
+ ) => {
+ // A merge completed an existing theme's light/dark pair; activating the
+ // whole theme shows the new palette right away.
+ if (mergedAppearance) {
+ if (!setTheme(savedTheme.id)) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not save your theme",
+ description: "Browser storage is unavailable, so the change was not kept.",
+ }),
+ );
+ return false;
+ }
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title: `${savedTheme.label} updated`,
+ description: `Its ${mergedAppearance} palette was added.`,
+ }),
+ );
+ return true;
+ }
+ if (!created) {
+ // The edited theme may be showing through the base preference or either
+ // half of the mix; the preference itself is untouched (a setTheme here
+ // would clear the mix), the palette just needs re-applying.
+ const wasActive =
+ getThemeDefinition(theme)?.id === savedTheme.id ||
+ themeHalves?.light === savedTheme.id ||
+ themeHalves?.dark === savedTheme.id;
+ if (wasActive) refreshTheme();
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title: `${savedTheme.label} saved`,
+ description: wasActive ? "Your changes are now active." : "Your changes are saved.",
+ }),
+ );
+ return true;
+ }
+
+ if (!setTheme(savedTheme.id)) {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not save your theme",
+ description: "Browser storage is unavailable, so the change was not kept.",
+ }),
+ );
+ return false;
+ }
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title: `${savedTheme.label} created`,
+ description: "It’s now active.",
+ }),
+ );
+ return true;
+ },
+ [refreshTheme, setTheme, theme, themeHalves],
+ );
+
+ if (!session) return null;
+
+ // Resolve on every render: an edit or import can change the stored
+ // definitions while a session is open.
+ const editingTheme = session.editingThemeId
+ ? (getThemeDefinition(session.editingThemeId) ?? null)
+ : null;
+ const seedTheme = session.seedThemeId ? (getThemeDefinition(session.seedThemeId) ?? null) : null;
+
+ return (
+ <ThemeEditorPanel
+ editingTheme={editingTheme}
+ initialAppearance={session.initialAppearance}
+ key={session.id}
+ onOpenChange={(open) => {
+ if (!open) closeThemeEditor();
+ }}
+ onSaved={handleSaved}
+ open
+ restoreTheme={refreshTheme}
+ seedName={session.seedName ?? undefined}
+ seedTheme={seedTheme}
+ />
+ );
+}
diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsx
new file mode 100644
index 000000000..0074ac893
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx
@@ -0,0 +1,1143 @@
+import { ChevronDownIcon, ChevronUpIcon, MousePointer2Icon, PlusIcon, XIcon } from "lucide-react";
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type PointerEvent as ReactPointerEvent,
+} from "react";
+import {
+ applyThemeColorPreview,
+ THEME_COLOR_ROLES,
+ THEME_FILE_VERSION,
+ createVividThemeColors,
+ getCustomThemes,
+ getStandardThemeColors,
+ getThemeColorsForMode,
+ getThemeModes,
+ installCustomTheme,
+ isThemeColor,
+ parseThemeFile,
+ removeCustomTheme,
+ themeIdFromName,
+ updateCustomTheme,
+ type ThemeAppearance,
+ type ThemeColorRole,
+ type ThemeDefinition,
+} from "../../themePalette";
+import { cn } from "../../lib/utils";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { Switch } from "../ui/switch";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import { getThemeRoleLabel, ThemeColorField } from "./ThemeColorPicker";
+import {
+ clearThemeInspectorHover,
+ clearThemeInspectorHighlights,
+ highlightThemeRoleUsage,
+ inspectThemeRoleAtElement,
+ inspectThemeRoleFromUtilitiesAtElement,
+ refreshThemeInspectorSpotlight,
+ showThemeInspectorHover,
+ type ThemeElementInspection,
+} from "./themeInspector";
+
+const THEME_EDITOR_PRIMARY_ROLES: ReadonlyArray<ThemeColorRole> = [
+ "canvas",
+ "chrome",
+ "sidebar",
+ "surface",
+ "text",
+ "textMuted",
+ "placeholder",
+ "secondaryLabel",
+ "iconMuted",
+ "accent",
+ "messageSurface",
+ "messageAction",
+];
+
+const THEME_EDITOR_SIMPLE_ROLES: ReadonlyArray<ThemeColorRole> = ["canvas", "accent"];
+
+const THEME_EDITOR_STATUS_ROLES: ReadonlyArray<ThemeColorRole> = [
+ "error",
+ "errorForeground",
+ "errorSurface",
+ "warning",
+ "warningForeground",
+ "warningSurface",
+ "update",
+ "updateForeground",
+ "updateSurface",
+];
+
+const THEME_EDITOR_ADVANCED_ROLES = THEME_COLOR_ROLES.filter(
+ (role) => !THEME_EDITOR_PRIMARY_ROLES.includes(role) && !THEME_EDITOR_STATUS_ROLES.includes(role),
+);
+
+const THEME_EDITOR_ROLE_GROUPS: ReadonlyArray<{
+ id: string;
+ title: string;
+ roles: ReadonlyArray<ThemeColorRole>;
+}> = [
+ {
+ id: "main",
+ title: "Main colors",
+ roles: THEME_EDITOR_PRIMARY_ROLES,
+ },
+ {
+ id: "status",
+ title: "Status colors",
+ roles: THEME_EDITOR_STATUS_ROLES,
+ },
+ {
+ id: "additional",
+ title: "Other colors",
+ roles: THEME_EDITOR_ADVANCED_ROLES,
+ },
+];
+
+type ThemeEditorColors = Record<ThemeColorRole, string>;
+type ThemeEditorColorsByAppearance = Record<ThemeAppearance, ThemeEditorColors>;
+
+// A draft with no source theme starts as the standard T3 Code look — the
+// palette on screen when no theme is installed — so creating from the default
+// theme changes nothing until the user edits a color.
+function getThemeEditorDefaults(appearance: ThemeAppearance): ThemeEditorColors {
+ return { ...getStandardThemeColors(appearance) };
+}
+
+function getThemeEditorColorsByAppearance(): ThemeEditorColorsByAppearance {
+ return {
+ light: getThemeEditorDefaults("light"),
+ dark: getThemeEditorDefaults("dark"),
+ };
+}
+
+function isThemeEditorColor(value: string): boolean {
+ return isThemeColor(value.trim());
+}
+
+function getManagedEditorColors(
+ appearance: ThemeAppearance,
+ colors: ThemeEditorColors,
+): ThemeEditorColors {
+ const defaults = getStandardThemeColors(appearance);
+ // The editor keeps the user's exact picks and derives the rest through the
+ // perceptual vivid engine, so a two-color theme carries its own identity.
+ return createVividThemeColors(
+ appearance,
+ isThemeEditorColor(colors.canvas) ? colors.canvas : defaults.canvas,
+ isThemeEditorColor(colors.accent) ? colors.accent : defaults.accent,
+ );
+}
+
+export function ThemeEditorPanel({
+ open,
+ onOpenChange,
+ onSaved,
+ editingTheme,
+ initialAppearance,
+ seedTheme,
+ seedName,
+ restoreTheme,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onSaved: (
+ theme: ThemeDefinition,
+ context: {
+ created: boolean;
+ /** Set when a create merged its palette into an existing theme. */
+ mergedAppearance?: ThemeAppearance;
+ },
+ ) => boolean;
+ editingTheme: ThemeDefinition | null;
+ initialAppearance: ThemeAppearance;
+ /** The theme a new theme starts from, so tuning what you already use is a
+ * matter of editing rather than rebuilding. Null starts from the defaults. */
+ seedTheme?: ThemeDefinition | null;
+ /** Prefilled name for an explicit duplicate; a plain create stays unnamed. */
+ seedName?: string | undefined;
+ /** Reapplies the stored theme once the draft stops being previewed. */
+ restoreTheme: () => void;
+}) {
+ const isEditing = editingTheme !== null;
+ const [name, setName] = useState("");
+ const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance);
+ const [isAdvanced, setIsAdvanced] = useState(false);
+ const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() =>
+ getThemeEditorColorsByAppearance(),
+ );
+ const [simpleColorsDirtyByAppearance, setSimpleColorsDirtyByAppearance] = useState<
+ Record<ThemeAppearance, boolean>
+ >({ light: false, dark: false });
+ const [error, setError] = useState<string | null>(null);
+ const [isMinimized, setIsMinimized] = useState(false);
+ const [roleQuery, setRoleQuery] = useState("");
+ const [isInspecting, setIsInspecting] = useState(false);
+ const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);
+ const [usageCount, setUsageCount] = useState<number | null>(null);
+ // Null parks the panel at its default corner; a value is a dragged spot,
+ // kept clamped so the header can always be grabbed again.
+ const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
+ // Null keeps the responsive default size; a value is a corner-grip resize.
+ const [size, setSize] = useState<{ width: number; height: number } | null>(null);
+ const panelRef = useRef<HTMLDivElement>(null);
+ const dragOffsetRef = useRef<{ dx: number; dy: number } | null>(null);
+ const resizeStartRef = useRef<{
+ pointerX: number;
+ pointerY: number;
+ // Where the panel's top-left sits: the grip only moves the opposite
+ // corner, so the room to grow is measured from here.
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ } | null>(null);
+ useEffect(() => {
+ if (!open) return;
+ // A panel sized wider than the window can no longer be clamped back into
+ // view by position alone -- its right edge (close, minimize, the grip)
+ // stays off screen. So the size shrinks to fit first, then the position
+ // is re-clamped against the new size.
+ const clamp = () => {
+ const margin = 8;
+ let clampedWidth: number | undefined;
+ let clampedHeight: number | undefined;
+ setSize((current) => {
+ if (!current) return current;
+ clampedWidth = Math.max(280, Math.min(current.width, window.innerWidth - margin * 2));
+ clampedHeight = Math.max(220, Math.min(current.height, window.innerHeight - margin * 2));
+ return { width: clampedWidth, height: clampedHeight };
+ });
+ setPosition((current) => {
+ if (!current) return current;
+ const clamped = clampPosition(current.x, current.y, clampedWidth);
+ // Dragging may park the panel with only its header showing, but a
+ // window resize should pull the whole thing back into view when it
+ // fits -- otherwise the grip ends up below the fold. Minimized, the
+ // stored height is not applied (the panel hugs its header), so the
+ // rendered height is what has to fit.
+ const height = isMinimized
+ ? (panelRef.current?.offsetHeight ?? 0)
+ : (clampedHeight ?? panelRef.current?.offsetHeight ?? 0);
+ const maxY = Math.max(margin, window.innerHeight - height - margin);
+ return { x: clamped.x, y: Math.min(clamped.y, maxY) };
+ });
+ };
+ window.addEventListener("resize", clamp);
+ return () => window.removeEventListener("resize", clamp);
+ // oxlint-disable-next-line exhaustive-deps -- clampPosition reads live layout only.
+ }, [isMinimized, open]);
+
+ // The draft only reaches the live app once this open has been seeded;
+ // previewing in the seeding commit would paint the previous session's
+ // colors for a frame.
+ const [isDraftSeeded, setIsDraftSeeded] = useState(false);
+ const previousOpenRef = useRef(false);
+
+ useEffect(() => {
+ if (open && !previousOpenRef.current) {
+ // Editing works on the theme itself; creating starts from the theme
+ // that is currently in use, so tuning what you already run is an edit
+ // away instead of a rebuild from the defaults.
+ const sourceTheme = editingTheme ?? seedTheme ?? null;
+ const nextColors = getThemeEditorColorsByAppearance();
+ const nextAppearance = sourceTheme
+ ? getThemeColorsForMode(sourceTheme, initialAppearance)
+ ? initialAppearance
+ : sourceTheme.appearance
+ : initialAppearance;
+ if (sourceTheme) {
+ nextColors[sourceTheme.appearance] = { ...sourceTheme.colors };
+ for (const appearance of ["light", "dark"] as const) {
+ const variantColors = sourceTheme.variants?.[appearance];
+ if (variantColors) nextColors[appearance] = { ...variantColors };
+ }
+ }
+
+ setName(editingTheme?.label ?? seedName ?? "");
+ setActiveAppearance(nextAppearance);
+ // Themes saved by the guided editor carry the managed flag; anything
+ // else (imports, hand-edited files, older saves) opens in advanced mode
+ // so guided regeneration cannot silently discard hand-tuned colors. A
+ // seeded new theme follows the same rule: its palette is only safe to
+ // regenerate when the guided editor produced it.
+ setIsAdvanced(sourceTheme !== null && sourceTheme.managed !== true);
+ setSimpleColorsDirtyByAppearance({ light: false, dark: false });
+ setColorsByAppearance(nextColors);
+ setSelectedRole(null);
+ setUsageCount(null);
+ setIsInspecting(false);
+ setError(null);
+ setIsDraftSeeded(true);
+ }
+ if (!open && isDraftSeeded) setIsDraftSeeded(false);
+ previousOpenRef.current = open;
+ }, [editingTheme, initialAppearance, isDraftSeeded, open, seedName, seedTheme]);
+
+ // A name an installed theme already uses combines instead of failing:
+ // creating adds the new palette to that theme, and renaming an existing
+ // theme onto it folds the edited palette in and retires the old entry —
+ // light "My Theme" plus a dark "My Theme" become one theme with both modes.
+ // Labels are matched as well as derived ids: a rename keeps a theme's
+ // original id, so its label is the only name a user can see and retype.
+ const nameTargetId = themeIdFromName(name);
+ const normalizedName = name.trim().toLowerCase();
+ const mergeTarget =
+ normalizedName === ""
+ ? null
+ : (getCustomThemes().find(
+ (theme) =>
+ theme.id !== editingTheme?.id &&
+ (theme.id === nameTargetId || theme.label.trim().toLowerCase() === normalizedName),
+ ) ?? null);
+ const takenAppearances = mergeTarget ? getThemeModes(mergeTarget) : [];
+ const editableAppearances = editingTheme ? getThemeModes(editingTheme) : null;
+
+ // The appearance a mode button would produce can be blocked two ways: the
+ // merge target already has that palette, or the theme being edited never
+ // had it (adding one is a create-with-same-name away).
+ const appearanceLockReason = (appearance: ThemeAppearance): string | null => {
+ if (editableAppearances && !editableAppearances.includes(appearance)) {
+ return `“${editingTheme?.label}” has no ${appearance} palette. Create a theme with the same name to add one.`;
+ }
+ if (!isEditing && takenAppearances.includes(appearance)) {
+ return `“${mergeTarget?.label}” already has a ${appearance} palette.`;
+ }
+ return null;
+ };
+
+ // Typing a name whose theme already owns the selected appearance flips the
+ // draft to the free side, so the merge affordance works without a manual
+ // toggle. Both sides taken leaves the selection alone; save is blocked with
+ // an explanation instead.
+ const mergeTargetId = mergeTarget?.id ?? null;
+ const takenAppearancesKey = takenAppearances.join(",");
+ useEffect(() => {
+ if (isEditing || mergeTargetId === null) return;
+ const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[];
+ if (taken.length !== 1) return;
+ setActiveAppearance((current) => {
+ if (!taken.includes(current)) return current;
+ return taken[0] === "light" ? "dark" : "light";
+ });
+ }, [isEditing, mergeTargetId, takenAppearancesKey]);
+
+ // The whole app wears the draft while the editor is open, so a role change
+ // is judged on the real interface rather than a miniature. The stored theme
+ // comes back when the editor closes, including on cancel.
+ useEffect(() => {
+ if (!open || !isDraftSeeded) return;
+ applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
+ }, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
+
+ useEffect(() => {
+ if (!open) return;
+ return () => {
+ restoreTheme();
+ };
+ }, [open, restoreTheme]);
+
+ const updateColor = useCallback(
+ (role: ThemeColorRole, value: string) => {
+ setColorsByAppearance((current) => {
+ const nextColors = { ...current[activeAppearance], [role]: value };
+ const shouldManageColors =
+ !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value);
+
+ return {
+ ...current,
+ [activeAppearance]: shouldManageColors
+ ? getManagedEditorColors(activeAppearance, nextColors)
+ : nextColors,
+ };
+ });
+ if (!isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value)) {
+ setSimpleColorsDirtyByAppearance((current) => ({
+ ...current,
+ [activeAppearance]: true,
+ }));
+ }
+ },
+ [activeAppearance, isAdvanced],
+ );
+
+ const selectThemeRole = useCallback((role: ThemeColorRole, reveal = false) => {
+ setSelectedRole(role);
+ if (!THEME_EDITOR_SIMPLE_ROLES.includes(role)) {
+ setIsAdvanced(true);
+ setRoleQuery("");
+ }
+ if (!reveal) return;
+
+ requestAnimationFrame(() => {
+ panelRef.current
+ ?.querySelector(`[data-theme-color-role="${role}"]`)
+ ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
+ });
+ }, []);
+
+ const toggleThemeRole = useCallback((role: ThemeColorRole) => {
+ setSelectedRole((current) => (current === role ? null : role));
+ }, []);
+
+ const clearInspectorSelection = useCallback(() => {
+ setSelectedRole(null);
+ setUsageCount(null);
+ setIsInspecting(false);
+ }, []);
+
+ const selectedHighlightRoles = selectedRole
+ ? !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)
+ ? THEME_COLOR_ROLES.filter(
+ (role) =>
+ colorsByAppearance[activeAppearance][role].trim().toLowerCase() ===
+ colorsByAppearance[activeAppearance][selectedRole].trim().toLowerCase(),
+ )
+ : [selectedRole]
+ : [];
+ const selectedHighlightRolesKey = selectedHighlightRoles.join(",");
+
+ useEffect(() => {
+ clearThemeInspectorHighlights();
+ if (!open || selectedRole === null) {
+ setUsageCount(null);
+ return;
+ }
+ // Picking a new element needs the unobscured app, so suspend the existing
+ // spotlight while the picker is armed.
+ if (isInspecting) return;
+
+ const highlightedRoles = selectedHighlightRolesKey.split(",") as Array<ThemeColorRole>;
+ const refreshHighlights = () => setUsageCount(highlightThemeRoleUsage(highlightedRoles));
+ refreshHighlights();
+ // A refresh snapshots computed styles for the whole tree twice, so it is
+ // throttled rather than run per frame: a streaming reply or a virtualized
+ // list mutates the DOM continuously and would otherwise stall the main
+ // thread for as long as the inspector is open.
+ const MIN_REFRESH_INTERVAL_MS = 500;
+ let refreshFrame: number | null = null;
+ let refreshTimer: ReturnType<typeof setTimeout> | null = null;
+ let lastRefreshAt = performance.now();
+ const scheduleRefresh = () => {
+ if (refreshFrame !== null || refreshTimer !== null) return;
+ const wait = Math.max(0, MIN_REFRESH_INTERVAL_MS - (performance.now() - lastRefreshAt));
+ const run = () => {
+ refreshFrame = null;
+ refreshTimer = null;
+ lastRefreshAt = performance.now();
+ refreshHighlights();
+ };
+ if (wait === 0) refreshFrame = requestAnimationFrame(run);
+ else refreshTimer = setTimeout(run, wait);
+ };
+ const observer = new MutationObserver((mutations) => {
+ if (
+ mutations.every(
+ (mutation) =>
+ mutation.target instanceof Element &&
+ (mutation.target.closest("#theme-inspector-spotlight") ||
+ mutation.target.closest("[data-theme-editor-panel]")),
+ )
+ ) {
+ return;
+ }
+ scheduleRefresh();
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ let spotlightFrame: number | null = null;
+ const scheduleSpotlightRefresh = () => {
+ spotlightFrame ??= requestAnimationFrame(() => {
+ spotlightFrame = null;
+ refreshThemeInspectorSpotlight();
+ });
+ };
+ window.addEventListener("resize", scheduleSpotlightRefresh);
+ window.addEventListener("scroll", scheduleSpotlightRefresh, true);
+ return () => {
+ observer.disconnect();
+ if (refreshFrame !== null) cancelAnimationFrame(refreshFrame);
+ if (refreshTimer !== null) clearTimeout(refreshTimer);
+ if (spotlightFrame !== null) cancelAnimationFrame(spotlightFrame);
+ window.removeEventListener("resize", scheduleSpotlightRefresh);
+ window.removeEventListener("scroll", scheduleSpotlightRefresh, true);
+ clearThemeInspectorHighlights();
+ };
+ }, [isInspecting, open, selectedHighlightRolesKey, selectedRole]);
+
+ useEffect(() => {
+ if (!open || !isInspecting) {
+ clearThemeInspectorHover();
+ return;
+ }
+
+ let shouldDisarmAfterClick = false;
+ let hoverTarget: Element | null = null;
+ let hoverInspection: ThemeElementInspection | null = null;
+ let hoverTimer: number | null = null;
+ let hoverFrame: number | null = null;
+ const clearHoverTimer = () => {
+ if (hoverTimer === null) return;
+ window.clearTimeout(hoverTimer);
+ hoverTimer = null;
+ };
+ const clearHover = () => {
+ clearHoverTimer();
+ hoverTarget = null;
+ hoverInspection = null;
+ clearThemeInspectorHover();
+ };
+ const showInspection = (inspection: ThemeElementInspection) => {
+ hoverInspection = inspection;
+ showThemeInspectorHover(inspection, getThemeRoleLabel(inspection.role));
+ };
+ const handlePointerOver = (event: PointerEvent) => {
+ const target = event.target;
+ if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) {
+ clearHover();
+ return;
+ }
+
+ clearHoverTimer();
+ hoverTarget = target;
+ hoverInspection = null;
+ const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(target);
+ if (utilityInspection) {
+ showInspection(utilityInspection);
+ return;
+ }
+
+ clearThemeInspectorHover();
+ hoverTimer = window.setTimeout(() => {
+ hoverTimer = null;
+ if (hoverTarget !== target || !target.isConnected) return;
+ const inspection = inspectThemeRoleAtElement(target);
+ if (inspection) showInspection(inspection);
+ }, 140);
+ };
+ const handlePointerOut = (event: PointerEvent) => {
+ if (event.relatedTarget === null) clearHover();
+ };
+ const handlePointerDown = (event: PointerEvent) => {
+ const target = event.target;
+ if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return;
+ event.preventDefault();
+ event.stopPropagation();
+ clearHoverTimer();
+ const inspection =
+ hoverTarget === target && hoverInspection
+ ? hoverInspection
+ : inspectThemeRoleAtElement(target);
+ if (!inspection) return;
+ clearHover();
+ selectThemeRole(inspection.role, true);
+ shouldDisarmAfterClick = true;
+ };
+ const blockInspectedClick = (event: MouseEvent) => {
+ const target = event.target;
+ if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return;
+ event.preventDefault();
+ event.stopPropagation();
+ if (shouldDisarmAfterClick) setIsInspecting(false);
+ shouldDisarmAfterClick = false;
+ };
+ const cancelInspection = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ clearHover();
+ clearInspectorSelection();
+ };
+ const refreshHover = () => {
+ if (!hoverInspection) return;
+ hoverFrame ??= requestAnimationFrame(() => {
+ hoverFrame = null;
+ if (hoverInspection) {
+ showThemeInspectorHover(hoverInspection, getThemeRoleLabel(hoverInspection.role));
+ }
+ });
+ };
+ const clearHoverOnScroll = () => clearHover();
+
+ document.addEventListener("pointerover", handlePointerOver, true);
+ document.addEventListener("pointerout", handlePointerOut, true);
+ document.addEventListener("pointerdown", handlePointerDown, true);
+ document.addEventListener("click", blockInspectedClick, true);
+ document.addEventListener("keydown", cancelInspection, true);
+ window.addEventListener("resize", refreshHover);
+ window.addEventListener("scroll", clearHoverOnScroll, true);
+ return () => {
+ document.removeEventListener("pointerover", handlePointerOver, true);
+ document.removeEventListener("pointerout", handlePointerOut, true);
+ document.removeEventListener("pointerdown", handlePointerDown, true);
+ document.removeEventListener("click", blockInspectedClick, true);
+ document.removeEventListener("keydown", cancelInspection, true);
+ window.removeEventListener("resize", refreshHover);
+ window.removeEventListener("scroll", clearHoverOnScroll, true);
+ clearHoverTimer();
+ if (hoverFrame !== null) cancelAnimationFrame(hoverFrame);
+ clearThemeInspectorHover();
+ };
+ }, [clearInspectorSelection, isInspecting, open, selectThemeRole]);
+
+ const handleAdvancedChange = useCallback(
+ (checked: boolean) => {
+ setIsAdvanced(checked);
+ if (checked) return;
+ if (selectedRole && !THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)) {
+ setSelectedRole(null);
+ }
+
+ // Regenerate every appearance the theme will save, not just the visible
+ // one, so the palettes shown after toggling match what gets saved.
+ const managedAppearances: ReadonlyArray<ThemeAppearance> =
+ editingTheme && getThemeModes(editingTheme).length > 1
+ ? ["light", "dark"]
+ : [activeAppearance];
+ setSimpleColorsDirtyByAppearance((current) => {
+ const next = { ...current };
+ for (const appearance of managedAppearances) next[appearance] = true;
+ return next;
+ });
+ setColorsByAppearance((current) => {
+ const next = { ...current };
+ for (const appearance of managedAppearances) {
+ next[appearance] = getManagedEditorColors(appearance, current[appearance]);
+ }
+ return next;
+ });
+ },
+ [activeAppearance, editingTheme, selectedRole],
+ );
+
+ const handleSubmit = useCallback(() => {
+ if (!name.trim()) {
+ setError("Name your theme first.");
+ return;
+ }
+
+ try {
+ // Only regenerate palettes the user actually touched in guided mode, so
+ // untouched appearances save exactly what the editor displayed.
+ const colorsForSave = !isAdvanced
+ ? {
+ light: simpleColorsDirtyByAppearance.light
+ ? getManagedEditorColors("light", colorsByAppearance.light)
+ : colorsByAppearance.light,
+ dark: simpleColorsDirtyByAppearance.dark
+ ? getManagedEditorColors("dark", colorsByAppearance.dark)
+ : colorsByAppearance.dark,
+ }
+ : colorsByAppearance;
+
+ let savedTheme: ThemeDefinition;
+ let mergedAppearance: ThemeAppearance | null = null;
+ let retiredTheme: ThemeDefinition | null = null;
+ if (editingTheme && mergeTarget) {
+ // Renamed onto another installed theme: this theme's palettes fold
+ // into it and the edited entry retires, so both cards become one.
+ // Colliding palettes cannot merge — neither side should be silently
+ // overwritten.
+ const editedModes = getThemeModes(editingTheme);
+ const collision = editedModes.find((mode) => takenAppearances.includes(mode));
+ if (collision) {
+ setError(`“${mergeTarget.label}” already has a ${collision} palette. Pick another name.`);
+ return;
+ }
+ mergedAppearance = editedModes[0] ?? null;
+ savedTheme = updateCustomTheme(
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: mergeTarget.id,
+ name: mergeTarget.label,
+ appearance: mergeTarget.appearance,
+ colors: mergeTarget.colors,
+ variants: {
+ ...mergeTarget.variants,
+ ...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
+ },
+ ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
+ }),
+ );
+ retiredTheme = editingTheme;
+ try {
+ removeCustomTheme(editingTheme.id);
+ } catch (cause) {
+ // The merge already persisted. Leaving it while the edited theme
+ // survives would collide on every retry, so the target goes back to
+ // its pre-merge palettes before the failure surfaces.
+ try {
+ updateCustomTheme(mergeTarget);
+ } catch {
+ // Storage is failing wholesale; the rethrow below reports it.
+ }
+ throw cause;
+ }
+ } else if (editingTheme) {
+ const baseAppearance = editingTheme.appearance;
+ const variantAppearance = baseAppearance === "light" ? "dark" : "light";
+ savedTheme = updateCustomTheme(
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: editingTheme.id,
+ name,
+ appearance: baseAppearance,
+ colors: colorsForSave[baseAppearance],
+ ...(getThemeModes(editingTheme).length > 1
+ ? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
+ : {}),
+ ...(isAdvanced ? {} : { managed: true }),
+ }),
+ );
+ } else if (mergeTarget) {
+ if (takenAppearances.includes(activeAppearance)) {
+ setError(
+ `“${mergeTarget.label}” already has light and dark palettes. Pick another name.`,
+ );
+ return;
+ }
+ // The new palette joins the existing theme as its other mode; its
+ // stored palettes are untouched. The guided (managed) flag only
+ // survives when every palette in the theme came from the guided
+ // editor.
+ mergedAppearance = activeAppearance;
+ savedTheme = updateCustomTheme(
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: mergeTarget.id,
+ name: mergeTarget.label,
+ appearance: mergeTarget.appearance,
+ colors: mergeTarget.colors,
+ variants: {
+ ...mergeTarget.variants,
+ [activeAppearance]: colorsForSave[activeAppearance],
+ },
+ ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
+ }),
+ );
+ } else {
+ savedTheme = installCustomTheme(
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name,
+ appearance: activeAppearance,
+ colors: colorsForSave[activeAppearance],
+ ...(isAdvanced ? {} : { managed: true }),
+ }),
+ );
+ }
+ if (
+ !onSaved(savedTheme, {
+ created: editingTheme === null && mergedAppearance === null,
+ ...(mergedAppearance ? { mergedAppearance } : {}),
+ })
+ ) {
+ if (!editingTheme && mergedAppearance === null) {
+ // Roll the install back so a retry can run it again instead of
+ // failing on the already-taken theme id.
+ try {
+ removeCustomTheme(savedTheme.id);
+ } catch {
+ // Storage is failing wholesale; the error below covers it.
+ }
+ } else if (mergeTarget && mergedAppearance !== null) {
+ // Put the pre-merge definitions back for the same reason.
+ try {
+ updateCustomTheme(mergeTarget);
+ if (retiredTheme) installCustomTheme(retiredTheme);
+ } catch {
+ // Storage is failing wholesale; the error below covers it.
+ }
+ }
+ setError("Theme saved, but it could not be made active. Try again.");
+ return;
+ }
+ onOpenChange(false);
+ } catch (cause) {
+ setError(
+ cause instanceof Error
+ ? cause.message
+ : isEditing
+ ? "Could not save the theme."
+ : "Could not create the theme.",
+ );
+ }
+ }, [
+ activeAppearance,
+ colorsByAppearance,
+ editingTheme,
+ isAdvanced,
+ isEditing,
+ mergeTarget,
+ name,
+ onOpenChange,
+ onSaved,
+ simpleColorsDirtyByAppearance,
+ takenAppearances,
+ ]);
+
+ const renderNameField = () => (
+ <label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
+ <span className="text-sm font-medium">Theme name</span>
+ <Input
+ autoFocus
+ onChange={(event) => {
+ setName(event.currentTarget.value);
+ // Most save failures are name collisions; retyping is the fix, so
+ // the stale message goes with the old name.
+ setError(null);
+ }}
+ placeholder={isEditing ? "Theme name" : "e.g. Aurora"}
+ value={name}
+ />
+ </label>
+ );
+
+ const renderAppearanceButton = (appearance: ThemeAppearance) => {
+ const isActive = activeAppearance === appearance;
+ const lockReason = appearanceLockReason(appearance);
+ // A locked mode stays hoverable so the tooltip can say why it is off;
+ // a real disabled attribute would swallow the pointer events.
+ const button = (
+ <Button
+ aria-disabled={lockReason !== null}
+ aria-pressed={isActive}
+ className={lockReason !== null ? "opacity-50" : undefined}
+ style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
+ variant={isActive ? "secondary" : "outline"}
+ onClick={() => {
+ if (lockReason === null) setActiveAppearance(appearance);
+ }}
+ >
+ {appearance === "light" ? "Light" : "Dark"}
+ </Button>
+ );
+ if (lockReason === null) return button;
+ return (
+ <Tooltip>
+ <TooltipTrigger render={button} />
+ <TooltipPopup>{lockReason}</TooltipPopup>
+ </Tooltip>
+ );
+ };
+
+ const renderAppearanceButtons = () => (
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
+ <span className="text-sm font-medium">Appearance</span>
+ <div aria-label="Theme appearance" className="grid grid-cols-2 gap-2" role="group">
+ {renderAppearanceButton("light")}
+ {renderAppearanceButton("dark")}
+ </div>
+ </div>
+ );
+
+ const renderColorsHeader = () => (
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
+ <div>
+ <h3 className="text-sm font-medium">Colors</h3>
+ {isAdvanced ? null : (
+ <p className="text-xs text-muted-foreground">Two colors, rest derived</p>
+ )}
+ </div>
+ <div className="flex min-w-0 items-start gap-3">
+ {isAdvanced ? (
+ <Input
+ aria-label="Filter colors"
+ className="min-w-0 flex-1"
+ onChange={(event) => setRoleQuery(event.currentTarget.value)}
+ placeholder="Filter colors"
+ size="sm"
+ value={roleQuery}
+ />
+ ) : null}
+ <label className="ml-auto flex shrink-0 cursor-pointer items-center gap-2 pt-0.5 text-sm font-medium">
+ <span>Advanced</span>
+ <Switch
+ aria-label="Use advanced theme colors"
+ checked={isAdvanced}
+ onCheckedChange={(checked) => handleAdvancedChange(Boolean(checked))}
+ />
+ </label>
+ </div>
+ </div>
+ );
+
+ const renderRoleFields = (
+ roles: ReadonlyArray<ThemeColorRole>,
+ gridClassName = "grid gap-2 sm:grid-cols-2",
+ ) => (
+ <div className={gridClassName}>
+ {roles.map((role) => (
+ <ThemeColorField
+ key={role}
+ onChange={updateColor}
+ onSelect={selectThemeRole}
+ onToggleSelected={toggleThemeRole}
+ role={role}
+ selected={selectedRole === role}
+ value={colorsByAppearance[activeAppearance][role]}
+ />
+ ))}
+ </div>
+ );
+
+ const renderColorFields = () => {
+ const query = roleQuery.trim().toLowerCase();
+ const groups = THEME_EDITOR_ROLE_GROUPS.map((group) => ({
+ ...group,
+ roles: group.roles.filter(
+ (role) => !query || getThemeRoleLabel(role).toLowerCase().includes(query),
+ ),
+ })).filter((group) => group.roles.length > 0);
+ return isAdvanced ? (
+ <div className="space-y-5">
+ {groups.map((group) => (
+ <section className="space-y-2" key={group.id}>
+ <h4 className="text-sm font-medium text-foreground">{group.title}</h4>
+ {renderRoleFields(group.roles, "grid gap-1")}
+ </section>
+ ))}
+ {groups.length === 0 ? <p className="text-xs text-muted-foreground">No matches.</p> : null}
+ </div>
+ ) : (
+ <div className="grid gap-1">
+ {THEME_EDITOR_SIMPLE_ROLES.map((role) => (
+ <ThemeColorField
+ key={role}
+ onChange={updateColor}
+ onSelect={selectThemeRole}
+ onToggleSelected={toggleThemeRole}
+ role={role}
+ label={role === "canvas" ? "Background" : "Accent"}
+ selected={selectedRole === role}
+ value={colorsByAppearance[activeAppearance][role]}
+ />
+ ))}
+ </div>
+ );
+ };
+
+ const clampPosition = (x: number, y: number, widthOverride?: number) => {
+ const panel = panelRef.current;
+ const margin = 8;
+ // The caller passes a width when it has just shrunk the panel: the DOM
+ // still reports the old one until React commits.
+ const width = widthOverride ?? panel?.offsetWidth ?? 0;
+ return {
+ x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)),
+ // Keep at least the header on screen even when dragged far down.
+ y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)),
+ };
+ };
+
+ const handleDragPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ // Buttons in the header keep their own behavior.
+ if ((event.target as HTMLElement).closest("button, input, a")) return;
+ const rect = panelRef.current?.getBoundingClientRect();
+ if (!rect) return;
+ dragOffsetRef.current = { dx: event.clientX - rect.x, dy: event.clientY - rect.y };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ };
+
+ const handleDragPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const offset = dragOffsetRef.current;
+ if (!offset) return;
+ setPosition(clampPosition(event.clientX - offset.dx, event.clientY - offset.dy));
+ };
+
+ const endDrag = () => {
+ dragOffsetRef.current = null;
+ };
+
+ const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const rect = panelRef.current?.getBoundingClientRect();
+ if (!rect) return;
+ event.preventDefault();
+ // The grip drags the bottom-right corner, so the top-left must hold
+ // still; the default parking spot is anchored bottom-right and would
+ // slide, so it converts to an explicit position first.
+ if (position === null) setPosition(clampPosition(rect.x, rect.y));
+ resizeStartRef.current = {
+ pointerX: event.clientX,
+ pointerY: event.clientY,
+ left: rect.x,
+ top: rect.y,
+ width: rect.width,
+ height: rect.height,
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ };
+
+ const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const start = resizeStartRef.current;
+ if (!start) return;
+ const margin = 8;
+ const MIN_WIDTH = 280;
+ const MIN_HEIGHT = 220;
+ // Grow only into the space right of and below the panel's own corner,
+ // otherwise a panel parked away from the top-left pushes its far edges
+ // (and this grip) off screen.
+ const maxWidth = Math.max(MIN_WIDTH, window.innerWidth - margin - start.left);
+ const maxHeight = Math.max(MIN_HEIGHT, window.innerHeight - margin - start.top);
+ setSize({
+ width: Math.min(Math.max(start.width + event.clientX - start.pointerX, MIN_WIDTH), maxWidth),
+ height: Math.min(
+ Math.max(start.height + event.clientY - start.pointerY, MIN_HEIGHT),
+ maxHeight,
+ ),
+ });
+ };
+
+ const endResize = () => {
+ resizeStartRef.current = null;
+ };
+
+ return (
+ <div
+ aria-label={isEditing ? "Edit theme" : "Create theme"}
+ className={cn(
+ "dialog-glass fixed z-[110] flex max-h-[min(42rem,calc(100dvh-6rem))] w-[min(26rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border text-popover-foreground",
+ position === null && "bottom-4 right-4",
+ isMinimized && "max-h-none",
+ )}
+ data-theme-editor-panel
+ ref={panelRef}
+ role="dialog"
+ style={{
+ ...(position ? { left: position.x, top: position.y } : {}),
+ ...(size ? { width: size.width } : {}),
+ // A chosen height only applies expanded; minimized keeps hugging the
+ // header. The viewport stays the ceiling either way.
+ ...(size && !isMinimized ? { height: size.height, maxHeight: "calc(100dvh - 1rem)" } : {}),
+ }}
+ >
+ <div
+ className="flex cursor-grab touch-none select-none items-center gap-1 border-b border-border/70 px-3 py-2 active:cursor-grabbing"
+ onPointerCancel={endDrag}
+ onPointerDown={handleDragPointerDown}
+ onPointerMove={handleDragPointerMove}
+ onPointerUp={endDrag}
+ >
+ <div className="flex min-w-0 flex-1 items-baseline gap-2">
+ <h2 className="shrink-0 truncate text-sm font-medium">
+ {isEditing ? "Edit theme" : "Create theme"}
+ </h2>
+ {isMinimized ? null : (
+ <p className="truncate text-xs text-muted-foreground">
+ {isInspecting
+ ? "Select an element · Esc to cancel"
+ : selectedRole
+ ? `${getThemeRoleLabel(selectedRole)} · ${usageCount ?? 0} ${usageCount === 1 ? "use" : "uses"}`
+ : "Select a color below"}
+ </p>
+ )}
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={isInspecting ? "Cancel inspecting app colors" : "Inspect app colors"}
+ aria-pressed={isInspecting}
+ size="xs"
+ variant={isInspecting ? "secondary" : "ghost"}
+ onClick={() => {
+ if (isInspecting) {
+ clearInspectorSelection();
+ return;
+ }
+ setIsInspecting(true);
+ }}
+ >
+ <MousePointer2Icon />
+ {isInspecting ? "Cancel" : "Inspect"}
+ </Button>
+ }
+ />
+ <TooltipPopup data-theme-editor-panel="">
+ {isInspecting ? "Cancel and clear the selection" : "Pick a color from the app"}
+ </TooltipPopup>
+ </Tooltip>
+ <Button
+ aria-label={isMinimized ? "Expand the theme editor" : "Minimize the theme editor"}
+ size="icon-xs"
+ variant="ghost"
+ onClick={() => setIsMinimized(!isMinimized)}
+ >
+ {isMinimized ? <ChevronUpIcon /> : <ChevronDownIcon />}
+ </Button>
+ <Button
+ aria-label="Close the theme editor"
+ size="icon-xs"
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ >
+ <XIcon />
+ </Button>
+ </div>
+
+ {isMinimized ? null : (
+ <>
+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto py-3 pl-3 pr-1.5">
+ {renderNameField()}
+ {/* Inline and above the color list: the panel scrolls, and an
+ error parked below every role would go unseen. */}
+ {error ? (
+ <p aria-live="polite" className="text-sm text-destructive">
+ {error}
+ </p>
+ ) : null}
+ {renderAppearanceButtons()}
+ <div className="space-y-3">
+ {renderColorsHeader()}
+ {renderColorFields()}
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t border-border/70 px-3 py-2">
+ <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button disabled={!name.trim()} size="sm" onClick={handleSubmit}>
+ {isEditing ? (
+ mergeTarget ? (
+ `Merge into “${mergeTarget.label}”`
+ ) : (
+ "Save changes"
+ )
+ ) : mergeTarget ? (
+ <>
+ <PlusIcon />
+ {`Add ${activeAppearance} palette`}
+ </>
+ ) : (
+ <>
+ <PlusIcon />
+ Create theme
+ </>
+ )}
+ </Button>
+ </div>
+ <div
+ aria-hidden
+ className="absolute bottom-0 right-0 z-10 flex size-5 cursor-se-resize touch-none select-none items-end justify-end p-1 text-muted-foreground/70"
+ onPointerCancel={endResize}
+ onPointerDown={handleResizePointerDown}
+ onPointerMove={handleResizePointerMove}
+ onPointerUp={endResize}
+ >
+ <svg
+ className="size-2.5"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeWidth="1.2"
+ viewBox="0 0 8 8"
+ >
+ <path d="M7 1 1 7M7 4.5 4.5 7" />
+ </svg>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/ThemeImportDialog.test.ts b/apps/web/src/components/settings/ThemeImportDialog.test.ts
new file mode 100644
index 000000000..6cd51e9b7
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeImportDialog.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { describeOversizedThemeFile, MAX_THEME_FILE_BYTES } from "./ThemeImportDialog";
+
+describe("theme import size guard", () => {
+ it("accepts anything a theme file could plausibly be", () => {
+ for (const bytes of [0, 4_096, MAX_THEME_FILE_BYTES]) {
+ expect(describeOversizedThemeFile(bytes)).toBeNull();
+ }
+ });
+
+ it("rejects a file too large to be a theme and names its size", () => {
+ const message = describeOversizedThemeFile(100 * 1024 * 1024);
+ expect(message).toContain("100.0 MB");
+ expect(message).toContain("256 KB");
+ });
+
+ it("reports sizes just past the limit in KB", () => {
+ expect(describeOversizedThemeFile(MAX_THEME_FILE_BYTES + 1)).toContain("256 KB");
+ });
+});
diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx
new file mode 100644
index 000000000..a74842aca
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeImportDialog.tsx
@@ -0,0 +1,537 @@
+import { PlusIcon, UploadIcon } from "lucide-react";
+import type { ChangeEvent, DragEvent, UIEvent } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { cn } from "../../lib/utils";
+import {
+ getCustomThemes,
+ installCustomTheme,
+ parseThemeFile,
+ removeCustomTheme,
+ THEME_FILE_VERSION,
+ updateCustomTheme,
+ type ThemeDefinition,
+} from "../../themePalette";
+import {
+ humanizeThemeName,
+ isVsCodeThemeFile,
+ pairVsCodeThemes,
+ parseVsCodeThemeFile,
+ resolveThemeLabelCollisions,
+} from "../../vscodeThemeImport";
+import { Alert } from "../ui/alert";
+import { Button } from "../ui/button";
+import {
+ Dialog,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+} from "../ui/dialog";
+
+/**
+ * A full theme export is a few KB, so anything past this is not a theme file.
+ * The guard runs on the size before the bytes are ever read: a large file
+ * would otherwise be pulled into memory, highlighted, and rendered, which
+ * locks the UI for as long as that takes.
+ */
+export const MAX_THEME_FILE_BYTES = 256 * 1024;
+
+/** Highlighting rebuilds the whole markup on every keystroke, so oversized
+ * pastes fall back to plain text instead of freezing the editor. */
+const MAX_HIGHLIGHTED_JSON_LENGTH = 20_000;
+
+function formatByteSize(bytes: number): string {
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${bytes} bytes`;
+}
+
+/** Returns the error to show for a file too large to be a theme, else null. */
+export function describeOversizedThemeFile(bytes: number): string | null {
+ if (bytes <= MAX_THEME_FILE_BYTES) return null;
+ return `That file is ${formatByteSize(bytes)}. Theme files are only a few KB, so this one was not read (limit ${formatByteSize(MAX_THEME_FILE_BYTES)}).`;
+}
+
+function escapeJsonHtml(value: string): string {
+ return value.replace(
+ /[&<>"']/g,
+ (character) =>
+ ({
+ "&": "&amp;",
+ "<": "&lt;",
+ ">": "&gt;",
+ '"': "&quot;",
+ "'": "&#39;",
+ })[character] ?? character,
+ );
+}
+
+function highlightJson(value: string): string {
+ const tokenPattern =
+ /"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g;
+ let highlighted = "";
+ let cursor = 0;
+
+ for (const match of value.matchAll(tokenPattern)) {
+ const token = match[0];
+ const index = match.index ?? 0;
+ highlighted += escapeJsonHtml(value.slice(cursor, index));
+
+ let tokenClass = "theme-json-number";
+ if (token.startsWith('"')) {
+ tokenClass = /^\s*:/.test(value.slice(index + token.length))
+ ? "theme-json-key"
+ : "theme-json-string";
+ } else if (token === "true" || token === "false" || token === "null") {
+ tokenClass = "theme-json-constant";
+ }
+ highlighted += `<span class="${tokenClass}">${escapeJsonHtml(token)}</span>`;
+ cursor = index + token.length;
+ }
+
+ return highlighted + escapeJsonHtml(value.slice(cursor));
+}
+
+function ThemeJsonEditor({
+ id,
+ value,
+ onChange,
+}: {
+ id: string;
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ const highlightRef = useRef<HTMLPreElement>(null);
+ const isPlainText = value.length > MAX_HIGHLIGHTED_JSON_LENGTH;
+ const highlightedJson = useMemo(
+ () => (value.length > MAX_HIGHLIGHTED_JSON_LENGTH ? "" : highlightJson(value)),
+ [value],
+ );
+
+ const syncScroll = useCallback((event: UIEvent<HTMLTextAreaElement>) => {
+ const highlightElement = highlightRef.current;
+ if (!highlightElement) return;
+ highlightElement.scrollTop = event.currentTarget.scrollTop;
+ highlightElement.scrollLeft = event.currentTarget.scrollLeft;
+ }, []);
+
+ return (
+ <div className="relative overflow-hidden rounded-xl border border-input bg-background shadow-xs/5 focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/24">
+ {isPlainText ? null : (
+ <pre
+ ref={highlightRef}
+ aria-hidden
+ className="pointer-events-none absolute inset-0 m-0 overflow-hidden whitespace-pre-wrap break-words p-3 font-mono text-[12px] leading-5 text-foreground"
+ >
+ <code dangerouslySetInnerHTML={{ __html: highlightedJson }} />
+ </pre>
+ )}
+ <textarea
+ aria-label="Theme JSON"
+ className={cn(
+ "relative z-10 block min-h-72 w-full resize-y overflow-auto bg-transparent p-3 font-mono text-[12px] leading-5 caret-foreground outline-none placeholder:text-muted-foreground selection:bg-accent/30",
+ isPlainText ? "text-foreground" : "text-transparent selection:text-transparent",
+ )}
+ id={id}
+ onChange={(event) => onChange(event.currentTarget.value)}
+ onScroll={syncScroll}
+ placeholder={
+ '{\n "version": 1,\n "name": "Aurora",\n "appearance": "light",\n "colors": { ... }\n}'
+ }
+ spellCheck={false}
+ value={value}
+ />
+ </div>
+ );
+}
+
+/** What the import pipeline needs from a file; DOM File satisfies it. */
+type ImportableThemeFile = { name: string; size: number; text: () => Promise<string> };
+
+export function ThemeImportDialog({
+ open,
+ onOpenChange,
+ onImported,
+ onImportedMany,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onImported: (theme: ThemeDefinition) => boolean;
+ /** Batch imports install without activating; the caller reports them. */
+ onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
+}) {
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [json, setJson] = useState("");
+ const [fileName, setFileName] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [isReading, setIsReading] = useState(false);
+ const [isDropTarget, setIsDropTarget] = useState(false);
+ // Imports whose id is already installed wait here for an update-or-copy
+ // decision instead of failing.
+ const [conflicts, setConflicts] = useState<ReadonlyArray<ThemeDefinition> | null>(null);
+ const importRequestRef = useRef(0);
+
+ useEffect(() => {
+ importRequestRef.current += 1;
+ // Reset on close too: a dialog dismissed mid-drag would otherwise reopen
+ // still wearing the drop highlight.
+ setIsDropTarget(false);
+ if (!open) return;
+ setJson("");
+ setFileName(null);
+ setError(null);
+ setIsReading(false);
+ setConflicts(null);
+ }, [open]);
+
+ const readThemeFile = useCallback(async (file: ImportableThemeFile) => {
+ // Check the size first: reading a large file is what locks the UI, so it
+ // never gets read at all.
+ const oversized = describeOversizedThemeFile(file.size);
+ if (oversized) {
+ setError(oversized);
+ return;
+ }
+
+ const requestId = ++importRequestRef.current;
+ setIsReading(true);
+ try {
+ const fileText = await file.text();
+ if (requestId !== importRequestRef.current) return;
+ setJson(fileText);
+ setFileName(file.name);
+ setError(null);
+ } catch {
+ if (requestId !== importRequestRef.current) return;
+ setError("Could not read that file. Paste the JSON below instead.");
+ } finally {
+ if (requestId === importRequestRef.current) setIsReading(false);
+ }
+ }, []);
+
+ // Several files at once import as a batch: VS Code families pair their
+ // light and dark variants, everything installs without activating, and the
+ // single-file flow keeps filling the editor for review.
+ const readThemeBatch = useCallback(
+ async (files: ReadonlyArray<ImportableThemeFile>) => {
+ const requestId = ++importRequestRef.current;
+ setIsReading(true);
+ const failures: string[] = [];
+ const parsed: Array<{ theme: ThemeDefinition; sourceName: string }> = [];
+ try {
+ for (const file of files) {
+ const oversized = describeOversizedThemeFile(file.size);
+ if (oversized) {
+ failures.push(`${file.name}: too large`);
+ continue;
+ }
+ try {
+ const value: unknown = JSON.parse(await file.text());
+ parsed.push({
+ sourceName: file.name,
+ theme: isVsCodeThemeFile(value) ? parseVsCodeThemeFile(value) : parseThemeFile(value),
+ });
+ } catch (cause) {
+ failures.push(
+ `${file.name}: ${cause instanceof Error ? cause.message : "not a theme file"}`,
+ );
+ }
+ }
+ if (requestId !== importRequestRef.current) return;
+ const installed: ThemeDefinition[] = [];
+ const conflicting: ThemeDefinition[] = [];
+ for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) {
+ if (getCustomThemes().some((existing) => existing.id === theme.id)) {
+ conflicting.push(theme);
+ continue;
+ }
+ try {
+ installed.push(installCustomTheme(theme));
+ } catch (cause) {
+ failures.push(
+ `${theme.label}: ${cause instanceof Error ? cause.message : "could not install"}`,
+ );
+ }
+ }
+ if (installed.length > 0) onImportedMany(installed, { updated: false });
+ if (failures.length > 0) {
+ setError(failures.join(" — "));
+ } else if (conflicting.length > 0) {
+ setConflicts(conflicting);
+ } else if (installed.length > 0) {
+ onOpenChange(false);
+ }
+ } finally {
+ if (requestId === importRequestRef.current) setIsReading(false);
+ }
+ },
+ [onImportedMany, onOpenChange],
+ );
+
+ const readThemeFiles = useCallback(
+ (files: ReadonlyArray<ImportableThemeFile>) => {
+ if (files.length === 0) return;
+ if (files.length === 1) void readThemeFile(files[0]!);
+ else void readThemeBatch(files);
+ },
+ [readThemeBatch, readThemeFile],
+ );
+
+ // On desktop the native picker opens in ~/.vscode/extensions (when it
+ // exists) and reads the files in the main process; the browser input is
+ // the fallback everywhere else.
+ const openFilePicker = useCallback(() => {
+ const bridge = window.desktopBridge;
+ if (bridge?.pickThemeFiles) {
+ void bridge.pickThemeFiles().then((picked) => {
+ if (!picked || picked.length === 0) return;
+ readThemeFiles(
+ picked.map((file) => ({
+ name: file.name,
+ size: file.size,
+ text: () => Promise.resolve(file.text),
+ })),
+ );
+ });
+ return;
+ }
+ fileInputRef.current?.click();
+ }, [readThemeFiles]);
+
+ const handleFileChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const files = [...(event.currentTarget.files ?? [])];
+ event.currentTarget.value = "";
+ readThemeFiles(files);
+ },
+ [readThemeFiles],
+ );
+
+ const handleDrop = useCallback(
+ (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ setIsDropTarget(false);
+ readThemeFiles([...event.dataTransfer.files]);
+ },
+ [readThemeFiles],
+ );
+
+ /** Copy of an already-installed theme under the source file's name when
+ * that differs (Dracula Soft), else the next free "Name (1)". */
+ const versionedCopy = (
+ theme: ThemeDefinition,
+ preferredName?: string | null,
+ ): ThemeDefinition => {
+ if (preferredName && preferredName.toLowerCase() !== theme.label.toLowerCase()) {
+ const candidate = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: preferredName.slice(0, 48),
+ appearance: theme.appearance,
+ colors: theme.colors,
+ ...(theme.variants ? { variants: theme.variants } : {}),
+ ...(theme.managed ? { managed: true } : {}),
+ });
+ if (!getCustomThemes().some((existing) => existing.id === candidate.id)) return candidate;
+ }
+ for (let copy = 1; copy < 100; copy += 1) {
+ const candidate = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: `${theme.label.slice(0, 48 - ` (${copy})`.length)} (${copy})`,
+ appearance: theme.appearance,
+ colors: theme.colors,
+ ...(theme.variants ? { variants: theme.variants } : {}),
+ ...(theme.managed ? { managed: true } : {}),
+ });
+ if (getCustomThemes().some((existing) => existing.id === candidate.id)) continue;
+ return candidate;
+ }
+ throw new Error(`Too many copies of "${theme.label}".`);
+ };
+
+ const resolveConflicts = useCallback(
+ (mode: "update" | "copy") => {
+ if (!conflicts) return;
+ const resolved: ThemeDefinition[] = [];
+ const failures: string[] = [];
+ const preferredName =
+ conflicts.length === 1 && fileName
+ ? humanizeThemeName(fileName.replace(/\.[^.]+$/, ""))
+ : null;
+ for (const theme of conflicts) {
+ try {
+ resolved.push(
+ mode === "update"
+ ? updateCustomTheme(theme)
+ : installCustomTheme(versionedCopy(theme, preferredName)),
+ );
+ } catch (cause) {
+ failures.push(`${theme.label}: ${cause instanceof Error ? cause.message : "failed"}`);
+ }
+ }
+ if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });
+ setConflicts(null);
+ if (failures.length > 0) setError(failures.join(" — "));
+ else onOpenChange(false);
+ },
+ [conflicts, fileName, onImportedMany, onOpenChange],
+ );
+
+ const handleSubmit = useCallback(() => {
+ // Pasted text bypasses the file guard, so the same limit applies here.
+ const oversized = describeOversizedThemeFile(json.length);
+ if (oversized) {
+ setError(oversized);
+ return;
+ }
+ try {
+ const parsed: unknown = JSON.parse(json);
+ // VS Code themes are converted on the way in; anything else has to be
+ // one of our own files.
+ const theme = isVsCodeThemeFile(parsed)
+ ? parseVsCodeThemeFile(parsed)
+ : parseThemeFile(parsed);
+ if (getCustomThemes().some((existing) => existing.id === theme.id)) {
+ setError(null);
+ setConflicts([theme]);
+ return;
+ }
+ const installedTheme = installCustomTheme(theme);
+ if (!onImported(installedTheme)) {
+ // Roll the install back so a retry can run it again instead of
+ // failing on the already-taken theme id.
+ try {
+ removeCustomTheme(installedTheme.id);
+ } catch {
+ // Storage is failing wholesale; the error below covers it.
+ }
+ setError("Theme added, but it could not be selected. Try again.");
+ return;
+ }
+ onOpenChange(false);
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "That theme file is invalid.");
+ }
+ }, [json, onImported, onOpenChange]);
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) setError(null);
+ onOpenChange(nextOpen);
+ }}
+ >
+ <DialogPopup className="max-w-3xl overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>Add a theme</DialogTitle>
+ </DialogHeader>
+ <DialogPanel className="space-y-4">
+ {(() => {
+ const dropHandlers = {
+ onDragEnter: (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ setIsDropTarget(true);
+ },
+ onDragOver: (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ setIsDropTarget(true);
+ },
+ onDragLeave: (event: DragEvent<HTMLDivElement>) => {
+ // Ignore moves between children of the drop zone.
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
+ setIsDropTarget(false);
+ },
+ onDrop: handleDrop,
+ };
+ const fileInput = (
+ <input
+ ref={fileInputRef}
+ accept=".json,application/json"
+ className="sr-only"
+ onChange={handleFileChange}
+ multiple
+ type="file"
+ />
+ );
+ const chooseButton = (label = "Choose files") => (
+ <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
+ <UploadIcon />
+ {isReading ? "Reading…" : label}
+ </Button>
+ );
+ const editorSection = () => (
+ <div className="space-y-2">
+ <div className="flex items-baseline justify-between gap-3">
+ <label className="text-sm font-medium" htmlFor="theme-json-editor">
+ Theme JSON
+ </label>
+ </div>
+ <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />
+ </div>
+ );
+ if (conflicts) {
+ return (
+ <div className="space-y-3">
+ <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
+ <p className="text-sm font-medium">Already installed</p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {conflicts.map((theme) => theme.label).join(", ")}
+ </p>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button size="sm" onClick={() => resolveConflicts("update")}>
+ Update existing
+ </Button>
+ <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
+ Keep both
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
+ Back
+ </Button>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div className="space-y-4">
+ <div
+ className={cn(
+ "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
+ isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
+ )}
+ {...dropHandlers}
+ >
+ <div className="min-w-0">
+ <p className="text-sm font-medium">Theme file</p>
+ <p className="truncate text-xs text-muted-foreground">
+ {fileName ?? "Drop T3 Code or VS Code .json files"}
+ </p>
+ </div>
+ {chooseButton()}
+ {fileInput}
+ </div>
+ {editorSection()}
+ </div>
+ );
+ })()}
+
+ {error ? (
+ <Alert aria-live="polite" variant="error">
+ {error}
+ </Alert>
+ ) : null}
+ </DialogPanel>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
+ <PlusIcon />
+ Add theme
+ </Button>
+ </DialogFooter>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/settings/ThemePreviewCircles.tsx b/apps/web/src/components/settings/ThemePreviewCircles.tsx
new file mode 100644
index 000000000..6c3f0afbd
--- /dev/null
+++ b/apps/web/src/components/settings/ThemePreviewCircles.tsx
@@ -0,0 +1,224 @@
+import { MoonIcon, SunIcon } from "lucide-react";
+import type { CSSProperties } from "react";
+import { cn } from "../../lib/utils";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
+import {
+ getThemeColorsForMode,
+ getThemeModes,
+ type ThemeAppearance,
+ type ThemeDefinition,
+} from "../../themePalette";
+
+const THEME_PREVIEW_ROLES = [
+ "sidebar",
+ "canvas",
+ "surface",
+ "accentSurface",
+ "accent",
+ "messageSurface",
+ "messageAction",
+] as const;
+type ThemePreviewRole = (typeof THEME_PREVIEW_ROLES)[number];
+type ThemeCardPreview = {
+ mode: ThemeAppearance;
+ colors: Readonly<Record<ThemePreviewRole, string>>;
+};
+export type ThemeCardDefinition = {
+ id: string;
+ label: string;
+ previews: ReadonlyArray<ThemeCardPreview>;
+};
+export type ThemeMode = ThemeAppearance | "system";
+export type ThemeCardPreviewColors = ThemeCardPreview["colors"];
+
+const STANDARD_THEME_PREVIEW_COLORS: Record<
+ ThemeAppearance,
+ Readonly<Record<ThemePreviewRole, string>>
+> = {
+ light: {
+ sidebar: "#fafafa",
+ canvas: "#fcfcfc",
+ surface: "#ffffff",
+ accentSurface: "#f4f4f5",
+ accent: "#f4f4f5",
+ messageSurface: "#e4e4e7",
+ messageAction: "#4f46e5",
+ },
+ dark: {
+ sidebar: "#0f0f10",
+ canvas: "#0a0a0a",
+ surface: "#121212",
+ accentSurface: "#27272a",
+ accent: "#1c1c1f",
+ messageSurface: "#27272a",
+ messageAction: "#8b9cff",
+ },
+};
+
+export const STANDARD_THEME_CARDS: ReadonlyArray<ThemeCardDefinition> = [
+ {
+ id: "default",
+ label: "T3 Code",
+ previews: (["light", "dark"] as const).map((mode) => ({
+ mode,
+ colors: STANDARD_THEME_PREVIEW_COLORS[mode],
+ })),
+ },
+];
+
+export function previewColorsOf(
+ card: ThemeCardDefinition,
+ mode: ThemeAppearance,
+): ThemeCardPreviewColors | null {
+ return card.previews.find((preview) => preview.mode === mode)?.colors ?? null;
+}
+
+export function getThemeCardDefinition(theme: ThemeDefinition): ThemeCardDefinition {
+ return {
+ id: theme.id,
+ label: theme.label,
+ previews: getThemeModes(theme).map((mode) => {
+ const colors = getThemeColorsForMode(theme, mode) ?? theme.colors;
+ return {
+ mode,
+ colors: {
+ sidebar: colors.sidebar,
+ canvas: colors.canvas,
+ surface: colors.surface,
+ accentSurface: colors.accentSurface,
+ accent: colors.accent,
+ messageSurface: colors.messageSurface,
+ messageAction: colors.messageAction,
+ },
+ };
+ }),
+ };
+}
+
+// Interpolating in oklab keeps the glow falloff perceptually even (no gray
+// mid-tones or banding rings), and premultiplied alpha keeps the fade to
+// transparent clean.
+function getThemePreviewStyle(
+ colors: ThemeCardPreviewColors,
+ mode: ThemeAppearance,
+): CSSProperties {
+ const isDark = mode === "dark";
+ // The canvas carries the ball's light/dark identity, so it stays dominant:
+ // a near-true base with a contained accent glow, instead of an accent wash
+ // that makes both modes read alike.
+ const modeBase = isDark
+ ? `color-mix(in oklab, ${colors.canvas} 80%, #09090b)`
+ : `color-mix(in oklab, ${colors.canvas} 80%, #ffffff)`;
+ const accentPosition = isDark ? "28% 78%" : "72% 22%";
+ const actionPosition = isDark ? "82% 18%" : "18% 82%";
+ const accentFade = isDark ? 62 : 72;
+ return {
+ backgroundColor: modeBase,
+ backgroundImage: [
+ `radial-gradient(circle at ${accentPosition} in oklab, ${colors.accent} 0%, color-mix(in oklab, ${colors.accent} ${accentFade}%, transparent) 28%, transparent 58%)`,
+ // The action color is a soft tint from the opposite corner, not a second
+ // light source — two bright hotspots read as headlights.
+ `radial-gradient(circle at ${actionPosition} in oklab, color-mix(in oklab, ${colors.messageAction} 45%, transparent) 0%, transparent 55%)`,
+ ].join(", "),
+ };
+}
+
+// The gradient halves of each ball can match the card surface, so every ball
+// carries a faint mode-appropriate inner ring to keep its silhouette legible.
+function themePreviewEdgeShadow(mode: ThemeAppearance): string {
+ return mode === "dark"
+ ? "inset 0 0 0 1px rgb(255 255 255 / 0.14), 0 1px 2px rgb(0 0 0 / 0.18)"
+ : "inset 0 0 0 1px rgb(0 0 0 / 0.10), 0 1px 2px rgb(0 0 0 / 0.08)";
+}
+
+export function ThemePreviewCircle({
+ colors,
+ mode,
+}: {
+ colors: ThemeCardPreviewColors;
+ mode: ThemeAppearance;
+}) {
+ return (
+ <span
+ aria-hidden
+ className="relative block size-14 shrink-0 overflow-hidden rounded-full border-2 border-background"
+ style={{ boxShadow: themePreviewEdgeShadow(mode) }}
+ >
+ <span
+ className="absolute inset-0 scale-110 rounded-full blur-[3px]"
+ style={getThemePreviewStyle(colors, mode)}
+ />
+ </span>
+ );
+}
+
+/**
+ * A theme card's light and dark balls. Clicking a ball assigns that theme to
+ * that half of the appearance mix; assigned balls carry a ring and a sun or
+ * moon badge.
+ */
+export function ThemePreviewCircles({
+ label,
+ activeModes,
+ onSelectMode,
+ previews,
+}: {
+ label: string;
+ activeModes: ReadonlyArray<ThemeMode>;
+ onSelectMode: (mode: ThemeMode) => void;
+ previews: ThemeCardDefinition["previews"];
+}) {
+ return (
+ <div className="flex min-h-16 items-center justify-center gap-2.5 px-3 pt-3">
+ {previews.map((preview) => {
+ const mode = preview.mode;
+ const isPicked = activeModes.includes(mode);
+ return (
+ <Tooltip key={mode}>
+ <TooltipTrigger
+ render={
+ <button
+ aria-label={`Use ${label} ${mode} mode`}
+ aria-pressed={isPicked}
+ className={cn(
+ "relative flex size-[68px] shrink-0 transform-gpu cursor-pointer items-center justify-center rounded-full p-1 outline-none transition-transform hover:scale-105 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card",
+ isPicked && "hover:scale-100",
+ )}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelectMode(mode);
+ }}
+ type="button"
+ >
+ <ThemePreviewCircle colors={preview.colors} mode={mode} />
+ {isPicked ? (
+ <>
+ <span
+ aria-hidden
+ className="pointer-events-none absolute inset-0 rounded-full"
+ style={{ boxShadow: "inset 0 0 0 2px var(--ring)" }}
+ />
+ <span
+ aria-hidden
+ className="pointer-events-none absolute bottom-0.5 right-0.5 flex size-5 items-center justify-center rounded-full border border-border/70 bg-background text-foreground shadow-sm"
+ >
+ {mode === "light" ? (
+ <SunIcon className="size-3" />
+ ) : (
+ <MoonIcon className="size-3" />
+ )}
+ </span>
+ </>
+ ) : null}
+ </button>
+ }
+ />
+ <TooltipPopup>
+ {mode === "light" ? "Use for light mode only" : "Use for dark mode only"}
+ </TooltipPopup>
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/ThemeSettings.tsx b/apps/web/src/components/settings/ThemeSettings.tsx
new file mode 100644
index 000000000..4eb790450
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeSettings.tsx
@@ -0,0 +1,658 @@
+import {
+ CopyIcon,
+ DownloadIcon,
+ PenLineIcon,
+ PlusIcon,
+ Trash2Icon,
+ UploadIcon,
+} from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { cn } from "../../lib/utils";
+import {
+ getThemeDefinition,
+ getThemeModes,
+ removeCustomTheme,
+ serializeThemeFile,
+ type ThemeAppearance,
+ type ThemeDefinition,
+ type ThemeHalves,
+ T3_CHAT_THEME,
+ EMBER_THEME,
+ GROVE_THEME,
+ IRIS_THEME,
+ OCEAN_THEME,
+} from "../../themePalette";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import { Button } from "../ui/button";
+import { stackedThreadToast, toastManager } from "../ui/toast";
+import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
+import { ThemeImportDialog } from "./ThemeImportDialog";
+import { useThemeEditorStore } from "./themeEditorStore";
+import {
+ STANDARD_THEME_CARDS,
+ getThemeCardDefinition,
+ previewColorsOf,
+ ThemePreviewCircles,
+ type ThemeCardDefinition,
+ type ThemeMode,
+} from "./ThemePreviewCircles";
+import { ThemeWireframe } from "./ThemeWireframe";
+
+const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [
+ T3_CHAT_THEME,
+ GROVE_THEME,
+ OCEAN_THEME,
+ EMBER_THEME,
+ IRIS_THEME,
+];
+
+function downloadThemeFile(filename: string, contents: string): void {
+ const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.click();
+ // Revoking synchronously can abort the download in some browsers; give the
+ // browser time to open the stream first.
+ setTimeout(() => URL.revokeObjectURL(url), 30_000);
+}
+
+function ThemeLibraryCard({
+ theme,
+ isActive,
+ onUse,
+ onUseMode,
+ activeModes,
+ onEdit,
+ onDuplicate,
+ onDownload,
+ onRemove,
+}: {
+ theme: ThemeCardDefinition;
+ isActive: boolean;
+ onUse: () => void;
+ onUseMode: (mode: ThemeMode) => void;
+ activeModes: ReadonlyArray<ThemeMode>;
+ onEdit?: () => void;
+ onDuplicate?: () => void;
+ onDownload?: () => void;
+ onRemove?: () => void;
+}) {
+ // A one-appearance theme can only take its own side of the mix, so the card
+ // tooltip promises exactly what clicking it does.
+ const cardModes = theme.previews.map((preview) => preview.mode);
+ return (
+ // The card surface stays a plain div (buttons cannot nest inside a button
+ // role); the title button and mode circles carry the accessible actions,
+ // while the card click is a pointer-only convenience.
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <div
+ className={cn(
+ "cursor-pointer overflow-hidden rounded-xl border border-border/70 bg-card/60 transition-colors hover:bg-accent/10",
+ isActive && "bg-accent/30",
+ )}
+ data-theme-library-card={theme.id}
+ onClick={onUse}
+ style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
+ >
+ <ThemePreviewCircles
+ label={theme.label}
+ activeModes={activeModes}
+ onSelectMode={onUseMode}
+ previews={theme.previews}
+ />
+ <div className="flex items-center gap-2 px-3 pb-3 pt-2">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <button
+ aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}
+ aria-pressed={isActive}
+ className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
+ type="button"
+ onClick={(event) => {
+ event.stopPropagation();
+ onUse();
+ }}
+ >
+ {theme.label}
+ </button>
+ </div>
+ </div>
+ {onEdit || onDuplicate || onDownload || onRemove ? (
+ <div className="flex shrink-0 items-center gap-1">
+ {onDuplicate ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={`Duplicate ${theme.label}`}
+ size="icon-xs"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ onDuplicate();
+ }}
+ >
+ <CopyIcon />
+ </Button>
+ }
+ />
+ <TooltipPopup>Duplicate theme</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ {onEdit ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={`Edit ${theme.label}`}
+ size="icon-xs"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ onEdit();
+ }}
+ >
+ <PenLineIcon />
+ </Button>
+ }
+ />
+ <TooltipPopup>Edit theme</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ {onDownload ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={`Export ${theme.label}`}
+ size="icon-xs"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ onDownload();
+ }}
+ >
+ <DownloadIcon />
+ </Button>
+ }
+ />
+ <TooltipPopup>Export theme file</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ {onRemove ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ aria-label={`Remove ${theme.label}`}
+ size="icon-xs"
+ variant="ghost"
+ className="text-muted-foreground hover:text-destructive"
+ onClick={(event) => {
+ event.stopPropagation();
+ onRemove();
+ }}
+ >
+ <Trash2Icon />
+ </Button>
+ }
+ />
+ <TooltipPopup>Remove theme</TooltipPopup>
+ </Tooltip>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ }
+ />
+ <TooltipPopup>
+ {cardModes.length > 1 ? "Use for both light and dark" : `Use for ${cardModes[0]} mode only`}
+ </TooltipPopup>
+ </Tooltip>
+ );
+}
+
+export function ThemeLibrary({
+ theme,
+ setTheme,
+ appearanceMode,
+ setAppearanceMode,
+ customThemes,
+ initialAppearance,
+ refreshTheme,
+ isImportOpen,
+ onImportOpenChange,
+ themeHalves,
+ setThemeHalf,
+}: {
+ theme: string;
+ setTheme: (theme: string) => boolean;
+ appearanceMode: ThemeMode;
+ setAppearanceMode: (mode: ThemeMode) => boolean;
+ customThemes: ReadonlyArray<ThemeDefinition>;
+ initialAppearance: ThemeAppearance;
+ refreshTheme: () => void;
+ isImportOpen: boolean;
+ onImportOpenChange: (open: boolean) => void;
+ themeHalves: ThemeHalves | null;
+ setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
+}) {
+ const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
+ const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);
+ // Keep the last removal target so the dialog title stays populated while the
+ // close animation plays after confirming.
+ const lastThemeToRemoveRef = useRef<ThemeDefinition | null>(null);
+ useEffect(() => {
+ if (themeToRemove) lastThemeToRemoveRef.current = themeToRemove;
+ }, [themeToRemove]);
+ const removeDialogTheme = themeToRemove ?? lastThemeToRemoveRef.current;
+
+ const notifyThemeSaveFailure = useCallback(() => {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Couldn’t save theme selection",
+ description: "Try again.",
+ }),
+ );
+ }, []);
+
+ const notifyThemeRemovalFailure = useCallback(() => {
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Couldn’t remove theme",
+ description: "Try again.",
+ }),
+ );
+ }, []);
+
+ const persistTheme = useCallback(
+ (nextTheme: string) => {
+ const didSave = setTheme(nextTheme);
+ if (!didSave) notifyThemeSaveFailure();
+ return didSave;
+ },
+ [notifyThemeSaveFailure, setTheme],
+ );
+
+ const handleRemoveTheme = useCallback((customTheme: ThemeDefinition) => {
+ setThemeToRemove(customTheme);
+ }, []);
+
+ const handleConfirmRemoveTheme = useCallback(() => {
+ if (!themeToRemove) return;
+ const removesBase = getThemeDefinition(theme)?.id === themeToRemove.id;
+ // Keep the theme installed if we cannot move the selection off it; the
+ // dialog stays open so the user can retry or cancel.
+ if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
+ return;
+ }
+ for (const appearance of ["light", "dark"] as const) {
+ const half = themeHalves?.[appearance];
+ if (half === undefined) continue;
+ // Writing a base preference clears the whole mix, so halves that name a
+ // surviving theme are written back; halves on the removed theme fall
+ // back to the base.
+ const next = half === themeToRemove.id ? null : removesBase ? half : undefined;
+ if (next !== undefined && !setThemeHalf(appearance, next)) {
+ notifyThemeRemovalFailure();
+ return;
+ }
+ }
+ try {
+ removeCustomTheme(themeToRemove.id);
+ } catch {
+ notifyThemeRemovalFailure();
+ return;
+ }
+ setThemeToRemove(null);
+ }, [
+ appearanceMode,
+ notifyThemeRemovalFailure,
+ persistTheme,
+ setThemeHalf,
+ theme,
+ themeHalves,
+ themeToRemove,
+ ]);
+
+ // ----- Automatic-mode mixing -------------------------------------------
+ // The pair model: one theme owns light, one owns dark, and the global
+ // appearance mode (light / dark / auto) decides which is showing.
+ const baseCardId = getThemeDefinition(theme)?.id ?? null;
+ const lightOwner = themeHalves?.light ?? baseCardId;
+ const darkOwner = themeHalves?.dark ?? baseCardId;
+
+ const assignHalf = useCallback(
+ (appearance: ThemeAppearance, cardId: string | null) => {
+ const otherAppearance = appearance === "light" ? "dark" : "light";
+ // Picking the default over a themed base cannot be stored as a half:
+ // the base would still own that appearance. Convert the base into an
+ // explicit half on the other side so this side falls back to default.
+ if (cardId === null && baseCardId !== null) {
+ const otherOwner = themeHalves?.[otherAppearance] ?? baseCardId;
+ if (!persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) return;
+ if (!setThemeHalf(otherAppearance, otherOwner)) {
+ // Best-effort rollback: restore the whole-theme selection rather
+ // than leaving the user with no theme at all.
+ setTheme(theme);
+ notifyThemeSaveFailure();
+ }
+ return;
+ }
+ if (!setThemeHalf(appearance, cardId)) {
+ notifyThemeSaveFailure();
+ }
+ },
+ [
+ appearanceMode,
+ baseCardId,
+ notifyThemeSaveFailure,
+ persistTheme,
+ setTheme,
+ setThemeHalf,
+ theme,
+ themeHalves,
+ ],
+ );
+
+ // "Create theme" starts from whatever is on screen for the appearance being
+ // edited, so tuning the theme you already use never means rebuilding it.
+ const activeThemeForAppearance =
+ getThemeDefinition((initialAppearance === "light" ? lightOwner : darkOwner) ?? "") ?? null;
+
+ const cardDefById = (id: string | null): ThemeCardDefinition => {
+ if (id === null) return STANDARD_THEME_CARDS[0]!;
+ const definition = getThemeDefinition(id);
+ return definition ? getThemeCardDefinition(definition) : STANDARD_THEME_CARDS[0]!;
+ };
+
+ const pickColors = (id: string | null, appearance: ThemeAppearance) => {
+ const card = cardDefById(id);
+ return previewColorsOf(card, appearance) ?? card.previews[0]!.colors;
+ };
+
+ const setMode = (mode: ThemeMode) => {
+ if (!setAppearanceMode(mode)) notifyThemeSaveFailure();
+ };
+
+ // ----- Wireframe tiles on top, two-ball cards below --------------------
+ const handlePairPick = (cardId: string | null) => (mode: ThemeMode) => {
+ if (mode === "system") return;
+ assignHalf(mode, cardId);
+ };
+
+ // Rings always show the effective owner of each appearance: an unpicked
+ // half belongs to the default card (a null owner), so a fresh install
+ // shows T3 Code selected instead of nothing.
+ const pickedModesFor = (cardId: string | null): ThemeMode[] => {
+ const rings: ThemeMode[] = [];
+ if (lightOwner === cardId) rings.push("light");
+ if (darkOwner === cardId) rings.push("dark");
+ return rings;
+ };
+
+ const wireframeColors = (appearance: ThemeAppearance) =>
+ pickColors(appearance === "light" ? lightOwner : darkOwner, appearance);
+
+ const renderWireframe = (mode: ThemeMode) => (
+ <ThemeWireframe
+ className="h-[8.75rem]"
+ panes={
+ mode === "system"
+ ? [
+ { clip: "left", colors: wireframeColors("light") },
+ { clip: "right", colors: wireframeColors("dark") },
+ ]
+ : [{ colors: wireframeColors(mode === "dark" ? "dark" : "light") }]
+ }
+ />
+ );
+
+ const renderModeTiles = () => (
+ <div
+ aria-label="Appearance mode"
+ className="mx-auto grid w-full max-w-[56rem] grid-cols-3 gap-3 px-3 sm:px-4"
+ role="group"
+ >
+ {(["system", "light", "dark"] as const).map((mode) => {
+ const isActive = appearanceMode === mode;
+ return (
+ <button
+ aria-label={mode === "system" ? "Follow the system appearance" : `Use ${mode} mode`}
+ aria-pressed={isActive}
+ className={cn(
+ "flex cursor-pointer flex-col items-stretch gap-1.5 rounded-xl border p-2 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring",
+ isActive
+ ? "border-transparent bg-accent/30"
+ : "border-border/70 bg-card/60 hover:bg-accent/10",
+ )}
+ key={mode}
+ style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
+ onClick={() => setMode(mode)}
+ type="button"
+ >
+ {renderWireframe(mode)}
+ <span
+ className={cn(
+ "flex items-center justify-center text-xs font-medium",
+ isActive ? "text-foreground" : "text-muted-foreground",
+ )}
+ >
+ {mode === "system" ? "System" : mode === "light" ? "Light" : "Dark"}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ );
+
+ const renderPairGrid = () => (
+ // One shared provider so every tooltip in the grid hands off instantly to
+ // the next hovered trigger instead of stacking on top of it. The card
+ // tooltip briefly showing while crossing between a card's two circles is
+ // accepted — scoping the group tighter makes the handoffs feel sluggish.
+ <TooltipProvider>
+ <div
+ className="mx-auto grid w-full max-w-[56rem] gap-2 px-3 sm:px-4"
+ style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 17rem), 1fr))" }}
+ >
+ {STANDARD_THEME_CARDS.map((standardTheme) => (
+ <ThemeLibraryCard
+ activeModes={pickedModesFor(null)}
+ isActive={false}
+ key={standardTheme.id}
+ onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)}
+ onUseMode={handlePairPick(null)}
+ theme={standardTheme}
+ />
+ ))}
+ {MAINTAINER_THEMES.map((maintainerTheme) => {
+ const card = getThemeCardDefinition(maintainerTheme);
+ return (
+ <ThemeLibraryCard
+ activeModes={pickedModesFor(maintainerTheme.id)}
+ isActive={false}
+ key={maintainerTheme.id}
+ onDuplicate={() =>
+ openThemeEditor({
+ editingThemeId: null,
+ seedThemeId: maintainerTheme.id,
+ seedName: `${maintainerTheme.label} copy`,
+ initialAppearance,
+ })
+ }
+ onUse={() => persistTheme(maintainerTheme.id)}
+ onUseMode={handlePairPick(maintainerTheme.id)}
+ theme={card}
+ />
+ );
+ })}
+ {customThemes.map((customTheme) => {
+ const card = getThemeCardDefinition(customTheme);
+ return (
+ <ThemeLibraryCard
+ activeModes={pickedModesFor(customTheme.id)}
+ isActive={false}
+ key={customTheme.id}
+ onDuplicate={() =>
+ openThemeEditor({
+ editingThemeId: null,
+ seedThemeId: customTheme.id,
+ seedName: `${customTheme.label} copy`,
+ initialAppearance,
+ })
+ }
+ onEdit={() =>
+ openThemeEditor({
+ editingThemeId: customTheme.id,
+ seedThemeId: null,
+ seedName: null,
+ initialAppearance,
+ })
+ }
+ onDownload={() =>
+ downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
+ }
+ onRemove={() => handleRemoveTheme(customTheme)}
+ onUse={() => {
+ const modes = getThemeModes(customTheme);
+ if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
+ else persistTheme(customTheme.id);
+ }}
+ onUseMode={handlePairPick(customTheme.id)}
+ theme={card}
+ />
+ );
+ })}
+ </div>
+ </TooltipProvider>
+ );
+
+ return (
+ <div className="space-y-3">
+ <p className="px-3 text-[13px] leading-[1.45] text-muted-foreground/80 sm:px-4">
+ Choose how T3 Code looks. Use a built-in theme or make your own.
+ </p>
+ <h3 className="px-3 text-sm font-medium tracking-[-0.005em] text-foreground sm:px-4">
+ Color scheme
+ </h3>
+ {renderModeTiles()}
+ <div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
+ <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <Button
+ className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
+ size="xs"
+ variant="ghost"
+ onClick={() =>
+ openThemeEditor({
+ editingThemeId: null,
+ seedThemeId: activeThemeForAppearance?.id ?? null,
+ seedName: null,
+ initialAppearance,
+ })
+ }
+ >
+ <PlusIcon />
+ Create theme
+ </Button>
+ <Button size="xs" variant="ghost" onClick={() => onImportOpenChange(true)}>
+ <UploadIcon />
+ Import theme
+ </Button>
+ </div>
+ </div>
+ {renderPairGrid()}
+ <ThemeImportDialog
+ onImportedMany={(importedThemes, { updated }) => {
+ // An updated theme that is showing (as the base or either half)
+ // needs its palette re-applied.
+ if (
+ updated &&
+ importedThemes.some(
+ (imported) =>
+ getThemeDefinition(theme)?.id === imported.id ||
+ themeHalves?.light === imported.id ||
+ themeHalves?.dark === imported.id,
+ )
+ ) {
+ refreshTheme();
+ }
+ const verb = updated ? "updated" : "added";
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title:
+ importedThemes.length === 1
+ ? `${importedThemes[0]!.label} ${verb}`
+ : `${importedThemes.length} themes ${verb}`,
+ description: importedThemes.map((imported) => imported.label).join(", "),
+ }),
+ );
+ }}
+ onImported={(importedTheme) => {
+ // Same rule as clicking the card: a one-appearance theme takes its
+ // side of the mix instead of becoming the base for both.
+ const modes = getThemeModes(importedTheme);
+ if (modes.length === 1) {
+ assignHalf(modes[0]!, importedTheme.id);
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title: `${importedTheme.label} added`,
+ description: `It’s now your ${modes[0]!} theme.`,
+ }),
+ );
+ return true;
+ }
+ if (!persistTheme(importedTheme.id)) return false;
+ toastManager.add(
+ stackedThreadToast({
+ type: "success",
+ title: `${importedTheme.label} added`,
+ description: "It’s now active.",
+ }),
+ );
+ return true;
+ }}
+ onOpenChange={onImportOpenChange}
+ open={isImportOpen}
+ />
+ <AlertDialog
+ open={themeToRemove !== null}
+ onOpenChange={(open) => {
+ if (!open) setThemeToRemove(null);
+ }}
+ >
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>
+ <AlertDialogDescription>
+ You can bring it back anytime by importing its JSON file.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
+ <Button variant="destructive" onClick={handleConfirmRemoveTheme}>
+ Remove theme
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/settings/ThemeWireframe.tsx b/apps/web/src/components/settings/ThemeWireframe.tsx
new file mode 100644
index 000000000..ce4f13f20
--- /dev/null
+++ b/apps/web/src/components/settings/ThemeWireframe.tsx
@@ -0,0 +1,136 @@
+import { cn } from "../../lib/utils";
+import type { ThemeCardPreviewColors } from "./ThemePreviewCircles";
+
+// A simple miniature of the app: sidebar, a short conversation, the
+// composer, and the orchestrator panel floating over the interface as an
+// island with horizontal agent rows.
+export function ThemeWireframePane({
+ colors,
+ clip,
+}: {
+ colors: ThemeCardPreviewColors;
+ clip?: "left" | "right" | undefined;
+}) {
+ const line = "rgb(127 127 127 / 0.25)";
+ return (
+ <span
+ className="absolute inset-0"
+ style={
+ clip === undefined
+ ? undefined
+ : {
+ clipPath:
+ clip === "left"
+ ? "polygon(0 0, calc(50% - 1px) 0, calc(50% - 1px) 100%, 0 100%)"
+ : "polygon(calc(50% + 1px) 0, 100% 0, 100% 100%, calc(50% + 1px) 100%)",
+ }
+ }
+ >
+ <span className="absolute inset-0" style={{ backgroundColor: colors.canvas }} />
+ <span
+ className="absolute inset-y-0 left-0 w-[22%]"
+ style={{ backgroundColor: colors.sidebar, boxShadow: `inset -1px 0 0 ${line}` }}
+ />
+
+ {/* Sidebar: search, then thread rows */}
+ <span
+ className="absolute left-[3%] top-[8%] h-[8%] w-[16%] rounded-md"
+ style={{ backgroundColor: colors.surface, boxShadow: `inset 0 0 0 1px ${line}` }}
+ />
+ <span
+ className="absolute left-[3%] top-[22%] h-[7%] w-[16%] rounded-md"
+ style={{ backgroundColor: colors.accentSurface }}
+ />
+ <span
+ className="absolute left-[3%] top-[32%] h-[7%] w-[16%] rounded-md"
+ style={{ backgroundColor: colors.messageSurface, opacity: 0.7 }}
+ />
+ <span
+ className="absolute left-[3%] top-[42%] h-[7%] w-[16%] rounded-md"
+ style={{ backgroundColor: colors.messageSurface, opacity: 0.5 }}
+ />
+
+ {/* Conversation */}
+ <span
+ className="absolute right-[28%] top-[11%] h-[9%] w-[24%] rounded-lg"
+ style={{ backgroundColor: colors.messageSurface }}
+ />
+ <span
+ className="absolute left-[27%] top-[28%] h-[5%] w-[34%] rounded-sm"
+ style={{ backgroundColor: line }}
+ />
+ <span
+ className="absolute left-[27%] top-[38%] h-[5%] w-[26%] rounded-sm"
+ style={{ backgroundColor: line }}
+ />
+
+ {/* Composer */}
+ <span
+ className="absolute bottom-[8%] left-[26%] right-[6%] flex h-[15%] items-center justify-between rounded-md px-[2.5%]"
+ style={{
+ backgroundColor: colors.surface,
+ boxShadow: `inset 0 0 0 1px ${line}`,
+ }}
+ >
+ <span
+ className="block h-[26%] w-[34%] rounded-full"
+ style={{ backgroundColor: line, opacity: 0.7 }}
+ />
+ <span
+ className="block aspect-square h-[58%] rounded-full"
+ style={{ backgroundColor: colors.messageAction }}
+ />
+ </span>
+
+ {/* Orchestrator island floating over the composer */}
+ <span
+ className="absolute right-[5%] top-[8%] h-[46%] w-[20%] rounded-lg"
+ style={{
+ backgroundColor: colors.surface,
+ boxShadow: `inset 0 0 0 1px ${line}, 0 2px 5px rgb(0 0 0 / 0.14)`,
+ }}
+ >
+ {[0, 1, 2].map((row) => (
+ <span
+ className="absolute left-[11%] right-[11%] flex items-center gap-[5%]"
+ key={row}
+ style={{ top: `${10 + row * 30}%`, height: "20%" }}
+ >
+ <span
+ className="block aspect-square h-[26%] rounded-full"
+ style={{
+ backgroundColor:
+ row === 0 ? "#34d399" : row === 1 ? colors.messageAction : "#fbbf24",
+ opacity: 0.55,
+ }}
+ />
+ <span className="block h-[30%] w-[52%] rounded-sm" style={{ backgroundColor: line }} />
+ </span>
+ ))}
+ </span>
+ </span>
+ );
+}
+
+export function ThemeWireframe({
+ className,
+ panes,
+}: {
+ /** Sizing (height) for the frame; the pane geometry is percentage based. */
+ className?: string;
+ panes: ReadonlyArray<{ colors: ThemeCardPreviewColors; clip?: "left" | "right" }>;
+}) {
+ return (
+ <span
+ aria-hidden
+ className={cn(
+ "relative block w-full overflow-hidden rounded-lg border border-border/60",
+ className,
+ )}
+ >
+ {panes.map((pane) => (
+ <ThemeWireframePane clip={pane.clip} colors={pane.colors} key={pane.clip ?? "pane"} />
+ ))}
+ </span>
+ );
+}
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index 3b3a8c220..2dcdd66f1 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -37,10 +37,20 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
* here once instead of separately in the panel and the index.
*/
export const SETTINGS_SEARCH_ITEMS = [
+ {
+ id: "color-scheme",
+ title: "Color scheme",
+ to: "/settings/appearance",
+ // The scheme tiles sit at the top of the Appearance section.
+ targetId: "appearance",
+ },
{
id: "theme",
- title: "Theme",
+ title: "Themes",
to: "/settings/appearance",
+ // Theme cards live directly under the scheme tiles; the section is the
+ // stable scroll destination for both.
+ targetId: "appearance",
},
{
// Prefixed because the slider control already owns the `glass-opacity` id.
diff --git a/apps/web/src/components/settings/themeEditorStore.test.ts b/apps/web/src/components/settings/themeEditorStore.test.ts
new file mode 100644
index 000000000..ec641b4ba
--- /dev/null
+++ b/apps/web/src/components/settings/themeEditorStore.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, it } from "vite-plus/test";
+
+import { OCEAN_THEME_ID, T3_CHAT_THEME_ID } from "../../themePalette";
+import { toggleThemeEditorForTheme, useThemeEditorStore } from "./themeEditorStore";
+
+afterEach(() => {
+ useThemeEditorStore.getState().closeThemeEditor();
+});
+
+describe("toggleThemeEditorForTheme", () => {
+ it("opens a new editor seeded from the theme active for the current appearance", () => {
+ toggleThemeEditorForTheme({
+ theme: T3_CHAT_THEME_ID,
+ themeHalves: { dark: OCEAN_THEME_ID },
+ initialAppearance: "dark",
+ });
+
+ expect(useThemeEditorStore.getState().session).toMatchObject({
+ editingThemeId: null,
+ seedThemeId: OCEAN_THEME_ID,
+ seedName: null,
+ initialAppearance: "dark",
+ });
+ });
+
+ it("closes an open editor", () => {
+ toggleThemeEditorForTheme({
+ theme: T3_CHAT_THEME_ID,
+ themeHalves: null,
+ initialAppearance: "light",
+ });
+ toggleThemeEditorForTheme({
+ theme: T3_CHAT_THEME_ID,
+ themeHalves: null,
+ initialAppearance: "light",
+ });
+
+ expect(useThemeEditorStore.getState().session).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/settings/themeEditorStore.ts b/apps/web/src/components/settings/themeEditorStore.ts
new file mode 100644
index 000000000..346785917
--- /dev/null
+++ b/apps/web/src/components/settings/themeEditorStore.ts
@@ -0,0 +1,68 @@
+import { create } from "zustand";
+
+import {
+ getThemeDefinition,
+ type ThemeAppearance,
+ type ThemeHalves,
+ type ThemePreference,
+} from "../../themePalette";
+
+/**
+ * The theme editor lives above the router so a draft survives navigation: the
+ * palette is painted on the live app, and judging it means browsing the app
+ * while the editor stays open. Themes are referenced by id because the stored
+ * definitions change underneath an open session (an edit, an import).
+ */
+export type ThemeEditorSessionInput = {
+ /** Set when editing an installed theme; null creates a new one. */
+ editingThemeId: string | null;
+ /** Theme a new theme starts from: the active one, or a duplicate target. */
+ seedThemeId: string | null;
+ /** Prefilled name, used by duplicate. */
+ seedName: string | null;
+ initialAppearance: ThemeAppearance;
+};
+
+export type ThemeEditorSession = ThemeEditorSessionInput & {
+ /**
+ * Distinguishes two sessions that name the same themes, so asking for a
+ * fresh draft while the panel is already open still reseeds it.
+ */
+ id: number;
+};
+
+type ThemeEditorStore = {
+ session: ThemeEditorSession | null;
+ openThemeEditor: (session: ThemeEditorSessionInput) => void;
+ closeThemeEditor: () => void;
+};
+
+let nextSessionId = 0;
+
+export const useThemeEditorStore = create<ThemeEditorStore>((set) => ({
+ session: null,
+ openThemeEditor: (session) => set({ session: { ...session, id: ++nextSessionId } }),
+ closeThemeEditor: () => set({ session: null }),
+}));
+
+export function toggleThemeEditorForTheme(input: {
+ theme: ThemePreference;
+ themeHalves: ThemeHalves | null;
+ initialAppearance: ThemeAppearance;
+}): void {
+ const store = useThemeEditorStore.getState();
+ if (store.session) {
+ store.closeThemeEditor();
+ return;
+ }
+
+ const baseThemeId = getThemeDefinition(input.theme)?.id ?? null;
+ const activeThemeId = input.themeHalves?.[input.initialAppearance] ?? baseThemeId;
+ const seedThemeId = activeThemeId ? (getThemeDefinition(activeThemeId)?.id ?? null) : null;
+ store.openThemeEditor({
+ editingThemeId: null,
+ seedThemeId,
+ seedName: null,
+ initialAppearance: input.initialAppearance,
+ });
+}
diff --git a/apps/web/src/components/settings/themeInspector.test.ts b/apps/web/src/components/settings/themeInspector.test.ts
new file mode 100644
index 000000000..b1aa574ef
--- /dev/null
+++ b/apps/web/src/components/settings/themeInspector.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "@effect/vitest";
+
+import {
+ changedThemePaintKinds,
+ themeRoleFromUtilityClass,
+ type ThemePaintSnapshot,
+} from "./themeInspector";
+
+const WHITE_PAINT: ThemePaintSnapshot = {
+ background: "rgb(255, 255, 255)\nnone",
+ border: "rgb(255, 255, 255)\nnone",
+ foreground: "rgb(255, 255, 255)\nnone",
+};
+
+describe("changedThemePaintKinds", () => {
+ it("does not match an identical hardcoded color", () => {
+ expect(changedThemePaintKinds(WHITE_PAINT, { ...WHITE_PAINT })).toEqual([]);
+ });
+
+ it("reports only paint that changed with the probed token", () => {
+ expect(
+ changedThemePaintKinds(WHITE_PAINT, {
+ ...WHITE_PAINT,
+ background: "rgb(1, 254, 167)\nnone",
+ foreground: "rgb(1, 254, 167)\nnone",
+ }),
+ ).toEqual(["background", "foreground"]);
+ });
+});
+
+describe("themeRoleFromUtilityClass", () => {
+ it("maps semantic utilities to their actual palette role", () => {
+ expect(themeRoleFromUtilityClass("text-foreground", "foreground")).toBe("text");
+ expect(themeRoleFromUtilityClass("bg-primary/90", "background")).toBe("messageAction");
+ expect(themeRoleFromUtilityClass("ring-ring", "border")).toBe("focus");
+ });
+
+ it("does not infer hardcoded or potentially inactive colors", () => {
+ expect(themeRoleFromUtilityClass("bg-white", "background")).toBeNull();
+ expect(themeRoleFromUtilityClass("hover:bg-accent", "background")).toBeNull();
+ });
+});
diff --git a/apps/web/src/components/settings/themeInspector.ts b/apps/web/src/components/settings/themeInspector.ts
new file mode 100644
index 000000000..7c0441006
--- /dev/null
+++ b/apps/web/src/components/settings/themeInspector.ts
@@ -0,0 +1,501 @@
+import { THEME_COLOR_ROLES, getThemeColorVariable, type ThemeColorRole } from "../../themePalette";
+
+export type ThemePaintKind = "background" | "border" | "foreground";
+
+export type ThemePaintSnapshot = Readonly<Record<ThemePaintKind, string>>;
+export type ThemeElementInspection = Readonly<{
+ element: Element;
+ role: ThemeColorRole;
+}>;
+
+const THEME_PAINT_KIND_ORDER: ReadonlyArray<ThemePaintKind> = [
+ "background",
+ "border",
+ "foreground",
+];
+
+export const THEME_INSPECTOR_MATCH_ATTRIBUTE = "data-theme-inspector-match";
+
+const THEME_TOKEN_PROBE_ATTRIBUTE = "data-theme-token-probe";
+const THEME_TOKEN_PROBE_COLOR = "#01fea7";
+const THEME_TOKEN_ALTERNATE_PROBE_COLOR = "#fe01a7";
+const THEME_SPOTLIGHT_ID = "theme-inspector-spotlight";
+const THEME_SPOTLIGHT_MASK_ID = "theme-inspector-spotlight-mask";
+const THEME_SPOTLIGHT_GLOW_ID = "theme-inspector-spotlight-glow";
+const THEME_HOVER_ID = "theme-inspector-hover";
+const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
+
+const THEME_UTILITY_ROLES: Readonly<Partial<Record<string, ThemeColorRole>>> = {
+ background: "canvas",
+ foreground: "text",
+ card: "surface",
+ "card-foreground": "text",
+ popover: "surfaceOverlay",
+ "popover-foreground": "text",
+ "surface-raised": "surfaceRaised",
+ primary: "messageAction",
+ "primary-foreground": "messageActionForeground",
+ secondary: "secondary",
+ "secondary-foreground": "secondaryForeground",
+ muted: "muted",
+ "muted-foreground": "textMuted",
+ placeholder: "placeholder",
+ "secondary-label": "secondaryLabel",
+ "icon-muted": "iconMuted",
+ accent: "accentSurface",
+ "accent-foreground": "accentSurfaceForeground",
+ destructive: "error",
+ "destructive-foreground": "errorForeground",
+ error: "error",
+ "error-foreground": "errorForeground",
+ "error-surface": "errorSurface",
+ warning: "warning",
+ "warning-foreground": "warningForeground",
+ "warning-surface": "warningSurface",
+ update: "update",
+ "update-foreground": "updateForeground",
+ "update-surface": "updateSurface",
+ message: "messageSurface",
+ "message-foreground": "messageForeground",
+ "message-action": "messageAction",
+ "message-action-foreground": "messageActionForeground",
+ "message-action-hover": "messageActionHover",
+ sidebar: "sidebar",
+ "sidebar-foreground": "sidebarForeground",
+ "sidebar-muted-foreground": "sidebarMutedForeground",
+ "sidebar-control-surface": "sidebarControlSurface",
+ "sidebar-row-hover": "sidebarRowHover",
+ "sidebar-row-active": "sidebarRowActive",
+ "sidebar-row-selected": "sidebarRowSelected",
+ "sidebar-border": "sidebarBorder",
+ border: "border",
+ input: "input",
+ ring: "focus",
+};
+
+const THEME_UTILITY_PREFIXES: Readonly<Record<ThemePaintKind, ReadonlyArray<string>>> = {
+ background: ["bg-"],
+ border: ["border-", "outline-", "ring-"],
+ foreground: ["text-", "caret-", "fill-", "stroke-"],
+};
+
+function clearThemeInspectorAttribute(attribute: string): void {
+ document
+ .querySelectorAll(`[${attribute}]`)
+ .forEach((element) => element.removeAttribute(attribute));
+}
+
+export function clearThemeInspectorHighlights(): void {
+ clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
+ document.getElementById(THEME_SPOTLIGHT_ID)?.remove();
+}
+
+export function clearThemeInspectorHover(): void {
+ document.getElementById(THEME_HOVER_ID)?.remove();
+}
+
+function svgElement<Name extends keyof SVGElementTagNameMap>(
+ name: Name,
+): SVGElementTagNameMap[Name] {
+ return document.createElementNS(SVG_NAMESPACE, name);
+}
+
+function spotlightRect(element: Element): {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ radius: number;
+} | null {
+ const bounds = element.getBoundingClientRect();
+ if (
+ bounds.width <= 0 ||
+ bounds.height <= 0 ||
+ bounds.right < 0 ||
+ bounds.bottom < 0 ||
+ bounds.left > window.innerWidth ||
+ bounds.top > window.innerHeight
+ ) {
+ return null;
+ }
+
+ const padding = 5;
+ // Keep the true bounds when an element is partially offscreen. Clamping its
+ // rectangle to the viewport would draw a fake glow edge along the crop.
+ const x = bounds.left - padding;
+ const y = bounds.top - padding;
+ const elementRadius =
+ Number.parseFloat(window.getComputedStyle(element).borderTopLeftRadius) || 0;
+ return {
+ x,
+ y,
+ width: bounds.width + padding * 2,
+ height: bounds.height + padding * 2,
+ radius: Math.min(18, Math.max(7, elementRadius + padding)),
+ };
+}
+
+export function showThemeInspectorHover(inspection: ThemeElementInspection, label: string): void {
+ const rectangle = spotlightRect(inspection.element);
+ if (!rectangle) {
+ clearThemeInspectorHover();
+ return;
+ }
+
+ let hover = document.getElementById(THEME_HOVER_ID);
+ if (!hover) {
+ hover = document.createElement("div");
+ hover.id = THEME_HOVER_ID;
+ hover.setAttribute("aria-hidden", "true");
+ const tokenLabel = document.createElement("span");
+ tokenLabel.dataset.themeInspectorHoverLabel = "";
+ hover.append(tokenLabel);
+ document.body.append(hover);
+ }
+
+ hover.style.left = `${rectangle.x}px`;
+ hover.style.top = `${rectangle.y}px`;
+ hover.style.width = `${rectangle.width}px`;
+ hover.style.height = `${rectangle.height}px`;
+ hover.style.borderRadius = `${rectangle.radius}px`;
+ hover.dataset.placement = rectangle.y < 32 ? "below" : "above";
+ const tokenLabel = hover.querySelector<HTMLElement>("[data-theme-inspector-hover-label]");
+ if (tokenLabel) tokenLabel.textContent = label;
+}
+
+function renderThemeInspectorSpotlight(elements: ReadonlyArray<Element>): void {
+ const rectangles = new Map<string, NonNullable<ReturnType<typeof spotlightRect>>>();
+ for (const element of elements) {
+ const rectangle = spotlightRect(element);
+ if (!rectangle) continue;
+ const key = [rectangle.x, rectangle.y, rectangle.width, rectangle.height]
+ .map((value) => Math.round(value))
+ .join(":");
+ rectangles.set(key, rectangle);
+ }
+
+ if (rectangles.size === 0) {
+ document.getElementById(THEME_SPOTLIGHT_ID)?.remove();
+ return;
+ }
+
+ let spotlight = document.getElementById(THEME_SPOTLIGHT_ID) as SVGSVGElement | null;
+ if (!spotlight) {
+ spotlight = svgElement("svg");
+ spotlight.id = THEME_SPOTLIGHT_ID;
+ spotlight.setAttribute("aria-hidden", "true");
+ spotlight.setAttribute("focusable", "false");
+ document.body.append(spotlight);
+ }
+ spotlight.setAttribute("viewBox", `0 0 ${window.innerWidth} ${window.innerHeight}`);
+
+ const definitions = svgElement("defs");
+ const mask = svgElement("mask");
+ mask.id = THEME_SPOTLIGHT_MASK_ID;
+ mask.setAttribute("maskUnits", "userSpaceOnUse");
+ const maskSurface = svgElement("rect");
+ maskSurface.setAttribute("width", String(window.innerWidth));
+ maskSurface.setAttribute("height", String(window.innerHeight));
+ maskSurface.setAttribute("fill", "white");
+ mask.append(maskSurface);
+
+ const glowFilter = svgElement("filter");
+ glowFilter.id = THEME_SPOTLIGHT_GLOW_ID;
+ glowFilter.setAttribute("x", "-50%");
+ glowFilter.setAttribute("y", "-50%");
+ glowFilter.setAttribute("width", "200%");
+ glowFilter.setAttribute("height", "200%");
+ const blur = svgElement("feGaussianBlur");
+ blur.setAttribute("stdDeviation", "5");
+ blur.setAttribute("result", "blur");
+ const merge = svgElement("feMerge");
+ const blurredGlow = svgElement("feMergeNode");
+ blurredGlow.setAttribute("in", "blur");
+ const crispGlow = svgElement("feMergeNode");
+ crispGlow.setAttribute("in", "SourceGraphic");
+ merge.append(blurredGlow, crispGlow);
+ glowFilter.append(blur, merge);
+ definitions.append(mask, glowFilter);
+
+ const glowGroup = svgElement("g");
+ for (const rectangle of rectangles.values()) {
+ const hole = svgElement("rect");
+ hole.setAttribute("x", String(rectangle.x));
+ hole.setAttribute("y", String(rectangle.y));
+ hole.setAttribute("width", String(rectangle.width));
+ hole.setAttribute("height", String(rectangle.height));
+ hole.setAttribute("rx", String(rectangle.radius));
+ hole.setAttribute("fill", "black");
+ mask.append(hole);
+
+ const glow = hole.cloneNode(false) as SVGRectElement;
+ glow.removeAttribute("fill");
+ glow.setAttribute("class", "theme-inspector-spotlight-glow");
+ glow.setAttribute("filter", `url(#${THEME_SPOTLIGHT_GLOW_ID})`);
+ glowGroup.append(glow);
+ }
+
+ const dimmer = svgElement("rect");
+ dimmer.setAttribute("class", "theme-inspector-spotlight-dimmer");
+ dimmer.setAttribute("width", String(window.innerWidth));
+ dimmer.setAttribute("height", String(window.innerHeight));
+ dimmer.setAttribute("mask", `url(#${THEME_SPOTLIGHT_MASK_ID})`);
+ spotlight.replaceChildren(definitions, dimmer, glowGroup);
+}
+
+export function refreshThemeInspectorSpotlight(): void {
+ renderThemeInspectorSpotlight([
+ ...document.querySelectorAll(`[${THEME_INSPECTOR_MATCH_ATTRIBUTE}]`),
+ ]);
+}
+
+function elementHasVisibleText(element: Element): boolean {
+ if (element.matches("input, textarea, select, option")) return true;
+ return Array.from(element.childNodes).some(
+ (node) => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim()),
+ );
+}
+
+function getThemePaintSnapshot(
+ element: Element,
+ { forHitTest = false }: { forHitTest?: boolean } = {},
+): ThemePaintSnapshot | null {
+ const style = window.getComputedStyle(element);
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) {
+ return null;
+ }
+
+ const borderPaints: Array<string> = [];
+ for (const [color, borderStyle, width] of [
+ [style.borderTopColor, style.borderTopStyle, style.borderTopWidth],
+ [style.borderRightColor, style.borderRightStyle, style.borderRightWidth],
+ [style.borderBottomColor, style.borderBottomStyle, style.borderBottomWidth],
+ [style.borderLeftColor, style.borderLeftStyle, style.borderLeftWidth],
+ ] as const) {
+ if (borderStyle !== "none" && Number.parseFloat(width) > 0) borderPaints.push(color);
+ }
+ if (style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0) {
+ borderPaints.push(style.outlineColor);
+ }
+ if (style.borderImageSource !== "none") borderPaints.push(style.borderImageSource);
+ if (style.boxShadow !== "none") borderPaints.push(style.boxShadow);
+
+ const foregroundPaints: Array<string> = [];
+ if (forHitTest || elementHasVisibleText(element)) foregroundPaints.push(style.color);
+ if (element instanceof SVGElement) foregroundPaints.push(style.fill, style.stroke);
+ if (element.matches("input, textarea")) foregroundPaints.push(style.caretColor);
+ if (style.textDecorationLine !== "none") foregroundPaints.push(style.textDecorationColor);
+ if (style.textShadow !== "none") foregroundPaints.push(style.textShadow);
+
+ return {
+ background: [style.backgroundColor, style.backgroundImage].join("\n"),
+ border: borderPaints.join("\n"),
+ foreground: foregroundPaints.join("\n"),
+ };
+}
+
+export function changedThemePaintKinds(
+ before: ThemePaintSnapshot,
+ after: ThemePaintSnapshot,
+): ReadonlyArray<ThemePaintKind> {
+ return THEME_PAINT_KIND_ORDER.filter((kind) => before[kind] !== after[kind]);
+}
+
+function withThemeTokenProbeSession<Result>(run: () => Result): Result {
+ const root = document.documentElement;
+ const wasAlreadyProbing = root.hasAttribute(THEME_TOKEN_PROBE_ATTRIBUTE);
+ if (!wasAlreadyProbing) root.setAttribute(THEME_TOKEN_PROBE_ATTRIBUTE, "");
+ try {
+ return run();
+ } finally {
+ // Flush every restored token while transitions are still suppressed. The
+ // browser never gets a paint opportunity between the probe and restore.
+ void window.getComputedStyle(root).color;
+ if (!wasAlreadyProbing) root.removeAttribute(THEME_TOKEN_PROBE_ATTRIBUTE);
+ }
+}
+
+function applyThemeTokenProbe(role: ThemeColorRole): () => void {
+ const root = document.documentElement;
+ const variable = getThemeColorVariable(role);
+ const originalValue = root.style.getPropertyValue(variable);
+ const originalPriority = root.style.getPropertyPriority(variable);
+ const resolvedValue = originalValue.trim().toLowerCase();
+ const probeColor =
+ resolvedValue === THEME_TOKEN_PROBE_COLOR
+ ? THEME_TOKEN_ALTERNATE_PROBE_COLOR
+ : THEME_TOKEN_PROBE_COLOR;
+ root.style.setProperty(variable, probeColor, "important");
+
+ return () => {
+ if (originalValue) {
+ root.style.setProperty(variable, originalValue, originalPriority);
+ } else {
+ root.style.removeProperty(variable);
+ }
+ };
+}
+
+function applyThemeTokenProbes(roles: ReadonlyArray<ThemeColorRole>): () => void {
+ const restores = roles.map(applyThemeTokenProbe);
+ return () => {
+ for (const restore of restores.toReversed()) restore();
+ };
+}
+
+function themeInspectorCandidates(): ReadonlyArray<Element> {
+ return [document.body, ...document.body.querySelectorAll("*")].filter(
+ (element) =>
+ !element.closest("[data-theme-editor-panel]") &&
+ !element.closest(`#${THEME_SPOTLIGHT_ID}, #${THEME_HOVER_ID}`),
+ );
+}
+
+export function themeRoleFromUtilityClass(
+ className: string,
+ kind: ThemePaintKind,
+): ThemeColorRole | null {
+ // Stateful variants such as hover: and disabled: may not be contributing to
+ // the current paint. The computed-style probe below handles those exactly.
+ if (className.includes(":")) return null;
+ for (const prefix of THEME_UTILITY_PREFIXES[kind]) {
+ if (!className.startsWith(prefix)) continue;
+ const colorName = className.slice(prefix.length).split("/", 1)[0] ?? "";
+ return THEME_UTILITY_ROLES[colorName] ?? null;
+ }
+ return null;
+}
+
+function themeRoleFromUtilities(element: Element): ThemeColorRole | null {
+ for (const kind of THEME_PAINT_KIND_ORDER) {
+ for (const className of element.classList) {
+ const role = themeRoleFromUtilityClass(className, kind);
+ if (role) return role;
+ }
+ }
+ return null;
+}
+
+function themeInspectionCandidates(initialElement: Element): ReadonlyArray<Element> {
+ const candidates: Array<Element> = [];
+ let element: Element | null = initialElement;
+ while (element && element !== document.documentElement) {
+ if (!element.closest("[data-theme-editor-panel]")) candidates.push(element);
+ element = element.parentElement;
+ }
+ return candidates;
+}
+
+export function inspectThemeRoleFromUtilitiesAtElement(
+ initialElement: Element,
+): ThemeElementInspection | null {
+ if (initialElement.closest("[data-theme-editor-panel]")) return null;
+ for (const candidate of themeInspectionCandidates(initialElement)) {
+ const role = themeRoleFromUtilities(candidate);
+ if (role) return { element: candidate, role };
+ }
+ return null;
+}
+
+/**
+ * Finds actual dependency on a theme token instead of comparing final colors.
+ * A token is synchronously replaced with a sentinel, computed paint is read,
+ * and the original value is restored before the browser can render a frame.
+ */
+export function highlightThemeRoleUsage(roles: ReadonlyArray<ThemeColorRole>): number {
+ const startedAt = performance.now();
+ clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
+ const candidates = themeInspectorCandidates();
+ const probeStartedAt = performance.now();
+ const matches = withThemeTokenProbeSession(() => {
+ const baseline = new Map<Element, ThemePaintSnapshot>();
+ for (const element of candidates) {
+ const snapshot = getThemePaintSnapshot(element);
+ if (snapshot) baseline.set(element, snapshot);
+ }
+
+ const restore = applyThemeTokenProbes(roles);
+ const changed = new Set<Element>();
+ try {
+ for (const [element, before] of baseline) {
+ const after = getThemePaintSnapshot(element);
+ if (after && changedThemePaintKinds(before, after).length > 0) changed.add(element);
+ }
+ } finally {
+ restore();
+ }
+ return changed;
+ });
+ const probeDuration = performance.now() - probeStartedAt;
+
+ const highlightedElements = new Set<Element>();
+ for (const element of matches) {
+ highlightedElements.add(
+ element instanceof SVGElement ? (element.closest("svg") ?? element) : element,
+ );
+ }
+ for (const element of highlightedElements) {
+ element.setAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE, "");
+ }
+ renderThemeInspectorSpotlight([...highlightedElements]);
+ if (import.meta.env.DEV) {
+ const spotlight = document.getElementById(THEME_SPOTLIGHT_ID);
+ if (spotlight) {
+ spotlight.dataset.themeInspectorCandidates = String(candidates.length);
+ spotlight.dataset.themeInspectorProbeMs = probeDuration.toFixed(2);
+ spotlight.dataset.themeInspectorTotalMs = (performance.now() - startedAt).toFixed(2);
+ }
+ }
+ return highlightedElements.size;
+}
+
+/** Resolves the nearest painted token at a touched element. */
+export function inspectThemeRoleAtElement(initialElement: Element): ThemeElementInspection | null {
+ if (initialElement.closest("[data-theme-editor-panel]")) return null;
+
+ const candidates = themeInspectionCandidates(initialElement);
+
+ // Most app paint comes from Tailwind's semantic color utilities. Those class
+ // names express the token dependency directly and avoid dozens of forced
+ // style recalculations on every pointer-down. Custom CSS still falls through
+ // to the exact computed-style probe.
+ const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(initialElement);
+ if (utilityInspection) return utilityInspection;
+
+ const rolesByElement = withThemeTokenProbeSession(() => {
+ const baseline = new Map<Element, ThemePaintSnapshot>();
+ const roles = new Map<Element, Partial<Record<ThemePaintKind, ThemeColorRole>>>();
+ for (const candidate of candidates) {
+ const snapshot = getThemePaintSnapshot(candidate, { forHitTest: true });
+ if (snapshot) baseline.set(candidate, snapshot);
+ }
+
+ for (const role of THEME_COLOR_ROLES) {
+ const restore = applyThemeTokenProbe(role);
+ try {
+ for (const [candidate, before] of baseline) {
+ const after = getThemePaintSnapshot(candidate, { forHitTest: true });
+ if (!after) continue;
+ const candidateRoles = roles.get(candidate) ?? {};
+ for (const kind of changedThemePaintKinds(before, after)) {
+ candidateRoles[kind] ??= role;
+ }
+ roles.set(candidate, candidateRoles);
+ }
+ } finally {
+ restore();
+ }
+ }
+ return roles;
+ });
+
+ for (const candidate of candidates) {
+ const roles = rolesByElement.get(candidate);
+ if (!roles) continue;
+ for (const kind of THEME_PAINT_KIND_ORDER) {
+ const role = roles[kind];
+ if (role) return { element: candidate, role };
+ }
+ }
+ return null;
+}
diff --git a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx
index b28b967ee..6e490f435 100644
--- a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx
+++ b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx
@@ -13,7 +13,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
const PROVIDER_UPDATE_PILL_STYLES = {
loading:
- "bg-primary/15 text-primary group-has-[button.provider-update-main:hover]/provider-update:bg-primary/22",
+ "bg-update-surface text-update group-has-[button.provider-update-main:hover]/provider-update:bg-update/22",
success:
"bg-success/12 text-success group-has-[button.provider-update-main:hover]/provider-update:bg-success/18",
warning:
diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
index 89120850f..f113e0fc9 100644
--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
@@ -159,11 +159,11 @@ export function SidebarUpdatePill() {
)}
{visible && (
<div
- className={`group/update relative flex h-7 w-full items-center rounded-lg bg-primary/15 text-xs font-medium text-primary ${
+ className={`group/update relative flex h-7 w-full items-center rounded-lg bg-update-surface text-xs font-medium text-update ${
disabled ? " cursor-not-allowed opacity-60" : ""
}`}
>
- <div className="pointer-events-none absolute inset-0 rounded-lg transition-colors group-has-[button.update-main:hover]/update:bg-primary/22" />
+ <div className="pointer-events-none absolute inset-0 rounded-lg transition-colors group-has-[button.update-main:hover]/update:bg-update/12" />
<Tooltip>
<TooltipTrigger
render={
@@ -224,7 +224,7 @@ export function SidebarUpdatePill() {
<button
type="button"
aria-label="Dismiss update"
- className="mr-1 inline-flex size-5 items-center justify-center rounded-md text-primary/60 transition-colors hover:text-primary"
+ className="mr-1 inline-flex size-5 items-center justify-center rounded-md text-update/60 transition-colors hover:text-update"
onClick={() => setDismissed(true)}
>
<XIcon className="size-3.5" />
diff --git a/apps/web/src/components/ui/alert.tsx b/apps/web/src/components/ui/alert.tsx
index 0af402097..d071fd2da 100644
--- a/apps/web/src/components/ui/alert.tsx
+++ b/apps/web/src/components/ui/alert.tsx
@@ -12,10 +12,11 @@ const alertVariants = cva("relative rounded-xl border px-3.5 py-3 text-card-fore
variant: {
default: "bg-transparent dark:bg-input/32 [&_svg]:text-muted-foreground",
error:
- "border-destructive/32 bg-destructive/4 text-destructive-foreground [&_[data-slot=alert-description]]:text-destructive-foreground/80 [&_svg]:text-destructive",
+ "border-error/32 bg-error-surface text-error-foreground [&_[data-slot=alert-description]]:text-error-foreground/80 [&_svg]:text-error",
info: "border-info/32 bg-info/4 [&_svg]:text-info",
success: "border-success/32 bg-success/4 [&_svg]:text-success",
- warning: "border-warning/32 bg-warning/4 [&_svg]:text-warning",
+ warning:
+ "border-warning/32 bg-warning-surface text-warning-foreground [&_[data-slot=alert-description]]:text-warning-foreground/80 [&_svg]:text-warning",
},
},
});
diff --git a/apps/web/src/components/ui/command.tsx b/apps/web/src/components/ui/command.tsx
index 0a713b769..06ce8d0b2 100644
--- a/apps/web/src/components/ui/command.tsx
+++ b/apps/web/src/components/ui/command.tsx
@@ -112,12 +112,12 @@ function CommandInput({
<AutocompleteInput
autoFocus
className={cn(
- "border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-muted-foreground/80 *:data-[slot=autocomplete-input]:ps-9! sm:*:data-[slot=autocomplete-input]:ps-[calc(var(--command-shell-inset)+1.5rem)]!",
+ "border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-placeholder *:data-[slot=autocomplete-input]:ps-9! sm:*:data-[slot=autocomplete-input]:ps-[calc(var(--command-shell-inset)+1.5rem)]!",
className,
)}
placeholder={placeholder}
size="lg"
- startAddon={<SearchIcon className="translate-x-0.5 text-muted-foreground" />}
+ startAddon={<SearchIcon className="translate-x-0.5 text-icon-muted" />}
{...props}
/>
</div>
@@ -203,7 +203,7 @@ function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
className={cn(
- "ms-auto font-medium font-sans text-muted-foreground/70 text-xs tracking-widest",
+ "ms-auto font-medium font-sans text-secondary-label text-xs tracking-widest",
className,
)}
data-slot="command-shortcut"
diff --git a/apps/web/src/components/ui/input.tsx b/apps/web/src/components/ui/input.tsx
index 7ab7eb6ce..6edc8d4a6 100644
--- a/apps/web/src/components/ui/input.tsx
+++ b/apps/web/src/components/ui/input.tsx
@@ -19,7 +19,7 @@ function Input({
...props
}: InputProps) {
const inputClassName = cn(
- "h-8.5 w-full min-w-0 rounded-[inherit] px-[calc(--spacing(3)-1px)] leading-8.5 outline-none placeholder:text-muted-foreground/72 sm:h-7.5 sm:leading-7.5 [transition:background-color_5000000s_ease-in-out_0s]",
+ "h-8.5 w-full min-w-0 rounded-[inherit] px-[calc(--spacing(3)-1px)] leading-8.5 outline-none placeholder:text-placeholder sm:h-7.5 sm:leading-7.5 [transition:background-color_5000000s_ease-in-out_0s]",
size === "sm" && "h-7.5 px-[calc(--spacing(2.5)-1px)] leading-7.5 sm:h-6.5 sm:leading-6.5",
size === "lg" && "h-9.5 leading-9.5 sm:h-8.5 sm:leading-8.5",
props.type === "search" &&
diff --git a/apps/web/src/components/ui/menu.tsx b/apps/web/src/components/ui/menu.tsx
index c2b130e51..efd7af880 100644
--- a/apps/web/src/components/ui/menu.tsx
+++ b/apps/web/src/components/ui/menu.tsx
@@ -203,7 +203,7 @@ function MenuShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
return (
<kbd
className={cn(
- "ms-auto font-medium font-sans text-muted-foreground/72 text-xs tracking-widest",
+ "ms-auto font-medium font-sans text-secondary-label text-xs tracking-widest",
className,
)}
data-slot="menu-shortcut"
diff --git a/apps/web/src/components/ui/select.tsx b/apps/web/src/components/ui/select.tsx
index 949beddd0..9a589c8d8 100644
--- a/apps/web/src/components/ui/select.tsx
+++ b/apps/web/src/components/ui/select.tsx
@@ -21,9 +21,9 @@ const selectTriggerVariants = cva(
variants: {
variant: {
default:
- "w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-muted-foreground [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
+ "w-full min-w-36 border-input bg-background not-dark:bg-clip-padding text-foreground shadow-xs/5 ring-ring/24 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 focus-visible:border-ring focus-visible:ring-[3px] aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/16 dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-focus-visible:not-aria-invalid:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='text-'])]:text-icon-muted [[data-disabled],:focus-visible,[aria-invalid],[data-pressed]]:shadow-none",
ghost:
- "border-transparent text-muted-foreground/70 focus-visible:ring-2 focus-visible:ring-ring data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent [:hover,[data-pressed]]:text-foreground/80",
+ "border-transparent text-secondary-label focus-visible:ring-2 focus-visible:ring-ring data-pressed:bg-accent [:hover,[data-pressed]]:bg-accent [:hover,[data-pressed]]:text-foreground",
},
size: {
default: "min-h-9 px-[calc(--spacing(3)-1px)] sm:min-h-8",
@@ -50,9 +50,7 @@ function SelectButton({ className, size, variant, render, children, ...props }:
const defaultProps = {
children: (
<>
- <span className="flex-1 truncate in-data-placeholder:text-muted-foreground/72">
- {children}
- </span>
+ <span className="flex-1 truncate in-data-placeholder:text-placeholder">{children}</span>
{variant === "ghost" ? (
<ChevronDownIcon className="-me-1 size-3 opacity-50" />
) : (
@@ -98,7 +96,7 @@ function SelectTrigger({
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
return (
<SelectPrimitive.Value
- className={cn("flex-1 truncate data-placeholder:text-muted-foreground", className)}
+ className={cn("flex-1 truncate data-placeholder:text-placeholder", className)}
data-slot="select-value"
{...props}
/>
diff --git a/apps/web/src/hooks/useCustomThemes.ts b/apps/web/src/hooks/useCustomThemes.ts
new file mode 100644
index 000000000..a8b351fa0
--- /dev/null
+++ b/apps/web/src/hooks/useCustomThemes.ts
@@ -0,0 +1,9 @@
+import { useSyncExternalStore } from "react";
+
+import { getCustomThemes, subscribeToCustomThemes } from "../themePalette";
+
+const EMPTY_CUSTOM_THEMES: readonly [] = [];
+
+export function useCustomThemes() {
+ return useSyncExternalStore(subscribeToCustomThemes, getCustomThemes, () => EMPTY_CUSTOM_THEMES);
+}
diff --git a/apps/web/src/hooks/useTheme.test.ts b/apps/web/src/hooks/useTheme.test.ts
index 6c814e301..ab87388ff 100644
--- a/apps/web/src/hooks/useTheme.test.ts
+++ b/apps/web/src/hooks/useTheme.test.ts
@@ -70,6 +70,18 @@ describe("theme failure handling", () => {
}
});
+ it("reads the persisted T3 Chat theme preference", async () => {
+ vi.stubGlobal("window", {
+ localStorage: createStorage({
+ getItem: () => "t3-chat",
+ }),
+ });
+
+ const { readThemePreference } = await import("./useTheme");
+
+ expect(readThemePreference()).toBe("t3-chat");
+ });
+
it("falls back during initial theme application and logs only safe attributes", async () => {
const cause = new Error("private browsing storage failure");
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
@@ -104,9 +116,10 @@ describe("theme failure handling", () => {
it("retries a failed storage read only after a relevant storage event", async () => {
const cause = new Error("persistent storage failure");
- const getItem = vi.fn(() => {
+ const themeGetItem = vi.fn((): string | null => {
throw cause;
});
+ const getItem = vi.fn((key: string) => (key === "t3code:theme" ? themeGetItem() : null));
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
let readSnapshot: (() => unknown) | undefined;
let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
@@ -141,14 +154,14 @@ describe("theme failure handling", () => {
readSnapshot?.();
readSnapshot?.();
- expect(getItem).toHaveBeenCalledTimes(1);
+ expect(themeGetItem).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledTimes(1);
const unsubscribe = subscribeToTheme?.(() => undefined);
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
readSnapshot?.();
- expect(getItem).toHaveBeenCalledTimes(2);
+ expect(themeGetItem).toHaveBeenCalledTimes(2);
expect(errorLog).toHaveBeenCalledTimes(2);
unsubscribe?.();
});
diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts
index bdaf37f09..68de5d474 100644
--- a/apps/web/src/hooks/useTheme.ts
+++ b/apps/web/src/hooks/useTheme.ts
@@ -2,12 +2,33 @@ import type { DesktopBridge } from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import * as Schema from "effect/Schema";
import { useCallback, useEffect, useSyncExternalStore } from "react";
-
-const ThemePreference = Schema.Literals(["light", "dark", "system"]);
-type Theme = typeof ThemePreference.Type;
+import {
+ applyThemePalette,
+ CUSTOM_THEMES_STORAGE_KEY,
+ invalidateCustomThemes,
+ canonicalThemePreference,
+ isKnownThemePreference,
+ getThemePreferenceMode,
+ parseThemeHalves,
+ resolveDesktopTheme,
+ resolveThemeAppearance,
+ resolveThemeHalf,
+ THEME_APPEARANCE_MODE_STORAGE_KEY,
+ THEME_FOLLOW_SYSTEM_STORAGE_KEY,
+ THEME_HALVES_STORAGE_KEY,
+ ThemePreference,
+ type ThemeAppearance,
+ type ThemeHalves,
+ type ThemePreferenceMode,
+} from "../themePalette";
+
+type Theme = ThemePreference;
type ThemeSnapshot = {
theme: Theme;
systemDark: boolean;
+ followSystem: boolean;
+ appearanceMode: ThemePreferenceMode;
+ themeHalves: ThemeHalves | null;
};
type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
@@ -17,7 +38,29 @@ const MEDIA_QUERY = "(prefers-color-scheme: dark)";
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
theme: "system",
systemDark: false,
+ followSystem: true,
+ appearanceMode: "system",
+ themeHalves: null,
};
+
+/** Live read of the stored appearance mix, for callers that must not rely on
+ * a render-time snapshot (for example rollback after an async dialog). */
+export function readThemeHalves(): ThemeHalves | null {
+ return readStoredThemeHalves();
+}
+
+function readStoredThemeHalves(): ThemeHalves | null {
+ if (typeof window === "undefined") return null;
+ try {
+ return parseThemeHalves(window.localStorage.getItem(THEME_HALVES_STORAGE_KEY));
+ } catch {
+ return null;
+ }
+}
+
+function themeHalvesSignature(halves: ThemeHalves | null): string {
+ return `${halves?.light ?? ""}|${halves?.dark ?? ""}`;
+}
const THEME_COLOR_META_NAME = "theme-color";
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
@@ -53,11 +96,13 @@ export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
-let lastDesktopTheme: Theme | null = null;
+let snapshotStale = true;
+let lastDesktopTheme: "light" | "dark" | "system" | null = null;
let lastAppliedTheme: ThemeSnapshot | null = null;
let themeStorageReadFailure: ThemeStorageError | null = null;
function emitChange() {
+ snapshotStale = true;
for (const listener of listeners) listener();
}
@@ -69,6 +114,53 @@ function getSystemDark() {
);
}
+function readStoredFollowSystem(theme: Theme): boolean {
+ if (typeof window === "undefined") return theme === "system";
+
+ try {
+ const raw = window.localStorage.getItem(THEME_FOLLOW_SYSTEM_STORAGE_KEY);
+ if (raw === "true") return true;
+ if (raw === "false") return false;
+ } catch {
+ // Fall back to the legacy theme value when the separate preference is unavailable.
+ }
+
+ return theme === "system";
+}
+
+function isThemePreferenceMode(value: string | null): value is ThemePreferenceMode {
+ return value === "light" || value === "dark" || value === "system";
+}
+
+export function readAppearanceModePreference(theme: Theme): ThemePreferenceMode {
+ if (typeof window !== "undefined") {
+ try {
+ const raw = window.localStorage.getItem(THEME_APPEARANCE_MODE_STORAGE_KEY);
+ if (isThemePreferenceMode(raw)) return raw;
+ } catch {
+ // Fall back to the legacy preference below when storage is unavailable.
+ }
+ }
+
+ if (readStoredFollowSystem(theme)) return "system";
+ return getThemePreferenceMode(theme) ?? "light";
+}
+
+function writeAppearanceModePreference(appearanceMode: ThemePreferenceMode): void {
+ if (typeof window === "undefined") return;
+ try {
+ // The legacy follow-system flag is read-only migration input now; the
+ // mode key is the single source of truth.
+ window.localStorage.setItem(THEME_APPEARANCE_MODE_STORAGE_KEY, appearanceMode);
+ } catch (cause) {
+ throw new ThemeStorageError({
+ operation: "write",
+ storageKey: THEME_APPEARANCE_MODE_STORAGE_KEY,
+ cause,
+ });
+ }
+}
+
export function readThemePreference(): Theme {
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
let raw: string | null;
@@ -81,7 +173,9 @@ export function readThemePreference(): Theme {
cause,
});
}
- if (raw === "light" || raw === "dark" || raw === "system") return raw;
+ if (raw !== null && isKnownThemePreference(raw)) {
+ return canonicalThemePreference(raw);
+ }
return DEFAULT_THEME_SNAPSHOT.theme;
}
@@ -161,34 +255,66 @@ function resolveBrowserChromeSurface(): HTMLElement {
export function syncBrowserChromeTheme() {
if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
+ const rootStyles = getComputedStyle(document.documentElement);
+ const themeChromeColor = document.documentElement.dataset.themeId
+ ? normalizeThemeColor(rootStyles.getPropertyValue("--app-chrome-background"))
+ : null;
const surfaceColor = normalizeThemeColor(
getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
);
const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
- const backgroundColor = surfaceColor ?? fallbackColor;
+ const backgroundColor = themeChromeColor ?? surfaceColor ?? fallbackColor;
if (!backgroundColor) return;
document.documentElement.style.backgroundColor = backgroundColor;
document.body.style.backgroundColor = backgroundColor;
- ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
+ // Update every theme-color meta so any element another layer added (for
+ // example a media-scoped one) carries the resolved color too.
+ const themeColorMetas = document.querySelectorAll<HTMLMetaElement>(
+ `meta[name="${THEME_COLOR_META_NAME}"]`,
+ );
+ if (themeColorMetas.length === 0) {
+ ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
+ return;
+ }
+ for (const element of themeColorMetas) {
+ element.setAttribute("content", backgroundColor);
+ }
}
function applyTheme(theme: Theme, suppressTransitions = false) {
if (typeof document === "undefined" || typeof window === "undefined") return;
- const systemDark = theme === "system" ? getSystemDark() : false;
- if (lastAppliedTheme?.theme === theme && lastAppliedTheme.systemDark === systemDark) {
- syncDesktopTheme(theme);
+ const appearanceMode = readAppearanceModePreference(theme);
+ const followSystem = appearanceMode === "system";
+ const systemDark = followSystem ? getSystemDark() : false;
+ const themeHalves = readStoredThemeHalves();
+ if (
+ lastAppliedTheme?.theme === theme &&
+ lastAppliedTheme.systemDark === systemDark &&
+ lastAppliedTheme.followSystem === followSystem &&
+ lastAppliedTheme.appearanceMode === appearanceMode &&
+ themeHalvesSignature(lastAppliedTheme.themeHalves) === themeHalvesSignature(themeHalves)
+ ) {
+ syncDesktopTheme(theme, followSystem, appearanceMode);
return;
}
if (suppressTransitions) {
document.documentElement.classList.add("no-transitions");
}
- const isDark = theme === "dark" || (theme === "system" && systemDark);
+ const resolvedAppearance = resolveThemeAppearance(
+ theme,
+ systemDark,
+ followSystem,
+ appearanceMode,
+ themeHalves,
+ );
+ applyThemePalette(resolveThemeHalf(theme, themeHalves, resolvedAppearance), resolvedAppearance);
+ const isDark = resolvedAppearance === "dark";
document.documentElement.classList.toggle("dark", isDark);
- lastAppliedTheme = { theme, systemDark };
+ lastAppliedTheme = { theme, systemDark, followSystem, appearanceMode, themeHalves };
syncBrowserChromeTheme();
- syncDesktopTheme(theme);
+ syncDesktopTheme(theme, followSystem, appearanceMode);
if (suppressTransitions) {
// Force a reflow so the no-transitions class takes effect before removal
// oxlint-disable-next-line no-unused-expressions
@@ -202,34 +328,45 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
export async function syncDesktopThemePreference(
bridge: DesktopThemeBridge,
theme: Theme,
+ followSystem?: boolean,
+ appearanceMode?: ThemePreferenceMode,
+ halves: ThemeHalves | null = readStoredThemeHalves(),
): Promise<void> {
try {
- await bridge.setTheme(theme);
+ await bridge.setTheme(resolveDesktopTheme(theme, followSystem, appearanceMode, halves));
} catch (cause) {
throw new DesktopThemeSyncError({ theme, cause });
}
}
-export function syncDesktopTheme(theme: Theme) {
+export function syncDesktopTheme(
+ theme: Theme,
+ followSystem?: boolean,
+ appearanceMode?: ThemePreferenceMode,
+) {
if (typeof window === "undefined") return;
const bridge = window.desktopBridge;
- if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
+ const halves = readStoredThemeHalves();
+ const desktopTheme = resolveDesktopTheme(theme, followSystem, appearanceMode, halves);
+ if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === desktopTheme) {
return;
}
- lastDesktopTheme = theme;
- void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
- const error = isDesktopThemeSyncError(cause)
- ? cause
- : new DesktopThemeSyncError({ theme, cause });
- console.error(error.message, {
- theme: error.theme,
- ...safeErrorLogAttributes(error),
- });
- if (lastDesktopTheme === theme) {
- lastDesktopTheme = null;
- }
- });
+ lastDesktopTheme = desktopTheme;
+ void syncDesktopThemePreference(bridge, theme, followSystem, appearanceMode, halves).catch(
+ (cause: unknown) => {
+ const error = isDesktopThemeSyncError(cause)
+ ? cause
+ : new DesktopThemeSyncError({ theme, cause });
+ console.error(error.message, {
+ theme: error.theme,
+ ...safeErrorLogAttributes(error),
+ });
+ if (lastDesktopTheme === desktopTheme) {
+ lastDesktopTheme = null;
+ }
+ },
+ );
}
// Apply immediately on module load to prevent flash
@@ -239,14 +376,28 @@ if (typeof document !== "undefined" && typeof window !== "undefined") {
function getSnapshot(): ThemeSnapshot {
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
+ // Reading the preference hits localStorage, so only recompute after a
+ // change was signalled; useTheme consumers call this on every render.
+ if (!snapshotStale && lastSnapshot) return lastSnapshot;
+ snapshotStale = false;
const theme = getStored();
- const systemDark = theme === "system" ? getSystemDark() : false;
+ const appearanceMode = readAppearanceModePreference(theme);
+ const followSystem = appearanceMode === "system";
+ const systemDark = followSystem ? getSystemDark() : false;
+ const themeHalves = readStoredThemeHalves();
- if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
+ if (
+ lastSnapshot &&
+ lastSnapshot.theme === theme &&
+ lastSnapshot.systemDark === systemDark &&
+ lastSnapshot.followSystem === followSystem &&
+ lastSnapshot.appearanceMode === appearanceMode &&
+ themeHalvesSignature(lastSnapshot.themeHalves) === themeHalvesSignature(themeHalves)
+ ) {
return lastSnapshot;
}
- lastSnapshot = { theme, systemDark };
+ lastSnapshot = { theme, systemDark, followSystem, appearanceMode, themeHalves };
return lastSnapshot;
}
@@ -254,32 +405,56 @@ function getServerSnapshot() {
return DEFAULT_THEME_SNAPSHOT;
}
+function handleSystemAppearanceChange() {
+ const storedTheme = getStored();
+ if (readAppearanceModePreference(storedTheme) === "system") applyTheme(storedTheme, true);
+ emitChange();
+}
+
+function handleStorageChange(e: StorageEvent) {
+ if (e.key === STORAGE_KEY) {
+ themeStorageReadFailure = null;
+ applyTheme(getStored(), true);
+ emitChange();
+ } else if (e.key === THEME_FOLLOW_SYSTEM_STORAGE_KEY) {
+ applyTheme(getStored(), true);
+ emitChange();
+ } else if (e.key === THEME_APPEARANCE_MODE_STORAGE_KEY || e.key === THEME_HALVES_STORAGE_KEY) {
+ applyTheme(getStored(), true);
+ emitChange();
+ } else if (e.key === CUSTOM_THEMES_STORAGE_KEY || e.key === null) {
+ if (e.key === null) themeStorageReadFailure = null;
+ invalidateCustomThemes();
+ lastAppliedTheme = null;
+ applyTheme(getStored(), true);
+ emitChange();
+ }
+}
+
+let removeWindowListeners: (() => void) | null = null;
+
function subscribe(listener: () => void): () => void {
if (typeof window === "undefined") return () => {};
listeners.push(listener);
- // Listen for system preference changes
- const mq = typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY) : null;
- const handleChange = () => {
- if (getStored() === "system") applyTheme("system", true);
- emitChange();
- };
- mq?.addEventListener("change", handleChange);
-
- // Listen for storage changes from other tabs
- const handleStorage = (e: StorageEvent) => {
- if (e.key === STORAGE_KEY) {
- themeStorageReadFailure = null;
- applyTheme(getStored(), true);
- emitChange();
- }
- };
- window.addEventListener("storage", handleStorage);
+ // The system-preference and cross-tab listeners are shared by all
+ // subscribers; each event applies the theme once and notifies everyone.
+ if (!removeWindowListeners) {
+ const mq = typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY) : null;
+ mq?.addEventListener("change", handleSystemAppearanceChange);
+ window.addEventListener("storage", handleStorageChange);
+ removeWindowListeners = () => {
+ mq?.removeEventListener("change", handleSystemAppearanceChange);
+ window.removeEventListener("storage", handleStorageChange);
+ };
+ }
return () => {
listeners = listeners.filter((l) => l !== listener);
- mq?.removeEventListener("change", handleChange);
- window.removeEventListener("storage", handleStorage);
+ if (listeners.length === 0) {
+ removeWindowListeners?.();
+ removeWindowListeners = null;
+ }
};
}
@@ -287,13 +462,34 @@ export function useTheme() {
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
const theme = snapshot.theme;
- const resolvedTheme: "light" | "dark" =
- theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
+ const resolvedTheme: "light" | "dark" = resolveThemeAppearance(
+ theme,
+ snapshot.systemDark,
+ snapshot.followSystem,
+ snapshot.appearanceMode,
+ snapshot.themeHalves,
+ );
- const setTheme = useCallback((next: Theme) => {
- if (typeof window === "undefined") return;
+ const setTheme = useCallback((next: Theme): boolean => {
+ if (typeof window === "undefined") return false;
try {
- writeThemePreference(next);
+ // Choosing a whole theme replaces any automatic-mode mix. The mix is
+ // captured first so a failed preference write can put it back instead
+ // of erasing it or leaving it attached to the new theme.
+ const previousHalvesRaw = window.localStorage.getItem(THEME_HALVES_STORAGE_KEY);
+ window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY);
+ try {
+ writeThemePreference(next);
+ } catch (cause) {
+ if (previousHalvesRaw !== null) {
+ try {
+ window.localStorage.setItem(THEME_HALVES_STORAGE_KEY, previousHalvesRaw);
+ } catch {
+ // Storage is failing wholesale; the outer handler reports it.
+ }
+ }
+ throw cause;
+ }
} catch (cause) {
const error = isThemeStorageError(cause)
? cause
@@ -309,16 +505,129 @@ export function useTheme() {
theme: next,
...safeErrorLogAttributes(error),
});
- return;
+ return false;
}
applyTheme(next, true);
emitChange();
+ return true;
+ }, []);
+
+ const setAppearanceMode = useCallback((nextAppearanceMode: ThemePreferenceMode): boolean => {
+ if (typeof window === "undefined") return false;
+ try {
+ writeAppearanceModePreference(nextAppearanceMode);
+ } catch (cause) {
+ const error = isThemeStorageError(cause)
+ ? cause
+ : new ThemeStorageError({
+ operation: "write",
+ storageKey: THEME_APPEARANCE_MODE_STORAGE_KEY,
+ cause,
+ });
+ console.error(error.message, {
+ operation: error.operation,
+ storageKey: error.storageKey,
+ ...safeErrorLogAttributes(error),
+ });
+ return false;
+ }
+ themeStorageReadFailure = null;
+ applyTheme(getStored(), true);
+ emitChange();
+ return true;
+ }, []);
+
+ const setFollowSystem = useCallback(
+ (nextFollowSystem: boolean): boolean => {
+ const currentMode = readAppearanceModePreference(theme);
+ const nextMode = nextFollowSystem
+ ? "system"
+ : currentMode === "system"
+ ? (getThemePreferenceMode(theme) ?? "light")
+ : currentMode;
+ return setAppearanceMode(nextMode);
+ },
+ [setAppearanceMode, theme],
+ );
+
+ const setThemeHalf = useCallback(
+ (appearance: ThemeAppearance, themeId: string | null): boolean => {
+ if (typeof window === "undefined") return false;
+ try {
+ const current = readStoredThemeHalves() ?? {};
+ const next: { light?: string; dark?: string } = { ...current };
+ if (themeId === null) delete next[appearance];
+ else next[appearance] = themeId;
+ if (next.light === undefined && next.dark === undefined) {
+ window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY);
+ } else {
+ window.localStorage.setItem(THEME_HALVES_STORAGE_KEY, JSON.stringify(next));
+ }
+ } catch (cause) {
+ const error = new ThemeStorageError({
+ operation: "write",
+ storageKey: THEME_HALVES_STORAGE_KEY,
+ cause,
+ });
+ console.error(error.message, {
+ operation: error.operation,
+ storageKey: error.storageKey,
+ ...safeErrorLogAttributes(error),
+ });
+ return false;
+ }
+ applyTheme(getStored(), true);
+ emitChange();
+ return true;
+ },
+ [],
+ );
+
+ const clearThemeHalves = useCallback((): boolean => {
+ if (typeof window === "undefined") return false;
+ try {
+ window.localStorage.removeItem(THEME_HALVES_STORAGE_KEY);
+ } catch (cause) {
+ const error = new ThemeStorageError({
+ operation: "write",
+ storageKey: THEME_HALVES_STORAGE_KEY,
+ cause,
+ });
+ console.error(error.message, {
+ operation: error.operation,
+ storageKey: error.storageKey,
+ ...safeErrorLogAttributes(error),
+ });
+ return false;
+ }
+ applyTheme(getStored(), true);
+ emitChange();
+ return true;
+ }, []);
+
+ const refreshTheme = useCallback(() => {
+ if (typeof window === "undefined") return;
+ lastAppliedTheme = null;
+ applyTheme(getStored(), true);
+ emitChange();
}, []);
// Keep DOM in sync on mount/change
useEffect(() => {
applyTheme(theme);
- }, [theme]);
-
- return { theme, setTheme, resolvedTheme } as const;
+ }, [snapshot.appearanceMode, theme]);
+
+ return {
+ theme,
+ setTheme,
+ setAppearanceMode,
+ setFollowSystem,
+ setThemeHalf,
+ clearThemeHalves,
+ refreshTheme,
+ followSystem: snapshot.followSystem,
+ appearanceMode: snapshot.appearanceMode,
+ resolvedTheme,
+ themeHalves: snapshot.themeHalves,
+ } as const;
}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 3108ef217..5b0ee6ec8 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -148,6 +148,13 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--animate-status-ping: status-ping 2s infinite;
--color-warning-foreground: var(--warning-foreground);
--color-warning: var(--warning);
+ --color-warning-surface: var(--warning-surface);
+ --color-error-foreground: var(--error-foreground);
+ --color-error: var(--error);
+ --color-error-surface: var(--error-surface);
+ --color-update-foreground: var(--update-foreground);
+ --color-update: var(--update);
+ --color-update-surface: var(--update-surface);
--color-success-foreground: var(--success-foreground);
--color-success: var(--success);
--color-info-foreground: var(--info-foreground);
@@ -161,6 +168,9 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
+ --color-placeholder: var(--placeholder);
+ --color-secondary-label: var(--secondary-label);
+ --color-icon-muted: var(--icon-muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
@@ -172,6 +182,11 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--color-foreground: var(--foreground);
--color-background: var(--background);
--color-surface-raised: var(--surface-raised);
+ --color-message: var(--message-surface);
+ --color-message-foreground: var(--message-foreground);
+ --color-message-action: var(--message-action);
+ --color-message-action-foreground: var(--message-action-foreground);
+ --color-message-action-hover: var(--message-action-hover);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-muted-foreground: var(--sidebar-muted-foreground);
@@ -833,7 +848,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
@utility surface-grain {
background-image: var(--surface-grain);
background-repeat: repeat;
- background-size: 256px 256px;
+ background-size: var(--surface-grain-size);
}
/* Suppress all transitions during theme changes */
@@ -850,6 +865,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--radius: 0.625rem;
--background: var(--color-zinc-25);
--app-chrome-background: var(--background);
+ --toolbar-background: var(--app-chrome-background);
+ --toolbar-foreground: var(--foreground);
+ --toolbar-border: var(--border);
+ --toolbar-control: var(--popover);
+ --toolbar-control-foreground: var(--foreground);
+ --toolbar-control-hover: var(--accent);
--surface-raised: color-mix(in srgb, var(--card) 20%, transparent);
--foreground: var(--color-zinc-800);
--card: var(--color-white);
@@ -862,19 +883,34 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--secondary-foreground: var(--color-zinc-800);
--muted: var(--color-zinc-50);
--muted-foreground: var(--color-zinc-500);
+ --placeholder: var(--muted-foreground);
+ --secondary-label: var(--muted-foreground);
+ --icon-muted: var(--muted-foreground);
+ --message-surface: var(--accent);
+ --message-foreground: var(--foreground);
+ --message-action: var(--primary);
+ --message-action-foreground: var(--primary-foreground);
+ --message-action-hover: color-mix(in srgb, var(--primary) 90%, var(--background));
--accent: var(--color-zinc-100);
--accent-foreground: var(--color-zinc-900);
- --destructive: var(--color-red-500);
+ --error: var(--color-red-500);
+ --error-foreground: var(--color-red-700);
+ --error-surface: color-mix(in srgb, var(--error) 8%, transparent);
+ --destructive: var(--error);
--border: var(--color-zinc-200);
--input: var(--color-zinc-300);
--ring: oklch(0.488 0.217 264);
- --destructive-foreground: var(--color-red-700);
+ --destructive-foreground: var(--error-foreground);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-700);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-700);
+ --warning-surface: color-mix(in srgb, var(--warning) 8%, transparent);
+ --update: var(--primary);
+ --update-foreground: var(--primary);
+ --update-surface: color-mix(in srgb, var(--update) 12%, transparent);
/* Keep every sidebar primitive on the same light surface hierarchy, including
portaled mobile sheets and settings navigation outside the app sidebar. */
--sidebar: var(--color-zinc-50);
@@ -886,6 +922,14 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--sidebar-row-selected: var(--color-white);
--sidebar-border: var(--border);
--sidebar-stage-fade: var(--sidebar);
+ --code-background: color-mix(in srgb, var(--card) 90%, var(--background));
+ --code-foreground: var(--foreground);
+ --terminal-background: var(--background);
+ --terminal-foreground: var(--foreground);
+ --terminal-cursor: rgb(38 56 78);
+ --terminal-selection-background: rgb(37 63 99 / 20%);
+ --terminal-scrollbar: rgb(0 0 0 / 15%);
+ --terminal-scrollbar-hover: rgb(0 0 0 / 25%);
@variant dark {
color-scheme: dark;
@@ -905,19 +949,34 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
+ --placeholder: var(--muted-foreground);
+ --secondary-label: var(--muted-foreground);
+ --icon-muted: var(--muted-foreground);
+ --message-surface: var(--accent);
+ --message-foreground: var(--foreground);
+ --message-action: var(--primary);
+ --message-action-foreground: var(--primary-foreground);
+ --message-action-hover: color-mix(in srgb, var(--primary) 90%, var(--background));
--accent: --alpha(var(--color-white) / 4%);
--accent-foreground: var(--color-neutral-100);
- --destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
+ --error: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
+ --error-foreground: var(--color-red-400);
+ --error-surface: color-mix(in srgb, var(--error) 16%, transparent);
+ --destructive: var(--error);
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--ring: oklch(0.588 0.217 264);
- --destructive-foreground: var(--color-red-400);
+ --destructive-foreground: var(--error-foreground);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-400);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-400);
+ --warning-surface: color-mix(in srgb, var(--warning) 16%, transparent);
+ --update: var(--primary);
+ --update-foreground: var(--primary);
+ --update-surface: color-mix(in srgb, var(--update) 18%, transparent);
--sidebar: var(--card);
--sidebar-foreground: var(--foreground);
--sidebar-muted-foreground: var(--muted-foreground);
@@ -927,6 +986,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--sidebar-row-selected: var(--muted);
--sidebar-border: var(--border);
--sidebar-stage-fade: var(--card);
+ --terminal-background: var(--background);
+ --terminal-foreground: var(--foreground);
+ --terminal-cursor: rgb(180 203 255);
+ --terminal-selection-background: rgb(180 203 255 / 25%);
+ --terminal-scrollbar: rgb(255 255 255 / 10%);
+ --terminal-scrollbar-hover: rgb(255 255 255 / 18%);
}
}
@@ -984,6 +1049,335 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--sidebar-stage-fade: var(--card);
}
+/* Theme files are expressed in app color roles and mapped to the existing
+ semantic surface tokens here. Keep this block after the sidebar-version
+ compatibility overrides so both navigation implementations receive the
+ same palette. Success, info, provider, and channel identity colors remain
+ independent; error, warning, and update roles are themeable below. */
+html[data-theme-id],
+html.dark[data-theme-id] {
+ --background: var(--app-theme-canvas);
+ --app-chrome-background: var(--app-theme-chrome);
+ --toolbar-background: var(--app-theme-toolbar);
+ --toolbar-foreground: var(--app-theme-toolbar-foreground);
+ --toolbar-border: var(--app-theme-toolbar-border);
+ --toolbar-control: var(--app-theme-toolbar-control);
+ --toolbar-control-foreground: var(--app-theme-toolbar-control-foreground);
+ --toolbar-control-hover: var(--app-theme-toolbar-control-hover);
+ --surface-raised: var(--app-theme-surface-raised);
+ --foreground: var(--app-theme-text);
+ --card: var(--app-theme-surface);
+ --card-foreground: var(--app-theme-text);
+ --popover: var(--app-theme-surface-overlay);
+ --popover-foreground: var(--app-theme-text);
+ /* Solid controls (CTAs, switches, sliders, the send button) all share the
+ theme's action color so every "act now" affordance reads consistently;
+ the accent keeps driving surfaces, selection, and focus. Palettes without
+ a distinct action color make these identical. */
+ --primary: var(--app-theme-message-action);
+ --primary-foreground: var(--app-theme-message-action-foreground);
+ --secondary: var(--app-theme-secondary);
+ --secondary-foreground: var(--app-theme-secondary-foreground);
+ --muted: var(--app-theme-muted);
+ --muted-foreground: var(--app-theme-text-muted);
+ --placeholder: var(--app-theme-placeholder);
+ --secondary-label: var(--app-theme-secondary-label);
+ --icon-muted: var(--app-theme-icon-muted);
+ --accent: var(--app-theme-accent-surface);
+ --accent-foreground: var(--app-theme-accent-surface-foreground);
+ --message-surface: var(--app-theme-message-surface);
+ --message-foreground: var(--app-theme-message-foreground);
+ --message-action: var(--app-theme-message-action);
+ --message-action-foreground: var(--app-theme-message-action-foreground);
+ --message-action-hover: var(--app-theme-message-action-hover);
+ --error: var(--app-theme-error);
+ --error-foreground: var(--app-theme-error-foreground);
+ --error-surface: var(--app-theme-error-surface);
+ --destructive: var(--error);
+ --destructive-foreground: var(--error-foreground);
+ --warning: var(--app-theme-warning);
+ --warning-foreground: var(--app-theme-warning-foreground);
+ --warning-surface: var(--app-theme-warning-surface);
+ --update: var(--app-theme-update);
+ --update-foreground: var(--app-theme-update-foreground);
+ --update-surface: var(--app-theme-update-surface);
+ --border: var(--app-theme-border);
+ --input: var(--app-theme-input);
+ --ring: var(--app-theme-focus);
+ --sidebar: var(--app-theme-sidebar);
+ --sidebar-foreground: var(--app-theme-sidebar-foreground);
+ --sidebar-muted-foreground: var(--app-theme-sidebar-muted-foreground);
+ --sidebar-control-surface: var(--app-theme-sidebar-control-surface);
+ --sidebar-row-hover: var(--app-theme-sidebar-row-hover);
+ --sidebar-row-active: var(--app-theme-sidebar-row-active);
+ --sidebar-row-selected: var(--app-theme-sidebar-row-selected);
+ --sidebar-border: var(--app-theme-sidebar-border);
+ --sidebar-stage-fade: var(--app-theme-sidebar);
+ --code-background: var(--app-theme-code-background);
+ --code-foreground: var(--app-theme-code-foreground);
+ --terminal-background: var(--app-theme-terminal-background);
+ --terminal-foreground: var(--app-theme-terminal-foreground);
+ --terminal-cursor: var(--app-theme-terminal-cursor);
+ --terminal-selection-background: var(--app-theme-terminal-selection-background);
+ --terminal-scrollbar: var(--app-theme-terminal-scrollbar);
+ --terminal-scrollbar-hover: var(--app-theme-terminal-scrollbar-hover);
+}
+
+/* T3 Chat's composer is a translucent lift over --chat-background. Route its
+ measured flattened color through the raised-surface role instead of deriving
+ another tint from the canvas, which made the dark composer too red. */
+html[data-theme-id] .chat-composer-glass-shell {
+ --chat-composer-glass-surface: var(--app-theme-surface-raised);
+}
+
+html[data-theme-id]:not(.dark) .chat-composer-glass-shell {
+ --chat-composer-outline: var(--app-theme-toolbar-border);
+}
+
+html.dark[data-theme-id] .chat-composer-glass-shell {
+ --chat-composer-outline: color-mix(in srgb, var(--app-theme-input) 30%, var(--background));
+ --chat-composer-highlight: color-mix(in srgb, var(--app-theme-input) 12%, transparent);
+}
+
+html.dark[data-theme-id="t3-chat"] .chat-composer-glass-shell {
+ /* T3 Chat's visible composer edge is a dark plum, not the stock translucent
+ white outline. Its highlight is derived from --chat-input-gradient. */
+ --chat-composer-outline: #241e28;
+ --chat-composer-highlight: color-mix(in srgb, #432d48 12%, transparent);
+}
+
+html[data-theme-id]:not(.dark) {
+ color-scheme: light;
+}
+
+html.dark[data-theme-id] {
+ color-scheme: dark;
+}
+
+html[data-theme-id] body {
+ background-color: var(--app-chrome-background);
+ color: var(--foreground);
+}
+
+/* Theme-token dependency probes are restored synchronously, before paint. Keep
+ transitions from observing the temporary sentinel color in between. */
+html[data-theme-token-probe],
+html[data-theme-token-probe] *,
+html[data-theme-token-probe] *::before,
+html[data-theme-token-probe] *::after {
+ transition: none !important;
+}
+
+#theme-inspector-spotlight {
+ position: fixed;
+ z-index: 100;
+ inset: 0;
+ width: 100vw;
+ height: 100dvh;
+ overflow: visible;
+ pointer-events: none;
+}
+
+[data-slot="popover-positioner"]:has([data-theme-editor-panel]),
+[data-slot="tooltip-positioner"]:has([data-theme-editor-panel]) {
+ z-index: 120;
+}
+
+.theme-inspector-spotlight-dimmer {
+ fill: rgb(2 3 8 / 54%);
+}
+
+.theme-inspector-spotlight-glow {
+ fill: color-mix(in oklab, var(--ring) 9%, transparent);
+ stroke: color-mix(in oklab, var(--ring) 72%, white);
+ stroke-width: 2px;
+ opacity: 0.92;
+ vector-effect: non-scaling-stroke;
+}
+
+#theme-inspector-hover {
+ position: fixed;
+ z-index: 101;
+ pointer-events: none;
+ background: color-mix(in oklab, var(--ring) 7%, transparent);
+ border: 1px solid color-mix(in oklab, var(--ring) 70%, white);
+ box-shadow:
+ 0 0 0 3px color-mix(in oklab, var(--ring) 16%, transparent),
+ 0 0 18px color-mix(in oklab, var(--ring) 38%, transparent);
+}
+
+#theme-inspector-hover [data-theme-inspector-hover-label] {
+ position: absolute;
+ left: 0;
+ max-width: 12rem;
+ overflow: hidden;
+ padding: 0.2rem 0.45rem;
+ border: 1px solid color-mix(in oklab, var(--ring) 48%, var(--border));
+ border-radius: 0.4rem;
+ background: var(--popover);
+ box-shadow: 0 4px 16px rgb(0 0 0 / 24%);
+ color: var(--popover-foreground);
+ font-size: 0.6875rem;
+ font-weight: 600;
+ line-height: 1rem;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+#theme-inspector-hover[data-placement="above"] [data-theme-inspector-hover-label] {
+ bottom: calc(100% + 0.35rem);
+}
+
+#theme-inspector-hover[data-placement="below"] [data-theme-inspector-hover-label] {
+ top: calc(100% + 0.35rem);
+}
+
+/* Workspace actions use a small, separate chrome hierarchy. Keeping these
+ roles explicit prevents the thread toolbar from falling back to the default
+ dark-mode whites while preserving the same theme file across clients. */
+html[data-theme-id] [data-chat-header] {
+ background-color: var(--toolbar-background);
+ color: var(--toolbar-foreground);
+}
+
+html[data-theme-id] [data-chat-header] [data-slot="button"],
+html[data-theme-id] [data-chat-header] [data-slot="menu-trigger"],
+html[data-theme-id] [data-chat-header] [data-toolbar-control] {
+ --control-icon-color: var(--toolbar-control-foreground);
+ background-color: var(--toolbar-control);
+ border-color: var(--toolbar-border);
+ color: var(--toolbar-control-foreground);
+}
+
+/* The panel layout toggles stay ghost: they render both inside the header and
+ in the titlebar strip, so filling them would make them change appearance as
+ the panel opens. They only take the themed foreground; hover and pressed
+ keep the base ghost accent. The tooltip trigger's data-slot wins over the
+ toggle's when the trigger renders the toggle, so match both. */
+html[data-theme-id] [data-panel-layout-controls] [data-slot="toggle"],
+html[data-theme-id] [data-panel-layout-controls] [data-slot="tooltip-trigger"],
+html[data-theme-id] .workspace-titlebar-controls [data-slot="toggle"],
+html[data-theme-id] .workspace-titlebar-controls [data-slot="tooltip-trigger"] {
+ --control-icon-color: var(--toolbar-foreground);
+ color: var(--toolbar-foreground);
+}
+
+html[data-theme-id] [data-chat-header] [data-slot="button"]:hover,
+html[data-theme-id] [data-chat-header] [data-slot="button"][data-pressed],
+html[data-theme-id] [data-chat-header] [data-slot="menu-trigger"]:hover,
+html[data-theme-id] [data-chat-header] [data-slot="menu-trigger"][data-pressed],
+html[data-theme-id] [data-chat-header] [data-toolbar-control]:hover,
+html[data-theme-id] [data-chat-header] [data-toolbar-control][data-pressed] {
+ background-color: var(--toolbar-control-hover);
+}
+
+html[data-theme-id] [data-chat-header] [data-slot="separator"] {
+ background-color: var(--toolbar-border);
+}
+
+/* Chat code blocks join the other code surfaces on the code tokens. The
+ default look keeps its secondary/input tints; themed palettes tint those
+ surfaces with the accent, which fights syntax highlighting. */
+html[data-theme-id] .chat-markdown .chat-markdown-codeblock {
+ background-color: var(--code-background);
+ border-color: var(--border);
+ color: var(--code-foreground);
+}
+
+html[data-theme-id] .chat-markdown pre {
+ background-color: var(--code-background);
+ color: var(--code-foreground);
+}
+
+html[data-theme-id] .chat-markdown .chat-markdown-codeblock pre {
+ background-color: transparent;
+}
+
+html[data-theme-id] .chat-markdown .chat-markdown-codeblock-header,
+html[data-theme-id] .chat-markdown .chat-markdown-chrome-action {
+ color: color-mix(in srgb, var(--code-foreground) 72%, transparent);
+}
+
+/* T3 Chat renders inline code and compact chat artifacts with its translucent
+ secondary surface flattened over the light chat canvas. The raw muted and
+ secondary tokens are substantially darker than those visible pixels. */
+html[data-theme-id="t3-chat"]:not(.dark) .chat-markdown :not(pre) > code,
+html[data-theme-id="t3-chat"]:not(.dark) [data-changed-files-state],
+html[data-theme-id="t3-chat"]:not(.dark) [data-changed-files-header] {
+ background-color: var(--message-surface);
+}
+
+html[data-theme-id="t3-chat"]:not(.dark) .chat-markdown :not(pre) > code,
+html[data-theme-id="t3-chat"]:not(.dark) [data-changed-files-state] {
+ border-color: transparent;
+}
+
+html[data-theme-id="t3-chat"]:not(.dark) .chat-markdown :not(pre) > code {
+ color: var(--message-foreground);
+}
+
+html[data-theme-id] .chat-markdown .chat-markdown-chrome-action:hover,
+html[data-theme-id] .chat-markdown .chat-markdown-chrome-action[aria-pressed="true"] {
+ color: var(--code-foreground);
+}
+
+html[data-theme-id] [data-sidebar-version="v1"],
+html[data-theme-id] [data-sidebar-version="v2"] {
+ --background: var(--app-theme-canvas);
+ --foreground: var(--app-theme-text);
+ --card: var(--app-theme-surface);
+ --card-foreground: var(--app-theme-text);
+ --accent: var(--app-theme-accent-surface);
+ --accent-foreground: var(--app-theme-accent-surface-foreground);
+ --muted: var(--app-theme-muted);
+ --muted-foreground: var(--app-theme-text-muted);
+ --border: var(--app-theme-border);
+ --input: var(--app-theme-input);
+ --sidebar: var(--app-theme-sidebar);
+ --sidebar-foreground: var(--app-theme-sidebar-foreground);
+ --sidebar-muted-foreground: var(--app-theme-sidebar-muted-foreground);
+ --sidebar-control-surface: var(--app-theme-sidebar-control-surface);
+ --sidebar-row-hover: var(--app-theme-sidebar-row-hover);
+ --sidebar-row-active: var(--app-theme-sidebar-row-active);
+ --sidebar-row-selected: var(--app-theme-sidebar-row-selected);
+ --sidebar-border: var(--app-theme-sidebar-border);
+ --sidebar-stage-fade: var(--app-theme-sidebar);
+ background-color: var(--sidebar);
+}
+
+/* Keep the navigation edge as quiet as the standard palettes. Theme files may
+ still use sidebarBorder for controls and internal separators, but the outer
+ divider should not become more prominent just because a palette is vivid. */
+html[data-theme-id] [data-app-sidebar] {
+ border-color: color-mix(in srgb, var(--sidebar-foreground) 10%, transparent);
+}
+
+html.dark[data-theme-id] [data-app-sidebar] {
+ border-color: color-mix(in srgb, var(--sidebar-foreground) 8%, transparent);
+}
+
+/* T3 Chat's panel divider is deliberately pink, and its resize affordance
+ keeps that color while hovered. Do not neutralize this branded edge. */
+html.dark[data-theme-id="t3-chat"] [data-app-sidebar] {
+ border-color: var(--sidebar-border);
+}
+
+.theme-json-key {
+ color: var(--app-theme-accent, var(--color-blue-600));
+}
+
+.theme-json-string {
+ color: var(--app-theme-message-action, var(--color-emerald-600));
+}
+
+.theme-json-number {
+ color: var(--app-theme-secondary-foreground, var(--color-amber-600));
+}
+
+.theme-json-constant {
+ color: var(--app-theme-accent-surface-foreground, var(--color-violet-600));
+}
+
body {
/* Reference the theme token (not a literal stack) so the Settings ->
Appearance runtime override of --font-sans reaches all interface text. */
@@ -1028,12 +1422,21 @@ body {
grain's subtle brightening and stand out against the body. */
:root {
--surface-grain: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.035'/%3E%3C/svg%3E");
+ --surface-grain-size: 256px 256px;
+}
+
+/* The live T3 Chat texture is a 128px grayscale tile with a constant 7/255
+ alpha. Keep our procedural texture cheap while matching that scale and
+ strength for the branded preset. */
+html[data-theme-id="t3-chat"] {
+ --surface-grain: url("data:image/svg+xml,%3Csvg viewBox='0 0 128 128' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='0.02745'/%3E%3C/svg%3E");
+ --surface-grain-size: 128px 128px;
}
body {
background-image: var(--surface-grain);
background-repeat: repeat;
- background-size: 256px 256px;
+ background-size: var(--surface-grain-size);
}
pre,
@@ -1584,15 +1987,34 @@ label:has(> select#reasoning-effort) select {
/* Diffs theme bridge (match diff surfaces to app palette) */
.diff-panel-viewport {
- background: color-mix(in srgb, var(--background) 94%, var(--card));
+ background: var(--background);
+}
+
+/* Diffs live directly on the panel canvas. Normal chat code blocks may use a
+ raised code surface, but carrying that fill into the diff creates a card-like
+ rectangle that does not belong in the panel. */
+.diff-render-surface {
+ --code-background: var(--background);
}
.diff-render-file,
-.diff-render-surface > diffs-container {
- border: 1px solid var(--border);
- border-radius: 0.5rem;
+.diff-render-surface diffs-container {
+ border: 0;
+ border-radius: 0;
overflow: clip;
- background: color-mix(in srgb, var(--card) 92%, var(--background));
+ background: var(--code-background);
+ color: var(--code-foreground);
+}
+
+/* Pierre's file renderer owns its own surface tokens. Keep the root of a file
+ preview on the same themeable code surface as the diff panel. */
+.diff-render-surface diffs-container,
+.file-preview-virtualizer diffs-container {
+ --diffs-bg: var(--code-background) !important;
+ --diffs-light-bg: var(--code-background) !important;
+ --diffs-dark-bg: var(--code-background) !important;
+ background-color: var(--code-background) !important;
+ color: var(--code-foreground) !important;
}
@keyframes ultrathink-rainbow {
diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts
index 703077e3e..11aa97dc8 100644
--- a/apps/web/src/keybindings.test.ts
+++ b/apps/web/src/keybindings.test.ts
@@ -128,6 +128,10 @@ const DEFAULT_BINDINGS = compile([
command: "projectSearch.toggle",
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
+ {
+ shortcut: modShortcut("t", { altKey: true, shiftKey: true }),
+ command: "themeEditor.toggle",
+ },
{
shortcut: modShortcut("m", { shiftKey: true }),
command: "modelPicker.toggle",
@@ -566,6 +570,25 @@ describe("chat/editor shortcuts", () => {
);
});
+ it("matches themeEditor.toggle on macOS and Windows", () => {
+ assert.strictEqual(
+ resolveShortcutCommand(
+ event({ key: "t", metaKey: true, altKey: true, shiftKey: true }),
+ DEFAULT_BINDINGS,
+ { platform: "MacIntel" },
+ ),
+ "themeEditor.toggle",
+ );
+ assert.strictEqual(
+ resolveShortcutCommand(
+ event({ key: "t", ctrlKey: true, altKey: true, shiftKey: true }),
+ DEFAULT_BINDINGS,
+ { platform: "Win32" },
+ ),
+ "themeEditor.toggle",
+ );
+ });
+
it("matches diff.toggle shortcut outside terminal focus", () => {
assert.isTrue(
isDiffToggleShortcut(event({ key: "d", metaKey: true }), DEFAULT_BINDINGS, {
diff --git a/apps/web/src/lib/diffRendering.ts b/apps/web/src/lib/diffRendering.ts
index 5a9e5d30d..9d29d2605 100644
--- a/apps/web/src/lib/diffRendering.ts
+++ b/apps/web/src/lib/diffRendering.ts
@@ -172,3 +172,74 @@ export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string
return "text-muted-foreground/80";
}
}
+
+/**
+ * Maps every diff/file surface the @pierre/diffs renderer paints onto the
+ * app's code tokens, so themed palettes reach the code body, gutter, and
+ * row tints instead of the renderer's bundled colors. Shared by the diff
+ * panel and the file preview.
+ */
+export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
+[data-diffs-header],
+[data-diff],
+[data-file],
+[data-error-wrapper],
+[data-virtualizer-buffer] {
+ --diffs-header-font-family: var(--font-sans) !important;
+ --diffs-font-family: var(--font-mono) !important;
+ --diffs-bg: var(--code-background) !important;
+ --diffs-light-bg: var(--code-background) !important;
+ --diffs-dark-bg: var(--code-background) !important;
+ --diffs-token-light-bg: transparent;
+ --diffs-token-dark-bg: transparent;
+
+ /* Gutter, context, and row tints all derive from the code surface the diff
+ body sits on — mixing from the canvas leaves the gutter looking unthemed
+ when a palette separates the two. */
+ --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
+ --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
+ --diffs-bg-separator-override: color-mix(
+ in srgb,
+ var(--code-background) 95%,
+ var(--code-foreground)
+ );
+ --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
+
+ --diffs-bg-addition-override: light-dark(
+ color-mix(in srgb, var(--code-background) 50%, var(--success)),
+ color-mix(in srgb, var(--code-background) 70%, var(--success))
+ );
+ --diffs-bg-addition-number-override: light-dark(
+ color-mix(in srgb, var(--code-background) 35%, var(--success)),
+ color-mix(in srgb, var(--code-background) 60%, var(--success))
+ );
+ --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--success));
+ --diffs-bg-addition-emphasis-override: color-mix(
+ in srgb,
+ var(--code-background) 80%,
+ var(--success)
+ );
+
+ --diffs-bg-deletion-override: light-dark(
+ color-mix(in srgb, var(--code-background) 50%, var(--destructive)),
+ color-mix(in srgb, var(--code-background) 70%, var(--destructive))
+ );
+ --diffs-bg-deletion-number-override: light-dark(
+ color-mix(in srgb, var(--code-background) 35%, var(--destructive)),
+ color-mix(in srgb, var(--code-background) 60%, var(--destructive))
+ );
+ --diffs-bg-deletion-hover-override: color-mix(
+ in srgb,
+ var(--code-background) 85%,
+ var(--destructive)
+ );
+ --diffs-bg-deletion-emphasis-override: color-mix(
+ in srgb,
+ var(--code-background) 80%,
+ var(--destructive)
+ );
+
+ background-color: var(--diffs-bg) !important;
+ color: var(--code-foreground) !important;
+}
+`;
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index bbad8a303..cff930539 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -19,6 +19,7 @@ import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstall
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
+import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
import { Button } from "../components/ui/button";
import {
AnchoredToastProvider,
@@ -139,6 +140,9 @@ function RootRouteView() {
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
{appShell}
+ {/* Above the router: a theme draft is judged by walking the app, so the
+ editor has to survive navigation away from settings. */}
+ <ThemeEditorHost />
</AnchoredToastProvider>
</ToastProvider>
);
diff --git a/apps/web/src/themeBoot.test.ts b/apps/web/src/themeBoot.test.ts
new file mode 100644
index 000000000..d6137e643
--- /dev/null
+++ b/apps/web/src/themeBoot.test.ts
@@ -0,0 +1,455 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import indexHtml from "../index.html?raw";
+import {
+ CUSTOM_THEMES_STORAGE_KEY,
+ getDefaultThemeColors,
+ getThemeColorsForMode,
+ invalidateCustomThemes,
+ isKnownThemePreference,
+ resolveThemeAppearance,
+ T3_CHAT_THEME,
+ EMBER_THEME,
+ GROVE_THEME,
+ IRIS_THEME,
+ OCEAN_THEME,
+ THEME_APPEARANCE_MODE_STORAGE_KEY,
+ THEME_FOLLOW_SYSTEM_STORAGE_KEY,
+} from "./themePalette";
+
+const THEME_STORAGE_KEY = "t3code:theme";
+// A custom theme that omits chrome falls back to the runtime default, so the
+// boot copy of that default stays derived from the real palette.
+const DEFAULT_DARK_CHROME = getDefaultThemeColors("dark").chrome;
+
+const bootScript = (() => {
+ const match = indexHtml.match(/<script>([\s\S]*?)<\/script>/);
+ if (!match?.[1]) throw new Error("Could not find the inline boot script in index.html");
+ return match[1];
+})();
+
+type BootResult = {
+ isDark: boolean;
+ themeId: string | undefined;
+ themeSelected: string | undefined;
+ backgroundColor: string;
+ bootVariables: Record<string, string>;
+ metaContent: string | null;
+};
+
+function runBootScript(options: {
+ storage?: Record<string, string>;
+ storageThrows?: boolean;
+ prefersDark: boolean;
+}): BootResult {
+ const classes = new Set<string>();
+ const bootVariables: Record<string, string> = {};
+ const meta = {
+ content: null as string | null,
+ setAttribute(_name: string, value: string) {
+ this.content = value;
+ },
+ };
+ const documentElement = {
+ dataset: {} as Record<string, string | undefined>,
+ classList: {
+ add: (name: string) => void classes.add(name),
+ remove: (name: string) => void classes.delete(name),
+ toggle: (name: string, force?: boolean) => {
+ const next = force ?? !classes.has(name);
+ if (next) classes.add(name);
+ else classes.delete(name);
+ return next;
+ },
+ },
+ style: {
+ backgroundColor: "",
+ setProperty: (name: string, value: string) => {
+ bootVariables[name] = value;
+ },
+ },
+ };
+ const fakeDocument = {
+ documentElement,
+ querySelectorAll: (selector: string) => (selector === 'meta[name="theme-color"]' ? [meta] : []),
+ };
+ const fakeWindow = {
+ localStorage: {
+ getItem: (key: string): string | null => {
+ if (options.storageThrows) throw new Error("storage blocked");
+ return options.storage?.[key] ?? null;
+ },
+ },
+ matchMedia: () => ({ matches: options.prefersDark }),
+ };
+
+ new Function("window", "document", bootScript)(fakeWindow, fakeDocument);
+
+ return {
+ isDark: classes.has("dark"),
+ themeId: documentElement.dataset.themeId,
+ themeSelected: documentElement.dataset.themeSelected,
+ backgroundColor: documentElement.style.backgroundColor,
+ bootVariables,
+ metaContent: meta.content,
+ };
+}
+
+/** Mirrors getStored + readAppearanceModePreference + resolveThemeAppearance from the runtime. */
+function runtimeResolvedAppearance(
+ storage: Record<string, string>,
+ prefersDark: boolean,
+): "light" | "dark" {
+ vi.stubGlobal("window", {
+ localStorage: { getItem: (key: string) => storage[key] ?? null },
+ matchMedia: () => ({ matches: prefersDark }),
+ });
+ invalidateCustomThemes();
+ try {
+ const raw = storage[THEME_STORAGE_KEY] ?? null;
+ const theme = raw !== null && isKnownThemePreference(raw) ? raw : "system";
+ const followRaw = storage[THEME_FOLLOW_SYSTEM_STORAGE_KEY] ?? null;
+ const appearanceRaw = storage[THEME_APPEARANCE_MODE_STORAGE_KEY] ?? null;
+ const appearanceMode =
+ appearanceRaw === "light" || appearanceRaw === "dark" || appearanceRaw === "system"
+ ? appearanceRaw
+ : followRaw === "true"
+ ? "system"
+ : followRaw === "false"
+ ? null
+ : theme === "system"
+ ? "system"
+ : null;
+ const followSystem = appearanceMode === "system";
+ return resolveThemeAppearance(theme, prefersDark, followSystem, appearanceMode ?? undefined);
+ } finally {
+ vi.unstubAllGlobals();
+ invalidateCustomThemes();
+ }
+}
+
+const AURORA_DUAL = {
+ id: "aurora",
+ label: "Aurora",
+ appearance: "light",
+ colors: { canvas: "#f8fbff", text: "#10243d", accent: "#5b6cff" },
+ variants: { dark: { canvas: "#101827", text: "#eef5ff", accent: "#7c93ff" } },
+};
+const CHARCOAL_DARK_ONLY = {
+ id: "charcoal",
+ label: "Charcoal",
+ appearance: "dark",
+ colors: { canvas: "#1c1210", text: "#ffe8d9", accent: "#ff7a45" },
+};
+
+describe("index.html boot script", () => {
+ const parityCases: ReadonlyArray<{
+ name: string;
+ storage: Record<string, string>;
+ prefersDark: boolean;
+ }> = [
+ { name: "no stored preference on a dark OS", storage: {}, prefersDark: true },
+ {
+ name: "T3 Chat follows a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "t3-chat", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "an explicit global dark mode applies to T3 Chat",
+ storage: {
+ [THEME_STORAGE_KEY]: "t3-chat",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "dark",
+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "false",
+ },
+ prefersDark: false,
+ },
+ {
+ name: "Grove follows a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "grove", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "Ocean follows a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "ocean", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "Ember follows a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "ember", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "Iris follows a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "iris", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "a legacy t3-grove preference resolves through the alias",
+ storage: { [THEME_STORAGE_KEY]: "t3-grove", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ },
+ {
+ name: "legacy t3-chat-dark resolves to dark T3 Chat",
+ storage: { [THEME_STORAGE_KEY]: "t3-chat-dark" },
+ prefersDark: true,
+ },
+ {
+ name: "a dual-mode custom theme follows the OS",
+ storage: {
+ [THEME_STORAGE_KEY]: "aurora",
+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([AURORA_DUAL]),
+ },
+ prefersDark: true,
+ },
+ {
+ name: "a dark-only custom theme stays dark on a light OS",
+ storage: {
+ [THEME_STORAGE_KEY]: "charcoal",
+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([CHARCOAL_DARK_ONLY]),
+ },
+ prefersDark: false,
+ },
+ {
+ name: "a legacy mode-suffixed preference is treated as unknown",
+ storage: {
+ [THEME_STORAGE_KEY]: "aurora:dark",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([AURORA_DUAL]),
+ },
+ prefersDark: true,
+ },
+ {
+ name: "a removed custom theme falls back to system",
+ storage: { [THEME_STORAGE_KEY]: "gone-theme" },
+ prefersDark: true,
+ },
+ {
+ name: "a corrupted follow-system value falls back to inference",
+ storage: { [THEME_STORAGE_KEY]: "system", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "1" },
+ prefersDark: true,
+ },
+ {
+ name: "follow-system off keeps an explicit light preference on a dark OS",
+ storage: { [THEME_STORAGE_KEY]: "light", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "false" },
+ prefersDark: true,
+ },
+ {
+ name: "a bare dark preference stays dark on a light OS",
+ storage: { [THEME_STORAGE_KEY]: "dark" },
+ prefersDark: false,
+ },
+ {
+ name: "follow-system off keeps a bare dark preference on a light OS",
+ storage: { [THEME_STORAGE_KEY]: "dark", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "false" },
+ prefersDark: false,
+ },
+ ];
+
+ it.each(parityCases)("matches the runtime appearance: $name", ({ storage, prefersDark }) => {
+ const boot = runBootScript({ storage, prefersDark });
+ expect(boot.isDark).toBe(runtimeResolvedAppearance(storage, prefersDark) === "dark");
+ });
+
+ it("marks built-in and custom themes on the document element", () => {
+ const chat = runBootScript({
+ storage: { [THEME_STORAGE_KEY]: "t3-chat", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },
+ prefersDark: true,
+ });
+ expect(chat.themeId).toBe("t3-chat");
+ expect(chat.themeSelected).toBe("true");
+ expect(chat.isDark).toBe(true);
+
+ const aurora = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "aurora",
+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([AURORA_DUAL]),
+ },
+ prefersDark: true,
+ });
+ expect(aurora.themeId).toBe("aurora");
+ expect(aurora.isDark).toBe(true);
+ expect(aurora.backgroundColor).toBe(DEFAULT_DARK_CHROME);
+ expect(aurora.bootVariables["--boot-background"]).toBe(AURORA_DUAL.variants.dark.canvas);
+ expect(aurora.metaContent).toBe(DEFAULT_DARK_CHROME);
+ });
+
+ // Asserting against the real palette definitions (not literals) turns the
+ // boot script's hand-maintained copy into a CI-enforced contract: any
+ // palette change breaks this test until the copy in index.html is updated.
+ it("keeps every built-in boot splash in sync with the real palettes", () => {
+ for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
+ // The boot script resolves every built-in from a light base appearance.
+ expect(theme.appearance).toBe("light");
+ for (const mode of ["light", "dark"] as const) {
+ const colors = getThemeColorsForMode(theme, mode);
+ expect(colors).not.toBeNull();
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: theme.id,
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: mode,
+ },
+ prefersDark: mode === "dark",
+ });
+ expect(boot.themeId).toBe(theme.id);
+ expect(boot.isDark).toBe(mode === "dark");
+ expect(boot.bootVariables["--boot-background"]).toBe(colors!.canvas);
+ expect(boot.bootVariables["--boot-foreground"]).toBe(colors!.text);
+ expect(boot.bootVariables["--boot-accent"]).toBe(colors!.accent);
+ expect(boot.backgroundColor).toBe(colors!.chrome);
+ expect(boot.metaContent).toBe(colors!.chrome);
+ }
+ }
+ });
+
+ it("applies the matching half of an automatic mix to the splash", () => {
+ const storage = {
+ [THEME_STORAGE_KEY]: "t3-chat",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "system",
+ "t3code:theme-halves:v1": JSON.stringify({ dark: GROVE_THEME.id }),
+ };
+
+ const dark = runBootScript({ storage, prefersDark: true });
+ expect(dark.isDark).toBe(true);
+ expect(dark.themeId).toBe(GROVE_THEME.id);
+ expect(dark.bootVariables["--boot-background"]).toBe(
+ getThemeColorsForMode(GROVE_THEME, "dark")!.canvas,
+ );
+
+ const light = runBootScript({ storage, prefersDark: false });
+ expect(light.isDark).toBe(false);
+ expect(light.themeId).toBe("t3-chat");
+ expect(light.bootVariables["--boot-background"]).toBe(
+ getThemeColorsForMode(T3_CHAT_THEME, "light")!.canvas,
+ );
+ });
+
+ it("lets a dark half go dark when the light-only base cannot", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "paper",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "system",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
+ {
+ id: "paper",
+ label: "Paper",
+ appearance: "light",
+ colors: { canvas: "#f8fbff", text: "#10243d", accent: "#5b6cff" },
+ },
+ ]),
+ "t3code:theme-halves:v1": JSON.stringify({ dark: GROVE_THEME.id }),
+ },
+ prefersDark: true,
+ });
+ expect(boot.isDark).toBe(true);
+ expect(boot.themeId).toBe(GROVE_THEME.id);
+ });
+
+ it("paints the half's splash when the base theme no longer exists", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "gone-theme",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "system",
+ "t3code:theme-halves:v1": JSON.stringify({ dark: GROVE_THEME.id }),
+ },
+ prefersDark: true,
+ });
+ expect(boot.isDark).toBe(true);
+ expect(boot.themeId).toBe(GROVE_THEME.id);
+ expect(boot.themeSelected).toBe("true");
+ expect(boot.bootVariables["--boot-background"]).toBe(
+ getThemeColorsForMode(GROVE_THEME, "dark")!.canvas,
+ );
+ });
+
+ it("resolves a legacy-prefixed mix half onto the renamed theme", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "t3-chat",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "system",
+ "t3code:theme-halves:v1": JSON.stringify({ dark: "t3-grove" }),
+ },
+ prefersDark: true,
+ });
+ expect(boot.isDark).toBe(true);
+ expect(boot.themeId).toBe(GROVE_THEME.id);
+ expect(boot.bootVariables["--boot-background"]).toBe(
+ getThemeColorsForMode(GROVE_THEME, "dark")!.canvas,
+ );
+ });
+
+ it("ignores a mix half that names an unknown theme", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "t3-chat",
+ [THEME_APPEARANCE_MODE_STORAGE_KEY]: "system",
+ "t3code:theme-halves:v1": JSON.stringify({ dark: "gone-theme" }),
+ },
+ prefersDark: true,
+ });
+ expect(boot.themeId).toBe("t3-chat");
+ expect(boot.isDark).toBe(true);
+ });
+
+ it("uses runtime defaults for malformed custom roles", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "partial",
+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
+ {
+ id: "partial",
+ label: "Partial",
+ appearance: "dark",
+ colors: { canvas: "not-a-color", text: "#fffaff", accent: "nope" },
+ },
+ ]),
+ },
+ prefersDark: true,
+ });
+
+ expect(boot.themeId).toBe("partial");
+ expect(boot.bootVariables["--boot-background"]).toBe("#1f1a24");
+ expect(boot.bootVariables["--boot-foreground"]).toBe("#fffaff");
+ expect(boot.bootVariables["--boot-accent"]).toBe("#a3004c");
+ expect(boot.backgroundColor).toBe(DEFAULT_DARK_CHROME);
+ expect(boot.metaContent).toBe(DEFAULT_DARK_CHROME);
+ });
+
+ it("ignores malformed custom theme entries before applying a splash", () => {
+ const boot = runBootScript({
+ storage: {
+ [THEME_STORAGE_KEY]: "broken",
+ [CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
+ { id: "broken", label: "Broken", appearance: "light", colors: "bad" },
+ ]),
+ },
+ prefersDark: false,
+ });
+
+ expect(boot.themeId).toBeUndefined();
+ expect(boot.themeSelected).toBeUndefined();
+ expect(boot.backgroundColor).toBe("#ffffff");
+ expect(boot.metaContent).toBe("#ffffff");
+ });
+
+ it("leaves unknown preferences unthemed so the runtime default applies", () => {
+ const boot = runBootScript({
+ storage: { [THEME_STORAGE_KEY]: "gone-theme" },
+ prefersDark: true,
+ });
+ expect(boot.themeId).toBeUndefined();
+ expect(boot.themeSelected).toBeUndefined();
+ expect(boot.isDark).toBe(true);
+ });
+
+ it("follows the OS appearance when storage is unavailable", () => {
+ const light = runBootScript({ storageThrows: true, prefersDark: false });
+ expect(light.isDark).toBe(false);
+ expect(light.themeId).toBeUndefined();
+
+ const dark = runBootScript({ storageThrows: true, prefersDark: true });
+ expect(dark.isDark).toBe(true);
+ });
+});
diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.ts
new file mode 100644
index 000000000..2ed4ff389
--- /dev/null
+++ b/apps/web/src/themePalette.test.ts
@@ -0,0 +1,509 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import {
+ getThemeColorsForMode,
+ getThemeDefinition,
+ getThemeModes,
+ getThemePreferenceMode,
+ isKnownThemePreference,
+ getCustomThemes,
+ invalidateCustomThemes,
+ installCustomTheme,
+ canonicalThemePreference,
+ parseThemeFile,
+ parseThemeHalves,
+ resolveDesktopTheme,
+ resolveThemeAppearance,
+ serializeThemeFile,
+ subscribeToCustomThemes,
+ T3_CHAT_THEME,
+ EMBER_THEME,
+ GROVE_THEME,
+ IRIS_THEME,
+ OCEAN_THEME,
+ updateCustomTheme,
+ CUSTOM_THEMES_STORAGE_KEY,
+ createManagedThemeColors,
+ createVividThemeColors,
+ getDefaultThemeColors,
+ THEME_FILE_VERSION,
+} from "./themePalette";
+
+function contrastRatio(first: string, second: string): number {
+ const toRgb = (value: string) => {
+ const hex = value.slice(1);
+ return [0, 1, 2].map(
+ (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
+ );
+ };
+ const luminance = (value: string) =>
+ toRgb(value)
+ .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
+ .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
+ const lighter = Math.max(luminance(first), luminance(second));
+ const darker = Math.min(luminance(first), luminance(second));
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+describe("theme files", () => {
+ it("derives a readable palette from extreme simple-editor colors", () => {
+ const light = createManagedThemeColors("light", "#111827", "#ffff00");
+ const dark = createManagedThemeColors("dark", "#ffffff", "#ffff00");
+ const darkDefaults = getDefaultThemeColors("dark");
+
+ expect(light.canvas).not.toBe("#111827");
+ expect(dark.canvas).not.toBe("#ffffff");
+ expect(contrastRatio(light.accent, light.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(dark.accent, dark.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(light.textMuted, light.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(dark.textMuted, dark.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(light.textMuted, light.canvas)).toBeLessThan(5.5);
+ expect(contrastRatio(dark.textMuted, dark.canvas)).toBeLessThan(5.5);
+ expect(contrastRatio(light.textMuted, light.canvas)).toBeCloseTo(4.705, 1);
+ expect(contrastRatio(dark.textMuted, dark.canvas)).toBeCloseTo(5.082, 1);
+ expect(light.secondaryLabel).toBe(light.textMuted);
+ expect(dark.secondaryLabel).toBe(dark.textMuted);
+ expect(contrastRatio(light.accentForeground, light.accent)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(dark.accentForeground, dark.accent)).toBeGreaterThanOrEqual(4.5);
+ // Status colors fall back to T3 Code's standard red and amber rather than
+ // the flagship palette's, so no generated theme inherits a brand tint.
+ const channels = (value: string) =>
+ [1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16)) as [
+ number,
+ number,
+ number,
+ ];
+ for (const colors of [light, dark]) {
+ const [errorRed, errorGreen, errorBlue] = channels(colors.error);
+ // Red leads by a wide margin; the old default was a pink whose blue sat
+ // close behind its red.
+ expect(errorRed).toBeGreaterThan(errorGreen * 2);
+ expect(errorRed).toBeGreaterThan(errorBlue * 2);
+ expect(contrastRatio(colors.error, "#ffffff")).toBeGreaterThanOrEqual(2.5);
+ expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ const [warnRed, warnGreen, warnBlue] = channels(colors.warning);
+ expect(warnRed).toBeGreaterThan(warnBlue);
+ expect(warnGreen).toBeGreaterThan(warnBlue);
+ }
+ expect(dark.error).not.toBe(darkDefaults.error);
+ });
+
+ it("derives readable, distinctive vivid palettes from exact seeds", () => {
+ const seeds: ReadonlyArray<["light" | "dark", string, string]> = [
+ ["light", "#f4f9f2", "#1d8a4e"],
+ ["dark", "#101a2c", "#4f8fe8"],
+ ["dark", "#211a23", "#df5398"],
+ ["light", "#fdf6ec", "#c2571b"],
+ // Inverted canvases: the palette follows the picked color, not the slot.
+ ["light", "#111827", "#8ab4f8"],
+ ["dark", "#f5ecf5", "#a84370"],
+ ];
+ for (const [appearance, canvas, accent] of seeds) {
+ const colors = createVividThemeColors(appearance, canvas, accent);
+ // Exact seeds are honored.
+ expect(colors.canvas).toBe(canvas);
+ expect(colors.accent).toBe(accent);
+ // Readability is solved per surface.
+ expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
+ expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(colors.textMuted, colors.canvas)).toBeLessThan(5.5);
+ expect(colors.secondaryLabel).toBe(colors.textMuted);
+ expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(4.5);
+ expect(
+ contrastRatio(colors.messageActionForeground, colors.messageAction),
+ ).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
+ // The companion action is a distinct voice, not the accent again.
+ expect(colors.messageAction).not.toBe(colors.accent);
+ // Update family follows the theme, not the default palette.
+ expect(colors.update).toBe(accent);
+ }
+ });
+
+ it("keys status colors off the canvas, not the appearance slot", () => {
+ // Inverted seeds: a dark canvas in the light slot must still get the dark
+ // status pair, or the alert foreground lands on a dark surface unreadable.
+ const inverted = [
+ createVividThemeColors("light", "#111827", "#8ab4f8"),
+ createVividThemeColors("dark", "#f5ecf5", "#a84370"),
+ createManagedThemeColors("light", "#0d1117", "#69b1ff", { exactSeeds: true }),
+ createManagedThemeColors("dark", "#fdfdfd", "#c2571b", { exactSeeds: true }),
+ ];
+ for (const colors of inverted) {
+ expect(contrastRatio(colors.errorForeground, colors.errorSurface)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ expect(contrastRatio(colors.warningForeground, colors.warningSurface)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ }
+ });
+
+ it("merges a small user file onto the matching contrast-safe base palette", () => {
+ const theme = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: "Ocean dusk",
+ appearance: "dark",
+ colors: {
+ canvas: "#07152f",
+ accent: "#67c2ff",
+ },
+ });
+
+ expect(theme).toMatchObject({
+ id: "ocean-dusk",
+ label: "Ocean dusk",
+ appearance: "dark",
+ colors: {
+ canvas: "#07152f",
+ accent: "#67c2ff",
+ placeholder: "#8f8699",
+ },
+ });
+ });
+
+ it("rejects unknown roles and invalid color values", () => {
+ expect(() =>
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: "Broken",
+ appearance: "light",
+ colors: { background: "#ffffff" },
+ }),
+ ).toThrow('"background" is not a supported theme color role.');
+
+ expect(() =>
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: "Broken",
+ appearance: "light",
+ colors: { accent: "var(--danger)" },
+ }),
+ ).toThrow('The color for "accent" must be a hex color');
+ });
+
+ it("serializes a theme back into the importable file shape", () => {
+ const serialized = serializeThemeFile(T3_CHAT_THEME);
+ expect(JSON.parse(serialized)).toMatchObject({
+ version: THEME_FILE_VERSION,
+ id: T3_CHAT_THEME.id,
+ name: T3_CHAT_THEME.label,
+ appearance: "light",
+ });
+ });
+
+ it("keeps optional light and dark palettes under one theme id", () => {
+ const theme = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: "aurora",
+ name: "Aurora",
+ appearance: "light",
+ colors: { canvas: "#f8fbff", text: "#10243d" },
+ variants: {
+ dark: { canvas: "#101827", text: "#eef5ff" },
+ },
+ });
+
+ expect(getThemeModes(theme)).toEqual(["light", "dark"]);
+ expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
+ canvas: "#101827",
+ text: "#eef5ff",
+ });
+ expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
+ expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
+ expect(resolveDesktopTheme(T3_CHAT_THEME.id, true)).toBe("system");
+ expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
+ expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
+ expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
+ canvas: "#101827",
+ text: "#eef5ff",
+ });
+ });
+
+ it("keeps the T3 Chat palette faithful and readable", () => {
+ expect(T3_CHAT_THEME.colors).toMatchObject({
+ canvas: "#fdf7fd",
+ chrome: "#fdf7fd",
+ toolbarBorder: "#efbdeb",
+ toolbarControl: "#f3e6f5",
+ toolbarControlHover: "#eccfe3",
+ surfaceRaised: "#fdfafd",
+ input: "#e7c1dc",
+ focus: "#db2777",
+ messageSurface: "#f7def2",
+ codeBackground: "#f5ecf9",
+ codeForeground: "#673c8b",
+ accentSurface: "#f3e6f5",
+ sidebar: "#f2e1f4",
+ });
+ expect(T3_CHAT_THEME.variants?.dark).toMatchObject({
+ canvas: "#1f1a24",
+ chrome: "#1f1a24",
+ surface: "#29232d",
+ surfaceRaised: "#2c2631",
+ input: "#302029",
+ focus: "#db2777",
+ messageSurface: "#2b2431",
+ codeBackground: "#1f1a24",
+ sidebar: "#171018",
+ sidebarBorder: "#322028",
+ });
+
+ for (const mode of ["light", "dark"] as const) {
+ const colors = getThemeColorsForMode(T3_CHAT_THEME, mode)!;
+ expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
+ expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(colors.messageForeground, colors.messageSurface)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ expect(contrastRatio(colors.secondaryForeground, colors.secondary)).toBeGreaterThanOrEqual(
+ 4.5,
+ );
+ expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
+ // The live light primary is intended for filled controls and clears the
+ // non-text UI-component threshold rather than normal-text AA.
+ expect(contrastRatio(colors.accentForeground, colors.accent)).toBeGreaterThanOrEqual(3);
+ }
+ });
+
+ it("includes the dual-mode maintainer themes", () => {
+ for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
+ expect(getThemeDefinition(theme.id)).toBe(theme);
+ expect(getThemeModes(theme)).toEqual(["light", "dark"]);
+ expect(theme.colors.accent).toMatch(/^#[0-9a-f]{6}$/i);
+ expect(theme.variants?.dark?.accent).toMatch(/^#[0-9a-f]{6}$/i);
+
+ for (const mode of ["light", "dark"] as const) {
+ const colors = getThemeColorsForMode(theme, mode);
+ expect(colors).not.toBeNull();
+ expect(contrastRatio(colors!.text, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeGreaterThanOrEqual(4.5);
+ if (theme !== T3_CHAT_THEME) {
+ expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeLessThan(5.5);
+ expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeCloseTo(
+ mode === "dark" ? 5.082 : 4.705,
+ 1,
+ );
+ }
+ expect(contrastRatio(colors!.accentForeground, colors!.accent)).toBeGreaterThanOrEqual(
+ theme === T3_CHAT_THEME ? 3 : 4.5,
+ );
+ expect(
+ contrastRatio(colors!.toolbarControlForeground, colors!.toolbarControl),
+ ).toBeGreaterThanOrEqual(4.5);
+ expect(
+ contrastRatio(colors!.messageForeground, colors!.messageSurface),
+ ).toBeGreaterThanOrEqual(4.5);
+ expect(
+ contrastRatio(colors!.messageActionForeground, colors!.messageAction),
+ ).toBeGreaterThanOrEqual(theme === T3_CHAT_THEME ? 3 : 4.5);
+ }
+ }
+ });
+
+ it("rejects a variant that repeats the base appearance", () => {
+ expect(() =>
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: "Duplicate light",
+ appearance: "light",
+ colors: { canvas: "#f8fbff" },
+ variants: { light: { canvas: "#101827" } },
+ }),
+ ).toThrow('Theme variants must not repeat the base appearance "light".');
+ });
+
+ it("keeps a single-mode theme on its only palette", () => {
+ const theme = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: "midnight-slate",
+ name: "Midnight Slate",
+ appearance: "dark",
+ colors: { canvas: "#111827", messageAction: "#2563eb" },
+ });
+
+ expect(getThemeModes(theme)).toEqual(["dark"]);
+ expect(getThemeColorsForMode(theme, "dark")).toMatchObject({ canvas: "#111827" });
+ expect(getThemeColorsForMode(theme, "light")).toBeNull();
+ });
+
+ it("invalidates cached themes when another tab clears localStorage", () => {
+ let storedThemes: string | null = JSON.stringify([
+ {
+ id: "ocean-dusk",
+ label: "Ocean dusk",
+ appearance: "dark",
+ colors: { canvas: "#07152f" },
+ },
+ ]);
+ let storageHandler: ((event: StorageEvent) => void) | undefined;
+ vi.stubGlobal("window", {
+ addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
+ if (type === "storage") storageHandler = listener;
+ },
+ removeEventListener: vi.fn(),
+ localStorage: {
+ getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
+ },
+ });
+
+ invalidateCustomThemes();
+ expect(getCustomThemes()).toHaveLength(1);
+ const listener = vi.fn();
+ const unsubscribe = subscribeToCustomThemes(listener);
+
+ storedThemes = null;
+ storageHandler?.({ key: null } as StorageEvent);
+
+ expect(listener).toHaveBeenCalledTimes(1);
+ expect(getCustomThemes()).toEqual([]);
+ unsubscribe();
+ invalidateCustomThemes();
+ vi.unstubAllGlobals();
+ });
+
+ it("updates a personal theme without changing its id", () => {
+ const stored = new Map<string, string>();
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) => stored.get(key) ?? null,
+ setItem: (key: string, value: string) => stored.set(key, value),
+ },
+ });
+
+ invalidateCustomThemes();
+ const createdTheme = installCustomTheme(
+ parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: "aurora",
+ name: "Aurora",
+ appearance: "light",
+ colors: { canvas: "#f8fbff", accent: "#5b6cff" },
+ }),
+ );
+ const updatedTheme = updateCustomTheme({
+ ...createdTheme,
+ label: "Aurora Night",
+ colors: { ...createdTheme.colors, accent: "#7c3aed" },
+ });
+
+ expect(updatedTheme).toMatchObject({ id: "aurora", label: "Aurora Night" });
+ expect(getCustomThemes()).toEqual([updatedTheme]);
+ expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
+ id: "aurora",
+ label: "Aurora Night",
+ });
+
+ vi.unstubAllGlobals();
+ invalidateCustomThemes();
+ });
+});
+
+describe("stored theme preferences", () => {
+ it("lets a configured half unlock an appearance the base theme lacks", () => {
+ // Light-only base: without halves, dark requests fall back to light.
+ const lightOnly = parseThemeFile({
+ version: THEME_FILE_VERSION,
+ id: "paper",
+ name: "Paper",
+ appearance: "light",
+ colors: { canvas: "#f8fbff" },
+ });
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) =>
+ key === CUSTOM_THEMES_STORAGE_KEY ? JSON.stringify([lightOnly]) : null,
+ },
+ });
+ invalidateCustomThemes();
+ try {
+ expect(resolveThemeAppearance("paper", true, true)).toBe("light");
+ const halves = { dark: GROVE_THEME.id };
+ expect(resolveThemeAppearance("paper", true, true, undefined, halves)).toBe("dark");
+ expect(resolveThemeAppearance("paper", false, false, "dark", halves)).toBe("dark");
+ expect(resolveDesktopTheme("paper", true, undefined, halves)).toBe("system");
+ } finally {
+ vi.unstubAllGlobals();
+ invalidateCustomThemes();
+ }
+ });
+
+ it("resolves the legacy t3-chat-dark preference to dark T3 Chat", () => {
+ expect(getThemeDefinition("t3-chat-dark")).toBe(T3_CHAT_THEME);
+ expect(getThemePreferenceMode("t3-chat-dark")).toBe("dark");
+ expect(resolveThemeAppearance("t3-chat-dark", true, false)).toBe("dark");
+ expect(resolveDesktopTheme("t3-chat-dark", false)).toBe("dark");
+ expect(isKnownThemePreference("t3-chat-dark")).toBe(true);
+ });
+
+ it("resolves legacy t3-prefixed ids onto the renamed themes", () => {
+ for (const [legacy, theme] of [
+ ["t3-grove", GROVE_THEME],
+ ["t3-ocean", OCEAN_THEME],
+ ["t3-ember", EMBER_THEME],
+ ["t3-iris", IRIS_THEME],
+ ] as const) {
+ expect(getThemeDefinition(legacy)).toBe(theme);
+ expect(isKnownThemePreference(legacy)).toBe(true);
+ expect(canonicalThemePreference(legacy)).toBe(theme.id);
+ }
+ // The dark-variant alias keeps its raw form: it still carries a mode hint.
+ expect(canonicalThemePreference("t3-chat-dark")).toBe("t3-chat-dark");
+ // A stored mix that predates the rename resolves to the new ids.
+ expect(parseThemeHalves(JSON.stringify({ light: "t3-ocean", dark: "t3-grove" }))).toEqual({
+ light: OCEAN_THEME.id,
+ dark: GROVE_THEME.id,
+ });
+ });
+
+ it("recognizes only preferences the runtime can render", () => {
+ for (const preference of ["light", "dark", "system", T3_CHAT_THEME.id, GROVE_THEME.id]) {
+ expect(isKnownThemePreference(preference)).toBe(true);
+ }
+ expect(isKnownThemePreference(`${GROVE_THEME.id}:dark`)).toBe(false);
+ expect(isKnownThemePreference("missing-theme")).toBe(false);
+ });
+
+ it("keeps stored themes with unknown roles and drops invalid entries", () => {
+ vi.stubGlobal("window", {
+ localStorage: {
+ getItem: (key: string) =>
+ key === CUSTOM_THEMES_STORAGE_KEY
+ ? JSON.stringify([
+ {
+ id: "aurora",
+ label: "Aurora",
+ appearance: "light",
+ colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
+ variants: { light: { canvas: "#101827" } },
+ },
+ { id: "light", label: "Reserved", appearance: "light", colors: {} },
+ { id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
+ ])
+ : null,
+ },
+ });
+ invalidateCustomThemes();
+
+ const themes = getCustomThemes();
+ expect(themes).toHaveLength(1);
+ expect(themes[0]).toMatchObject({
+ id: "aurora",
+ colors: { canvas: "#f8fbff", accent: getDefaultThemeColors("light").accent },
+ });
+ // The variant shadowing the base appearance is dropped so the theme
+ // round-trips through parseThemeFile on export.
+ expect(getThemeModes(themes[0]!)).toEqual(["light"]);
+
+ vi.unstubAllGlobals();
+ invalidateCustomThemes();
+ });
+});
diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts
new file mode 100644
index 000000000..dafc5dbf4
--- /dev/null
+++ b/apps/web/src/themePalette.ts
@@ -0,0 +1,1767 @@
+import * as Schema from "effect/Schema";
+
+export const T3_CHAT_THEME_ID = "t3-chat" as const;
+export const T3_CHAT_THEME_LABEL = "T3 Chat";
+export const GROVE_THEME_ID = "grove" as const;
+export const GROVE_THEME_LABEL = "Grove";
+export const OCEAN_THEME_ID = "ocean" as const;
+export const OCEAN_THEME_LABEL = "Ocean";
+export const EMBER_THEME_ID = "ember" as const;
+export const EMBER_THEME_LABEL = "Ember";
+export const IRIS_THEME_ID = "iris" as const;
+export const IRIS_THEME_LABEL = "Iris";
+export const THEME_FILE_VERSION = 1 as const;
+export const CUSTOM_THEMES_STORAGE_KEY = "t3code:themes:v1";
+export const THEME_FOLLOW_SYSTEM_STORAGE_KEY = "t3code:theme-follow-system";
+export const THEME_APPEARANCE_MODE_STORAGE_KEY = "t3code:theme-appearance-mode";
+export const THEME_HALVES_STORAGE_KEY = "t3code:theme-halves:v1";
+
+const LEGACY_T3_CHAT_DARK_THEME_ID = "t3-chat-dark";
+
+export const ThemePreference = Schema.String;
+export type ThemePreference = typeof ThemePreference.Type;
+
+export const THEME_COLOR_ROLES = [
+ "canvas",
+ "chrome",
+ "toolbar",
+ "toolbarForeground",
+ "toolbarBorder",
+ "toolbarControl",
+ "toolbarControlForeground",
+ "toolbarControlHover",
+ "surface",
+ "surfaceRaised",
+ "surfaceOverlay",
+ "text",
+ "textMuted",
+ "border",
+ "input",
+ "focus",
+ "accent",
+ "accentForeground",
+ "secondary",
+ "secondaryForeground",
+ "muted",
+ "mutedForeground",
+ "placeholder",
+ "secondaryLabel",
+ "iconMuted",
+ "error",
+ "errorForeground",
+ "errorSurface",
+ "warning",
+ "warningForeground",
+ "warningSurface",
+ "update",
+ "updateForeground",
+ "updateSurface",
+ "accentSurface",
+ "accentSurfaceForeground",
+ "messageSurface",
+ "messageForeground",
+ "messageAction",
+ "messageActionForeground",
+ "messageActionHover",
+ "codeBackground",
+ "codeForeground",
+ "sidebar",
+ "sidebarForeground",
+ "sidebarMutedForeground",
+ "sidebarControlSurface",
+ "sidebarRowHover",
+ "sidebarRowActive",
+ "sidebarRowSelected",
+ "sidebarBorder",
+ "terminalBackground",
+ "terminalForeground",
+ "terminalCursor",
+ "terminalSelection",
+ "terminalScrollbar",
+ "terminalScrollbarHover",
+] as const;
+
+export type ThemeColorRole = (typeof THEME_COLOR_ROLES)[number];
+const THEME_COLOR_ROLE_SET: ReadonlySet<string> = new Set(THEME_COLOR_ROLES);
+export type ThemeAppearance = "light" | "dark";
+
+export type ThemeColors = Readonly<Record<ThemeColorRole, string>>;
+export type ThemeColorOverrides = Readonly<Partial<Record<ThemeColorRole, string>>>;
+export type ThemeVariants = Readonly<Partial<Record<ThemeAppearance, ThemeColors>>>;
+export type ThemeVariantOverrides = Readonly<Partial<Record<ThemeAppearance, ThemeColorOverrides>>>;
+export type ThemePreferenceMode = ThemeAppearance | "system";
+export type ThemeDefinition = Readonly<{
+ id: string;
+ label: string;
+ appearance: ThemeAppearance;
+ colors: ThemeColors;
+ variants?: ThemeVariants;
+ /** True when the palette was generated by the guided editor from its
+ * canvas and accent; such themes reopen in guided mode. */
+ managed?: boolean;
+}>;
+export type ThemeFile = Readonly<{
+ version: typeof THEME_FILE_VERSION;
+ id: string;
+ name: string;
+ appearance: ThemeAppearance;
+ colors: ThemeColorOverrides;
+ variants?: ThemeVariantOverrides;
+ managed?: boolean;
+}>;
+
+const RESERVED_THEME_IDS = new Set([
+ "system",
+ "light",
+ "dark",
+ T3_CHAT_THEME_ID,
+ GROVE_THEME_ID,
+ OCEAN_THEME_ID,
+ EMBER_THEME_ID,
+ IRIS_THEME_ID,
+ LEGACY_T3_CHAT_DARK_THEME_ID,
+ "t3-grove",
+ "t3-ocean",
+ "t3-ember",
+ "t3-iris",
+]);
+
+const customThemeListeners = new Set<() => void>();
+let customThemesSnapshot: ReadonlyArray<ThemeDefinition> | null = null;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function isThemeAppearance(value: unknown): value is ThemeAppearance {
+ return value === "light" || value === "dark";
+}
+
+export function isThemeColor(value: unknown): value is string {
+ return (
+ typeof value === "string" &&
+ /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value)
+ );
+}
+
+function isThemeId(value: unknown): value is string {
+ return typeof value === "string" && /^[a-z0-9](?:[a-z0-9-]{0,47})$/.test(value);
+}
+
+function isThemeLabel(value: unknown): value is string {
+ return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
+}
+
+function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
+ if (!isRecord(value)) return null;
+
+ const colors: Partial<Record<ThemeColorRole, string>> = {
+ ...getDefaultThemeColors(appearance),
+ };
+ // Tolerate unknown roles and malformed values so themes saved by other
+ // builds (for example one that adds a new role) keep their remaining colors.
+ for (const [role, color] of Object.entries(value)) {
+ if (THEME_COLOR_ROLE_SET.has(role) && isThemeColor(color)) {
+ colors[role as ThemeColorRole] = color;
+ }
+ }
+ return colors as ThemeColors;
+}
+
+function parseStoredThemeVariants(
+ value: unknown,
+ baseAppearance: ThemeAppearance,
+): ThemeVariants | null | undefined {
+ if (value === undefined) return undefined;
+ if (!isRecord(value)) return null;
+
+ const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
+ for (const [appearance, colors] of Object.entries(value)) {
+ if (!isThemeAppearance(appearance)) return null;
+ // A variant matching the base appearance would be shadowed by the base
+ // colors; drop it so the theme round-trips through parseThemeFile.
+ if (appearance === baseAppearance) continue;
+ const parsedColors = parseStoredThemeColors(colors, appearance);
+ if (!parsedColors) return null;
+ variants[appearance] = parsedColors;
+ }
+ return Object.keys(variants).length > 0 ? variants : undefined;
+}
+
+function parseStoredTheme(value: unknown): ThemeDefinition | null {
+ if (!isRecord(value)) return null;
+ if (!isThemeId(value.id) || RESERVED_THEME_IDS.has(value.id)) return null;
+ if (!isThemeLabel(value.label) || !isThemeAppearance(value.appearance)) return null;
+ const colors = parseStoredThemeColors(value.colors, value.appearance);
+ if (!colors) return null;
+ const variants = parseStoredThemeVariants(value.variants, value.appearance);
+ if (value.variants !== undefined && variants === null) return null;
+
+ return {
+ id: value.id,
+ label: value.label.trim(),
+ appearance: value.appearance,
+ colors,
+ ...(variants ? { variants } : {}),
+ ...(value.managed === true ? { managed: true } : {}),
+ };
+}
+
+function readCustomThemesFromStorage(): ReadonlyArray<ThemeDefinition> {
+ if (typeof window === "undefined") return [];
+
+ try {
+ const raw = window.localStorage.getItem(CUSTOM_THEMES_STORAGE_KEY);
+ if (!raw) return [];
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+
+ const themes: ThemeDefinition[] = [];
+ for (const value of parsed) {
+ const theme = parseStoredTheme(value);
+ if (theme && !themes.some((existing) => existing.id === theme.id)) {
+ themes.push(theme);
+ }
+ }
+ return themes;
+ } catch {
+ return [];
+ }
+}
+
+function notifyCustomThemeListeners() {
+ for (const listener of customThemeListeners) listener();
+}
+
+export function invalidateCustomThemes() {
+ customThemesSnapshot = null;
+ notifyCustomThemeListeners();
+}
+
+export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
+ if (customThemesSnapshot === null) {
+ customThemesSnapshot = readCustomThemesFromStorage();
+ }
+ return customThemesSnapshot;
+}
+
+export function subscribeToCustomThemes(listener: () => void): () => void {
+ customThemeListeners.add(listener);
+ if (typeof window === "undefined") {
+ return () => customThemeListeners.delete(listener);
+ }
+ const handleStorage = (event: StorageEvent) => {
+ if (event.key === CUSTOM_THEMES_STORAGE_KEY || event.key === null) {
+ invalidateCustomThemes();
+ }
+ };
+ window.addEventListener("storage", handleStorage);
+
+ return () => {
+ customThemeListeners.delete(listener);
+ window.removeEventListener("storage", handleStorage);
+ };
+}
+
+// Earlier builds shipped every maintainer theme under a t3- prefix; only the
+// genuinely T3-branded palette keeps it. Stored preferences and mixes with the
+// old ids stay readable through this alias table.
+const LEGACY_THEME_ID_ALIASES: Readonly<Record<string, string>> = {
+ [LEGACY_T3_CHAT_DARK_THEME_ID]: T3_CHAT_THEME_ID,
+ "t3-grove": GROVE_THEME_ID,
+ "t3-ocean": OCEAN_THEME_ID,
+ "t3-ember": EMBER_THEME_ID,
+ "t3-iris": IRIS_THEME_ID,
+};
+
+function normalizeThemeId(themeId: string): string {
+ return LEGACY_THEME_ID_ALIASES[themeId] ?? themeId;
+}
+
+/**
+ * Map a stored preference onto the id the runtime applies, so selection state
+ * matches the theme cards. The legacy dark-variant id stays as-is because it
+ * still carries the appearance hint getThemePreferenceMode reads.
+ */
+export function canonicalThemePreference(theme: string): string {
+ return theme === LEGACY_T3_CHAT_DARK_THEME_ID ? theme : normalizeThemeId(theme);
+}
+
+function themeIdFromPreference(theme: ThemePreference): string {
+ return normalizeThemeId(theme);
+}
+
+// Older builds stored the dark T3 Chat palette as a separate theme. Keep
+// those preferences readable while mapping them to the dark variant.
+function legacyThemeMode(theme: ThemePreference): ThemeAppearance | null {
+ return theme === LEGACY_T3_CHAT_DARK_THEME_ID ? "dark" : null;
+}
+
+/**
+ * Maintainer palettes use product color roles rather than Tailwind or component
+ * names so the same definitions can feed other clients and native surfaces.
+ */
+// Measured from the live t3.chat default theme. Translucent chat surfaces are
+// flattened over --chat-background so this opaque palette reproduces the
+// pixels users see after T3 Chat's blur and noise layers are composited.
+const T3_CHAT_LIGHT_COLORS: ThemeColors = {
+ canvas: "#fdf7fd",
+ // T3 Code's workspace header belongs to the chat panel, so keep it seamless
+ // with the light chat canvas rather than mapping it to T3 Chat's outer shell.
+ chrome: "#fdf7fd",
+ toolbar: "#fdf7fd",
+ toolbarForeground: "#501854",
+ toolbarBorder: "#efbdeb",
+ // T3 Chat's light chrome controls sit on its pale gradient-noise surface,
+ // not the substantially darker solid accent token.
+ toolbarControl: "#f3e6f5",
+ toolbarControlForeground: "#501854",
+ toolbarControlHover: "#eccfe3",
+ surface: "#faf3fb",
+ surfaceRaised: "#fdfafd",
+ surfaceOverlay: "#ffffff",
+ text: "#501854",
+ textMuted: "#ac1668",
+ border: "#eee1ed",
+ input: "#e7c1dc",
+ focus: "#db2777",
+ accent: "#e33f86",
+ accentForeground: "#ffffff",
+ secondary: "#f1c4e6",
+ secondaryForeground: "#77347c",
+ muted: "#eaa7cb",
+ mutedForeground: "#ac1668",
+ placeholder: "#ad83b0",
+ secondaryLabel: "#ac1668",
+ iconMuted: "#ac1668",
+ error: "#f7086c",
+ errorForeground: "#9d174d",
+ errorSurface: "#fde4f1",
+ warning: "#f59e0b",
+ warningForeground: "#b45309",
+ warningSurface: "#fcf0ea",
+ update: "#e33f86",
+ updateForeground: "#ac1668",
+ updateSurface: "#fadfef",
+ accentSurface: "#f3e6f5",
+ accentSurfaceForeground: "#454554",
+ messageSurface: "#f7def2",
+ messageForeground: "#492c61",
+ messageAction: "#e33f86",
+ messageActionForeground: "#ffffff",
+ messageActionHover: "#d56698",
+ // T3 Chat uses a light lavender code surface in light mode. Keeping the
+ // dark plum pair here also leaked the dark palette into T3 Code's diffs.
+ codeBackground: "#f5ecf9",
+ codeForeground: "#673c8b",
+ // The live sidebar is transparent over T3 Chat's outer shell. Use that
+ // rendered shell color rather than its unused, darker sidebar token.
+ sidebar: "#f2e1f4",
+ sidebarForeground: "#454554",
+ sidebarMutedForeground: "#ac1668",
+ sidebarControlSurface: "#f8f8f7",
+ sidebarRowHover: "#f8f8f7",
+ sidebarRowActive: "#f8f8f7",
+ sidebarRowSelected: "#f8f8f7",
+ sidebarBorder: "#eceae9",
+ terminalBackground: "#fdf7fd",
+ terminalForeground: "#501854",
+ terminalCursor: "#db2777",
+ terminalSelection: "#f1c4e6",
+ terminalScrollbar: "#e7c1dc",
+ terminalScrollbarHover: "#eaa7cb",
+};
+
+const T3_CHAT_DARK_COLORS: ThemeColors = {
+ canvas: "#1f1a24",
+ // T3 Code's workspace header belongs to the chat panel, so keep it seamless
+ // with the canvas rather than mapping it to T3 Chat's outer shell.
+ chrome: "#1f1a24",
+ toolbar: "#1f1a24",
+ toolbarForeground: "#f9f8fb",
+ toolbarBorder: "#27242c",
+ toolbarControl: "#362d3d",
+ toolbarControlForeground: "#d4c7e1",
+ toolbarControlHover: "#463753",
+ // Cards and panels stay in T3 Chat's plum surface family. Near-black here
+ // made the right-panel surface picker look unrelated to the chat canvas.
+ surface: "#29232d",
+ // Pre-composited for the composer's 80% glass layer; this resolves to the
+ // measured #29232d input fill over the canvas.
+ surfaceRaised: "#2c2631",
+ surfaceOverlay: "#100a0e",
+ text: "#f9f8fb",
+ textMuted: "#e7d0dd",
+ border: "#27242c",
+ input: "#302029",
+ focus: "#db2777",
+ accent: "#a3004c",
+ accentForeground: "#fbd0e8",
+ secondary: "#362d3d",
+ secondaryForeground: "#d4c7e1",
+ muted: "#423a45",
+ mutedForeground: "#e7d0dd",
+ placeholder: "#8f8699",
+ secondaryLabel: "#e7d0dd",
+ iconMuted: "#d4c7e1",
+ error: "#9d174d",
+ errorForeground: "#fbd0e8",
+ errorSurface: "#331a2b",
+ warning: "#f59e0b",
+ warningForeground: "#fbbf24",
+ warningSurface: "#412f20",
+ update: "#a3004c",
+ updateForeground: "#fbd0e8",
+ updateSurface: "#37152b",
+ accentSurface: "#463753",
+ accentSurfaceForeground: "#f8f1f5",
+ messageSurface: "#2b2431",
+ messageForeground: "#f2ebfa",
+ messageAction: "#a3004c",
+ messageActionForeground: "#fbd0e8",
+ messageActionHover: "#a2004c",
+ // Diffs and file previews are full workspace surfaces in T3 Code. Keep them
+ // continuous with the themed canvas instead of dropping to near-black.
+ codeBackground: "#1f1a24",
+ codeForeground: "#d8c3ef",
+ // The live sidebar starts from #131314, then gains its hue from a pink
+ // gradient/noise stack. This pre-grain base lands on the same #1a131a
+ // visible shell color after our surface-grain layer is composited.
+ sidebar: "#171018",
+ sidebarForeground: "#f4f4f5",
+ sidebarMutedForeground: "#e7d0dd",
+ sidebarControlSurface: "#261922",
+ sidebarRowHover: "#261922",
+ sidebarRowActive: "#261922",
+ sidebarRowSelected: "#261922",
+ // T3 Chat draws the chat panel edge in this muted pink. The resize rail uses
+ // the same role on hover, so it stays pink instead of falling back to black.
+ sidebarBorder: "#322028",
+ terminalBackground: "#1f1a24",
+ terminalForeground: "#f9f8fb",
+ terminalCursor: "#db2777",
+ terminalSelection: "#362d3d",
+ terminalScrollbar: "#302029",
+ terminalScrollbarHover: "#423a45",
+};
+
+/**
+ * The palette T3 Code wears with no theme installed, captured from the app's
+ * stock tokens (index.css) so a draft seeded from the default look paints the
+ * pixels the user is already seeing. Alpha-bearing tokens are flattened over
+ * their real backdrops (canvas, or the sidebar for its rows) because theme
+ * colors must be opaque hex.
+ */
+const T3_CODE_LIGHT_THEME_COLORS: ThemeColors = {
+ canvas: "#fcfcfc",
+ chrome: "#fcfcfc",
+ toolbar: "#fcfcfc",
+ toolbarForeground: "#27272a",
+ toolbarBorder: "#e4e4e7",
+ toolbarControl: "#ffffff",
+ toolbarControlForeground: "#27272a",
+ toolbarControlHover: "#f4f4f5",
+ surface: "#ffffff",
+ surfaceRaised: "#fcfcfc",
+ surfaceOverlay: "#ffffff",
+ text: "#27272a",
+ textMuted: "#71717b",
+ border: "#e4e4e7",
+ input: "#d4d4d8",
+ focus: "#1b4ed8",
+ accent: "#1b4ed8",
+ accentForeground: "#ffffff",
+ secondary: "#fafafa",
+ secondaryForeground: "#27272a",
+ muted: "#fafafa",
+ mutedForeground: "#71717b",
+ placeholder: "#71717b",
+ secondaryLabel: "#71717b",
+ iconMuted: "#71717b",
+ error: "#fb2c36",
+ errorForeground: "#c10007",
+ errorSurface: "#fcebec",
+ warning: "#fe9a00",
+ warningForeground: "#bb4d00",
+ warningSurface: "#fcf4e8",
+ update: "#1b4ed8",
+ updateForeground: "#1b4ed8",
+ updateSurface: "#e0e6f7",
+ accentSurface: "#f4f4f5",
+ accentSurfaceForeground: "#18181b",
+ messageSurface: "#f4f4f5",
+ messageForeground: "#27272a",
+ messageAction: "#1b4ed8",
+ messageActionForeground: "#ffffff",
+ messageActionHover: "#3160db",
+ codeBackground: "#ffffff",
+ codeForeground: "#27272a",
+ sidebar: "#fafafa",
+ sidebarForeground: "#27272a",
+ sidebarMutedForeground: "#71717b",
+ sidebarControlSurface: "#f4f4f5",
+ sidebarRowHover: "#fcfcfc",
+ sidebarRowActive: "#ffffff",
+ sidebarRowSelected: "#ffffff",
+ sidebarBorder: "#e4e4e7",
+ terminalBackground: "#fcfcfc",
+ terminalForeground: "#27272a",
+ terminalCursor: "#26384e",
+ terminalSelection: "#d0d6dd",
+ terminalScrollbar: "#d6d6d6",
+ terminalScrollbarHover: "#bdbdbd",
+};
+
+const T3_CODE_DARK_THEME_COLORS: ThemeColors = {
+ canvas: "#0a0a0a",
+ chrome: "#0a0a0a",
+ toolbar: "#0a0a0a",
+ toolbarForeground: "#f5f5f5",
+ toolbarBorder: "#191919",
+ toolbarControl: "#191919",
+ toolbarControlForeground: "#f5f5f5",
+ toolbarControlHover: "#141414",
+ surface: "#111111",
+ surfaceRaised: "#141414",
+ surfaceOverlay: "#191919",
+ text: "#f5f5f5",
+ textMuted: "#818181",
+ border: "#191919",
+ input: "#1e1e1e",
+ focus: "#366ffb",
+ accent: "#366ffb",
+ accentForeground: "#ffffff",
+ secondary: "#141414",
+ secondaryForeground: "#f5f5f5",
+ muted: "#141414",
+ mutedForeground: "#818181",
+ placeholder: "#818181",
+ secondaryLabel: "#818181",
+ iconMuted: "#818181",
+ error: "#fb414a",
+ errorForeground: "#ff6467",
+ errorSurface: "#301214",
+ warning: "#fe9a00",
+ warningForeground: "#ffb900",
+ warningSurface: "#312108",
+ update: "#366ffb",
+ updateForeground: "#366ffb",
+ updateSurface: "#121c35",
+ accentSurface: "#141414",
+ accentSurfaceForeground: "#f5f5f5",
+ messageSurface: "#141414",
+ messageForeground: "#f5f5f5",
+ messageAction: "#366ffb",
+ messageActionForeground: "#ffffff",
+ messageActionHover: "#3265e3",
+ codeBackground: "#111111",
+ codeForeground: "#f5f5f5",
+ sidebar: "#000000",
+ sidebarForeground: "#f1f3f7",
+ sidebarMutedForeground: "#a3a3a3",
+ sidebarControlSurface: "#0a0a0a",
+ sidebarRowHover: "#131313",
+ sidebarRowActive: "#1a1b1b",
+ sidebarRowSelected: "#111111",
+ sidebarBorder: "#141414",
+ terminalBackground: "#0a0a0a",
+ terminalForeground: "#f5f5f5",
+ terminalCursor: "#b4cbff",
+ terminalSelection: "#343a47",
+ terminalScrollbar: "#222222",
+ terminalScrollbarHover: "#363636",
+};
+
+/**
+ * The standard T3 Code look as a theme palette, for seeding a new theme when
+ * no theme is installed. Distinct from {@link getDefaultThemeColors}, which
+ * carries the flagship T3 Chat palette used to fill roles omitted by theme
+ * files.
+ */
+export function getStandardThemeColors(appearance: ThemeAppearance): ThemeColors {
+ return appearance === "dark" ? T3_CODE_DARK_THEME_COLORS : T3_CODE_LIGHT_THEME_COLORS;
+}
+
+type ThemeRgbColor = {
+ r: number;
+ g: number;
+ b: number;
+};
+
+type ThemeHslColor = {
+ h: number;
+ s: number;
+ l: number;
+};
+
+const THEME_LIGHT_FOREGROUND: ThemeRgbColor = { r: 255, g: 250, b: 255 };
+const THEME_DARK_FOREGROUND: ThemeRgbColor = { r: 36, g: 21, b: 35 };
+const THEME_WHITE_FOREGROUND: ThemeRgbColor = { r: 255, g: 255, b: 255 };
+const THEME_BLACK_FOREGROUND: ThemeRgbColor = { r: 0, g: 0, b: 0 };
+
+function parseThemeRgbColor(value: string, fallback: ThemeRgbColor): ThemeRgbColor {
+ const match = value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
+ if (!match) return fallback;
+
+ const raw = match[1];
+ if (!raw) return fallback;
+ const hex =
+ raw.length <= 4
+ ? raw
+ .slice(0, 3)
+ .split("")
+ .map((part) => part.repeat(2))
+ .join("")
+ : raw.slice(0, 6);
+ if (hex.length !== 6) return fallback;
+
+ return {
+ r: Number.parseInt(hex.slice(0, 2), 16),
+ g: Number.parseInt(hex.slice(2, 4), 16),
+ b: Number.parseInt(hex.slice(4, 6), 16),
+ };
+}
+
+function themeRgbToHexColor(color: ThemeRgbColor): string {
+ return `#${[color.r, color.g, color.b]
+ .map((channel) =>
+ Math.round(Math.min(255, Math.max(0, channel)))
+ .toString(16)
+ .padStart(2, "0"),
+ )
+ .join("")}`;
+}
+
+function themeRgbToHsl(color: ThemeRgbColor): ThemeHslColor {
+ const red = color.r / 255;
+ const green = color.g / 255;
+ const blue = color.b / 255;
+ const max = Math.max(red, green, blue);
+ const min = Math.min(red, green, blue);
+ const delta = max - min;
+ const lightness = (max + min) / 2;
+
+ if (delta === 0) return { h: 0, s: 0, l: lightness };
+
+ const saturation = delta / (1 - Math.abs(2 * lightness - 1));
+ let hue = 0;
+ if (max === red) hue = ((green - blue) / delta) % 6;
+ else if (max === green) hue = (blue - red) / delta + 2;
+ else hue = (red - green) / delta + 4;
+
+ return { h: (hue * 60 + 360) % 360, s: saturation, l: lightness };
+}
+
+function themeHslToRgb(color: ThemeHslColor): ThemeRgbColor {
+ const hue = ((color.h % 360) + 360) % 360;
+ const chroma = (1 - Math.abs(2 * color.l - 1)) * color.s;
+ const hueSector = hue / 60;
+ const secondary = chroma * (1 - Math.abs((hueSector % 2) - 1));
+ const match = color.l - chroma / 2;
+ const [red, green, blue] =
+ hueSector < 1
+ ? [chroma, secondary, 0]
+ : hueSector < 2
+ ? [secondary, chroma, 0]
+ : hueSector < 3
+ ? [0, chroma, secondary]
+ : hueSector < 4
+ ? [0, secondary, chroma]
+ : hueSector < 5
+ ? [secondary, 0, chroma]
+ : [chroma, 0, secondary];
+
+ return { r: (red + match) * 255, g: (green + match) * 255, b: (blue + match) * 255 };
+}
+
+function mixThemeRgbColors(
+ base: ThemeRgbColor,
+ overlay: ThemeRgbColor,
+ amount: number,
+): ThemeRgbColor {
+ return {
+ r: base.r + (overlay.r - base.r) * amount,
+ g: base.g + (overlay.g - base.g) * amount,
+ b: base.b + (overlay.b - base.b) * amount,
+ };
+}
+
+function themeRelativeLuminance(color: ThemeRgbColor): number {
+ const linearize = (channel: number) => {
+ const normalized = channel / 255;
+ return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
+ };
+
+ return 0.2126 * linearize(color.r) + 0.7152 * linearize(color.g) + 0.0722 * linearize(color.b);
+}
+
+// ---------------------------------------------------------------------------
+// Vivid palette engine: perceptual (OKLCH) derivation for user-created themes.
+// Built-in themes keep the legacy derivation so their shipped palettes and the
+// boot splash copies stay byte-identical.
+
+type ThemeOklch = { L: number; C: number; h: number };
+
+function srgbChannelToLinear(channel: number): number {
+ const c = channel / 255;
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+}
+
+function linearChannelToSrgb(channel: number): number {
+ const c = channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
+ return Math.round(Math.min(1, Math.max(0, c)) * 255);
+}
+
+function themeRgbToOklch(color: ThemeRgbColor): ThemeOklch {
+ const r = srgbChannelToLinear(color.r);
+ const g = srgbChannelToLinear(color.g);
+ const b = srgbChannelToLinear(color.b);
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
+ const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
+ const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
+ const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
+ return { L, C: Math.hypot(a, bb), h: (Math.atan2(bb, a) * 180) / Math.PI };
+}
+
+function oklchToRgbUnclamped({ L, C, h }: ThemeOklch): { r: number; g: number; b: number } {
+ const hr = (h * Math.PI) / 180;
+ const a = C * Math.cos(hr);
+ const bb = C * Math.sin(hr);
+ const l = (L + 0.3963377774 * a + 0.2158037573 * bb) ** 3;
+ const m = (L - 0.1055613458 * a - 0.0638541728 * bb) ** 3;
+ const s = (L - 0.0894841775 * a - 1.291485548 * bb) ** 3;
+ return {
+ r: 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
+ g: -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
+ b: -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
+ };
+}
+
+/** Convert to sRGB, walking chroma toward grey until the color is in gamut. */
+function themeOklchToRgb(color: ThemeOklch): ThemeRgbColor {
+ let { C } = color;
+ for (let step = 0; step < 12; step += 1) {
+ const linear = oklchToRgbUnclamped({ ...color, C });
+ const inGamut = [linear.r, linear.g, linear.b].every(
+ (channel) => channel >= -0.0001 && channel <= 1.0001,
+ );
+ if (inGamut) {
+ return {
+ r: linearChannelToSrgb(linear.r),
+ g: linearChannelToSrgb(linear.g),
+ b: linearChannelToSrgb(linear.b),
+ };
+ }
+ C *= 0.82;
+ }
+ const linear = oklchToRgbUnclamped({ ...color, C: 0 });
+ return {
+ r: linearChannelToSrgb(linear.r),
+ g: linearChannelToSrgb(linear.g),
+ b: linearChannelToSrgb(linear.b),
+ };
+}
+
+/** Binary-search the lightness that reaches the contrast target against a background. */
+function solveOklchLightness(
+ base: ThemeOklch,
+ against: ThemeRgbColor,
+ minContrast: number,
+ direction: "lighter" | "darker",
+): ThemeOklch {
+ let low = direction === "lighter" ? base.L : 0;
+ let high = direction === "lighter" ? 1 : base.L;
+ let candidate = { ...base };
+ if (themeContrastRatio(themeOklchToRgb(candidate), against) >= minContrast) return candidate;
+ for (let step = 0; step < 18; step += 1) {
+ const mid = (low + high) / 2;
+ candidate = { ...base, L: mid };
+ const contrast = themeContrastRatio(themeOklchToRgb(candidate), against);
+ if (contrast >= minContrast) {
+ if (direction === "lighter") high = mid;
+ else low = mid;
+ } else {
+ if (direction === "lighter") low = mid;
+ else high = mid;
+ }
+ }
+ return { ...base, L: direction === "lighter" ? high : low };
+}
+
+/**
+ * The status colors T3 Code shows without a theme, read from the app's own
+ * tokens (red-500 / amber-500 families). Generated palettes fall back to
+ * these instead of the flagship theme's, so an imported or created theme
+ * never inherits a brand tint on destructive buttons and warnings.
+ */
+const STANDARD_STATUS_COLORS = {
+ light: {
+ error: "#fb2c36",
+ errorForeground: "#c10007",
+ warning: "#fe9a00",
+ warningForeground: "#bb4d00",
+ },
+ dark: {
+ error: "#fb414a",
+ errorForeground: "#ff6467",
+ warning: "#fe9a00",
+ warningForeground: "#ffb900",
+ },
+} as const;
+
+/**
+ * Status surfaces are the standard color laid over the theme's own canvas
+ * (the unthemed app uses 8% in light and 16% in dark), so alerts still sit on
+ * the palette while the signal color stays standard.
+ */
+function standardStatusColors(canvas: ThemeRgbColor): {
+ error: string;
+ errorForeground: string;
+ errorSurface: string;
+ warning: string;
+ warningForeground: string;
+ warningSurface: string;
+} {
+ // Keyed off the canvas rather than the appearance slot: a dark canvas saved
+ // as a light theme still needs the dark pair, or the alert foreground lands
+ // on a dark surface unreadable.
+ const appearance: ThemeAppearance = themeRelativeLuminance(canvas) < 0.179 ? "dark" : "light";
+ const standard = STANDARD_STATUS_COLORS[appearance];
+ const surfaceMix = appearance === "dark" ? 0.16 : 0.08;
+ const surfaceOf = (value: string) =>
+ mixThemeRgbColors(canvas, parseThemeRgbColor(value, canvas), surfaceMix);
+ // The standard foregrounds are tuned against the unthemed canvas; on a
+ // tinted one they can fall just short, so lightness is nudged until the
+ // pair clears 4.5 while the hue stays standard.
+ const readableOn = (foreground: string, surface: ThemeRgbColor) =>
+ themeRgbToHexColor(
+ themeOklchToRgb(
+ solveOklchLightness(
+ themeRgbToOklch(parseThemeRgbColor(foreground, canvas)),
+ surface,
+ // A hair above 4.5: the solve happens in OKLCH and the result is
+ // quantized to 8-bit hex, which can shave the last hundredth off.
+ 4.6,
+ appearance === "dark" ? "lighter" : "darker",
+ ),
+ ),
+ );
+ const errorSurface = surfaceOf(standard.error);
+ const warningSurface = surfaceOf(standard.warning);
+ return {
+ ...standard,
+ errorForeground: readableOn(standard.errorForeground, errorSurface),
+ errorSurface: themeRgbToHexColor(errorSurface),
+ warningForeground: readableOn(standard.warningForeground, warningSurface),
+ warningSurface: themeRgbToHexColor(warningSurface),
+ };
+}
+
+/**
+ * Derive a full palette from two exact seed colors, in OKLCH. Surfaces climb a
+ * perceptually even lightness ramp that carries the accent hue at low chroma,
+ * a companion action color is rotated off the accent, and every foreground is
+ * contrast-solved against its own surface.
+ */
+export function createVividThemeColors(
+ appearance: ThemeAppearance,
+ backgroundValue: string,
+ accentValue: string,
+): ThemeColors {
+ const defaults = getDefaultThemeColors(appearance);
+ const canvasRgb = parseThemeRgbColor(
+ backgroundValue,
+ appearance === "dark" ? { r: 24, g: 15, b: 27 } : { r: 250, g: 245, b: 250 },
+ );
+ const accentRgb = parseThemeRgbColor(accentValue, { r: 168, g: 67, b: 112 });
+ const canvas = themeRgbToOklch(canvasRgb);
+ const accent = themeRgbToOklch(accentRgb);
+ // The ramp and every contrast search follow the canvas the user actually
+ // picked, not the appearance slot, so a dark canvas saved as a light theme
+ // still gets light text and raised surfaces. 0.179 is the relative
+ // luminance where white and black text have equal contrast headroom.
+ const dark = themeRelativeLuminance(canvasRgb) < 0.179;
+ const hue = accent.C < 0.02 ? canvas.h : accent.h;
+ const tintC = Math.min(0.045, Math.max(0.008, accent.C * 0.22));
+ const step = dark ? 1 : -1;
+
+ const surfaceAt = (deltaL: number, chroma = tintC): ThemeOklch => ({
+ L: Math.min(0.98, Math.max(0.05, canvas.L + step * deltaL)),
+ C: chroma,
+ h: hue,
+ });
+ const hex = (color: ThemeOklch) => themeRgbToHexColor(themeOklchToRgb(color));
+
+ // Text carries a whisper of the accent hue instead of falling back to a
+ // fixed foreground, and is solved to WCAG AAA against the canvas.
+ const textBase: ThemeOklch = {
+ L: dark ? 0.95 : 0.2,
+ C: Math.min(0.035, accent.C * 0.25),
+ h: hue,
+ };
+ const text = solveOklchLightness(textBase, canvasRgb, 7, dark ? "lighter" : "darker");
+ const textRgb = themeOklchToRgb(text);
+ const textMutedRgb = standardMutedThemeText(canvasRgb, textRgb);
+
+ // The companion action rotates off the accent so a two-color theme still
+ // gets the dual-voice character of the hand-tuned palettes.
+ const action: ThemeOklch = {
+ L: Math.min(0.85, Math.max(0.35, accent.L + (dark ? 0.06 : -0.02))),
+ C: Math.max(accent.C * 0.9, 0.06),
+ h: (hue + 50) % 360,
+ };
+ const actionRgb = themeOklchToRgb(action);
+ const actionForeground = readableThemeForeground(actionRgb);
+ const accentForeground = readableThemeForeground(accentRgb);
+
+ const sidebar = surfaceAt(0.045, tintC * 1.4);
+ const sidebarRgb = themeOklchToRgb(sidebar);
+ const surface = surfaceAt(0.015);
+ const surfaceRaised = surfaceAt(0.05);
+ const surfaceOverlay = surfaceAt(0.075);
+ const border = surfaceAt(dark ? 0.16 : 0.12, Math.min(0.07, accent.C * 0.35));
+ const input = surfaceAt(dark ? 0.21 : 0.16, Math.min(0.08, accent.C * 0.4));
+ const secondary = surfaceAt(dark ? 0.1 : 0.06, Math.min(0.09, accent.C * 0.5));
+ const secondaryRgb = themeOklchToRgb(secondary);
+ const muted = surfaceAt(dark ? 0.06 : 0.04, Math.min(0.06, accent.C * 0.35));
+ const accentSurface = surfaceAt(dark ? 0.13 : 0.08, Math.min(0.11, accent.C * 0.55));
+ const accentSurfaceRgb = themeOklchToRgb(accentSurface);
+ const messageSurface = surfaceAt(dark ? 0.16 : 0.1, Math.min(0.13, accent.C * 0.6));
+ const messageSurfaceRgb = themeOklchToRgb(messageSurface);
+ const codeBackground = surfaceAt(0.035, tintC * 0.8);
+ const updateSurface = surfaceAt(dark ? 0.14 : 0.09, Math.min(0.12, accent.C * 0.55));
+
+ const foregroundOn = (surfaceRgb: ThemeRgbColor): string =>
+ themeRgbToHexColor(
+ themeOklchToRgb(solveOklchLightness(textBase, surfaceRgb, 4.6, dark ? "lighter" : "darker")),
+ );
+
+ const actionHover: ThemeOklch = { ...action, L: action.L + (dark ? 0.06 : -0.06) };
+
+ return {
+ ...defaults,
+ ...standardStatusColors(canvasRgb),
+ canvas: themeRgbToHexColor(canvasRgb),
+ // The top bar shares the canvas so the main panel reads as one surface.
+ chrome: themeRgbToHexColor(canvasRgb),
+ toolbar: themeRgbToHexColor(canvasRgb),
+ toolbarForeground: themeRgbToHexColor(textRgb),
+ toolbarBorder: hex(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.08, accent.C * 0.4))),
+ toolbarControl: hex(surfaceAt(dark ? 0.09 : 0.05, tintC * 1.3)),
+ toolbarControlForeground: themeRgbToHexColor(textRgb),
+ toolbarControlHover: hex(surfaceAt(dark ? 0.14 : 0.09, tintC * 1.6)),
+ surface: hex(surface),
+ surfaceRaised: hex(surfaceRaised),
+ surfaceOverlay: hex(surfaceOverlay),
+ text: themeRgbToHexColor(textRgb),
+ textMuted: themeRgbToHexColor(textMutedRgb),
+ border: hex(border),
+ input: hex(input),
+ focus: themeRgbToHexColor(accentRgb),
+ accent: themeRgbToHexColor(accentRgb),
+ accentForeground: themeRgbToHexColor(accentForeground),
+ secondary: hex(secondary),
+ secondaryForeground: foregroundOn(secondaryRgb),
+ muted: hex(muted),
+ mutedForeground: themeRgbToHexColor(textMutedRgb),
+ placeholder: themeRgbToHexColor(textMutedRgb),
+ secondaryLabel: themeRgbToHexColor(textMutedRgb),
+ iconMuted: themeRgbToHexColor(textMutedRgb),
+ update: themeRgbToHexColor(accentRgb),
+ updateForeground: foregroundOn(themeOklchToRgb(updateSurface)),
+ updateSurface: hex(updateSurface),
+ accentSurface: hex(accentSurface),
+ accentSurfaceForeground: foregroundOn(accentSurfaceRgb),
+ messageSurface: hex(messageSurface),
+ messageForeground: foregroundOn(messageSurfaceRgb),
+ messageAction: themeRgbToHexColor(actionRgb),
+ messageActionForeground: themeRgbToHexColor(actionForeground),
+ messageActionHover: hex(actionHover),
+ codeBackground: hex(codeBackground),
+ codeForeground: themeRgbToHexColor(textRgb),
+ sidebar: hex(sidebar),
+ sidebarForeground: foregroundOn(sidebarRgb),
+ sidebarMutedForeground: themeRgbToHexColor(standardMutedThemeText(sidebarRgb, textRgb)),
+ sidebarControlSurface: hex(surfaceAt(dark ? 0.1 : 0.07, tintC * 1.5)),
+ sidebarRowHover: hex(surfaceAt(dark ? 0.08 : 0.06, Math.min(0.08, accent.C * 0.45))),
+ sidebarRowActive: hex(surfaceAt(dark ? 0.12 : 0.09, Math.min(0.1, accent.C * 0.55))),
+ sidebarRowSelected: hex(surfaceAt(dark ? 0.14 : 0.1, Math.min(0.11, accent.C * 0.6))),
+ sidebarBorder: hex(surfaceAt(dark ? 0.17 : 0.12, Math.min(0.08, accent.C * 0.4))),
+ terminalBackground: themeRgbToHexColor(canvasRgb),
+ terminalForeground: themeRgbToHexColor(textRgb),
+ terminalCursor: themeRgbToHexColor(accentRgb),
+ terminalSelection: hex(surfaceAt(dark ? 0.18 : 0.12, Math.min(0.12, accent.C * 0.55))),
+ terminalScrollbar: hex(surfaceAt(dark ? 0.22 : 0.16, tintC)),
+ terminalScrollbarHover: hex(surfaceAt(dark ? 0.3 : 0.22, tintC)),
+ };
+}
+
+function themeContrastRatio(first: ThemeRgbColor, second: ThemeRgbColor): number {
+ const firstLuminance = themeRelativeLuminance(first);
+ const secondLuminance = themeRelativeLuminance(second);
+ const lighter = Math.max(firstLuminance, secondLuminance);
+ const darker = Math.min(firstLuminance, secondLuminance);
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+function readableThemeForeground(background: ThemeRgbColor): ThemeRgbColor {
+ const lightContrast = themeContrastRatio(background, THEME_LIGHT_FOREGROUND);
+ const darkContrast = themeContrastRatio(background, THEME_DARK_FOREGROUND);
+ if (Math.max(lightContrast, darkContrast) >= 4.5) {
+ return lightContrast >= darkContrast ? THEME_LIGHT_FOREGROUND : THEME_DARK_FOREGROUND;
+ }
+
+ return themeContrastRatio(background, THEME_WHITE_FOREGROUND) >=
+ themeContrastRatio(background, THEME_BLACK_FOREGROUND)
+ ? THEME_WHITE_FOREGROUND
+ : THEME_BLACK_FOREGROUND;
+}
+
+function readableThemeText(
+ background: ThemeRgbColor,
+ foreground: ThemeRgbColor,
+ amount: number,
+ minimumRatio: number,
+): ThemeRgbColor {
+ const softened = mixThemeRgbColors(foreground, background, amount);
+ if (themeContrastRatio(softened, background) >= minimumRatio) return softened;
+
+ // Find the quietest point between the requested mix and the primary
+ // foreground that still clears the contrast floor. Returning the primary
+ // foreground here made secondary labels jump from slightly too dim to full
+ // brightness, which is especially conspicuous in dark custom themes.
+ let readable = foreground;
+ let lowerAmount = 0;
+ let upperAmount = amount;
+ for (let index = 0; index < 12; index += 1) {
+ const candidateAmount = (lowerAmount + upperAmount) / 2;
+ const candidate = mixThemeRgbColors(foreground, background, candidateAmount);
+ if (themeContrastRatio(candidate, background) >= minimumRatio) {
+ readable = candidate;
+ lowerAmount = candidateAmount;
+ } else {
+ upperAmount = candidateAmount;
+ }
+ }
+ return readable;
+}
+
+// Match the perceived strength of the stock palettes rather than choosing an
+// arbitrary foreground mix. These are the measured contrast ratios of zinc-500
+// on the standard light canvas and #818181 on the standard dark canvas.
+const STANDARD_LIGHT_MUTED_CONTRAST = 4.705;
+const STANDARD_DARK_MUTED_CONTRAST = 5.082;
+
+function standardMutedThemeText(
+ background: ThemeRgbColor,
+ foreground: ThemeRgbColor,
+): ThemeRgbColor {
+ const target =
+ themeRelativeLuminance(background) < 0.179
+ ? STANDARD_DARK_MUTED_CONTRAST
+ : STANDARD_LIGHT_MUTED_CONTRAST;
+ return readableThemeText(background, foreground, 1, target);
+}
+
+function managedThemeBackground(value: string, appearance: ThemeAppearance): ThemeRgbColor {
+ const selected = parseThemeRgbColor(
+ value,
+ appearance === "dark" ? { r: 24, g: 15, b: 27 } : { r: 250, g: 245, b: 250 },
+ );
+ const hsl = themeRgbToHsl(selected);
+ return themeHslToRgb({
+ h: hsl.h,
+ // A background tint should support the selected mode, not turn the whole
+ // app into a high-saturation surface.
+ s: Math.min(hsl.s, appearance === "dark" ? 0.3 : 0.2),
+ l:
+ appearance === "dark"
+ ? Math.min(0.13, Math.max(0.07, hsl.l))
+ : Math.min(0.985, Math.max(0.94, hsl.l)),
+ });
+}
+
+function managedThemeAccent(
+ value: string,
+ appearance: ThemeAppearance,
+ background: ThemeRgbColor,
+): ThemeRgbColor {
+ const selected = parseThemeRgbColor(value, { r: 168, g: 67, b: 112 });
+ const hsl = themeRgbToHsl(selected);
+ const preferredLightness =
+ appearance === "dark"
+ ? Math.min(0.72, Math.max(0.42, hsl.l))
+ : Math.min(0.58, Math.max(0.35, hsl.l));
+ const lightnessRange: readonly [number, number] =
+ appearance === "dark" ? [0.42, 0.82] : [0.22, 0.58];
+ const saturation = Math.min(hsl.s, 0.82);
+ const candidates = Array.from({ length: 61 }, (_, index) => {
+ const lightness =
+ lightnessRange[0] + ((lightnessRange[1] - lightnessRange[0]) * index) / (61 - 1);
+ const color = themeHslToRgb({ h: hsl.h, s: saturation, l: lightness });
+ return { color, lightness, contrast: themeContrastRatio(color, background) };
+ });
+ // Leave a little room for rounding when the generated RGB values become a
+ // six-digit hex token.
+ const readableCandidates = candidates.filter((candidate) => candidate.contrast >= 4.7);
+ const pool = readableCandidates.length > 0 ? readableCandidates : candidates;
+
+ return pool.reduce((best, candidate) => {
+ const distance = Math.abs(candidate.lightness - preferredLightness);
+ const bestDistance = Math.abs(best.lightness - preferredLightness);
+ return distance < bestDistance ||
+ (distance === bestDistance && candidate.contrast > best.contrast)
+ ? candidate
+ : best;
+ }).color;
+}
+
+/**
+ * Creates the guided palette used by the basic theme editor. The two user
+ * colors control the mood, while dependent roles are generated together so
+ * text, surfaces, message actions, code, and terminal UI stay coherent.
+ */
+export function createManagedThemeColors(
+ appearance: ThemeAppearance,
+ backgroundValue: string,
+ accentValue: string,
+ options?: {
+ /** Use the seeds exactly as given instead of nudging them into the
+ * readability envelope. Derived foregrounds still adapt for contrast. */
+ exactSeeds?: boolean;
+ },
+): ThemeColors {
+ const defaults = getDefaultThemeColors(appearance);
+ const canvas = options?.exactSeeds
+ ? parseThemeRgbColor(
+ backgroundValue,
+ appearance === "dark" ? { r: 24, g: 15, b: 27 } : { r: 250, g: 245, b: 250 },
+ )
+ : managedThemeBackground(backgroundValue, appearance);
+ const accent = options?.exactSeeds
+ ? parseThemeRgbColor(accentValue, { r: 168, g: 67, b: 112 })
+ : managedThemeAccent(accentValue, appearance, canvas);
+ const text = readableThemeForeground(canvas);
+ const textMuted = standardMutedThemeText(canvas, text);
+ // The top bar is part of the main panel, not a separate chrome layer: it
+ // shares the canvas, and its controls sit on the panel's own surfaces.
+ const chrome = canvas;
+ const sidebar = mixThemeRgbColors(canvas, accent, 0.08);
+ const surfaceRaised = mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.12 : 0.035);
+ const surfaceOverlay = mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.18 : 0.06);
+ const secondary = mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.2 : 0.08);
+ const muted = mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.13 : 0.06);
+ const accentSurface = mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.3 : 0.14);
+ const messageSurface = mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.36 : 0.18);
+ const toolbarControl = mixThemeRgbColors(chrome, accent, appearance === "dark" ? 0.2 : 0.08);
+ const toolbarBorder = mixThemeRgbColors(chrome, accent, appearance === "dark" ? 0.35 : 0.14);
+ const accentForeground = readableThemeForeground(accent);
+ // Code and terminal are large surfaces: they keep the canvas hue instead of
+ // drifting toward the foreground grey. Code sits just above the canvas —
+ // a whisper of the text tint — and the terminal sits on the canvas itself.
+ const codeBackground = mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.06 : 0.025);
+ const terminalBackground = canvas;
+ const messageActionHover = mixThemeRgbColors(
+ accent,
+ accentForeground === THEME_LIGHT_FOREGROUND || accentForeground === THEME_WHITE_FOREGROUND
+ ? THEME_BLACK_FOREGROUND
+ : THEME_WHITE_FOREGROUND,
+ 0.12,
+ );
+
+ // The update family follows the accent instead of inheriting the default
+ // palette's brand color, so generated themes carry their own identity in
+ // update pills and banners. Error and warning stay semantic defaults.
+ const updateSurface = mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.32 : 0.16);
+ const updateForeground = mixThemeRgbColors(
+ accent,
+ appearance === "dark" ? THEME_WHITE_FOREGROUND : THEME_BLACK_FOREGROUND,
+ 0.35,
+ );
+
+ return {
+ ...defaults,
+ ...standardStatusColors(canvas),
+ update: themeRgbToHexColor(accent),
+ updateForeground: themeRgbToHexColor(updateForeground),
+ updateSurface: themeRgbToHexColor(updateSurface),
+ canvas: themeRgbToHexColor(canvas),
+ chrome: themeRgbToHexColor(chrome),
+ toolbar: themeRgbToHexColor(chrome),
+ toolbarForeground: themeRgbToHexColor(text),
+ toolbarBorder: themeRgbToHexColor(toolbarBorder),
+ toolbarControl: themeRgbToHexColor(toolbarControl),
+ toolbarControlForeground: themeRgbToHexColor(text),
+ toolbarControlHover: themeRgbToHexColor(accentSurface),
+ surface: themeRgbToHexColor(canvas),
+ surfaceRaised: themeRgbToHexColor(surfaceRaised),
+ surfaceOverlay: themeRgbToHexColor(surfaceOverlay),
+ text: themeRgbToHexColor(text),
+ textMuted: themeRgbToHexColor(textMuted),
+ // Borders blend through the accent before lightening so control chrome
+ // carries the theme hue like the hand-tuned palettes (#5c345b, #e0d3e1)
+ // instead of flattening to grey.
+ border: themeRgbToHexColor(
+ mixThemeRgbColors(
+ mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.22 : 0.1),
+ text,
+ 0.1,
+ ),
+ ),
+ input: themeRgbToHexColor(
+ mixThemeRgbColors(
+ mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.3 : 0.14),
+ text,
+ appearance === "dark" ? 0.14 : 0.13,
+ ),
+ ),
+ focus: themeRgbToHexColor(accent),
+ accent: themeRgbToHexColor(accent),
+ accentForeground: themeRgbToHexColor(accentForeground),
+ secondary: themeRgbToHexColor(secondary),
+ secondaryForeground: themeRgbToHexColor(readableThemeForeground(secondary)),
+ muted: themeRgbToHexColor(muted),
+ mutedForeground: themeRgbToHexColor(textMuted),
+ placeholder: themeRgbToHexColor(textMuted),
+ secondaryLabel: themeRgbToHexColor(textMuted),
+ iconMuted: themeRgbToHexColor(textMuted),
+ accentSurface: themeRgbToHexColor(accentSurface),
+ accentSurfaceForeground: themeRgbToHexColor(readableThemeForeground(accentSurface)),
+ messageSurface: themeRgbToHexColor(messageSurface),
+ messageForeground: themeRgbToHexColor(readableThemeForeground(messageSurface)),
+ messageAction: themeRgbToHexColor(accent),
+ messageActionForeground: themeRgbToHexColor(accentForeground),
+ messageActionHover: themeRgbToHexColor(messageActionHover),
+ codeBackground: themeRgbToHexColor(codeBackground),
+ codeForeground: themeRgbToHexColor(readableThemeForeground(codeBackground)),
+ sidebar: themeRgbToHexColor(sidebar),
+ sidebarForeground: themeRgbToHexColor(readableThemeForeground(sidebar)),
+ sidebarMutedForeground: themeRgbToHexColor(standardMutedThemeText(sidebar, text)),
+ sidebarControlSurface: themeRgbToHexColor(
+ mixThemeRgbColors(sidebar, text, appearance === "dark" ? 0.16 : 0.08),
+ ),
+ sidebarRowHover: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.12)),
+ sidebarRowActive: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.2)),
+ sidebarRowSelected: themeRgbToHexColor(mixThemeRgbColors(sidebar, accent, 0.24)),
+ sidebarBorder: themeRgbToHexColor(
+ mixThemeRgbColors(sidebar, text, appearance === "dark" ? 0.35 : 0.12),
+ ),
+ terminalBackground: themeRgbToHexColor(terminalBackground),
+ terminalForeground: themeRgbToHexColor(readableThemeForeground(terminalBackground)),
+ terminalCursor: themeRgbToHexColor(accent),
+ terminalSelection: themeRgbToHexColor(
+ mixThemeRgbColors(canvas, accent, appearance === "dark" ? 0.35 : 0.18),
+ ),
+ terminalScrollbar: themeRgbToHexColor(
+ mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.42 : 0.22),
+ ),
+ terminalScrollbarHover: themeRgbToHexColor(
+ mixThemeRgbColors(canvas, text, appearance === "dark" ? 0.55 : 0.32),
+ ),
+ };
+}
+
+export const T3_CHAT_THEME: ThemeDefinition = {
+ id: T3_CHAT_THEME_ID,
+ label: T3_CHAT_THEME_LABEL,
+ appearance: "light",
+ colors: T3_CHAT_LIGHT_COLORS,
+ variants: {
+ dark: T3_CHAT_DARK_COLORS,
+ },
+};
+
+/** Theme-file defaults follow the flagship palette for the requested mode. */
+export function getDefaultThemeColors(appearance: ThemeAppearance): ThemeColors {
+ return appearance === "dark" ? T3_CHAT_DARK_COLORS : T3_CHAT_LIGHT_COLORS;
+}
+
+/**
+ * A companion action color in the T3 Chat mold. This gives send buttons,
+ * status pills, and theme previews a second voice; foreground and hover follow
+ * the same rules as the managed generator.
+ */
+function themeActionColors(
+ action: string,
+): Pick<ThemeColors, "messageAction" | "messageActionForeground" | "messageActionHover"> {
+ const rgb = parseThemeRgbColor(action, THEME_DARK_FOREGROUND);
+ const foreground = readableThemeForeground(rgb);
+ const towardOpposite =
+ foreground === THEME_LIGHT_FOREGROUND || foreground === THEME_WHITE_FOREGROUND
+ ? THEME_BLACK_FOREGROUND
+ : THEME_WHITE_FOREGROUND;
+ return {
+ messageAction: action,
+ messageActionForeground: themeRgbToHexColor(foreground),
+ messageActionHover: themeRgbToHexColor(mixThemeRgbColors(rgb, towardOpposite, 0.12)),
+ };
+}
+
+export const GROVE_THEME: ThemeDefinition = {
+ id: GROVE_THEME_ID,
+ label: GROVE_THEME_LABEL,
+ appearance: "light",
+ colors: {
+ ...createManagedThemeColors("light", "#f2f8f4", "#19734a"),
+ ...themeActionColors("#8f6410"),
+ },
+ variants: {
+ dark: {
+ ...createManagedThemeColors("dark", "#1d2b24", "#69d69a"),
+ ...themeActionColors("#e3b34e"),
+ },
+ },
+};
+
+export const OCEAN_THEME: ThemeDefinition = {
+ id: OCEAN_THEME_ID,
+ label: OCEAN_THEME_LABEL,
+ appearance: "light",
+ colors: {
+ ...createManagedThemeColors("light", "#f2f7fb", "#2878b8"),
+ ...themeActionColors("#0a6f75"),
+ },
+ variants: {
+ dark: {
+ ...createManagedThemeColors("dark", "#1b2938", "#70b9ee"),
+ ...themeActionColors("#5bd0d6"),
+ },
+ },
+};
+
+export const EMBER_THEME: ThemeDefinition = {
+ id: EMBER_THEME_ID,
+ label: EMBER_THEME_LABEL,
+ appearance: "light",
+ colors: {
+ ...createManagedThemeColors("light", "#fff6ef", "#c4602f"),
+ ...themeActionColors("#b23535"),
+ },
+ variants: {
+ dark: {
+ ...createManagedThemeColors("dark", "#30231e", "#f39a62"),
+ ...themeActionColors("#f78a7a"),
+ },
+ },
+};
+
+export const IRIS_THEME: ThemeDefinition = {
+ id: IRIS_THEME_ID,
+ label: IRIS_THEME_LABEL,
+ appearance: "light",
+ colors: {
+ ...createManagedThemeColors("light", "#f7f4fc", "#7254b9"),
+ ...themeActionColors("#a82c87"),
+ },
+ variants: {
+ dark: {
+ ...createManagedThemeColors("dark", "#29243b", "#ad92f5"),
+ ...themeActionColors("#f099d8"),
+ },
+ },
+};
+
+const BUILT_IN_THEME_DEFINITIONS: ReadonlyArray<ThemeDefinition> = [
+ T3_CHAT_THEME,
+ GROVE_THEME,
+ OCEAN_THEME,
+ EMBER_THEME,
+ IRIS_THEME,
+];
+
+export function getThemeDefinition(theme: ThemePreference): ThemeDefinition | null {
+ const themeId = themeIdFromPreference(theme);
+ return (
+ BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId) ??
+ getCustomThemes().find((definition) => definition.id === themeId) ??
+ null
+ );
+}
+
+export function getThemeColorsForMode(
+ theme: ThemeDefinition,
+ mode: ThemeAppearance,
+): ThemeColors | null {
+ if (mode === theme.appearance) return theme.colors;
+ return theme.variants?.[mode] ?? null;
+}
+
+export function getThemeModes(theme: ThemeDefinition): ReadonlyArray<ThemeAppearance> {
+ return (["light", "dark"] as const).filter((mode) => getThemeColorsForMode(theme, mode) !== null);
+}
+
+export function getThemePreferenceMode(theme: ThemePreference): ThemeAppearance | null {
+ if (theme === "system") return null;
+ if (theme === "light" || theme === "dark") return theme;
+ const legacyMode = legacyThemeMode(theme);
+ if (legacyMode) return legacyMode;
+ return getThemeDefinition(theme)?.appearance ?? null;
+}
+
+export function themeIdFromName(name: string): string {
+ const normalized = name
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 48);
+ return normalized || "custom-theme";
+}
+
+export class ThemeLibraryStorageError extends Schema.TaggedErrorClass<ThemeLibraryStorageError>()(
+ "ThemeLibraryStorageError",
+ { storageKey: Schema.String, cause: Schema.Defect() },
+) {
+ override get message(): string {
+ return `Failed to write the theme library to ${this.storageKey}.`;
+ }
+}
+
+export const isThemeLibraryStorageError = Schema.is(ThemeLibraryStorageError);
+
+function saveCustomThemes(themes: ReadonlyArray<ThemeDefinition>): void {
+ if (typeof window === "undefined") return;
+ try {
+ window.localStorage.setItem(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify(themes));
+ customThemesSnapshot = themes;
+ } catch (cause) {
+ throw new ThemeLibraryStorageError({ storageKey: CUSTOM_THEMES_STORAGE_KEY, cause });
+ }
+ notifyCustomThemeListeners();
+}
+
+export function installCustomTheme(theme: ThemeDefinition): ThemeDefinition {
+ if (RESERVED_THEME_IDS.has(theme.id)) {
+ throw new Error(`The theme id "${theme.id}" is reserved.`);
+ }
+ if (
+ [...BUILT_IN_THEME_DEFINITIONS, ...getCustomThemes()].some(
+ (existing) => existing.id === theme.id,
+ )
+ ) {
+ throw new Error(`A theme named "${theme.label}" is already installed.`);
+ }
+ saveCustomThemes([...getCustomThemes(), theme]);
+ return theme;
+}
+
+export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
+ if (RESERVED_THEME_IDS.has(theme.id)) {
+ throw new Error(`The theme id "${theme.id}" is reserved.`);
+ }
+
+ const themes = getCustomThemes();
+ const themeIndex = themes.findIndex((existing) => existing.id === theme.id);
+ if (themeIndex === -1) {
+ throw new Error(`The theme "${theme.label}" is not installed.`);
+ }
+
+ const nextThemes = [...themes];
+ nextThemes[themeIndex] = theme;
+ saveCustomThemes(nextThemes);
+ return theme;
+}
+
+export function removeCustomTheme(themeId: string): void {
+ const nextThemes = getCustomThemes().filter((theme) => theme.id !== themeId);
+ if (nextThemes.length === getCustomThemes().length) return;
+ saveCustomThemes(nextThemes);
+}
+
+function parseThemeColorOverrides(value: unknown): ThemeColorOverrides {
+ if (!isRecord(value)) throw new Error("Theme colors must be objects.");
+
+ const overrides: Partial<Record<ThemeColorRole, string>> = {};
+ for (const [role, color] of Object.entries(value)) {
+ if (!THEME_COLOR_ROLE_SET.has(role)) {
+ throw new Error(`"${role}" is not a supported theme color role.`);
+ }
+ if (!isThemeColor(color)) {
+ throw new Error(`The color for "${role}" must be a hex color such as #8b5cf6.`);
+ }
+ overrides[role as ThemeColorRole] = color;
+ }
+ if (Object.keys(overrides).length === 0) {
+ throw new Error("Add at least one color role to the theme file.");
+ }
+ return overrides;
+}
+
+export function parseThemeFile(value: unknown): ThemeDefinition {
+ if (!isRecord(value)) {
+ throw new Error("Theme files must contain a JSON object.");
+ }
+ if (value.version !== THEME_FILE_VERSION) {
+ throw new Error(`This theme file uses an unsupported version. Expected ${THEME_FILE_VERSION}.`);
+ }
+
+ const name = value.name;
+ const appearance = value.appearance;
+ const rawColors = value.colors;
+ if (!isThemeLabel(name)) throw new Error("Theme files need a name (48 characters or fewer).");
+ if (!isThemeAppearance(appearance)) {
+ throw new Error('Theme files need an appearance of "light" or "dark".');
+ }
+ if (!isRecord(rawColors)) throw new Error("Theme files need a colors object.");
+
+ const id = value.id === undefined ? themeIdFromName(name) : value.id;
+ if (!isThemeId(id)) {
+ throw new Error("Theme ids may only contain lowercase letters, numbers, and hyphens.");
+ }
+ if (RESERVED_THEME_IDS.has(id)) {
+ throw new Error(`The theme id "${id}" is reserved.`);
+ }
+
+ const overrides = parseThemeColorOverrides(rawColors);
+
+ const fallback = getDefaultThemeColors(appearance);
+ const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
+ if (value.variants !== undefined) {
+ if (!isRecord(value.variants)) throw new Error("Theme variants must be an object.");
+ for (const [variantAppearance, variantColors] of Object.entries(value.variants)) {
+ if (!isThemeAppearance(variantAppearance)) {
+ throw new Error('Theme variants may only be named "light" or "dark".');
+ }
+ if (variantAppearance === appearance) {
+ throw new Error(`Theme variants must not repeat the base appearance "${appearance}".`);
+ }
+ const variantFallback = getDefaultThemeColors(variantAppearance);
+ variants[variantAppearance] = {
+ ...variantFallback,
+ ...parseThemeColorOverrides(variantColors),
+ };
+ }
+ }
+
+ return {
+ id,
+ label: name.trim(),
+ appearance,
+ colors: { ...fallback, ...overrides },
+ ...(Object.keys(variants).length > 0 ? { variants } : {}),
+ ...(value.managed === true ? { managed: true } : {}),
+ };
+}
+
+export function serializeThemeFile(theme: ThemeDefinition): string {
+ const file: ThemeFile = {
+ version: THEME_FILE_VERSION,
+ id: theme.id,
+ name: theme.label,
+ appearance: theme.appearance,
+ colors: theme.colors,
+ ...(theme.variants ? { variants: theme.variants } : {}),
+ ...(theme.managed ? { managed: true } : {}),
+ };
+ return `${JSON.stringify(file, null, 2)}\n`;
+}
+
+const APP_THEME_VARIABLES: Readonly<Record<ThemeColorRole, string>> = {
+ canvas: "--app-theme-canvas",
+ chrome: "--app-theme-chrome",
+ toolbar: "--app-theme-toolbar",
+ toolbarForeground: "--app-theme-toolbar-foreground",
+ toolbarBorder: "--app-theme-toolbar-border",
+ toolbarControl: "--app-theme-toolbar-control",
+ toolbarControlForeground: "--app-theme-toolbar-control-foreground",
+ toolbarControlHover: "--app-theme-toolbar-control-hover",
+ surface: "--app-theme-surface",
+ surfaceRaised: "--app-theme-surface-raised",
+ surfaceOverlay: "--app-theme-surface-overlay",
+ text: "--app-theme-text",
+ textMuted: "--app-theme-text-muted",
+ border: "--app-theme-border",
+ input: "--app-theme-input",
+ focus: "--app-theme-focus",
+ accent: "--app-theme-accent",
+ accentForeground: "--app-theme-accent-foreground",
+ secondary: "--app-theme-secondary",
+ secondaryForeground: "--app-theme-secondary-foreground",
+ muted: "--app-theme-muted",
+ mutedForeground: "--app-theme-muted-foreground",
+ placeholder: "--app-theme-placeholder",
+ secondaryLabel: "--app-theme-secondary-label",
+ iconMuted: "--app-theme-icon-muted",
+ error: "--app-theme-error",
+ errorForeground: "--app-theme-error-foreground",
+ errorSurface: "--app-theme-error-surface",
+ warning: "--app-theme-warning",
+ warningForeground: "--app-theme-warning-foreground",
+ warningSurface: "--app-theme-warning-surface",
+ update: "--app-theme-update",
+ updateForeground: "--app-theme-update-foreground",
+ updateSurface: "--app-theme-update-surface",
+ accentSurface: "--app-theme-accent-surface",
+ accentSurfaceForeground: "--app-theme-accent-surface-foreground",
+ messageSurface: "--app-theme-message-surface",
+ messageForeground: "--app-theme-message-foreground",
+ messageAction: "--app-theme-message-action",
+ messageActionForeground: "--app-theme-message-action-foreground",
+ messageActionHover: "--app-theme-message-action-hover",
+ codeBackground: "--app-theme-code-background",
+ codeForeground: "--app-theme-code-foreground",
+ sidebar: "--app-theme-sidebar",
+ sidebarForeground: "--app-theme-sidebar-foreground",
+ sidebarMutedForeground: "--app-theme-sidebar-muted-foreground",
+ sidebarControlSurface: "--app-theme-sidebar-control-surface",
+ sidebarRowHover: "--app-theme-sidebar-row-hover",
+ sidebarRowActive: "--app-theme-sidebar-row-active",
+ sidebarRowSelected: "--app-theme-sidebar-row-selected",
+ sidebarBorder: "--app-theme-sidebar-border",
+ terminalBackground: "--app-theme-terminal-background",
+ terminalForeground: "--app-theme-terminal-foreground",
+ terminalCursor: "--app-theme-terminal-cursor",
+ terminalSelection: "--app-theme-terminal-selection-background",
+ terminalScrollbar: "--app-theme-terminal-scrollbar",
+ terminalScrollbarHover: "--app-theme-terminal-scrollbar-hover",
+};
+
+export function getThemeColorVariable(role: ThemeColorRole): string {
+ return APP_THEME_VARIABLES[role];
+}
+
+/** Marks the document as wearing an unsaved draft rather than a stored theme. */
+export const THEME_PREVIEW_ID = "__preview";
+
+/**
+ * Paint a draft palette onto the live app without installing it, so the editor
+ * can be judged against the real interface instead of a miniature. Callers
+ * restore the stored theme (refreshTheme) when the draft goes away.
+ */
+export function applyThemeColorPreview(colors: ThemeColors, appearance: ThemeAppearance): void {
+ if (typeof document === "undefined") return;
+ const root = document.documentElement;
+ if (!root?.style) return;
+
+ root.dataset.themeId = THEME_PREVIEW_ID;
+ root.classList.toggle("dark", appearance === "dark");
+ for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
+ // A half-typed hex keeps the last good value instead of blanking the role.
+ if (isThemeColor(value)) root.style.setProperty(APP_THEME_VARIABLES[role], value);
+ }
+}
+
+export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppearance): void {
+ if (typeof document === "undefined") return;
+
+ const root = document.documentElement;
+ if (!root?.style) return;
+
+ const palette = getThemeDefinition(theme);
+
+ if (palette) {
+ root.dataset.themeId = palette.id;
+ const mode = appearance ?? legacyThemeMode(theme) ?? palette.appearance;
+ const colors = getThemeColorsForMode(palette, mode) ?? palette.colors;
+ for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
+ root.style.setProperty(APP_THEME_VARIABLES[role], value);
+ }
+ return;
+ }
+
+ delete root.dataset.themeId;
+ for (const variable of Object.values(APP_THEME_VARIABLES)) {
+ root.style.removeProperty(variable);
+ }
+}
+
+export function resolveThemeAppearance(
+ theme: ThemePreference,
+ systemDark: boolean,
+ followSystem?: boolean,
+ appearanceMode?: ThemePreferenceMode,
+ halves?: ThemeHalves | null,
+): "light" | "dark" {
+ const systemAppearance = systemDark ? "dark" : "light";
+ const mode = appearanceMode ?? ((followSystem ?? theme === "system") ? "system" : null);
+ if (mode === "system") {
+ // A configured half guarantees the appearance is renderable even when the
+ // base theme lacks that mode.
+ if (halves?.[systemAppearance]) return systemAppearance;
+ const definition = getThemeDefinition(theme);
+ return definition && getThemeColorsForMode(definition, systemAppearance) === null
+ ? definition.appearance
+ : systemAppearance;
+ }
+ if (mode === "light" || mode === "dark") {
+ if (halves?.[mode]) return mode;
+ const definition = getThemeDefinition(theme);
+ return definition && getThemeColorsForMode(definition, mode) === null
+ ? definition.appearance
+ : mode;
+ }
+ return getThemePreferenceMode(theme) ?? "light";
+}
+
+export function resolveDesktopTheme(
+ theme: ThemePreference,
+ followSystem?: boolean,
+ appearanceMode?: ThemePreferenceMode,
+ halves?: ThemeHalves | null,
+): "light" | "dark" | "system" {
+ const mode = appearanceMode ?? ((followSystem ?? theme === "system") ? "system" : null);
+ if (mode === "system") {
+ const definition = getThemeDefinition(theme);
+ // A configured half fills in an appearance the base theme cannot render.
+ const hasLightMode =
+ halves?.light !== undefined ||
+ (definition !== null && getThemeColorsForMode(definition, "light") !== null);
+ const hasDarkMode =
+ halves?.dark !== undefined ||
+ (definition !== null && getThemeColorsForMode(definition, "dark") !== null);
+ return definition && (!hasLightMode || !hasDarkMode) ? definition.appearance : "system";
+ }
+ if (mode === "light" || mode === "dark") {
+ if (halves?.[mode]) return mode;
+ const definition = getThemeDefinition(theme);
+ return definition && getThemeColorsForMode(definition, mode) === null
+ ? definition.appearance
+ : mode;
+ }
+ return getThemePreferenceMode(theme) ?? "system";
+}
+
+export function isKnownThemePreference(theme: string): boolean {
+ if (theme === "light" || theme === "dark" || theme === "system") return true;
+ return getThemeDefinition(theme) !== null;
+}
+
+/**
+ * An automatic-mode mix: a different theme per resolved appearance. Halves
+ * only name real themes that can render their half; anything else is dropped
+ * so a stale mix degrades to the base preference.
+ */
+export type ThemeHalves = Readonly<{ light?: string; dark?: string }>;
+
+export function parseThemeHalves(raw: string | null): ThemeHalves | null {
+ if (!raw) return null;
+ try {
+ const value: unknown = JSON.parse(raw);
+ if (!isRecord(value)) return null;
+ const halves: { light?: string; dark?: string } = {};
+ for (const appearance of ["light", "dark"] as const) {
+ const themeId = value[appearance];
+ if (typeof themeId !== "string") continue;
+ const definition = getThemeDefinition(themeId);
+ if (definition && getThemeColorsForMode(definition, appearance) !== null) {
+ // Store the definition's id so legacy aliases resolve to the same
+ // value the runtime applies to the document.
+ halves[appearance] = definition.id;
+ }
+ }
+ return halves.light !== undefined || halves.dark !== undefined ? halves : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The theme that should render the given appearance under a mix, if any. */
+export function resolveThemeHalf(
+ theme: ThemePreference,
+ halves: ThemeHalves | null,
+ appearance: ThemeAppearance,
+): ThemePreference {
+ return halves?.[appearance] ?? theme;
+}
diff --git a/apps/web/src/vscodeThemeImport.test.ts b/apps/web/src/vscodeThemeImport.test.ts
new file mode 100644
index 000000000..a736620b2
--- /dev/null
+++ b/apps/web/src/vscodeThemeImport.test.ts
@@ -0,0 +1,282 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { getThemeColorsForMode, THEME_FILE_VERSION } from "./themePalette";
+import {
+ isVsCodeThemeFile,
+ pairVsCodeThemes,
+ parseVsCodeThemeFile,
+ resolveThemeLabelCollisions,
+} from "./vscodeThemeImport";
+
+function contrastRatio(first: string, second: string): number {
+ const toChannels = (value: string) => {
+ const hex = value.slice(1);
+ return [0, 1, 2].map(
+ (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
+ );
+ };
+ const luminance = (value: string) =>
+ toChannels(value)
+ .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
+ .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
+ const lighter = Math.max(luminance(first), luminance(second));
+ const darker = Math.min(luminance(first), luminance(second));
+ return (lighter + 0.05) / (darker + 0.05);
+}
+
+// Shaped like a real workbench theme: dotted keys, alpha overlays, and a lot
+// of roles simply left out.
+const VSCODE_DARK = {
+ name: "pierre-dark-soft",
+ type: "dark",
+ colors: {
+ "editor.background": "#171717",
+ "editor.foreground": "#d4d4d4",
+ foreground: "#d4d4d4",
+ "sideBar.background": "#101010",
+ "sideBar.foreground": "#8a8a8a",
+ "sideBar.border": "#1d1d1d",
+ focusBorder: "#69b1ff",
+ "button.background": "#69b1ff",
+ "button.foreground": "#171717",
+ "input.border": "#2c2c2c",
+ "input.placeholderForeground": "#525252",
+ "terminal.background": "#101010",
+ "terminal.foreground": "#8a8a8a",
+ "list.hoverBackground": "#1f3e5e59",
+ "list.activeSelectionBackground": "#1f3e5e99",
+ },
+ tokenColors: [],
+};
+
+describe("VS Code theme import", () => {
+ it("recognises workbench themes and rejects our own files", () => {
+ expect(isVsCodeThemeFile(VSCODE_DARK)).toBe(true);
+ expect(isVsCodeThemeFile({ type: "dark", tokenColors: [] })).toBe(true);
+ expect(
+ isVsCodeThemeFile({
+ version: THEME_FILE_VERSION,
+ name: "Aurora",
+ appearance: "light",
+ colors: { canvas: "#ffffff" },
+ }),
+ ).toBe(false);
+ expect(isVsCodeThemeFile("nope")).toBe(false);
+ });
+
+ it("carries the editor surfaces and accent across", () => {
+ const theme = parseVsCodeThemeFile(VSCODE_DARK);
+ // The slug name is read as words; a displayName would win verbatim.
+ expect(theme.label).toBe("Pierre Dark Soft");
+ expect(theme.appearance).toBe("dark");
+ expect(theme.colors.canvas).toBe("#171717");
+ expect(theme.colors.text).toBe("#d4d4d4");
+ expect(theme.colors.accent).toBe("#69b1ff");
+ expect(theme.colors.sidebar).toBe("#101010");
+ expect(theme.colors.terminalBackground).toBe("#101010");
+ });
+
+ it("flattens alpha overlays onto the surface they sit on", () => {
+ const theme = parseVsCodeThemeFile(VSCODE_DARK);
+ // #1f3e5e59 over the #101010 sidebar, not left semi-transparent.
+ expect(theme.colors.sidebarRowHover).toMatch(/^#[0-9a-f]{6}$/);
+ expect(theme.colors.sidebarRowHover).not.toBe("#1f3e5e59");
+ expect(theme.colors.sidebarRowSelected).not.toBe(theme.colors.sidebar);
+ });
+
+ it("fills every role the file omits with a readable derived value", () => {
+ const theme = parseVsCodeThemeFile(VSCODE_DARK);
+ const colors = getThemeColorsForMode(theme, "dark")!;
+ for (const value of Object.values(colors)) {
+ expect(value).toMatch(/^#[0-9a-f]{3,8}$/i);
+ }
+ expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(4.5);
+ expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
+ expect(
+ contrastRatio(colors.messageActionForeground, colors.messageAction),
+ ).toBeGreaterThanOrEqual(4.5);
+ });
+
+ it("falls back to the editor background when the type is missing or odd", () => {
+ const untyped = parseVsCodeThemeFile({
+ name: "Untyped",
+ colors: { "editor.background": "#fdfdfd", "editor.foreground": "#202020" },
+ });
+ expect(untyped.appearance).toBe("light");
+ const hc = parseVsCodeThemeFile({
+ name: "High contrast",
+ type: "hc-light",
+ colors: { "editor.background": "#ffffff" },
+ });
+ expect(hc.appearance).toBe("light");
+ });
+
+ it("keeps an unreadable foreground out of the palette", () => {
+ const theme = parseVsCodeThemeFile({
+ name: "Unreadable",
+ type: "dark",
+ colors: { "editor.background": "#101010", "editor.foreground": "#111111" },
+ });
+ expect(theme.colors.text).not.toBe("#111111");
+ expect(contrastRatio(theme.colors.text, theme.colors.canvas)).toBeGreaterThanOrEqual(4.5);
+ });
+
+ it("stays readable when the file replaces a surface but not its foreground", () => {
+ // A dark theme with a light sidebar: the derived sidebar foreground was
+ // solved for a dark surface and would vanish on this one.
+ const theme = parseVsCodeThemeFile({
+ name: "Split",
+ type: "dark",
+ colors: {
+ "editor.background": "#101010",
+ "editor.foreground": "#f5f5f5",
+ "sideBar.background": "#fafafa",
+ "terminal.background": "#fbfbfb",
+ },
+ });
+ expect(theme.colors.sidebar).toBe("#fafafa");
+ expect(
+ contrastRatio(theme.colors.sidebarForeground, theme.colors.sidebar),
+ ).toBeGreaterThanOrEqual(4.5);
+ expect(
+ contrastRatio(theme.colors.terminalForeground, theme.colors.terminalBackground),
+ ).toBeGreaterThanOrEqual(4.5);
+ });
+
+ it("reads wide-gamut color() notation", () => {
+ // Themes authored for P3 displays (the shipped Pierre "vibrant" pair) use
+ // this instead of hex.
+ const theme = parseVsCodeThemeFile({
+ name: "Vibrant",
+ type: "dark",
+ colors: {
+ "editor.background": "color(display-p3 0.039216 0.039216 0.039216)",
+ "editor.foreground": "color(display-p3 0.980392 0.980392 0.980392)",
+ focusBorder: "color(display-p3 0.308664 0.645271 1.000000)",
+ "editor.selectionBackground": "color(display-p3 0.308664 0.645271 1.000000 / 0.300000)",
+ },
+ });
+ expect(theme.colors.canvas).toMatch(/^#0[89ab]/);
+ expect(theme.colors.text).toMatch(/^#f[a-f0-9]/);
+ // The P3 blue lands in sRGB blue, not black or a clipped grey.
+ const accent = theme.colors.accent;
+ const [red, green, blue] = [1, 3, 5].map((index) =>
+ Number.parseInt(accent.slice(index, index + 2), 16),
+ ) as [number, number, number];
+ expect(blue).toBeGreaterThan(200);
+ expect(blue).toBeGreaterThan(red);
+ expect(green).toBeGreaterThan(red);
+ });
+
+ it("pairs light and dark files from one family into dual-mode themes", () => {
+ const make = (name: string, type: "light" | "dark") =>
+ parseVsCodeThemeFile({
+ name,
+ type,
+ colors: {
+ "editor.background": type === "dark" ? "#101014" : "#fdfdfd",
+ "editor.foreground": type === "dark" ? "#e6e6e6" : "#1f1f1f",
+ focusBorder: "#69b1ff",
+ },
+ });
+ const themes = pairVsCodeThemes([
+ make("github-dark", "dark"),
+ make("github-light", "light"),
+ make("github-dark-colorblind", "dark"),
+ make("github-light-colorblind", "light"),
+ make("github-dark-dimmed", "dark"),
+ ]);
+
+ const labels = themes.map((theme) => theme.label);
+ expect(labels).toEqual(["Github", "Github Colorblind", "Github Dark Dimmed"]);
+ const github = themes[0]!;
+ expect(github.appearance).toBe("light");
+ expect(getThemeColorsForMode(github, "dark")).not.toBeNull();
+ expect(getThemeColorsForMode(github, "dark")!.canvas).toBe("#101014");
+ expect(github.colors.canvas).toBe("#fdfdfd");
+ // The unpaired dimmed variant stays a single dark theme.
+ expect(getThemeColorsForMode(themes[2]!, "light")).toBeNull();
+ });
+
+ it("does not guess when a family is ambiguous", () => {
+ const make = (name: string, type: "light" | "dark") =>
+ parseVsCodeThemeFile({
+ name,
+ type,
+ colors: { "editor.background": type === "dark" ? "#101014" : "#fdfdfd" },
+ });
+ const themes = pairVsCodeThemes([
+ make("solar-dark", "dark"),
+ make("solar-dark-soft", "dark"),
+ make("solar-light", "light"),
+ ]);
+ // "solar-dark-soft" groups under its own key with no light partner, so
+ // it keeps its full name; the remaining pair merges.
+ expect(themes.map((theme) => theme.label).sort()).toEqual(["Solar", "Solar Dark Soft"]);
+ });
+
+ it("keeps derived surfaces neutral instead of washing them with the accent", () => {
+ // A gray theme with a blue focusBorder: roles the file omits (code
+ // surface, plain surfaces) must stay near the canvas, not turn blue.
+ const theme = parseVsCodeThemeFile(VSCODE_DARK);
+ const spread = (value: string) => {
+ const channels = [1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16));
+ return Math.max(...channels) - Math.min(...channels);
+ };
+ expect(spread(theme.colors.codeBackground)).toBeLessThanOrEqual(8);
+ expect(spread(theme.colors.surface)).toBeLessThanOrEqual(8);
+ expect(spread(theme.colors.text)).toBeLessThanOrEqual(12);
+ // The accent itself keeps the file's color.
+ expect(theme.colors.accent).toBe("#69b1ff");
+ });
+
+ it("tells same-named variants apart by their file names", () => {
+ // Dracula ships dracula.json and dracula-soft.json that both say
+ // "Dracula" inside.
+ const dracula = (bg: string) =>
+ parseVsCodeThemeFile({
+ name: "Dracula",
+ type: "dark",
+ colors: { "editor.background": bg, "editor.foreground": "#f8f8f2" },
+ });
+ const themes = resolveThemeLabelCollisions([
+ { theme: dracula("#282a36"), sourceName: "dracula.json" },
+ { theme: dracula("#22232e"), sourceName: "dracula-soft.json" },
+ ]);
+ expect(themes.map((theme) => theme.label)).toEqual(["Dracula", "Dracula Soft"]);
+ expect(themes.map((theme) => theme.id)).toEqual(["dracula", "dracula-soft"]);
+ // Without file names the second falls back to numbering.
+ const numbered = resolveThemeLabelCollisions([
+ { theme: dracula("#282a36") },
+ { theme: dracula("#22232e") },
+ ]);
+ expect(numbered.map((theme) => theme.label)).toEqual(["Dracula", "Dracula 2"]);
+ });
+
+ it("falls back to the name when the displayName humanizes to nothing", () => {
+ const theme = parseVsCodeThemeFile({
+ displayName: "---",
+ name: "night-owl",
+ type: "dark",
+ colors: { "editor.background": "#011627" },
+ });
+ expect(theme.label).toBe("Night Owl");
+ });
+
+ it("keeps a pair whose stripped name is reserved as two single themes", () => {
+ const make = (name: string, type: "light" | "dark") =>
+ parseVsCodeThemeFile({
+ name,
+ type,
+ colors: { "editor.background": type === "dark" ? "#101014" : "#fdfdfd" },
+ });
+ const themes = pairVsCodeThemes([make("grove-light", "light"), make("grove-dark", "dark")]);
+ expect(themes.map((theme) => theme.label).sort()).toEqual(["Grove Dark", "Grove Light"]);
+ });
+
+ it("explains a file with no editor background", () => {
+ expect(() => parseVsCodeThemeFile({ name: "Empty", type: "dark", colors: {} })).toThrow(
+ /editor\.background/,
+ );
+ });
+});
diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.ts
new file mode 100644
index 000000000..6432e6886
--- /dev/null
+++ b/apps/web/src/vscodeThemeImport.ts
@@ -0,0 +1,449 @@
+import {
+ createVividThemeColors,
+ getThemeModes,
+ parseThemeFile,
+ THEME_FILE_VERSION,
+ type ThemeAppearance,
+ type ThemeColorRole,
+ type ThemeDefinition,
+} from "./themePalette";
+
+/**
+ * Best-effort import of a VS Code color theme (`*-color-theme.json`).
+ *
+ * VS Code themes describe editor chrome, not an app palette: they carry a few
+ * hundred workbench keys, leave most of them unset, and freely use 8-digit
+ * hex with alpha for overlays. So the conversion derives a complete, contrast
+ * -solved palette from the theme's editor background and accent, then layers
+ * the workbench colors it did specify on top. Anything the file omits keeps
+ * the derived value instead of falling back to an unrelated palette.
+ */
+
+type VsCodeRgba = { r: number; g: number; b: number; a: number };
+type VsCodeRgb = { r: number; g: number; b: number };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/** sRGB transfer function, and its inverse, shared by the wide-gamut path. */
+function decodeGamma(value: number): number {
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+}
+
+function encodeGamma(value: number): number {
+ const clamped = Math.max(0, Math.min(1, value));
+ return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055;
+}
+
+/**
+ * `color(display-p3 r g b / a)` shows up in themes authored for wide-gamut
+ * displays. Out-of-gamut colors clip to the sRGB edge, which is what a browser
+ * on an sRGB screen shows anyway.
+ */
+function parseColorFunction(value: string): VsCodeRgba | null {
+ const match = /^color\(\s*(display-p3|srgb)\s+([^)]+)\)$/i.exec(value);
+ if (!match) return null;
+ const [space, body] = [match[1]!.toLowerCase(), match[2]!];
+ const [channelPart, alphaPart] = body.split("/");
+ const channels = channelPart!
+ .trim()
+ .split(/\s+/)
+ .map((part) => (part.endsWith("%") ? Number.parseFloat(part) / 100 : Number.parseFloat(part)));
+ if (channels.length !== 3 || channels.some((channel) => !Number.isFinite(channel))) return null;
+ const alphaRaw = alphaPart?.trim();
+ const alpha =
+ alphaRaw === undefined
+ ? 1
+ : alphaRaw.endsWith("%")
+ ? Number.parseFloat(alphaRaw) / 100
+ : Number.parseFloat(alphaRaw);
+ if (!Number.isFinite(alpha)) return null;
+
+ const [red, green, blue] = channels as [number, number, number];
+ if (space === "srgb") {
+ return { r: red * 255, g: green * 255, b: blue * 255, a: Math.max(0, Math.min(1, alpha)) };
+ }
+ const [linearRed, linearGreen, linearBlue] = [red, green, blue].map(decodeGamma) as [
+ number,
+ number,
+ number,
+ ];
+ // Display P3 linear -> sRGB linear.
+ const srgb = [
+ 1.2249401762805 * linearRed - 0.2249401762805 * linearGreen,
+ -0.042056961239 * linearRed + 1.042056961239 * linearGreen,
+ -0.0196375547643 * linearRed - 0.0786360655012 * linearGreen + 1.0982736202656 * linearBlue,
+ ].map((channel) => encodeGamma(channel) * 255) as [number, number, number];
+ return { r: srgb[0], g: srgb[1], b: srgb[2], a: Math.max(0, Math.min(1, alpha)) };
+}
+
+/** VS Code accepts #RGB, #RGBA, #RRGGBB, and #RRGGBBAA; some themes also use
+ * CSS color() notation for wide-gamut palettes. */
+function parseVsCodeColor(value: unknown): VsCodeRgba | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ if (trimmed.startsWith("color(")) return parseColorFunction(trimmed);
+ const hex = trimmed.replace(/^#/, "");
+ if (!/^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
+ const expand = (part: string) =>
+ part.length === 1 ? Number.parseInt(part + part, 16) : Number.parseInt(part, 16);
+ if (hex.length <= 4) {
+ return {
+ r: expand(hex[0]!),
+ g: expand(hex[1]!),
+ b: expand(hex[2]!),
+ a: hex.length === 4 ? expand(hex[3]!) / 255 : 1,
+ };
+ }
+ return {
+ r: Number.parseInt(hex.slice(0, 2), 16),
+ g: Number.parseInt(hex.slice(2, 4), 16),
+ b: Number.parseInt(hex.slice(4, 6), 16),
+ a: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1,
+ };
+}
+
+function toHex(color: VsCodeRgb): string {
+ const channel = (value: number) =>
+ Math.max(0, Math.min(255, Math.round(value)))
+ .toString(16)
+ .padStart(2, "0");
+ return `#${channel(color.r)}${channel(color.g)}${channel(color.b)}`;
+}
+
+/** Overlays are semi-transparent in VS Code; our roles are opaque, so they are
+ * composited onto whatever surface they sit on. */
+function flattenOver(color: VsCodeRgba, base: VsCodeRgb): string {
+ if (color.a >= 1) return toHex(color);
+ return toHex({
+ r: color.r * color.a + base.r * (1 - color.a),
+ g: color.g * color.a + base.g * (1 - color.a),
+ b: color.b * color.a + base.b * (1 - color.a),
+ });
+}
+
+function relativeLuminance(color: VsCodeRgb): number {
+ const channel = (value: number) => {
+ const ratio = value / 255;
+ return ratio <= 0.03928 ? ratio / 12.92 : ((ratio + 0.055) / 1.055) ** 2.4;
+ };
+ return 0.2126 * channel(color.r) + 0.7152 * channel(color.g) + 0.0722 * channel(color.b);
+}
+
+function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
+ const a = relativeLuminance(first);
+ const b = relativeLuminance(second);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+}
+
+function hexToRgb(value: string): VsCodeRgb {
+ return parseVsCodeColor(value) ?? { r: 0, g: 0, b: 0, a: 1 };
+}
+
+/**
+ * A VS Code theme is recognised by its workbench colors: the keys are dotted
+ * paths (`editor.background`), which our own files never use.
+ */
+export function isVsCodeThemeFile(value: unknown): boolean {
+ if (!isRecord(value)) return false;
+ if (value.version === THEME_FILE_VERSION) return false;
+ const hasWorkbenchColors =
+ isRecord(value.colors) && Object.keys(value.colors).some((key) => key.includes("."));
+ return hasWorkbenchColors || Array.isArray(value.tokenColors);
+}
+
+function resolveAppearance(value: Record<string, unknown>, canvas: VsCodeRgb): ThemeAppearance {
+ const type = typeof value.type === "string" ? value.type.toLowerCase() : null;
+ if (type === "light" || type === "hc-light") return "light";
+ if (type === "dark" || type === "hc-black") return "dark";
+ // Unlabelled themes (and the odd custom `type`) follow the editor surface.
+ return relativeLuminance(canvas) < 0.179 ? "dark" : "light";
+}
+
+/** Extension `name` fields are often package slugs; read them as words. */
+export function humanizeThemeName(raw: string): string {
+ const trimmed = raw.trim();
+ if (/\s/.test(trimmed) || !/[-_.]/.test(trimmed)) return trimmed;
+ return trimmed
+ .split(/[-_.]+/)
+ .filter(Boolean)
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
+}
+
+function resolveName(value: Record<string, unknown>): string {
+ // Judge candidates by their humanized form: a displayName of "---"
+ // humanizes to nothing and must fall through to the name.
+ for (const candidate of [value.displayName, value.name]) {
+ if (typeof candidate !== "string") continue;
+ const humanized = humanizeThemeName(candidate);
+ if (humanized.length > 0) return humanized.slice(0, 48);
+ }
+ return "VS Code theme";
+}
+
+export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
+ if (!isRecord(value)) throw new Error("Theme files must contain a JSON object.");
+ const colors = isRecord(value.colors) ? value.colors : {};
+
+ /** First key that carries a usable color, in priority order. */
+ const pick = (...keys: ReadonlyArray<string>): VsCodeRgba | null => {
+ for (const key of keys) {
+ const parsed = parseVsCodeColor(colors[key]);
+ if (parsed) return parsed;
+ }
+ return null;
+ };
+ const solidOver = (base: VsCodeRgb, ...keys: ReadonlyArray<string>): string | null => {
+ const parsed = pick(...keys);
+ return parsed ? flattenOver(parsed, base) : null;
+ };
+
+ const canvasColor = pick("editor.background", "editorPane.background");
+ if (!canvasColor) {
+ throw new Error(
+ 'That VS Code theme has no "editor.background" color, so there is nothing to build a palette from.',
+ );
+ }
+ const canvas = { r: canvasColor.r, g: canvasColor.g, b: canvasColor.b };
+ const appearance = resolveAppearance(value, canvas);
+
+ const accentColor = pick(
+ "focusBorder",
+ "button.background",
+ "textLink.foreground",
+ "activityBarBadge.background",
+ "progressBar.background",
+ "badge.background",
+ );
+ const canvasHex = toHex(canvas);
+ const accentHex = accentColor ? flattenOver(accentColor, canvas) : null;
+
+ // The derived palette is the floor: every role starts contrast-solved, then
+ // the theme's own workbench colors replace what it actually specified. The
+ // floor derives from a muted accent -- the vivid engine carries the accent
+ // hue into every surface, which washes an imported neutral palette (a gray
+ // theme with a blue focusBorder would get blue code and text surfaces).
+ const mutedAccentHex = accentColor
+ ? flattenOver({ r: accentColor.r, g: accentColor.g, b: accentColor.b, a: 0.2 }, canvas)
+ : null;
+ const derived = createVividThemeColors(appearance, canvasHex, mutedAccentHex ?? canvasHex);
+ const sidebarHex =
+ solidOver(canvas, "sideBar.background", "activityBar.background") ?? derived.sidebar;
+ const sidebar = hexToRgb(sidebarHex);
+ const terminalHex =
+ solidOver(canvas, "terminal.background", "panel.background") ?? derived.terminalBackground;
+ const terminal = hexToRgb(terminalHex);
+
+ /** Foregrounds only win when they stay readable on the surface they land on;
+ * a theme tuned for its own chrome can be unreadable on ours. */
+ const readableOn = (
+ surface: string,
+ fallback: string,
+ ...keys: ReadonlyArray<string>
+ ): string => {
+ const surfaceRgb = hexToRgb(surface);
+ const isReadable = (candidate: string) => contrastRatio(hexToRgb(candidate), surfaceRgb) >= 4.5;
+ const specified = solidOver(surfaceRgb, ...keys);
+ if (specified && isReadable(specified)) return specified;
+ // The derived fallback was solved against the derived surface. When the
+ // file replaced that surface (a light sideBar in a dark theme, say), the
+ // fallback has to clear the bar there too, or the text falls back to the
+ // readable end of the greyscale for the surface actually in play.
+ if (isReadable(fallback)) return fallback;
+ return relativeLuminance(surfaceRgb) < 0.179 ? "#ffffff" : "#000000";
+ };
+
+ const overrides: Partial<Record<ThemeColorRole, string>> = {
+ canvas: canvasHex,
+ text: readableOn(canvasHex, derived.text, "editor.foreground", "foreground"),
+ textMuted: readableOn(
+ canvasHex,
+ derived.textMuted,
+ "descriptionForeground",
+ "disabledForeground",
+ ),
+ surface: solidOver(canvas, "editorWidget.background") ?? derived.surface,
+ surfaceRaised:
+ solidOver(canvas, "editorWidget.background", "dropdown.background") ?? derived.surfaceRaised,
+ surfaceOverlay:
+ solidOver(canvas, "menu.background", "quickInput.background", "dropdown.background") ??
+ derived.surfaceOverlay,
+ border:
+ solidOver(canvas, "panel.border", "editorGroup.border", "contrastBorder") ?? derived.border,
+ input: solidOver(canvas, "input.border", "dropdown.border") ?? derived.input,
+ placeholder: readableOn(canvasHex, derived.placeholder, "input.placeholderForeground"),
+ error: readableOn(canvasHex, derived.error, "editorError.foreground", "errorForeground"),
+ warning: readableOn(canvasHex, derived.warning, "editorWarning.foreground"),
+ accentSurface:
+ solidOver(canvas, "list.activeSelectionBackground", "list.hoverBackground") ??
+ derived.accentSurface,
+ codeBackground: solidOver(canvas, "textCodeBlock.background") ?? derived.codeBackground,
+ sidebar: sidebarHex,
+ sidebarForeground: readableOn(sidebarHex, derived.sidebarForeground, "sideBar.foreground"),
+ sidebarBorder: solidOver(sidebar, "sideBar.border") ?? derived.sidebarBorder,
+ sidebarRowHover: solidOver(sidebar, "list.hoverBackground") ?? derived.sidebarRowHover,
+ sidebarRowActive:
+ solidOver(sidebar, "list.inactiveSelectionBackground", "list.hoverBackground") ??
+ derived.sidebarRowActive,
+ sidebarRowSelected:
+ solidOver(sidebar, "list.activeSelectionBackground") ?? derived.sidebarRowSelected,
+ terminalBackground: terminalHex,
+ terminalForeground: readableOn(terminalHex, derived.terminalForeground, "terminal.foreground"),
+ terminalCursor:
+ solidOver(terminal, "terminalCursor.foreground", "editorCursor.foreground") ??
+ derived.terminalCursor,
+ terminalSelection:
+ solidOver(terminal, "terminal.selectionBackground", "editor.selectionBackground") ??
+ derived.terminalSelection,
+ terminalScrollbar:
+ solidOver(terminal, "scrollbarSlider.background") ?? derived.terminalScrollbar,
+ };
+ if (accentHex) {
+ overrides.accent = accentHex;
+ overrides.focus = accentHex;
+ // The button pair is the closest thing VS Code has to our action color.
+ const actionHex = solidOver(canvas, "button.background") ?? accentHex;
+ overrides.messageAction = actionHex;
+ overrides.messageActionForeground = readableOn(
+ actionHex,
+ derived.messageActionForeground,
+ "button.foreground",
+ );
+ overrides.accentForeground = readableOn(
+ accentHex,
+ derived.accentForeground,
+ "button.foreground",
+ );
+ }
+
+ // Reuse the theme-file parser so ids, names, and color values go through the
+ // same validation as a hand-written file.
+ return parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: resolveName(value),
+ appearance,
+ colors: { ...derived, ...overrides },
+ });
+}
+
+/**
+ * Extensions ship a family of themes (GitHub: dark, light, dark-colorblind,
+ * light-colorblind, dark-dimmed, ...). When several are imported together,
+ * a light and a dark file whose names differ only by the appearance word
+ * become one dual-mode theme; everything else stays its own theme.
+ */
+export function pairVsCodeThemes(
+ themes: ReadonlyArray<ThemeDefinition>,
+): ReadonlyArray<ThemeDefinition> {
+ const stripAppearance = (label: string) =>
+ label
+ .replace(/\b(?:light|dark)\b/gi, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ type Group = { light: ThemeDefinition[]; dark: ThemeDefinition[]; order: number };
+ const groups = new Map<string, Group>();
+ const passthrough: Array<{ theme: ThemeDefinition; order: number }> = [];
+ themes.forEach((theme, order) => {
+ // Only single-appearance themes with an appearance word in the name can
+ // pair; anything else is already what the user asked for.
+ const key = stripAppearance(theme.label);
+ if (getThemeModes(theme).length !== 1 || key === theme.label || key.length === 0) {
+ passthrough.push({ theme, order });
+ return;
+ }
+ const group = groups.get(key) ?? { light: [], dark: [], order };
+ group[theme.appearance].push(theme);
+ groups.set(key, group);
+ });
+
+ const paired: Array<{ theme: ThemeDefinition; order: number }> = [];
+ for (const [key, group] of groups) {
+ // Ambiguity (two darks for one light) is not guessed at, and a pair
+ // whose stripped name collides with a built-in id ("Grove Light" +
+ // "Grove Dark" -> the reserved "grove") stays two single themes rather
+ // than failing the whole batch.
+ if (group.light.length === 1 && group.dark.length === 1) {
+ try {
+ paired.push({
+ order: group.order,
+ theme: parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: key,
+ appearance: "light",
+ colors: group.light[0]!.colors,
+ variants: { dark: group.dark[0]!.colors },
+ }),
+ });
+ continue;
+ } catch {
+ // Fall through to the individual themes below.
+ }
+ }
+ for (const theme of [...group.light, ...group.dark]) {
+ paired.push({ theme, order: group.order });
+ }
+ }
+
+ return [...passthrough, ...paired].sort((a, b) => a.order - b.order).map((entry) => entry.theme);
+}
+
+/**
+ * Some extensions reuse one display name across every file: Dracula ships
+ * dracula.json and dracula-soft.json that both say "Dracula". When a batch
+ * carries the same id twice, the file names are the only thing that tells
+ * the variants apart, so colliding entries are relabelled from their file
+ * name (and numbered only when even that collides).
+ */
+export function resolveThemeLabelCollisions(
+ entries: ReadonlyArray<{ theme: ThemeDefinition; sourceName?: string | undefined }>,
+): ReadonlyArray<ThemeDefinition> {
+ // Null when the new name is unusable (reserved id, invalid characters).
+ const rename = (theme: ThemeDefinition, name: string): ThemeDefinition | null => {
+ try {
+ return parseThemeFile({
+ version: THEME_FILE_VERSION,
+ name: name.slice(0, 48),
+ appearance: theme.appearance,
+ colors: theme.colors,
+ ...(theme.variants ? { variants: theme.variants } : {}),
+ ...(theme.managed ? { managed: true } : {}),
+ });
+ } catch {
+ return null;
+ }
+ };
+
+ const counts = new Map<string, number>();
+ for (const entry of entries) {
+ counts.set(entry.theme.id, (counts.get(entry.theme.id) ?? 0) + 1);
+ }
+ const relabelled = entries.map(({ theme, sourceName }) => {
+ if ((counts.get(theme.id) ?? 0) < 2) return theme;
+ const stem = sourceName?.replace(/\.[^.]+$/, "");
+ const fromFile = stem ? humanizeThemeName(stem) : null;
+ const renamed =
+ fromFile && fromFile.toLowerCase() !== theme.label.toLowerCase()
+ ? rename(theme, fromFile)
+ : null;
+ return renamed ?? theme;
+ });
+
+ const seen = new Set<string>();
+ return relabelled.map((theme) => {
+ if (!seen.has(theme.id)) {
+ seen.add(theme.id);
+ return theme;
+ }
+ for (let suffix = 2; suffix < 100; suffix += 1) {
+ const candidate = rename(theme, `${theme.label} ${suffix}`);
+ if (candidate && !seen.has(candidate.id)) {
+ seen.add(candidate.id);
+ return candidate;
+ }
+ }
+ return theme;
+ });
+}
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index d94d3dc2d..f7f6facbe 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -40,6 +40,12 @@ Commands are IDs like `terminal.toggle`, `commandPalette.toggle`, `preview.refre
`filePicker.toggle` opens file search for the active project and defaults to `mod+p`.
`projectSearch.toggle` searches inside the active project's files and defaults to `mod+shift+f`.
Repeating either shortcut closes that search, and switching shortcuts replaces the open search.
+`themeEditor.toggle` opens or closes the floating theme editor and defaults to
+`mod+alt+shift+t`. Select a color label to spotlight the elements that use it; select the label
+again to clear the spotlight. The swatch and hex field keep that color selected while you edit it.
+Use **Inspect** to pick an element in the app and reveal its color token. Inspect disarms after one
+successful pick; its hover glow and badge preview the element and token that click will select.
+**Cancel** or `Escape` exits Inspect and clears its selection and spotlight.
The command palette searches active thread titles, projects, branches, user messages, and final
agent responses across connected environments. Message matches show one labeled excerpt while
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 43167bbf0..64ef755ee 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -440,6 +440,23 @@ export const PickFolderOptionsSchema = Schema.Struct({
targetEnvironmentId: Schema.optionalKey(Schema.String),
});
+/**
+ * A file returned by the desktop theme-file picker. Oversized files carry an
+ * empty text so the renderer can reject them by size without the main
+ * process ever holding their contents.
+ */
+export interface PickedThemeFile {
+ name: string;
+ size: number;
+ text: string;
+}
+
+export const PickedThemeFileSchema = Schema.Struct({
+ name: Schema.String,
+ size: Schema.Number,
+ text: Schema.String,
+});
+
export interface DesktopWslDistro {
name: string;
isDefault: boolean;
@@ -1019,6 +1036,12 @@ export interface DesktopBridge {
setWslDistro: (distro: string | null) => Promise<DesktopWslState>;
setWslOnly: (enabled: boolean) => Promise<DesktopWslState>;
pickFolder: (options?: PickFolderOptions) => Promise<string | null>;
+ /**
+ * Multi-select JSON file picker that opens in the VS Code extensions
+ * directory when one exists. Optional: older desktop builds lack it, and
+ * web callers fall back to a plain file input.
+ */
+ pickThemeFiles?: () => Promise<readonly PickedThemeFile[] | null>;
confirm: (message: string) => Promise<boolean>;
setTheme: (theme: DesktopTheme) => Promise<void>;
showContextMenu: <T extends string>(
diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts
index ec8c839be..342e44678 100644
--- a/packages/contracts/src/keybindings.test.ts
+++ b/packages/contracts/src/keybindings.test.ts
@@ -72,6 +72,12 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsedProjectSearch.command, "projectSearch.toggle");
+ const parsedThemeEditor = yield* decode(KeybindingRule, {
+ key: "mod+alt+shift+t",
+ command: "themeEditor.toggle",
+ });
+ assert.strictEqual(parsedThemeEditor.command, "themeEditor.toggle");
+
const parsedLocal = yield* decode(KeybindingRule, {
key: "mod+shift+n",
command: "chat.newLocal",
diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts
index 88867bd8a..3fcbf6ef5 100644
--- a/packages/contracts/src/keybindings.ts
+++ b/packages/contracts/src/keybindings.ts
@@ -65,6 +65,7 @@ const STATIC_KEYBINDING_COMMANDS = [
"commandPalette.toggle",
"filePicker.toggle",
"projectSearch.toggle",
+ "themeEditor.toggle",
"composer.stash",
"chat.new",
"chat.newLocal",
diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.ts
index 6add9f478..158a9ffb1 100644
--- a/packages/shared/src/keybindings.ts
+++ b/packages/shared/src/keybindings.ts
@@ -37,6 +37,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+p", command: "filePicker.toggle", when: "!terminalFocus" },
{ key: "mod+shift+f", command: "projectSearch.toggle", when: "!terminalFocus" },
+ { key: "mod+alt+shift+t", command: "themeEditor.toggle" },
{ key: "mod+s", command: "composer.stash", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },