The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(themes): one sRGB color-math module in @hermes/shared; measured readableOn + fine ensureContrast ladder on both surfaces
teknium135022e02edcb
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex e1880bc8eff..c9c066a4b37 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1746,10 +1746,10 @@ export { ackStoredSessionId, forgetSessionUnread, markSessionUnreadFinished } fr* a setting, so a plugin that sets it must clear it on dispose. */export { $accentOverride, setAccentOverride } from '@/themes/accent-override'/** OKLCH colour maths, for anything deriving a palette rather than hardcoding- * one: perceptual conversion, the sRGB gamut boundary, WCAG contrast, and- * hue-stable blending. */+ * one: perceptual conversion, the sRGB gamut boundary, and hue-stable+ * blending. `readableOn` is the SDK's public name for the desktop's ink pick+ * (`#161616` or `#ffffff`, whichever measures better on the background). */export {- contrastRatio,hexToOklch,hueDelta,maxChroma,@@ -1758,7 +1758,7 @@ export {type Oklch,oklchToHex,oklchToSrgb255,- readableOn+ readableInk as readableOn} from '@/themes/color'/** The painted theme, its name, and the appearance it resolved to — plus* `setTheme` / `setMode` to change it from a component. */@@ -1785,6 +1785,9 @@ export {REASONING_EFFORTS,type ReasoningEffort} from '@hermes/shared'+/** WCAG contrast, from the sRGB primitives shared with the TUI (`null` for+ * an unparseable colour, never a fake 0). */+export { contrastRatio } from '@hermes/shared/color'/** Subscribe a component to a `host.state` atom. */export { useStore as useValue } from '@nanostores/react'/** The app's data-fetching layer. Plugins share the ONE QueryClient mounted atdiff --git a/apps/desktop/src/themes/color.ts b/apps/desktop/src/themes/color.tsindex 313ec8d2a27..60019414580 100644--- a/apps/desktop/src/themes/color.ts+++ b/apps/desktop/src/themes/color.ts@@ -1,106 +1,24 @@/**- * Small color helpers shared by the theme context (synthesised light variants)- * and the VS Code theme converter (token → seed mapping).+ * Desktop-only color helpers: the naive light/dark bucketer, the VS Code hex+ * normaliser, and the OKLCH toolkit. The sRGB primitives (parse/mix/measure/+ * ensureContrast) live in `@hermes/shared/color` and are shared with the TUI.** Everything works in 6-digit `#rrggbb`. `normalizeHex` is the front door for* untrusted input (VS Code themes use `#rgb`, `#rgba`, `#rrggbbaa`, and named* tokens), flattening alpha over a backdrop so downstream math stays simple.*/-export function hexToRgb(hex: string): [number, number, number] | null {- const clean = hex.trim().replace(/^#/, '')+import { contrastRatio, parseColor, readableOn, relativeLuminance, toHex } from '@hermes/shared/color'- if (!/^[0-9a-f]{6}$/i.test(clean)) {- return null- }-- return [0, 2, 4].map(i => parseInt(clean.slice(i, i + 2), 16)) as [number, number, number]-}--export const rgbToHex = ([r, g, b]: [number, number, number]): string =>- `#${[r, g, b]- .map(n =>- Math.round(Math.min(255, Math.max(0, n)))- .toString(16)- .padStart(2, '0')- )- .join('')}`--export function mix(a: string, b: string, amount: number): string {- const ar = hexToRgb(a)- const br = hexToRgb(b)-- return ar && br- ? rgbToHex([ar[0] + (br[0] - ar[0]) * amount, ar[1] + (br[1] - ar[1]) * amount, ar[2] + (br[2] - ar[2]) * amount])- : a-}--const linearize = (channel: number): number =>- channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4+/** The desktop's ink pair: its near-black text colour, not pure black. */+const DESKTOP_INKS = ['#161616', '#ffffff'] as const-/** WCAG relative luminance (gamma-corrected), 0..1. */-export function relativeLuminance(hex: string): number {- const rgb = hexToRgb(hex)-- if (!rgb) {- return 0- }-- const [r, g, b] = rgb.map(v => linearize(v / 255))-- return 0.2126 * r + 0.7152 * g + 0.0722 * b-}--/** WCAG contrast ratio (1..21) between two hex colors. */-export function contrastRatio(a: string, b: string): number {- const la = relativeLuminance(a)- const lb = relativeLuminance(b)-- return la >= lb ? (la + 0.05) / (lb + 0.05) : (lb + 0.05) / (la + 0.05)-}--/**- * A readable foreground (`#161616` or `#ffffff`) for a background hex.- *- * Picks whichever of the two actually measures better, rather than splitting on- * a luminance threshold. The threshold version got mid-lightness accents wrong- * in the direction that matters — white on GitHub's dark green `#4f9e5e` is- * 3.29:1 (fails AA) where near-black is 5.50:1, and Catppuccin's mauve was a- * 2.03:1 white-on-lilac. Two candidates is a cheap enough search to just- * measure.- */-export function readableOn(hex: string): string {- return contrastRatio(hex, '#ffffff') >= contrastRatio(hex, '#161616') ? '#ffffff' : '#161616'-}--/**- * Guarantee `color` reads against `bg`: if it's below `min` contrast, mix it- * toward white (on a dark bg) or black (on a light bg) in steps until it clears,- * keeping the hue as much as possible. Used so imported accents never collapse- * into a near-background sidebar (the "invisible label" case).- */-export function ensureContrast(color: string, bg: string, min: number): string {- if (contrastRatio(color, bg) >= min) {- return color- }-- const towards = relativeLuminance(bg) < 0.5 ? '#ffffff' : '#000000'- let best = color-- for (let amount = 0.2; amount <= 1.0001; amount += 0.2) {- best = mix(color, towards, Math.min(amount, 1))-- if (contrastRatio(best, bg) >= min) {- return best- }- }-- return best-}+/** A readable foreground (`#161616` or `#ffffff`) for a background hex. */+export const readableInk = (bg: string): string => readableOn(bg, DESKTOP_INKS)/** Perceptual-ish luminance in 0..1 (naive, for light/dark bucketing). */export function luminance(hex: string): number {- const rgb = hexToRgb(hex)+ const rgb = parseColor(hex)if (!rgb) {return 0@@ -136,20 +54,20 @@ export function normalizeHex(input: string | undefined | null, backdrop = '#0000return null}- const rgb = hexToRgb(`#${clean.slice(0, 6)}`)+ const rgb = parseColor(`#${clean.slice(0, 6)}`)if (!rgb) {return null}if (clean.length === 6) {- return rgbToHex(rgb)+ return toHex(rgb)}const alpha = parseInt(clean.slice(6, 8), 16) / 255- const base = hexToRgb(backdrop) ?? [0, 0, 0]+ const base = parseColor(backdrop) ?? [0, 0, 0]- return rgbToHex([+ return toHex([base[0] + (rgb[0] - base[0]) * alpha,base[1] + (rgb[1] - base[1]) * alpha,base[2] + (rgb[2] - base[2]) * alpha@@ -174,7 +92,7 @@ export interface Oklch {}export function hexToOklch(hex: string): Oklch | null {- const rgb = hexToRgb(hex)+ const rgb = parseColor(hex)if (!rgb) {return null@@ -241,7 +159,7 @@ const inSrgbGamut = (rgb: readonly number[]): boolean => rgb.every(c => c >= -0.*/export function oklchToHex(color: Oklch): string {if (inSrgbGamut(oklchToRgbRaw(color))) {- return rgbToHex(oklchToRgbRaw(color).map(c => delinearize01(c) * 255) as [number, number, number])+ return toHex(oklchToRgbRaw(color).map(c => delinearize01(c) * 255) as [number, number, number])}let lo = 0@@ -257,7 +175,7 @@ export function oklchToHex(color: Oklch): string {}}- return rgbToHex(oklchToRgbRaw({ ...color, c: lo }).map(c => delinearize01(c) * 255) as [number, number, number])+ return toHex(oklchToRgbRaw({ ...color, c: lo }).map(c => delinearize01(c) * 255) as [number, number, number])}/**@@ -346,8 +264,8 @@ export function harmonize(hex: string, accent: string, strength: number): string* blending neutrals, where there is no hue to preserve.*/export function mixOklab(a: string, b: string, amount: number): string {- const ra = hexToRgb(a)- const rb = hexToRgb(b)+ const ra = parseColor(a)+ const rb = parseColor(b)if (!ra || !rb) {return a@@ -379,7 +297,9 @@ export function withHue(hex: string, hue: number): string {* ends of the lightness range rather than looping.*/export function ensureContrastOklch(hex: string, bg: string, min: number): string {- if (contrastRatio(hex, bg) >= min) {+ const ratio = contrastRatio(hex, bg)++ if (ratio === null || ratio >= min) {return hex}@@ -390,7 +310,7 @@ export function ensureContrastOklch(hex: string, bg: string, min: number): strin}// Lighten on a dark backdrop, darken on a light one.- const up = relativeLuminance(bg) < 0.5+ const up = (relativeLuminance(bg) ?? 0) < 0.5let best = hexfor (let step = 1; step <= 40; step += 1) {@@ -402,7 +322,7 @@ export function ensureContrastOklch(hex: string, bg: string, min: number): strinbest = oklchToHex({ ...lch, l })- if (contrastRatio(best, bg) >= min) {+ if ((contrastRatio(best, bg) ?? 0) >= min) {return best}}diff --git a/apps/desktop/src/themes/context.tsx b/apps/desktop/src/themes/context.tsxindex 44635d50877..cc556225afb 100644--- a/apps/desktop/src/themes/context.tsx+++ b/apps/desktop/src/themes/context.tsx@@ -9,6 +9,7 @@* The two are persisted independently. Shift+X toggles light/dark.*/+import { ensureContrast, mix, parseColor } from '@hermes/shared/color'import { useStore } from '@nanostores/react'import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'@@ -20,7 +21,7 @@ import { setAppearance } from '@/store/translucency'import { $accentOverride } from './accent-override'import { $backendThemes, $pendingSkinApply } from './backend-sync'-import { ensureContrast, harmonize, hexToRgb, mix, readableOn } from './color'+import { harmonize, readableInk } from './color'import { BUILTIN_THEME_LIST, DEFAULT_SKIN_NAME, DEFAULT_TYPOGRAPHY, nousTheme } from './presets'import { retintTheme } from './retint'import type { DesktopTheme, DesktopThemeColors } from './types'@@ -102,8 +103,8 @@ const readBootProfileKey = () => normalizeProfileKey(storedString(LAST_PROFILE_Kconst rememberActiveProfileKey = (profile: string) => persistString(LAST_PROFILE_KEY, profile)// ─── Color math (for synthesised light variants of dark-only skins) ────────-// hexToRgb / mix / readableOn live in ./color so the VS Code converter shares-// the exact same math.+// mix / ensureContrast live in @hermes/shared/color (shared with the TUI);+// readableInk in ./color pins the desktop's near-black ink.function synthLightColors(seed: DesktopTheme): DesktopThemeColors {const accent = seed.colors.ring || seed.colors.primary@@ -122,7 +123,7 @@ function synthLightColors(seed: DesktopTheme): DesktopThemeColors {popover: '#ffffff',popoverForeground: '#161616',primary: accent,- primaryForeground: readableOn(accent),+ primaryForeground: readableInk(accent),secondary: soft,secondaryForeground: mix('#2a2a2a', accent, 0.34),accent: soft,@@ -131,7 +132,7 @@ function synthLightColors(seed: DesktopTheme): DesktopThemeColors {input: mix('#e2e2e6', accent, 0.18),ring: accent,midground,- midgroundForeground: readableOn(midground),+ midgroundForeground: readableInk(midground),destructive: '#b94a3a',destructiveForeground: '#ffffff',sidebarBackground: mix('#fafafa', accent, 0.05),@@ -170,7 +171,7 @@ function deriveTheme(skinName: string, mode: 'light' | 'dark'): DesktopTheme {* the actual background luminance.*/function renderedModeFor(colors: DesktopThemeColors, mode: 'light' | 'dark'): 'light' | 'dark' {- const rgb = hexToRgb(colors.background)+ const rgb = parseColor(colors.background)if (!rgb) {return mode@@ -253,7 +254,7 @@ function applyTheme(theme: DesktopTheme, mode: 'light' | 'dark') {'--dt-input': c.input,'--dt-ring': c.ring,'--dt-muted': c.muted,- '--dt-midground-foreground': c.midgroundForeground ?? readableOn(midground),+ '--dt-midground-foreground': c.midgroundForeground ?? readableInk(midground),// A LOUD fill of the brand colour, for the rare surface that has to read as// the app speaking rather than as chrome. `primary` alone can't do that job:// a pale accent (imported VS Code themes love a pastel pink) is a perfectlydiff --git a/apps/desktop/src/themes/retint.test.ts b/apps/desktop/src/themes/retint.test.tsindex 9422b222f99..3e10745e495 100644--- a/apps/desktop/src/themes/retint.test.ts+++ b/apps/desktop/src/themes/retint.test.ts@@ -1,6 +1,7 @@+import { contrastRatio } from '@hermes/shared/color'import { describe, expect, it } from 'vitest'-import { contrastRatio, hexToOklch, withHue } from './color'+import { hexToOklch, withHue } from './color'import { githubTheme, nousTheme } from './presets'import { retintTheme, themeHue } from './retint'import type { DesktopThemeColors } from './types'diff --git a/apps/desktop/src/themes/retint.ts b/apps/desktop/src/themes/retint.tsindex 2f9c3b5b030..ff7edb4ec5c 100644--- a/apps/desktop/src/themes/retint.ts+++ b/apps/desktop/src/themes/retint.ts@@ -34,7 +34,7 @@ import {normalizeHex,type Oklch,oklchToHex,- readableOn+ readableInk} from './color'import type { DesktopTheme, DesktopThemeColors } from './types'@@ -117,8 +117,8 @@ function retintColors(colors: DesktopThemeColors, seed: string, isDark: boolean)// Foregrounds that sit ON the accent have to be re-picked: a new seed can// cross the light/dark readability boundary.- next.primaryForeground = readableOn(seed)- next.midgroundForeground = readableOn(seed)+ next.primaryForeground = readableInk(seed)+ next.midgroundForeground = readableInk(seed)return next}diff --git a/apps/desktop/src/themes/skin.ts b/apps/desktop/src/themes/skin.tsindex 61fa711220a..abfaebea0eb 100644--- a/apps/desktop/src/themes/skin.ts+++ b/apps/desktop/src/themes/skin.ts@@ -15,9 +15,10 @@* still picks `.dark` from the real background luminance.*/+import { ensureContrast, mix } from '@hermes/shared/color'import type { HermesSkin, SkinColors } from '@hermes/shared/skin'-import { ensureContrast, luminance, mix, normalizeHex, readableOn } from './color'+import { luminance, normalizeHex, readableInk } from './color'import type { DesktopTheme, DesktopThemeColors } from './types'// The accent labels the sidebar in small uppercase text, so it must clear WCAG AA@@ -86,7 +87,7 @@ export function skinToDesktopTheme(skin: HermesSkin): DesktopTheme | null {popover: mix(background, foreground, dark ? 0.08 : 0.05),popoverForeground: foreground,primary: accent,- primaryForeground: readableOn(accent),+ primaryForeground: readableInk(accent),secondary: mix(accent, background, dark ? 0.72 : 0.86),secondaryForeground: foreground,accent: mix(accent, background, dark ? 0.82 : 0.88),@@ -95,10 +96,10 @@ export function skinToDesktopTheme(skin: HermesSkin): DesktopTheme | null {input: pick(colors, ['completion_menu_bg'], background) ?? mix(background, foreground, dark ? 0.1 : 0.06),ring: accent,midground: accent,- midgroundForeground: readableOn(accent),+ midgroundForeground: readableInk(accent),composerRing: accent,destructive,- destructiveForeground: readableOn(destructive),+ destructiveForeground: readableInk(destructive),sidebarBackground: sidebar,sidebarBorder: border,userBubble: mix(background, accent, dark ? 0.18 : 0.12),diff --git a/apps/desktop/src/themes/vscode.test.ts b/apps/desktop/src/themes/vscode.test.tsindex ac7cc9f9bd9..3798bbca2e6 100644--- a/apps/desktop/src/themes/vscode.test.ts+++ b/apps/desktop/src/themes/vscode.test.ts@@ -1,6 +1,6 @@+import { contrastRatio } from '@hermes/shared/color'import { describe, expect, it } from 'vitest'-import { contrastRatio } from './color'import { convertVscodeColorTheme, parseVscodeTheme, vscodeThemeSlug } from './vscode'describe('vscodeThemeSlug', () => {diff --git a/apps/desktop/src/themes/vscode.ts b/apps/desktop/src/themes/vscode.tsindex 77340f9ea41..d1dc3c13dd3 100644--- a/apps/desktop/src/themes/vscode.ts+++ b/apps/desktop/src/themes/vscode.ts@@ -15,7 +15,9 @@* background luminance, so surface-bound UI matches what's on screen.*/-import { ensureContrast, luminance, mix, normalizeHex, readableOn } from './color'+import { ensureContrast, mix } from '@hermes/shared/color'++import { luminance, normalizeHex, readableInk } from './color'import type { DesktopTerminalPalette, DesktopTheme, DesktopThemeColors } from './types'// Section headers / sidebar labels render in --theme-primary directly on the@@ -327,7 +329,7 @@ export function convertVscodeColorTheme(raw: VscodeColorTheme, opts: ConvertOptipopover: elevated,popoverForeground: foreground,primary: accent,- primaryForeground: readableOn(accent),+ primaryForeground: readableInk(accent),secondary,secondaryForeground: foreground,accent: accentSoft,@@ -336,10 +338,10 @@ export function convertVscodeColorTheme(raw: VscodeColorTheme, opts: ConvertOptiinput,ring: accent,midground: accent,- midgroundForeground: readableOn(accent),+ midgroundForeground: readableInk(accent),composerRing: accent,destructive,- destructiveForeground: readableOn(destructive),+ destructiveForeground: readableInk(destructive),sidebarBackground: sidebar,sidebarBorder: border,userBubble: mix(card, accent, dark ? 0.18 : 0.12),diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.jsonindex 6fee8d9da45..f1971402243 100644--- a/apps/desktop/tsconfig.json+++ b/apps/desktop/tsconfig.json@@ -20,6 +20,7 @@"@hermes/plugin-sdk": ["./src/sdk/index.ts"],"@hermes/shared/ansi": ["../shared/src/ansi.ts"],"@hermes/shared/billing": ["../shared/src/billing-types.ts"],+ "@hermes/shared/color": ["../shared/src/color.ts"],"@hermes/shared/i18n": ["../shared/src/i18n.ts"],"@hermes/shared/translucency": ["../shared/src/translucency.ts"],"@hermes/shared": ["../shared/src/index.ts"]diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.tsindex b6d895f348b..25269efb0be 100644--- a/apps/desktop/vite.config.ts+++ b/apps/desktop/vite.config.ts@@ -1,6 +1,6 @@-import { defineConfig } from 'vite'import babel from '@rolldown/plugin-babel'import react, { reactCompilerPreset } from '@vitejs/plugin-react'+import { defineConfig } from 'vite'/** React Compiler preset scoped to modules that can actually contain* components/hooks (JSX syntax or a react-ish import). The preset's default@@ -10,12 +10,15 @@ import react, { reactCompilerPreset } from '@vitejs/plugin-react'function compilerPreset() {const preset = reactCompilerPreset()preset.rolldown.filter.code = /\/>|<\/|from\s*['"][^'"]*react/+return preset}-import tailwindcss from '@tailwindcss/vite'-import path from 'path'+import fs from 'fs'import { createRequire } from 'module'+import path from 'path'++import tailwindcss from '@tailwindcss/vite'// `hgui` symlinks a worktree's node_modules to the main checkout. Vite realpaths// those before enforcing server.fs.allow, so codicon/font assets resolve outside@@ -80,9 +83,10 @@ const emojibaseAssets = () => ({}) {server.middlewares.use('/emojibase', (req, res, next) => {const rel = (req.url ?? '').split('?')[0].replace(/^\/+/, '')- if (!emojibaseDir || !EMOJIBASE_PATH.test(rel)) return next()++ if (!emojibaseDir || !EMOJIBASE_PATH.test(rel)) {return next()}fs.readFile(path.join(emojibaseDir, rel), (err: unknown, buf: Buffer) => {- if (err) return next()+ if (err) {return next()}res.setHeader('Content-Type', 'application/json')res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')res.end(buf)@@ -90,7 +94,8 @@ const emojibaseAssets = () => ({})},generateBundle(this: { emitFile: (asset: { type: 'asset'; fileName: string; source: Uint8Array }) => void }) {- if (!emojibaseDir) return+ if (!emojibaseDir) {return}+for (const rel of ['en/data.json', 'en/messages.json', 'en/shortcodes/emojibase.json']) {this.emitFile({type: 'asset',@@ -202,6 +207,7 @@ export default defineConfig(({ command }) => ({'@': path.resolve(__dirname, './src'),'@hermes/plugin-sdk': path.resolve(__dirname, './src/sdk/index.ts'),'@hermes/shared/billing': path.resolve(__dirname, '../shared/src/billing-types.ts'),+ '@hermes/shared/color': path.resolve(__dirname, '../shared/src/color.ts'),'@hermes/shared': path.resolve(__dirname, '../shared/src'),// The tour tool's preview surface injects driver.js's prebuilt IIFE into// the pane's guest page as raw source; the package's exports map doesn'tdiff --git a/apps/shared/package.json b/apps/shared/package.jsonindex 23cb4350ad8..3aa4faa0ec7 100644--- a/apps/shared/package.json+++ b/apps/shared/package.json@@ -9,6 +9,7 @@"./billing": "./src/billing-types.ts","./billing-policy": "./src/billing-policy.ts","./charge-settlement": "./src/charge-settlement.ts",+ "./color": "./src/color.ts","./format": "./src/format.ts","./fuzzy": "./src/fuzzy.ts","./gateway-events": "./src/gateway-events.ts",diff --git a/apps/shared/src/color.test.ts b/apps/shared/src/color.test.tsnew file mode 100644index 00000000000..98d4ada19f3--- /dev/null+++ b/apps/shared/src/color.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest'++import { contrastRatio, ensureContrast, mix, parseColor, readableOn, relativeLuminance, toHex } from './color'++describe('parseColor', () => {+ it('parses hex6, hex3 and rgb() forms', () => {+ expect(parseColor('#1a2b3c')).toEqual([0x1a, 0x2b, 0x3c])+ expect(parseColor('1a2b3c')).toEqual([0x1a, 0x2b, 0x3c])+ expect(parseColor('#abc')).toEqual([0xaa, 0xbb, 0xcc])+ expect(parseColor('rgb(220,255,220)')).toEqual([220, 255, 220])+ expect(parseColor('rgba(10, 20, 30, 0.5)')).toEqual([10, 20, 30])+ })++ it('rejects garbage', () => {+ expect(parseColor('')).toBeNull()+ expect(parseColor('ansi256(245)')).toBeNull()+ expect(parseColor('#12345')).toBeNull()+ })+})++describe('mix', () => {+ it('lerps in sRGB and round-trips through toHex', () => {+ expect(mix('#000000', '#ffffff', 0.5)).toBe('#808080')+ expect(mix('#ff0000', '#0000ff', 0)).toBe('#ff0000')+ expect(mix('#ff0000', '#0000ff', 1)).toBe('#0000ff')+ expect(toHex(parseColor(mix('#123456', '#654321', 0.3))!)).toBe(mix('#123456', '#654321', 0.3))+ })++ it('passes unparseable inputs through unchanged', () => {+ expect(mix('ansi256(245)', '#ffffff', 0.5)).toBe('ansi256(245)')+ expect(mix('#ff0000', 'nope', 0.5)).toBe('#ff0000')+ })+})++describe('contrast', () => {+ it('measures WCAG ratios at the anchors and refuses to measure garbage', () => {+ expect(contrastRatio('#000000', '#ffffff')).toBeCloseTo(21, 0)+ expect(contrastRatio('#ffffff', '#ffffff')).toBeCloseTo(1, 5)+ expect(relativeLuminance('#ffffff')).toBeCloseTo(1, 5)+ expect(relativeLuminance('#000000')).toBeCloseTo(0, 5)+ expect(relativeLuminance('ansi256(245)')).toBeNull()+ expect(contrastRatio('#ffffff', 'ansi256(245)')).toBeNull()+ })++ // Mid-lightness accents are where a luminance threshold and a measurement+ // disagree: GitHub green #4f9e5e sits just under L=0.5 (threshold → white,+ // 3.29:1) while near-black measures 5.50:1. The contract is "the ink that+ // measures better", so assert against the measurement, not a hardcoded hex.+ it.each([+ ['#4f9e5e', ['#000000', '#ffffff']],+ ['#4f9e5e', ['#161616', '#ffffff']],+ ['#cba6f7', ['#161616', '#ffffff']],+ ['#ffffff', ['#000000', '#ffffff']],+ ['#101014', ['#000000', '#ffffff']]+ ] as const)('readableOn(%s) returns the ink with the higher measured contrast', (bg, inks) => {+ const best = inks.reduce((a, b) => (contrastRatio(bg, b)! > contrastRatio(bg, a)! ? b : a))++ expect(readableOn(bg, inks)).toBe(best)+ })++ it('readableOn defaults to the black/white poles', () => {+ expect(readableOn('#ffffff')).toBe('#000000')+ expect(readableOn('#101014')).toBe('#ffffff')+ })++ it.each([+ ['#FFF8DC', '#ffffff', 3.9],+ ['#4f9e5e', '#ffffff', 4.5],+ ['#3a3a5c', '#101014', 4.5],+ ['#0053fd', '#161616', 4.5],+ ['#cba6f7', '#ffffff', 7]+ ])('ensureContrast(%s on %s) clears %s', (color, bg, min) => {+ const fixed = ensureContrast(color, bg, min)++ expect(contrastRatio(fixed, bg)!).toBeGreaterThanOrEqual(min)+ })++ it('ensureContrast leaves passing and unparseable colors byte-identical', () => {+ expect(ensureContrast('#3D2F13', '#ffffff', 3.9)).toBe('#3D2F13')+ expect(ensureContrast('ansi256(245)', '#ffffff', 3.9)).toBe('ansi256(245)')+ })+})diff --git a/apps/shared/src/color.ts b/apps/shared/src/color.tsnew file mode 100644index 00000000000..86e35f79b33--- /dev/null+++ b/apps/shared/src/color.ts@@ -0,0 +1,155 @@+/**+ * THE sRGB color primitive for every TypeScript surface (desktop themes, the+ * Ink TUI). Parse, mix, measure and fix colors here so tone ladders, contrast+ * floors and one-off UI needs share one set of semantics — and so the two+ * surfaces can never drift apart on what "readable" means again.+ *+ * Mixing is an sRGB lerp — deliberately, for byte parity with the desktop's+ * `color-mix(in srgb, ...)` ladder in styles.css. Perceptual (OKLCH) math is+ * desktop-only and lives in `apps/desktop/src/themes/color.ts`.+ *+ * Everything that measures returns `null` for unparseable input rather than 0:+ * a silent 0 makes `ansi256(245)` look like pure black and passes garbage+ * through contrast checks as if it were a real measurement.+ */++export type Rgb = readonly [number, number, number]++const HEX6_RE = /^#?([0-9a-f]{6})$/i+const HEX3_RE = /^#?([0-9a-f]{3})$/i+const RGB_FN_RE = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/i++const clampChannel = (v: number) => Math.max(0, Math.min(255, Math.round(v)))++/** Parse `#rgb`, `#rrggbb` or `rgb(r,g,b)` → channels. Null for anything else. */+export function parseColor(input: string): Rgb | null {+ const value = input.trim()++ let m = HEX6_RE.exec(value)++ if (m) {+ const n = parseInt(m[1]!, 16)++ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]+ }++ m = HEX3_RE.exec(value)++ if (m) {+ const [r, g, b] = m[1]!++ return [parseInt(r! + r!, 16), parseInt(g! + g!, 16), parseInt(b! + b!, 16)]+ }++ m = RGB_FN_RE.exec(value)++ if (m) {+ return [clampChannel(Number(m[1])), clampChannel(Number(m[2])), clampChannel(Number(m[3]))]+ }++ return null+}++export const toHex = (rgb: Rgb): string => '#' + rgb.map(c => clampChannel(c).toString(16).padStart(2, '0')).join('')++/** sRGB lerp `a → b` by `t` in [0,1]. Unparseable inputs return `a` unchanged. */+export function mix(a: string, b: string, t: number): string {+ const pa = parseColor(a)+ const pb = parseColor(b)++ if (!pa || !pb) {+ return a+ }++ return toHex([pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t, pa[2] + (pb[2] - pa[2]) * t])+}++function channelLuminance(value: number): number {+ const normalized = value / 255++ return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4+}++/** WCAG relative luminance in [0,1]. Null when unparseable. */+export function relativeLuminance(color: string): null | number {+ const rgb = parseColor(color)++ return rgb+ ? 0.2126 * channelLuminance(rgb[0]) + 0.7152 * channelLuminance(rgb[1]) + 0.0722 * channelLuminance(rgb[2])+ : null+}++/** WCAG contrast ratio between two colors (1–21). Null when unparseable. */+export function contrastRatio(a: string, b: string): null | number {+ const la = relativeLuminance(a)+ const lb = relativeLuminance(b)++ if (la === null || lb === null) {+ return null+ }++ const [hi, lo] = la >= lb ? [la, lb] : [lb, la]++ return (hi + 0.05) / (lo + 0.05)+}++const DEFAULT_INKS = ['#000000', '#ffffff'] as const++/**+ * The readable ink for a background: whichever candidate MEASURES better.+ *+ * Splitting on a luminance threshold got mid-lightness accents wrong in the+ * direction that matters — white on GitHub's dark green `#4f9e5e` is 3.29:1+ * (fails AA) where near-black is 5.50:1, and Catppuccin's mauve was a 2.03:1+ * white-on-lilac. Two candidates is a cheap enough search to just measure.+ * Ties and an unparseable background (nothing to measure against) go to the+ * LAST candidate — the light pole in both the default pair and the desktop's,+ * which is what both surfaces previously fell back to.+ */+export function readableOn(bg: string, inks: readonly [string, ...string[]] = DEFAULT_INKS): string {+ let best: string = inks[inks.length - 1]!+ let bestRatio = -1++ for (const ink of inks) {+ const ratio = contrastRatio(bg, ink)++ if (ratio !== null && ratio >= bestRatio) {+ best = ink+ bestRatio = ratio+ }+ }++ return best+}++/**+ * Step-mix `color` toward the readable pole of `bg` until the contrast ratio+ * clears `min`. Each step re-mixes from the ORIGINAL color in 0.05 increments+ * so hue decays linearly, not exponentially, and the color stops at the first+ * rung that passes — minimal hue loss for the ratio. Returns the original when+ * it already passes or isn't parseable.+ */+export function ensureContrast(color: string, bg: string, min: number): string {+ if (relativeLuminance(bg) === null || parseColor(color) === null) {+ return color+ }++ const pole = readableOn(bg)+ let current = color++ for (let step = 0; step <= 20; step++) {+ const ratio = contrastRatio(current, bg)++ if (ratio === null || ratio >= min) {+ return current+ }++ current = mix(color, pole, Math.min(1, (step + 1) * 0.05))+ }++ return current+}++/** Recede toward the background pole (opposite of `readableOn`). */+export const lighten = (color: string, t: number) => mix(color, '#ffffff', t)+export const darken = (color: string, t: number) => mix(color, '#000000', t)diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.tsindex 05449d2c95f..8f3a6cc7b88 100644--- a/apps/shared/src/index.ts+++ b/apps/shared/src/index.ts@@ -36,6 +36,18 @@ export {type SettlementDeps,type SettlementOutcome} from './charge-settlement'+export {+ contrastRatio,+ darken,+ ensureContrast,+ lighten,+ mix,+ parseColor,+ readableOn,+ relativeLuminance,+ type Rgb,+ toHex+} from './color'export {createCronTriggerController,type CronTriggerController,diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 33a7ed8c8d4..6006596a5bf 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -3,6 +3,7 @@ import { execFile } from 'child_process'import { forceRedraw, onTerminalBackground, onTerminalForeground } from '@hermes/ink'import type { SubagentStatus, Usage } from '@hermes/shared/gateway-events'import { stripAnsi } from '@hermes/shared/ansi'+import { relativeLuminance } from '@hermes/shared/color'import { STARTUP_IMAGE, STARTUP_QUERY } from '../config/env.js'import { STREAM_BATCH_MS } from '../config/timing.js'@@ -16,7 +17,6 @@ import type {SessionMostRecentResponse} from '../gatewayTypes.js'import { billingDialogCopy } from '../lib/billingDialog.js'-import { relativeLuminance } from '../lib/color.js'import { isTodoDone } from '../lib/liveProgress.js'import { openExternalUrl } from '../lib/openExternalUrl.js'import { rpcErrorMessage } from '../lib/rpc.js'diff --git a/ui-tui/src/components/agentsPanel.tsx b/ui-tui/src/components/agentsPanel.tsxindex 00f4e07aaf5..71dcea81a5f 100644--- a/ui-tui/src/components/agentsPanel.tsx+++ b/ui-tui/src/components/agentsPanel.tsx@@ -1,11 +1,11 @@import { Box, stringWidth, Text, useStdout } from '@hermes/ink'+import { mix } from '@hermes/shared/color'import { useStore } from '@nanostores/react'import { useEffect, useState } from 'react'import { $agentDockCollapsed, useAgentRoster } from '../app/agentRoster.js'import { $uiState } from '../app/uiStore.js'import { type AgentRows, buildAgentRows, dockRowLimit } from '../lib/agentRows.js'-import { mix } from '../lib/color.js'import { statusGlyph } from '../lib/subagentGlyph.js'import { fmtDuration } from '../lib/subagentTree.js'import { compactPreview } from '../lib/text.js'diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsxindex 18fdf3332c7..99c6bb6f37b 100644--- a/ui-tui/src/components/branding.tsx+++ b/ui-tui/src/components/branding.tsx@@ -1,9 +1,9 @@import { Box, Text, useStdout } from '@hermes/ink'+import { mix } from '@hermes/shared/color'import { useEffect, useState } from 'react'import unicodeSpinners from 'unicode-animations'import { artWidth, caduceus, CADUCEUS_WIDTH, logo, LOGO_WIDTH } from '../banner.js'-import { mix } from '../lib/color.js'import { flat } from '../lib/text.js'import type { Theme } from '../theme.js'import type { PanelSection, SessionInfo } from '../types.js'diff --git a/ui-tui/src/components/loaders.tsx b/ui-tui/src/components/loaders.tsxindex 8ce6ed7f959..2877fb82e86 100644--- a/ui-tui/src/components/loaders.tsx+++ b/ui-tui/src/components/loaders.tsx@@ -1,8 +1,7 @@import { Box, Text } from '@hermes/ink'+import { mix } from '@hermes/shared/color'import { useEffect, useState } from 'react'-import { mix } from '../lib/color.js'-/*** Animated ASCII loaders — THE loading-state primitives (session panel* skeleton, widget apps via the SDK). A highlight band sweeps across blockdiff --git a/ui-tui/src/components/overlayPrimitives.tsx b/ui-tui/src/components/overlayPrimitives.tsxindex b7cb7b60d98..91df713e62f 100644--- a/ui-tui/src/components/overlayPrimitives.tsx+++ b/ui-tui/src/components/overlayPrimitives.tsx@@ -1,9 +1,10 @@import type { Key } from '@hermes/ink'import { Text, useInput } from '@hermes/ink'+import { mix } from '@hermes/shared/color'import { type ReactNode, useState } from 'react'import type { UsageModelData } from '../gatewayTypes.js'-import { liftForContrast, mix } from '../lib/color.js'+import { liftForContrast } from '../lib/color.js'import type { Theme } from '../theme.js'/**diff --git a/ui-tui/src/lib/color.test.ts b/ui-tui/src/lib/color.test.tsindex b19325ad0df..01a54f0d97a 100644--- a/ui-tui/src/lib/color.test.ts+++ b/ui-tui/src/lib/color.test.ts@@ -1,59 +1,7 @@+import { contrastRatio, relativeLuminance } from '@hermes/shared/color'import { describe, expect, it } from 'vitest'-import { color, contrastRatio, ensureContrast, mix, parseColor, readableOn, relativeLuminance, toHex } from './color.js'--describe('parseColor', () => {- it('parses hex6, hex3 and rgb() forms', () => {- expect(parseColor('#1a2b3c')).toEqual([0x1a, 0x2b, 0x3c])- expect(parseColor('1a2b3c')).toEqual([0x1a, 0x2b, 0x3c])- expect(parseColor('#abc')).toEqual([0xaa, 0xbb, 0xcc])- expect(parseColor('rgb(220,255,220)')).toEqual([220, 255, 220])- expect(parseColor('rgba(10, 20, 30, 0.5)')).toEqual([10, 20, 30])- })-- it('rejects garbage', () => {- expect(parseColor('')).toBeNull()- expect(parseColor('ansi256(245)')).toBeNull()- expect(parseColor('#12345')).toBeNull()- })-})--describe('mix', () => {- it('lerps in sRGB and round-trips through toHex', () => {- expect(mix('#000000', '#ffffff', 0.5)).toBe('#808080')- expect(mix('#ff0000', '#0000ff', 0)).toBe('#ff0000')- expect(mix('#ff0000', '#0000ff', 1)).toBe('#0000ff')- expect(toHex(parseColor(mix('#123456', '#654321', 0.3))!)).toBe(mix('#123456', '#654321', 0.3))- })-- it('passes unparseable inputs through unchanged', () => {- expect(mix('ansi256(245)', '#ffffff', 0.5)).toBe('ansi256(245)')- expect(mix('#ff0000', 'nope', 0.5)).toBe('#ff0000')- })-})--describe('contrast', () => {- it('measures WCAG ratios at the anchors', () => {- expect(contrastRatio('#000000', '#ffffff')).toBeCloseTo(21, 0)- expect(contrastRatio('#ffffff', '#ffffff')).toBeCloseTo(1, 5)- expect(relativeLuminance('#ffffff')).toBeCloseTo(1, 5)- expect(relativeLuminance('#000000')).toBeCloseTo(0, 5)- })-- it('readableOn picks the ink pole', () => {- expect(readableOn('#ffffff')).toBe('#000000')- expect(readableOn('#101014')).toBe('#ffffff')- })-- it('ensureContrast lifts failing colors monotonically and leaves passing ones alone', () => {- const pale = '#FFF8DC'- const fixed = ensureContrast(pale, '#ffffff', 3.9)-- expect(contrastRatio(fixed, '#ffffff')!).toBeGreaterThanOrEqual(3.9)- expect(ensureContrast('#3D2F13', '#ffffff', 3.9)).toBe('#3D2F13')- expect(ensureContrast('ansi256(245)', '#ffffff', 3.9)).toBe('ansi256(245)')- })-})+import { color } from './color.js'describe('color() chain', () => {it('composes the ladder operations', () => {diff --git a/ui-tui/src/lib/color.ts b/ui-tui/src/lib/color.tsindex d051934cfd8..00d99b2b597 100644--- a/ui-tui/src/lib/color.ts+++ b/ui-tui/src/lib/color.ts@@ -1,126 +1,25 @@/**- * THE color primitive — every color computation in the TUI goes through this- * module (the twin of the desktop app's `src/themes/color.ts`). No component- * or theme code does its own hex parsing or channel math: parse, mix, measure- * and fix colors here, so tone ladders, contrast floors and one-off UI needs- * all share one set of semantics.- *- * Mixing is an sRGB lerp — deliberately, for byte parity with the desktop's- * `color-mix(in srgb, ...)` ladder in styles.css.+ * TUI-only color derivations. The sRGB primitives (parse, mix, WCAG measure,+ * `ensureContrast`) live in `@hermes/shared/color`, shared byte-for-byte with+ * the desktop app; this module adds what only a terminal needs — xterm.js's+ * multiplicative contrast lift, HSL re-toning for light-terminal variants, and+ * the chainable `color()` form — and re-parses nothing itself.*/-export type Rgb = readonly [number, number, number]--const HEX6_RE = /^#?([0-9a-f]{6})$/i-const HEX3_RE = /^#?([0-9a-f]{3})$/i-const RGB_FN_RE = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/i+import {+ contrastRatio,+ darken,+ ensureContrast,+ lighten,+ mix,+ parseColor,+ relativeLuminance,+ type Rgb,+ toHex+} from '@hermes/shared/color'const clampChannel = (v: number) => Math.max(0, Math.min(255, Math.round(v)))-/** Parse `#rgb`, `#rrggbb` or `rgb(r,g,b)` → channels. Null for anything else. */-export function parseColor(input: string): Rgb | null {- const value = input.trim()-- let m = HEX6_RE.exec(value)-- if (m) {- const n = parseInt(m[1]!, 16)-- return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]- }-- m = HEX3_RE.exec(value)-- if (m) {- const [r, g, b] = m[1]!-- return [parseInt(r! + r!, 16), parseInt(g! + g!, 16), parseInt(b! + b!, 16)]- }-- m = RGB_FN_RE.exec(value)-- if (m) {- return [clampChannel(Number(m[1])), clampChannel(Number(m[2])), clampChannel(Number(m[3]))]- }-- return null-}--export const toHex = (rgb: Rgb): string => '#' + rgb.map(c => clampChannel(c).toString(16).padStart(2, '0')).join('')--/** sRGB lerp `a → b` by `t` in [0,1]. Unparseable inputs return `a` unchanged. */-export function mix(a: string, b: string, t: number): string {- const pa = parseColor(a)- const pb = parseColor(b)-- if (!pa || !pb) {- return a- }-- return toHex([pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t, pa[2] + (pb[2] - pa[2]) * t])-}--function channelLuminance(value: number): number {- const normalized = value / 255-- return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4-}--/** WCAG relative luminance in [0,1]. Null when unparseable. */-export function relativeLuminance(color: string): null | number {- const rgb = parseColor(color)-- return rgb- ? 0.2126 * channelLuminance(rgb[0]) + 0.7152 * channelLuminance(rgb[1]) + 0.0722 * channelLuminance(rgb[2])- : null-}--/** WCAG contrast ratio between two colors (1–21). Null when unparseable. */-export function contrastRatio(a: string, b: string): null | number {- const la = relativeLuminance(a)- const lb = relativeLuminance(b)-- if (la === null || lb === null) {- return null- }-- const [hi, lo] = la >= lb ? [la, lb] : [lb, la]-- return (hi + 0.05) / (lo + 0.05)-}--/** The readable ink pole for a given background (desktop `readableOn`). */-export function readableOn(bg: string): '#000000' | '#ffffff' {- return (relativeLuminance(bg) ?? 0) > 0.5 ? '#000000' : '#ffffff'-}--/**- * Step-mix `color` toward the readable pole of `bg` until the contrast ratio- * clears `min` (desktop `ensureContrast`). Each step re-mixes from the- * ORIGINAL color so hue decays linearly, not exponentially. Returns the- * original when it already passes or isn't parseable.- */-export function ensureContrast(color: string, bg: string, min: number): string {- if (relativeLuminance(bg) === null || parseColor(color) === null) {- return color- }-- const pole = readableOn(bg)- let current = color-- for (let step = 0; step <= 20; step++) {- const ratio = contrastRatio(current, bg)-- if (ratio === null || ratio >= min) {- return current- }-- current = mix(color, pole, Math.min(1, (step + 1) * 0.05))- }-- return current-}-/*** xterm.js's minimum-contrast algorithm (Color.ts reduce/increaseLuminance),* ported faithfully: multiplicative 10% channel steps toward the readable@@ -171,10 +70,6 @@ export function liftForContrast(color: string, bg: string, ratio: number): strinreturn toHex([r, g, b])}-/** Recede toward the background pole (opposite of `readableOn`). */-export const lighten = (color: string, t: number) => mix(color, '#ffffff', t)-export const darken = (color: string, t: number) => mix(color, '#000000', t)-/** The luminance-weighted gray of a color (its perceptual brightness). */export function grayOf(color: string): string {const rgb = parseColor(color)diff --git a/ui-tui/src/sdk/apps/weather.tsx b/ui-tui/src/sdk/apps/weather.tsxindex 676a067c70a..eedd51e1a70 100644--- a/ui-tui/src/sdk/apps/weather.tsx+++ b/ui-tui/src/sdk/apps/weather.tsx@@ -1,8 +1,8 @@import { Box, Text } from '@hermes/ink'+import { mix } from '@hermes/shared/color'import { ShimmerRows } from '../../components/loaders.js'import { Dialog } from '../../components/overlay.js'-import { mix } from '../../lib/color.js'import type { Theme } from '../../theme.js'import { updateWidget } from '../host.js'import { defineWidgetApp } from '../registry.js'diff --git a/ui-tui/src/sdk/index.ts b/ui-tui/src/sdk/index.tsindex 6070ce02cdb..3220b7111cc 100644--- a/ui-tui/src/sdk/index.ts+++ b/ui-tui/src/sdk/index.ts@@ -29,7 +29,7 @@ export {export { GridAreas, WidgetGrid } from '../components/widgetGrid.js'export { gauge, hbars, sparkline, sparkRows } from '../lib/charts.js'-export { contrastRatio, liftForContrast, mix, relativeLuminance } from '../lib/color.js'+export { liftForContrast } from '../lib/color.js'// Layout engineexport {type GridAreaItem,@@ -43,8 +43,8 @@ export {type WidgetGridLayout,type WidgetGridLayoutOptions} from '../lib/widgetGrid.js'-export type { Theme, ThemeColors } from '../theme.js'+// App contract + hostexport {ActiveWidgetSlot,@@ -67,3 +67,4 @@ export {type WidgetRenderCtx} from './types.js'export { loadUserWidgets, type UserWidgetLoadResult, widgetSdk, type WidgetSdk } from './userWidgets.js'+export { contrastRatio, mix, relativeLuminance } from '@hermes/shared/color'diff --git a/ui-tui/src/theme.ts b/ui-tui/src/theme.tsindex 3601c8634db..4122a623d75 100644--- a/ui-tui/src/theme.ts+++ b/ui-tui/src/theme.ts@@ -1,6 +1,7 @@+import { contrastRatio, ensureContrast, mix, parseColor, relativeLuminance, toHex } from '@hermes/shared/color'import type { SkinBranding, SkinColors } from '@hermes/shared/skin'-import { desaturate, grayOf, liftForContrast, mix, parseColor, relativeLuminance, toHex } from './lib/color.js'+import { desaturate, grayOf, liftForContrast } from './lib/color.js'export interface ThemeColors {primary: string@@ -68,12 +69,13 @@ export interface Theme {// ── Color math ───────────────────────────────────────────────────────//-// All generic color computation lives in lib/color.ts (the color primitive);+// Generic color computation lives in @hermes/shared/color (the primitives,+// shared with the desktop) and lib/color.ts (TUI-only lifts and re-toning);// this file keeps only the ANSI-256 remapping that is specific to the// limited-palette Apple Terminal path. contrastRatio/ensureContrast are// re-exported for existing consumers (tests, /theme-info).-export { contrastRatio, ensureContrast } from './lib/color.js'+export { contrastRatio, ensureContrast }const XTERM_6_LEVELS = [0, 95, 135, 175, 215, 255] as constconst ANSI_LIGHT_MAX_LUMINANCE = 0.72