LibreChat/packages/client/src/theme
Marco Beretta 246e7e5de7
💠 fix: Paint Native Tool Verification Badges (#15862)
* 🪪 style: Give Native Tools a Painted Verified Mark

The native badge on a tool card was lucide's BadgeCheck filled with status-success-strong: green, the same hue the card already uses for selected, and stroked in currentColor, so the white check color also outlined the badge and left a white halo on any surface that is not the card's own white — hover, selection, dark mode.\n\nVerifiedIcon paints the badge instead of stroking it and carries the check as the only stroked path, and status-verified gives provenance its own blue across all four themes.

* 🩹 fix: Hold the Verified Mark at 3:1 on Every Card State

The dark fill was tuned against surface-secondary, but ToolCard repaints to surface-tertiary (#2f2f2f) on hover, where #0b74d4 fell to 2.85:1 — below the non-text floor, and invisible to the spec, which asserted the panel only. The fill moves to #1a7fd8 and the contract now covers every background the card takes. Both of the mark's relationships are graphical objects under WCAG 1.4.11, so the check is held at 3:1 rather than AA: no hue clears 3:1 on the hover surface and 4.5:1 under a white check at once.\n\nA theme that predates the token names status-success-strong and not status-verified, and would otherwise wear LibreChat's stock blue beside its own text-on-status and card surfaces. resolveTheme and the legacy mapColors adapter now carry the mark onto the fill it had before the token existed, following the six derived-token fallbacks already there.

* ✅ test: Exercise the Verified Mark in the Tool Library

Four scenarios in the mock harness, each named by the behavior it observes: the mark a native card wears, its silhouette under the dark hover repaint that the retune fixes, a pre-token deployment palette carrying it on the theme's own success fill, and a third-party MCP server card carrying no mark at all. The contrast assertions read the rendered colors rather than the tokens, so a regression in the component or in theme application fails them.

* 🧪 fix: Teach the Marketplace Dialog Spec About VerifiedIcon

The suite hand-lists the @librechat/client surface it mocks, so ToolCard's new icon resolved to undefined and every render in the file threw.

* 🧪 fix: Reach the Agent Builder on a Narrow Viewport

The scenario run covers mobile emulation, where the side rail is collapsed and the panel opens from the header's Control Panel toggle; the helper only knew the rail. The MCP scenario also minted its access token before the app had loaded, so the refresh request had no origin to resolve against.

* 🧪 fix: Run the Verified-Mark Scenarios on a Touch Viewport

Mobile emulation has no side rail: the panel switcher lives inside a sidebar that starts off-canvas, so the helper opens the sidebar and picks the Agent Builder entry from the switcher's menu. A touch viewport also has no hover state, so the hover scenario measures whatever background the card actually takes there and still holds the mark to 3:1 against it.

* 🩹 fix: Keep Pre-Token Themes on the Fill the Mark Inherited

The first fallback only fired when a theme restated status-success-strong, so a partial palette that customizes surfaces or text-on-status and inherits the green still landed on the stock blue. resolveTheme now derives the omission for any custom theme from the resolved success fill, and the legacy adapter takes the mode's bundled palette from ThemeProvider so it can do the same for a theme that names neither.\n\nThe scenario helper picked its path from a one-second probe for the desktop rail, which turns a slow first paint into the mobile branch; it now decides on viewport width and keeps the suite's full assertion timeout in each branch. The mock project is Desktop Chrome, so a touch scenario asks for a touch context explicitly rather than leaving that layout unexercised in CI.

* 🧪 fix: Match the App's Inclusive Layout Breakpoint

useSidebarState switches on (max-width: 768px), so a 768px-wide context renders the sidebar switcher while the helper's strict comparison went looking for the desktop rail.

* 🩹 fix: Scope the Verified Fallback to Themes That Painted the Mark

Two rounds pulled the same predicate in opposite directions: keying it on a theme restating status-success-strong missed palettes that only repaint the check or the card, and keying it on any custom color at all gave a new partial theme a green mark identical to the selected cue. Both are answered by asking what the theme actually painted — the fill the mark wore, the text-on-status check it carries, or the surfaces ToolCard takes — which is the same shape as the series-scale fallback above it. A theme that repaints none of those keeps the bundled blue.

* 🧪 fix: Wait for the Shell Before Reading the Sidebar State

isVisible() answers immediately, so a slow first paint read as an already-open drawer and the helper then waited on a switcher sealed inside it. It now waits for whichever of the opener and the switcher the shell paints first, which is the same assertion timeout the desktop branch gets.

* 📝 fix: Keep the Token Catalog Entry Catalog-Sized

The entry restated the icon's construction, the contrast rule and the pre-token fallback, all of which live on the token's own doc comment and in semanticTokens.spec.ts; the catalog around it is one line per role.

* 🔦 fix: Let a Crashed Lighthouse Run Be Retried

The audit shells out to Lighthouse three times and fails the lane if any single process exits nonzero, so a NO_NAVSTART — Lighthouse losing the trace of a page load, whose own message is "run Lighthouse again" — sinks a pull request that has nothing wrong with it. That is what happened on this branch: runs 1 and 2 wrote reports, run 3 crashed, and the identical head passed on rerun.\n\nEach run now gets a second attempt before the failure propagates. The repeat is per run, so the median is still taken over three completed reports, and a page that genuinely cannot be traced fails both attempts and still fails the lane.

* 🧪 fix: Read the Drawer State From Its Inert Marker

The readiness wait accepted the panel switcher, which is mounted whether or not the drawer is open — translated off-canvas and inert — so a shell that painted the sidebar before the chat header could satisfy it with the drawer closed and leave the helper clicking an off-viewport control. The drawer's own inert attribute is the state, so the helper waits for the drawer to attach and reads it there, with no timing probe on either side.

* 🧪 fix: Open the Drawer Before Trusting the Restored Form

A narrow context that had already selected the builder restores the form inside the closed drawer, and a translated element passes a visibility check, so the early probe accepted a form sitting under an inert drawer and handed it to the caller. The layout decision now comes first and the drawer is opened before anything inside it is read.
2026-09-12 16:03:03 -04:00
..
atoms ⚡ refactor: Migrate @librechat/client build to tsdown (#13596) 2026-06-08 11:20:03 -04:00
context 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
themes 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
types 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
utils 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
highContrast.css ♿ feat: High Contrast Light and Dark Appearance Modes (#15178) 2026-09-05 22:20:33 +02:00
index.ts ♿ feat: High Contrast Light and Dark Appearance Modes (#15178) 2026-09-05 22:20:33 +02:00
README.md 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
registry.spec.ts 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
registry.ts 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
semanticTokens.spec.ts 💠 fix: Paint Native Tool Verification Badges (#15862) 2026-09-12 16:03:03 -04:00
tailwind.spec.js 🎨 feat: Add Versioned Theme Foundation (#14709) 2026-08-10 13:41:03 -04:00

Dynamic Theme System for @librechat/client

Versioned theme definitions

New themes should use the versioned ThemeDefinition interface. Definitions are data-only, may provide separate light and dark overrides, and resolve missing values against LibreChat's bundled defaults before any CSS variables are applied.

const compactTheme: ThemeDefinition = {
  version: 1,
  name: 'compact',
  modes: {
    light: {
      appearance: {
        controlRadius: '0.25rem',
        roundControlRadius: '9999px',
        surfaceRadius: '0.5rem',
        largeSurfaceRadius: '0.75rem',
        controlHeight: '2rem',
      },
    },
  },
};

<ThemeProvider themeDefinition={compactTheme}>{children}</ThemeProvider>;

The initial appearance registry intentionally covers only shared control shape, surface shape, control height, compact/normal spacing, UI typography, surface elevation, and fast/normal motion. themeRGB, REACT_APP_THEME_*, and the existing localStorage keys remain supported through legacy adapters. Theme application removes only variables owned by the theme module when a theme is reset.

This theme system allows you to dynamically change colors in your React application using CSS variables and Tailwind CSS. It combines dark/light mode switching with dynamic color theming capabilities.

Table of Contents

Overview

The theme system provides:

  1. Dark/Light Mode Switching - Automatic theme switching based on user preference
  2. Dynamic Color Theming - Change colors at runtime without recompiling CSS
  3. CSS Variable Based - Uses CSS custom properties for performance
  4. Tailwind Integration - Works seamlessly with Tailwind CSS utilities
  5. TypeScript Support - Full type safety for theme definitions

How It Works

The theme system operates in three layers:

  1. CSS Variables Layer: Default colors defined in your app's CSS
  2. ThemeProvider Layer: React context that manages theme state and applies CSS variables
  3. Tailwind Layer: Maps CSS variables to Tailwind utility classes

Default Behavior (No Custom Theme)

  • CSS variables cascade from your app's style.css definitions
  • Light mode uses variables under html selector
  • Dark mode uses variables under .dark selector
  • No JavaScript intervention in color values

Custom Theme Behavior

  • Prefer the versioned themeDefinition prop; the legacy themeRGB prop remains supported
  • Overrides CSS variables with bare R G B channel triplets
  • Resolves missing themeDefinition values against the bundled light/dark defaults
  • Leaves colors omitted by legacy themeRGB unset so consumer CSS continues to cascade

Basic Usage

1. Install the Component Library

npm install @librechat/client

2. Wrap Your App with ThemeProvider

import { ThemeProvider } from '@librechat/client';

function App() {
  return (
    <ThemeProvider initialTheme="system">
      <YourApp />
    </ThemeProvider>
  );
}

3. Set Up Your Base CSS

Ensure your app has CSS variables defined as fallbacks. Every theme variable must hold a bare R G B channel triplet, not a complete CSS color, because the Tailwind color map wraps them as rgb(var(--x) / <alpha-value>) so that opacity modifiers such as bg-surface-primary/50 work:

/* style.css */
:root {
  --white: 255 255 255;
  --gray-800: 33 33 33;
  --gray-100: 236 236 236;
  /* ... other color definitions */
}

html {
  --text-primary: var(--gray-800);
  --surface-primary: var(--white);
  /* ... other theme variables */
}

.dark {
  --text-primary: var(--gray-100);
  --surface-primary: var(--gray-900);
  /* ... other dark theme variables */
}

Any direct use of these variables in hand-written CSS must wrap the triplet itself: color: rgb(var(--text-primary));.

Breaking change: earlier versions accepted complete colors (--text-primary: #212121). Hex, rgb(...), and named colors now produce invalid declarations and must be converted to channel triplets.

4. Configure Tailwind

Update your tailwind.config.js:

const libreChatTailwindPreset = require('@librechat/client/tailwind-preset');

module.exports = {
  presets: [libreChatTailwindPreset],
  content: [
    './src/**/*.{js,jsx,ts,tsx}',
    // Include component library files
    './node_modules/@librechat/client/dist/**/*.js',
  ],
  darkMode: ['class'],
  theme: {
    extend: {
      colors: {
        // Wrap each channel triplet so opacity modifiers keep working
        'text-primary': 'rgb(var(--text-primary) / <alpha-value>)',
        'surface-primary': 'rgb(var(--surface-primary) / <alpha-value>)',
        'brand-purple': 'rgb(var(--brand-purple) / <alpha-value>)',
        // ... other colors
      },
    },
  },
};

The published preset supplies the semantic appearance utilities used by theme-aware component variants, including h-theme-control, rounded-theme-control, gap-theme-compact, and duration-theme-fast. Keep the preset enabled even when defining additional project utilities.

5. Use Theme Colors in Components

function MyComponent() {
  return (
    <div className="border border-border-light bg-surface-primary text-text-primary">
      <h1 className="text-text-secondary">Hello World</h1>
      <button className="bg-surface-submit text-text-on-status hover:bg-surface-submit-hover">
        Submit
      </button>
    </div>
  );
}

Available Theme Colors

Text Colors

  • text-text-primary - Primary text color
  • text-text-secondary - Secondary text color
  • text-text-secondary-alt - Alternative secondary text
  • text-text-tertiary - Tertiary text color
  • text-text-warning - Warning text color
  • text-text-destructive - Destructive/error text color
  • text-text-on-status - Text color for strong status surfaces

Surface Colors

  • bg-surface-primary - Primary background
  • bg-surface-secondary - Secondary background
  • bg-surface-tertiary - Tertiary background
  • bg-surface-submit - Submit button background
  • bg-surface-destructive - Destructive action background
  • bg-surface-dialog - Dialog/modal background
  • bg-surface-overlay - Dialog/modal scrim, adapted per theme
  • bg-surface-chat - Chat interface background

Border Colors

  • border-border-light - Light border
  • border-border-medium - Medium border
  • border-border-heavy - Heavy border
  • border-border-xheavy - Extra heavy border
  • border-border-destructive - Destructive action border

Status Colors

Each status family has a foreground, a -subtle background, a -border, and a -strong surface for high-contrast notifications:

  • text-status-success / bg-status-success-subtle / border-status-success-border
  • text-status-info / bg-status-info-subtle / border-status-info-border
  • text-status-warning / bg-status-warning-subtle / border-status-warning-border
  • text-status-error / bg-status-error-subtle / border-status-error-border
  • text-status-neutral / bg-status-neutral-subtle / border-status-neutral-border
  • bg-status-success-strong / bg-status-info-strong / bg-status-warning-strong / bg-status-error-strong
  • text-status-verified — fill of the verified mark VerifiedIcon paints, carrying a stroke-text-on-status check. See rgb-status-verified in types/index.ts for why it is its own role and what a pre-token theme gets.

Other Colors

  • bg-brand-purple - Brand purple color
  • bg-presentation - Presentation background
  • ring-ring-primary - Focus ring color

Creating Custom Themes

1. Define Your Theme

import { IThemeRGB } from '@librechat/client';

export const customTheme: IThemeRGB = {
  'rgb-text-primary': '0 0 0', // Black
  'rgb-text-secondary': '100 100 100', // Gray
  'rgb-surface-primary': '255 255 255', // White
  'rgb-surface-submit': '0 128 0', // Green
  'rgb-brand-purple': '138 43 226', // Blue Violet
  // ... define other colors
};

2. Use Your Custom Theme

import { ThemeProvider } from '@librechat/client';
import { customTheme } from './themes/custom';

function App() {
  return (
    <ThemeProvider themeRGB={customTheme} themeName="custom">
      <YourApp />
    </ThemeProvider>
  );
}

Environment Variable Themes

Load theme colors from environment variables:

1. Create Environment Variables

# .env.local
REACT_APP_THEME_BRAND_PURPLE=171 104 255
REACT_APP_THEME_TEXT_PRIMARY=33 33 33
REACT_APP_THEME_TEXT_SECONDARY=66 66 66
REACT_APP_THEME_SURFACE_PRIMARY=255 255 255
REACT_APP_THEME_SURFACE_SUBMIT=4 120 87
REACT_APP_THEME_LINK=37 99 235
REACT_APP_THEME_ACCENT_PRIMARY=18 110 107
REACT_APP_THEME_STATUS_ERROR=185 28 28
REACT_APP_THEME_STATUS_ERROR_SUBTLE=254 226 226
REACT_APP_THEME_STATUS_ERROR_BORDER=252 165 165

Every IThemeRGB key is configurable this way: drop the rgb- prefix and upper-snake-case the rest, so rgb-status-error-border becomes REACT_APP_THEME_STATUS_ERROR_BORDER.

The prefix must be listed in the bundler's envPrefix (Vite) or equivalent, and values are inlined at build time, so the client has to be rebuilt after changing them.

2. Create a Theme Loader

function getThemeFromEnv(env = import.meta.env): IThemeRGB | undefined {
  const theme = {
    'rgb-text-primary': env.REACT_APP_THEME_TEXT_PRIMARY,
    'rgb-brand-purple': env.REACT_APP_THEME_BRAND_PURPLE,
    // ... other colors
  };

  const set = Object.fromEntries(Object.entries(theme).filter(([, value]) => value));
  return Object.keys(set).length > 0 ? set : undefined; // Fall back to default themes
}

3. Apply Environment Theme

<ThemeProvider initialTheme="system" themeRGB={getThemeFromEnv()}>
  <App />
</ThemeProvider>

Dark/Light Mode

The ThemeProvider handles dark/light mode automatically:

Using the Theme Hook

import { useTheme } from '@librechat/client';

function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  return (
    <button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
      Current theme: {theme}
    </button>
  );
}

Theme Options

  • 'light' - Force light mode
  • 'dark' - Force dark mode
  • 'system' - Follow system preference, for both colour scheme and contrast
  • 'high-contrast-light' - Accessibility mode: black on white, WCAG AAA
  • 'high-contrast-dark' - Accessibility mode: white on black, WCAG AAA

High contrast applies the built-in highContrastTheme definition (themes/highContrast.ts), which outranks a deployment's custom theme, and adds a high-contrast class to <html> for the CSS-only variables the token layer cannot reach.

Three predicates, and they answer different questions:

  • isDark(theme) - which colour scheme to render. high-contrast-dark is dark.
  • isHighContrast(theme) - did the user pick a contrast mode. This is what the theme toggle preserves when it flips the scheme, so system is never included.
  • resolvesToHighContrast(theme) - will the contrast palette actually apply. True for the two explicit modes, and for system when the OS asks for more contrast through any of prefers-contrast: more, prefers-contrast: custom or forced-colors: active.

Because system resolves contrast from the OS, a user who has switched on "Increase contrast" (macOS) or "Contrast themes" (Windows) gets the accessible palette without first finding this setting. Windows is why the list has three queries: a Contrast Theme surfaces as forced-colors: active with prefers-contrast: custom, never more.

Migration Guide

If you're migrating from an older theme system:

1. Update Imports

Before:

import { ThemeContext, ThemeProvider } from '~/hooks/ThemeContext';

After:

import { ThemeContext, ThemeProvider } from '@librechat/client';

2. Update ThemeProvider Usage

The new ThemeProvider is backward compatible but adds new capabilities:

<ThemeProvider
  initialTheme="system" // Same as before
  themeRGB={customTheme} // New: optional custom colors
>
  <App />
</ThemeProvider>

3. Existing Components

Components using ThemeContext continue to work without changes:

// This still works!
const { theme, setTheme } = useContext(ThemeContext);

Implementation Details

File Structure

packages/client/src/theme/
├── context/
│   └── ThemeProvider.tsx    # Main theme provider
├── types/
│   └── index.ts            # TypeScript interfaces
├── themes/
│   ├── default.ts          # Light theme colors
│   ├── dark.ts             # Dark theme colors
│   └── index.ts            # Theme exports
├── utils/
│   ├── applyTheme.ts       # Apply CSS variables
│   ├── tailwindConfig.ts   # Tailwind helpers
│   └── createTailwindColors.js
├── README.md               # This documentation
└── index.ts               # Main exports

CSS Variable Format

The theme system uses RGB values in CSS variables:

  • CSS Variable: --text-primary: 33 33 33
  • Theme Definition: 'rgb-text-primary': '33 33 33'
  • Tailwind Usage: text-text-primary

RGB Format Requirements

All color values must be in space-separated RGB format:

  • ✅ Correct: '255 255 255'
  • ❌ Incorrect: '#ffffff' or 'rgb(255, 255, 255)'

This format allows Tailwind to apply opacity modifiers like bg-surface-primary/50.

Troubleshooting

Common Issues

1. Colors Not Applying

  • Issue: Custom theme colors aren't showing
  • Solution: Pass a valid themeDefinition, or use the legacy themeRGB prop for color-only overrides
  • Check: CSS variables in DevTools should show a bare R G B triplet

2. Circular Reference Errors

  • Issue: --brand-purple: var(--brand-purple) creates infinite loop
  • Solution: Use direct channel values: --brand-purple: 171 104 255

3. Dark Mode Not Working

  • Issue: Dark mode doesn't switch
  • Solution: Ensure darkMode: ['class'] is in your Tailwind config
  • Check: The <html> element should have class="dark" in dark mode

4. TypeScript Errors

  • Issue: Type errors when defining themes
  • Solution: Import and use the IThemeRGB interface:
import { IThemeRGB } from '@librechat/client';

Debugging Tips

  1. Check CSS Variables: Use browser DevTools to inspect computed CSS variables
  2. Verify Theme Application: Look for inline styles on the root element
  3. Console Errors: Check for validation errors in the console
  4. Test Isolation: Try a minimal theme to isolate issues

Examples

Dynamic Theme Switching

import { ThemeProvider, defaultTheme, darkTheme } from '@librechat/client';
import { useState } from 'react';

function App() {
  const [isDark, setIsDark] = useState(false);

  return (
    <ThemeProvider
      initialTheme={isDark ? 'dark' : 'light'}
      themeRGB={isDark ? darkTheme : defaultTheme}
      themeName={isDark ? 'dark' : 'default'}
    >
      <button onClick={() => setIsDark(!isDark)}>Toggle Theme</button>
      <YourApp />
    </ThemeProvider>
  );
}

Multi-Theme Selector

const themes = {
  default: undefined, // Use CSS defaults
  ocean: {
    'rgb-brand-purple': '0 119 190',
    'rgb-surface-primary': '240 248 255',
    // ... ocean theme colors
  },
  forest: {
    'rgb-brand-purple': '34 139 34',
    'rgb-surface-primary': '245 255 250',
    // ... forest theme colors
  },
};

function App() {
  const [selectedTheme, setSelectedTheme] = useState('default');

  return (
    <ThemeProvider themeRGB={themes[selectedTheme]} themeName={selectedTheme}>
      <select onChange={(e) => setSelectedTheme(e.target.value)}>
        {Object.keys(themes).map((name) => (
          <option key={name} value={name}>
            {name}
          </option>
        ))}
      </select>
      <YourApp />
    </ThemeProvider>
  );
}

Using with the Main Application

When using the ThemeProvider in your main application with localStorage persistence:

import { ThemeProvider } from '@librechat/client';
import { getThemeFromEnv } from './utils';

function App() {
  const envTheme = getThemeFromEnv();

  return (
    <ThemeProvider
      // Only pass props if you want to override stored values
      // If you always pass props, they will override localStorage
      initialTheme={envTheme ? 'system' : undefined}
      themeRGB={envTheme || undefined}
    >
      {/* Your app content */}
    </ThemeProvider>
  );
}

Important: The themeDefinition, themeRGB, and themeName props override stored values and remain synchronized when they change. Only pass theme props when the parent should control those values; otherwise use the context setters and allow stored preferences to remain authoritative.

Set persistThemeDefinition={false} when a parent controls a deployment or embedded theme that must not replace the user's stored theme definition, legacy colors, name, or source. Appearance mode changes remain independently persisted through color-theme; leave initialTheme undefined when the stored light, dark, or system preference should remain authoritative.

Contributing

When adding new theme colors:

  1. Add the type definition in types/index.ts
  2. Add the color to default and dark themes
  3. Update the applyTheme mapping
  4. Add to Tailwind configuration
  5. Document in this README

License

This theme system is part of the @librechat/client package.