Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🌅 fix: Paint the Cached Deployment Theme on the First Frame (#16590)

Marco Beretta82127a2269f3
diff --git a/client/index.html b/client/index.html
index 9fe3086ed9..3c083790ae 100644
--- a/client/index.html
+++ b/client/index.html
@@ -28,56 +28,114 @@
}
</style>
<script>
- let theme = null;
- try {
- theme = localStorage.getItem('color-theme');
- } catch (e) {
- /* Web Storage denied by browser policy: the shell falls back to the system theme. */
- }
- const loadingContainerStyle = document.createElement('style');
- let backgroundColor;
+ (function () {
+ let theme = null;
+ try {
+ theme = localStorage.getItem('color-theme');
+ } catch (e) {
+ /* Web Storage denied by browser policy: the shell falls back to the system theme. */
+ }
+ const loadingContainerStyle = document.createElement('style');
+ let dark;
+ let contrast;
- if (theme === 'high-contrast-dark') {
- backgroundColor = '#000000';
- } else if (theme === 'high-contrast-light') {
- backgroundColor = '#ffffff';
- } else if (theme === 'dark') {
- backgroundColor = '#0d0d0d';
- } else if (theme === 'light') {
- backgroundColor = '#ffffff';
- } else {
- /* `system`, and anything unset or unrecognised, which ThemeProvider also
- * resolves as `system`. The OS decides the scheme and the contrast, and
- * a contrast request moves the dark canvas to pure black, so keying off
- * the scheme alone would flash #0d0d0d behind the black palette.
- * The three contrast queries mirror ThemeProvider's `CONTRAST_QUERIES`:
- * a Windows Contrast Theme reports `forced-colors: active` with
- * `prefers-contrast: custom`, never `more`. */
- const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
- const prefersMoreContrast = [
- '(prefers-contrast: more)',
- '(prefers-contrast: custom)',
- '(forced-colors: active)',
- ].some(function (query) {
- return window.matchMedia(query).matches;
- });
- backgroundColor = prefersDarkScheme
- ? prefersMoreContrast
- ? '#000000'
- : '#0d0d0d'
- : '#ffffff';
- }
+ if (theme === 'high-contrast-dark' || theme === 'high-contrast-light') {
+ dark = theme === 'high-contrast-dark';
+ contrast = true;
+ } else if (theme === 'dark' || theme === 'light') {
+ dark = theme === 'dark';
+ contrast = false;
+ } else {
+ /* `system`, and anything unset or unrecognised, which ThemeProvider also
+ * resolves as `system`. The OS decides the scheme and the contrast, and
+ * a contrast request moves the dark canvas to pure black, so keying off
+ * the scheme alone would flash #0d0d0d behind the black palette.
+ * The three contrast queries mirror ThemeProvider's `CONTRAST_QUERIES`:
+ * a Windows Contrast Theme reports `forced-colors: active` with
+ * `prefers-contrast: custom`, never `more`. */
+ dark = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ contrast = [
+ '(prefers-contrast: more)',
+ '(prefers-contrast: custom)',
+ '(forced-colors: active)',
+ ].some(function (query) {
+ return window.matchMedia(query).matches;
+ });
+ }
+ let backgroundColor = dark ? (contrast ? '#000000' : '#0d0d0d') : '#ffffff';
+ const root = document.documentElement;
+ root.classList.add(dark ? 'dark' : 'light');
- loadingContainerStyle.innerHTML = `
- #loading-container {
- display: flex;
- align-items: center;
- justify-content: center;
- height: 100vh;
- background-color: ${backgroundColor};
+ /* The deployment theme (`interface.theme`) arrives with /api/config, so a
+ * signed-in reload replays the copy DeploymentTheme cached under
+ * `deployment-theme` (client/src/Providers/themeCache.ts) to paint it
+ * before the bundle runs. High contrast outranks it, as in ThemeProvider,
+ * which drops this copy (`data-theme-boot`) once it applies its own. */
+ const base = document.querySelector('base');
+ const basePath = base ? new URL(base.href).pathname : '/';
+ const path =
+ location.pathname.indexOf(basePath) === 0
+ ? location.pathname.slice(basePath.length)
+ : location.pathname.replace(/^\//, '');
+ /* Same list as `isPublicRoute`: auth pages and shared links never render
+ * under the viewer's signed-in config. */
+ const publicRoute =
+ /^(?:share|oauth|login|register|forgot-password|reset-password|verify)(?:\/|$)/i.test(
+ path,
+ );
+ if (!contrast && !publicRoute) {
+ try {
+ const cached = JSON.parse(localStorage.getItem('deployment-theme') || 'null');
+ const boot =
+ cached && cached.v === 1 && cached.modes && cached.modes[dark ? 'dark' : 'light'];
+ if (boot && Array.isArray(boot.properties)) {
+ let surface;
+ boot.properties.forEach(function (entry) {
+ if (typeof entry[0] === 'string' && entry[0].indexOf('--') === 0) {
+ root.style.setProperty(entry[0], String(entry[1]));
+ /* Only an `R G B` triple reaches the shell's stylesheet text; any
+ * whitespace between channels is accepted, as the theme validator does. */
+ const channels = String(entry[1]).trim().split(/\s+/);
+ if (
+ entry[0] === '--surface-primary-alt' &&
+ channels.length === 3 &&
+ channels.every(function (channel) {
+ return /^\d{1,3}$/.test(channel);
+ })
+ ) {
+ surface = channels.join(', ');
+ }
+ }
+ });
+ ['data-theme', 'data-theme-disabled', 'data-theme-field-focus'].forEach(
+ function (name) {
+ const value = boot.attributes && boot.attributes[name];
+ if (typeof value === 'string') {
+ root.setAttribute(name, value);
+ }
+ },
+ );
+ root.setAttribute('data-theme-boot', '');
+ if (surface) {
+ backgroundColor = 'rgb(' + surface + ')';
+ }
+ }
+ } catch (e) {
+ /* Denied or corrupt storage paints the stock shell, as before. */
+ }
}
- `;
- document.head.appendChild(loadingContainerStyle);
+
+ loadingContainerStyle.innerHTML = `
+ #loading-container {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100vh;
+ background-color: ${backgroundColor};
+ }
+ `;
+ document.head.appendChild(loadingContainerStyle);
+ })();
</script>
<script>
(function () {
diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsx
index 59d8ccea78..a7882babc9 100644
--- a/client/src/Providers/DeploymentTheme.tsx
+++ b/client/src/Providers/DeploymentTheme.tsx
@@ -8,8 +8,9 @@ import {
createContext,
useLayoutEffect,
} from 'react';
+import { useRecoilValue } from 'recoil';
import { notifyManager, useQueryClient } from '@tanstack/react-query';
-import { QueryKeys, isBundledThemeName } from 'librechat-data-provider';
+import { QueryKeys, MutationKeys, isBundledThemeName } from 'librechat-data-provider';
import {
ThemeProvider,
clickHouseTheme,
@@ -17,11 +18,26 @@ import {
fromLegacyTheme,
validateThemeDefinition,
} from '@librechat/client';
-import type { TInterfaceConfig, BundledThemeName } from 'librechat-data-provider';
+import type {
+ TInterfaceConfig,
+ BundledThemeName,
+ TRefreshTokenResponse,
+} from 'librechat-data-provider';
import type { IThemeRGB, ThemeDefinition } from '@librechat/client';
import type { ComponentProps } from 'react';
+import {
+ themeOwner,
+ appBasePath,
+ isPublicRoute,
+ readThemeCache,
+ clearThemeCache,
+ buildThemeCache,
+ writeThemeCache,
+ reconcileThemeCache,
+} from './themeCache';
import { getThemeFromEnv } from '~/utils/getThemeFromEnv';
import { useGetStartupConfig } from '~/data-provider';
+import store from '~/store';
type DeploymentThemeValue = TInterfaceConfig['theme'];
@@ -125,6 +141,70 @@ function useRebindOnStartupConfigRebuild() {
);
}
+/**
+ * The cached deployment theme, as last read or written. Losing the signed-in user drops
+ * it, whichever way the session ended (logout, an empty silent refresh, a failed user
+ * query, account deletion), so the next person on this browser does not get the
+ * previous identity's theme painted before their own config answers.
+ */
+function useThemeCache(owner?: string) {
+ const queryClient = useQueryClient();
+ const [cached, setCached] = useState(() =>
+ isPublicRoute(window.location.pathname, appBasePath()) ? undefined : readThemeCache(),
+ );
+ const signedIn = useRef(owner);
+ useEffect(() => {
+ if (signedIn.current && !owner) {
+ clearThemeCache();
+ setCached(undefined);
+ }
+ signedIn.current = owner;
+ }, [owner]);
+ /**
+ * The session also ends where no user was ever set, or before it is cleared: a silent
+ * refresh that fails or returns no token, a failed user query, and a logout, which goes
+ * as soon as it starts because an identity-provider logout unloads the page first. An
+ * account deletion only counts once it succeeds.
+ */
+ useEffect(() => {
+ const drop = () => {
+ clearThemeCache();
+ setCached(undefined);
+ };
+ const unsubscribeMutations = queryClient.getMutationCache().subscribe((event) => {
+ const key = event?.mutation?.options.mutationKey?.[0];
+ if (event?.type === 'added' && key === MutationKeys.logoutUser) {
+ return drop();
+ }
+ if (event?.type !== 'updated') {
+ return;
+ }
+ const { status, data } = event.mutation.state;
+ const tokenless = status === 'success' && !(data as TRefreshTokenResponse | undefined)?.token;
+ if (
+ (key === MutationKeys.deleteUser && status === 'success') ||
+ (key === MutationKeys.refreshToken && (status === 'error' || tokenless))
+ ) {
+ drop();
+ }
+ });
+ const unsubscribeQueries = queryClient.getQueryCache().subscribe((event) => {
+ if (
+ event?.type === 'updated' &&
+ event.query.queryKey[0] === QueryKeys.user &&
+ event.query.state.status === 'error'
+ ) {
+ drop();
+ }
+ });
+ return () => {
+ unsubscribeMutations();
+ unsubscribeQueries();
+ };
+ }, [queryClient]);
+ return [cached, setCached] as const;
+}
+
/** A route's own deployment theme source; `undefined` defers to the startup config. */
type ThemeOverride = { theme: DeploymentThemeValue } | undefined;
@@ -155,16 +235,49 @@ export function useDeploymentThemeOverride(ready: boolean, theme: DeploymentThem
* 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.
+ * deployment theme is never persisted to the user's theme keys, so the stored theme
+ * survives its removal; a separate cache (`./themeCache`) paints it before the
+ * config answers on a reload.
*/
export default function DeploymentTheme({ children }: { children: React.ReactNode }) {
const envTheme = useMemo(() => getThemeFromEnv(), []);
useRebindOnStartupConfigRebuild();
- const { data: startupConfig } = useGetStartupConfig({ keepPreviousData: true });
+ const { data: startupConfig, isPreviousData } = useGetStartupConfig({ keepPreviousData: true });
+ const owner = themeOwner(useRecoilValue(store.user));
+ const [cached, setCached] = useThemeCache(owner);
const [override, setOverride] = useState<ThemeOverride>(undefined);
- const configTheme = override ? override.theme : startupConfig?.interface?.theme;
+ /** A route override is another tenant's theme: it neither reads nor writes the cache. */
+ const decision = override
+ ? { theme: override.theme, cache: 'keep' as const }
+ : reconcileThemeCache({
+ cached,
+ owner,
+ answer: startupConfig && {
+ theme: startupConfig.interface?.theme,
+ current: !isPreviousData,
+ },
+ });
+ const configTheme = decision.theme;
const themeDefinition = useMemo(() => resolveDeploymentTheme(configTheme), [configTheme]);
+ /** Storage is an external system, so the cache follows the decision after the commit. */
+ const cacheAction = decision.cache;
+ useEffect(() => {
+ if (cacheAction === 'keep') {
+ return;
+ }
+ if (cacheAction === 'write' && owner && configTheme != null && themeDefinition) {
+ const entry = buildThemeCache(owner, configTheme, themeDefinition);
+ writeThemeCache(entry);
+ setCached(entry);
+ return;
+ }
+ clearThemeCache();
+ setCached((entry) =>
+ cacheAction === 'disown' && entry ? { ...entry, disowned: true } : undefined,
+ );
+ }, [cacheAction, owner, configTheme, themeDefinition, setCached]);
+
/**
* 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
diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
index c1eaca0879..60257f4280 100644
--- a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
+++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx
@@ -1,12 +1,15 @@
import { useState } from 'react';
-import { RecoilRoot } from 'recoil';
-import { useTheme } from '@librechat/client';
+import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { useTheme, clickHouseTheme } 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 { QueryKeys, MutationKeys, dataService } from 'librechat-data-provider';
+import type { TStartupConfig, TUser } from 'librechat-data-provider';
+import type { ThemeDefinition } from '@librechat/client';
+import { buildThemeCache, writeThemeCache, THEME_CACHE_KEY } from '../themeCache';
import DeploymentTheme, { useDeploymentThemeOverride } from '../DeploymentTheme';
import { useGetStartupConfig } from '~/data-provider';
+import store from '~/store';
const mockGetThemeFromEnv = jest.fn();
@@ -86,9 +89,9 @@ function SharedThemeSource({ theme }: { theme: ConfigTheme }) {
return null;
}
-function renderTheme(queryClient: QueryClient) {
+function renderTheme(queryClient: QueryClient, user?: Pick<TUser, 'id' | 'tenantId'>) {
return render(
- <RecoilRoot>
+ <RecoilRoot initializeState={({ set }) => user && set(store.user, user as TUser)}>
<QueryClientProvider client={queryClient}>
<DeploymentTheme>
<LateRoute />
@@ -384,3 +387,243 @@ describe('DeploymentTheme', () => {
expect(snapshotStorage()).toEqual(before);
});
});
+
+describe('DeploymentTheme cache', () => {
+ const user = { id: 'user-1', tenantId: 'tenant-a' };
+ let queryClient: QueryClient;
+ let getStartupConfig: jest.SpyInstance;
+ let warn: jest.SpyInstance;
+
+ const cacheTheme = (owner = 'tenant-a:user-1', theme: ConfigTheme = 'clickhouse') => {
+ const definition = theme === 'clickhouse' ? clickHouseTheme : (theme as ThemeDefinition);
+ writeThemeCache(buildThemeCache(owner, theme as NonNullable<ConfigTheme>, definition));
+ };
+ const cachedEntry = () => JSON.parse(localStorage.getItem(THEME_CACHE_KEY) ?? 'null');
+ const pending = () => getStartupConfig.mockReturnValue(new Promise(() => undefined));
+
+ beforeEach(() => {
+ localStorage.clear();
+ 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();
+ });
+
+ it('paints the cached theme in the first commit, before the config answers', () => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient);
+
+ expect(root().dataset.theme).toBe('clickhouse');
+ expect(localStorage.getItem('theme-definition')).toBeNull();
+ });
+
+ it('does not seed the cache on a shared link, which paints its own tenant', () => {
+ cacheTheme();
+ pending();
+ window.history.pushState({}, '', '/share/abc');
+ renderTheme(queryClient);
+ window.history.pushState({}, '', '/');
+
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('caches the theme served to the signed-in identity', async () => {
+ getStartupConfig.mockResolvedValue(configWith(inlineTheme));
+ renderTheme(queryClient, user);
+
+ await waitFor(() => expect(cachedEntry()?.source).toEqual(inlineTheme));
+ expect(cachedEntry().owner).toBe('tenant-a:user-1');
+ expect(cachedEntry().modes.light.properties).toContainEqual(['--surface-primary', '10 20 30']);
+ expect(localStorage.getItem('theme-definition')).toBeNull();
+ });
+
+ it('lets a changed deployment theme win over the cache', async () => {
+ cacheTheme();
+ getStartupConfig.mockResolvedValue(configWith(inlineTheme));
+ renderTheme(queryClient, user);
+
+ await waitFor(() => expect(root().dataset.theme).toBe('acme'));
+ await waitFor(() => expect(cachedEntry()?.source).toEqual(inlineTheme));
+ });
+
+ it('lets a removed deployment theme win and clears the cache', async () => {
+ cacheTheme();
+ getStartupConfig.mockResolvedValue(configWith());
+ renderTheme(queryClient, user);
+
+ await waitFor(() => expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull());
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('clears the cache when the served theme is invalid', async () => {
+ cacheTheme();
+ getStartupConfig.mockResolvedValue(configWith('not-a-theme' as ConfigTheme));
+ renderTheme(queryClient, user);
+
+ await waitFor(() => expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull());
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('never paints a theme cached for another tenant', async () => {
+ cacheTheme('tenant-b:user-1');
+ pending();
+ renderTheme(queryClient, user);
+
+ expect(root().dataset.theme).toBeUndefined();
+ await waitFor(() => expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull());
+ });
+
+ it('paints no previous answer after a cache from another tenant until its own answer', async () => {
+ cacheTheme('tenant-b:user-1');
+ let signIn: () => void = () => undefined;
+ function SignIn() {
+ const setUser = useSetRecoilState(store.user);
+ signIn = () => setUser(user as TUser);
+ return null;
+ }
+ getStartupConfig.mockResolvedValueOnce(configWith('clickhouse'));
+ render(
+ <RecoilRoot>
+ <QueryClientProvider client={queryClient}>
+ <DeploymentTheme>
+ <SignIn />
+ </DeploymentTheme>
+ </QueryClientProvider>
+ </RecoilRoot>,
+ );
+ await waitFor(() => expect(root().dataset.theme).toBe('clickhouse'));
+
+ let answer: (config: TStartupConfig) => void = () => undefined;
+ getStartupConfig.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ act(() => signIn());
+ await waitFor(() => expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull());
+ expect(root().dataset.theme).toBeUndefined();
+
+ await act(async () => answer(configWith(inlineTheme)));
+ await waitFor(() => expect(root().dataset.theme).toBe('acme'));
+ });
+
+ it('does not write a signed-out answer over the cache', async () => {
+ cacheTheme();
+ getStartupConfig.mockResolvedValue(configWith());
+ renderTheme(queryClient);
+
+ await waitFor(() => expect(getStartupConfig).toHaveBeenCalled());
+ await waitFor(() => expect(root().dataset.theme).toBeUndefined());
+ expect(cachedEntry()?.source).toBe('clickhouse');
+ });
+
+ it('neither reads nor writes the cache for a route override', async () => {
+ getStartupConfig.mockResolvedValue(configWith('clickhouse'));
+ renderTheme(queryClient, user);
+ await waitFor(() => expect(cachedEntry()?.source).toBe('clickhouse'));
+
+ act(() => showSharedRoute(inlineTheme));
+ await waitFor(() => expect(root().dataset.theme).toBe('acme'));
+ expect(cachedEntry()?.source).toBe('clickhouse');
+ });
+
+ it('clears the cache whenever the signed-in user goes away', async () => {
+ cacheTheme();
+ pending();
+ let signOut: () => void = () => undefined;
+ function SignOut() {
+ const setUser = useSetRecoilState(store.user);
+ signOut = () => setUser(undefined);
+ return null;
+ }
+ render(
+ <RecoilRoot initializeState={({ set }) => set(store.user, user as TUser)}>
+ <QueryClientProvider client={queryClient}>
+ <DeploymentTheme>
+ <SignOut />
+ </DeploymentTheme>
+ </QueryClientProvider>
+ </RecoilRoot>,
+ );
+ expect(cachedEntry()?.source).toBe('clickhouse');
+
+ act(() => signOut());
+ await waitFor(() => expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull());
+ expect(root().dataset.theme).toBeUndefined();
+ });
+
+ it('clears the cache as soon as a logout starts, before any identity-provider redirect', () => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient, user);
+
+ act(() => {
+ void queryClient
+ .getMutationCache()
+ .build(queryClient, {
+ mutationKey: [MutationKeys.logoutUser],
+ mutationFn: () => new Promise(() => undefined),
+ })
+ .execute();
+ });
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ const runMutation = (key: string, mutationFn: () => Promise<unknown>) =>
+ act(async () => {
+ await queryClient
+ .getMutationCache()
+ .build(queryClient, { mutationKey: [key], mutationFn })
+ .execute()
+ .catch(() => undefined);
+ });
+
+ it('keeps the cache when an account deletion fails, and drops it when one succeeds', async () => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient, user);
+
+ await runMutation(MutationKeys.deleteUser, () => Promise.reject(new Error('bad 2FA code')));
+ expect(cachedEntry()?.source).toBe('clickhouse');
+
+ await runMutation(MutationKeys.deleteUser, () => Promise.resolve({}));
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ it.each([
+ ['fails', () => Promise.reject(new Error('expired'))],
+ ['returns no token', () => Promise.resolve(undefined)],
+ ])('clears the cache when the silent refresh %s before any user is set', async (_, refresh) => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient);
+
+ await runMutation(MutationKeys.refreshToken, refresh);
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ it('keeps the cache when the silent refresh restores a session', async () => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient);
+
+ await runMutation(MutationKeys.refreshToken, () => Promise.resolve({ token: 't', user }));
+ expect(cachedEntry()?.source).toBe('clickhouse');
+ });
+
+ it('clears the cache when the user query fails', async () => {
+ cacheTheme();
+ pending();
+ renderTheme(queryClient);
+
+ await act(() =>
+ queryClient
+ .fetchQuery([QueryKeys.user], () => Promise.reject(new Error('401')))
+ .catch(() => undefined),
+ );
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+});
diff --git a/client/src/Providers/__tests__/bootScript.spec.tsx b/client/src/Providers/__tests__/bootScript.spec.tsx
new file mode 100644
index 0000000000..31a738ce1c
--- /dev/null
+++ b/client/src/Providers/__tests__/bootScript.spec.tsx
@@ -0,0 +1,197 @@
+import { resolve } from 'path';
+import { readFileSync } from 'fs';
+import { render } from '@testing-library/react';
+import { ThemeProvider, applyResolvedTheme, resolveTheme } from '@librechat/client';
+import type { ThemeDefinition } from '@librechat/client';
+import { isPublicRoute, buildThemeCache, writeThemeCache } from '../themeCache';
+
+/** The inline shell script in `client/index.html`, run as the browser runs it. */
+const bootScript = (() => {
+ const html = readFileSync(resolve(__dirname, '../../../index.html'), 'utf8');
+ const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((match) => match[1]);
+ const script = scripts.find((source) => source.includes('deployment-theme'));
+ if (!script) {
+ throw new Error('client/index.html has no deployment theme boot script');
+ }
+ return script;
+})();
+
+const acme: ThemeDefinition = {
+ version: 1,
+ name: 'acme',
+ modes: {
+ light: {
+ colors: { 'rgb-surface-primary': '240 244 255', 'rgb-surface-primary-alt': '230 234 250' },
+ appearance: { controlRadius: '2px', disabledStyle: 'fill' },
+ },
+ dark: {
+ colors: { 'rgb-surface-primary': '12 16 32', 'rgb-surface-primary-alt': '8 10 24' },
+ appearance: { controlRadius: '2px', fieldFocusStyle: 'border' },
+ },
+ },
+};
+
+const root = () => document.documentElement;
+
+function mockMedia(dark: boolean) {
+ window.matchMedia = jest.fn().mockImplementation((query: string) => ({
+ matches: dark && query === '(prefers-color-scheme: dark)',
+ media: query,
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ }));
+}
+
+function boot() {
+ new Function(bootScript)();
+}
+
+/** What `applyResolvedTheme` writes for `mode`, read off a detached element. */
+function appliedStyle(mode: 'light' | 'dark') {
+ const element = document.createElement('div');
+ applyResolvedTheme(resolveTheme(acme, mode), element);
+ return element;
+}
+
+describe('index.html deployment theme boot script', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ root().removeAttribute('style');
+ root().removeAttribute('class');
+ [...root().attributes].forEach(({ name }) => {
+ if (name.startsWith('data-')) {
+ root().removeAttribute(name);
+ }
+ });
+ document.head.querySelectorAll('style, base').forEach((element) => element.remove());
+ const base = document.createElement('base');
+ base.href = '/';
+ document.head.append(base);
+ mockMedia(false);
+ window.history.pushState({}, '', '/c/new');
+ writeThemeCache(buildThemeCache('tenant-a:user-1', 'acme', acme));
+ });
+
+ it.each(['light', 'dark'] as const)(
+ 'paints the cached %s theme exactly as the provider would, before the bundle',
+ (mode) => {
+ localStorage.setItem('color-theme', mode);
+ boot();
+
+ const expected = appliedStyle(mode);
+ expect(root().getAttribute('style')).toBe(expected.getAttribute('style'));
+ expect(root().dataset.theme).toBe('acme');
+ expect(root().getAttribute('data-theme-disabled')).toBe(
+ expected.getAttribute('data-theme-disabled'),
+ );
+ expect(root().getAttribute('data-theme-field-focus')).toBe(
+ expected.getAttribute('data-theme-field-focus'),
+ );
+ expect(root().hasAttribute('data-theme-boot')).toBe(true);
+ expect(root().classList.contains(mode)).toBe(true);
+ const surface = acme.modes[mode]?.colors?.['rgb-surface-primary-alt'];
+ expect(document.head.textContent).toContain(
+ `background-color: rgb(${surface?.split(' ').join(', ')})`,
+ );
+ },
+ );
+
+ it('follows the OS scheme under `system`', () => {
+ mockMedia(true);
+ boot();
+ expect(root().style.getPropertyValue('--surface-primary')).toBe('12 16 32');
+ expect(root().classList.contains('dark')).toBe(true);
+ });
+
+ it('leaves the shell alone under high contrast, which outranks the deployment theme', () => {
+ localStorage.setItem('color-theme', 'high-contrast-dark');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(document.head.textContent).toContain('background-color: #000000');
+ });
+
+ it.each(['/login', '/register', '/share/abc', '/Share/abc', '/reset-password', '/oauth/success'])(
+ 'does not replay the cache on %s, which never renders the signed-in config',
+ (path) => {
+ window.history.pushState({}, '', path);
+ localStorage.setItem('color-theme', 'dark');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(isPublicRoute(path)).toBe(true);
+ },
+ );
+
+ it('replays the cache on app routes', () => {
+ for (const path of ['/c/new', '/c/login-notes', '/agents', '/']) {
+ window.history.pushState({}, '', path);
+ expect(isPublicRoute(path)).toBe(false);
+ }
+ window.history.pushState({}, '', '/c/new');
+ boot();
+ expect(root().dataset.theme).toBe('acme');
+ });
+
+ it('keeps a cached surface that is not an RGB triple out of the shell stylesheet', () => {
+ localStorage.setItem('color-theme', 'dark');
+ const entry = buildThemeCache('tenant-a:user-1', 'acme', acme);
+ entry.modes.dark.properties = entry.modes.dark.properties.map(([name, value]) =>
+ name === '--surface-primary-alt' ? [name, '0 0 0;}</style><b>x'] : [name, value],
+ );
+ writeThemeCache(entry);
+ boot();
+ expect(document.head.textContent).toContain('background-color: #0d0d0d');
+ expect(document.head.textContent).not.toContain('</style>');
+ });
+
+ it('accepts any whitespace between the cached surface channels', () => {
+ localStorage.setItem('color-theme', 'dark');
+ const entry = buildThemeCache('tenant-a:user-1', 'acme', acme);
+ entry.modes.dark.properties = entry.modes.dark.properties.map(([name, value]) =>
+ name === '--surface-primary-alt' ? [name, ' 8 10\t24 '] : [name, value],
+ );
+ writeThemeCache(entry);
+ boot();
+ expect(document.head.textContent).toContain('background-color: rgb(8, 10, 24)');
+ });
+
+ it('paints the stock shell for a corrupt entry', () => {
+ localStorage.setItem('color-theme', 'dark');
+ localStorage.setItem('deployment-theme', '{not json');
+ boot();
+ expect(root().getAttribute('style')).toBeNull();
+ expect(document.head.textContent).toContain('background-color: #0d0d0d');
+ });
+
+ it('is dropped by the provider, so a withdrawn theme restores the stylesheet, not the copy', () => {
+ localStorage.setItem('color-theme', 'light');
+ boot();
+
+ const { rerender, unmount } = render(
+ <ThemeProvider themeDefinition={acme} persistThemeDefinition={false}>
+ {null}
+ </ThemeProvider>,
+ );
+ expect(root().hasAttribute('data-theme-boot')).toBe(false);
+ expect(root().style.getPropertyValue('--surface-primary')).toBe('240 244 255');
+
+ rerender(<ThemeProvider persistThemeDefinition={false}>{null}</ThemeProvider>);
+ expect(root().style.getPropertyValue('--surface-primary')).toBe('');
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(root().hasAttribute('data-theme-disabled')).toBe(false);
+ unmount();
+ });
+
+ it('is dropped when the provider starts without a theme', () => {
+ localStorage.setItem('color-theme', 'dark');
+ boot();
+
+ const { unmount } = render(<ThemeProvider>{null}</ThemeProvider>);
+ expect(root().getAttribute('style') ?? '').toBe('');
+ expect(root().hasAttribute('data-theme')).toBe(false);
+ expect(root().hasAttribute('data-theme-boot')).toBe(false);
+ expect(root().classList.contains('dark')).toBe(true);
+ unmount();
+ });
+});
diff --git a/client/src/Providers/__tests__/themeCache.spec.ts b/client/src/Providers/__tests__/themeCache.spec.ts
new file mode 100644
index 0000000000..e06258b002
--- /dev/null
+++ b/client/src/Providers/__tests__/themeCache.spec.ts
@@ -0,0 +1,136 @@
+import { clickHouseTheme } from '@librechat/client';
+import type { ThemeCacheEntry } from '../themeCache';
+import {
+ themeOwner,
+ isPublicRoute,
+ readThemeCache,
+ buildThemeCache,
+ clearThemeCache,
+ writeThemeCache,
+ THEME_CACHE_KEY,
+ reconcileThemeCache,
+} from '../themeCache';
+
+const OWNER = 'tenant-a:user-1';
+const cached: ThemeCacheEntry = buildThemeCache(OWNER, 'clickhouse', clickHouseTheme);
+
+describe('reconcileThemeCache', () => {
+ it('paints the cached theme before any config answers', () => {
+ expect(reconcileThemeCache({ cached })).toEqual({ theme: 'clickhouse', cache: 'keep' });
+ expect(reconcileThemeCache({ cached, owner: OWNER })).toEqual({
+ theme: 'clickhouse',
+ cache: 'keep',
+ });
+ });
+
+ it('prefers the cache over a previous answer served to another identity', () => {
+ expect(
+ reconcileThemeCache({ cached, owner: OWNER, answer: { theme: undefined, current: false } }),
+ ).toEqual({ theme: 'clickhouse', cache: 'keep' });
+ });
+
+ it('lets a changed theme served to the signed-in identity win and rewrite the cache', () => {
+ expect(
+ reconcileThemeCache({ cached, owner: OWNER, answer: { theme: 'librechat', current: true } }),
+ ).toEqual({ theme: 'librechat', cache: 'write' });
+ });
+
+ it('lets a removed theme win and clears the cache', () => {
+ expect(
+ reconcileThemeCache({ cached, owner: OWNER, answer: { theme: undefined, current: true } }),
+ ).toEqual({ theme: undefined, cache: 'clear' });
+ });
+
+ it('never paints or keeps a theme cached for another tenant or user', () => {
+ const otherTenant = reconcileThemeCache({ cached, owner: 'tenant-b:user-1' });
+ expect(otherTenant).toEqual({ theme: undefined, cache: 'disown' });
+
+ const otherUser = reconcileThemeCache({
+ cached,
+ owner: 'tenant-a:user-2',
+ answer: { theme: 'librechat', current: false },
+ });
+ expect(otherUser).toEqual({ theme: undefined, cache: 'disown' });
+ });
+
+ it('never paints a disowned entry, even once the identity is unknown again', () => {
+ const disowned = { ...cached, disowned: true as const };
+ expect(reconcileThemeCache({ cached: disowned })).toEqual({ theme: undefined, cache: 'keep' });
+ expect(
+ reconcileThemeCache({
+ cached: disowned,
+ owner: OWNER,
+ answer: { theme: 'librechat', current: true },
+ }),
+ ).toEqual({ theme: 'librechat', cache: 'write' });
+ });
+
+ it('applies a signed-out answer without writing or clearing the cache', () => {
+ expect(reconcileThemeCache({ cached, answer: { theme: undefined, current: true } })).toEqual({
+ theme: undefined,
+ cache: 'keep',
+ });
+ });
+
+ it('keeps the uncached behavior when nothing is cached', () => {
+ expect(reconcileThemeCache({})).toEqual({ theme: undefined, cache: 'keep' });
+ expect(
+ reconcileThemeCache({ owner: OWNER, answer: { theme: 'clickhouse', current: false } }),
+ ).toEqual({ theme: 'clickhouse', cache: 'keep' });
+ });
+});
+
+describe('theme cache storage', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('matches public routes case-insensitively, as the router does', () => {
+ expect(isPublicRoute('/Share/abc')).toBe(true);
+ expect(isPublicRoute('/LOGIN')).toBe(true);
+ });
+
+ it('recognizes public routes under a subdirectory base path', () => {
+ expect(isPublicRoute('/chat/login', '/chat/')).toBe(true);
+ expect(isPublicRoute('/chat/share/abc', '/chat/')).toBe(true);
+ expect(isPublicRoute('/chat/c/new', '/chat/')).toBe(false);
+ });
+
+ it('stamps the owner from the tenant and user id', () => {
+ expect(themeOwner({ id: 'user-1', tenantId: 'tenant-a' })).toBe(OWNER);
+ expect(themeOwner({ id: 'user-1' })).toBe(':user-1');
+ expect(themeOwner(undefined)).toBeUndefined();
+ });
+
+ it('stores both modes of the resolved theme for the boot script', () => {
+ expect(cached.modes.light.attributes['data-theme']).toBe('clickhouse');
+ expect(cached.modes.dark.properties).toContainEqual([
+ '--surface-primary',
+ clickHouseTheme.modes.dark?.colors?.['rgb-surface-primary'],
+ ]);
+ });
+
+ it('round-trips an entry and clears it', () => {
+ writeThemeCache(cached);
+ expect(readThemeCache()).toEqual(cached);
+ clearThemeCache();
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ it('removes the superseded entry when a replacement cannot be stored', () => {
+ writeThemeCache(cached);
+ const setItem = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new DOMException('full', 'QuotaExceededError');
+ });
+ writeThemeCache(buildThemeCache(OWNER, 'librechat', clickHouseTheme));
+ setItem.mockRestore();
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+
+ it('drops a corrupt or older entry instead of painting it', () => {
+ localStorage.setItem(THEME_CACHE_KEY, '{not json');
+ expect(readThemeCache()).toBeUndefined();
+
+ localStorage.setItem(THEME_CACHE_KEY, JSON.stringify({ ...cached, v: 0 }));
+ expect(readThemeCache()).toBeUndefined();
+ expect(localStorage.getItem(THEME_CACHE_KEY)).toBeNull();
+ });
+});
diff --git a/client/src/Providers/themeCache.ts b/client/src/Providers/themeCache.ts
new file mode 100644
index 0000000000..308cacc0ce
--- /dev/null
+++ b/client/src/Providers/themeCache.ts
@@ -0,0 +1,164 @@
+import { resolveTheme, describeResolvedTheme } from '@librechat/client';
+import type { ResolvedThemeStyle, ThemeDefinition } from '@librechat/client';
+import type { TInterfaceConfig, TUser } from 'librechat-data-provider';
+
+type DeploymentThemeValue = TInterfaceConfig['theme'];
+
+/**
+ * The last deployment theme a signed-in identity was served, kept apart from the
+ * user's own theme keys. The boot script in `client/index.html` reads this key and
+ * replays `modes` before the bundle runs, so its key and shape must stay in step.
+ */
+export const THEME_CACHE_KEY = 'deployment-theme';
+export const THEME_CACHE_VERSION = 1;
+
+export type ThemeCacheEntry = {
+ v: typeof THEME_CACHE_VERSION;
+ /** `tenantId:userId` of the identity the theme was served to. */
+ owner: string;
+ /** The raw `interface.theme`, which the app resolves itself until the config answers. */
+ source: NonNullable<DeploymentThemeValue>;
+ modes: { light: ResolvedThemeStyle; dark: ResolvedThemeStyle };
+ /** In memory only: an identity mismatch proved this entry is someone else's. */
+ disowned?: true;
+};
+
+/**
+ * `disown` removes the stored entry and marks the one in memory, so the identity mismatch
+ * it proves keeps holding, even once the identity is unknown again, until a current
+ * answer arrives.
+ */
+export type ThemeCacheAction = 'keep' | 'clear' | 'disown' | 'write';
+
+/** A config answer; `current` is false while `keepPreviousData` shows another identity's answer. */
+export type ThemeAnswer = { theme: DeploymentThemeValue; current: boolean };
+
+/**
+ * Routes that render without the viewer's signed-in config: the auth pages, and shared
+ * links, which paint their own tenant's theme. Neither the boot script nor the first
+ * commit replays the cache there; `client/index.html` keeps the same list.
+ */
+const PUBLIC_ROUTE =
+ /^(?:share|oauth|login|register|forgot-password|reset-password|verify)(?:\/|$)/i;
+
+/** The `<base href>` path, which a subdirectory deployment moves off `/`. */
+export function appBasePath(): string {
+ const base = document.querySelector('base');
+ return base ? new URL(base.href).pathname : '/';
+}
+
+/** `pathname` relative to the app's base path. */
+export function isPublicRoute(pathname: string, basePath = '/'): boolean {
+ const path = pathname.startsWith(basePath)
+ ? pathname.slice(basePath.length)
+ : pathname.replace(/^\//, '');
+ return PUBLIC_ROUTE.test(path);
+}
+
+export const themeOwner = (user?: Pick<TUser, 'id' | 'tenantId'>): string | undefined =>
+ user?.id ? `${user.tenantId ?? ''}:${user.id}` : undefined;
+
+const isStyle = (value: unknown): value is ResolvedThemeStyle =>
+ typeof value === 'object' &&
+ value !== null &&
+ Array.isArray((value as ResolvedThemeStyle).properties) &&
+ typeof (value as ResolvedThemeStyle).attributes === 'object';
+
+/** A corrupt or older entry reads as absent and is removed, so it is never painted again. */
+export function readThemeCache(): ThemeCacheEntry | undefined {
+ try {
+ const raw = localStorage.getItem(THEME_CACHE_KEY);
+ if (!raw) {
+ return undefined;
+ }
+ const entry = JSON.parse(raw) as Partial<ThemeCacheEntry> | null;
+ if (
+ entry?.v === THEME_CACHE_VERSION &&
+ typeof entry.owner === 'string' &&
+ entry.source != null &&
+ isStyle(entry.modes?.light) &&
+ isStyle(entry.modes?.dark)
+ ) {
+ return entry as ThemeCacheEntry;
+ }
+ localStorage.removeItem(THEME_CACHE_KEY);
+ } catch {
+ // Storage is an optional adapter: denied or corrupt storage paints no cached theme.
+ }
+ return undefined;
+}
+
+export function clearThemeCache(): void {
+ try {
+ localStorage.removeItem(THEME_CACHE_KEY);
+ } catch {
+ // Nothing to remove when storage is unavailable.
+ }
+}
+
+export function buildThemeCache(
+ owner: string,
+ source: NonNullable<DeploymentThemeValue>,
+ definition: ThemeDefinition,
+): ThemeCacheEntry {
+ return {
+ v: THEME_CACHE_VERSION,
+ owner,
+ source,
+ modes: {
+ light: describeResolvedTheme(resolveTheme(definition, 'light')),
+ dark: describeResolvedTheme(resolveTheme(definition, 'dark')),
+ },
+ };
+}
+
+/** Writes only when the entry changed, so a reload that is served the same theme costs a read. */
+export function writeThemeCache(entry: ThemeCacheEntry): void {
+ try {
+ const raw = JSON.stringify(entry);
+ if (localStorage.getItem(THEME_CACHE_KEY) !== raw) {
+ localStorage.setItem(THEME_CACHE_KEY, raw);
+ }
+ } catch {
+ /** A full storage must not keep the superseded entry for the next reload to paint;
+ * without one, that reload only loses its pre-paint theme. */
+ clearThemeCache();
+ }
+}
+
+/**
+ * Which deployment theme paints, and what happens to the cache:
+ * - an answer served to the current identity wins; a signed-in one rewrites the
+ * cache (a removed theme clears it), a signed-out one never touches it;
+ * - with no current answer, the cache stands in, unless the signed-in identity is
+ * known and is not the one it was served to: then nothing paints until that
+ * identity's own answer arrives, since a previous answer may be the other one's;
+ * - otherwise the previous answer, if any, keeps painting as before.
+ * A theme that turns out invalid is cleared by the caller, which resolves it.
+ */
+export function reconcileThemeCache({
+ cached,
+ owner,
+ answer,
+}: {
+ cached?: ThemeCacheEntry;
+ owner?: string;
+ answer?: ThemeAnswer;
+}): { theme: DeploymentThemeValue; cache: ThemeCacheAction } {
+ if (answer?.current) {
+ if (!owner) {
+ return { theme: answer.theme, cache: 'keep' };
+ }
+ return { theme: answer.theme, cache: answer.theme == null ? 'clear' : 'write' };
+ }
+ if (cached?.disowned) {
+ return { theme: undefined, cache: 'keep' };
+ }
+ if (cached && owner !== undefined && cached.owner !== owner) {
+ return { theme: undefined, cache: 'disown' };
+ }
+ if (cached) {
+ return { theme: cached.source, cache: 'keep' };
+ }
+ return { theme: answer?.theme, cache: 'keep' };
+}
diff --git a/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts b/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
new file mode 100644
index 0000000000..e7a1d2b0af
--- /dev/null
+++ b/e2e/specs/mock/scenarios/deployment-theme-first-paint.spec.ts
@@ -0,0 +1,200 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
+import { resolveTheme } from '../../../../packages/client/src/theme/registry';
+
+/**
+ * `interface.theme` exists only in the `/api/config` answer, so before this
+ * change a signed-in reload painted the chat in the default palette until that
+ * answer arrived. The reload now replays the last served deployment theme from
+ * the inline boot script in `client/index.html` and from `DeploymentTheme`'s
+ * cache, so every frame before the answer already wears it.
+ *
+ * The reload runs throttled (400 ms latency, 1.5 Mbps, 4x CPU) and the config
+ * answer is held back further, so frames of both the loading shell and the
+ * rendered app (the chat layout paints before the config answers; the composer
+ * waits for it) land before it. Every frame is sampled in a
+ * `requestAnimationFrame` callback, which runs before the frame paints.
+ */
+
+type Mode = 'light' | 'dark';
+
+type Frame = {
+ at: number;
+ theme: string | null;
+ surface: string;
+ shell: string | null;
+ /** The bundle has replaced the loading shell with the app. */
+ app: boolean;
+};
+
+declare global {
+ interface Window {
+ __themeFrames?: Frame[];
+ }
+}
+
+const CONFIG_HOLD_MS = 1500;
+const CACHE_KEY = 'deployment-theme';
+
+/**
+ * Serves `theme` as `interface.theme` (`null` removes it), holding the answer while
+ * `held()`. Returns when each signed-in answer was sent: that answer is the one
+ * carrying the signed-in theme, so the frames before it are the ones under test.
+ */
+async function serveTheme(page: Page, theme: () => string | null, held: () => boolean) {
+ const answeredAt: number[] = [];
+ await page.route(
+ (url) => url.pathname === '/api/config',
+ async (route) => {
+ const response = await route.fetch();
+ const body = await response.json();
+ const served = { ...body.interface };
+ delete served.theme;
+ const value = theme();
+ if (value !== null) {
+ served.theme = value;
+ }
+ if (held()) {
+ await new Promise((resolve) => setTimeout(resolve, CONFIG_HOLD_MS));
+ }
+ if (route.request().headers()['authorization']) {
+ answeredAt.push(Date.now());
+ }
+ await route.fulfill({ response, json: { ...body, interface: served } });
+ },
+ );
+ return answeredAt;
+}
+
+/** Records every frame from the first one the document can paint. */
+async function sampleFrames(page: Page) {
+ await page.addInitScript(() => {
+ window.__themeFrames = [];
+ const sample = () => {
+ if (document.body) {
+ const root = document.documentElement;
+ const shell = document.getElementById('loading-container');
+ window.__themeFrames?.push({
+ at: performance.timeOrigin + performance.now(),
+ theme: root.getAttribute('data-theme'),
+ surface: getComputedStyle(root).getPropertyValue('--surface-primary').trim(),
+ shell: shell ? getComputedStyle(shell).backgroundColor : null,
+ app: !shell && (document.getElementById('root')?.childElementCount ?? 0) > 0,
+ });
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+}
+
+async function throttle(page: Page) {
+ const session = await page.context().newCDPSession(page);
+ await session.send('Network.enable');
+ await session.send('Network.emulateNetworkConditions', {
+ offline: false,
+ latency: 400,
+ downloadThroughput: (1.5 * 1024 * 1024) / 8,
+ uploadThroughput: (750 * 1024) / 8,
+ });
+ await session.send('Emulation.setCPUThrottlingRate', { rate: 4 });
+}
+
+async function openChat(page: Page) {
+ await page.goto('/c/new');
+ await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 30000 });
+}
+
+const rgb = (channels?: string) => `rgb(${(channels ?? '').split(' ').join(', ')})`;
+
+/** Reloads throttled with the config held, and checks every frame before the answer. */
+async function expectFirstPaint(page: Page, mode: Mode) {
+ let held = false;
+ const answeredAt = await serveTheme(
+ page,
+ () => 'clickhouse',
+ () => held,
+ );
+ const { colors } = resolveTheme(clickHouseTheme, mode);
+
+ await openChat(page);
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect
+ .poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY))
+ .not.toBeNull();
+
+ await sampleFrames(page);
+ await throttle(page);
+ held = true;
+ const reloadedAt = Date.now();
+ await page.reload();
+ await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 60000 });
+ await expect.poll(() => answeredAt.some((at) => at > reloadedAt)).toBe(true);
+
+ const answered = Math.min(...answeredAt.filter((at) => at > reloadedAt));
+ const frames = (await page.evaluate(() => window.__themeFrames ?? [])).filter(
+ (frame) => frame.at < answered,
+ );
+
+ /** Frames of both surfaces landed before the answer, so both were tested. */
+ expect(frames.length).toBeGreaterThan(0);
+ expect(frames[0].shell).not.toBeNull();
+ expect(frames.some((frame) => frame.app)).toBe(true);
+
+ for (const frame of frames) {
+ expect(frame.theme).toBe('clickhouse');
+ expect(frame.surface).toBe(colors['rgb-surface-primary']);
+ if (frame.shell !== null) {
+ expect(frame.shell).toBe(rgb(colors['rgb-surface-primary-alt']));
+ }
+ }
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect(page.locator('html')).not.toHaveAttribute('data-theme-boot');
+}
+
+test.describe('deployment theme first paint (light)', () => {
+ test.use({ colorScheme: 'light', viewport: { width: 1280, height: 800 } });
+
+ test('a signed-in reload paints the cached deployment theme from the first frame in light @scenario:deployment-theme-first-paint-light', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstPaint(page, 'light');
+ });
+});
+
+test.describe('deployment theme first paint (dark)', () => {
+ test.use({ colorScheme: 'dark', viewport: { width: 1280, height: 800 } });
+
+ test('a signed-in reload paints the cached deployment theme from the first frame in dark @scenario:deployment-theme-first-paint-dark', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ await expectFirstPaint(page, 'dark');
+ });
+});
+
+test('a deployment theme removed since the last visit wins once the config answers @scenario:deployment-theme-removed-wins-over-cache', async ({
+ page,
+}) => {
+ test.setTimeout(90000);
+ let theme: string | null = 'clickhouse';
+ await serveTheme(
+ page,
+ () => theme,
+ () => false,
+ );
+
+ await openChat(page);
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect
+ .poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY))
+ .not.toBeNull();
+
+ theme = null;
+ await page.reload();
+ await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 30000 });
+ await expect(page.locator('html')).not.toHaveAttribute('data-theme', 'clickhouse');
+ await expect.poll(() => page.evaluate((key) => localStorage.getItem(key), CACHE_KEY)).toBeNull();
+});
diff --git a/packages/client/src/theme/context/ThemeProvider.tsx b/packages/client/src/theme/context/ThemeProvider.tsx
index 7804942060..18ccef1c4f 100644
--- a/packages/client/src/theme/context/ThemeProvider.tsx
+++ b/packages/client/src/theme/context/ThemeProvider.tsx
@@ -12,7 +12,9 @@ import { JSX } from 'react/jsx-runtime';
import type { IThemeRGB, ThemeDefinition, ThemeMode } from '../types';
import applyTheme, {
applyResolvedTheme,
+ clearAppliedTheme,
themeOwnedProperties,
+ THEME_BOOT_ATTRIBUTE,
THEME_DISABLED_ATTRIBUTE,
THEME_FIELD_FOCUS_ATTRIBUTE,
} from '../utils/applyTheme';
@@ -731,6 +733,12 @@ export function ThemeProvider({
setResolvedMode(mode);
setHighContrast(highContrast);
+ /** The boot script's pre-paint copy is not the host's own state: drop it before the
+ * snapshot below, in the same pre-paint pass that applies the provider's theme. */
+ if (root.hasAttribute(THEME_BOOT_ATTRIBUTE)) {
+ clearAppliedTheme(root);
+ }
+
if (!themeClassSnapshot.current) {
themeClassSnapshot.current = {
dark: root.classList.contains('dark'),
diff --git a/packages/client/src/theme/index.ts b/packages/client/src/theme/index.ts
index d302676eec..d230f875cd 100644
--- a/packages/client/src/theme/index.ts
+++ b/packages/client/src/theme/index.ts
@@ -16,8 +16,11 @@ export {
default as applyTheme,
applyResolvedTheme,
clearAppliedTheme,
+ describeResolvedTheme,
themeOwnedProperties,
+ THEME_BOOT_ATTRIBUTE,
} from './utils/applyTheme';
+export type { ResolvedThemeStyle } from './utils/applyTheme';
export {
HIGH_CONTRAST_THEME_NAME,
diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts
index 335e9afabf..c293f21def 100644
--- a/packages/client/src/theme/utils/applyTheme.ts
+++ b/packages/client/src/theme/utils/applyTheme.ts
@@ -187,38 +187,56 @@ export const THEME_SCOPE_ATTRIBUTE = 'data-theme-scope';
*/
export const THEME_FIELD_FOCUS_ATTRIBUTE = 'data-theme-field-focus';
+/**
+ * Marks a root that `client/index.html` painted from the cached deployment theme before the
+ * bundle ran. The provider drops that copy before it snapshots the root, so a later restore
+ * returns to the stylesheet rather than to a theme the server may since have withdrawn.
+ */
+export const THEME_BOOT_ATTRIBUTE = 'data-theme-boot';
+
export function clearAppliedTheme(root: HTMLElement = document.documentElement): void {
themeOwnedProperties.forEach((property) => root.style.removeProperty(property));
root.removeAttribute('data-theme');
root.removeAttribute(THEME_DISABLED_ATTRIBUTE);
root.removeAttribute(THEME_SCOPE_ATTRIBUTE);
root.removeAttribute(THEME_FIELD_FOCUS_ATTRIBUTE);
+ root.removeAttribute(THEME_BOOT_ATTRIBUTE);
+}
+
+/** What `applyResolvedTheme` writes on the root, as plain data a boot script can replay. */
+export type ResolvedThemeStyle = {
+ properties: Array<[string, string]>;
+ attributes: Record<string, string>;
+};
+
+export function describeResolvedTheme(theme: ResolvedThemeDefinition): ResolvedThemeStyle {
+ return {
+ properties: [
+ ...mapColors(theme.colors),
+ ...mapAppearance(theme.appearance),
+ ...themeBrandTokens.map(
+ (token) => [brandProperty(token), theme.brands[token]] as [string, string],
+ ),
+ ],
+ attributes: {
+ 'data-theme': theme.name,
+ ...(theme.appearance.disabledStyle === 'fill' && { [THEME_DISABLED_ATTRIBUTE]: 'fill' }),
+ ...(theme.appearance.fieldFocusStyle === 'border' && {
+ [THEME_FIELD_FOCUS_ATTRIBUTE]: 'border',
+ }),
+ },
+ };
}
export function applyResolvedTheme(
theme: ResolvedThemeDefinition,
root: HTMLElement = document.documentElement,
): void {
- const variables = [
- ...mapColors(theme.colors),
- ...mapAppearance(theme.appearance),
- ...themeBrandTokens.map(
- (token) => [brandProperty(token), theme.brands[token]] as [string, string],
- ),
- ];
-
- variables.forEach(([property, value]) => root.style.setProperty(property, value));
- root.dataset.theme = theme.name;
- if (theme.appearance.disabledStyle === 'fill') {
- root.setAttribute(THEME_DISABLED_ATTRIBUTE, 'fill');
- } else {
- root.removeAttribute(THEME_DISABLED_ATTRIBUTE);
- }
- if (theme.appearance.fieldFocusStyle === 'border') {
- root.setAttribute(THEME_FIELD_FOCUS_ATTRIBUTE, 'border');
- } else {
- root.removeAttribute(THEME_FIELD_FOCUS_ATTRIBUTE);
- }
+ const { properties, attributes } = describeResolvedTheme(theme);
+ properties.forEach(([property, value]) => root.style.setProperty(property, value));
+ root.removeAttribute(THEME_DISABLED_ATTRIBUTE);
+ root.removeAttribute(THEME_FIELD_FOCUS_ATTRIBUTE);
+ Object.entries(attributes).forEach(([name, value]) => root.setAttribute(name, value));
}
/**