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

🌗 feat: Hand the Colour Mode Over on an Entry Link (#17056)

Marco Berettae216f082895b
diff --git a/api/server/experimental.js b/api/server/experimental.js
index 00d9c6c83e..b17cd2e350 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -38,6 +38,7 @@ const {
loadToolApprovalHooks,
maybeInjectQueryDevtoolsBootstrap,
injectConfiguredFooterBootstrap,
+ injectColorModeHandoff,
preAuthTenantMiddleware,
requestContextMiddleware,
configureServerTimeouts,
@@ -544,6 +545,8 @@ if (cluster.isMaster) {
customFooter: process.env.CUSTOM_FOOTER,
});
+ indexHTML = injectColorModeHandoff(indexHTML, baseAppConfig?.interfaceConfig?.colorModeFromUrl);
+
const cspPolicy = createCspPolicy();
const shellCache = shellCacheHeaders(cspPolicy != null);
diff --git a/api/server/index.js b/api/server/index.js
index 1a97a81d01..fe1e723e4e 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -45,6 +45,7 @@ const {
loadToolApprovalHooks,
maybeInjectQueryDevtoolsBootstrap,
injectConfiguredFooterBootstrap,
+ injectColorModeHandoff,
preAuthTenantMiddleware,
requestContextMiddleware,
registerShutdownTask,
@@ -302,6 +303,8 @@ const startServer = async () => {
customFooter: process.env.CUSTOM_FOOTER,
});
+ indexHTML = injectColorModeHandoff(indexHTML, appConfig.interfaceConfig?.colorModeFromUrl);
+
const cspPolicy = createCspPolicy();
const shellCache = shellCacheHeaders(cspPolicy != null);
diff --git a/client/index.html b/client/index.html
index 35f40da433..a6eb922b13 100644
--- a/client/index.html
+++ b/client/index.html
@@ -53,6 +53,32 @@
} catch (e) {
/* Web Storage denied by browser policy: the shell falls back to the system theme. */
}
+ /* `interface.colorModeFromUrl` marks the shell (packages/api/src/html/handoff.ts)
+ * so a link from another app can hand over its colour mode as `?theme=`. It is
+ * stored as the user's own choice, which a later in-app change replaces, and
+ * leaves the address before the router reads it. A high-contrast choice of the
+ * same scheme is kept, since the link asks for a scheme, not less contrast. */
+ if (document.documentElement.hasAttribute('data-color-mode-from-url')) {
+ const params = new URLSearchParams(location.search);
+ const handoff = params.get('theme');
+ if (handoff === 'dark' || handoff === 'light' || handoff === 'system') {
+ if (theme !== 'high-contrast-' + handoff) {
+ theme = handoff;
+ try {
+ localStorage.setItem('color-theme', handoff);
+ } catch (e) {
+ /* Unstored, the handed-over mode still paints this page. */
+ }
+ }
+ params.delete('theme');
+ const query = params.toString();
+ history.replaceState(
+ history.state,
+ '',
+ location.pathname + (query ? '?' + query : '') + location.hash,
+ );
+ }
+ }
const loadingContainerStyle = document.createElement('style');
let dark;
let contrast;
diff --git a/client/src/Providers/__tests__/handoff.spec.tsx b/client/src/Providers/__tests__/handoff.spec.tsx
new file mode 100644
index 0000000000..b5dcbac522
--- /dev/null
+++ b/client/src/Providers/__tests__/handoff.spec.tsx
@@ -0,0 +1,159 @@
+import { resolve } from 'path';
+import { readFileSync } from 'fs';
+import { act, render } from '@testing-library/react';
+import { ThemeProvider, useTheme } from '@librechat/client';
+import { injectThemeCacheVersion } from '../bootVersion';
+
+/** The inline shell script in `client/index.html` that paints the colour mode. */
+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('data-color-mode-from-url'));
+ if (!script) {
+ throw new Error('client/index.html has no colour-mode handoff in its boot script');
+ }
+ return injectThemeCacheVersion(script);
+})();
+
+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(url: string, enabled = true) {
+ window.history.replaceState({ key: 'entry' }, '', url);
+ if (enabled) {
+ root().setAttribute('data-color-mode-from-url', '');
+ }
+ new Function(bootScript)();
+}
+
+const address = () => `${location.pathname}${location.search}${location.hash}`;
+const painted = () => (root().classList.contains('dark') ? 'dark' : 'light');
+
+describe('index.html colour-mode handoff', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ root().removeAttribute('class');
+ root().removeAttribute('style');
+ [...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);
+ });
+
+ it.each([
+ ['dark', 'light'],
+ ['light', 'dark'],
+ ] as const)('paints and stores ?theme=%s over a stored %s mode', (mode, stored) => {
+ localStorage.setItem('color-theme', stored);
+ boot(`/c/new?theme=${mode}`);
+
+ expect(painted()).toBe(mode);
+ expect(localStorage.getItem('color-theme')).toBe(mode);
+ expect(address()).toBe('/c/new');
+ });
+
+ it('applies the handoff on a fresh profile and keeps the history entry state', () => {
+ boot('/c/new?theme=dark');
+
+ expect(painted()).toBe('dark');
+ expect(localStorage.getItem('color-theme')).toBe('dark');
+ expect(window.history.state).toEqual({ key: 'entry' });
+ });
+
+ it('hands `system` back to the OS scheme', () => {
+ localStorage.setItem('color-theme', 'light');
+ mockMedia(true);
+ boot('/c/new?theme=system');
+
+ expect(painted()).toBe('dark');
+ expect(localStorage.getItem('color-theme')).toBe('system');
+ });
+
+ it('removes only its own parameter, keeping the rest of the link', () => {
+ boot('/c/new?prompt=hello&theme=dark&submit=true#composer');
+
+ expect(address()).toBe('/c/new?prompt=hello&submit=true#composer');
+ });
+
+ it.each(['Dark', 'high-contrast-dark', 'blue', '', 'dark%20', '%3Cscript%3E'])(
+ 'ignores the unsupported value %p',
+ (value) => {
+ localStorage.setItem('color-theme', 'light');
+ boot(`/c/new?theme=${value}`);
+
+ expect(painted()).toBe('light');
+ expect(localStorage.getItem('color-theme')).toBe('light');
+ expect(location.search).toBe(`?theme=${value}`);
+ },
+ );
+
+ it('ignores the parameter when the deployment has not enabled the handoff', () => {
+ localStorage.setItem('color-theme', 'light');
+ boot('/c/new?theme=dark', false);
+
+ expect(painted()).toBe('light');
+ expect(localStorage.getItem('color-theme')).toBe('light');
+ expect(location.search).toBe('?theme=dark');
+ });
+
+ it('keeps a high-contrast choice of the requested scheme', () => {
+ localStorage.setItem('color-theme', 'high-contrast-dark');
+ boot('/c/new?theme=dark');
+
+ expect(painted()).toBe('dark');
+ expect(localStorage.getItem('color-theme')).toBe('high-contrast-dark');
+ expect(document.head.textContent).toContain('background-color: #000000');
+ expect(address()).toBe('/c/new');
+ });
+
+ it('still paints the handed-over mode when storage refuses the write', () => {
+ const setItem = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('denied');
+ });
+ boot('/c/new?theme=dark');
+ setItem.mockRestore();
+
+ expect(painted()).toBe('dark');
+ expect(address()).toBe('/c/new');
+ });
+
+ it('starts the app in the handed-over mode, and a later in-app choice wins', () => {
+ let setTheme: (theme: string) => void = () => undefined;
+ function Selector() {
+ setTheme = useTheme().setTheme;
+ return null;
+ }
+
+ boot('/c/new?theme=dark');
+ const { unmount } = render(
+ <ThemeProvider>
+ <Selector />
+ </ThemeProvider>,
+ );
+
+ expect(painted()).toBe('dark');
+ expect(localStorage.getItem('color-theme')).toBe('dark');
+
+ act(() => setTheme('light'));
+ unmount();
+ root().removeAttribute('class');
+ boot('/c/new');
+
+ expect(localStorage.getItem('color-theme')).toBe('light');
+ expect(painted()).toBe('light');
+ });
+});
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index 625d89d0a7..e31c765ead 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -17,6 +17,9 @@ interface:
# control in the composer. Mock Provider A resolves Anthropic's adaptive
# `effort` setting through its custom endpoint configuration below.
parameters: true
+ # Opts the shell into the `?theme=` colour-mode handoff (off by default).
+ # color-mode-handoff.spec.ts follows links that carry it.
+ colorModeFromUrl: true
# Grants MULTI_CONVO.USE so the composer's `+` command opens the added-model
# popover. agent-skills-added.spec.ts drives that flow; without an explicit
# value the permission falls through to the seeded role default and
diff --git a/e2e/specs/mock/scenarios/color-mode-handoff.spec.ts b/e2e/specs/mock/scenarios/color-mode-handoff.spec.ts
new file mode 100644
index 0000000000..711862a85c
--- /dev/null
+++ b/e2e/specs/mock/scenarios/color-mode-handoff.spec.ts
@@ -0,0 +1,159 @@
+import { expect, test } from '@playwright/test';
+import type { Browser, BrowserContext, Page } from '@playwright/test';
+
+/**
+ * Another app links into this one with its colour mode on the URL
+ * (`interface.colorModeFromUrl`, enabled in e2e/config/librechat.e2e.yaml). The
+ * shell paints that mode before the first frame, keeps it as the user's own
+ * choice and drops the parameter from the address.
+ */
+
+type Mode = 'dark' | 'light';
+
+declare global {
+ interface Window {
+ /** The scheme on `<html>` after every class change since the document started. */
+ __modeSamples?: string[];
+ }
+}
+
+const opposite = (mode: Mode): Mode => (mode === 'dark' ? 'light' : 'dark');
+
+/** A context signed in as the e2e user, with nothing remembered in its storage. */
+async function freshProfile(browser: Browser, context: BrowserContext) {
+ const { cookies } = await context.storageState();
+ return browser.newContext({ storageState: { cookies, origins: [] } });
+}
+
+/** Records every scheme `<html>` carries, served with the HTML ahead of the boot script. */
+async function recordModes(page: Page) {
+ await page.route('**/*', async (route) => {
+ if (route.request().resourceType() !== 'document') {
+ return route.fallback();
+ }
+ const response = await route.fetch();
+ const recorder = `<script>
+ window.__modeSamples = [];
+ new MutationObserver(function () {
+ var list = document.documentElement.classList;
+ window.__modeSamples.push(list.contains('dark') ? 'dark' : list.contains('light') ? 'light' : 'none');
+ }).observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
+</script>`;
+ const body = (await response.text()).replace('<head>', `<head>${recorder}`);
+ await route.fulfill({ response, body });
+ });
+}
+
+async function expectSettled(page: Page, mode: Mode) {
+ await expect(page.getByTestId('composer-surface')).toBeVisible({ timeout: 30000 });
+ const samples = await page.evaluate(() => window.__modeSamples ?? []);
+ expect(samples.length).toBeGreaterThan(0);
+ expect(samples).not.toContain(opposite(mode));
+ expect(samples).not.toContain('none');
+ await expect(page.locator('html')).toHaveClass(new RegExp(`\\b${mode}\\b`));
+}
+
+const storedMode = (page: Page) => page.evaluate(() => localStorage.getItem('color-theme'));
+
+/** Follows `?theme=<mode>` from a profile with nothing stored and an OS asking for the other scheme. */
+async function landsFresh(browser: Browser, context: BrowserContext, mode: Mode) {
+ const profile = await freshProfile(browser, context);
+ const page = await profile.newPage();
+ await page.emulateMedia({ colorScheme: opposite(mode) });
+ await recordModes(page);
+ try {
+ await page.goto(`/c/new?theme=${mode}`);
+ await expectSettled(page, mode);
+ expect(
+ await page.evaluate(() => document.documentElement.hasAttribute('data-color-mode-from-url')),
+ ).toBe(true);
+ expect(new URL(page.url()).searchParams.has('theme')).toBe(false);
+ expect(await storedMode(page)).toBe(mode);
+ await page.screenshot({ path: test.info().outputPath(`handoff-${mode}.png`) });
+
+ await page.reload();
+ await expectSettled(page, mode);
+ expect(await storedMode(page)).toBe(mode);
+ } finally {
+ await profile.close();
+ }
+}
+
+/** Follows `?theme=<mode>` from a profile that stored the other mode. */
+async function replacesStored(browser: Browser, context: BrowserContext, mode: Mode) {
+ const profile = await freshProfile(browser, context);
+ const page = await profile.newPage();
+ await recordModes(page);
+ try {
+ await page.goto('/c/new');
+ await page.evaluate((stored) => localStorage.setItem('color-theme', stored), opposite(mode));
+ await page.goto('/c/new');
+ await expectSettled(page, opposite(mode));
+
+ await page.goto(`/c/new?theme=${mode}`);
+ await expectSettled(page, mode);
+ expect(new URL(page.url()).searchParams.has('theme')).toBe(false);
+ expect(await storedMode(page)).toBe(mode);
+
+ await page.reload();
+ await expectSettled(page, mode);
+ } finally {
+ await profile.close();
+ }
+}
+
+test.describe('colour-mode handoff', () => {
+ test('a fresh profile lands in ?theme=dark and keeps it @scenario:color-mode-handoff-fresh-dark', async ({
+ browser,
+ context,
+ }) => {
+ test.setTimeout(90000);
+ await landsFresh(browser, context, 'dark');
+ });
+
+ test('a fresh profile lands in ?theme=light and keeps it @scenario:color-mode-handoff-fresh-light', async ({
+ browser,
+ context,
+ }) => {
+ test.setTimeout(90000);
+ await landsFresh(browser, context, 'light');
+ });
+
+ test('?theme=dark replaces a stored light mode without a flash @scenario:color-mode-handoff-over-stored-dark', async ({
+ browser,
+ context,
+ }) => {
+ test.setTimeout(90000);
+ await replacesStored(browser, context, 'dark');
+ });
+
+ test('?theme=light replaces a stored dark mode without a flash @scenario:color-mode-handoff-over-stored-light', async ({
+ browser,
+ context,
+ }) => {
+ test.setTimeout(90000);
+ await replacesStored(browser, context, 'light');
+ });
+
+ test('an unsupported value is ignored @scenario:color-mode-handoff-ignores-invalid', async ({
+ browser,
+ context,
+ }) => {
+ test.setTimeout(90000);
+ const profile = await freshProfile(browser, context);
+ const page = await profile.newPage();
+ await recordModes(page);
+ try {
+ await page.goto('/c/new');
+ await page.evaluate(() => localStorage.setItem('color-theme', 'light'));
+
+ for (const value of ['purple', 'DARK', 'high-contrast-dark']) {
+ await page.goto(`/c/new?theme=${value}`);
+ await expectSettled(page, 'light');
+ expect(await storedMode(page)).toBe('light');
+ }
+ } finally {
+ await profile.close();
+ }
+ });
+});
diff --git a/packages/api/src/html/handoff.spec.ts b/packages/api/src/html/handoff.spec.ts
new file mode 100644
index 0000000000..0c44077ee4
--- /dev/null
+++ b/packages/api/src/html/handoff.spec.ts
@@ -0,0 +1,33 @@
+import { COLOR_MODE_FROM_URL_ATTRIBUTE, injectColorModeHandoff } from './handoff';
+
+const SHELL =
+ '<!DOCTYPE html><html lang="en-US"><head><title>LibreChat</title>' +
+ `<script>if (document.documentElement.hasAttribute('${COLOR_MODE_FROM_URL_ATTRIBUTE}')) {}</script>` +
+ '</head><body><div id="root"></div></body></html>';
+
+describe('injectColorModeHandoff', () => {
+ it('marks the root element when the deployment enables the handoff', () => {
+ const html = injectColorModeHandoff(SHELL, true);
+
+ expect(html).toContain(`<html ${COLOR_MODE_FROM_URL_ATTRIBUTE} lang="en-US">`);
+ });
+
+ it('leaves the shell untouched when the handoff is off or unset', () => {
+ expect(injectColorModeHandoff(SHELL, false)).toBe(SHELL);
+ expect(injectColorModeHandoff(SHELL, undefined)).toBe(SHELL);
+ expect(injectColorModeHandoff(SHELL, null)).toBe(SHELL);
+ });
+
+ it('marks the shell once when served through the injector twice', () => {
+ const html = injectColorModeHandoff(injectColorModeHandoff(SHELL, true), true);
+
+ expect(html.split(COLOR_MODE_FROM_URL_ATTRIBUTE)).toHaveLength(3);
+ expect(html).toContain(`<html ${COLOR_MODE_FROM_URL_ATTRIBUTE} lang="en-US">`);
+ });
+
+ it('keeps the per-request language rewrite matching the marked tag', () => {
+ const html = injectColorModeHandoff(SHELL, true).replace(/lang="en-US"/g, 'lang="de"');
+
+ expect(html).toContain(`<html ${COLOR_MODE_FROM_URL_ATTRIBUTE} lang="de">`);
+ });
+});
diff --git a/packages/api/src/html/handoff.ts b/packages/api/src/html/handoff.ts
new file mode 100644
index 0000000000..53edca4faf
--- /dev/null
+++ b/packages/api/src/html/handoff.ts
@@ -0,0 +1,23 @@
+/** Marks the shell for the boot script in `client/index.html`, which reads `?theme=`. */
+export const COLOR_MODE_FROM_URL_ATTRIBUTE = 'data-color-mode-from-url';
+
+/**
+ * Opts the HTML shell into the colour-mode handoff (`interface.colorModeFromUrl`).
+ *
+ * The boot script paints the colour mode before any app script or bootstrap
+ * global exists, so the answer rides on the `<html>` element it already reads.
+ * Like the footer answer, it is the deployment's base configuration: the shell
+ * is served before there is a caller whose overrides could be resolved.
+ */
+export const injectColorModeHandoff = (html: string, enabled?: boolean | null): string => {
+ if (enabled !== true) {
+ return html;
+ }
+
+ /* Only the tag is inspected: the boot script names the attribute it reads. */
+ return html.replace(/<html\b[^>]*>/i, (tag) =>
+ tag.includes(COLOR_MODE_FROM_URL_ATTRIBUTE)
+ ? tag
+ : `<html ${COLOR_MODE_FROM_URL_ATTRIBUTE}${tag.slice('<html'.length)}`,
+ );
+};
diff --git a/packages/api/src/html/index.ts b/packages/api/src/html/index.ts
index 78f2438dda..c13fd0ddf7 100644
--- a/packages/api/src/html/index.ts
+++ b/packages/api/src/html/index.ts
@@ -1,3 +1,4 @@
export * from './bootstrap';
export * from './devtools';
export * from './footer';
+export * from './handoff';
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index d7575d9ca6..e965a0a80c 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -2838,6 +2838,8 @@ export const interfaceSchema = z
temporaryChatRetention: z.number().min(1).max(8760).optional(),
generalChatRetention: z.number().min(1).max(8760).optional(),
autoSubmitFromUrl: z.boolean().optional(),
+ /** Accept `?theme=dark|light|system` on an entry link as the user's colour mode, so another app can hand its mode over. */
+ colorModeFromUrl: z.boolean().optional(),
retentionMode: z.nativeEnum(RetentionMode).default(RetentionMode.TEMPORARY),
retainAgentFiles: z.boolean().optional(),
runCode: z.boolean().optional(),
@@ -3068,6 +3070,7 @@ export const interfaceSchema = z
},
temporaryChat: true,
autoSubmitFromUrl: true,
+ colorModeFromUrl: false,
runCode: true,
webSearch: true,
contextUsage: true,
diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.ts
index a4dc10e8fb..55f77476a6 100644
--- a/packages/data-schemas/src/app/interface.spec.ts
+++ b/packages/data-schemas/src/app/interface.spec.ts
@@ -169,6 +169,20 @@ describe('loadDefaultInterface', () => {
expect(interfaceConfig?.autoSubmitFromUrl).toBe(false);
});
+ it('keeps the colour-mode URL handoff off unless configured', async () => {
+ const unset = await loadDefaultInterface({
+ config: {},
+ configDefaults: getConfigDefaults(),
+ });
+ const enabled = await loadDefaultInterface({
+ config: { interface: { colorModeFromUrl: true } },
+ configDefaults: getConfigDefaults(),
+ });
+
+ expect(unset?.colorModeFromUrl).toBe(false);
+ expect(enabled?.colorModeFromUrl).toBe(true);
+ });
+
it('preserves a disabled build info flag', async () => {
const config: Partial<TCustomConfig> = {
interface: {
diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.ts
index 370144a58f..a323b92794 100644
--- a/packages/data-schemas/src/app/interface.ts
+++ b/packages/data-schemas/src/app/interface.ts
@@ -43,6 +43,7 @@ export async function loadDefaultInterface({
mcpServers: interfaceConfig?.mcpServers ?? defaults.mcpServers,
customWelcome: interfaceConfig?.customWelcome ?? defaults.customWelcome,
autoSubmitFromUrl: interfaceConfig?.autoSubmitFromUrl ?? defaults.autoSubmitFromUrl,
+ colorModeFromUrl: interfaceConfig?.colorModeFromUrl ?? defaults.colorModeFromUrl,
buildInfo: interfaceConfig?.buildInfo ?? defaults.buildInfo,
mascot: interfaceConfig?.mascot ?? defaults.mascot,
contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage,