mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-16 13:00:55 +00:00
🧩 feat: Ignore Unknown Theme Color Tokens Instead of Dropping the Theme (#16529)
This commit is contained in:
parent
dd5fdf1ff4
commit
491ea868da
15 changed files with 536 additions and 86 deletions
|
|
@ -201,7 +201,7 @@ describe('DeploymentTheme', () => {
|
|||
renderTheme(queryClient);
|
||||
|
||||
await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
|
||||
expect(warn.mock.calls[0][0]).toContain('Unknown color token: rgb-not-a-token');
|
||||
expect(warn.mock.calls[0][0]).toContain('Invalid RGB value for rgb-not-a-token: red');
|
||||
expect(root().dataset.theme).toBe('stored');
|
||||
});
|
||||
|
||||
|
|
|
|||
106
e2e/specs/mock/scenarios/theme-override.spec.ts
Normal file
106
e2e/specs/mock/scenarios/theme-override.spec.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import type { APIRequestContext } from '@playwright/test';
|
||||
import { getPrimaryE2EUser } from '../../../setup/users.mock';
|
||||
import { loginAdmin, requestResult } from '../content-filters.helpers';
|
||||
import { inOneProject } from './lint.helpers';
|
||||
import { withMongo } from '../db';
|
||||
|
||||
/**
|
||||
* A theme a DB config override supplies is merged after the YAML loader ran, so the service
|
||||
* applies the loader's rules itself: unknown colors are left out of what `/api/config` serves,
|
||||
* and an override theme the client would reject leaves the principal with the base theme.
|
||||
*/
|
||||
test.describe.configure({ mode: 'serial', timeout: 120_000 });
|
||||
|
||||
type InterfaceBody = { interface?: { theme?: unknown; customWelcome?: string } };
|
||||
|
||||
/** A sibling field the override also sets, so a check never passes before the override applies. */
|
||||
const MARKER = 'e2e theme override applied';
|
||||
|
||||
async function getPrimaryUserId(): Promise<string> {
|
||||
const { email } = getPrimaryE2EUser();
|
||||
const id = await withMongo(async (db) => {
|
||||
const user = await db.collection('users').findOne({ email }, { projection: { _id: 1 } });
|
||||
return user?._id?.toString();
|
||||
});
|
||||
if (!id) {
|
||||
throw new Error('primary user id not found');
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
async function withThemeOverride(
|
||||
request: APIRequestContext,
|
||||
theme: unknown,
|
||||
check: (token: string) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const token = await loginAdmin(request);
|
||||
const headers = { Authorization: `Bearer ${token}` };
|
||||
const path = `/api/admin/config/user/${encodeURIComponent(await getPrimaryUserId())}`;
|
||||
const saved = await request.put(path, {
|
||||
headers,
|
||||
data: { overrides: { interface: { theme, customWelcome: MARKER } } },
|
||||
});
|
||||
expect(saved.ok(), await saved.text()).toBe(true);
|
||||
try {
|
||||
await check(token);
|
||||
} finally {
|
||||
const removed = await request.delete(path, { headers, failOnStatusCode: false });
|
||||
expect([200, 404], await removed.text()).toContain(removed.status());
|
||||
}
|
||||
}
|
||||
|
||||
async function servedInterface(
|
||||
request: APIRequestContext,
|
||||
token: string,
|
||||
): Promise<InterfaceBody['interface']> {
|
||||
const config = await requestResult(request, { path: '/api/config', token });
|
||||
return (config.body as InterfaceBody | undefined)?.interface;
|
||||
}
|
||||
|
||||
async function servedOverrideTheme(request: APIRequestContext, token: string): Promise<unknown> {
|
||||
let served: InterfaceBody['interface'];
|
||||
await expect
|
||||
.poll(async () => {
|
||||
served = await servedInterface(request, token);
|
||||
return served?.customWelcome;
|
||||
})
|
||||
.toBe(MARKER);
|
||||
return served?.theme;
|
||||
}
|
||||
|
||||
test.describe('interface.theme from a config override', () => {
|
||||
test.beforeEach(() => inOneProject());
|
||||
|
||||
test('an override theme with an unknown color token is served without it @scenario:override-theme-unknown-color-left-out', async ({
|
||||
request,
|
||||
}) => {
|
||||
const theme = {
|
||||
version: 1,
|
||||
name: 'e2e-override',
|
||||
modes: { light: { colors: { 'rgb-surface-primary': '1 2 3', 'surface-future': '4 5 6' } } },
|
||||
};
|
||||
await withThemeOverride(request, theme, async (token) => {
|
||||
expect(await servedOverrideTheme(request, token)).toEqual({
|
||||
version: 1,
|
||||
name: 'e2e-override',
|
||||
modes: { light: { colors: { 'rgb-surface-primary': '1 2 3' } } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('an invalid override theme leaves the user with the base theme @scenario:override-theme-invalid-keeps-base', async ({
|
||||
request,
|
||||
}) => {
|
||||
const token = await loginAdmin(request);
|
||||
const base = (await servedInterface(request, token))?.theme;
|
||||
const theme = {
|
||||
version: 1,
|
||||
name: 'e2e-override-invalid',
|
||||
modes: { dark: { colors: { 'rgb-surface-primary': '300 16 32' } } },
|
||||
};
|
||||
await withThemeOverride(request, theme, async (overrideToken) => {
|
||||
expect(await servedOverrideTheme(request, overrideToken)).toEqual(base);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -118,36 +118,93 @@ test.describe('appearance tokens this build does not know', () => {
|
|||
});
|
||||
|
||||
/**
|
||||
* The same holds for a color role added after this build: a well-formed `rgb-` name with a valid
|
||||
* triplet is dropped with a warning, so a newer definition keeps every color this build paints.
|
||||
* The same holds for a color token this build does not know, whether it is a role added later
|
||||
* or a misspelling: a plain token name with a valid triplet is dropped with a warning, so the
|
||||
* definition keeps every color this build paints. A bad value still rejects the definition.
|
||||
*/
|
||||
test.describe('color tokens this build does not know', () => {
|
||||
const NEWER_COLORS = {
|
||||
version: 1,
|
||||
name: 'e2e-newer-colors',
|
||||
modes: {
|
||||
light: { colors: { 'rgb-surface-primary': '240 244 255', 'rgb-future-role': '1 2 3' } },
|
||||
dark: { colors: { 'rgb-surface-primary': '12 16 32', 'rgb-future-role': '1 2 3' } },
|
||||
light: {
|
||||
colors: {
|
||||
'rgb-surface-primary': '240 244 255',
|
||||
'rgb-future-role': '1 2 3',
|
||||
'surface-future': '7 8 9',
|
||||
},
|
||||
},
|
||||
dark: {
|
||||
colors: {
|
||||
'rgb-surface-primary': '12 16 32',
|
||||
'rgb-future-role': '1 2 3',
|
||||
'surface-future': '7 8 9',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
test('a stored theme with an unknown color role keeps the colors this build paints @scenario:stored-theme-unknown-color-token-applies-rest', async ({
|
||||
page,
|
||||
}) => {
|
||||
async function expectNewerColorsApplied(page: Page) {
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', NEWER_COLORS.name);
|
||||
const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
|
||||
expect(await themeValue(page, '--surface-primary')).toBe(dark ? '12 16 32' : '240 244 255');
|
||||
expect(await themeValue(page, '--future-role')).toBe('');
|
||||
const style = (await page.locator('html').getAttribute('style')) ?? '';
|
||||
expect(style).not.toContain('future');
|
||||
expect(style).not.toContain('7 8 9');
|
||||
}
|
||||
|
||||
const collectWarnings = (page: Page): string[] => {
|
||||
const warnings: string[] = [];
|
||||
page.on('console', (message) => {
|
||||
if (message.type() === 'warning') {
|
||||
warnings.push(message.text());
|
||||
}
|
||||
});
|
||||
return warnings;
|
||||
};
|
||||
|
||||
test('a stored theme with an unknown color token keeps the colors this build paints @scenario:stored-theme-unknown-color-token-applies-rest', async ({
|
||||
page,
|
||||
}) => {
|
||||
const warnings = collectWarnings(page);
|
||||
await storeTheme(page, NEWER_COLORS);
|
||||
|
||||
await openChat(page);
|
||||
|
||||
await expect(page.locator('html')).toHaveAttribute('data-theme', NEWER_COLORS.name);
|
||||
const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
|
||||
expect(await themeValue(page, '--surface-primary')).toBe(dark ? '12 16 32' : '240 244 255');
|
||||
expect(await themeValue(page, '--future-role')).toBe('');
|
||||
await expectNewerColorsApplied(page);
|
||||
expect(warnings.join('\n')).toContain('color token ignored: rgb-future-role');
|
||||
expect(warnings.join('\n')).toContain('color token ignored: surface-future');
|
||||
});
|
||||
|
||||
test('a deployment theme with an unknown color token keeps the colors this build paints @scenario:deployment-theme-unknown-color-token-applies-rest', async ({
|
||||
page,
|
||||
}) => {
|
||||
const warnings = collectWarnings(page);
|
||||
await serveTheme(page, NEWER_COLORS);
|
||||
|
||||
await openChat(page);
|
||||
|
||||
await expectNewerColorsApplied(page);
|
||||
expect(warnings.join('\n')).toContain('color token ignored: surface-future');
|
||||
});
|
||||
|
||||
test('a stored theme whose unknown color token has an invalid value is still rejected @scenario:stored-theme-unknown-color-invalid-value-rejected', async ({
|
||||
page,
|
||||
}) => {
|
||||
const theme = {
|
||||
version: 1,
|
||||
name: 'e2e-invalid-unknown-color',
|
||||
modes: {
|
||||
light: { colors: { 'rgb-surface-primary': '240 244 255', 'surface-future': 'red' } },
|
||||
dark: { colors: { 'rgb-surface-primary': '12 16 32', 'surface-future': 'red' } },
|
||||
},
|
||||
};
|
||||
await storeTheme(page, theme);
|
||||
|
||||
await openChat(page);
|
||||
|
||||
await expect(page.locator('html')).not.toHaveAttribute('data-theme', theme.name);
|
||||
expect(await themeValue(page, '--surface-primary')).not.toBe('240 244 255');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { inOneProject, repoRoot, run } from './lint.helpers';
|
|||
/**
|
||||
* A mistake in `interface.theme` used to fail the whole librechat.yaml and stop the server. The
|
||||
* config loader that `/api` wires up now drops only the theme, names each problem by its path, and
|
||||
* loads everything else. The mock lane serves one shared yaml, so these load their own fixtures
|
||||
* loads everything else; a token this version does not know only warns. The mock lane serves one shared yaml, so these load their own fixtures
|
||||
* through that same loader in a child process, the way the server does at startup and on reload.
|
||||
*/
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
|
@ -56,17 +56,22 @@ test.describe('interface.theme in librechat.yaml', () => {
|
|||
delete process.env.CONFIG_PATH;
|
||||
});
|
||||
|
||||
test('a typo in a theme token leaves the server running on the default theme @scenario:yaml-theme-typo-falls-back', () => {
|
||||
test('a color token this version does not know is ignored and the theme still loads @scenario:yaml-theme-unknown-color-kept', () => {
|
||||
const { outcome, log } = loadFixture('unknown-token');
|
||||
|
||||
expect(outcome.exited).toBeUndefined();
|
||||
expect(outcome.interface).toEqual({ modelSelect: true });
|
||||
expect(log).toContain('the default theme applies instead');
|
||||
expect(outcome.interface?.modelSelect).toBe(true);
|
||||
expect(outcome.interface?.theme).toEqual({
|
||||
version: 1,
|
||||
name: 'acme',
|
||||
modes: { light: { colors: { 'rgb-surface-primary': '240 244 255' } } },
|
||||
});
|
||||
expect(log).not.toContain('the default theme applies instead');
|
||||
expect(log).toContain(
|
||||
'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token: rgb-surfce-secondary',
|
||||
'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown light color token ignored: rgb-surfce-secondary',
|
||||
);
|
||||
expect(log).toContain(
|
||||
'interface.theme.modes.light.colors.surface-tertiary: Unknown color token: surface-tertiary',
|
||||
'interface.theme.modes.light.colors.surface-tertiary: Unknown light color token ignored: surface-tertiary',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -113,11 +118,11 @@ test.describe('interface.theme in librechat.yaml', () => {
|
|||
});
|
||||
|
||||
test('a config reload with a broken theme applies the same fallback @scenario:yaml-theme-reload-falls-back', () => {
|
||||
const { outcome, log } = loadFixture('unknown-token', 'reload');
|
||||
const { outcome, log } = loadFixture('bad-value', 'reload');
|
||||
|
||||
expect(outcome.rejected).toBeUndefined();
|
||||
expect(outcome.interface).toEqual({ modelSelect: true });
|
||||
expect(log).toContain('interface.theme.modes.light.colors.rgb-surfce-secondary');
|
||||
expect(log).toContain('interface.theme.modes.dark.colors.rgb-surface-primary');
|
||||
});
|
||||
|
||||
test('an invalid key outside the theme still stops startup @scenario:yaml-theme-other-errors-still-exit', () => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,15 @@
|
|||
version: 1.3.17
|
||||
cache: true
|
||||
interface:
|
||||
modelSelect: true
|
||||
theme:
|
||||
version: 1
|
||||
name: acme
|
||||
modes:
|
||||
light:
|
||||
colors:
|
||||
rgb-surface-primary: '240 244 255'
|
||||
rgb-future-role: 'red'
|
||||
dark:
|
||||
colors:
|
||||
'Surface Tertiary': '245 245 245'
|
||||
|
|
@ -55,21 +55,40 @@ describe('createCustomConfigLoader interface.theme', () => {
|
|||
expect(exit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops a theme naming an unknown color token and keeps the rest of the config', async () => {
|
||||
it('keeps a theme naming a color token this version does not know, without that token', async () => {
|
||||
const config = await load('unknown-token');
|
||||
|
||||
expect(exit).not.toHaveBeenCalled();
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.interface).not.toHaveProperty('theme');
|
||||
expect(config?.interface?.theme).toEqual({
|
||||
version: 1,
|
||||
name: 'acme',
|
||||
modes: { light: { colors: { 'rgb-surface-primary': '240 244 255' } } },
|
||||
});
|
||||
expect(config?.interface?.modelSelect).toBe(true);
|
||||
expect(config?.cache).toBe(true);
|
||||
expect(warnings(warn)).toContain(
|
||||
'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token: rgb-surfce-secondary',
|
||||
'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown light color token ignored: rgb-surfce-secondary',
|
||||
);
|
||||
expect(warnings(warn)).toContain(
|
||||
'interface.theme.modes.light.colors.surface-tertiary: Unknown color token: surface-tertiary',
|
||||
'interface.theme.modes.light.colors.surface-tertiary: Unknown light color token ignored: surface-tertiary',
|
||||
);
|
||||
expect(warnings(warn)).toContain('the default theme applies instead');
|
||||
expect(warnings(warn)).not.toContain('the default theme applies instead');
|
||||
});
|
||||
|
||||
it('still drops a theme whose unknown color token has an invalid value or name', async () => {
|
||||
const config = await load('unknown-token-invalid');
|
||||
|
||||
expect(exit).not.toHaveBeenCalled();
|
||||
expect(config?.interface).not.toHaveProperty('theme');
|
||||
expect(config?.interface?.modelSelect).toBe(true);
|
||||
const logged = warnings(warn);
|
||||
expect(logged).toContain(
|
||||
'interface.theme.modes.light.colors.rgb-future-role: Invalid RGB value for rgb-future-role: red',
|
||||
);
|
||||
expect(logged).toContain(
|
||||
'interface.theme.modes.dark.colors.Surface Tertiary: Unknown color token: Surface Tertiary',
|
||||
);
|
||||
expect(logged).toContain('the default theme applies instead');
|
||||
});
|
||||
|
||||
it('reports every bad value with its path and drops the theme', async () => {
|
||||
|
|
@ -141,12 +160,12 @@ describe('createCustomConfigLoader interface.theme', () => {
|
|||
|
||||
describe('reload mode', () => {
|
||||
it('applies the same fallback instead of rejecting the reload', async () => {
|
||||
const config = await load('unknown-token', 'reload');
|
||||
const config = await load('bad-value', 'reload');
|
||||
|
||||
expect(config?.interface).not.toHaveProperty('theme');
|
||||
expect(config?.interface?.modelSelect).toBe(true);
|
||||
expect(warnings(warn)).toContain(
|
||||
'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token',
|
||||
'interface.theme.modes.dark.colors.rgb-surface-primary: Invalid RGB value',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -248,6 +248,68 @@ describe('createAppConfigService', () => {
|
|||
expect(config.modelSpecs?.list?.[0]?.preset?.agent_id).toBe('agent_abc');
|
||||
});
|
||||
|
||||
it('leaves unknown colors out of a theme a DB override supplies', async () => {
|
||||
const deps = createDeps({
|
||||
getApplicableConfigs: jest.fn().mockResolvedValue([
|
||||
{
|
||||
priority: 10,
|
||||
isActive: true,
|
||||
overrides: {
|
||||
interface: {
|
||||
theme: {
|
||||
version: 1,
|
||||
name: 'override',
|
||||
modes: {
|
||||
light: {
|
||||
colors: { 'rgb-surface-primary': '1 2 3', 'surface-future': '4 5 6' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const { getAppConfig } = createAppConfigService(deps);
|
||||
|
||||
const config = await getAppConfig({ role: 'USER' });
|
||||
|
||||
expect(config.interfaceConfig?.theme).toEqual({
|
||||
version: 1,
|
||||
name: 'override',
|
||||
modes: { light: { colors: { 'rgb-surface-primary': '1 2 3' } } },
|
||||
});
|
||||
expect(config.interfaceConfig?.modelSelect).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps the base theme when a DB override supplies an invalid one', async () => {
|
||||
const deps = createDeps({
|
||||
loadBaseConfig: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ interfaceConfig: { modelSelect: true, theme: 'clickhouse' } }),
|
||||
getApplicableConfigs: jest.fn().mockResolvedValue([
|
||||
{
|
||||
priority: 10,
|
||||
isActive: true,
|
||||
overrides: {
|
||||
interface: {
|
||||
theme: {
|
||||
version: 1,
|
||||
name: 'override',
|
||||
modes: { dark: { colors: { 'rgb-surface-primary': '300 16 32' } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
const { getAppConfig } = createAppConfigService(deps);
|
||||
|
||||
const config = await getAppConfig({ role: 'USER' });
|
||||
|
||||
expect(config.interfaceConfig?.theme).toBe('clickhouse');
|
||||
});
|
||||
|
||||
it('caches empty result — does not re-query DB on second call', async () => {
|
||||
const deps = createDeps({ getApplicableConfigs: jest.fn().mockResolvedValue([]) });
|
||||
const { getAppConfig } = createAppConfigService(deps);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import {
|
|||
import type { AppConfig, IConfig } from '@librechat/data-schemas';
|
||||
import type { Types } from 'mongoose';
|
||||
import type { CustomConfigLoadMode } from './loader';
|
||||
import { checkAppConfigTheme } from './theme';
|
||||
|
||||
const BASE_CONFIG_KEY = '_BASE_';
|
||||
|
||||
|
|
@ -20,6 +21,33 @@ export type AppConfigPrincipal = {
|
|||
principalId?: string | Types.ObjectId;
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies the loader's theme rules to a theme a DB override replaced. Unknown colors are left
|
||||
* out as they are for the YAML theme; an override theme the client would reject counts as unset,
|
||||
* so the principal keeps the base theme instead of losing its theme to a bad override.
|
||||
*/
|
||||
function checkOverrideTheme(baseConfig: AppConfig, merged: AppConfig): AppConfig {
|
||||
const baseTheme = baseConfig.interfaceConfig?.theme;
|
||||
if (merged.interfaceConfig?.theme === baseTheme) {
|
||||
return merged;
|
||||
}
|
||||
const { appConfig, errors, warnings } = checkAppConfigTheme(merged);
|
||||
if (warnings.length > 0) {
|
||||
logger.warn(
|
||||
'[getAppConfig] interface.theme from a config override names tokens this version ignores:\n' +
|
||||
warnings.map((warning) => `- ${warning}`).join('\n'),
|
||||
);
|
||||
}
|
||||
if (errors.length === 0) {
|
||||
return appConfig;
|
||||
}
|
||||
logger.warn(
|
||||
'[getAppConfig] Ignoring interface.theme from a config override; the base theme applies instead:\n' +
|
||||
errors.map((error) => `- ${error}`).join('\n'),
|
||||
);
|
||||
return { ...merged, interfaceConfig: { ...merged.interfaceConfig, theme: baseTheme } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes inferable model-spec fields (an omitted `preset.endpoint` for
|
||||
* agent specs) so every consumer of the effective config reads complete specs.
|
||||
|
|
@ -384,7 +412,10 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
|
|||
try {
|
||||
const configs = await getApplicableConfigs(principals);
|
||||
if (configs.length > 0) {
|
||||
merged = materializeConfigModelSpecs(mergeConfigOverrides(baseConfig, configs));
|
||||
merged = checkOverrideTheme(
|
||||
baseConfig,
|
||||
materializeConfigModelSpecs(mergeConfigOverrides(baseConfig, configs)),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (failClosed) throw error;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
collectThemeWarningIssues,
|
||||
} from 'librechat-data-provider';
|
||||
import type { ThemeIssue } from 'librechat-data-provider';
|
||||
import type { AppConfig } from '@librechat/data-schemas';
|
||||
|
||||
const THEME_PATH = ['interface', 'theme'];
|
||||
|
||||
|
|
@ -50,11 +51,37 @@ function collectErrors(theme: unknown): ThemeIssue[] {
|
|||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* A client older than this server tolerates only the unknown color names it was built to expect,
|
||||
* so a token this version does not paint is left out of the served theme rather than handed to
|
||||
* a cached client that might reject the whole definition for it.
|
||||
*/
|
||||
function withoutUnknownColors(
|
||||
theme: Record<string, unknown>,
|
||||
warnings: ThemeIssue[],
|
||||
): Record<string, unknown> {
|
||||
const unknown = warnings.filter(({ path }) => path[2] === 'colors');
|
||||
if (unknown.length === 0 || !isPlainThemeRecord(theme.modes)) {
|
||||
return theme;
|
||||
}
|
||||
const modes: Record<string, unknown> = { ...theme.modes };
|
||||
unknown.forEach(({ path: [, mode, , token] }) => {
|
||||
const definition = modes[mode];
|
||||
if (!isPlainThemeRecord(definition) || !isPlainThemeRecord(definition.colors)) {
|
||||
return;
|
||||
}
|
||||
const { [token]: _ignored, ...colors } = definition.colors;
|
||||
modes[mode] = { ...definition, colors };
|
||||
});
|
||||
return { ...theme, modes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks `interface.theme` with the rules the client applies before painting it. A theme the
|
||||
* client would reject is removed, so the deployment falls back to the default theme and the rest
|
||||
* of the config still loads; unknown appearance tokens, which the client drops on its own, only
|
||||
* warn. A config without a theme, or with a valid one, is returned as the same object.
|
||||
* of the config still loads; unknown color and appearance tokens, which the client drops on its
|
||||
* own, only warn, and unknown colors are left out of the returned theme. A config without a
|
||||
* theme, or with a valid one naming only known colors, is returned as the same object.
|
||||
*/
|
||||
export function checkConfigTheme(config: unknown): ConfigThemeCheck {
|
||||
const unchanged: ConfigThemeCheck = { config, errors: [], warnings: [] };
|
||||
|
|
@ -69,9 +96,43 @@ export function checkConfigTheme(config: unknown): ConfigThemeCheck {
|
|||
const theme = interfaceConfig.theme;
|
||||
const errors = collectErrors(theme).map(formatIssue);
|
||||
if (errors.length === 0) {
|
||||
return { config, errors, warnings: collectThemeWarningIssues(theme).map(formatIssue) };
|
||||
const warningIssues = collectThemeWarningIssues(theme);
|
||||
const warnings = warningIssues.map(formatIssue);
|
||||
const served = isPlainThemeRecord(theme) ? withoutUnknownColors(theme, warningIssues) : theme;
|
||||
if (served === theme) {
|
||||
return { config, errors, warnings };
|
||||
}
|
||||
return {
|
||||
config: { ...config, interface: { ...interfaceConfig, theme: served } },
|
||||
errors,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
const { theme: _dropped, ...rest } = interfaceConfig;
|
||||
return { config: { ...config, interface: rest }, errors, warnings: [] };
|
||||
}
|
||||
|
||||
export interface AppConfigThemeCheck {
|
||||
/** The assembled config, the input itself unless its theme had to be cleaned or dropped. */
|
||||
appConfig: AppConfig;
|
||||
errors: string[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The same check for an assembled config whose theme a DB override supplied: overrides are
|
||||
* merged after the YAML loader ran, so their theme would otherwise reach the client unchecked.
|
||||
*/
|
||||
export function checkAppConfigTheme(appConfig: AppConfig): AppConfigThemeCheck {
|
||||
const { interfaceConfig } = appConfig;
|
||||
if (interfaceConfig?.theme === undefined) {
|
||||
return { appConfig, errors: [], warnings: [] };
|
||||
}
|
||||
const { config, errors, warnings } = checkConfigTheme({ interface: interfaceConfig });
|
||||
const checked = (config as { interface: AppConfig['interfaceConfig'] }).interface;
|
||||
if (checked === interfaceConfig) {
|
||||
return { appConfig, errors, warnings };
|
||||
}
|
||||
return { appConfig: { ...appConfig, interfaceConfig: checked }, errors, warnings };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -931,6 +931,87 @@ describe('ThemeProvider', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('a definition carrying a color token this reader does not know', () => {
|
||||
const newerDefinition = {
|
||||
version: 1 as const,
|
||||
name: 'newer',
|
||||
modes: {
|
||||
light: { colors: { 'rgb-accent-primary': '4 5 6', 'surface-future': '7 8 9' } },
|
||||
dark: { colors: { 'rgb-accent-primary': '6 5 4', 'rgb-future-role': '9 8 7' } },
|
||||
},
|
||||
};
|
||||
let warn: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
warn.mockRestore();
|
||||
});
|
||||
|
||||
const expectApplied = () => {
|
||||
const root = document.documentElement;
|
||||
expect(root.dataset.theme).toBe('newer');
|
||||
expect(root.style.getPropertyValue('--accent-primary')).toBe('4 5 6');
|
||||
expect(root.getAttribute('style')).not.toContain('future');
|
||||
expect(root.getAttribute('style')).not.toContain('7 8 9');
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[ThemeProvider] Unknown light color token ignored: surface-future; ' +
|
||||
'Unknown dark color token ignored: rgb-future-role',
|
||||
);
|
||||
};
|
||||
|
||||
it('restores the stored definition with the rest applied and keeps the key stored', async () => {
|
||||
localStorage.setItem('theme-definition', JSON.stringify(newerDefinition));
|
||||
localStorage.setItem('theme-source', 'definition');
|
||||
|
||||
render(
|
||||
<ThemeProvider initialTheme="light">
|
||||
<Controls />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
await waitFor(expectApplied);
|
||||
expect(JSON.parse(localStorage.getItem('theme-definition') ?? '{}')).toEqual(newerDefinition);
|
||||
});
|
||||
|
||||
it('applies the same definition from a controlled deployment prop', async () => {
|
||||
render(
|
||||
<ThemeProvider
|
||||
initialTheme="light"
|
||||
persistThemeDefinition={false}
|
||||
themeDefinition={newerDefinition}
|
||||
>
|
||||
<Controls />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
await waitFor(expectApplied);
|
||||
expect(localStorage.getItem('theme-definition')).toBeNull();
|
||||
});
|
||||
|
||||
it('still discards a stored definition whose unknown token has an invalid value', async () => {
|
||||
const invalid = {
|
||||
...newerDefinition,
|
||||
modes: { light: { colors: { 'rgb-accent-primary': '4 5 6', 'surface-future': 'red' } } },
|
||||
};
|
||||
localStorage.setItem('theme-definition', JSON.stringify(invalid));
|
||||
|
||||
render(
|
||||
<ThemeProvider initialTheme="light">
|
||||
<Controls />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.documentElement.classList.contains('light')).toBe(true);
|
||||
});
|
||||
expect(document.documentElement.dataset.theme).toBeUndefined();
|
||||
expect(document.documentElement.style.getPropertyValue('--accent-primary')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
it('uses a stable identity when a legacy consumer clears an active theme name', async () => {
|
||||
render(
|
||||
<ThemeProvider
|
||||
|
|
|
|||
|
|
@ -1103,7 +1103,7 @@ describe('theme registry', () => {
|
|||
|
||||
expect(validateThemeDefinition(invalidTheme)).toEqual([
|
||||
'Invalid RGB value for rgb-text-primary: 999 0 0',
|
||||
'Unknown color token: rgb-unknown',
|
||||
'Invalid RGB value for rgb-unknown: red',
|
||||
'Invalid appearance value for controlRadius: url(theme.css)',
|
||||
'Invalid appearance value for shadowLg: 0 1px red; color: red',
|
||||
'Invalid appearance value for shadowMd: not-a-shadow',
|
||||
|
|
@ -1162,39 +1162,61 @@ describe('theme registry', () => {
|
|||
expect(() => resolveTheme(theme, 'light')).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it('ignores a well-formed colour role it predates and paints the rest', () => {
|
||||
it('ignores a colour token it does not know and paints the rest', () => {
|
||||
const theme = {
|
||||
version: 1,
|
||||
name: 'colour',
|
||||
modes: {
|
||||
light: {
|
||||
colors: { 'rgb-future': '1 2 3', 'rgb-accent-primary': '4 5 6' },
|
||||
colors: {
|
||||
'rgb-future': '1 2 3',
|
||||
'surface-future': '7 8 9',
|
||||
'rgb-accent-primary': '4 5 6',
|
||||
},
|
||||
appearance: { futureSpacing: '1rem' },
|
||||
},
|
||||
dark: { colors: { 'rgb-surfce-primary': '1 1 1' } },
|
||||
},
|
||||
} as ThemeDefinition;
|
||||
|
||||
expect(validateThemeDefinition(theme)).toEqual([]);
|
||||
expect(collectThemeWarnings(theme)).toEqual([
|
||||
'Unknown light color token ignored: rgb-future',
|
||||
'Unknown light color token ignored: surface-future',
|
||||
'Unknown light appearance token ignored: futureSpacing',
|
||||
'Unknown dark color token ignored: rgb-surfce-primary',
|
||||
]);
|
||||
const resolved = resolveTheme(theme, 'light');
|
||||
expect(resolved.colors['rgb-accent-primary']).toBe('4 5 6');
|
||||
expect(resolved.colors).not.toHaveProperty('rgb-future');
|
||||
expect(resolved.colors).not.toHaveProperty('surface-future');
|
||||
expect(resolveTheme(theme, 'dark').colors).not.toHaveProperty('rgb-surfce-primary');
|
||||
});
|
||||
|
||||
it('still rejects an unknown colour token that is not a well-formed role', () => {
|
||||
it('still rejects an unknown colour token with an invalid value or a malformed name', () => {
|
||||
const theme = {
|
||||
version: 1,
|
||||
name: 'colour',
|
||||
modes: { light: { colors: { 'rgb-future': 'red', future: '1 2 3' } } },
|
||||
modes: {
|
||||
light: {
|
||||
colors: {
|
||||
'rgb-future': 'red',
|
||||
'surface-future': '300 0 0',
|
||||
'Surface Future': '1 2 3',
|
||||
'rgb-x;}': '1 2 3',
|
||||
},
|
||||
},
|
||||
},
|
||||
} as ThemeDefinition;
|
||||
|
||||
expect(validateThemeDefinition(theme)).toEqual([
|
||||
'Unknown color token: rgb-future',
|
||||
'Unknown color token: future',
|
||||
'Invalid RGB value for rgb-future: red',
|
||||
'Invalid RGB value for surface-future: 300 0 0',
|
||||
'Unknown color token: Surface Future',
|
||||
'Unknown color token: rgb-x;}',
|
||||
]);
|
||||
expect(collectThemeWarnings(theme)).toEqual([]);
|
||||
expect(() => resolveTheme(theme, 'light')).toThrow(TypeError);
|
||||
});
|
||||
|
||||
it('still rejects an injection attempt carried by an unknown key', () => {
|
||||
|
|
|
|||
|
|
@ -314,17 +314,13 @@ export const highContrastTheme: ThemeDefinition = Object.freeze({
|
|||
/** Tailwind composes `--tw-shadow` into one list with the ring layers, where `none` is invalid. */
|
||||
const disabledShadow = '0 0 #0000';
|
||||
|
||||
/** The client may be older than the server whose theme it paints, so it ignores color roles it
|
||||
* predates the way it already ignores appearance keys. */
|
||||
const clientReader = { ignoreFutureColors: true } as const;
|
||||
|
||||
/** The color and appearance tokens this reader does not know, which `resolveTheme` leaves out. */
|
||||
export function collectThemeWarnings(theme: ThemeDefinition): string[] {
|
||||
return collectThemeWarningIssues(theme, clientReader).map(({ message }) => message);
|
||||
return collectThemeWarningIssues(theme).map(({ message }) => message);
|
||||
}
|
||||
|
||||
export function validateThemeDefinition(theme: ThemeDefinition): string[] {
|
||||
return collectThemeIssues(theme, clientReader).map(({ message }) => message);
|
||||
return collectThemeIssues(theme).map(({ message }) => message);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -342,7 +338,7 @@ function definedEntries<T extends object>(values?: Partial<T>): Partial<T> {
|
|||
) as Partial<T>;
|
||||
}
|
||||
|
||||
/** A color role this reader predates passed validation as a warning; it never reaches the DOM. */
|
||||
/** A color token this reader does not know passed validation as a warning; it never reaches the DOM. */
|
||||
function knownColors(colors?: IThemeRGB): IThemeRGB | undefined {
|
||||
if (!colors) {
|
||||
return colors;
|
||||
|
|
|
|||
|
|
@ -2092,17 +2092,26 @@ describe('interface theme config', () => {
|
|||
expect(parseTheme({ ...inlineTheme, version: 2 }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects unknown keys and color names without the rgb- prefix', () => {
|
||||
it('rejects unknown keys and color names that are not plain tokens', () => {
|
||||
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' } } },
|
||||
modes: { light: { colors: { 'Surface Primary': '255 255 255' } } },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts an unknown color token name so the loader can ignore it', () => {
|
||||
expect(
|
||||
parseTheme({
|
||||
...inlineTheme,
|
||||
modes: { light: { colors: { 'surface-primary': '255 255 255' } } },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts the ceilings and rejects values above them', () => {
|
||||
const atCeiling = { maxFiles: 500, maxInstructionsLength: 200000, maxDescriptionLength: 10000 };
|
||||
expect(chatProjectsConfigSchema.parse(atCeiling)).toEqual(atCeiling);
|
||||
|
|
|
|||
|
|
@ -2254,7 +2254,10 @@ export enum RetentionMode {
|
|||
|
||||
const themeModeSchema = z
|
||||
.object({
|
||||
colors: z.record(z.string().regex(/^rgb-/), z.string().regex(/^\d{1,3} \d{1,3} \d{1,3}$/)),
|
||||
colors: z.record(
|
||||
z.string().regex(/^[a-z][a-z0-9-]*$/),
|
||||
z.string().regex(/^\d{1,3} \d{1,3} \d{1,3}$/),
|
||||
),
|
||||
appearance: z.record(z.string()),
|
||||
brands: z.record(z.string()),
|
||||
})
|
||||
|
|
|
|||
|
|
@ -388,24 +388,15 @@ const isFutureAppearance = (key: string, value: unknown): boolean =>
|
|||
/^[a-z][a-zA-Z0-9]*$/.test(key) && typeof value === 'string' && !/[;{}<>]|url\s*\(/i.test(value);
|
||||
|
||||
/**
|
||||
* The same allowance for a color role: a well-formed `rgb-` name holding an RGB triplet is one
|
||||
* this reader predates, so it is ignored rather than rejecting a theme a newer server or build
|
||||
* wrote. Anything else under an unknown name is still an error.
|
||||
* The same allowance for a color role: a color token this reader does not know is ignored rather
|
||||
* than rejecting the theme, so a newer definition keeps every role this version can paint and a
|
||||
* misspelled one costs only itself. The name must still be a plain token; its value is checked
|
||||
* like any other role.
|
||||
*/
|
||||
const isFutureColor = (key: string, value: unknown): boolean =>
|
||||
/^rgb-[a-z][a-z0-9-]*$/.test(key) && isThemeRGB(value);
|
||||
const isColorTokenName = (key: string): boolean => /^[a-z][a-z0-9-]*$/.test(key);
|
||||
|
||||
const issue = (path: string[], message: string): ThemeIssue => ({ path, message });
|
||||
|
||||
export interface ThemeReadOptions {
|
||||
/**
|
||||
* A reader that may be older than the definition it paints (a cached client reading a newer
|
||||
* server's theme) ignores well-formed color roles it predates. The server reads its own config
|
||||
* with its own token list, so there an unknown role is a typo and stays an error.
|
||||
*/
|
||||
ignoreFutureColors?: boolean;
|
||||
}
|
||||
|
||||
/** LibreChat's own switch, which a theme naming only one of the two dimensions keeps for the other. */
|
||||
export const defaultSwitchSize = Object.freeze({ switchWidth: '2.75rem', switchHeight: '1.5rem' });
|
||||
|
||||
|
|
@ -465,10 +456,7 @@ function collectSwitchIssues(appearance: Record<string, unknown>, base: string[]
|
|||
}
|
||||
|
||||
/** The color and appearance tokens this reader does not know, which a resolved theme leaves out. */
|
||||
export function collectThemeWarningIssues(
|
||||
theme: unknown,
|
||||
{ ignoreFutureColors = false }: ThemeReadOptions = {},
|
||||
): ThemeIssue[] {
|
||||
export function collectThemeWarningIssues(theme: unknown): ThemeIssue[] {
|
||||
if (!isPlainThemeRecord(theme) || !isPlainThemeRecord(theme.modes)) {
|
||||
return [];
|
||||
}
|
||||
|
|
@ -479,14 +467,15 @@ export function collectThemeWarningIssues(
|
|||
return [];
|
||||
}
|
||||
const { colors, appearance } = definition;
|
||||
const futureColors =
|
||||
ignoreFutureColors && isPlainThemeRecord(colors)
|
||||
? Object.entries(colors)
|
||||
.filter(([key, value]) => !colorTokenSet.has(key) && isFutureColor(key, value))
|
||||
.map(([key]) =>
|
||||
issue(['modes', mode, 'colors', key], `Unknown ${mode} color token ignored: ${key}`),
|
||||
)
|
||||
: [];
|
||||
const futureColors = isPlainThemeRecord(colors)
|
||||
? Object.entries(colors)
|
||||
.filter(
|
||||
([key, value]) => !colorTokenSet.has(key) && isColorTokenName(key) && isThemeRGB(value),
|
||||
)
|
||||
.map(([key]) =>
|
||||
issue(['modes', mode, 'colors', key], `Unknown ${mode} color token ignored: ${key}`),
|
||||
)
|
||||
: [];
|
||||
const futureAppearance = isPlainThemeRecord(appearance)
|
||||
? Object.keys(appearance)
|
||||
.filter((key) => !isThemeAppearanceToken(key))
|
||||
|
|
@ -524,11 +513,7 @@ function collectBrandIssues(brands: unknown, path: string[]): ThemeIssue[] {
|
|||
});
|
||||
}
|
||||
|
||||
function collectModeIssues(
|
||||
mode: 'light' | 'dark',
|
||||
definition: unknown,
|
||||
{ ignoreFutureColors = false }: ThemeReadOptions,
|
||||
): ThemeIssue[] {
|
||||
function collectModeIssues(mode: 'light' | 'dark', definition: unknown): ThemeIssue[] {
|
||||
const base = ['modes', mode];
|
||||
if (definition === undefined) {
|
||||
return [];
|
||||
|
|
@ -547,10 +532,8 @@ function collectModeIssues(
|
|||
} else {
|
||||
Object.entries(colors ?? {}).forEach(([key, value]) => {
|
||||
const path = [...base, 'colors', key];
|
||||
if (!colorTokenSet.has(key)) {
|
||||
if (!ignoreFutureColors || !isFutureColor(key, value)) {
|
||||
issues.push(issue(path, `Unknown color token: ${key}`));
|
||||
}
|
||||
if (!colorTokenSet.has(key) && !isColorTokenName(key)) {
|
||||
issues.push(issue(path, `Unknown color token: ${key}`));
|
||||
return;
|
||||
}
|
||||
if (value !== undefined && !isThemeRGB(value)) {
|
||||
|
|
@ -586,7 +569,7 @@ function collectModeIssues(
|
|||
}
|
||||
|
||||
/** Every reason a definition cannot be painted; empty when it can. */
|
||||
export function collectThemeIssues(theme: unknown, options: ThemeReadOptions = {}): ThemeIssue[] {
|
||||
export function collectThemeIssues(theme: unknown): ThemeIssue[] {
|
||||
if (!isPlainThemeRecord(theme)) {
|
||||
return [issue([], 'Theme definition must be an object')];
|
||||
}
|
||||
|
|
@ -611,7 +594,7 @@ export function collectThemeIssues(theme: unknown, options: ThemeReadOptions = {
|
|||
.filter((mode) => mode !== 'light' && mode !== 'dark')
|
||||
.forEach((mode) => issues.push(issue(['modes', mode], `Unknown theme mode: ${mode}`)));
|
||||
|
||||
themeModes.forEach((mode) => issues.push(...collectModeIssues(mode, modes[mode], options)));
|
||||
themeModes.forEach((mode) => issues.push(...collectModeIssues(mode, modes[mode])));
|
||||
|
||||
if (theme.brands !== undefined && !isPlainThemeRecord(theme.brands)) {
|
||||
issues.push(issue(['brands'], 'Theme brands must be an object'));
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue