mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
feat(claude): match Claude Code's theme to the Orca terminal theme (#39447)
* feat(claude): sync the terminal theme into Claude Code * fix(claude): retry missed theme reloads, keep settings key order, search entry * fix(claude): persist theme ownership before settings writes, skip deliberate themes, restore only on toggle * fix(claude): gate theme sync on Claude Code 2.1.119, follow Orca's Claude config dirs, keep restores owed * refactor(theme): point markdown Monaco rules at the shared contrast helpers * fix(claude): lock theme ownership edits across Orca processes, retry missed theme reloads with backoff * test(e2e): opt-in real Claude Code theme sync journey; retry theme reloads for up to five minutes * fix(claude): keep theme takeover recoverable when settings writes or the lock fail; steadier e2e journey * fix(claude): serialize theme publication with takeover and restore, per-file reload retries; record the real-Claude e2e in the isolated home * fix(claude): retry an owed restore publish, stop off-state retries, reread settings right before writing * fix(claude): republish theme files under the cross-process lock * refactor(theme): point chat selection contrast at the shared helpers * feat(claude): default theme sync on for new profiles; offer it once to existing users at their next Claude launch * fix(claude): offer theme sync to every existing profile, confirm only after the save, honest offer copy * fix(claude): right-align the theme sync offer's two actions, primary last
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<string, ClaudeThemeOwnership>
|
||||
|
||||
// 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<OwnershipByConfigDir | null> {
|
||||
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<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<T>(
|
||||
configDir: string,
|
||||
edit: (slot: ClaudeThemeOwnershipSlot) => Promise<T>
|
||||
): Promise<T> {
|
||||
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<T>(run: () => Promise<T>): Promise<T> {
|
||||
return await withManagedHookInstallLock(homedir(), undefined, run)
|
||||
}
|
||||
@@ -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<GlobalSettings, 'claudeCodeThemeSync'> &
|
||||
Parameters<typeof resolveTerminalPalette>[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<void> {
|
||||
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<GlobalSettings>) => 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<typeof setTimeout> | null = null
|
||||
// Per file, so a pass that touches one config folder keeps another folder's pending retries.
|
||||
const retryTimers = new Map<string, ReturnType<typeof setTimeout>[]>()
|
||||
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()
|
||||
}
|
||||
@@ -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<typeof ClaudeHookEventVersions>()),
|
||||
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)
|
||||
}
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -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<void> {
|
||||
// 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<string[]> {
|
||||
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<string[]> {
|
||||
// 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<string>
|
||||
): 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<string[]> {
|
||||
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<ClaudeCodeThemeSyncResult> {
|
||||
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<string>()
|
||||
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
|
||||
}
|
||||
@@ -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<string, string>
|
||||
}
|
||||
|
||||
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<string, Rgba | null> = {
|
||||
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] : []
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -14,7 +14,8 @@ type LoadedCohortMigrationOperationsRuntime = Pick<StoreRuntimeState, 'loadNeeds
|
||||
export class LoadedCohortMigrationOperations {
|
||||
constructor(private readonly runtime: LoadedCohortMigrationOperationsRuntime) {}
|
||||
|
||||
migrateKeybindings(state: PersistedState, fileExistedOnLoad: boolean): PersistedState {
|
||||
/** Freezes each rollout's new-or-existing cohort on first load, before a save makes a fresh install look existing. */
|
||||
migrateCohortSeeds(state: PersistedState, fileExistedOnLoad: boolean): PersistedState {
|
||||
// Secondary profiles start with only the install's telemetry consent, before their first load.
|
||||
const telemetryOnly =
|
||||
Object.keys(state).length === 1 &&
|
||||
@@ -37,6 +38,21 @@ export class LoadedCohortMigrationOperations {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.settings?.claudeCodeThemeSyncOffer === undefined) {
|
||||
this.runtime.loadNeedsSave = true
|
||||
// Why: existing users keep Claude Code's look until they accept the offer at their next Claude launch.
|
||||
// Not keyed on a saved claudeCodeThemeSync: offline writers copy the default (on) into old profiles.
|
||||
const offer = existingProfile
|
||||
state = {
|
||||
...state,
|
||||
settings: {
|
||||
...state.settings,
|
||||
...(offer
|
||||
? { claudeCodeThemeSync: false, claudeCodeThemeSyncOffer: 'pending' as const }
|
||||
: { claudeCodeThemeSyncOffer: 'settled' as const })
|
||||
}
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ export class LoadedStateParsingOperations {
|
||||
if (parsed === undefined) {
|
||||
throw new Error('Profile state startup snapshot is missing')
|
||||
}
|
||||
parsed = this.cohorts.migrateKeybindings(parsed, true)
|
||||
parsed = this.cohorts.migrateCohortSeeds(parsed, true)
|
||||
// Freeze audience before defaults or migrations alter the saved Chat UI state.
|
||||
chatUiLaunchTipAudience = this.cohorts.captureChatUiLaunchTipAudience(parsed)
|
||||
this.runtime.originalExperimentalNativeChat =
|
||||
@@ -196,7 +196,7 @@ export class LoadedStateParsingOperations {
|
||||
}
|
||||
|
||||
if (result === null) {
|
||||
result = this.cohorts.migrateKeybindings(getDefaultPersistedState(homedir()), false)
|
||||
result = this.cohorts.migrateCohortSeeds(getDefaultPersistedState(homedir()), false)
|
||||
}
|
||||
|
||||
const workspaceSession = pruneWorkspaceSessionBrowserHistory(
|
||||
|
||||
@@ -45,6 +45,7 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../shared/layout-owner-switch'
|
||||
import { repairDuplicatePtyPanesOnStart } from '../runtime/moved-pane-owner-rekey'
|
||||
import { WslUsageReporter } from '../telemetry/wsl-usage-reporter'
|
||||
import { ALL_RPC_METHODS } from '../runtime/rpc/methods/rpc-method-registry'
|
||||
import { startClaudeCodeThemeSync } from '../claude/theme-sync/claude-code-theme-sync-schedule'
|
||||
|
||||
// Headless serve has no first window; timer fallback must still sweep trash.
|
||||
const WORKTREE_TRASH_SWEEP_FALLBACK_MS = 15_000
|
||||
@@ -125,6 +126,16 @@ export async function initializeReadyRuntimeServices(): Promise<void> {
|
||||
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({
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -26,6 +26,7 @@ export const SETTING_LABELS: Partial<Record<keyof GlobalSettings, string>> = {
|
||||
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',
|
||||
|
||||
@@ -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 ? (
|
||||
<ClaudeCodeThemeSyncSetting settings={settings} updateSettings={updateSettings} />
|
||||
) : null}
|
||||
|
||||
{showDesktopThemeImports ? (
|
||||
<>
|
||||
<TerminalConfigImportModal
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
getTerminalPaneInteractionSearchEntries
|
||||
} from './appearance/terminal-pane-appearance-search'
|
||||
import {
|
||||
getClaudeCodeThemeSyncSearchEntry,
|
||||
getTerminalDarkThemeSearchEntries,
|
||||
getTerminalLightThemeSearchEntries,
|
||||
getTerminalThemeTargetSearchEntries,
|
||||
@@ -52,12 +53,14 @@ const getTerminalAppearanceSearchEntriesWithoutImports = createLocalizedCatalog(
|
||||
)
|
||||
|
||||
// Compose catalogs because translated titles cannot reliably identify desktop-only entries.
|
||||
// Claude Code theme sync writes this computer's Claude config, so web clients do not offer it.
|
||||
const getTerminalAppearanceSearchEntriesWithImports = createLocalizedCatalog(
|
||||
(): SettingsSearchEntry[] => [
|
||||
...getTerminalAppearanceSearchEntriesWithoutImports(),
|
||||
...getTerminalConfigImportSearchEntries(),
|
||||
...getTerminalWarpImportSearchEntries(),
|
||||
...getTerminalYamlImportSearchEntries()
|
||||
...getTerminalYamlImportSearchEntries(),
|
||||
...getClaudeCodeThemeSyncSearchEntry()
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -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<GlobalSettings>) => void
|
||||
}): React.JSX.Element {
|
||||
const [entry] = getClaudeCodeThemeSyncSearchEntry()
|
||||
return (
|
||||
<div className="ml-4">
|
||||
<SearchableSetting {...entry} className="border-y border-border/40">
|
||||
<SettingsSwitchRow
|
||||
label={entry.title}
|
||||
description={entry.description}
|
||||
checked={settings.claudeCodeThemeSync}
|
||||
onChange={() => updateSettings({ claudeCodeThemeSync: !settings.claudeCodeThemeSync })}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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')
|
||||
]
|
||||
}
|
||||
])
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+4
-4
@@ -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()
|
||||
})
|
||||
+11
-9
@@ -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()
|
||||
}
|
||||
+78
@@ -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])
|
||||
}
|
||||
+2
-2
@@ -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])
|
||||
}
|
||||
|
||||
+2
-2
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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('')}`
|
||||
}
|
||||
@@ -97,6 +97,7 @@ export function buildDefaultSettings(args: {
|
||||
terminalUseSeparateLightTheme: true,
|
||||
terminalColorOverridesSplit: true,
|
||||
terminalThemeLight: 'Builtin Tango Light',
|
||||
claudeCodeThemeSync: true,
|
||||
terminalCustomThemes: [],
|
||||
terminalDividerColorLight: '#d4d4d8',
|
||||
terminalInactivePaneOpacity: args.terminalInactivePaneOpacity,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<number | null> {
|
||||
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<number> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<string, unknown>) => Promise<unknown>
|
||||
shot: (name: string) => Promise<unknown>
|
||||
windowShot: (name: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
/** 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<Journey> {
|
||||
await waitForSessionReady(orcaPage)
|
||||
await ensureTerminalVisible(orcaPage)
|
||||
await waitForActiveTerminalManager(orcaPage)
|
||||
const updateSettings = (updates: Record<string, unknown>) =>
|
||||
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<string, unknown> => {
|
||||
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)
|
||||
})
|
||||
Reference in New Issue
Block a user