diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js index 3608dd4cc0..3cf1e60c40 100644 --- a/api/server/routes/__tests__/config.spec.js +++ b/api/server/routes/__tests__/config.spec.js @@ -260,6 +260,18 @@ describe('GET /api/config', () => { expect(response.body).not.toHaveProperty('interface'); }); + it('should include the deployment theme so the login page paints it', async () => { + mockGetAppConfig.mockResolvedValue({ + ...baseAppConfig, + interfaceConfig: { modelSelect: true, theme: 'clickhouse' }, + }); + const app = createApp(null); + + const response = await request(app).get('/api/config'); + + expect(response.body.interface).toEqual({ theme: 'clickhouse' }); + }); + it('keeps passkeys advertised for management when email login is disabled', async () => { mockGetAppConfig.mockResolvedValue(baseAppConfig); const previous = { diff --git a/api/server/routes/config.js b/api/server/routes/config.js index 9d2632203a..bc25d6b6bc 100644 --- a/api/server/routes/config.js +++ b/api/server/routes/config.js @@ -17,6 +17,7 @@ const { resolveCodeEnvironmentDecisionVersion, resolveCodeEnvironmentMoveVersion, isPasskeyEnabled, + buildPreLoginInterface, } = require('@librechat/api'); const { DEFAULT_MCP_APP_CSP_LIMITS, @@ -234,18 +235,9 @@ router.get('/', async function (req, res) { }; const interfaceConfig = baseConfig?.interfaceConfig; - const buildInfoDisabled = interfaceConfig?.buildInfo === false; - if (interfaceConfig?.privacyPolicy || interfaceConfig?.termsOfService || buildInfoDisabled) { - payload.interface = {}; - if (interfaceConfig.privacyPolicy) { - payload.interface.privacyPolicy = interfaceConfig.privacyPolicy; - } - if (interfaceConfig.termsOfService) { - payload.interface.termsOfService = interfaceConfig.termsOfService; - } - if (buildInfoDisabled) { - payload.interface.buildInfo = false; - } + const preLoginInterface = buildPreLoginInterface(interfaceConfig); + if (preLoginInterface) { + payload.interface = preLoginInterface; } const unauthBuildInfo = buildBuildInfoPayload(interfaceConfig); diff --git a/client/src/App.jsx b/client/src/App.jsx index 24bf66f8ea..cae2221eec 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -4,13 +4,13 @@ import { DndProvider } from 'react-dnd'; import { RouterProvider } from 'react-router-dom'; import * as RadixToast from '@radix-ui/react-toast'; import { HTML5Backend } from 'react-dnd-html5-backend'; +import { Toast, ToastProvider, useInputModality } from '@librechat/client'; import { QueryClient, QueryClientProvider, QueryCache } from '@tanstack/react-query'; -import { Toast, ThemeProvider, ToastProvider, useInputModality } from '@librechat/client'; import { ScreenshotProvider, useApiErrorBoundary } from './hooks'; import WakeLockManager from '~/components/System/WakeLockManager'; import QueryDevtoolsGate from '~/components/QueryDevtoolsGate'; import LanguageSync from '~/components/System/LanguageSync'; -import { getThemeFromEnv } from './utils/getThemeFromEnv'; +import DeploymentTheme from '~/Providers/DeploymentTheme'; import { initializeFontSize } from '~/store/fontSize'; import { LiveAnnouncer } from '~/a11y'; import { router } from './routes'; @@ -43,24 +43,12 @@ const App = () => { initializeFontSize(); }, []); - // Load theme from environment variables if available - const envTheme = getThemeFromEnv(); - return ( - - {/* The ThemeProvider will automatically: - 1. Apply dark/light mode classes - 2. Apply custom theme colors if envTheme is provided - 3. Otherwise use stored theme preferences from localStorage - 4. Fall back to default theme colors if nothing is stored */} + @@ -91,7 +79,7 @@ const App = () => { - + diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsx new file mode 100644 index 0000000000..f1138a3804 --- /dev/null +++ b/client/src/Providers/DeploymentTheme.tsx @@ -0,0 +1,171 @@ +import { useEffect, useMemo, useReducer, useRef, useState } from 'react'; +import { QueryKeys } from 'librechat-data-provider'; +import { notifyManager, useQueryClient } from '@tanstack/react-query'; +import { + ThemeProvider, + clickHouseTheme, + libreChatTheme, + fromLegacyTheme, + validateThemeDefinition, +} from '@librechat/client'; +import type { IThemeRGB, ThemeDefinition } from '@librechat/client'; +import type { TInterfaceConfig } from 'librechat-data-provider'; +import type { ComponentProps } from 'react'; +import { getThemeFromEnv } from '~/utils/getThemeFromEnv'; +import { useGetStartupConfig } from '~/data-provider'; + +type DeploymentThemeValue = TInterfaceConfig['theme']; + +const bundledThemes: Readonly> = { + librechat: libreChatTheme, + clickhouse: clickHouseTheme, +}; + +/** + * Resolves `interface.theme` from librechat.yaml to a theme definition: a bundled + * name, or an inline definition that passes the registry's validation. Anything + * else is reported once and ignored, so a bad value falls back to today's theme. + */ +export function resolveDeploymentTheme(theme: DeploymentThemeValue): ThemeDefinition | undefined { + if (theme == null) { + return undefined; + } + + if (typeof theme === 'string') { + const definition = Object.hasOwn(bundledThemes, theme) ? bundledThemes[theme] : undefined; + if (!definition) { + console.warn(`[DeploymentTheme] Ignoring unknown interface.theme "${theme}"`); + } + return definition; + } + + const definition = theme as ThemeDefinition; + const errors = validateThemeDefinition(definition); + if (errors.length > 0) { + console.warn(`[DeploymentTheme] Ignoring invalid interface.theme: ${errors.join('; ')}`); + return undefined; + } + return definition; +} + +/** A corrupt entry reads as absent, so the next storage adapter still gets its turn. */ +const parseStored = (key: string): unknown => { + try { + const raw = localStorage.getItem(key); + return raw ? JSON.parse(raw) : undefined; + } catch { + return undefined; + } +}; + +const isValidDefinition = (value: unknown): value is ThemeDefinition => + typeof value === 'object' && + value !== null && + validateThemeDefinition(value as ThemeDefinition).length === 0; + +/** + * The user's own theme in the shape `ThemeProvider` restores it: a versioned + * definition, or legacy colors that the provider overlays on both modes. Stored + * with source `legacy`, a definition is the legacy compatibility copy and goes back + * through the legacy path. The deployment theme is never persisted, so storage + * still holds this while the deployment theme is applied. + */ +type StoredTheme = { definition: ThemeDefinition } | { legacyColors: IThemeRGB; name: string }; + +export function readStoredTheme(): StoredTheme | undefined { + try { + const definition = parseStored('theme-definition'); + if (isValidDefinition(definition)) { + const legacyColors = definition.modes.light?.colors; + return localStorage.getItem('theme-source') === 'legacy' && legacyColors + ? { legacyColors, name: definition.name } + : { definition }; + } + const colors = parseStored('theme-colors'); + if (typeof colors !== 'object' || colors === null) { + return undefined; + } + const name = localStorage.getItem('theme-name') ?? 'custom'; + return isValidDefinition(fromLegacyTheme(colors as IThemeRGB, name)) + ? { legacyColors: colors as IThemeRGB, name } + : undefined; + } catch { + return undefined; + } +} + +/** + * The auth mutations call `removeQueries()`, which detaches this long-lived + * observer from the query it was reading; only a re-render rebinds it to the + * rebuilt one. The cache event is checked by key alone, since it fires for every + * query in the app, and the re-render is deferred past the render that built it. + */ +function useRebindOnStartupConfigRebuild() { + const queryClient = useQueryClient(); + const [, rebind] = useReducer((count: number) => count + 1, 0); + useEffect( + () => + queryClient.getQueryCache().subscribe( + notifyManager.batchCalls((event) => { + if (event.type === 'added' && event.query.queryKey[0] === QueryKeys.startupConfig) { + rebind(); + } + }), + ), + [queryClient], + ); +} + +/** + * Supplies the deployment theme from the startup config to `ThemeProvider`. + * Precedence: high-contrast modes (inside the provider), then `interface.theme`, + * then the `REACT_APP_THEME_*` build colors, then the user's stored theme. The + * deployment theme is never persisted, so the stored theme survives its removal. + */ +export default function DeploymentTheme({ children }: { children: React.ReactNode }) { + const envTheme = useMemo(() => getThemeFromEnv(), []); + useRebindOnStartupConfigRebuild(); + const { data: startupConfig } = useGetStartupConfig({ keepPreviousData: true }); + const configTheme = startupConfig?.interface?.theme; + const themeDefinition = useMemo(() => resolveDeploymentTheme(configTheme), [configTheme]); + + /** + * Persistence stays off while a deployment theme is applied and for the render + * that withdraws it, so neither the deployment theme nor the restore writes + * storage. Once the restored theme is installed, the user's own changes persist. + */ + const deploymentThemeApplied = useRef(false); + const [persistenceReleased, setPersistenceReleased] = useState(false); + if (themeDefinition) { + deploymentThemeApplied.current = true; + } + const withdrawn = !themeDefinition && deploymentThemeApplied.current; + useEffect(() => { + setPersistenceReleased(withdrawn); + }, [withdrawn]); + const persistenceOff = Boolean(themeDefinition) || (withdrawn && !persistenceReleased); + + /** + * Clearing the prop would leave the provider on the LibreChat palette, so a + * deployment theme that goes away hands the provider the user's stored theme, + * unless the build-time colors outrank it. + */ + const storedTheme = useMemo( + () => (withdrawn && !envTheme ? readStoredTheme() : undefined), + [withdrawn, envTheme], + ); + + const props: Omit, 'children'> = { + ...(envTheme && { initialTheme: 'system', themeRGB: envTheme }), + ...(themeDefinition && { themeDefinition }), + ...(storedTheme && 'definition' in storedTheme && { themeDefinition: storedTheme.definition }), + ...(storedTheme && + 'legacyColors' in storedTheme && { + themeRGB: storedTheme.legacyColors, + themeName: storedTheme.name, + }), + ...(persistenceOff && { persistThemeDefinition: false }), + }; + + return {children}; +} diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx new file mode 100644 index 0000000000..4376e4360e --- /dev/null +++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx @@ -0,0 +1,301 @@ +import { useState } from 'react'; +import { RecoilRoot } from 'recoil'; +import { useTheme } from '@librechat/client'; +import { act, render, waitFor } from '@testing-library/react'; +import { QueryKeys, dataService } from 'librechat-data-provider'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { TStartupConfig } from 'librechat-data-provider'; +import { useGetStartupConfig } from '~/data-provider'; +import DeploymentTheme from '../DeploymentTheme'; + +const mockGetThemeFromEnv = jest.fn(); + +jest.mock('librechat-data-provider', () => { + const actual = + jest.requireActual('librechat-data-provider'); + return { ...actual, dataService: { ...actual.dataService } }; +}); + +jest.mock('~/utils/getThemeFromEnv', () => ({ + getThemeFromEnv: () => mockGetThemeFromEnv(), +})); + +type ConfigTheme = NonNullable['theme']; + +const THEME_KEYS = ['theme-definition', 'theme-colors', 'theme-name', 'theme-source']; + +const storedDefinition = { + version: 1, + name: 'stored', + modes: { light: { colors: { 'rgb-accent-primary': '1 2 3' } } }, +}; + +const inlineTheme = { + version: 1 as const, + name: 'acme', + modes: { + light: { + colors: { 'rgb-surface-primary': '10 20 30' }, + appearance: { controlRadius: '2px' }, + }, + dark: { colors: { 'rgb-surface-primary': '40 50 60' } }, + }, +}; + +const configWith = (theme?: ConfigTheme) => + ({ interface: theme === undefined ? {} : { theme } }) as TStartupConfig; + +const snapshotStorage = () => THEME_KEYS.map((key) => localStorage.getItem(key)); + +const root = () => document.documentElement; + +let applyUserColors: () => void = () => undefined; + +/** Stands in for a host surface that lets the user change their theme. */ +function ThemeEditor() { + const { setThemeRGB } = useTheme(); + applyUserColors = () => setThemeRGB({ 'rgb-accent-primary': '9 9 9' }); + return null; +} + +function StartupConsumer() { + useGetStartupConfig(); + return null; +} + +let mountRoute: () => void = () => undefined; + +/** Mounts a startup config consumer later without re-rendering the wrapper, as a route does. */ +function LateRoute() { + const [mounted, setMounted] = useState(false); + mountRoute = () => setMounted(true); + return mounted ? : null; +} + +function renderTheme(queryClient: QueryClient) { + return render( + + + + + + + + , + ); +} + +describe('DeploymentTheme', () => { + let queryClient: QueryClient; + let getStartupConfig: jest.SpyInstance; + let warn: jest.SpyInstance; + + const serveTheme = (theme?: ConfigTheme) => getStartupConfig.mockResolvedValue(configWith(theme)); + + beforeEach(() => { + localStorage.clear(); + localStorage.setItem('theme', 'light'); + localStorage.setItem('theme-definition', JSON.stringify(storedDefinition)); + localStorage.setItem('theme-name', 'stored'); + localStorage.setItem('theme-source', 'definition'); + queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + getStartupConfig = jest.spyOn(dataService, 'getStartupConfig'); + mockGetThemeFromEnv.mockReturnValue(undefined); + warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + + afterEach(() => { + queryClient.clear(); + getStartupConfig.mockRestore(); + warn.mockRestore(); + mockGetThemeFromEnv.mockReset(); + }); + + it('resolves a bundled theme name without touching stored preferences', async () => { + const before = snapshotStorage(); + serveTheme('clickhouse'); + renderTheme(queryClient); + + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + expect(root().style.getPropertyValue('--surface-primary')).toBe('255 255 255'); + expect(snapshotStorage()).toEqual(before); + expect(warn).not.toHaveBeenCalled(); + }); + + it('applies a valid inline definition without persisting it', async () => { + const before = snapshotStorage(); + serveTheme(inlineTheme); + renderTheme(queryClient); + + await waitFor(() => expect(root().dataset.theme).toBe('acme')); + expect(root().style.getPropertyValue('--surface-primary')).toBe('10 20 30'); + expect(root().style.getPropertyValue('--theme-control-radius')).toBe('2px'); + expect(snapshotStorage()).toEqual(before); + }); + + it('ignores an invalid inline definition with a warning and keeps the stored theme', async () => { + serveTheme({ + ...inlineTheme, + modes: { light: { colors: { 'rgb-not-a-token': '1 2 3' } } }, + }); + renderTheme(queryClient); + + await waitFor(() => expect(warn).toHaveBeenCalledTimes(1)); + expect(warn.mock.calls[0][0]).toContain('Unknown color token: rgb-not-a-token'); + expect(root().dataset.theme).toBe('stored'); + }); + + it('rejects names that are not deployment themes', async () => { + serveTheme('high-contrast'); + renderTheme(queryClient); + + await waitFor(() => expect(warn).toHaveBeenCalledTimes(1)); + expect(warn.mock.calls[0][0]).toContain('"high-contrast"'); + expect(root().dataset.theme).toBe('stored'); + }); + + it('prefers the yaml theme over the build-time environment colors', async () => { + mockGetThemeFromEnv.mockReturnValue({ 'rgb-surface-primary': '99 99 99' }); + serveTheme(inlineTheme); + renderTheme(queryClient); + + await waitFor(() => expect(root().dataset.theme).toBe('acme')); + expect(root().style.getPropertyValue('--surface-primary')).toBe('10 20 30'); + }); + + it('falls back to the environment colors when no yaml theme is set', async () => { + mockGetThemeFromEnv.mockReturnValue({ 'rgb-surface-primary': '99 99 99' }); + serveTheme(); + renderTheme(queryClient); + + await waitFor(() => expect(getStartupConfig).toHaveBeenCalled()); + await waitFor(() => + expect(root().style.getPropertyValue('--surface-primary')).toBe('99 99 99'), + ); + expect(root().dataset.theme).not.toBe('clickhouse'); + }); + + const replaceConfig = (theme?: ConfigTheme) => + act(() => { + queryClient.setQueryData([QueryKeys.startupConfig, false, 'default'], configWith(theme)); + }); + + it('restores the stored theme when the deployment theme is withdrawn', async () => { + const before = snapshotStorage(); + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + + replaceConfig(); + + await waitFor(() => expect(root().dataset.theme).toBe('stored')); + expect(root().style.getPropertyValue('--accent-primary')).toBe('1 2 3'); + expect(snapshotStorage()).toEqual(before); + }); + + it('restores a legacy color map behind a corrupt stored definition when the deployment theme is withdrawn', async () => { + localStorage.setItem('theme-definition', '{not json'); + localStorage.setItem('theme-colors', JSON.stringify({ 'rgb-accent-primary': '7 8 9' })); + localStorage.setItem('theme-name', 'legacy-colors'); + localStorage.setItem('theme-source', 'legacy'); + const before = snapshotStorage(); + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + + replaceConfig(); + + await waitFor(() => expect(root().dataset.theme).toBe('legacy-colors')); + expect(root().style.getPropertyValue('--accent-primary')).toBe('7 8 9'); + expect(snapshotStorage()).toEqual(before); + }); + + it('restores a legacy-source theme onto dark mode when the deployment theme is withdrawn', async () => { + const legacy = { + version: 1, + name: 'legacy-stored', + modes: { light: { colors: { 'rgb-accent-primary': '4 5 6' } } }, + }; + localStorage.setItem('color-theme', 'dark'); + localStorage.setItem('theme-definition', JSON.stringify(legacy)); + localStorage.setItem('theme-colors', JSON.stringify(legacy.modes.light.colors)); + localStorage.setItem('theme-name', 'legacy-stored'); + localStorage.setItem('theme-source', 'legacy'); + const before = snapshotStorage(); + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + + replaceConfig(); + + await waitFor(() => expect(root().dataset.theme).toBe('legacy-stored')); + expect(root().classList.contains('dark')).toBe(true); + expect(root().style.getPropertyValue('--accent-primary')).toBe('4 5 6'); + expect(snapshotStorage()).toEqual(before); + }); + + it('falls back to the environment colors when the deployment theme is withdrawn', async () => { + mockGetThemeFromEnv.mockReturnValue({ 'rgb-surface-primary': '99 99 99' }); + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + + replaceConfig(); + + await waitFor(() => + expect(root().style.getPropertyValue('--surface-primary')).toBe('99 99 99'), + ); + expect(root().dataset.theme).not.toBe('stored'); + }); + + it('persists theme changes the user makes after the deployment theme is withdrawn', async () => { + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + act(() => applyUserColors()); + expect(localStorage.getItem('theme-colors')).toBeNull(); + + replaceConfig(); + await waitFor(() => expect(root().dataset.theme).toBe('stored')); + expect(JSON.parse(localStorage.getItem('theme-definition') ?? '{}')).toEqual(storedDefinition); + + act(() => applyUserColors()); + + await waitFor(() => + expect(JSON.parse(localStorage.getItem('theme-colors') ?? '{}')).toEqual({ + 'rgb-accent-primary': '9 9 9', + }), + ); + expect(localStorage.getItem('theme-source')).toBe('legacy'); + }); + + it('does not persist a deployment theme that returns after a withdrawal', async () => { + const before = snapshotStorage(); + serveTheme('clickhouse'); + renderTheme(queryClient); + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + + replaceConfig(); + await waitFor(() => expect(root().dataset.theme).toBe('stored')); + replaceConfig(inlineTheme); + + await waitFor(() => expect(root().dataset.theme).toBe('acme')); + expect(snapshotStorage()).toEqual(before); + }); + + it('picks up the theme after the auth flow removes the startup config query', async () => { + const before = snapshotStorage(); + getStartupConfig.mockReturnValueOnce(new Promise(() => undefined)); + renderTheme(queryClient); + await waitFor(() => expect(getStartupConfig).toHaveBeenCalledTimes(1)); + + /** What the refresh-token and login mutations do in `onMutate`. */ + act(() => queryClient.removeQueries()); + serveTheme('clickhouse'); + act(() => mountRoute()); + + await waitFor(() => expect(root().dataset.theme).toBe('clickhouse')); + expect(getStartupConfig).toHaveBeenCalledTimes(2); + expect(snapshotStorage()).toEqual(before); + }); +}); diff --git a/e2e/specs/mock/scenarios/deployment-theme.spec.ts b/e2e/specs/mock/scenarios/deployment-theme.spec.ts new file mode 100644 index 0000000000..5915f03bad --- /dev/null +++ b/e2e/specs/mock/scenarios/deployment-theme.spec.ts @@ -0,0 +1,196 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse'; +import { defaultTheme } from '../../../../packages/client/src/theme/themes/default'; +import { darkTheme } from '../../../../packages/client/src/theme/themes/dark'; +import { getE2EUser } from '../../../setup/user'; +import { themeValue } from './style.helpers'; + +/** + * `interface.theme` in librechat.yaml reaches the client through `/api/config`, + * both before sign-in and after it. Each scenario serves the value there and + * nothing through storage, so the theme can only come from the config. The mode + * comes from the project (light, dark, mobile), and every expectation is read + * for the mode the page actually resolved. + */ + +type Mode = 'light' | 'dark'; +/** `null` serves a payload with no `interface.theme`. */ +type ConfigTheme = string | Record | null; + +const STORED_DEFINITION = { + version: 1, + name: 'stored', + modes: { + light: { colors: { 'rgb-surface-primary': '250 240 230' } }, + dark: { colors: { 'rgb-surface-primary': '30 20 10' } }, + }, +}; + +const INLINE_THEME = { + version: 1, + name: 'acme', + modes: { + light: { + colors: { 'rgb-surface-primary': '240 244 255' }, + appearance: { controlRadius: '2px' }, + }, + dark: { + colors: { 'rgb-surface-primary': '12 16 32' }, + appearance: { controlRadius: '2px' }, + }, + }, +}; + +test.use({ storageState: { cookies: [], origins: [] } }); + +/** Serves `signedOut` on the pre-login payload and `signedIn` once a token is sent. */ +async function serveTheme(page: Page, signedOut: ConfigTheme, signedIn: ConfigTheme = signedOut) { + await page.route( + (url) => url.pathname === '/api/config', + async (route) => { + const authenticated = Boolean(route.request().headers()['authorization']); + const theme = authenticated ? signedIn : signedOut; + const response = await route.fetch(); + const body = await response.json(); + const served = { ...body.interface }; + delete served.theme; + if (theme !== null) { + served.theme = theme; + } + await route.fulfill({ response, json: { ...body, interface: served } }); + }, + ); +} + +async function seedStorage(page: Page, entries: Record) { + await page.addInitScript((values) => { + if (sessionStorage.getItem('e2e-seeded')) { + return; + } + sessionStorage.setItem('e2e-seeded', '1'); + for (const [key, value] of Object.entries(values)) { + localStorage.setItem(key, value); + } + }, entries); +} + +async function resolvedMode(page: Page): Promise { + const dark = await page.evaluate(() => document.documentElement.classList.contains('dark')); + return dark ? 'dark' : 'light'; +} + +async function openLogin(page: Page) { + await page.goto('/login'); + await expect(page.getByTestId('login-button')).toBeVisible({ timeout: 20000 }); +} + +async function signIn(page: Page) { + const user = getE2EUser(); + await page.getByLabel('Email').fill(user.email); + await page.getByLabel('Password').fill(user.password); + await page.getByTestId('login-button').click(); + await page.waitForURL(/\/c\/new/, { timeout: 20000 }); + await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({ + timeout: 20000, + }); +} + +async function expectClickHouse(page: Page) { + const colors = clickHouseTheme.modes[await resolvedMode(page)]?.colors ?? {}; + await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse'); + expect(await themeValue(page, '--surface-primary')).toBe(colors['rgb-surface-primary']); + expect(await themeValue(page, '--theme-control-radius')).toBe('0.25rem'); +} + +const storedDefinition = (page: Page) => + page.evaluate(() => localStorage.getItem('theme-definition')); + +test.describe('deployment theme from librechat.yaml', () => { + test('a bundled deployment theme paints the login page and the chat without being saved @scenario:deployment-theme-paints-login-and-chat', async ({ + page, + }) => { + test.setTimeout(90000); + await serveTheme(page, 'clickhouse'); + + await openLogin(page); + await expectClickHouse(page); + expect(await storedDefinition(page)).toBeNull(); + + await signIn(page); + await expectClickHouse(page); + expect(await storedDefinition(page)).toBeNull(); + }); + + test('an inline deployment theme applies its own colors and appearance @scenario:inline-deployment-theme-applies-its-colors', async ({ + page, + }) => { + test.setTimeout(60000); + await serveTheme(page, INLINE_THEME); + + await openLogin(page); + const mode = await resolvedMode(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'acme'); + expect(await themeValue(page, '--surface-primary')).toBe( + INLINE_THEME.modes[mode].colors['rgb-surface-primary'], + ); + expect(await themeValue(page, '--theme-control-radius')).toBe('2px'); + expect(await storedDefinition(page)).toBeNull(); + }); + + test('an invalid deployment theme is ignored and the default look stays @scenario:invalid-deployment-theme-keeps-default-look', async ({ + page, + }) => { + test.setTimeout(60000); + const warnings: string[] = []; + page.on('console', (message) => { + if (message.type() === 'warning' && message.text().includes('[DeploymentTheme]')) { + warnings.push(message.text()); + } + }); + await serveTheme(page, { + ...INLINE_THEME, + modes: { light: { colors: { 'rgb-not-a-token': '1 2 3' } } }, + }); + + await openLogin(page); + const palette = (await resolvedMode(page)) === 'dark' ? darkTheme : defaultTheme; + await expect.poll(() => warnings.length).toBeGreaterThan(0); + await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'acme'); + expect(await themeValue(page, '--surface-primary')).toBe(palette['rgb-surface-primary']); + }); + + test('withdrawing the deployment theme after sign-in brings back the user theme @scenario:withdrawn-deployment-theme-restores-user-theme', async ({ + page, + }) => { + test.setTimeout(90000); + const stored = JSON.stringify(STORED_DEFINITION); + await seedStorage(page, { 'theme-definition': stored, 'theme-source': 'definition' }); + await serveTheme(page, 'clickhouse', null); + + await openLogin(page); + await expectClickHouse(page); + + await signIn(page); + const mode = await resolvedMode(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'stored'); + expect(await themeValue(page, '--surface-primary')).toBe( + STORED_DEFINITION.modes[mode].colors['rgb-surface-primary'], + ); + expect(await storedDefinition(page)).toBe(stored); + }); + + test('a high-contrast mode outranks the deployment theme @scenario:high-contrast-outranks-deployment-theme', async ({ + page, + }) => { + test.setTimeout(60000); + await seedStorage(page, { 'color-theme': 'high-contrast-dark' }); + await serveTheme(page, 'clickhouse'); + + await openLogin(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'high-contrast'); + expect(await themeValue(page, '--surface-primary')).not.toBe( + clickHouseTheme.modes.dark?.colors?.['rgb-surface-primary'], + ); + }); +}); diff --git a/librechat.example.yaml b/librechat.example.yaml index d05d649925..709c252798 100644 --- a/librechat.example.yaml +++ b/librechat.example.yaml @@ -145,6 +145,25 @@ interface: customWelcome: 'Welcome to LibreChat! Enjoy your experience.' # Minimum interval between syntax-highlighting passes while streamed code changes (default: 300 ms) # codeHighlightThrottleMs: 300 + # Deployment theme applied to every user, in both light and dark mode (default: unset). + # It is not saved to the browser, outranks REACT_APP_THEME_* colors and stored themes, + # and yields to the high-contrast modes. Either a bundled theme name (librechat, clickhouse): + # theme: clickhouse + # or an inline definition. Colors are space-separated RGB triplets keyed by rgb-* token: + # theme: + # version: 1 + # name: acme + # modes: + # light: + # colors: + # rgb-surface-primary: '255 255 255' + # rgb-surface-submit: '21 21 21' + # appearance: + # controlRadius: '0.25rem' + # dark: + # colors: + # rgb-surface-primary: '31 31 28' + # rgb-surface-submit: '250 255 105' # Enable/disable file search as a chatarea selection (default: true) # Note: This setting does not disable the Agents File Search Capability. # To disable the Agents Capability, see the Agents Endpoint configuration instead. diff --git a/packages/api/src/app/index.ts b/packages/api/src/app/index.ts index 52e45da305..99589970aa 100644 --- a/packages/api/src/app/index.ts +++ b/packages/api/src/app/index.ts @@ -12,3 +12,4 @@ export * from './origin'; export * from './agents'; export { resolveBuildInfo } from './build'; export type { BuildInfo } from './build'; +export { buildPreLoginInterface } from './interface'; diff --git a/packages/api/src/app/interface.spec.ts b/packages/api/src/app/interface.spec.ts new file mode 100644 index 0000000000..a0038fdd1c --- /dev/null +++ b/packages/api/src/app/interface.spec.ts @@ -0,0 +1,39 @@ +import { buildPreLoginInterface } from './interface'; + +describe('buildPreLoginInterface', () => { + it('omits the interface when nothing public is configured', () => { + expect(buildPreLoginInterface(undefined)).toBeUndefined(); + expect(buildPreLoginInterface({ modelSelect: true, buildInfo: true })).toBeUndefined(); + }); + + it('keeps only the legal links and a disabled build-info flag', () => { + expect( + buildPreLoginInterface({ + privacyPolicy: { externalUrl: 'https://example.com/privacy' }, + termsOfService: { externalUrl: 'https://example.com/tos' }, + buildInfo: false, + modelSelect: true, + parameters: false, + }), + ).toEqual({ + privacyPolicy: { externalUrl: 'https://example.com/privacy' }, + termsOfService: { externalUrl: 'https://example.com/tos' }, + buildInfo: false, + }); + }); + + it('carries a bundled theme name', () => { + expect(buildPreLoginInterface({ theme: 'clickhouse', modelSelect: true })).toEqual({ + theme: 'clickhouse', + }); + }); + + it('carries an inline theme definition unchanged', () => { + const theme = { + version: 1 as const, + name: 'acme', + modes: { light: { colors: { 'rgb-surface-primary': '255 255 255' } } }, + }; + expect(buildPreLoginInterface({ theme })).toEqual({ theme }); + }); +}); diff --git a/packages/api/src/app/interface.ts b/packages/api/src/app/interface.ts new file mode 100644 index 0000000000..de3d5fb704 --- /dev/null +++ b/packages/api/src/app/interface.ts @@ -0,0 +1,28 @@ +import type { TInterfaceConfig } from 'librechat-data-provider'; + +type PreLoginInterface = Pick< + TInterfaceConfig, + 'privacyPolicy' | 'termsOfService' | 'buildInfo' | 'theme' +>; + +/** + * Selects the interface fields a signed-out client may see: the legal links the + * login page renders, a disabled build-info flag, and the deployment theme so the + * login page paints it instead of switching after sign-in. Returns `undefined` + * when none of them is configured, so the payload omits `interface` entirely. + */ +export function buildPreLoginInterface( + interfaceConfig?: Partial, +): PreLoginInterface | undefined { + if (!interfaceConfig) { + return undefined; + } + const { privacyPolicy, termsOfService, buildInfo, theme } = interfaceConfig; + const selected: PreLoginInterface = { + ...(privacyPolicy && { privacyPolicy }), + ...(termsOfService && { termsOfService }), + ...(buildInfo === false && { buildInfo }), + ...(theme && { theme }), + }; + return Object.keys(selected).length > 0 ? selected : undefined; +} diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts index e1be70b786..8b110d9c54 100644 --- a/packages/data-provider/src/config.spec.ts +++ b/packages/data-provider/src/config.spec.ts @@ -2130,3 +2130,67 @@ describe('MCP UI refresh configuration', () => { ).toBe(false); }); }); + +describe('interface theme config', () => { + const parseTheme = (theme: unknown) => + configSchema.safeParse({ version: '1.3.0', interface: { theme } }); + + const inlineTheme = { + version: 1, + name: 'acme', + modes: { + light: { + colors: { 'rgb-surface-primary': '255 255 255', 'rgb-text-primary': '22 21 23' }, + appearance: { controlRadius: '0.25rem' }, + }, + dark: { colors: { 'rgb-surface-primary': '31 31 28' } }, + }, + brands: { 'provider-openai': '#19C37D' }, + }; + + it('is absent when not configured', () => { + const result = configSchema.safeParse({ version: '1.3.0', interface: {} }); + expect(result.success).toBe(true); + expect(result.success && result.data.interface.theme).toBeUndefined(); + }); + + it('accepts a bundled theme name', () => { + const result = parseTheme('clickhouse'); + expect(result.success).toBe(true); + expect(result.success && result.data.interface.theme).toBe('clickhouse'); + }); + + it('rejects an empty theme name', () => { + expect(parseTheme(' ').success).toBe(false); + }); + + it('accepts a valid inline definition', () => { + const result = parseTheme(inlineTheme); + expect(result.success).toBe(true); + expect(result.success && result.data.interface.theme).toEqual(inlineTheme); + }); + + it('rejects a malformed RGB triplet', () => { + expect( + parseTheme({ + ...inlineTheme, + modes: { light: { colors: { 'rgb-surface-primary': '#ffffff' } } }, + }).success, + ).toBe(false); + }); + + it('rejects an unsupported version', () => { + expect(parseTheme({ ...inlineTheme, version: 2 }).success).toBe(false); + }); + + it('rejects unknown keys and color names without the rgb- prefix', () => { + expect(parseTheme({ ...inlineTheme, css: 'body {}' }).success).toBe(false); + expect(parseTheme({ ...inlineTheme, modes: { sepia: { colors: {} } } }).success).toBe(false); + expect( + parseTheme({ + ...inlineTheme, + modes: { light: { colors: { 'surface-primary': '255 255 255' } } }, + }).success, + ).toBe(false); + }); +}); diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index 604000d949..18b0332785 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -2292,26 +2292,34 @@ export enum RetentionMode { TEMPORARY = 'temporary', } -/** Single source for the agents panel selector's unsearched list cap; the - * schema default and the client fallback both read it. */ -export const DEFAULT_AGENT_SELECTOR_LIMIT = 10; -export const AGENT_SELECTOR_LIMIT_MIN = 1; -export const AGENT_SELECTOR_LIMIT_MAX = 100; +const themeModeSchema = z + .object({ + colors: z.record(z.string().regex(/^rgb-/), z.string().regex(/^\d{1,3} \d{1,3} \d{1,3}$/)), + appearance: z.record(z.string()), + brands: z.record(z.string()), + }) + .partial() + .strict(); -/** Runtime guard for values that bypass `interfaceSchema`: raw librechat.yaml - * reads and principal-scoped admin overrides reach the client unparsed, so an - * out-of-bounds value falls back to the default instead of emptying the list. */ -export function normalizeAgentSelectorLimit(value: unknown): number { - return typeof value === 'number' && - Number.isInteger(value) && - value >= AGENT_SELECTOR_LIMIT_MIN && - value <= AGENT_SELECTOR_LIMIT_MAX - ? value - : DEFAULT_AGENT_SELECTOR_LIMIT; -} +/** + * Shape of an inline deployment theme. Token names and value ranges are checked + * by the client registry (`validateThemeDefinition`), which owns the token list. + */ +export const themeDefinitionSchema = z + .object({ + version: z.literal(1), + name: z.string().trim().min(1), + modes: z.object({ light: themeModeSchema, dark: themeModeSchema }).partial().strict(), + brands: z.record(z.string()).optional(), + }) + .strict(); + +export type TThemeDefinitionConfig = z.infer; export const interfaceSchema = z .object({ + /** A bundled theme name or an inline theme definition applied to every user. */ + theme: z.union([z.string().trim().min(1), themeDefinitionSchema]).optional(), privacyPolicy: z .object({ externalUrl: z.string().optional(), diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts index 66c52ecaa8..74f56519a4 100644 --- a/packages/data-schemas/src/app/interface.spec.ts +++ b/packages/data-schemas/src/app/interface.spec.ts @@ -302,4 +302,39 @@ describe('loadDefaultInterface', () => { expect(interfaceConfig?.traceViewer).toBeUndefined(); }); + + it('passes a bundled theme name through unchanged', async () => { + const interfaceConfig = await loadDefaultInterface({ + config: { interface: { theme: 'clickhouse' } }, + configDefaults: getConfigDefaults(), + }); + + expect(interfaceConfig?.theme).toBe('clickhouse'); + }); + + it('passes an inline theme definition through unchanged', async () => { + const theme = { + version: 1 as const, + name: 'acme', + modes: { + light: { colors: { 'rgb-surface-primary': '255 255 255' } }, + dark: { appearance: { controlRadius: '0.25rem' } }, + }, + }; + const interfaceConfig = await loadDefaultInterface({ + config: { interface: { theme } }, + configDefaults: getConfigDefaults(), + }); + + expect(interfaceConfig?.theme).toEqual(theme); + }); + + it('leaves the theme unset when not configured', async () => { + const interfaceConfig = await loadDefaultInterface({ + config: {}, + configDefaults: getConfigDefaults(), + }); + + expect(interfaceConfig).not.toHaveProperty('theme'); + }); }); diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts index e0dee79d25..de9bce7783 100644 --- a/packages/data-schemas/src/app/interface.ts +++ b/packages/data-schemas/src/app/interface.ts @@ -47,6 +47,7 @@ export async function loadDefaultInterface({ contextCost: interfaceConfig?.contextCost ?? defaults.contextCost, feedback: interfaceConfig?.feedback ?? defaults.feedback, currency: interfaceConfig?.currency ?? defaults.currency, + theme: interfaceConfig?.theme, // Permissions and related settings - only include if explicitly configured bookmarks: interfaceConfig?.bookmarks, diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts index 00d040548f..f1ed8a393c 100644 --- a/packages/data-schemas/src/app/resolution.spec.ts +++ b/packages/data-schemas/src/app/resolution.spec.ts @@ -44,6 +44,43 @@ describe('mergeConfigOverrides', () => { expect(mergeConfigOverrides(baseConfig, undefined as unknown as IConfig[])).toBe(baseConfig); }); + it('replaces an inline interface theme whole instead of merging two definitions', () => { + const base = { + interfaceConfig: { + theme: { + version: 1, + name: 'base', + modes: { + light: { colors: { 'rgb-surface-primary': '255 255 255' } }, + dark: { colors: { 'rgb-surface-primary': '0 0 0' } }, + }, + brands: { 'provider-openai': '#19C37D' }, + }, + }, + } as unknown as AppConfig; + const override = { + version: 1, + name: 'principal', + modes: { light: { colors: { 'rgb-surface-primary': '240 240 240' } } }, + }; + + const result = mergeConfigOverrides(base, [fakeConfig({ interface: { theme: override } }, 10)]); + + expect(result.interfaceConfig?.theme).toEqual(override); + }); + + it('lets a bundled theme name override an inline base theme', () => { + const base = { + interfaceConfig: { theme: { version: 1, name: 'base', modes: {} } }, + } as unknown as AppConfig; + + const result = mergeConfigOverrides(base, [ + fakeConfig({ interface: { theme: 'clickhouse' } }, 10), + ]); + + expect(result.interfaceConfig?.theme).toBe('clickhouse'); + }); + it('does not allow DB overrides or tombstones to weaken base-only filters', () => { const base = { filters: { diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts index 1bd85676a6..c15a7b247c 100644 --- a/packages/data-schemas/src/app/resolution.ts +++ b/packages/data-schemas/src/app/resolution.ts @@ -35,6 +35,13 @@ const ARRAY_MERGE_KEYS: Record = { 'endpoints.custom': 'name', }; +/** + * Object-valued paths an override replaces whole instead of merging into. A theme + * definition is one coherent value: merging two would keep the base theme's modes, + * brands and tokens under the override's name. Uses AppConfig key names. + */ +const ATOMIC_MERGE_PATHS = new Set(['interfaceConfig.theme']); + /** * Maps YAML-level override keys (TCustomConfig) to their AppConfig equivalents. * Overrides are stored with YAML keys but merged into the already-processed AppConfig @@ -185,6 +192,7 @@ function deepMerge(target: T, source: AnyObject, depth = 0, const targetVal = result[key]; if ( depth < MAX_MERGE_DEPTH && + !ATOMIC_MERGE_PATHS.has(currentPath) && sourceVal != null && typeof sourceVal === 'object' && !Array.isArray(sourceVal) &&