Skip to content

The agent that grows with you

fix(shared): ensureContrast keeps the desktop's 0.2-step ladder; TUI chain opts into 0.05

teknium1c764d6d354f7
diff --git a/apps/desktop/src/themes/context.test.tsx b/apps/desktop/src/themes/context.test.tsx
index 780f9155625..cb87c997510 100644
--- a/apps/desktop/src/themes/context.test.tsx
+++ b/apps/desktop/src/themes/context.test.tsx
@@ -2,8 +2,8 @@ import { act, cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { __resetBackendSkinSync, ingestBackendSkin } from './backend-sync'
-import { skinPref, ThemeProvider, useTheme } from './context'
-import { everforestTheme } from './presets'
+import { getBaseColors, skinPref, ThemeProvider, useTheme } from './context'
+import { BUILTIN_THEME_LIST, everforestTheme } from './presets'
// The live-authoring loop: Hermes writes/edits one skin file and every surface
// repaints. An in-place edit keeps the NAME — only the palette moves.
@@ -161,3 +161,95 @@ describe('ThemeProvider highlight preview', () => {
expect(cssVar('--theme-foreground')).toBe(painted)
})
})
+
+// `--dt-primary-solid` is the loud brand fill of every shipped preset. The
+// desktop's original ensureContrast ladder (5 rungs of 0.2 toward the pole
+// opposite the background, re-mixed from the ORIGINAL colour) is reproduced
+// here as a reference implementation; the shared @hermes/shared/color ladder
+// must land byte-identical for every preset in every mode, or presets change
+// colour under users on an "only math moved" refactor.
+describe('ThemeProvider --dt-primary-solid preset parity', () => {
+ const hexToRgb = (hex: string): [number, number, number] =>
+ [0, 2, 4].map(i => parseInt(hex.replace(/^#/, '').slice(i, i + 2), 16)) as [number, number, number]
+
+ const rgbToHex = (rgb: [number, number, number]) =>
+ `#${rgb.map(n => Math.round(Math.min(255, Math.max(0, n))).toString(16).padStart(2, '0')).join('')}`
+
+ const oldMix = (a: string, b: string, amount: number) => {
+ const ar = hexToRgb(a)
+ const br = hexToRgb(b)
+
+ return rgbToHex([ar[0] + (br[0] - ar[0]) * amount, ar[1] + (br[1] - ar[1]) * amount, ar[2] + (br[2] - ar[2]) * amount])
+ }
+
+ const linearize = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
+
+ const oldLuminance = (hex: string) => {
+ const [r, g, b] = hexToRgb(hex).map(v => linearize(v / 255))
+
+ return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!
+ }
+
+ const oldContrast = (a: string, b: string) => {
+ const la = oldLuminance(a)
+ const lb = oldLuminance(b)
+
+ return la >= lb ? (la + 0.05) / (lb + 0.05) : (lb + 0.05) / (la + 0.05)
+ }
+
+ const oldEnsureContrast = (color: string, bg: string, min: number) => {
+ if (oldContrast(color, bg) >= min) {
+ return color
+ }
+
+ const towards = oldLuminance(bg) < 0.5 ? '#ffffff' : '#000000'
+ let best = color
+
+ for (let amount = 0.2; amount <= 1.0001; amount += 0.2) {
+ best = oldMix(color, towards, Math.min(amount, 1))
+
+ if (oldContrast(best, bg) >= min) {
+ return best
+ }
+ }
+
+ return best
+ }
+
+ beforeEach(() => {
+ window.localStorage.clear()
+ __resetBackendSkinSync()
+ })
+
+ afterEach(cleanup)
+
+ let ctx: ReturnType<typeof useTheme>
+
+ function Probe() {
+ ctx = useTheme()
+
+ return null
+ }
+
+ const cases = BUILTIN_THEME_LIST.flatMap(theme => (['light', 'dark'] as const).map(mode => [theme.name, mode] as const))
+
+ it.each(cases)('%s/%s keeps the pre-refactor loud fill', (name, mode) => {
+ render(
+ <ThemeProvider>
+ <Probe />
+ </ThemeProvider>
+ )
+
+ act(() => ctx.previewTheme(name, mode))
+
+ const primary = getBaseColors(name, mode).primary
+ const expected = oldEnsureContrast(primary, '#fcfcfc', 4.5)
+
+ expect(cssVar('--dt-primary-solid')).toBe(expected)
+
+ // At least some presets need a lift; the assertion must not be vacuous.
+ if (name === 'nous' && mode === 'dark') {
+ expect(expected).not.toBe(primary)
+ }
+ })
+})
diff --git a/apps/shared/src/color.ts b/apps/shared/src/color.ts
index 86e35f79b33..b532799a3af 100644
--- a/apps/shared/src/color.ts
+++ b/apps/shared/src/color.ts
@@ -123,31 +123,46 @@ export function readableOn(bg: string, inks: readonly [string, ...string[]] = DE
}
/**
- * 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.
+ * Step-mix `color` toward the pole opposite `bg` (white on a dark background,
+ * black on a light one) until the contrast ratio clears `min`. Each rung
+ * re-mixes from the ORIGINAL color, so hue decays linearly, not
+ * exponentially, and the color stops at the first rung that passes. Returns
+ * the original when it already passes or isn't parseable.
+ *
+ * `step` is the rung size. The default 0.2 (5 rungs) is the desktop's ladder
+ * and MUST stay: `--dt-primary-solid` for every shipped preset is derived
+ * from it and a finer ladder lands visibly different fills (nous `#3b6acb` vs
+ * `#3f70d8`). The TUI's chainable form opts into 0.05 for less hue loss.
+ * The accumulating loop (rather than `i * step`) is deliberate — it is the
+ * exact float sequence the old desktop ladder produced.
*/
-export function ensureContrast(color: string, bg: string, min: number): string {
- if (relativeLuminance(bg) === null || parseColor(color) === null) {
+export function ensureContrast(color: string, bg: string, min: number, step = 0.2): string {
+ const bgLuminance = relativeLuminance(bg)
+
+ if (bgLuminance === null || parseColor(color) === null) {
return color
}
- const pole = readableOn(bg)
- let current = color
+ const ratio = contrastRatio(color, bg)
- for (let step = 0; step <= 20; step++) {
- const ratio = contrastRatio(current, bg)
+ if (ratio === null || ratio >= min) {
+ return color
+ }
- if (ratio === null || ratio >= min) {
- return current
- }
+ const pole = bgLuminance < 0.5 ? '#ffffff' : '#000000'
+ let best = color
- current = mix(color, pole, Math.min(1, (step + 1) * 0.05))
+ for (let amount = step; amount <= 1.0001; amount += step) {
+ best = mix(color, pole, Math.min(amount, 1))
+
+ const stepRatio = contrastRatio(best, bg)
+
+ if (stepRatio !== null && stepRatio >= min) {
+ return best
+ }
}
- return current
+ return best
}
/** Recede toward the background pole (opposite of `readableOn`). */
diff --git a/ui-tui/src/lib/color.ts b/ui-tui/src/lib/color.ts
index 00d99b2b597..55575b291f8 100644
--- a/ui-tui/src/lib/color.ts
+++ b/ui-tui/src/lib/color.ts
@@ -202,8 +202,9 @@ class ColorChain {
return new ColorChain(darken(this.value, t))
}
+ /** Fine 0.05 ladder: the terminal palette is derived here and pays for hue loss. */
ensureContrast(bg: string, min: number): ColorChain {
- return new ColorChain(ensureContrast(this.value, bg, min))
+ return new ColorChain(ensureContrast(this.value, bg, min, 0.05))
}
luminance(): null | number {
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 619923bc177..3cf661d3298 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -912,7 +912,7 @@ not treat this pipeline as a trust boundary.
| Area constants | `PANES_AREA`, `ROUTES_AREA`, `SIDEBAR_NAV_AREA`, `STATUSBAR_AREAS`, `TITLEBAR_AREAS`, `PALETTE_AREA`, `KEYBINDS_AREA`, `THEMES_AREA`, `COMPOSER_AREAS` |
| Area payloads | `RouteContribution`, `SidebarNavContribution`, `StatusbarItem`, `TitlebarTool`, `PaletteContribution`, `KeybindContribution`, `ComposerMiddleware`, `ComposerAttachmentProvider` |
| React / state | `useValue`, `atom`, `computed`, `useQuery`, `useMutation`, `useQueryClient`, `queryClient`, `Contribute` |
-| Theming | `useTheme`, `requestTheme`, `setAccentOverride`, `$accentOverride`, `retintTheme`, `themeHue`, `DesktopTheme`, `DesktopThemeColors`, plus OKLCH math (`hexToOklch`, `oklchToHex`, `oklchToSrgb255`, `mixOklab`, `maxChroma`, `hueDelta`, `contrastRatio`, `readableOn`, `normalizeHex`) |
+| Theming | `useTheme`, `requestTheme`, `setAccentOverride`, `$accentOverride`, `retintTheme`, `themeHue`, `DesktopTheme`, `DesktopThemeColors`, plus OKLCH math (`hexToOklch`, `oklchToHex`, `oklchToSrgb255`, `mixOklab`, `maxChroma`, `hueDelta`, `normalizeHex`) and sRGB measures (`contrastRatio` — `number | null`, null for unparseable input — `readableOn`) |
| UI kit | `Button`, `Input`, `Textarea`, `Select*`, `Switch`, `Checkbox`, `SegmentedControl`, `Tabs*`, `Dialog*`, `ConfirmDialog`, `DropdownMenu*`, `ContextMenu*`, `Popover*`, `Tip`/`Tooltip*`, `Badge`, `Kbd`/`KbdGroup`, `SearchField`, `ScrollArea`, `Separator`, `Skeleton`, `GlyphSpinner`, `Loader`, `EmptyState`, `ErrorState`, `CopyButton`, `StatusDot`, `LogView`, `Codicon`, `DecodeText` |
| Helpers | `cn`, `icons`, `haptic`, `useI18n`, `profileColor`, `profileColorSoft`, `relativeTime`, `fmtDateTime`, `fmtDayTime`, `coarseElapsed`, `evaluateRuntimeReadiness` |