diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 035146fcbab..635fce9b16f 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -6100,7 +6100,7 @@ "src/renderer/src/components/terminal-pane/provider-notices/codex-backfill/codex-backfill-error-detector.test.ts": 26, "src/renderer/src/components/terminal-pane/account-restart/detached/codex-detached-pane-restart.test.ts": 2270, "src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-shared-server-banner.test.tsx": 2766, - "src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.test.ts": 76, + "src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts": 76, "src/renderer/src/components/terminal-pane/pty-connection/output/deferred-reattach-live-data-queue.test.ts": 184, "src/renderer/src/components/terminal-pane/layout/split/deferred-split-pane-handoff.test.ts": 78, "src/renderer/src/components/terminal-pane/viewport/desktop-fit-fallback.test.ts": 92, diff --git a/src/main/claude/claude-hook-event-versions.ts b/src/main/claude/claude-hook-event-versions.ts index cc64aab2b7c..3321a3703d1 100644 --- a/src/main/claude/claude-hook-event-versions.ts +++ b/src/main/claude/claude-hook-event-versions.ts @@ -26,6 +26,9 @@ export const CLAUDE_HOOK_EVENT_FIRST_VERSIONS = { // Older CLIs reject the whole settings file on an unknown top-level key. export const CLAUDE_STATUS_LINE_FIRST_VERSION = '1.0.64' +// Before this, a `theme` naming a custom theme is ignored, or (1.0.49 to 1.0.66) voids settings.json. +const CLAUDE_CUSTOM_THEME_FIRST_VERSION = '2.1.119' + // Exec-form hooks (`args`) spawn without a shell, so a spaced path needs no quoting. const CLAUDE_HOOK_EXEC_FORM_FIRST_VERSION = '2.1.139' @@ -71,6 +74,10 @@ export function claudeKnowsStatusLine(version: string | null | undefined): boole return claudeKnowsSince(version, CLAUDE_STATUS_LINE_FIRST_VERSION) } +export function claudeLoadsCustomThemes(version: string | null | undefined): boolean { + return claudeVersionReaches(version, CLAUDE_CUSTOM_THEME_FIRST_VERSION) +} + // Unknown versions keep the shell form because an older CLI ignores `args`. export function claudeAcceptsExecFormHooks(version: string | null | undefined): boolean { return claudeVersionReaches(version, CLAUDE_HOOK_EXEC_FORM_FIRST_VERSION) diff --git a/src/main/claude/theme-sync/claude-code-theme-ownership.ts b/src/main/claude/theme-sync/claude-code-theme-ownership.ts new file mode 100644 index 00000000000..c3c241a29fb --- /dev/null +++ b/src/main/claude/theme-sync/claude-code-theme-ownership.ts @@ -0,0 +1,93 @@ +import { readFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import { isPlainObject, parseHooksJsonText } from '../../agent-hooks/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +import { withManagedHookInstallLock } from '../../agent-hooks/managed-hook-install-lock' + +/** What Orca replaced in one config dir's settings.json, so turning the sync off can put it back. */ +export type ClaudeThemeOwnership = { + /** The Orca profile (userData path) that took over; only it restores, so builds with different settings do not fight. */ + owner: string + /** null when settings.json had no theme. */ + previousTheme: string | null + /** The user picked another theme after Orca's; Orca stops writing it. */ + userChangedTheme?: true +} + +type OwnershipByConfigDir = Map + +// Why under ~/.orca, not userData: every Orca build on this machine must agree on what it replaced. +function ownershipPath(): string { + return join(homedir(), '.orca', 'claude-theme-sync.json') +} + +/** Every config dir Orca took over, keyed by path; null when the record exists but cannot be read. */ +export async function readClaudeThemeOwnership(): Promise { + let raw: string + try { + raw = await readFile(ownershipPath(), 'utf-8') + } catch (error) { + return isDefinitiveAbsence(error) ? new Map() : null + } + const parsed = parseHooksJsonText(raw) + if (!parsed) { + return null + } + const owned: OwnershipByConfigDir = new Map() + for (const [dir, entry] of Object.entries(parsed)) { + const previous = isPlainObject(entry) ? entry.previousTheme : undefined + if ( + isPlainObject(entry) && + typeof entry.owner === 'string' && + (typeof previous === 'string' || previous === null) + ) { + owned.set(dir, { + owner: entry.owner, + previousTheme: previous, + ...(entry.userChangedTheme === true ? { userChangedTheme: true } : {}) + }) + } + } + return owned +} + +/** One config dir's record, read and written under Orca's managed-hook lock. */ +export type ClaudeThemeOwnershipSlot = { + entry: ClaudeThemeOwnership | undefined + /** Saves `next` (undefined removes it) before the caller goes on. */ + save: (next: ClaudeThemeOwnership | undefined) => Promise +} + +/** + * Runs `edit` with a fresh read of `configDir`'s record under Orca's cross-process managed-hook lock, + * so two Orca builds never drop each other's entries or edit settings.json for the theme at once. + */ +export async function withClaudeThemeOwnership( + configDir: string, + edit: (slot: ClaudeThemeOwnershipSlot) => Promise +): Promise { + return await withManagedHookInstallLock(homedir(), undefined, async () => { + const owned = await readClaudeThemeOwnership() + if (!owned) { + throw new Error(`Cannot read ${ownershipPath()}`) + } + return await edit({ + entry: owned.get(configDir), + save: async (next) => { + if (next) { + owned.set(configDir, next) + } else if (!owned.delete(configDir)) { + return + } + await writeHooksJsonAsync(ownershipPath(), Object.fromEntries(owned)) + } + }) + }) +} + +/** Holds the same lock as record edits, so a reload retry never republishes a file another Orca just replaced. */ +export async function withClaudeThemeFileLock(run: () => Promise): Promise { + return await withManagedHookInstallLock(homedir(), undefined, run) +} diff --git a/src/main/claude/theme-sync/claude-code-theme-sync-schedule.ts b/src/main/claude/theme-sync/claude-code-theme-sync-schedule.ts new file mode 100644 index 00000000000..e7d5718fce2 --- /dev/null +++ b/src/main/claude/theme-sync/claude-code-theme-sync-schedule.ts @@ -0,0 +1,143 @@ +import { readFile } from 'node:fs/promises' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { resolveTerminalPalette } from '../../../shared/terminal-themes/terminal-theme-selection' +import { claudeCodeThemeFromTerminal } from './claude-code-theme' +import { withClaudeThemeFileLock } from './claude-code-theme-ownership' +import { + replaceFile, + syncClaudeCodeThemeConfigDirs, + type ClaudeCodeThemeSyncTarget +} from './claude-code-theme-sync' + +const SYNC_DEBOUNCE_MS = 250 +// Why: Claude Code reloads a theme only on a file event, and macOS drops some of them under load; +// each later replace is another chance, spaced out to outlast a stalled event stream. +const RELOAD_RETRY_DELAYS_MS = [1_500, 5_000, 15_000, 45_000, 120_000, 300_000] +// Catches a theme picked in Claude Code, a new account home, or a pass that failed, without polling. +const FOCUS_RESYNC_MS = 60_000 + +type SyncSettings = Pick & + Parameters[0] + +/** Replaces the file again with the theme it holds; odd attempts add a newline so the size changes too. + * A session that already reloaded parses the same theme and does not repaint. */ +async function republishThemeFile(path: string, attempt: number): Promise { + const content = await readFile(path, 'utf-8').catch(() => null) + if (content !== null) { + const canonical = `${content.trimEnd()}\n` + await replaceFile(path, attempt % 2 === 0 ? `${canonical}\n` : canonical) + } +} + +/** Null while on but the palette has no readable colors: Orca then leaves Claude Code as it is. */ +function syncTarget( + settings: SyncSettings, + systemPrefersDark: boolean +): ClaudeCodeThemeSyncTarget | null { + const theme = claudeCodeThemeFromTerminal( + resolveTerminalPalette(settings, systemPrefersDark).theme + ) + if (settings.claudeCodeThemeSync === false) { + return { enabled: false, terminalBase: theme?.base ?? 'dark' } + } + return theme ? { enabled: true, theme } : null +} + +const SYNC_SETTING_KEYS: readonly (keyof GlobalSettings)[] = [ + 'claudeCodeThemeSync', + 'theme', + 'terminalThemeDark', + 'terminalThemeLight', + 'terminalUseSeparateLightTheme', + 'terminalCustomThemes', + 'terminalPluginPalettes', + 'terminalColorOverrides', + 'terminalColorOverridesLight', + 'pluginSystemEnabled', + 'disabledPlugins' +] + +function warnSyncFailed(error: unknown): void { + console.warn('[claude-theme] Sync failed:', error) +} + +/** Keeps Claude Code's theme on the terminal palette while the setting is on, and restores it when turned off. */ +export function startClaudeCodeThemeSync(host: { + getSettings: () => SyncSettings + onSettingsChanged: (listener: (updates: Partial) => void) => unknown + systemPrefersDark: () => boolean + onSystemThemeChanged: (listener: () => void) => unknown + onAppFocused: (listener: () => void) => unknown + userDataPath: string +}): void { + let lastSynced: string | null = null + let lastForcedAt = Date.now() + let restorePending = false + let timer: ReturnType | null = null + // Per file, so a pass that touches one config folder keeps another folder's pending retries. + const retryTimers = new Map[]>() + let queue = Promise.resolve() + const cancelReloadRetries = (path: string): void => { + retryTimers.get(path)?.forEach(clearTimeout) + retryTimers.delete(path) + } + const scheduleReloadRetries = (path: string): void => { + cancelReloadRetries(path) + retryTimers.set( + path, + RELOAD_RETRY_DELAYS_MS.map((delay, attempt) => + setTimeout(() => { + queue = queue + .then(() => withClaudeThemeFileLock(() => republishThemeFile(path, attempt))) + .catch(warnSyncFailed) + }, delay) + ) + ) + } + const sync = (force = false): void => { + timer = null + const target = syncTarget(host.getSettings(), host.systemPrefersDark()) + const key = JSON.stringify(target) + if (!target || (key === lastSynced && !force)) { + return + } + lastSynced = key + queue = queue + .then(async () => { + const result = await syncClaudeCodeThemeConfigDirs(target, host.userDataPath) + restorePending = result.restorePending + if (!target.enabled) { + // Off: keep retrying only the files this pass restored. + for (const path of retryTimers.keys()) { + if (!result.replaced.includes(path)) { + cancelReloadRetries(path) + } + } + } + new Set(result.replaced).forEach(scheduleReloadRetries) + }) + .catch(warnSyncFailed) + } + const schedule = (): void => { + if (timer) { + clearTimeout(timer) + } + timer = setTimeout(sync, SYNC_DEBOUNCE_MS) + } + host.onSettingsChanged((updates) => { + if (SYNC_SETTING_KEYS.some((key) => key in updates)) { + schedule() + } + }) + host.onSystemThemeChanged(schedule) + host.onAppFocused(() => { + if ( + (host.getSettings().claudeCodeThemeSync !== false || restorePending) && + Date.now() - lastForcedAt > FOCUS_RESYNC_MS + ) { + lastForcedAt = Date.now() + sync(true) + } + }) + sync() +} diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.test.ts b/src/main/claude/theme-sync/claude-code-theme-sync.test.ts new file mode 100644 index 00000000000..7163f01a89f --- /dev/null +++ b/src/main/claude/theme-sync/claude-code-theme-sync.test.ts @@ -0,0 +1,142 @@ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as ClaudeHookEventVersions from '../claude-hook-event-versions' + +vi.mock('../claude-hook-event-versions', async (importOriginal) => ({ + ...(await importOriginal()), + probeRecentClaudeCliVersion: () => Promise.resolve(claudeVersion) +})) +let claudeVersion: string | null = '2.1.319' +import { syncClaudeCodeThemeConfigDirs } from './claude-code-theme-sync' +import { claudeCodeThemeFromTerminal } from './claude-code-theme' +import { TERMINAL_THEME_CATALOG } from '../../../shared/terminal-themes/terminal-theme-catalog' +import { contrastRatio } from '../../../shared/color/rgba-contrast' +import { parseTerminalColor } from '../../../shared/terminal-themes/terminal-title-contrast' + +const THEME = { name: 'Orca', base: 'dark', overrides: { claude: '#7aa2f7' } } +const on = { enabled: true, theme: THEME } as const +const off = { enabled: false, terminalBase: 'dark' } as const + +describe('Claude Code theme sync', () => { + let home: string + let configDir: string + let settingsPath: string + const readSettings = () => JSON.parse(readFileSync(settingsPath, 'utf-8')) + const writeSettings = (value: unknown) => writeFileSync(settingsPath, JSON.stringify(value)) + const sync = (target: typeof on | typeof off) => + syncClaudeCodeThemeConfigDirs(target, join(home, 'userData')) + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'orca-claude-theme-sync-')) + configDir = join(home, 'claude-config') + settingsPath = join(configDir, 'settings.json') + mkdirSync(configDir) + vi.stubEnv('HOME', home) + vi.stubEnv('USERPROFILE', home) + vi.stubEnv('CLAUDE_CONFIG_DIR', configDir) + }) + + afterEach(() => { + vi.unstubAllEnvs() + rmSync(home, { recursive: true, force: true }) + }) + + it('selects the Orca theme beside the user keys and restores the replaced theme', async () => { + writeSettings({ theme: 'light', hooks: { Stop: [] } }) + await sync(on) + expect(readSettings()).toEqual({ theme: 'custom:orca', hooks: { Stop: [] } }) + expect(JSON.parse(readFileSync(join(configDir, 'themes', 'orca.json'), 'utf-8'))).toEqual(THEME) + + await sync(off) + expect(readSettings()).toEqual({ theme: 'light', hooks: { Stop: [] } }) + // Running sessions keep reading the file, so it takes the restored look. + expect(JSON.parse(readFileSync(join(configDir, 'themes', 'orca.json'), 'utf-8'))).toEqual({ + name: 'Orca', + base: 'light', + overrides: {} + }) + }) + + it('removes the theme key it added when there was none', async () => { + writeSettings({ model: 'opus' }) + await sync(on) + await sync(off) + expect(readSettings()).toEqual({ model: 'opus' }) + }) + + it('stops writing once the user picks another theme, and leaves it on disable', async () => { + writeSettings({ theme: 'dark' }) + await sync(on) + writeSettings({ theme: 'light-daltonized' }) + await sync(on) + await sync(on) + expect(readSettings()).toEqual({ theme: 'light-daltonized' }) + await sync(off) + expect(readSettings()).toEqual({ theme: 'light-daltonized' }) + }) + + it('leaves a colorblind or custom theme the user picked alone', async () => { + writeSettings({ theme: 'dark-daltonized' }) + await sync(on) + expect(readSettings()).toEqual({ theme: 'dark-daltonized' }) + }) + + it('leaves settings alone for a Claude Code without custom themes', async () => { + claudeVersion = '2.1.118' + writeSettings({ theme: 'dark' }) + await sync(on) + claudeVersion = '2.1.319' + expect(readSettings()).toEqual({ theme: 'dark' }) + }) + + it.skipIf(process.platform === 'win32')( + 'takes over later when the settings write fails, instead of treating it as the user’s pick', + async () => { + writeSettings({ theme: 'dark' }) + mkdirSync(join(configDir, 'themes')) + chmodSync(configDir, 0o555) + try { + await sync(on) + } finally { + chmodSync(configDir, 0o755) + } + expect(readSettings()).toEqual({ theme: 'dark' }) + await sync(on) + expect(readSettings()).toEqual({ theme: 'custom:orca' }) + } + ) + + it('never rewrites a settings file it cannot parse', async () => { + writeFileSync(settingsPath, '{ "theme": "dark", ') + await sync(on) + expect(readFileSync(settingsPath, 'utf-8')).toBe('{ "theme": "dark", ') + }) + + it('leaves Claude Code alone when its config dir does not exist', async () => { + rmSync(configDir, { recursive: true }) + await sync(on) + expect(() => readFileSync(settingsPath)).toThrow() + }) +}) + +describe('Claude Code theme from the terminal palette', () => { + it.each(['Solarized Light', 'Solarized Dark', 'Builtin Tango Light', 'Gruvbox Light'])( + 'keeps %s text and hues readable on its background', + (name) => { + const palette = TERMINAL_THEME_CATALOG[name] + const theme = claudeCodeThemeFromTerminal(palette) + const background = parseTerminalColor(palette.background) + const ratio = (key: string): number => { + const color = parseTerminalColor(theme?.overrides[key]) + return color && background ? contrastRatio(color, background) : 0 + } + expect(ratio('text')).toBeGreaterThanOrEqual(4.5) + expect(ratio('inactive')).toBeGreaterThanOrEqual(4.5) + for (const key of ['claude', 'success', 'error', 'warning', 'permission']) { + expect(ratio(key)).toBeGreaterThanOrEqual(3) + } + } + ) +}) diff --git a/src/main/claude/theme-sync/claude-code-theme-sync.ts b/src/main/claude/theme-sync/claude-code-theme-sync.ts new file mode 100644 index 00000000000..7b4233a2d8f --- /dev/null +++ b/src/main/claude/theme-sync/claude-code-theme-sync.ts @@ -0,0 +1,270 @@ +import { randomUUID } from 'node:crypto' +import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' +import { readHooksJson } from '../../agent-hooks/hooks-json-read' +import { writeHooksJson } from '../../agent-hooks/installer-utils' +import { defaultClaudeConfigDir } from '../claude-config-dir-pin' +import { listClaudeProfileHomesAsync } from '../../claude-accounts/claude-profile-homes' +import { + getClaudeObservedConfigDirs, + getClaudeProfileRouter +} from '../../claude-accounts/claude-profile-installed-router' +import { resolveClaudeCommand } from '../../codex-cli/command' +import { claudeLoadsCustomThemes, probeRecentClaudeCliVersion } from '../claude-hook-event-versions' +import type { ClaudeCodeTheme } from './claude-code-theme' +import { + readClaudeThemeOwnership, + withClaudeThemeOwnership, + type ClaudeThemeOwnership +} from './claude-code-theme-ownership' + +const THEME_SETTING = 'custom:orca' +// Why only these: colorblind and ANSI-only themes, and the user's own custom ones, were picked on purpose. +const REPLACEABLE_THEMES = new Set(['dark', 'light', 'auto']) + +export type ClaudeCodeThemeSyncTarget = + | { enabled: true; theme: ClaudeCodeTheme } + | { enabled: false; terminalBase: string } + +function themeFilePath(configDir: string): string { + return join(configDir, 'themes', 'orca.json') +} + +/** Atomic so Claude Code's theme watcher never reads a half-written file. */ +export async function replaceFile(path: string, content: string): Promise { + // Why not .json: Claude Code only loads .json files, so it never sees the temp file as a theme. + const tmp = join(dirname(path), `.orca-${randomUUID()}.tmp`) + try { + await writeFile(tmp, content, 'utf-8') + await rename(tmp, path) + } finally { + await rm(tmp, { force: true }) + } +} + +/** Returns the path when it replaced the file, for the reload retry. */ +async function writeThemeFile(configDir: string, theme: ClaudeCodeTheme): Promise { + const path = themeFilePath(configDir) + const serialized = `${JSON.stringify(theme, null, 2)}\n` + // trimEnd: a reload retry may have left one extra newline. + if ((await readFile(path, 'utf-8').catch(() => null))?.trimEnd() === serialized.trimEnd()) { + return [] + } + await mkdir(dirname(path), { recursive: true }) + await replaceFile(path, serialized) + return [path] +} + +function isReplaceableTheme(theme: unknown): boolean { + return theme === undefined || (typeof theme === 'string' && REPLACEABLE_THEMES.has(theme)) +} + +async function applyToConfigDir( + configDir: string, + theme: ClaudeCodeTheme, + owner: string, + recorded: ClaudeThemeOwnership | undefined +): Promise { + // The file goes first so settings never name a theme Claude Code cannot load. + const replaced = await writeThemeFile(configDir, theme) + const settingsPath = join(configDir, 'settings.json') + const unlocked = readHooksJson(settingsPath) + if (!unlocked) { + console.warn(`[claude-theme] Skipping ${settingsPath}: it is not valid JSON`) + return replaced + } + // Lock-free check: most passes leave settings.json and the record as they are. + const mayChange = recorded + ? !recorded.userChangedTheme && unlocked.theme !== THEME_SETTING + : isReplaceableTheme(unlocked.theme) + // Probe outside the lock: it spawns Claude Code, and only a first takeover needs it. + if ( + !mayChange || + (!recorded && + !claudeLoadsCustomThemes(await probeRecentClaudeCliVersion(resolveClaudeCommand()))) + ) { + return replaced + } + await withClaudeThemeOwnership(configDir, async ({ entry, save }) => { + if (entry?.userChangedTheme) { + return + } + // Why sync reads and writes: Orca's in-process hook installer edits this file synchronously. + const settings = readHooksJson(settingsPath) + if (!settings) { + return + } + if (entry) { + if (settings.theme !== THEME_SETTING) { + await save({ ...entry, userChangedTheme: true }) + } + return + } + if (!isReplaceableTheme(settings.theme)) { + return + } + // Under the lock, so another Orca's restore cannot leave its look in the file Orca now selects. + replaced.push(...(await writeThemeFile(configDir, theme))) + // The record lands first: a crash between the two writes must still leave a way back. + await save({ + owner, + previousTheme: typeof settings.theme === 'string' ? settings.theme : null + }) + // Reread after the last await: Claude Code or the hook installer may have saved meanwhile. + const current = readHooksJson(settingsPath) + if (!current || current.theme !== settings.theme) { + await save(undefined) + return + } + try { + writeHooksJson(settingsPath, { ...current, theme: THEME_SETTING }) + } catch (error) { + // Without this, the next pass would read the unchanged theme as the user's own pick. + await save(undefined) + throw error + } + }).catch((error: unknown) => { + console.warn(`[claude-theme] Could not select the Orca theme in ${settingsPath}:`, error) + }) + return replaced +} + +/** The look Orca's theme file takes on once released, so running sessions show the restored theme. */ +function releasedTheme(previousTheme: string | null, terminalBase: string): ClaudeCodeTheme { + // Claude Code's own default is dark; `auto` follows the terminal background. + const base = + previousTheme === null ? 'dark' : previousTheme === 'auto' ? terminalBase : previousTheme + return { name: 'Orca', base, overrides: {} } +} + +/** Writes the replaced theme back into settings.json; the theme to show running sessions, if it reverted. */ +function revertSettings( + settingsPath: string, + entry: ClaudeThemeOwnership, + dirState: 'present' | 'gone' | 'unreadable' +): { restored: boolean; previousTheme?: string | null } { + const settings = + dirState === 'unreadable' ? null : dirState === 'present' ? readHooksJson(settingsPath) : {} + if (!settings) { + console.warn(`[claude-theme] Could not restore ${settingsPath} yet`) + return { restored: false } + } + if (entry.userChangedTheme) { + return { restored: true } + } + if (settings.theme !== THEME_SETTING) { + // Already reverted by a pass whose theme-file write failed; that write is still owed. + const reverted = settings.theme === (entry.previousTheme ?? undefined) + return reverted ? { restored: true, previousTheme: entry.previousTheme } : { restored: true } + } + const { theme: _orcaTheme, ...rest } = settings + writeHooksJson( + settingsPath, + entry.previousTheme === null ? rest : { ...settings, theme: entry.previousTheme } + ) + return { restored: true, previousTheme: entry.previousTheme } +} + +/** Puts the replaced theme back; false keeps the record while settings.json or its dir cannot be read. */ +async function restoreConfigDir( + configDir: string, + recorded: ClaudeThemeOwnership, + terminalBase: string, + publishedThemeFiles: Set +): Promise<{ restored: boolean; replaced: string[] }> { + const dirState = await stat(configDir).then( + () => 'present' as const, + (error: unknown) => (isDefinitiveAbsence(error) ? ('gone' as const) : ('unreadable' as const)) + ) + const settingsPath = join(configDir, 'settings.json') + return await withClaudeThemeOwnership(configDir, async ({ entry, save }) => { + if (!entry || entry.owner !== recorded.owner) { + return { restored: true, replaced: [] } + } + const reverted = revertSettings(settingsPath, entry, dirState) + if (!reverted.restored) { + return { restored: false, replaced: [] } + } + // Why: account homes can share the default's themes folder; the first restored look wins. + const themeFile = await realpath(themeFilePath(configDir)).catch(() => themeFilePath(configDir)) + let replaced: string[] = [] + if (reverted.previousTheme !== undefined && !publishedThemeFiles.has(themeFile)) { + // Under the lock and before the record goes, so a failed write is retried and cannot + // overwrite the theme another Orca selects right after. + replaced = await writeThemeFile( + configDir, + releasedTheme(reverted.previousTheme, terminalBase) + ) + publishedThemeFiles.add(themeFile) + } + await save(undefined) + return { restored: true, replaced } + }).catch((error: unknown) => { + console.warn(`[claude-theme] Could not restore ${settingsPath} yet:`, error) + return { restored: false, replaced: [] } + }) +} + +/** Where Claude Code runs from Orca: the user's own folder, account homes, and folders hooks reported. */ +async function claudeConfigDirs(userDataPath: string): Promise { + const router = getClaudeProfileRouter() + return [ + defaultClaudeConfigDir(router ? { CLAUDE_CONFIG_DIR: router.userConfigDir() } : process.env), + ...(await listClaudeProfileHomesAsync(userDataPath)), + ...(getClaudeObservedConfigDirs()?.list() ?? []) + ] +} + +export type ClaudeCodeThemeSyncResult = { + replaced: string[] + /** A restore this profile owes could not finish yet. */ + restorePending: boolean +} + +/** One pass over every Claude Code config dir Orca's terminals can launch with. */ +export async function syncClaudeCodeThemeConfigDirs( + target: ClaudeCodeThemeSyncTarget, + userDataPath: string +): Promise { + const result: ClaudeCodeThemeSyncResult = { replaced: [], restorePending: false } + const owned = await readClaudeThemeOwnership() + if (!owned) { + console.warn('[claude-theme] Skipping sync: Orca cannot read its record of replaced themes') + return { ...result, restorePending: !target.enabled } + } + if (target.enabled) { + for (const dir of new Set(await claudeConfigDirs(userDataPath))) { + const isDir = await stat(dir).then( + (info) => info.isDirectory(), + () => false + ) + if (isDir) { + result.replaced.push( + ...(await applyToConfigDir(dir, target.theme, userDataPath, owned.get(dir)).catch( + (error: unknown) => { + console.warn(`[claude-theme] Could not sync ${dir}:`, error) + return [] + } + )) + ) + } + } + return result + } + const published = new Set() + for (const [dir, entry] of owned) { + if (entry.owner !== userDataPath) { + continue + } + const restore = await restoreConfigDir(dir, entry, target.terminalBase, published).catch( + (error: unknown) => { + console.warn(`[claude-theme] Could not restore ${dir}:`, error) + return { restored: false, replaced: [] } + } + ) + result.replaced.push(...restore.replaced) + result.restorePending ||= !restore.restored + } + return result +} diff --git a/src/main/claude/theme-sync/claude-code-theme.ts b/src/main/claude/theme-sync/claude-code-theme.ts new file mode 100644 index 00000000000..0dc862d33da --- /dev/null +++ b/src/main/claude/theme-sync/claude-code-theme.ts @@ -0,0 +1,101 @@ +import type { ITheme } from '@xterm/xterm' +import { + contrastRatio, + mix, + over, + readableOn, + rgbaToHex, + type Rgba +} from '../../../shared/color/rgba-contrast' +import { terminalPaletteRgba } from '../../../shared/terminal-themes/terminal-palette-rgba' +import { + isTerminalBackgroundLight, + parseTerminalColor +} from '../../../shared/terminal-themes/terminal-title-contrast' + +/** Claude Code's custom theme file: a built-in base plus color overrides, keyed by its own color names. */ +export type ClaudeCodeTheme = { + name: string + /** One of Claude Code's built-in theme names. */ + base: string + overrides: Record +} + +const MIN_TEXT_CONTRAST = 4.5 +// Why 3:1: hues only tint status words and borders, the same floor Orca's own theme gate uses. +const MIN_HUE_CONTRAST = 3 + +/** Claude Code colors from the terminal palette Orca paints, so Claude's own UI matches its pane. */ +export function claudeCodeThemeFromTerminal(palette: ITheme | null): ClaudeCodeTheme | null { + const colors = terminalPaletteRgba(palette, parseTerminalColor) + if (!palette || !colors) { + return null + } + const { background, foreground, color } = colors + const light = isTerminalBackgroundLight(palette.background) + const tint = (hue: Rgba | null, percent: number): Rgba | null => + hue && mix(hue, background, percent) + const surfaces = { + diffAdded: tint(color('green'), 15), + diffRemoved: tint(color('red'), 15), + diffAddedDimmed: tint(color('green'), 8), + diffRemovedDimmed: tint(color('red'), 8), + diffAddedWord: tint(color('green'), 32), + diffRemovedWord: tint(color('red'), 32), + userMessageBackground: mix(foreground, background, 6), + userMessageBackgroundHover: mix(foreground, background, 10), + bashMessageBackgroundColor: mix(foreground, background, 6), + memoryBackgroundColor: mix(foreground, background, 6), + rate_limit_empty: mix(foreground, background, 20) + } + const textSurfaces = [background, ...Object.values(surfaces).filter((value) => value !== null)] + const text = readableOn(foreground, textSurfaces, light, MIN_TEXT_CONTRAST) + const readable = (value: Rgba | null | undefined, minimum = MIN_HUE_CONTRAST): Rgba | null => + value ? readableOn(value, [background], light, minimum) : null + const accent = readable(colors.accent) + const shimmer = (value: Rgba | null): Rgba | null => value && readable(mix(text, value, 35)) + const yellow = readable(color('yellow')) + const blue = readable(color('blue')) + const cyan = readable(color('cyan')) + const selectionColor = parseTerminalColor(palette.selectionBackground) + const selection = selectionColor && over(selectionColor, background) + const overrides: Record = { + claude: accent, + claudeShimmer: shimmer(accent), + promptBorder: accent, + promptBorderShimmer: shimmer(accent), + rate_limit_fill: accent, + briefLabelClaude: accent, + permission: blue, + permissionShimmer: shimmer(blue), + suggestion: cyan, + planMode: cyan, + ide: readable(color('brightCyan')), + remember: yellow, + warning: yellow, + warningShimmer: shimmer(yellow), + autoAccept: yellow, + briefLabelYou: yellow, + success: readable(color('green')), + error: readable(color('red')), + merged: readable(color('magenta')), + bashBorder: readable(color('brightMagenta')), + text, + inverseText: background, + inactive: readable(mix(foreground, background, 60), MIN_TEXT_CONTRAST), + inactiveShimmer: readable(mix(foreground, background, 75), MIN_TEXT_CONTRAST), + subtle: readable(mix(foreground, background, 35)), + ...surfaces, + // Selected text keeps Claude's own highlight when the palette's would hide it. + selectionBg: selection && contrastRatio(text, selection) >= MIN_TEXT_CONTRAST ? selection : null + } + return { + name: 'Orca', + base: light ? 'light' : 'dark', + overrides: Object.fromEntries( + Object.entries(overrides).flatMap(([key, value]) => + value ? [[key, rgbaToHex(value)] as const] : [] + ) + ) + } +} diff --git a/src/main/orca-profiles/new-profile-state.ts b/src/main/orca-profiles/new-profile-state.ts index 6f420ae3b79..a55a5194a26 100644 --- a/src/main/orca-profiles/new-profile-state.ts +++ b/src/main/orca-profiles/new-profile-state.ts @@ -30,7 +30,7 @@ export function initializeNewOrcaProfileState( } const defaults = getDefaultPersistedState(homedir()) const cohorts = new LoadedCohortMigrationOperations({ loadNeedsSave: false }) - const initial = cohorts.migrateKeybindings( + const initial = cohorts.migrateCohortSeeds( telemetry ? { ...defaults, settings: { ...defaults.settings, telemetry } } : cohorts.migrateTelemetry(defaults, false), diff --git a/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts b/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts new file mode 100644 index 00000000000..1e988411bb8 --- /dev/null +++ b/src/main/persistence/loading-store/loaded-cohort-migrations.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultPersistedState } from '../../../shared/constants' +import type { PersistedState } from '../../../shared/persisted-state-types' +import { LoadedCohortMigrationOperations } from './loaded-cohort-migrations' + +const seed = (state: PersistedState, fileExistedOnLoad: boolean) => + new LoadedCohortMigrationOperations({ loadNeedsSave: false }).migrateCohortSeeds( + state, + fileExistedOnLoad + ).settings + +describe('Claude Code theme sync cohort', () => { + it('turns the sync on for a new profile', () => { + expect(seed(getDefaultPersistedState('/home/user'), false)).toMatchObject({ + claudeCodeThemeSync: true, + claudeCodeThemeSyncOffer: 'settled' + }) + }) + + it('keeps an existing profile off and owes it the offer, even when a writer copied the default in', () => { + const existing = getDefaultPersistedState('/home/user') + expect(seed(existing, true)).toMatchObject({ + claudeCodeThemeSync: false, + claudeCodeThemeSyncOffer: 'pending' + }) + }) + + it('never re-offers once the offer settled', () => { + const state = getDefaultPersistedState('/home/user') + const settled = { + ...state, + settings: { + ...state.settings, + claudeCodeThemeSync: false, + claudeCodeThemeSyncOffer: 'settled' as const + } + } + expect(seed(settled, true)).toMatchObject({ + claudeCodeThemeSync: false, + claudeCodeThemeSyncOffer: 'settled' + }) + }) +}) diff --git a/src/main/persistence/loading-store/loaded-cohort-migrations.ts b/src/main/persistence/loading-store/loaded-cohort-migrations.ts index a9249560e22..124c4cde593 100644 --- a/src/main/persistence/loading-store/loaded-cohort-migrations.ts +++ b/src/main/persistence/loading-store/loaded-cohort-migrations.ts @@ -14,7 +14,8 @@ type LoadedCohortMigrationOperationsRuntime = Pick { runAfterFirstWindowShown(() => { app.on('browser-window-focus', startSpeechModelWarmup(store)) }, WORKTREE_TRASH_SWEEP_FALLBACK_MS) + runAfterFirstWindowShown(() => { + startClaudeCodeThemeSync({ + getSettings: () => store.getSettings(), + onSettingsChanged: (listener) => store.onSettingsChanged(listener), + systemPrefersDark: () => nativeTheme.shouldUseDarkColors, + onSystemThemeChanged: (listener) => nativeTheme.on('updated', listener), + onAppFocused: (listener) => app.on('browser-window-focus', listener), + userDataPath: app.getPath('userData') + }) + }, WORKTREE_TRASH_SWEEP_FALLBACK_MS) nativeTheme.themeSource = store.getSettings().theme ?? 'system' // Wait for shell PATH before probing Codex; start reconciliation early so first launch can share it. startCodexHooks({ diff --git a/src/renderer/src/app-shell/use-app-shell-services.ts b/src/renderer/src/app-shell/use-app-shell-services.ts index de8745a914d..0226ffe0399 100644 --- a/src/renderer/src/app-shell/use-app-shell-services.ts +++ b/src/renderer/src/app-shell/use-app-shell-services.ts @@ -21,6 +21,7 @@ import { useTerminalViewerColorPublication } from './use-terminal-viewer-color-p import { useBrowserIdentityMigrationNotice } from '../components/browser-pane/browser-user-agent-migration-notice' import { useBrowserClientHostedDownloadNotices } from '../components/browser-pane/browser-client-hosted-download-notices' import { useCodexTerminalServerIsolationNotice } from '../components/terminal-pane/provider-notices/codex-server-isolation/codex-terminal-server-isolation-notice' +import { useClaudeThemeSyncOffer } from '../components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer' import { useVisibleHostedReviewRefresh } from './use-visible-hosted-review-refresh' import { useProfileStateSaveDelayNotice } from './use-profile-state-save-delay-notice' @@ -53,4 +54,5 @@ export function useAppShellServices(): void { useBrowserIdentityMigrationNotice() useBrowserClientHostedDownloadNotices() useCodexTerminalServerIsolationNotice() + useClaudeThemeSyncOffer() } diff --git a/src/renderer/src/assets/theme-token-contrast.test.ts b/src/renderer/src/assets/theme-token-contrast.test.ts index 959655062b6..95753fdc498 100644 --- a/src/renderer/src/assets/theme-token-contrast.test.ts +++ b/src/renderer/src/assets/theme-token-contrast.test.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' -import { contrastRatio, type Rgba } from '../lib/plugin-theme-tokens' +import { contrastRatio, type Rgba } from '../../../shared/color/rgba-contrast' import { CHAT_SELECTION_MIX, chatSelectionMixOver } from '../lib/chat-selection-mix' const css = readFileSync(new URL('./main.css', import.meta.url), 'utf8').replace( diff --git a/src/renderer/src/components/settings/search/setting-labels.ts b/src/renderer/src/components/settings/search/setting-labels.ts index a084e087cd5..b07b64b58e7 100644 --- a/src/renderer/src/components/settings/search/setting-labels.ts +++ b/src/renderer/src/components/settings/search/setting-labels.ts @@ -26,6 +26,7 @@ export const SETTING_LABELS: Partial> = { terminalThemeLight: 'Light Terminal Theme', terminalUseSeparateLightTheme: 'Separate Light Theme', terminalCustomThemes: 'Imported Themes', + claudeCodeThemeSync: 'Match Claude Code to Terminal Theme', terminalMacOptionAsAlt: 'Option as Alt', terminalPaddingX: 'Padding X', terminalPaddingY: 'Padding Y', diff --git a/src/renderer/src/components/settings/terminal/appearance/TerminalAppearanceSection.tsx b/src/renderer/src/components/settings/terminal/appearance/TerminalAppearanceSection.tsx index 54a0370a24e..5ebda98260b 100644 --- a/src/renderer/src/components/settings/terminal/appearance/TerminalAppearanceSection.tsx +++ b/src/renderer/src/components/settings/terminal/appearance/TerminalAppearanceSection.tsx @@ -31,6 +31,7 @@ import { SearchableSetting } from '../../section-layout/SearchableSetting' import { TerminalFontSizeSetting } from './TerminalFontSizeSetting' import { TerminalAdvancedTypographyControls } from './TerminalAdvancedTypographyControls' import { TerminalThemeCatalogSection } from '../themes/TerminalThemeSections' +import { ClaudeCodeThemeSyncSetting } from '../themes/ClaudeCodeThemeSyncSetting' import { TerminalWindowSection } from '../TerminalWindowSection' import { TerminalCursorAppearanceSection } from './TerminalCursorAppearanceSection' import { TerminalPaneAppearanceSection } from './TerminalPaneAppearanceSection' @@ -293,6 +294,10 @@ export function TerminalAppearanceSection({ /> ) : null} + {showDesktopThemeImports ? ( + + ) : null} + {showDesktopThemeImports ? ( <> [ ...getTerminalAppearanceSearchEntriesWithoutImports(), ...getTerminalConfigImportSearchEntries(), ...getTerminalWarpImportSearchEntries(), - ...getTerminalYamlImportSearchEntries() + ...getTerminalYamlImportSearchEntries(), + ...getClaudeCodeThemeSyncSearchEntry() ] ) diff --git a/src/renderer/src/components/settings/terminal/themes/ClaudeCodeThemeSyncSetting.tsx b/src/renderer/src/components/settings/terminal/themes/ClaudeCodeThemeSyncSetting.tsx new file mode 100644 index 00000000000..746fe91d583 --- /dev/null +++ b/src/renderer/src/components/settings/terminal/themes/ClaudeCodeThemeSyncSetting.tsx @@ -0,0 +1,26 @@ +import type { GlobalSettings } from '../../../../../../shared/global-settings-types' +import { SettingsSwitchRow } from '../../form-controls/SettingsFormControls' +import { SearchableSetting } from '../../section-layout/SearchableSetting' +import { getClaudeCodeThemeSyncSearchEntry } from './terminal-theme-search' + +export function ClaudeCodeThemeSyncSetting({ + settings, + updateSettings +}: { + settings: GlobalSettings + updateSettings: (updates: Partial) => void +}): React.JSX.Element { + const [entry] = getClaudeCodeThemeSyncSearchEntry() + return ( +
+ + updateSettings({ claudeCodeThemeSync: !settings.claudeCodeThemeSync })} + /> + +
+ ) +} diff --git a/src/renderer/src/components/settings/terminal/themes/terminal-theme-search.ts b/src/renderer/src/components/settings/terminal/themes/terminal-theme-search.ts index 30311108fb0..1f3bd80d45a 100644 --- a/src/renderer/src/components/settings/terminal/themes/terminal-theme-search.ts +++ b/src/renderer/src/components/settings/terminal/themes/terminal-theme-search.ts @@ -157,3 +157,24 @@ export const getTerminalWarpImportSearchEntries = createLocalizedCatalog(() => [ ] } ]) + +export const getClaudeCodeThemeSyncSearchEntry = createLocalizedCatalog(() => [ + { + title: translate( + 'components.settings.terminal.claudeCodeThemeSync.title', + 'Match Claude Code to Terminal Theme' + ), + description: translate( + 'components.settings.terminal.claudeCodeThemeSync.description', + 'Claude Code on this computer uses your terminal colors and follows theme changes live, including outside Orca. Turning this off restores your previous Claude Code theme. Picking a theme in Claude Code stops the sync.' + ), + keywords: [ + ...translateSearchKeyword('auto.components.settings.terminal.search.0ce176909a', 'theme'), + ...translateSearchKeyword( + 'components.settings.terminal.claudeCodeThemeSync.claude', + 'claude' + ), + ...translateSearchKeyword('auto.components.settings.terminal.search.674b7c8436', 'color') + ] + } +]) diff --git a/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts b/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts index 5a5b5c16b04..6a49569d9c4 100644 --- a/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts +++ b/src/renderer/src/components/terminal-pane/appearance/terminal-appearance.ts @@ -32,7 +32,7 @@ import { maybePushMode2031Flip } from '../emulation/terminal-mode-2031-replies' import { resolveTerminalMinimumContrastRatio } from '../../../../../shared/terminal-themes/terminal-contrast-correction' import { resolveTerminalInlineImagesEnabled } from '../../../../../shared/terminal/images/terminal-inline-images-settings' import { windowBackdropActive } from '@/lib/window-backdrop' -import { contrastRatio, over, type Rgba } from '@/lib/plugin-theme-tokens' +import { contrastRatio, over, type Rgba } from '../../../../../shared/color/rgba-contrast' import { getTerminalFontSizeOverride } from './terminal-font-size-overrides' function hexToRgb(hex: string): Rgba { diff --git a/src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.test.ts b/src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts similarity index 85% rename from src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.test.ts rename to src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts index d9bbe7bba61..813b27477da 100644 --- a/src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.test.ts +++ b/src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.test.ts @@ -1,10 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { noticeTestStore } from '../codex-notice-test-harness' -import { whenCodexTerminalAppears } from './codex-terminal-presence' +import { whenAgentTerminalAppears } from './agent-terminal-presence' vi.mock('@/store/index', () => import('../codex-notice-test-harness')) -describe('whenCodexTerminalAppears', () => { +describe('whenAgentTerminalAppears', () => { beforeEach(() => { noticeTestStore.setState( { tabsByWorktree: {}, agentStatusByPaneKey: {}, paneForegroundAgentByPaneKey: {} }, @@ -21,7 +21,7 @@ describe('whenCodexTerminalAppears', () => { ] ])('calls back once for %s', (_name, patch) => { const onAppear = vi.fn() - whenCodexTerminalAppears(onAppear) + whenAgentTerminalAppears('codex', onAppear) noticeTestStore.setState(patch) noticeTestStore.setState({ tabsByWorktree: { 'wt-2': [{ launchAgent: 'codex' }] } }) @@ -31,7 +31,7 @@ describe('whenCodexTerminalAppears', () => { it('stops watching once unsubscribed', () => { const onAppear = vi.fn() - whenCodexTerminalAppears(onAppear)() + whenAgentTerminalAppears('codex', onAppear)() noticeTestStore.setState({ tabsByWorktree: { 'wt-1': [{ launchAgent: 'codex' }] } }) expect(onAppear).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.ts b/src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.ts similarity index 60% rename from src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.ts rename to src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.ts index 4ac7a20cc7f..4376f73a59f 100644 --- a/src/renderer/src/components/terminal-pane/provider-notices/codex-presence/codex-terminal-presence.ts +++ b/src/renderer/src/components/terminal-pane/provider-notices/agent-presence/agent-terminal-presence.ts @@ -1,14 +1,16 @@ import { useAppStore } from '@/store/index' import type { AppState } from '@/store/types' -// Why three sources: Orca-launched tabs, hook-reported agents (SSH too), and a typed `codex` seen locally. -function hasCodexTerminal(state: AppState): boolean { +type NoticeAgent = 'codex' | 'claude' + +// Why three sources: Orca-launched tabs, hook-reported agents (SSH too), and an agent typed in a local pane. +function hasAgentTerminal(state: AppState, agent: NoticeAgent): boolean { return ( Object.values(state.tabsByWorktree).some((tabs) => - tabs.some((tab) => tab.launchAgent === 'codex') + tabs.some((tab) => tab.launchAgent === agent) ) || - Object.values(state.agentStatusByPaneKey).some((entry) => entry.agentType === 'codex') || - Object.values(state.paneForegroundAgentByPaneKey).some((entry) => entry.agent === 'codex') + Object.values(state.agentStatusByPaneKey).some((entry) => entry.agentType === agent) || + Object.values(state.paneForegroundAgentByPaneKey).some((entry) => entry.agent === agent) ) } @@ -20,15 +22,15 @@ function didSourcesChange(state: AppState, previous: AppState): boolean { ) } -/** Calls `onAppear` once, as soon as a Codex terminal exists. Returns the unsubscribe. */ -export function whenCodexTerminalAppears(onAppear: () => void): () => void { - if (hasCodexTerminal(useAppStore.getState())) { +/** Calls `onAppear` once, as soon as a terminal running `agent` exists. Returns the unsubscribe. */ +export function whenAgentTerminalAppears(agent: NoticeAgent, onAppear: () => void): () => void { + if (hasAgentTerminal(useAppStore.getState(), agent)) { onAppear() return () => {} } // Why a filtered subscription: a selector would rescan every tab on each store write. const unsubscribe = useAppStore.subscribe((state, previous) => { - if (didSourcesChange(state, previous) && hasCodexTerminal(state)) { + if (didSourcesChange(state, previous) && hasAgentTerminal(state, agent)) { unsubscribe() onAppear() } diff --git a/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts b/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts new file mode 100644 index 00000000000..f3e546a353e --- /dev/null +++ b/src/renderer/src/components/terminal-pane/provider-notices/claude-theme-sync/claude-theme-sync-offer.ts @@ -0,0 +1,78 @@ +import { useEffect } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store/index' +import type { AppState } from '@/store/types' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import { TRAILING_ACTIONS_CLASS_NAMES } from '@/components/ui/sonner' +import { whenAgentTerminalAppears } from '../agent-presence/agent-terminal-presence' + +const OFFER_TOAST_ID = 'claude-theme-sync-offer' + +function isOfferDue(state: AppState): boolean { + return state.settings?.claudeCodeThemeSyncOffer === 'pending' +} + +function showClaudeThemeSyncOffer(): void { + const { updateSettings, updateSettingsOrThrow } = useAppStore.getState() + // Why settle before showing: shown means answered, so a dismiss, quit or reload never asks again. + void updateSettings({ claudeCodeThemeSyncOffer: 'settled' }) + toast(translate('terminal.claudeThemeSyncOffer.title', 'Match Claude Code to your Orca theme?'), { + // Why a stable id: a late settings sync can't stack a second offer. + id: OFFER_TOAST_ID, + description: translate( + 'terminal.claudeThemeSyncOffer.description', + 'Claude Code on this computer would use your terminal colors and follow theme changes, including outside Orca. You can change this in Settings.' + ), + duration: Infinity, + classNames: TRAILING_ACTIONS_CLASS_NAMES, + action: { + label: translate('terminal.claudeThemeSyncOffer.accept', 'Match Theme'), + onClick: () => { + // Why confirm only after the write: a failed save must not claim the sync is on. + updateSettingsOrThrow({ claudeCodeThemeSync: true }).then( + () => + toast.success( + translate('terminal.claudeThemeSyncOffer.accepted', 'Claude Code theme sync is on'), + { + description: translate( + 'terminal.claudeThemeSyncOffer.acceptedDescription', + 'New Claude Code sessions on this computer use your Orca theme.' + ) + } + ), + () => + toast.error( + translate( + 'terminal.claudeThemeSyncOffer.failed', + 'Could not turn on Claude Code theme sync' + ), + { + description: translate( + 'terminal.claudeThemeSyncOffer.failedDescription', + 'Turn it on in Settings.' + ) + } + ) + ) + } + }, + cancel: { + label: translate('terminal.claudeThemeSyncOffer.decline', 'No Thanks'), + onClick: () => {} + } + }) +} + +/** Offers theme sync to profiles that predate it, once, when Claude Code first runs in an Orca terminal. */ +export function useClaudeThemeSyncOffer(): void { + const due = useAppStore(isOfferDue) + + useEffect(() => { + // Why: a paired web client's Claude runs on the host, whose settings this window does not own. + if (!due || isPairedWebClientWindow()) { + return + } + return whenAgentTerminalAppears('claude', showClaudeThemeSyncOffer) + }, [due]) +} diff --git a/src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-terminal-server-isolation-notice.ts b/src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-terminal-server-isolation-notice.ts index db904a90db9..9482bcc97ac 100644 --- a/src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-terminal-server-isolation-notice.ts +++ b/src/renderer/src/components/terminal-pane/provider-notices/codex-server-isolation/codex-terminal-server-isolation-notice.ts @@ -6,7 +6,7 @@ import type { AppState } from '@/store/types' import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' import { CODEX_TERMINAL_SERVER_ISOLATION_SETTINGS_TARGET_ID } from '@/lib/settings-navigation-types' import { isCodexTerminalServerIsolationEnabled } from '../../../../../../shared/codex-terminal-server-isolation' -import { whenCodexTerminalAppears } from '../codex-presence/codex-terminal-presence' +import { whenAgentTerminalAppears } from '../agent-presence/agent-terminal-presence' // Why no hydration check: the seen flag defaults to true until the persisted value arrives. function isNoticeDue(state: AppState): boolean { @@ -69,6 +69,6 @@ export function useCodexTerminalServerIsolationNotice(): void { if (!due || isPairedWebClientWindow()) { return } - return whenCodexTerminalAppears(showCodexTerminalServerIsolationNotice) + return whenAgentTerminalAppears('codex', showCodexTerminalServerIsolationNotice) }, [due]) } diff --git a/src/renderer/src/components/terminal-pane/provider-notices/codex-settings/codex-shared-settings-notice.ts b/src/renderer/src/components/terminal-pane/provider-notices/codex-settings/codex-shared-settings-notice.ts index 89a89059f99..69071f42a60 100644 --- a/src/renderer/src/components/terminal-pane/provider-notices/codex-settings/codex-shared-settings-notice.ts +++ b/src/renderer/src/components/terminal-pane/provider-notices/codex-settings/codex-shared-settings-notice.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useState } from 'react' import { useAppStore } from '@/store/index' import { isLocalWindowsDesktopClient } from '@/lib/desktop-window-chrome' -import { whenCodexTerminalAppears } from '../codex-presence/codex-terminal-presence' +import { whenAgentTerminalAppears } from '../agent-presence/agent-terminal-presence' /** Whether to show the one-time "Codex now uses ~/.codex" card this session, and its dismiss. */ export function useCodexSharedSettingsNotice(): { visible: boolean; dismiss: () => void } { @@ -14,7 +14,7 @@ export function useCodexSharedSettingsNotice(): { visible: boolean; dismiss: () if (seen || !isLocalWindowsDesktopClient()) { return } - return whenCodexTerminalAppears(() => { + return whenAgentTerminalAppears('codex', () => { // Why mark before showing: seen means shown, so a quit or reload never repeats it. useAppStore.getState().markCodexSharedSettingsNoticeSeen() setVisible(true) diff --git a/src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx b/src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx index e08db22a83c..01818c7fc9d 100644 --- a/src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx +++ b/src/renderer/src/components/ui/security-surface-theme-contrast.test.tsx @@ -5,7 +5,7 @@ import { resolve } from 'node:path' import { cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import { applyPluginAppTheme } from '@/lib/document-theme' -import { contrastRatio, type Rgba } from '@/lib/plugin-theme-tokens' +import { contrastRatio, type Rgba } from '../../../../shared/color/rgba-contrast' import { Dialog, DialogContent, DialogDescription, DialogTitle } from './dialog' const css = readFileSync(resolve('src/renderer/src/assets/main.css'), 'utf8') diff --git a/src/renderer/src/components/ui/sonner.tsx b/src/renderer/src/components/ui/sonner.tsx index 318f55d11c5..77ab112c5fe 100644 --- a/src/renderer/src/components/ui/sonner.tsx +++ b/src/renderer/src/components/ui/sonner.tsx @@ -22,6 +22,12 @@ export const INLINE_ACTION_CLASS_NAMES = { actionButton: '!m-0 !self-center' } +// Why: a two-way choice ends at the right edge, the way the Windows terminal weight notice keeps Okay +// at the end; the global footer rule otherwise starts actions under the copy. +export const TRAILING_ACTIONS_CLASS_NAMES = { + cancelButton: '!ml-auto' +} + // Why: scope to real modals; Radix menus/selects also set body pointer-events:none. function isModalOverlayOpen(element: Element): boolean { return element.ownerDocument.body.querySelector(MODAL_OVERLAY_CHILD_SELECTOR) !== null diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 3ffffab8408..518cd58095a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21208,6 +21208,11 @@ "scrollback": "scrollback", "snap": "snap", "position": "position" + }, + "claudeCodeThemeSync": { + "title": "Match Claude Code to Terminal Theme", + "description": "Claude Code on this computer uses your terminal colors and follows theme changes live, including outside Orca. Turning this off restores your previous Claude Code theme. Picking a theme in Claude Code stops the sync.", + "claude": "claude" } }, "nativeChat": { @@ -22299,6 +22304,16 @@ "title": "Terminal text on Windows is now lighter", "okay": "Okay", "lighterText": "Lighter terminal text" + }, + "claudeThemeSyncOffer": { + "title": "Match Claude Code to your Orca theme?", + "description": "Claude Code on this computer would use your terminal colors and follow theme changes, including outside Orca. You can change this in Settings.", + "accept": "Match Theme", + "accepted": "Claude Code theme sync is on", + "acceptedDescription": "New Claude Code sessions on this computer use your Orca theme.", + "decline": "No Thanks", + "failed": "Could not turn on Claude Code theme sync", + "failedDescription": "Turn it on in Settings." } }, "fileExplorer": { diff --git a/src/renderer/src/lib/chat-selection-mix.ts b/src/renderer/src/lib/chat-selection-mix.ts index 26c40e059ac..4e194f7f925 100644 --- a/src/renderer/src/lib/chat-selection-mix.ts +++ b/src/renderer/src/lib/chat-selection-mix.ts @@ -1,12 +1,6 @@ import { MIN_TEXT_CONTRAST } from './plugin-theme-contrast-rules' -import { - browserColorProbe, - contrastRatio, - mix, - paintedThemeColors, - type ColorProbe, - type Rgba -} from './plugin-theme-tokens' +import { browserColorProbe, paintedThemeColors, type ColorProbe } from './plugin-theme-tokens' +import { contrastRatio, mix, type Rgba } from '../../../shared/color/rgba-contrast' export const CHAT_SELECTION_MIX_TOKEN = '--chat-selection-mix' // Keep in sync with --chat-selection-mix in main.css: about as deep as the system highlight. diff --git a/src/renderer/src/lib/left-sidebar-appearance.ts b/src/renderer/src/lib/left-sidebar-appearance.ts index 3f9e056406a..169dd101973 100644 --- a/src/renderer/src/lib/left-sidebar-appearance.ts +++ b/src/renderer/src/lib/left-sidebar-appearance.ts @@ -5,7 +5,8 @@ import { normalizeLeftSidebarTintOpacity } from '../../../shared/left-sidebar-appearance' import { pluginAppThemeCssFallback } from '../../../shared/plugins/artifacts/plugin-theme-css-fallbacks' -import { hostPillOutlineMixOver, mix, type ColorProbe, type Rgba } from './plugin-theme-tokens' +import { hostPillOutlineMixOver, type ColorProbe } from './plugin-theme-tokens' +import { mix, type Rgba } from '../../../shared/color/rgba-contrast' type LeftSidebarAppearanceSettings = Pick< GlobalSettings, diff --git a/src/renderer/src/lib/monaco-languages/markdown-monaco-theme-rules.ts b/src/renderer/src/lib/monaco-languages/markdown-monaco-theme-rules.ts index b3e8481a0d3..7dd57ece024 100644 --- a/src/renderer/src/lib/monaco-languages/markdown-monaco-theme-rules.ts +++ b/src/renderer/src/lib/monaco-languages/markdown-monaco-theme-rules.ts @@ -1,7 +1,7 @@ import type * as Monaco from 'monaco-editor' import { MIN_SYNTAX_CONTRAST } from '../plugin-monaco-theme' import { MARKDOWN_TOKEN_PREFIX, markdownTokenRules } from '../plugin-monaco-token-rules' -import { contrastRatio, type Rgba } from '../plugin-theme-tokens' +import { contrastRatio, type Rgba } from '../../../../shared/color/rgba-contrast' type ThemeRule = Monaco.editor.ITokenThemeRule type ThemeBase = 'light' | 'dark' diff --git a/src/renderer/src/lib/plugin-monaco-theme.ts b/src/renderer/src/lib/plugin-monaco-theme.ts index 467d0d83380..489e9e7c91b 100644 --- a/src/renderer/src/lib/plugin-monaco-theme.ts +++ b/src/renderer/src/lib/plugin-monaco-theme.ts @@ -1,7 +1,8 @@ import type * as Monaco from 'monaco-editor' import type { PluginThemeTokenColorRule } from '../../../shared/plugins/artifacts/plugin-theme-artifact' import { pluginMonacoTokenRules } from './plugin-monaco-token-rules' -import { contrastRatio, type ColorProbe, type Rgba } from './plugin-theme-tokens' +import type { ColorProbe } from './plugin-theme-tokens' +import { contrastRatio, type Rgba } from '../../../shared/color/rgba-contrast' export type PluginMonacoTheme = { name: string; data: Monaco.editor.IStandaloneThemeData } diff --git a/src/renderer/src/lib/plugin-theme-tokens.ts b/src/renderer/src/lib/plugin-theme-tokens.ts index 0df023b5c4e..2844bea1da7 100644 --- a/src/renderer/src/lib/plugin-theme-tokens.ts +++ b/src/renderer/src/lib/plugin-theme-tokens.ts @@ -11,35 +11,10 @@ import { type ContrastRule } from './plugin-theme-contrast-rules' +import { contrastRatio, mix, over, type Rgba } from '../../../shared/color/rgba-contrast' + /** sRGB channels 0-255 and alpha 0-1, or null when the value is not a CSS color. */ -export type ColorProbe = (value: string) => readonly [number, number, number, number] | null -export type Rgba = readonly [number, number, number, number] - -function luminance([r, g, b]: Rgba): number { - const channel = (value: number): number => { - const c = value / 255 - return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4 - } - return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) -} - -/** WCAG contrast ratio between two opaque colors. */ -export function contrastRatio(a: Rgba, b: Rgba): number { - const first = luminance(a) - const second = luminance(b) - return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05) -} - -export function over([r, g, b, a]: Rgba, [br, bg, bb]: Rgba): Rgba { - return [r * a + br * (1 - a), g * a + bg * (1 - a), b * a + bb * (1 - a), 1] -} - -/** `color-mix(in srgb, a percent%, b)`. */ -export function mix(a: Rgba, b: Rgba, percent: number): Rgba { - const p = percent / 100 - const channel = (index: 0 | 1 | 2 | 3): number => a[index] * p + b[index] * (1 - p) - return [channel(0), channel(1), channel(2), channel(3)] -} +export type ColorProbe = (value: string) => Rgba | null /** The `over` layers painted bottom-up; opaque only when the bottom layer is. */ function paintedLayers( diff --git a/src/renderer/src/lib/terminal-app-theme.test.ts b/src/renderer/src/lib/terminal-app-theme.test.ts index 603d9e2359b..b5ca962188e 100644 --- a/src/renderer/src/lib/terminal-app-theme.test.ts +++ b/src/renderer/src/lib/terminal-app-theme.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest' import { getDefaultSettings } from '../../../shared/constants' import type { GlobalSettings } from '../../../shared/global-settings-types' -import { contrastRatio, over, safePluginThemeTokens, type ColorProbe } from './plugin-theme-tokens' +import { safePluginThemeTokens, type ColorProbe } from './plugin-theme-tokens' +import { contrastRatio, over } from '../../../shared/color/rgba-contrast' import { synthesizeTerminalAppTheme } from './terminal-app-theme' // Parses #rrggbb and rgb(r g b), which is all the synthesized theme and its inputs use. diff --git a/src/renderer/src/lib/terminal-app-theme.ts b/src/renderer/src/lib/terminal-app-theme.ts index 9c5c5cfe872..1ab89a15bdb 100644 --- a/src/renderer/src/lib/terminal-app-theme.ts +++ b/src/renderer/src/lib/terminal-app-theme.ts @@ -12,12 +12,20 @@ import { } from '../../../shared/terminal-themes/terminal-theme-selection' import type { AppThemePaint } from './document-theme' import { hashThemeContent } from './plugin-monaco-theme' -import { contrastRatio, type ColorProbe, type Rgba } from './plugin-theme-tokens' +import type { ColorProbe } from './plugin-theme-tokens' +import { + contrastRatio, + mix, + readableOn, + rgbaToHex, + type Rgba +} from '../../../shared/color/rgba-contrast' import { getSystemPrefersDark } from './terminal-theme' import { isTerminalBackgroundLight, resolveOpaqueTerminalBackground } from '../../../shared/terminal-themes/terminal-title-contrast' +import { terminalPaletteRgba } from '../../../shared/terminal-themes/terminal-palette-rgba' export type TerminalAppTheme = AppThemePaint & { id: typeof MATCH_TERMINAL_APP_THEME @@ -25,8 +33,6 @@ export type TerminalAppTheme = AppThemePaint & { } const MIN_TEXT_CONTRAST = 4.5 -// Why 3:1: a focus ring or cursor must stand out; the shared gate's 2:1 is only its floor. -const MIN_ACCENT_CONTRAST = 3 /** The palette the active terminal paints with: the mode's theme plus that mode's overrides. * Why no opacity: theme surfaces must be opaque for the contrast gate. */ @@ -93,37 +99,6 @@ export function resolvePaintedTheme( return dark === requestedDark ? theme : dark ? 'dark' : 'light' } -function over([r, g, b, a]: Rgba, [br, bg, bb]: Rgba): Rgba { - return [r * a + br * (1 - a), g * a + bg * (1 - a), b * a + bb * (1 - a), 1] -} - -function mix(color: Rgba, background: Rgba, amount: number): Rgba { - return over([color[0], color[1], color[2], amount], background) -} - -function hex([r, g, b]: Rgba): string { - return `#${[r, g, b] - .map((channel) => - Math.round(Math.min(255, Math.max(0, channel))) - .toString(16) - .padStart(2, '0') - ) - .join('')}` -} - -/** Pushes text toward black or white until it reads on every surface; low-contrast palettes - * (Solarized) keep their hue instead of losing the token to the contrast gate. */ -function legible(text: Rgba, surfaces: readonly Rgba[], light: boolean): Rgba { - const extreme: Rgba = light ? [0, 0, 0, 1] : [255, 255, 255, 1] - for (let step = 0; step <= 20; step += 1) { - const candidate = mix(extreme, text, step / 20) - if (surfaces.every((surface) => contrastRatio(candidate, surface) >= MIN_TEXT_CONTRAST)) { - return candidate - } - } - return extreme -} - // Why these scopes: the ones every grammar emits, mapped to the ANSI roles shells use for them. const SYNTAX_SCOPES: readonly (readonly [keyof ITheme, string[]])[] = [ ['brightBlack', ['comment']], @@ -147,25 +122,17 @@ export function synthesizeTerminalAppTheme( systemPrefersDark: boolean, probe: ColorProbe ): TerminalAppTheme | null { - const palette = activeTerminalPalette(settings, systemPrefersDark) const base = terminalAppThemeBase(settings, systemPrefersDark) - const opaqueBackground = resolveOpaqueTerminalBackground(palette?.background) - const background = opaqueBackground ? probe(opaqueBackground) : null - const rawForeground = palette?.foreground ? probe(palette.foreground) : null - if (!palette || !base || !background || !rawForeground) { + const palette = terminalPaletteRgba(activeTerminalPalette(settings, systemPrefersDark), probe) + if (!base || !palette) { return null } const light = base === 'light' - const foreground = over(rawForeground, background) - const ansi = (key: keyof ITheme): Rgba | null => { - const value = palette[key] - const parsed = typeof value === 'string' ? probe(value) : null - return parsed ? over(parsed, background) : null - } + const { background, foreground, color: ansi, accent: accentColor } = palette const surfacesToward = (tint: Rgba) => ({ - popover: mix(tint, background, 0.05), - muted: mix(tint, background, 0.07), - accent: mix(tint, background, 0.12) + popover: mix(tint, background, 5), + muted: mix(tint, background, 7), + accent: mix(tint, background, 12) }) const extreme: Rgba = light ? [0, 0, 0, 1] : [255, 255, 255, 1] const towardText = surfacesToward(foreground) @@ -175,50 +142,52 @@ export function synthesizeTerminalAppTheme( ) ? towardText : surfacesToward(light ? [255, 255, 255, 1] : [0, 0, 0, 1]) - const text = legible(foreground, [background, ...Object.values(surfaces)], light) + const text = readableOn( + foreground, + [background, ...Object.values(surfaces)], + light, + MIN_TEXT_CONTRAST + ) // Why: the host pill paints muted text on the accent, tinted in dark over the sidebar (= background). const hostBadgeRule = pluginAppThemeCssFallback('--host-badge', base) const hostBadge = mix( surfaces.accent, background, - hostBadgeRule && 'tint' in hostBadgeRule ? hostBadgeRule.percent / 100 : 1 + hostBadgeRule && 'tint' in hostBadgeRule ? hostBadgeRule.percent : 100 ) - const mutedText = legible( - mix(foreground, background, 0.7), + const mutedText = readableOn( + mix(foreground, background, 70), [background, surfaces.muted, hostBadge], - light - ) - const accentColor = [ansi('blue'), ansi('brightBlue')].find( - (color): color is Rgba => - color !== null && contrastRatio(color, background) >= MIN_ACCENT_CONTRAST + light, + MIN_TEXT_CONTRAST ) const primaryText = accentColor ? [background, text].find((color) => contrastRatio(color, accentColor) >= MIN_TEXT_CONTRAST) : undefined const charts = (['blue', 'green', 'yellow', 'magenta', 'cyan'] as const).flatMap((key, index) => { const color = ansi(key) - return color ? [[`--chart-${index + 1}`, hex(color)] as const] : [] + return color ? [[`--chart-${index + 1}`, rgbaToHex(color)] as const] : [] }) const tokens = completePluginAppThemeTokens({ - '--background': hex(background), - '--foreground': hex(text), - '--popover': hex(surfaces.popover), - '--muted': hex(surfaces.muted), - '--secondary': hex(surfaces.muted), - '--accent': hex(surfaces.accent), - '--muted-foreground': hex(mutedText), - '--border': hex(mix(foreground, background, 0.1)), + '--background': rgbaToHex(background), + '--foreground': rgbaToHex(text), + '--popover': rgbaToHex(surfaces.popover), + '--muted': rgbaToHex(surfaces.muted), + '--secondary': rgbaToHex(surfaces.muted), + '--accent': rgbaToHex(surfaces.accent), + '--muted-foreground': rgbaToHex(mutedText), + '--border': rgbaToHex(mix(foreground, background, 10)), // Why the sidebar equals the terminal: that is what "Match Terminal" looked like before. - '--sidebar': hex(background), - ...(accentColor ? { '--ring': hex(accentColor) } : {}), + '--sidebar': rgbaToHex(background), + ...(accentColor ? { '--ring': rgbaToHex(accentColor) } : {}), ...(accentColor && primaryText - ? { '--primary': hex(accentColor), '--primary-foreground': hex(primaryText) } + ? { '--primary': rgbaToHex(accentColor), '--primary-foreground': rgbaToHex(primaryText) } : {}), ...Object.fromEntries(charts) }) const tokenColors = SYNTAX_SCOPES.flatMap(([key, scope]) => { const color = ansi(key) - return color ? [{ scope, settings: { foreground: hex(color) } }] : [] + return color ? [{ scope, settings: { foreground: rgbaToHex(color) } }] : [] }) const content = JSON.stringify({ base, tokens, tokenColors }) // Why reuse: settings writes hand out fresh arrays, and a fresh theme object would repaint :root. diff --git a/src/shared/color/rgba-contrast.ts b/src/shared/color/rgba-contrast.ts new file mode 100644 index 00000000000..c132f0d1a50 --- /dev/null +++ b/src/shared/color/rgba-contrast.ts @@ -0,0 +1,59 @@ +/** sRGB channels 0-255 and alpha 0-1. */ +export type Rgba = readonly [number, number, number, number] + +const BLACK: Rgba = [0, 0, 0, 1] +const WHITE: Rgba = [255, 255, 255, 1] + +function luminance([r, g, b]: Rgba): number { + const channel = (value: number): number => { + const c = value / 255 + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4 + } + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) +} + +/** WCAG contrast ratio between two opaque colors. */ +export function contrastRatio(a: Rgba, b: Rgba): number { + const first = luminance(a) + const second = luminance(b) + return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05) +} + +export function over([r, g, b, a]: Rgba, [br, bg, bb]: Rgba): Rgba { + return [r * a + br * (1 - a), g * a + bg * (1 - a), b * a + bb * (1 - a), 1] +} + +/** `color-mix(in srgb, a percent%, b)`. */ +export function mix(a: Rgba, b: Rgba, percent: number): Rgba { + const p = percent / 100 + const channel = (index: 0 | 1 | 2 | 3): number => a[index] * p + b[index] * (1 - p) + return [channel(0), channel(1), channel(2), channel(3)] +} + +/** Pushes a color toward black or white until it reads on every surface, so low-contrast + * palettes (Solarized) keep their hue instead of losing the color to a contrast gate. */ +export function readableOn( + color: Rgba, + surfaces: readonly Rgba[], + light: boolean, + minimum: number +): Rgba { + const extreme = light ? BLACK : WHITE + for (let step = 0; step <= 20; step += 1) { + const candidate = mix(extreme, color, (step / 20) * 100) + if (surfaces.every((surface) => contrastRatio(candidate, surface) >= minimum)) { + return candidate + } + } + return extreme +} + +export function rgbaToHex([r, g, b]: Rgba): string { + return `#${[r, g, b] + .map((channel) => + Math.round(Math.min(255, Math.max(0, channel))) + .toString(16) + .padStart(2, '0') + ) + .join('')}` +} diff --git a/src/shared/default-global-settings.ts b/src/shared/default-global-settings.ts index a3d6f776b3d..70d0459d1de 100644 --- a/src/shared/default-global-settings.ts +++ b/src/shared/default-global-settings.ts @@ -97,6 +97,7 @@ export function buildDefaultSettings(args: { terminalUseSeparateLightTheme: true, terminalColorOverridesSplit: true, terminalThemeLight: 'Builtin Tango Light', + claudeCodeThemeSync: true, terminalCustomThemes: [], terminalDividerColorLight: '#d4d4d8', terminalInactivePaneOpacity: args.terminalInactivePaneOpacity, diff --git a/src/shared/global-settings-types.ts b/src/shared/global-settings-types.ts index f341d11385e..df328adf01a 100644 --- a/src/shared/global-settings-types.ts +++ b/src/shared/global-settings-types.ts @@ -129,6 +129,10 @@ export type GlobalSettings = GlobalSettingsBase & { terminalUseSeparateLightTheme: boolean terminalThemeLight: string terminalDividerColorLight: string + /** Mirror the terminal palette into Claude Code's theme; off restores the theme Orca replaced. */ + claudeCodeThemeSync: boolean + /** Existing profiles get `pending` and an offer toast at their next Claude launch; `settled` once shown or for new profiles. */ + claudeCodeThemeSyncOffer?: 'pending' | 'settled' terminalInactivePaneOpacity: number terminalActivePaneOpacity: number terminalPaneOpacityTransitionMs: number diff --git a/src/shared/terminal-themes/terminal-palette-rgba.ts b/src/shared/terminal-themes/terminal-palette-rgba.ts new file mode 100644 index 00000000000..0fb5fd12bc6 --- /dev/null +++ b/src/shared/terminal-themes/terminal-palette-rgba.ts @@ -0,0 +1,38 @@ +import type { ITheme } from '@xterm/xterm' +import { contrastRatio, over, type Rgba } from '../color/rgba-contrast' +import { resolveOpaqueTerminalBackground } from './terminal-title-contrast' + +// Why 3:1: a focus ring or cursor must stand out; the shared gate's 2:1 is only its floor. +const MIN_TERMINAL_ACCENT_CONTRAST = 3 + +export type TerminalPaletteRgba = { + background: Rgba + foreground: Rgba + /** A palette color painted over the background; null when the palette lacks it. */ + color: (key: keyof ITheme) => Rgba | null + /** Blue, else bright blue, when it stands out on the background. */ + accent: Rgba | undefined +} + +/** The terminal palette as the opaque colors it paints; null without a readable background or foreground. */ +export function terminalPaletteRgba( + palette: ITheme | null, + probe: (value: string) => Rgba | null +): TerminalPaletteRgba | null { + const opaqueBackground = resolveOpaqueTerminalBackground(palette?.background) + const background = opaqueBackground ? probe(opaqueBackground) : null + const rawForeground = palette?.foreground ? probe(palette.foreground) : null + if (!palette || !background || !rawForeground) { + return null + } + const color = (key: keyof ITheme): Rgba | null => { + const value = palette[key] + const parsed = typeof value === 'string' ? probe(value) : null + return parsed ? over(parsed, background) : null + } + const accent = [color('blue'), color('brightBlue')].find( + (candidate): candidate is Rgba => + candidate !== null && contrastRatio(candidate, background) >= MIN_TERMINAL_ACCENT_CONTRAST + ) + return { background, foreground: over(rawForeground, background), color, accent } +} diff --git a/src/shared/terminal-themes/terminal-title-contrast.ts b/src/shared/terminal-themes/terminal-title-contrast.ts index b79c0623f16..41531fbcc13 100644 --- a/src/shared/terminal-themes/terminal-title-contrast.ts +++ b/src/shared/terminal-themes/terminal-title-contrast.ts @@ -1,3 +1,5 @@ +import type { Rgba } from '../color/rgba-contrast' + type RgbaColor = { r: number; g: number; b: number; a: number } const APP_SURFACE_COLORS: Record<'dark' | 'light', RgbaColor> = { @@ -52,6 +54,12 @@ function compositeTerminalBackground( return alpha < 1 ? compositeRgb(color, appSurface, alpha) : { ...color, a: 1 } } +/** A hex, rgb()/rgba() or basic named color as channels; null when it is none of those. */ +export function parseTerminalColor(color: string | undefined): Rgba | null { + const parsed = parseCssRgbColor(color) + return parsed ? [parsed.r, parsed.g, parsed.b, parsed.a] : null +} + function parseCssRgbColor(color: string | undefined): RgbaColor | null { const value = color?.trim().toLowerCase() if (!value) { diff --git a/tests/e2e/claude-code-theme-sync.spec.ts b/tests/e2e/claude-code-theme-sync.spec.ts new file mode 100644 index 00000000000..f893842f615 --- /dev/null +++ b/tests/e2e/claude-code-theme-sync.spec.ts @@ -0,0 +1,307 @@ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import type { ElectronApplication, Page } from '@playwright/test' +import { expect, test } from './helpers/orca-app' +import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' +import { + discoverActivePtyId, + execInTerminal, + sendToTerminal, + waitForActiveTerminalManager +} from './helpers/terminal' + +const enabled = process.env.ORCA_REAL_CLAUDE_THEME_TEST === '1' +// Claude Code's own light theme paints its prompt border this gray. +const CLAUDE_LIGHT_BORDER = 0x8a8a8a +const TOKYO_NIGHT_ACCENT = 0x7aa2f7 +const GRUVBOX_DARK_ACCENT = 0x458588 +const TOKYO_NIGHT_LIGHT_ACCENT = 0x34548a +// Covers Orca's first five reload attempts (to 120 s) when macOS drops file events. +const LIVE_SWITCH_TIMEOUT_MS = 130_000 + +test.use({ + launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' }, + orcaAppExtraEnv: { DISABLE_AUTOUPDATER: '1' } +}) +test.skip(!enabled, 'Set ORCA_REAL_CLAUDE_THEME_TEST=1 to run the installed Claude Code') +// The journey types POSIX shell commands. +test.skip(process.platform === 'win32', 'Uses a POSIX shell command line') + +/** Claude's prompt border: the first cell of the first full-width rule it draws. */ +function promptBorderColor(page: Page): Promise { + return page.evaluate(() => { + const state = window.__store!.getState() + const pane = window.__paneManagers?.get(state.activeTabId ?? '')?.getActivePane() + const buffer = pane?.terminal.buffer.active + if (!buffer) { + return null + } + for (let y = buffer.length - 1; y >= 0; y -= 1) { + const line = buffer.getLine(y) + if (line?.translateToString(true).startsWith('────────')) { + const cell = line.getCell(0) + return cell?.isFgRGB() ? cell.getFgColor() : null + } + } + return null + }) +} + +/** Samples the border until it shows `target`; every earlier sample must still show `previous` + * (a redraw can briefly hide the border, so samples without one are skipped). */ +async function expectLiveSwitch(page: Page, previous: number, target: number): Promise { + const started = Date.now() + const frames: number[] = [] + await expect + .poll( + async () => { + const color = await promptBorderColor(page) + if (color !== null) { + frames.push(color) + } + return color + }, + { timeout: LIVE_SWITCH_TIMEOUT_MS, intervals: [100] } + ) + .toBe(target) + expect(frames.slice(0, -1).every((color) => color === previous)).toBe(true) + return Date.now() - started +} + +/** Plain text of the active pane; Claude styles words separately, so serialized output splits them. */ +function terminalText(page: Page): Promise { + return page.evaluate(() => { + const state = window.__store!.getState() + const buffer = window.__paneManagers?.get(state.activeTabId ?? '')?.getActivePane()?.terminal + .buffer.active + const lines: string[] = [] + for (let y = 0; buffer && y < buffer.length; y += 1) { + lines.push(buffer.getLine(y)?.translateToString(true) ?? '') + } + return lines.join('\n') + }) +} + +async function startClaude(page: Page, ptyId: string, workDir: string): Promise { + await execInTerminal(page, ptyId, `cd '${workDir}' && clear && claude`) + await expect.poll(() => terminalText(page), { timeout: 30_000 }).toContain('Claude Code v') + await expect.poll(() => promptBorderColor(page), { timeout: 15_000 }).not.toBeNull() +} + +async function exitClaude(page: Page, ptyId: string): Promise { + await sendToTerminal(page, ptyId, '/exit') + // Enter must land after the command menu picked /exit, or Claude submits a prompt. + await expect.poll(() => terminalText(page), { timeout: 10_000 }).toContain('Exit the CLI') + await sendToTerminal(page, ptyId, '\r') + // Back at the shell prompt. + await expect + .poll(async () => (await terminalText(page)).trimEnd().split('\n').at(-1)?.trimEnd(), { + timeout: 15_000 + }) + .toMatch(/[$%#]$/) +} + +type Journey = { + home: string + workDir: string + ptyId: string + readTheme: () => unknown + readThemeFile: () => string + updateSettings: (updates: Record) => Promise + shot: (name: string) => Promise + windowShot: (name: string) => Promise +} + +/** An existing profile (the e2e fixture seeds one) whose Claude Code uses its own light theme. */ +async function startJourney( + electronApp: ElectronApplication, + orcaPage: Page, + testInfo: { outputPath: (name: string) => string }, + appTheme: 'dark' | 'light' +): Promise { + await waitForSessionReady(orcaPage) + await ensureTerminalVisible(orcaPage) + await waitForActiveTerminalManager(orcaPage) + const updateSettings = (updates: Record) => + orcaPage.evaluate((next) => window.__store!.getState().updateSettings(next), updates) + const settings = () => + orcaPage.evaluate(() => { + const { claudeCodeThemeSync, claudeCodeThemeSyncOffer } = window.__store!.getState().settings! + return { claudeCodeThemeSync, claudeCodeThemeSyncOffer } + }) + // Existing profiles start with the sync off and an offer owed. + expect(await settings()).toEqual({ + claudeCodeThemeSync: false, + claudeCodeThemeSyncOffer: 'pending' + }) + await updateSettings({ + theme: appTheme, + terminalThemeDark: 'Tokyo Night', + terminalThemeLight: 'Tokyo Night Light', + terminalUseSeparateLightTheme: true + }) + const home = await electronApp.evaluate(({ app }) => app.getPath('home')) + const settingsPath = join(home, '.claude', 'settings.json') + const workDir = join(home, 'claude-theme-work') + mkdirSync(workDir, { recursive: true }) + mkdirSync(dirname(settingsPath), { recursive: true }) + writeFileSync( + join(home, '.claude.json'), + JSON.stringify({ + hasCompletedOnboarding: true, + projects: { [workDir]: { hasTrustDialogAccepted: true } } + }) + ) + const readSettings = (): Record => { + try { + return JSON.parse(readFileSync(settingsPath, 'utf-8')) + } catch { + return {} + } + } + writeFileSync(settingsPath, `${JSON.stringify({ ...readSettings(), theme: 'light' }, null, 2)}\n`) + const readThemeFile = () => { + try { + return readFileSync(join(home, '.claude', 'themes', 'orca.json'), 'utf-8') + } catch { + return '' + } + } + return { + home, + workDir, + ptyId: await discoverActivePtyId(orcaPage), + readTheme: () => readSettings().theme, + readThemeFile, + updateSettings, + shot: (name) => + orcaPage + .locator('.pane:visible .xterm-screen') + .first() + .screenshot({ path: testInfo.outputPath(`${name}.png`) }), + windowShot: (name) => orcaPage.screenshot({ path: testInfo.outputPath(`${name}.png`) }) + } +} + +const offerTitle = 'Match Claude Code to your Orca theme?' + +test('an existing user accepts the offer, then Claude Code follows the Orca theme live and restores', async ({ + electronApp, + orcaPage +}, testInfo) => { + // Real Claude Code launches, three live switches and a restore, each allowed Orca's reload retries. + test.setTimeout(6 * 60_000) + const journey = await startJourney(electronApp, orcaPage, testInfo, 'dark') + const { ptyId, workDir, readTheme, readThemeFile, updateSettings, shot, windowShot } = journey + + // Off matches main: Claude keeps its own light theme on the dark terminal, and Orca offers the sync once. + await startClaude(orcaPage, ptyId, workDir) + await expect + .poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }) + .toBe(CLAUDE_LIGHT_BORDER) + await shot('before-dark') + const offer = orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle }) + // Agent detection for a typed `claude` can lag its first frame. + await expect(offer).toBeVisible({ timeout: 30_000 }) + // Shoot once the slide-in settled, so the proof shows the toast as users see it. + await expect(offer).toHaveAttribute('data-mounted', 'true') + await expect(offer).toBeInViewport({ ratio: 1 }) + await expect(offer).toHaveCSS('opacity', '1') + await windowShot('offer-toast-dark') + await offer.screenshot({ path: testInfo.outputPath('offer-toast-dark-closeup.png') }) + await offer.getByRole('button', { name: 'Match Theme' }).click() + await expect.poll(readTheme, { timeout: 30_000 }).toBe('custom:orca') + await expect.poll(readThemeFile, { timeout: 30_000 }).toContain('"promptBorder": "#7aa2f7"') + await exitClaude(orcaPage, ptyId) + + // The previous session's frames stay in scrollback; wait for the new session's border. + await startClaude(orcaPage, ptyId, workDir) + await expect.poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }).toBe(TOKYO_NIGHT_ACCENT) + await shot('after-dark') + await expect(orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle })).toHaveCount( + 0 + ) + + // The running session recolors without a restart. + await updateSettings({ terminalThemeDark: 'Gruvbox Dark' }) + const darkSwitchMs = await expectLiveSwitch(orcaPage, TOKYO_NIGHT_ACCENT, GRUVBOX_DARK_ACCENT) + await shot('after-dark-live-gruvbox') + await updateSettings({ theme: 'light' }) + const lightSwitchMs = await expectLiveSwitch( + orcaPage, + GRUVBOX_DARK_ACCENT, + TOKYO_NIGHT_LIGHT_ACCENT + ) + await shot('after-light-live') + + // Turning it off through the real switch restores the user's theme, live too. + await orcaPage.evaluate(() => window.__store!.getState().openSettingsPage()) + await orcaPage.getByPlaceholder('Search settings').fill('Match Claude Code') + const toggle = orcaPage.getByRole('switch', { name: 'Match Claude Code to Terminal Theme' }) + await expect(toggle).toBeChecked() + await windowShot('settings-on-light') + await toggle.click() + await expect(toggle).not.toBeChecked() + await windowShot('settings-off-light') + await expect.poll(readTheme, { timeout: 15_000 }).toBe('light') + await orcaPage.evaluate(() => window.__store!.getState().closeSettingsPage()) + const restoreMs = await expectLiveSwitch(orcaPage, TOKYO_NIGHT_LIGHT_ACCENT, CLAUDE_LIGHT_BORDER) + await shot('restored-light') + + // The same switch in dark mode, off then on. + await updateSettings({ theme: 'dark' }) + await orcaPage.evaluate(() => window.__store!.getState().openSettingsPage()) + await orcaPage.getByPlaceholder('Search settings').fill('Match Claude Code') + await expect(toggle).not.toBeChecked() + await windowShot('settings-off-dark') + await toggle.click() + await expect(toggle).toBeChecked() + await expect.poll(readTheme, { timeout: 15_000 }).toBe('custom:orca') + await windowShot('settings-on-dark') + await orcaPage.evaluate(() => window.__store!.getState().closeSettingsPage()) + testInfo.annotations.push({ + type: 'live-switch-ms', + description: JSON.stringify({ darkSwitchMs, lightSwitchMs, restoreMs }) + }) + await exitClaude(orcaPage, ptyId) +}) + +test('an existing user who declines the offer keeps Claude Code as it was and is not asked again', async ({ + electronApp, + orcaPage +}, testInfo) => { + // Two real Claude Code launches. + test.setTimeout(3 * 60_000) + const { ptyId, workDir, readTheme, shot, windowShot } = await startJourney( + electronApp, + orcaPage, + testInfo, + 'light' + ) + await startClaude(orcaPage, ptyId, workDir) + const offer = orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle }) + // Agent detection for a typed `claude` can lag its first frame. + await expect(offer).toBeVisible({ timeout: 30_000 }) + // Shoot once the slide-in settled, so the proof shows the toast as users see it. + await expect(offer).toHaveAttribute('data-mounted', 'true') + await expect(offer).toBeInViewport({ ratio: 1 }) + await expect(offer).toHaveCSS('opacity', '1') + await windowShot('offer-toast-light') + await offer.screenshot({ path: testInfo.outputPath('offer-toast-light-closeup.png') }) + await offer.getByRole('button', { name: 'No Thanks' }).click() + await expect(offer).toHaveCount(0) + await expect + .poll(() => + orcaPage.evaluate(() => window.__store!.getState().settings!.claudeCodeThemeSyncOffer) + ) + .toBe('settled') + await exitClaude(orcaPage, ptyId) + await startClaude(orcaPage, ptyId, workDir) + await expect + .poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }) + .toBe(CLAUDE_LIGHT_BORDER) + await shot('declined-light') + expect(readTheme()).toBe('light') + await expect(offer).toHaveCount(0) + await exitClaude(orcaPage, ptyId) +})