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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
♿ feat: High Contrast Light and Dark Appearance Modes (#15178)
Marco Beretta8144574b43b8
diff --git a/client/index.html b/client/index.htmlindex 7ea758aacc..bb05828ff7 100644--- a/client/index.html+++ b/client/index.html@@ -32,15 +32,35 @@const loadingContainerStyle = document.createElement('style');let backgroundColor;- if (theme === 'dark') {+ 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 if (theme === 'system') {- const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)').matches;- backgroundColor = prefersDarkScheme ? '#0d0d0d' : '#ffffff';} else {- backgroundColor = '#ffffff';+ /* `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';}loadingContainerStyle.innerHTML = `diff --git a/client/src/__tests__/loadingCanvas.spec.ts b/client/src/__tests__/loadingCanvas.spec.tsnew file mode 100644index 0000000000..9d7369e6ad--- /dev/null+++ b/client/src/__tests__/loadingCanvas.spec.ts@@ -0,0 +1,76 @@+import { join } from 'node:path';+import { readFileSync } from 'node:fs';++/** The pre-React canvas is painted by an inline bootstrap in `index.html`, which+ * no bundle imports, so the only way to hold it to the resolved palette is to+ * run the script the document actually ships. */+const bootstrap = (() => {+ const html = readFileSync(join(__dirname, '..', '..', 'index.html'), 'utf8');+ const script = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]+ .map(([, body]) => body)+ .find((body) => body.includes('#loading-container'));++ if (!script) {+ throw new Error('index.html no longer carries a #loading-container bootstrap');+ }++ return script;+})();++const canvasFor = (stored: string | null, matching: string[]): string | undefined => {+ window.localStorage.clear();+ if (stored !== null) {+ window.localStorage.setItem('color-theme', stored);+ }+ window.matchMedia = ((query: string) =>+ ({ matches: matching.includes(query) }) as MediaQueryList) as typeof window.matchMedia;+ document.head.querySelectorAll('style').forEach((node) => node.remove());++ new Function(bootstrap)();++ return document.head+ .querySelector('style')+ ?.innerHTML.match(/background-color:\s*([^;\s]+)/)?.[1];+};++const DARK_SCHEME = '(prefers-color-scheme: dark)';+const MORE_CONTRAST = '(prefers-contrast: more)';+const CUSTOM_CONTRAST = '(prefers-contrast: custom)';+const FORCED_COLORS = '(forced-colors: active)';++describe('loading canvas', () => {+ it.each([+ ['high-contrast-dark', [], '#000000'],+ ['high-contrast-light', [], '#ffffff'],+ ['dark', [], '#0d0d0d'],+ ['light', [], '#ffffff'],+ ])('paints the stored %s mode', (stored, matching, expected) => {+ expect(canvasFor(stored, matching as string[])).toBe(expected);+ });++ /** The mismatch this guards: `system` plus `prefers-contrast: more` resolves to+ * the pure-black palette, so the standard-dark canvas would flash behind it+ * for the whole application load. */+ it('follows both OS preferences under system', () => {+ expect(canvasFor('system', [DARK_SCHEME, MORE_CONTRAST])).toBe('#000000');+ expect(canvasFor('system', [DARK_SCHEME])).toBe('#0d0d0d');+ expect(canvasFor('system', [MORE_CONTRAST])).toBe('#ffffff');+ expect(canvasFor('system', [])).toBe('#ffffff');+ });++ /** A Windows Contrast Theme reports `forced-colors: active` with+ * `prefers-contrast: custom`, never `more`, so keying the canvas off `more`+ * alone flashes #0d0d0d on the platform the theme README names. */+ it('treats a forced-colors palette as a contrast request', () => {+ expect(canvasFor('system', [DARK_SCHEME, CUSTOM_CONTRAST, FORCED_COLORS])).toBe('#000000');+ expect(canvasFor('system', [DARK_SCHEME, FORCED_COLORS])).toBe('#000000');+ });++ /** An unset or unrecognised value is what `getInitialTheme` resolves as+ * `system`, so the canvas has to resolve it the same way. */+ it('treats an unset or unknown mode as system', () => {+ expect(canvasFor(null, [DARK_SCHEME])).toBe('#0d0d0d');+ expect(canvasFor(null, [DARK_SCHEME, MORE_CONTRAST])).toBe('#000000');+ expect(canvasFor('sepia', [DARK_SCHEME, MORE_CONTRAST])).toBe('#000000');+ });+});diff --git a/client/src/components/Appearance/Selectors.tsx b/client/src/components/Appearance/Selectors.tsxindex 2814c9daba..beea8cde86 100644--- a/client/src/components/Appearance/Selectors.tsx+++ b/client/src/components/Appearance/Selectors.tsx@@ -25,6 +25,8 @@ export const ThemeSelector = ({{ value: 'system', label: localize('com_nav_theme_system') },{ value: 'dark', label: localize('com_nav_theme_dark') },{ value: 'light', label: localize('com_nav_theme_light') },+ { value: 'high-contrast-light', label: localize('com_nav_theme_high_contrast_light') },+ { value: 'high-contrast-dark', label: localize('com_nav_theme_high_contrast_dark') },];const labelId = 'theme-selector-label';diff --git a/client/src/components/Appearance/ThemeSelector.spec.tsx b/client/src/components/Appearance/ThemeSelector.spec.tsxindex ebb54c6978..cb19f1d657 100644--- a/client/src/components/Appearance/ThemeSelector.spec.tsx+++ b/client/src/components/Appearance/ThemeSelector.spec.tsx@@ -1,7 +1,7 @@// ThemeSelector.spec.tsximport 'test/matchMedia.mock';import React from 'react';-import { render, waitFor } from '@testing-library/react';+import { fireEvent, render, waitFor } from '@testing-library/react';import { clickDropdown, flushDropdownEffects } from 'test/dropdown';import '@testing-library/jest-dom/extend-expect';import { RecoilRoot } from 'recoil';@@ -58,4 +58,41 @@ describe('ThemeSelector', () => {expect(mockOnChange).toHaveBeenCalledWith('dark');});});++ it('offers both high contrast options and reports the selected one', async () => {+ global.ResizeObserver = class MockedResizeObserver {+ observe = jest.fn();+ unobserve = jest.fn();+ disconnect = jest.fn();+ };+ const { getByText, getByTestId } = render(+ <RecoilRoot>+ <ThemeSelector theme="system" onChange={mockOnChange} />+ </RecoilRoot>,+ );++ fireEvent.click(getByTestId('theme-selector'));++ expect(getByText('High contrast light')).toBeInTheDocument();+ fireEvent.click(getByText('High contrast dark'));++ await waitFor(() => {+ expect(mockOnChange).toHaveBeenCalledWith('high-contrast-dark');+ });+ });++ it('shows the active high contrast mode as the current value', () => {+ global.ResizeObserver = class MockedResizeObserver {+ observe = jest.fn();+ unobserve = jest.fn();+ disconnect = jest.fn();+ };+ const { getByRole } = render(+ <RecoilRoot>+ <ThemeSelector theme="high-contrast-light" onChange={mockOnChange} />+ </RecoilRoot>,+ );++ expect(getByRole('combobox')).toHaveTextContent('High contrast light');+ });});diff --git a/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx b/client/src/components/Artifacts/ArtifactCodeEditor.test.tsxindex cfb6bce9cb..8b6588fcc6 100644--- a/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx+++ b/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx@@ -1,5 +1,8 @@import React from 'react';import { render, act } from '@testing-library/react';+import { ThemeContext, highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';+import type { Monaco } from '@monaco-editor/react';+import type { IThemeRGB } from '@librechat/client';import type { editor } from 'monaco-editor';import type { Artifact } from '~/common';import { ArtifactCodeEditor } from './ArtifactCodeEditor';@@ -17,7 +20,13 @@ interface MutationHandlers {onError?: (error?: unknown) => void;}-const mockEditorProps: { onChange?: (value: string | undefined) => void } = {};+interface MonacoEditorProps {+ onChange?: (value: string | undefined) => void;+ beforeMount?: (monaco: Monaco) => void;+ theme?: string;+}++const mockEditorProps: MonacoEditorProps = {};const mockMutationHandlers: MutationHandlers = {};// Calling mutate replays onMutate synchronously so currentUpdateRef reflects the@@ -28,8 +37,8 @@ const mockMutate = jest.fn((vars: MutationVars) => {jest.mock('@monaco-editor/react', () => ({__esModule: true,- default: (props: { onChange?: (value: string | undefined) => void }) => {- mockEditorProps.onChange = props.onChange;+ default: (props: MonacoEditorProps) => {+ Object.assign(mockEditorProps, props);return null;},}));@@ -81,12 +90,65 @@ const otherArtifact: Artifact = {type: 'text/plain',};-const renderEditor = (initial: Artifact = artifact) => {+type Appearance = {+ resolvedMode: 'light' | 'dark';+ highContrast: boolean;+};++const defaultAppearance: Appearance = { resolvedMode: 'light', highContrast: false };++const renderEditor = (initial: Artifact = artifact, initialAppearance = defaultAppearance) => {const monacoRef: React.MutableRefObject<editor.IStandaloneCodeEditor | null> = { current: null };- const utils = render(<ArtifactCodeEditor artifact={initial} monacoRef={monacoRef} />);- const rerenderWith = (next: Artifact) =>- utils.rerender(<ArtifactCodeEditor artifact={next} monacoRef={monacoRef} />);- return { ...utils, rerenderWith };+ let currentArtifact = initial;+ let currentAppearance = initialAppearance;+ const tree = () => (+ <ThemeContext.Provider+ value={+ {+ resolvedMode: currentAppearance.resolvedMode,+ highContrast: currentAppearance.highContrast,+ } as React.ContextType<typeof ThemeContext>+ }+ >+ <ArtifactCodeEditor artifact={currentArtifact} monacoRef={monacoRef} />+ </ThemeContext.Provider>+ );+ const utils = render(tree());+ const rerenderWith = (next: Artifact) => {+ currentArtifact = next;+ utils.rerender(tree());+ };+ const rerenderAppearance = (next: Appearance) => {+ currentAppearance = next;+ utils.rerender(tree());+ };+ return { ...utils, rerenderWith, rerenderAppearance };+};++const toHexColor = (palette: IThemeRGB, token: keyof IThemeRGB) =>+ `#${palette[token]+ ?.split(/\s+/)+ .map((channel) => Number(channel).toString(16).padStart(2, '0'))+ .join('')}`;++const createMonacoMock = () => {+ const defaults = {+ setDiagnosticsOptions: jest.fn(),+ setCompilerOptions: jest.fn(),+ };+ const defineTheme = jest.fn();+ const monaco = {+ editor: { defineTheme },+ languages: {+ typescript: {+ typescriptDefaults: defaults,+ javascriptDefaults: defaults,+ JsxEmit: { React: 1 },+ },+ },+ } as unknown as Monaco;++ return { monaco, defineTheme };};const fireEdit = (value: string) => {@@ -96,10 +158,12 @@ const fireEdit = (value: string) => {});};-describe('ArtifactCodeEditor retry guard', () => {+describe('ArtifactCodeEditor', () => {beforeEach(() => {jest.useFakeTimers();mockEditorProps.onChange = undefined;+ mockEditorProps.beforeMount = undefined;+ mockEditorProps.theme = undefined;mockMutationHandlers.onMutate = undefined;mockMutationHandlers.onSuccess = undefined;mockMutationHandlers.onError = undefined;@@ -110,6 +174,73 @@ describe('ArtifactCodeEditor retry guard', () => {jest.useRealTimers();});+ it('paints the loading canvas with the standard Monaco canvas outside high contrast', () => {+ const { container } = renderEditor();++ expect(mockEditorProps.theme).toBe('vs-dark');+ expect(container.firstElementChild).toHaveStyle({ backgroundColor: '#1e1e1e' });+ });++ it('moves the Monaco theme and its loading canvas together across contrast appearances', () => {+ const { rerenderAppearance, container } = renderEditor(artifact, {+ resolvedMode: 'light',+ highContrast: true,+ });++ expect(mockEditorProps.theme).toBe('librechat-high-contrast-light');+ expect(container.firstElementChild).toHaveStyle({+ backgroundColor: toHexColor(highContrastLightTheme, 'rgb-surface-primary-alt'),+ });++ rerenderAppearance({ resolvedMode: 'dark', highContrast: true });++ expect(mockEditorProps.theme).toBe('librechat-high-contrast-dark');+ expect(container.firstElementChild).toHaveStyle({+ backgroundColor: toHexColor(highContrastDarkTheme, 'rgb-presentation'),+ });+ });++ it('defines both contrast themes from the semantic syntax palettes', () => {+ renderEditor(artifact, { resolvedMode: 'light', highContrast: true });+ const { monaco, defineTheme } = createMonacoMock();++ mockEditorProps.beforeMount?.(monaco);++ expect(defineTheme).toHaveBeenCalledTimes(2);+ expect(defineTheme).toHaveBeenCalledWith(+ 'librechat-high-contrast-light',+ expect.objectContaining({+ base: 'vs',+ inherit: false,+ colors: expect.objectContaining({+ 'editor.background': toHexColor(highContrastLightTheme, 'rgb-surface-primary-alt'),+ 'editor.foreground': toHexColor(highContrastLightTheme, 'rgb-syntax-text'),+ 'editor.selectionBackground': toHexColor(highContrastLightTheme, 'rgb-text-primary'),+ 'editor.selectionForeground': toHexColor(highContrastLightTheme, 'rgb-surface-primary'),+ }),+ rules: expect.arrayContaining([+ expect.objectContaining({+ token: 'keyword',+ foreground: toHexColor(highContrastLightTheme, 'rgb-syntax-keyword').slice(1),+ }),+ ]),+ }),+ );+ expect(defineTheme).toHaveBeenCalledWith(+ 'librechat-high-contrast-dark',+ expect.objectContaining({+ base: 'vs-dark',+ inherit: false,+ colors: expect.objectContaining({+ 'editor.background': toHexColor(highContrastDarkTheme, 'rgb-presentation'),+ 'editor.foreground': toHexColor(highContrastDarkTheme, 'rgb-syntax-text'),+ 'editor.selectionBackground': toHexColor(highContrastDarkTheme, 'rgb-text-primary'),+ 'editor.selectionForeground': toHexColor(highContrastDarkTheme, 'rgb-surface-primary'),+ }),+ }),+ );+ });+it('does not re-run a mutation for content that just failed', () => {renderEditor();diff --git a/client/src/components/Artifacts/ArtifactCodeEditor.tsx b/client/src/components/Artifacts/ArtifactCodeEditor.tsxindex f95d7f044b..ad1b42b420 100644--- a/client/src/components/Artifacts/ArtifactCodeEditor.tsx+++ b/client/src/components/Artifacts/ArtifactCodeEditor.tsx@@ -1,7 +1,9 @@-import React, { useMemo, useState, useEffect, useRef, useCallback } from 'react';+import React, { useMemo, useState, useEffect, useRef, useCallback, useContext } from 'react';import debounce from 'lodash/debounce';import MonacoEditor from '@monaco-editor/react';+import { ThemeContext, highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';import type { Monaco } from '@monaco-editor/react';+import type { IThemeRGB } from '@librechat/client';import type { editor } from 'monaco-editor';import type { Artifact } from '~/common';import { useMutationState, useCodeState } from '~/Providers/EditorContext';@@ -50,6 +52,126 @@ const TYPE_MAP: Record<string, string> = {'application/vnd.mermaid': 'markdown',};+const HIGH_CONTRAST_LIGHT_EDITOR_THEME = 'librechat-high-contrast-light';+const HIGH_CONTRAST_DARK_EDITOR_THEME = 'librechat-high-contrast-dark';++/** Monaco's stock `vs-dark` canvas. `@monaco-editor/react` renders its loading+ * view transparent, so the wrapper has to paint whatever the active Monaco+ * theme paints or the Code tab flashes the wrong color before the editor+ * mounts. The contrast themes take their canvas from the semantic palettes+ * below; this one belongs to a Monaco built-in, so no LibreChat role names it+ * and no theme can move it. */+const STANDARD_EDITOR_BACKGROUND = '#1e1e1e';++const toHexColor = (palette: IThemeRGB, token: keyof IThemeRGB): string => {+ const value = palette[token];+ if (value == null) {+ throw new Error(`Missing Monaco theme token: ${token}`);+ }++ const channels = value.split(/\s+/).map((channel) => Number(channel));+ if (channels.length !== 3 || channels.some((channel) => !Number.isInteger(channel))) {+ throw new Error(`Invalid Monaco theme token: ${token}`);+ }++ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;+};++const createHighContrastEditorTheme = (+ palette: IThemeRGB,+ base: 'vs' | 'vs-dark',+ backgroundToken: keyof IThemeRGB,+): editor.IStandaloneThemeData => {+ const color = (token: keyof IThemeRGB) => toHexColor(palette, token);+ const syntax = (token: keyof IThemeRGB) => color(token).slice(1);++ return {+ base,+ inherit: false,+ rules: [+ { token: '', foreground: syntax('rgb-syntax-text') },+ { token: 'identifier', foreground: syntax('rgb-syntax-text') },+ { token: 'comment', foreground: syntax('rgb-syntax-comment') },+ { token: 'meta', foreground: syntax('rgb-syntax-meta') },+ { token: 'annotation', foreground: syntax('rgb-syntax-meta') },+ { token: 'delimiter', foreground: syntax('rgb-syntax-meta') },+ { token: 'predefined', foreground: syntax('rgb-syntax-builtin') },+ { token: 'class', foreground: syntax('rgb-syntax-builtin') },+ { token: 'keyword', foreground: syntax('rgb-syntax-keyword') },+ { token: 'literal', foreground: syntax('rgb-syntax-keyword') },+ { token: 'string', foreground: syntax('rgb-syntax-string') },+ { token: 'regexp', foreground: syntax('rgb-syntax-string') },+ { token: 'variable', foreground: syntax('rgb-syntax-attr') },+ { token: 'number', foreground: syntax('rgb-syntax-attr') },+ { token: 'type', foreground: syntax('rgb-syntax-attr') },+ { token: 'attribute.name', foreground: syntax('rgb-syntax-attr') },+ { token: 'tag', foreground: syntax('rgb-syntax-title') },+ { token: 'symbol', foreground: syntax('rgb-syntax-title') },+ ],+ colors: {+ 'editor.background': color(backgroundToken),+ 'editor.foreground': color('rgb-syntax-text'),+ 'editorLineNumber.foreground': color('rgb-text-secondary'),+ 'editorLineNumber.activeForeground': color('rgb-text-primary'),+ 'editorCursor.foreground': color('rgb-ring-primary'),+ /** These palettes have no mid-tones, so a focused selection inverts the+ * canvas exactly as `::selection` does in `client/src/style.css` — 21:1,+ * and the only treatment that works without the perimeter the selected+ * surfaces rely on elsewhere. The weaker emphases (unfocused selection,+ * matching occurrences, other find hits) share `surface-hover-alt` so+ * they never outshout the focused one; the current find match is told+ * apart by its ink `findMatchBorder`. */+ 'editor.selectionBackground': color('rgb-text-primary'),+ 'editor.selectionForeground': color('rgb-surface-primary'),+ 'editor.inactiveSelectionBackground': color('rgb-surface-hover-alt'),+ 'editor.selectionHighlightBackground': color('rgb-surface-hover-alt'),+ 'editor.lineHighlightBackground': color('rgb-surface-hover'),+ 'editor.findMatchBackground': color('rgb-surface-hover-alt'),+ 'editor.findMatchBorder': color('rgb-border-heavy'),+ 'editor.findMatchHighlightBackground': color('rgb-surface-hover-alt'),+ 'editorWidget.background': color('rgb-surface-dialog'),+ 'editorWidget.border': color('rgb-border-medium'),+ 'input.background': color('rgb-surface-primary'),+ 'input.foreground': color('rgb-text-primary'),+ 'input.border': color('rgb-border-medium'),+ focusBorder: color('rgb-ring-primary'),+ 'editorIndentGuide.background1': color('rgb-border-light'),+ 'editorIndentGuide.activeBackground1': color('rgb-border-heavy'),+ 'scrollbarSlider.background': color('rgb-border-light'),+ 'scrollbarSlider.hoverBackground': color('rgb-border-heavy'),+ 'scrollbarSlider.activeBackground': color('rgb-border-xheavy'),+ },+ };+};++const highContrastLightEditorTheme = createHighContrastEditorTheme(+ highContrastLightTheme,+ 'vs',+ 'rgb-surface-primary-alt',+);+const highContrastDarkEditorTheme = createHighContrastEditorTheme(+ highContrastDarkTheme,+ 'vs-dark',+ 'rgb-presentation',+);++/** Theme name paired with the canvas it paints, so the wrapper behind the+ * editor and the editor itself can never disagree. */+type EditorAppearance = { theme: string; background: string };++const standardEditorAppearance: EditorAppearance = {+ theme: 'vs-dark',+ background: STANDARD_EDITOR_BACKGROUND,+};+const highContrastLightEditorAppearance: EditorAppearance = {+ theme: HIGH_CONTRAST_LIGHT_EDITOR_THEME,+ background: highContrastLightEditorTheme.colors['editor.background'],+};+const highContrastDarkEditorAppearance: EditorAppearance = {+ theme: HIGH_CONTRAST_DARK_EDITOR_THEME,+ background: highContrastDarkEditorTheme.colors['editor.background'],+};+type ArtifactEditTarget = {artifactId: string;messageId: string;@@ -107,6 +229,7 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({monacoRef: React.MutableRefObject<editor.IStandaloneCodeEditor | null>;readOnly?: boolean;}) {+ const { resolvedMode, highContrast } = useContext(ThemeContext);const { isSubmitting } = useArtifactsContext();const readOnly = (externalReadOnly ?? false) || isSubmitting;const { setCurrentCode } = useCodeState();@@ -338,6 +461,9 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({* as `{ deprecated: true }` while the runtime API is fully functional.*/const handleBeforeMount = useCallback((monaco: Monaco) => {+ monaco.editor.defineTheme(HIGH_CONTRAST_LIGHT_EDITOR_THEME, highContrastLightEditorTheme);+ monaco.editor.defineTheme(HIGH_CONTRAST_DARK_EDITOR_THEME, highContrastDarkEditorTheme);+const { typescriptDefaults, javascriptDefaults, JsxEmit } = monaco.languages.typescript as unknown as {typescriptDefaults: {@@ -388,6 +514,13 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({);const language = getMonacoLanguage(artifact.type, artifact.language);+ let editorAppearance = standardEditorAppearance;+ if (highContrast) {+ editorAppearance =+ resolvedMode === 'dark'+ ? highContrastDarkEditorAppearance+ : highContrastLightEditorAppearance;+ }const editorOptions = useMemo<editor.IStandaloneEditorConstructionOptions>(() => ({@@ -433,11 +566,11 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({}return (- <div className="h-full w-full bg-[#1e1e1e]">+ <div className="h-full w-full" style={{ backgroundColor: editorAppearance.background }}><MonacoEditorheight="100%"language={readOnly ? 'plaintext' : language}- theme="vs-dark"+ theme={editorAppearance.theme}defaultValue={artifact.content}onChange={handleChange}beforeMount={handleBeforeMount}diff --git a/client/src/components/Artifacts/Artifacts.tsx b/client/src/components/Artifacts/Artifacts.tsxindex f72494f87e..a3fdeecdc4 100644--- a/client/src/components/Artifacts/Artifacts.tsx+++ b/client/src/components/Artifacts/Artifacts.tsx@@ -382,7 +382,7 @@ export default function Artifacts() {onPointerCancel={handleDragEnd}onKeyDown={handleDragKeyDown}>- <div className="h-1 w-12 rounded-full bg-border-xheavy opacity-40 transition-all duration-200 active:opacity-60 motion-reduce:transition-none" />+ <div className="h-1 w-12 rounded-full bg-border-xheavy opacity-40 transition-all duration-200 active:opacity-60 high-contrast:opacity-100 motion-reduce:transition-none" /></div>)}diff --git a/client/src/components/Bookmarks/BookmarkEditDialog.tsx b/client/src/components/Bookmarks/BookmarkEditDialog.tsxindex 05fc902698..7d59d2081c 100644--- a/client/src/components/Bookmarks/BookmarkEditDialog.tsx+++ b/client/src/components/Bookmarks/BookmarkEditDialog.tsx@@ -107,7 +107,6 @@ const BookmarkEditDialog = ({type="submit"disabled={mutation.isLoading}onClick={handleSubmitForm}- className="text-white">{mutation.isLoading ? <Spinner /> : localize('com_ui_save')}</Button>diff --git a/client/src/components/Bookmarks/DeleteBookmarkButton.tsx b/client/src/components/Bookmarks/DeleteBookmarkButton.tsxindex dbb7d8a1a7..38d77d3b0e 100644--- a/client/src/components/Bookmarks/DeleteBookmarkButton.tsx+++ b/client/src/components/Bookmarks/DeleteBookmarkButton.tsx@@ -74,7 +74,8 @@ const DeleteBookmarkButton: FC<{}selection={{selectHandler: confirmDelete,- selectClasses: 'bg-surface-destructive hover:bg-surface-destructive-hover text-white',+ selectClasses:+ 'bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsxindex 1190a9fc96..1f25da2efd 100644--- a/client/src/components/Chat/Input/ChatForm.tsx+++ b/client/src/components/Chat/Input/ChatForm.tsx@@ -598,8 +598,16 @@ const ChatForm = memo(function ChatForm({composerSurfaceClasses(),isTextAreaFocused ? composerSurfaceShadow.focused : composerSurfaceShadow.blurred,/* Temporary-chat accent is a ChatForm-only override, not part of- the shared composer-surface decision. */- isTemporary && 'border-violet-800/60 bg-violet-950/10',+ the shared composer-surface decision. Semantic `series-6`, the+ same categorical slot the purple tool badge uses, so the accent+ follows the theme instead of the raw `violet-800/60` edge that+ composited to 1.48:1 on the high contrast dark canvas.+ Held at half alpha in the standard palettes, where series-6 is+ a saturated #7e23cd / #ab68fe and a full-strength edge reads as+ a warning rather than a quiet mode hint. The contrast modes take+ it opaque, because that is the only way it clears the 3:1+ non-text floor there. */+ isTemporary && 'border-series-6/50 bg-series-6/10 high-contrast:border-series-6',)}>{project ? <ProjectLandingChip project={project} /> : null}diff --git a/client/src/components/Chat/Input/Files/SourceIcon.tsx b/client/src/components/Chat/Input/Files/SourceIcon.tsxindex 9f1392be64..63a8ef790b 100644--- a/client/src/components/Chat/Input/Files/SourceIcon.tsx+++ b/client/src/components/Chat/Input/Files/SourceIcon.tsx@@ -13,8 +13,11 @@ const sourceToClassname = {[FileSources.azure]: 'azure-bg-color',[FileSources.azure_blob]: 'azure-bg-color',[FileSources.execute_code]: 'bg-black text-white opacity-85',- [FileSources.text]: 'bg-blue-500 dark:bg-blue-900 opacity-85 text-white',- [FileSources.vectordb]: 'bg-yellow-700 dark:bg-yellow-900 opacity-85 text-white',+ /** Categorical rather than status: a source is an identity, so it takes a+ * series slot and the label ink that pairs with one. No alpha here, which+ * composited the fill back into the preview the badge sits on. */+ [FileSources.text]: 'bg-series-1 text-text-on-status',+ [FileSources.vectordb]: 'bg-series-4 text-text-on-status',};const defaultClassName =diff --git a/client/src/components/Chat/Input/InFlightSteers.tsx b/client/src/components/Chat/Input/InFlightSteers.tsxindex 262b26394b..5884663c40 100644--- a/client/src/components/Chat/Input/InFlightSteers.tsx+++ b/client/src/components/Chat/Input/InFlightSteers.tsx@@ -19,6 +19,7 @@ import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDiaimport { supportsGenerationProtocolV2, useArmSteerMutation } from '~/data-provider';import { steerOverlayHeightFamily, escalatingSteerFamily } from '~/store/steer';import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';+import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';import FileContainer from '~/components/Chat/Input/Files/FileContainer';import { useSteerCancel, useSteerReclaim, useLocalize } from '~/hooks';@@ -438,7 +439,7 @@ const InFlightSteer = memo(function InFlightSteer({{key: 'queue',label: localize('com_ui_convert_to_queue'),- icon: <Clock className="h-4 w-4 text-cyan-500" aria-hidden="true" />,+ icon: <Clock className={cn('h-4 w-4', QUEUE_ICON)} aria-hidden="true" />,onClick: () => {void reclaim().then((reclaimed) => {if (reclaimed) {@@ -520,7 +521,7 @@ const InFlightSteer = memo(function InFlightSteer({><MorphIconicon={preempting ? ZapOff : Zap}- className="mt-1 h-3.5 w-3.5 shrink-0 text-amber-500"+ className={cn('mt-1 h-3.5 w-3.5 shrink-0', STEER_ICON)}/><span className="sr-only">{localize(preempting ? 'com_ui_steer_in_flight_preempt' : 'com_ui_steer_in_flight')}diff --git a/client/src/components/Chat/Input/MCPConfigDialog.tsx b/client/src/components/Chat/Input/MCPConfigDialog.tsxindex d6ad627a26..a9aa947100 100644--- a/client/src/components/Chat/Input/MCPConfigDialog.tsx+++ b/client/src/components/Chat/Input/MCPConfigDialog.tsx@@ -115,7 +115,7 @@ export default function MCPConfigDialog({/>{details.description && (<p- className="text-xs text-text-secondary [&_a]:text-link [&_a]:hover:text-link-hover"+ className="text-xs text-text-secondary [&_a]:text-link [&_a]:underline [&_a]:hover:text-link-hover"dangerouslySetInnerHTML={{ __html: sanitize(details.description) }}/>)}@@ -128,7 +128,7 @@ export default function MCPConfigDialog({}selection={{selectHandler: handleSubmit(onFormSubmit),- selectClasses: 'bg-surface-submit text-white hover:bg-surface-submit-hover',+ selectClasses: 'bg-surface-submit text-text-on-status hover:bg-surface-submit-hover',selectText: isSubmitting ? localize('com_ui_saving') : localize('com_ui_save'),}}buttons={diff --git a/client/src/components/Chat/Input/PendingManualSkillsChips.tsx b/client/src/components/Chat/Input/PendingManualSkillsChips.tsxindex 5111ea985d..29396723c0 100644--- a/client/src/components/Chat/Input/PendingManualSkillsChips.tsx+++ b/client/src/components/Chat/Input/PendingManualSkillsChips.tsx@@ -42,7 +42,7 @@ function PendingManualSkillsChips({ conversationId }: { conversationId: string }role="listitem"className="inline-flex items-center gap-1 rounded-full border border-border-light bg-surface-secondary px-2 py-0.5 text-xs text-text-secondary">- <ScrollText className="h-3 w-3 text-cyan-500" aria-hidden="true" />+ <ScrollText className="h-3 w-3 text-status-info" aria-hidden="true" /><span className="max-w-[12rem] truncate">{name}</span><buttontype="button"diff --git a/client/src/components/Chat/Input/PendingQuoteChips.tsx b/client/src/components/Chat/Input/PendingQuoteChips.tsxindex 1ea04ff67a..ef2f441d5b 100644--- a/client/src/components/Chat/Input/PendingQuoteChips.tsx+++ b/client/src/components/Chat/Input/PendingQuoteChips.tsx@@ -11,6 +11,13 @@ const REMOVE_BTN_CLASS ='-mr-0.5 shrink-0 rounded-full p-0.5 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy';const TRIGGER_CLASS ='inline-flex min-w-0 items-center gap-1.5 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-xheavy';+/**+ * Quote mark. Semantic `status-info` rather than `cyan-500`, matching the queue+ * identity in `Chat/Steering/identity.ts`: the raw hue lands at 2.43:1 on the+ * high contrast light composer, under the 3:1 floor for a chip whose only type+ * cue is this icon.+ */+const QUOTE_ICON_CLASS = 'h-4 w-4 shrink-0 text-status-info';/** Grace period so moving the pointer between the chip and the popup doesn't close it. */const CLOSE_DELAY_MS = 120;@@ -87,7 +94,7 @@ function PendingQuoteChips({ conversationId }: { conversationId: string }) {>{!isMulti ? (<span role="listitem" className={CHIP_CLASS}>- <TextQuote className="h-4 w-4 shrink-0 text-cyan-500" aria-hidden="true" />+ <TextQuote className={QUOTE_ICON_CLASS} aria-hidden="true" /><span className="max-w-[16rem] truncate" title={quotes[0]}>{quotes[0]}</span>@@ -114,7 +121,7 @@ function PendingQuoteChips({ conversationId }: { conversationId: string }) {aria-label={localize('com_ui_quote_selections', { 0: quotes.length })}onClick={() => setFocusOnShow(true)}>- <TextQuote className="h-4 w-4 shrink-0 text-cyan-500" aria-hidden="true" />+ <TextQuote className={QUOTE_ICON_CLASS} aria-hidden="true" /><span className="truncate">{localize('com_ui_quote_selections', { 0: quotes.length })}</span>diff --git a/client/src/components/Chat/Input/PendingSteerChips.tsx b/client/src/components/Chat/Input/PendingSteerChips.tsxindex 3e21c69f3b..dc820c6d0e 100644--- a/client/src/components/Chat/Input/PendingSteerChips.tsx+++ b/client/src/components/Chat/Input/PendingSteerChips.tsx@@ -27,6 +27,7 @@ import {useDefaultToggleEntry,useInterruptToggleEntry,} from './SteerMenu';+import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';import { escalatingSteerFamily } from '~/store/steer';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -211,7 +212,7 @@ function QueuedRow({{isRejected || isUnconfirmed || isIndeterminate ? (<TriangleAlert className="h-4 w-4 shrink-0 text-text-warning" aria-hidden="true" />) : (- <Clock className="h-4 w-4 shrink-0 text-cyan-500" aria-hidden="true" />+ <Clock className={cn('h-4 w-4 shrink-0', QUEUE_ICON)} aria-hidden="true" />)}<span className="min-w-0 flex-1 truncate" title={message.text}>{message.text}@@ -238,7 +239,7 @@ function QueuedRow({>{canSteerNow ? (<>- <Zap className="h-4 w-4 text-amber-500" aria-hidden="true" />+ <Zap className={cn('h-4 w-4', STEER_ICON)} aria-hidden="true" />{localize('com_ui_steer')}</>) : (@@ -338,7 +339,7 @@ function FailedSteerRow({{key: 'queue',label: localize('com_ui_convert_to_queue'),- icon: <Clock className="h-4 w-4 text-cyan-500" aria-hidden="true" />,+ icon: <Clock className={cn('h-4 w-4', QUEUE_ICON)} aria-hidden="true" />,onClick: () =>steering.convertSteerToQueue(steer.steerId,@@ -354,10 +355,10 @@ function FailedSteerRow({return (<divrole="listitem"- className={cn(ROW_CLASS, 'border-red-500/60')}+ className={cn(ROW_CLASS, 'border-border-destructive')}data-testid="steer-message-row">- <Zap className="h-4 w-4 shrink-0 text-red-500" aria-hidden="true" />+ <Zap className="h-4 w-4 shrink-0 text-text-destructive" aria-hidden="true" /><span className="min-w-0 flex-1 truncate" title={steer.text}>{steer.text}</span>@@ -367,7 +368,7 @@ function FailedSteerRow({0: String(steer.quotes?.length ?? 0),})}/>- <span className="shrink-0 text-xs text-red-500">+ <span className="shrink-0 text-xs text-text-destructive">{localize(steer.deliveryUncertain ? 'com_ui_steer_delivery_unconfirmed' : 'com_ui_steer_failed',)}diff --git a/client/src/components/Chat/Input/SkillsCommand.tsx b/client/src/components/Chat/Input/SkillsCommand.tsxindex 27d5ad91e9..6ed2f756c0 100644--- a/client/src/components/Chat/Input/SkillsCommand.tsx+++ b/client/src/components/Chat/Input/SkillsCommand.tsx@@ -19,7 +19,7 @@ import store from '~/store';const commandChar = '$';const ROW_HEIGHT = 44;-const skillIcon = <ScrollText className="icon-md text-cyan-500" />;+const skillIcon = <ScrollText className="icon-md text-status-info" />;/*** Determines whether a skill should appear in the `$` command popover.diff --git a/client/src/components/Chat/Input/SteerMenu.tsx b/client/src/components/Chat/Input/SteerMenu.tsxindex 26db8066a9..768e7d04ba 100644--- a/client/src/components/Chat/Input/SteerMenu.tsx+++ b/client/src/components/Chat/Input/SteerMenu.tsx@@ -7,6 +7,7 @@ import { ArrowUp, CircleHelp, MoreHorizontal } from 'lucide-react';import type { Ref } from 'react';import type { SteeringControls } from '~/hooks/Chat/useSteering';import { useShortcutAriaKey, useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';+import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';import { useLocalize } from '~/hooks';import { cn } from '~/utils';import store from '~/store';@@ -288,7 +289,7 @@ export function useDefaultToggleEntry(steering: SteeringControls): MenuEntry {icon: (<MorphIconicon={next === 'queue' ? Clock : Zap}- className={cn('h-4 w-4', next === 'queue' ? 'text-cyan-500' : 'text-amber-500')}+ className={cn('h-4 w-4', next === 'queue' ? QUEUE_ICON : STEER_ICON)}/>),info: localize('com_nav_info_during_run_action'),@@ -314,7 +315,10 @@ export function useInterruptToggleEntry(): MenuEntry {? localize('com_ui_wait_for_tool_steps'): localize('com_ui_always_interrupt'),icon: (- <MorphIcon icon={interruptsByDefault ? Zap : ZapOff} className="h-4 w-4 text-amber-500" />+ <MorphIcon+ icon={interruptsByDefault ? Zap : ZapOff}+ className={cn('h-4 w-4', STEER_ICON)}+ />),info: localize(!interruptsByDefault && defaultAction === 'queue'diff --git a/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx b/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsxindex 63d9e4f5d2..36e0899780 100644--- a/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/PendingManualSkillsChips.spec.tsx@@ -31,11 +31,12 @@ describe('PendingManualSkillsChips', () => {});it('renders one chip per queued skill', () => {- renderWithSkills(['brand-guidelines', 'pptx']);+ const { container } = renderWithSkills(['brand-guidelines', 'pptx']);const items = screen.getAllByRole('listitem');expect(items).toHaveLength(2);expect(items[0]).toHaveTextContent('brand-guidelines');expect(items[1]).toHaveTextContent('pptx');+ expect(container.querySelector('svg')).toHaveClass('text-status-info');});it('removes the chip when its × button is clicked', async () => {diff --git a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsxindex d9c9317643..9947d7f34f 100644--- a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx+++ b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx@@ -146,6 +146,24 @@ describe('PendingSteerChips — ambiguous delivery retry', () => {{ preempt: false, createdAt: 1, generationProtocolVersion: 2 },);});++ it('uses semantic destructive roles for a failed steer', () => {+ renderChips([], {+ steers: [+ {+ steerId: 'failed-steer',+ text: 'failed message',+ status: 'failed',+ createdAt: 1,+ },+ ],+ });++ const row = screen.getByTestId('steer-message-row');+ expect(row).toHaveClass('border-border-destructive');+ expect(row.querySelector('svg')).toHaveClass('text-text-destructive');+ expect(screen.getByText('com_ui_steer_failed')).toHaveClass('text-text-destructive');+ });});describe('PendingSteerChips — queued primary availability', () => {diff --git a/client/src/components/Chat/Input/__tests__/accents.spec.ts b/client/src/components/Chat/Input/__tests__/accents.spec.tsnew file mode 100644index 0000000000..8796b6fdd8--- /dev/null+++ b/client/src/components/Chat/Input/__tests__/accents.spec.ts@@ -0,0 +1,17 @@+import { badgeAccents } from '../accents';++describe('badgeAccents', () => {+ it('uses opaque semantic series borders for checked capability badges', () => {+ expect(badgeAccents).toEqual({+ amber: 'border-series-4 bg-series-4/10 hover:bg-series-4/20',+ blue: 'border-series-1 bg-series-1/10 hover:bg-series-1/20',+ cyan: 'border-series-3 bg-series-3/10 hover:bg-series-3/20',+ green: 'border-series-7 bg-series-7/10 hover:bg-series-7/20',+ purple: 'border-series-6 bg-series-6/10 hover:bg-series-6/20',+ });++ expect(Object.values(badgeAccents).join(' ')).not.toMatch(+ /(?:amber|blue|cyan|green|purple)-\d/,+ );+ });+});diff --git a/client/src/components/Chat/Input/accents.ts b/client/src/components/Chat/Input/accents.tsindex ec1b6a50f5..b883c2f24d 100644--- a/client/src/components/Chat/Input/accents.ts+++ b/client/src/components/Chat/Input/accents.ts@@ -3,9 +3,9 @@* Written out in full because Tailwind cannot resolve interpolated class names.*/export const badgeAccents = {- amber: 'border-amber-600/40 bg-amber-500/10 hover:bg-amber-700/10',- blue: 'border-blue-600/40 bg-blue-500/10 hover:bg-blue-700/10',- cyan: 'border-cyan-600/40 bg-cyan-500/10 hover:bg-cyan-700/10',- green: 'border-green-600/40 bg-green-500/10 hover:bg-green-700/10',- purple: 'border-purple-600/40 bg-purple-500/10 hover:bg-purple-700/10',+ amber: 'border-series-4 bg-series-4/10 hover:bg-series-4/20',+ blue: 'border-series-1 bg-series-1/10 hover:bg-series-1/20',+ cyan: 'border-series-3 bg-series-3/10 hover:bg-series-3/20',+ green: 'border-series-7 bg-series-7/10 hover:bg-series-7/20',+ purple: 'border-series-6 bg-series-6/10 hover:bg-series-6/20',} as const;diff --git a/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx b/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsxindex 2b5980bf92..f169a1baa9 100644--- a/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx+++ b/client/src/components/Chat/Menus/Endpoints/components/GroupIcon.tsx@@ -36,7 +36,7 @@ const GroupIcon: React.FC<GroupIconProps> = ({ iconURL, groupName }) => {className="absolute flex items-center justify-center rounded-full bg-surface-destructive"style={{ width: '14px', height: '14px', top: 0, right: 0 }}>- <AlertCircle size={10} className="text-white" />+ <AlertCircle size={10} className="text-text-on-status" /></div>)}</div>diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsxindex 852b8320e1..d2f9d4d7ca 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx@@ -2,6 +2,7 @@ import React from 'react';import { RecoilRoot, useRecoilValue } from 'recoil';import { render, screen, fireEvent } from '@testing-library/react';import type { TMessage } from 'librechat-data-provider';+import { STEER_ICON } from '~/components/Chat/Steering/identity';import SteerPart from '../SteerPart';import store from '~/store';@@ -277,13 +278,13 @@ describe('SteerPart live receipt draw-in', () => {describe('SteerPart receipt settling', () => {const checks = () => screen.getByLabelText('com_ui_steer_applied_info').querySelector('svg');- it('keeps the amber identity while the owning response is still generating', () => {+ it('keeps the steer identity while the owning response is still generating', () => {render(<RecoilRoot initializeState={({ set }) => set(store.user, SEEDED_USER as never)}><SteerPart steer="steered words" steerId="s1" createdAt={1} isSubmitting /></RecoilRoot>,);- expect(checks()).toHaveClass('dark:text-amber-500');+ expect(checks()).toHaveClass(STEER_ICON);expect(checks()).not.toHaveClass('text-text-secondary');});@@ -292,6 +293,6 @@ describe('SteerPart receipt settling', () => {// rendering: still a double check, no longer lit.renderPart();expect(checks()).toHaveClass('text-text-secondary');- expect(checks()).not.toHaveClass('dark:text-amber-500');+ expect(checks()).not.toHaveClass(STEER_ICON);});});diff --git a/client/src/components/Chat/Messages/Content/SkillPills.tsx b/client/src/components/Chat/Messages/Content/SkillPills.tsxindex b9b60f116a..d261957cc2 100644--- a/client/src/components/Chat/Messages/Content/SkillPills.tsx+++ b/client/src/components/Chat/Messages/Content/SkillPills.tsx@@ -53,9 +53,9 @@ function SkillPills({className="inline-flex items-center gap-1 rounded-full border border-border-light bg-surface-secondary px-2 py-1 text-xs text-text-secondary">{source === 'always-apply' ? (- <Pin className="h-3 w-3 text-cyan-500" aria-hidden="true" />+ <Pin className="h-3 w-3 text-status-info" aria-hidden="true" />) : (- <ScrollText className="h-3 w-3 text-cyan-500" aria-hidden="true" />+ <ScrollText className="h-3 w-3 text-status-info" aria-hidden="true" />)}<span className="max-w-[12rem] truncate">{name}</span></span>diff --git a/client/src/components/Chat/Messages/Content/__tests__/SkillPills.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/SkillPills.test.tsxindex 9b7a41b132..134cc0224b 100644--- a/client/src/components/Chat/Messages/Content/__tests__/SkillPills.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/SkillPills.test.tsx@@ -60,10 +60,11 @@ describe('SkillPills', () => {const manualSvg = manual.querySelector('svg');expect(alwaysApplySvg).toBeTruthy();expect(manualSvg).toBeTruthy();- // Pin vs. ScrollText have distinct lucide class names; both carry the- // cyan-500 accent the component applies, but only one carries the- // lucide-pin class.+ // Pin vs. ScrollText have distinct lucide class names, but both use the+ // same semantic informational color.expect(alwaysApplySvg?.getAttribute('class')).toContain('lucide-pin');expect(manualSvg?.getAttribute('class')).not.toContain('lucide-pin');+ expect(alwaysApplySvg).toHaveClass('text-status-info');+ expect(manualSvg).toHaveClass('text-status-info');});});diff --git a/client/src/components/Chat/Messages/MessageNav.tsx b/client/src/components/Chat/Messages/MessageNav.tsxindex 58131cdbb2..4cef105caa 100644--- a/client/src/components/Chat/Messages/MessageNav.tsx+++ b/client/src/components/Chat/Messages/MessageNav.tsx@@ -290,7 +290,7 @@ const indicatorButtonClasses = cn();const dimIndicatorClasses =- 'opacity-40 group-hover/nav:opacity-100 group-focus-within/nav:opacity-100';+ 'opacity-40 high-contrast:opacity-50 group-hover/nav:opacity-100 group-focus-within/nav:opacity-100';const MessageIndicator = memo(function MessageIndicator({entry,@@ -350,7 +350,7 @@ const MessageIndicator = memo(function MessageIndicator({});const chevronButtonClasses = cn(- '-mr-1 rounded-md p-0.5 text-text-tertiary opacity-40 transition-[color,opacity] duration-300',+ '-mr-1 rounded-md p-0.5 text-text-tertiary opacity-40 transition-[color,opacity] duration-300 high-contrast:opacity-50','group-hover/nav:text-text-secondary group-hover/nav:opacity-100','group-focus-within/nav:text-text-secondary group-focus-within/nav:opacity-100','group-hover/nav:hover:text-text-primary',diff --git a/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsxindex c71a422f16..5ae0fcb7db 100644--- a/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/MessageNav.spec.tsx@@ -1,5 +1,5 @@import React from 'react';-import { render, act, fireEvent } from '@testing-library/react';+import { render, act, fireEvent, screen } from '@testing-library/react';type ReactNode = React.ReactNode;type RefObject<T> = React.RefObject<T>;@@ -392,7 +392,17 @@ describe('MessageNav', () => {const ribB = container.querySelector('[data-msg-id="b"]') as HTMLElement;expect(ribA.className).toContain('opacity-100');expect(ribA.className).not.toContain('opacity-40');+ expect(ribA.querySelector('span')).toHaveClass('bg-text-primary');expect(ribB.className).toContain('opacity-40');+ expect(ribB.className).toContain('high-contrast:opacity-50');+ expect(ribB.querySelector('span')).toHaveClass('bg-text-tertiary');+ expect(ribA.querySelector('span')?.className).not.toMatch(/bg-gray-|dark:bg-gray-/);+ expect(ribB.querySelector('span')?.className).not.toMatch(/bg-gray-|dark:bg-gray-/);++ const previous = screen.getByRole('button', { name: 'com_ui_message_nav_previous' });+ const next = screen.getByRole('button', { name: 'com_ui_message_nav_next' });+ expect(previous).toHaveClass('text-text-tertiary', 'high-contrast:opacity-50');+ expect(next).toHaveClass('text-text-tertiary', 'high-contrast:opacity-50');});});@@ -716,7 +726,7 @@ describe('MessageNav', () => {const activeLine = container.querySelector('[aria-current="true"] span');expect(activeLine?.className).toContain('bg-text-primary');- /** The other two rows are on screen, so they read as the in-view band —+ /** The other two rows are on screen, so they read as the in-view band:* lit, but plainly not the mark that says where the reader is. */const band = messageRibs(container).slice(1)@@ -1218,7 +1228,7 @@ describe('MessageNav', () => {expect(writes.length).toBeGreaterThan(0);});- it('highlights only the hovered rib white, dimming the rest', () => {+ it('highlights only the hovered rib, dimming the rest', () => {const messages = [buildMessage({ messageId: 'a', text: 'alpha', isCreatedByUser: true }),buildMessage({ messageId: 'b', text: 'bravo' }),@@ -1234,11 +1244,11 @@ describe('MessageNav', () => {});const ribs = messageRibs(container);- const white = ribs.filter((r) =>+ const highlighted = ribs.filter((r) =>r.querySelector('span')?.className.includes('bg-text-primary'),);- expect(white).toHaveLength(1);- expect(white[0]).toHaveAttribute('data-msg-id', 'a');+ expect(highlighted).toHaveLength(1);+ expect(highlighted[0]).toHaveAttribute('data-msg-id', 'a');});});diff --git a/client/src/components/Chat/Steering/Receipt.tsx b/client/src/components/Chat/Steering/Receipt.tsxindex da2f1b5b1f..1844b56d25 100644--- a/client/src/components/Chat/Steering/Receipt.tsx+++ b/client/src/components/Chat/Steering/Receipt.tsx@@ -1,16 +1,12 @@import { memo } from 'react';import { Check, CheckCheck } from 'lucide-react';import { InfoHoverCard, ESide } from '@librechat/client';+import { STEER_DOT, STEER_ICON } from './identity';import { useLocalize } from '~/hooks';import { cn } from '~/utils';export type SteerReceiptState = 'sending' | 'delivered' | 'interrupting' | 'applied';-/** Amber-500 is the steering identity (the in-flight Zap), but it reads weak- * on white; 600 carries the same identity at legible contrast in light. */-const AMBER_ICON = 'text-amber-600 dark:text-amber-500';-const AMBER_DOT = 'bg-amber-600 dark:bg-amber-500';-/*** Delivery receipt for a steered message: iMessage-style checkmarks whose* every state is driven by an event the protocol already emits, so a check@@ -20,11 +16,11 @@ const AMBER_DOT = 'bg-amber-600 dark:bg-amber-500';* exists from the first frame instead of flickering in.* - `delivered`: the 202 durably queued it (one gray check).* - `interrupting`: asked to seal generation at the next safe boundary — the- * amber label and pulsing dot say "working, not stuck". Until the arm is- * server-confirmed (`confirmed` false) the label shows without its check.+ * steer-colored label and pulsing dot say "working, not stuck". Until the arm+ * is server-confirmed (`confirmed` false) the label shows without its check.* - `applied`: the running response durably absorbed the words (double check,- * persistent). It stays lit amber only while the owning response is still- * generating — the window where "did it land" is the question — then+ * persistent). It stays lit in the steer color only while the owning response+ * is still generating — the window where "did it land" is the question — then* settles to the same muted gray as the timestamp, so a conversation full* of historical steers doesn't glow forever.*@@ -40,7 +36,7 @@ const SteerReceipt = memo(function SteerReceipt({}: {state: SteerReceiptState;/** Applied only: the owning response is still generating, so the receipt is- * the newest thing on screen and keeps the amber steering identity. Off+ * the newest thing on screen and keeps the steering identity color. Off* (settled, reload, share, search) it dims to the timestamp gray. */live?: boolean;/** Server confirmation of the underlying enqueue/arm; an interrupt awaiting@@ -76,7 +72,7 @@ const SteerReceipt = memo(function SteerReceipt({<CheckCheckclassName={cn('h-4 w-4 transition-colors duration-theme-normal motion-reduce:transition-none',- live ? AMBER_ICON : 'text-text-secondary',+ live ? STEER_ICON : 'text-text-secondary',animateIn && 'ease-out animate-in fade-in-0 zoom-in-50 motion-reduce:animate-none',)}aria-hidden="true"@@ -102,20 +98,20 @@ const SteerReceipt = memo(function SteerReceipt({<span className="flex items-center gap-1.5">{interrupting && (<span- className={cn('h-1.5 w-1.5 rounded-full motion-safe:animate-pulse', AMBER_DOT)}+ className={cn('h-1.5 w-1.5 rounded-full motion-safe:animate-pulse', STEER_DOT)}aria-hidden="true"/>)}{(!interrupting || confirmed) && (<Check- className={cn('h-4 w-4', interrupting ? AMBER_ICON : 'text-text-secondary')}+ className={cn('h-4 w-4', interrupting ? STEER_ICON : 'text-text-secondary')}aria-hidden="true"/>)}<spanclassName={cn('text-xs',- interrupting ? cn('font-medium', AMBER_ICON) : 'text-text-secondary',+ interrupting ? cn('font-medium', STEER_ICON) : 'text-text-secondary',)}>{localize(interrupting ? 'com_ui_steer_in_flight_preempt' : 'com_ui_steer_delivered')}diff --git a/client/src/components/Chat/Steering/identity.ts b/client/src/components/Chat/Steering/identity.tsnew file mode 100644index 0000000000..8635232ec6--- /dev/null+++ b/client/src/components/Chat/Steering/identity.ts@@ -0,0 +1,22 @@+/**+ * Steering identity colors, shared by the composer chips, the row menus and the+ * inline delivery receipt so one steer reads the same everywhere it appears.+ *+ * Written as semantic status roles rather than palette hues. Both marks carry+ * state, and the receipt renders its label in the steer color at 12px, so the+ * identity has to clear the 4.5:1 text floor as well as the 3:1 floor for+ * graphical objects — on every canvas, including the enhanced-contrast themes.+ * A fixed palette hue cannot: `amber-600` label text lands at 3.19:1 on the+ * high-contrast light canvas, and the `amber-500`/`cyan-500` marks at 1.97:1+ * and 2.43:1, because a raw utility does not move when the theme does.+ *+ * `status-warning` and `status-info` are the theme-aware roles nearest the+ * amber and cyan identities they replace, and they clear both floors in every+ * theme: 4.69:1 and 4.83:1 at worst on the default light surfaces, 8.42:1 and+ * 10.31:1 at high contrast light, and higher on both dark canvases. The roles+ * also match the semantics — a steer preempts the running response, a queued+ * message is merely waiting.+ */+export const STEER_ICON = 'text-status-warning';+export const STEER_DOT = 'bg-status-warning';+export const QUEUE_ICON = 'text-status-info';diff --git a/client/src/components/Endpoints/MessageEndpointIcon.spec.tsx b/client/src/components/Endpoints/MessageEndpointIcon.spec.tsxindex fa2ae8a9a9..f6bd488b9f 100644--- a/client/src/components/Endpoints/MessageEndpointIcon.spec.tsx+++ b/client/src/components/Endpoints/MessageEndpointIcon.spec.tsx@@ -84,7 +84,7 @@ describe('MessageEndpointIcon', () => {/>,);- const badge = container.querySelector('[title="OpenAI"] > .bg-status-error');+ const badge = container.querySelector('[title="OpenAI"] > .bg-status-error-strong');expect(badge).toHaveTextContent('!');});diff --git a/client/src/components/Endpoints/MessageEndpointIcon.tsx b/client/src/components/Endpoints/MessageEndpointIcon.tsxindex 09bf90fb8c..7daedf8ee1 100644--- a/client/src/components/Endpoints/MessageEndpointIcon.tsx+++ b/client/src/components/Endpoints/MessageEndpointIcon.tsx@@ -78,7 +78,7 @@ const MessageEndpointIcon: React.FC<IconProps> = (props) => {};const errorBadge = error === true && (- <span className="absolute right-0 top-[20px] -mr-2 flex h-3 w-3 items-center justify-center rounded-full border border-white bg-status-error text-[10px] text-white">+ <span className="absolute right-0 top-[20px] -mr-2 flex h-3 w-3 items-center justify-center rounded-full border border-surface-primary bg-status-error-strong text-[10px] text-text-on-status">!</span>);diff --git a/client/src/components/Endpoints/MinimalIcon.tsx b/client/src/components/Endpoints/MinimalIcon.tsxindex ee703f49ad..969ab49af9 100644--- a/client/src/components/Endpoints/MinimalIcon.tsx+++ b/client/src/components/Endpoints/MinimalIcon.tsx@@ -38,7 +38,7 @@ const MinimalIcon: React.FC<IconProps> = (props) => {>{icon}{error === true && (- <span className="absolute right-0 top-[20px] -mr-2 flex h-4 w-4 items-center justify-center rounded-full border border-white bg-status-error text-[10px] text-text-secondary">+ <span className="absolute right-0 top-[20px] -mr-2 flex h-4 w-4 items-center justify-center rounded-full border border-surface-primary bg-status-error-strong text-[10px] text-text-on-status">!</span>)}diff --git a/client/src/components/Endpoints/Settings/Advanced.tsx b/client/src/components/Endpoints/Settings/Advanced.tsxindex 647e7f1b59..09d0a245ce 100644--- a/client/src/components/Endpoints/Settings/Advanced.tsx+++ b/client/src/components/Endpoints/Settings/Advanced.tsx@@ -81,7 +81,9 @@ export default function Settings({<div className="grid w-full items-center gap-2"><Label htmlFor="chatGptLabel" className="text-left text-sm font-medium">{localize('com_endpoint_custom_name')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><Inputid="chatGptLabel"@@ -99,7 +101,9 @@ export default function Settings({<div className="grid w-full items-center gap-2"><Label htmlFor="promptPrefix" className="text-left text-sm font-medium">{localize('com_endpoint_prompt_prefix')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><TextareaAutosizeid="promptPrefix"@@ -120,7 +124,7 @@ export default function Settings({<div className="flex justify-between"><Label htmlFor="temp-int" className="text-left text-sm font-medium">{localize('com_endpoint_temperature')}{' '}- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '1' })})</small></Label>@@ -161,7 +165,7 @@ export default function Settings({<div className="flex justify-between"><Label htmlFor="top-p-int" className="text-left text-sm font-medium">{localize('com_endpoint_top_p')}{' '}- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '1' })})</small></Label>@@ -203,7 +207,7 @@ export default function Settings({<div className="flex justify-between"><Label htmlFor="freq-penalty-int" className="text-left text-sm font-medium">{localize('com_endpoint_frequency_penalty')}{' '}- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '0' })})</small></Label>@@ -245,7 +249,7 @@ export default function Settings({<div className="flex justify-between"><Label htmlFor="pres-penalty-int" className="text-left text-sm font-medium">{localize('com_endpoint_presence_penalty')}{' '}- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '0' })})</small></Label>diff --git a/client/src/components/Endpoints/Settings/Assistants.tsx b/client/src/components/Endpoints/Settings/Assistants.tsxindex 1ae0f8cb41..96a65d5b86 100644--- a/client/src/components/Endpoints/Settings/Assistants.tsx+++ b/client/src/components/Endpoints/Settings/Assistants.tsx@@ -152,7 +152,9 @@ export default function Settings({ conversation, setOption, models, readonly }:<div className="grid w-full items-center gap-2"><Label htmlFor="promptPrefix" className="text-left text-sm font-medium">{localize('com_endpoint_prompt_prefix_assistants')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><TextareaAutosizeid="promptPrefix"@@ -169,7 +171,9 @@ export default function Settings({ conversation, setOption, models, readonly }:<div className="grid w-full items-center gap-2"><Label htmlFor="instructions" className="text-left text-sm font-medium">{localize('com_endpoint_instructions_assistants')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><TextareaAutosizeid="instructions"diff --git a/client/src/components/Endpoints/Settings/Examples.tsx b/client/src/components/Endpoints/Settings/Examples.tsxindex 1e32ff2f30..3855c2c5a6 100644--- a/client/src/components/Endpoints/Settings/Examples.tsx+++ b/client/src/components/Endpoints/Settings/Examples.tsx@@ -32,7 +32,9 @@ function Examples({ readonly, examples, setExample, addExample, removeExample }:<div className="grid w-full items-center gap-2"><Label htmlFor={`input-${idx}`} className="text-left text-sm font-medium">{localize('com_ui_input')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><TextareaAutosizeid={`input-${idx}`}@@ -57,7 +59,9 @@ function Examples({ readonly, examples, setExample, addExample, removeExample }:<div className="grid w-full items-center gap-2"><Label htmlFor={`output-${idx}`} className="text-left text-sm font-medium">{localize('com_endpoint_output')}{' '}- <small className="opacity-40">({localize('com_endpoint_default_blank')})</small>+ <small className="opacity-40 high-contrast:opacity-100">+ ({localize('com_endpoint_default_blank')})+ </small></Label><TextareaAutosizeid={`output-${idx}`}diff --git a/client/src/components/Endpoints/URLIcon.tsx b/client/src/components/Endpoints/URLIcon.tsxindex 3b78636b0f..e514bc8e46 100644--- a/client/src/components/Endpoints/URLIcon.tsx+++ b/client/src/components/Endpoints/URLIcon.tsx@@ -35,10 +35,10 @@ export const URLIcon = memo(</div>{imageError && iconURL && (<div- className="absolute flex items-center justify-center rounded-full bg-status-error"+ className="absolute flex items-center justify-center rounded-full bg-status-error-strong"style={{ width: '14px', height: '14px', top: 0, right: 0 }}>- <AlertCircle size={10} className="text-white" aria-hidden="true" />+ <AlertCircle size={10} className="text-text-on-status" aria-hidden="true" /></div>)}</div>diff --git a/client/src/components/Files/DeleteIconButton.tsx b/client/src/components/Files/DeleteIconButton.tsxindex 3d944e7094..a28b88e0d5 100644--- a/client/src/components/Files/DeleteIconButton.tsx+++ b/client/src/components/Files/DeleteIconButton.tsx@@ -8,10 +8,7 @@ type DeleteIconButtonProps = {export default function DeleteIconButton({ onClick }: DeleteIconButtonProps) {return (<div className="w-fit">- <Button- className="bg-surface-destructive p-3 hover:bg-surface-destructive-hover"- onClick={onClick}- >+ <Button variant="destructive" className="p-3" onClick={onClick}><TrashIcon /></Button></div>diff --git a/client/src/components/Input/SetKeyDialog/SetKeyDialog.tsx b/client/src/components/Input/SetKeyDialog/SetKeyDialog.tsxindex 440197dc86..4cb2b52105 100644--- a/client/src/components/Input/SetKeyDialog/SetKeyDialog.tsx+++ b/client/src/components/Input/SetKeyDialog/SetKeyDialog.tsx@@ -137,7 +137,7 @@ const RevokeKeysButton = ({variant="destructive"onClick={onClick}disabled={isLoading}- className="bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover"+ className="bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover">{isLoading ? <Spinner /> : localize('com_ui_revoke')}</Button>diff --git a/client/src/components/MCP/MCPServerStatusIcon.tsx b/client/src/components/MCP/MCPServerStatusIcon.tsxindex 8d6b0b01bd..1618972be3 100644--- a/client/src/components/MCP/MCPServerStatusIcon.tsx+++ b/client/src/components/MCP/MCPServerStatusIcon.tsx@@ -118,8 +118,11 @@ interface CompactStatusDotProps {function CompactStatusDot({ serverStatus, isInitializing }: CompactStatusDotProps) {if (isInitializing) {return (+ /** `status-info` rather than `-strong`: the strong slot is a neutral grey+ * in both standard palettes, so using it turned this blue dot grey. The+ * pulse takes the on-status ink so it inverts with the fill. */<div className="flex size-3.5 items-center justify-center rounded-full border-2 border-surface-secondary bg-status-info">- <div className="size-1.5 animate-pulse rounded-full bg-white" />+ <div className="size-1.5 animate-pulse rounded-full bg-text-on-status" /></div>);}diff --git a/client/src/components/Nav/Settings/Dialog.tsx b/client/src/components/Nav/Settings/Dialog.tsxindex c2d29132ae..af1bd2784a 100644--- a/client/src/components/Nav/Settings/Dialog.tsx+++ b/client/src/components/Nav/Settings/Dialog.tsx@@ -63,7 +63,10 @@ export default function SettingsDialog({ open, onOpenChange }: TDialogProps) {<div className="fixed inset-0 flex w-screen items-center justify-center p-4"><DialogPanelclassName={cn(- 'flex max-h-[85vh] w-full flex-col overflow-hidden rounded-2xl bg-surface-dialog shadow-2xl',+ /** Headless UI panel, so it bypasses the shared dialog primitives+ * and needs the contrast edge declared here. `shadow-2xl` is a+ * black shadow with nothing to separate against on a black canvas. */+ 'flex max-h-[85vh] w-full flex-col overflow-hidden rounded-2xl bg-surface-dialog shadow-2xl high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none','md:h-[85vh] md:w-[900px]',)}>diff --git a/client/src/components/Nav/Settings/registry.tsx b/client/src/components/Nav/Settings/registry.tsxindex ecd7f0b137..ba831ccbd2 100644--- a/client/src/components/Nav/Settings/registry.tsx+++ b/client/src/components/Nav/Settings/registry.tsx@@ -63,7 +63,15 @@ export const registry: SettingEntry[] = [tab: GENERAL,section: 'appearance',labelKey: 'com_nav_theme',- keywords: ['dark', 'light', 'appearance', 'color'],+ keywords: [+ 'dark',+ 'light',+ 'appearance',+ 'color',+ 'contrast',+ 'high contrast',+ 'accessibility',+ ],Component: ThemeSetting,},{diff --git a/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx b/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsxindex 29a4251afb..6eadb74f1d 100644--- a/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx+++ b/client/src/components/Nav/SettingsTabs/Account/DeleteAccount.tsx@@ -186,7 +186,7 @@ const renderDeleteButton = ('mt-4 w-full gap-0 bg-surface-tertiary text-text-primary transition-all duration-200 hover:bg-surface-tertiary',isLocked? 'cursor-not-allowed opacity-30 disabled:opacity-30'- : 'bg-surface-destructive text-white hover:bg-surface-destructive-hover disabled:opacity-100',+ : 'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover disabled:opacity-100',)}onClick={handleDeleteUser}disabled={isDeleting || isLocked}diff --git a/client/src/components/Nav/SettingsTabs/ApiKeys/DeleteKeyDialog.tsx b/client/src/components/Nav/SettingsTabs/ApiKeys/DeleteKeyDialog.tsxindex 271cee4e21..b07590b7ef 100644--- a/client/src/components/Nav/SettingsTabs/ApiKeys/DeleteKeyDialog.tsx+++ b/client/src/components/Nav/SettingsTabs/ApiKeys/DeleteKeyDialog.tsx@@ -58,7 +58,7 @@ export default function DeleteKeyDialog({selection={{selectHandler: handleDelete,selectClasses:- 'bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',selectText: deleteMutation.isLoading ? <Spinner /> : localize('com_ui_delete'),}}/>diff --git a/client/src/components/Nav/SettingsTabs/DangerButton.tsx b/client/src/components/Nav/SettingsTabs/DangerButton.tsxindex 9befd453b5..171e727cfb 100644--- a/client/src/components/Nav/SettingsTabs/DangerButton.tsx+++ b/client/src/components/Nav/SettingsTabs/DangerButton.tsx@@ -45,7 +45,7 @@ const DangerButton = (props: TDangerButtonProps, ref: ForwardedRef<HTMLButtonEledisabled={disabled}onClick={onClick}className={cn(- 'btn relative border-none bg-surface-destructive text-white hover:bg-surface-destructive-hover',+ 'btn relative border-none bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover',className,)}>diff --git a/client/src/components/Nav/SettingsTabs/Data/ClearChats.tsx b/client/src/components/Nav/SettingsTabs/Data/ClearChats.tsxindex a8377af58c..14994b5f9a 100644--- a/client/src/components/Nav/SettingsTabs/Data/ClearChats.tsx+++ b/client/src/components/Nav/SettingsTabs/Data/ClearChats.tsx@@ -54,7 +54,7 @@ export const ClearChats = () => {selection={{selectHandler: clearConvos,selectClasses:- 'bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',selectText: clearConvosMutation.isLoading ? <Spinner /> : localize('com_ui_delete'),}}/>diff --git a/client/src/components/Nav/SettingsTabs/Data/DeleteCache.tsx b/client/src/components/Nav/SettingsTabs/Data/DeleteCache.tsxindex 0865daef4e..46c2a96683 100644--- a/client/src/components/Nav/SettingsTabs/Data/DeleteCache.tsx+++ b/client/src/components/Nav/SettingsTabs/Data/DeleteCache.tsx@@ -67,7 +67,7 @@ export const DeleteCache = ({ disabled = false }: { disabled?: boolean }) => {selection={{selectHandler: revokeAllUserKeys,selectClasses:- 'bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',selectText: isLoading ? <Spinner /> : localize('com_ui_delete'),}}/>diff --git a/client/src/components/Nav/SettingsTabs/Data/RevokeKeys.tsx b/client/src/components/Nav/SettingsTabs/Data/RevokeKeys.tsxindex 8d3650b907..986f682644 100644--- a/client/src/components/Nav/SettingsTabs/Data/RevokeKeys.tsx+++ b/client/src/components/Nav/SettingsTabs/Data/RevokeKeys.tsx@@ -62,7 +62,7 @@ export const RevokeKeys = ({selection={{selectHandler: onClick,selectClasses:- 'bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',selectText: isLoading ? <Spinner /> : localize('com_ui_revoke'),}}/>diff --git a/client/src/components/Nav/SettingsTabs/Data/SharedLinks.tsx b/client/src/components/Nav/SettingsTabs/Data/SharedLinks.tsxindex 91ddf85467..03071b67d7 100644--- a/client/src/components/Nav/SettingsTabs/Data/SharedLinks.tsx+++ b/client/src/components/Nav/SettingsTabs/Data/SharedLinks.tsx@@ -345,7 +345,7 @@ export default function SharedLinks() {}selection={{selectHandler: confirmDelete,- selectClasses: `bg-surface-destructive hover:bg-surface-destructive-hover text-white ${+ selectClasses: `bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status ${deleteMutation.isLoading ? 'cursor-not-allowed opacity-80' : ''}`,selectText: deleteMutation.isLoading ? <Spinner /> : localize('com_ui_delete'),diff --git a/client/src/components/Nav/SettingsTabs/Speech/STT/DecibelSelector.tsx b/client/src/components/Nav/SettingsTabs/Speech/STT/DecibelSelector.tsxindex aab70e232e..de83f0b6e6 100755--- a/client/src/components/Nav/SettingsTabs/Speech/STT/DecibelSelector.tsx+++ b/client/src/components/Nav/SettingsTabs/Speech/STT/DecibelSelector.tsx@@ -15,7 +15,7 @@ export default function DecibelSelector() {<div className="flex items-center justify-between"><div id="decibel-selector-label">{localize('com_nav_db_sensitivity')}</div><div className="w-2" />- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '-45' })})</small></div>diff --git a/client/src/components/Nav/SettingsTabs/Speech/TTS/PlaybackRate.tsx b/client/src/components/Nav/SettingsTabs/Speech/TTS/PlaybackRate.tsxindex 6edd454514..7e1a55844f 100755--- a/client/src/components/Nav/SettingsTabs/Speech/TTS/PlaybackRate.tsx+++ b/client/src/components/Nav/SettingsTabs/Speech/TTS/PlaybackRate.tsx@@ -15,7 +15,7 @@ export default function DecibelSelector() {<div className="flex items-center justify-between"><div id="playback-rate-label">{localize('com_nav_playback_rate')}</div><div className="w-2" />- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default_with_num', { 0: '1' })})</small></div>diff --git a/client/src/components/Nav/ShortcutRecorder.tsx b/client/src/components/Nav/ShortcutRecorder.tsxindex d73ced5986..bd14a03028 100644--- a/client/src/components/Nav/ShortcutRecorder.tsx+++ b/client/src/components/Nav/ShortcutRecorder.tsx@@ -167,9 +167,9 @@ export function RecorderPill({state;let stateBorder = 'border-border-medium';if (hasConflict) {- stateBorder = 'border-amber-500/60';+ stateBorder = 'border-status-warning-border';} else if (showInvalid) {- stateBorder = 'animate-shortcut-shake border-red-500/60';+ stateBorder = 'animate-shortcut-shake border-border-destructive';}return (<div@@ -247,7 +247,7 @@ export function RecorderInfo({<spanclassName={cn('text-[11.5px]',- showInvalid ? 'text-red-600 dark:text-red-400' : 'text-text-secondary',+ showInvalid ? 'text-text-destructive' : 'text-text-secondary',)}>{showInvaliddiff --git a/client/src/components/Nav/__tests__/ShortcutRecorder.spec.tsx b/client/src/components/Nav/__tests__/ShortcutRecorder.spec.tsxnew file mode 100644index 0000000000..6d5ebb8d0c--- /dev/null+++ b/client/src/components/Nav/__tests__/ShortcutRecorder.spec.tsx@@ -0,0 +1,54 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { RecorderInfo, RecorderPill, useShortcutRecorder } from '../ShortcutRecorder';+import { bindingHash } from '~/utils/shortcuts';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++function Harness({ bindingMap = new Map() }: { bindingMap?: Map<string, string> }) {+ const state = useShortcutRecorder({+ initial: null,+ bindingMap,+ ownerId: 'test-action',+ getActionLabel: (id) => id,+ onSave: jest.fn(),+ onCancel: jest.fn(),+ });++ return (+ <>+ <RecorderPill state={state} ariaLabel="Shortcut recorder" ownerId="test-action" />+ <RecorderInfo+ state={state}+ ownerId="test-action"+ onCancel={jest.fn()}+ onSaveReplacing={jest.fn()}+ />+ </>+ );+}++describe('ShortcutRecorder', () => {+ it('uses semantic destructive roles when a shortcut has no modifier', () => {+ render(<Harness />);++ const recorder = screen.getByRole('textbox', { name: 'Shortcut recorder' });+ fireEvent.keyDown(recorder, { key: 'a' });++ expect(recorder).toHaveClass('border-border-destructive');+ expect(screen.getByText('com_shortcut_recorder_needs_modifier')).toHaveClass(+ 'text-text-destructive',+ );+ });++ it('uses the semantic warning border when a shortcut conflicts', () => {+ const binding = { meta: false, ctrl: true, alt: false, shift: false, key: 'A' };+ render(<Harness bindingMap={new Map([[bindingHash(binding), 'other-action']])} />);++ const recorder = screen.getByRole('textbox', { name: 'Shortcut recorder' });+ fireEvent.keyDown(recorder, { key: 'a', ctrlKey: true });++ expect(recorder).toHaveClass('border-status-warning-border');+ });+});diff --git a/client/src/components/Plugins/Store/PluginAuthForm.tsx b/client/src/components/Plugins/Store/PluginAuthForm.tsxindex 26ce0e4db9..de6b433cb3 100644--- a/client/src/components/Plugins/Store/PluginAuthForm.tsx+++ b/client/src/components/Plugins/Store/PluginAuthForm.tsx@@ -183,11 +183,7 @@ function PluginAuthForm({</span>)}{showHint && (- <span- id={`${authField}-hint`}- aria-live="polite"- className="text-amber-600 dark:text-amber-500"- >+ <span id={`${authField}-hint`} aria-live="polite" className="text-text-warning">{localize('com_ui_auth_format_hint', { 0: expectedPrefix })}</span>)}diff --git a/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx b/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsxindex 0b3c7402cc..41dc140648 100644--- a/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx+++ b/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx@@ -48,7 +48,7 @@ describe('PluginAuthForm', () => {expect(urlField.parentElement?.querySelector('button')).toBeNull();});- it('shows a format-hint placeholder for recognized credential fields', () => {+ it('shows a semantic warning for a recognized credential with the wrong format', async () => {const openAiPlugin = {pluginKey: 'dalle',authConfig: [{ authField: 'DALLE3_API_KEY||DALLE_API_KEY', label: 'OpenAI API Key' }],@@ -56,7 +56,12 @@ describe('PluginAuthForm', () => {//@ts-ignore - dont need all props of pluginrender(<PluginAuthForm plugin={openAiPlugin} onSubmit={onSubmit} />);- expect(screen.getByLabelText('OpenAI API Key')).toHaveAttribute('placeholder', 'sk-...');+ const input = screen.getByLabelText('OpenAI API Key');+ expect(input).toHaveAttribute('placeholder', 'sk-...');++ await userEvent.type(input, 'invalid-key');++ expect(document.getElementById('DALLE3_API_KEY-hint')).toHaveClass('text-text-warning');});it('calls the onSubmit function with the form data when submitted', async () => {diff --git a/client/src/components/Prompts/buttons/AdminSettings.tsx b/client/src/components/Prompts/buttons/AdminSettings.tsxindex 7168217694..f4145d997d 100644--- a/client/src/components/Prompts/buttons/AdminSettings.tsx+++ b/client/src/components/Prompts/buttons/AdminSettings.tsx@@ -60,7 +60,7 @@ const AdminSettings = () => {setConfirmAdminUseChange(null);},selectClasses:- 'bg-surface-destructive hover:bg-surface-destructive-hover text-white transition-colors duration-200',+ 'bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status transition-colors duration-200',selectText: localize('com_ui_confirm_action'),isLoading: false,}}diff --git a/client/src/components/Prompts/dialogs/DeletePrompt.tsx b/client/src/components/Prompts/dialogs/DeletePrompt.tsxindex fc855b43ca..e27b868cc0 100644--- a/client/src/components/Prompts/dialogs/DeletePrompt.tsx+++ b/client/src/components/Prompts/dialogs/DeletePrompt.tsx@@ -58,7 +58,7 @@ const DeleteConfirmDialog = ({selection={{selectHandler,selectClasses:- 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/Prompts/display/PromptVersions.tsx b/client/src/components/Prompts/display/PromptVersions.tsxindex 63eadc6f73..3f829a0ca7 100644--- a/client/src/components/Prompts/display/PromptVersions.tsx+++ b/client/src/components/Prompts/display/PromptVersions.tsx@@ -49,7 +49,7 @@ const VersionBadge = ({const getTimelineConnectorClasses = (isSelected: boolean, isProduction: boolean) => {if (isSelected) {- return 'border-status-success bg-status-success text-text-inverted';+ return 'border-status-success-strong bg-status-success-strong text-text-on-status';}if (isProduction) {return 'border-status-success-border bg-transparent text-status-success';diff --git a/client/src/components/Prompts/utils/CategoryIcon.spec.tsx b/client/src/components/Prompts/utils/CategoryIcon.spec.tsxnew file mode 100644index 0000000000..84594373fa--- /dev/null+++ b/client/src/components/Prompts/utils/CategoryIcon.spec.tsx@@ -0,0 +1,42 @@+import React from 'react';+import { render } from '@testing-library/react';+import CategoryIcon from './CategoryIcon';++const categoryColors = {+ code: 'text-series-5',+ misc: 'text-series-1',+ shop: 'text-series-6',+ idea: 'text-series-4',+ write: 'text-series-6',+ travel: 'text-series-4',+ finance: 'text-series-2',+ roleplay: 'text-series-2',+ teach_or_explain: 'text-series-1',+ general: 'text-series-1',+ hr: 'text-series-7',+ rd: 'text-series-6',+ it: 'text-series-5',+ sales: 'text-series-2',+ aftersales: 'text-series-4',+};++describe('CategoryIcon', () => {+ it.each(Object.entries(categoryColors))(+ 'uses the semantic series color for %s',+ (category, color) => {+ const { container } = render(<CategoryIcon category={category} />);+ const icon = container.querySelector('svg');++ expect(icon).toHaveClass(color);+ expect(icon?.getAttribute('class')).not.toMatch(+ /(?:dark:)?text-(?:red|blue|purple|yellow|orange|green)-/,+ );+ },+ );++ it('uses secondary text for an unknown category', () => {+ const { container } = render(<CategoryIcon category="unknown" />);++ expect(container.querySelector('svg')).toHaveClass('text-text-secondary');+ });+});diff --git a/client/src/components/Prompts/utils/CategoryIcon.tsx b/client/src/components/Prompts/utils/CategoryIcon.tsxindex 836ec7502d..4c826123dc 100644--- a/client/src/components/Prompts/utils/CategoryIcon.tsx+++ b/client/src/components/Prompts/utils/CategoryIcon.tsx@@ -35,21 +35,21 @@ const categoryIconMap: Record<string, React.ElementType> = {};const categoryColorMap: Record<string, string> = {- code: 'text-red-500',- misc: 'text-blue-300',- shop: 'text-purple-400',- idea: 'text-yellow-500/90 dark:text-yellow-300',- write: 'text-purple-400',- travel: 'text-yellow-500/90 dark:text-yellow-300',- finance: 'text-orange-400',- roleplay: 'text-orange-400',- teach_or_explain: 'text-blue-300',- general: 'text-blue-500',- hr: 'text-green-500',- rd: 'text-purple-500',- it: 'text-red-500',- sales: 'text-orange-500',- aftersales: 'text-yellow-500',+ code: 'text-series-5',+ misc: 'text-series-1',+ shop: 'text-series-6',+ idea: 'text-series-4',+ write: 'text-series-6',+ travel: 'text-series-4',+ finance: 'text-series-2',+ roleplay: 'text-series-2',+ teach_or_explain: 'text-series-1',+ general: 'text-series-1',+ hr: 'text-series-7',+ rd: 'text-series-6',+ it: 'text-series-5',+ sales: 'text-series-2',+ aftersales: 'text-series-4',};export default function CategoryIcon({diff --git a/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx b/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsxindex b4cb5f96b2..b5c4a66fda 100644--- a/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx+++ b/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx@@ -20,22 +20,24 @@ const PeoplePickerSearchItem = forwardRef<HTMLDivElement, PeoplePickerSearchItemconst displayName = name || localize('com_ui_unknown');const subtitle = email || `${type} (${principal.source || 'local'})`;- /** Get badge styling based on type */+ /** Semantic series roles rather than palette hues: a raw utility does not+ * move when the theme does, and these labels render at 12px, so they answer+ * to the text floor on whichever canvas the viewer picked. */const getBadgeConfig = () => {switch (type) {case PrincipalType.USER:return {- className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300',+ className: 'bg-series-1/10 text-series-1',label: localize('com_ui_user'),};case PrincipalType.GROUP:return {- className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300',+ className: 'bg-series-7/10 text-series-7',label: localize('com_ui_group'),};case PrincipalType.ROLE:return {- className: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300',+ className: 'bg-series-6/10 text-series-6',label: localize('com_ui_role'),};default:diff --git a/client/src/components/SidePanel/Agents/ActionsInput.tsx b/client/src/components/SidePanel/Agents/ActionsInput.tsxindex 4d32acb714..e65c9d0208 100644--- a/client/src/components/SidePanel/Agents/ActionsInput.tsx+++ b/client/src/components/SidePanel/Agents/ActionsInput.tsx@@ -269,7 +269,7 @@ export default function ActionsInput({className="block min-h-[12rem] w-full resize-y rounded-lg border border-border-light bg-transparent p-3 font-mono text-xs leading-relaxed transition-colors focus-visible:border-border-heavy focus-visible:ring-0"/>{validationError && (- <div className="mt-1.5 text-xs text-red-500">+ <div className="mt-1.5 text-xs text-text-destructive">{validationError.split('\n').map((line: string, i: number) => (<div key={i}>{line}</div>))}@@ -323,7 +323,7 @@ export default function ActionsInput({/></div>{validationError && (- <div className="max-h-24 shrink-0 overflow-y-auto text-xs text-red-500">+ <div className="max-h-24 shrink-0 overflow-y-auto text-xs text-text-destructive">{validationError.split('\n').map((line: string, i: number) => (<div key={i}>{line}</div>))}diff --git a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsxindex 6aa881100c..e4d82fce1a 100644--- a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx+++ b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx@@ -10,13 +10,20 @@ export type Spec = {domain: string;};-/** Color-codes the HTTP verb the way API docs do, so the method reads at a glance. */+/**+ * Color-codes the HTTP verb the way API docs do, so the method reads at a+ * glance. The hues come from the categorical series ramp, which is what that+ * scale is for: identity rather than status, contrast-checked per mode, and+ * separable under simulated deuteranopia. Slots are chosen to stay close to the+ * conventional verb colours. `delete` is the one exception, taking the error+ * role, because destructive really is a status.+ */const METHOD_STYLES: Record<string, string> = {- get: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',- post: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',- put: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',- patch: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',- delete: 'bg-red-500/10 text-red-600 dark:text-red-400',+ get: 'bg-series-1/10 text-series-1',+ post: 'bg-series-7/10 text-series-7',+ put: 'bg-series-4/10 text-series-4',+ patch: 'bg-series-6/10 text-series-6',+ delete: 'bg-status-error-subtle text-status-error',};function HeaderCell({ labelKey }: { labelKey: TranslationKeys }) {diff --git a/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx b/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsxindex 85588b76f6..227dc96403 100644--- a/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx@@ -84,7 +84,7 @@ export default function AdvancedPanel() {<Copy className="h-3.5 w-3.5" aria-hidden="true" /></span><span className="t-icon" data-icon="b">- <Check className="h-3.5 w-3.5 text-green-500" aria-hidden="true" />+ <Check className="h-3.5 w-3.5 text-status-success" aria-hidden="true" /></span></span></Button>diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsxindex 98c2331eb5..8cdaadede9 100644--- a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx@@ -158,7 +158,7 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId,</div>{nothingToSpawn && (- <p className="flex items-center gap-2 text-xs italic text-amber-600 dark:text-amber-400">+ <p className="flex items-center gap-2 text-xs italic text-text-warning"><Users size={14} aria-hidden="true" />{localize('com_ui_agent_subagents_empty')}</p>diff --git a/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx b/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsxindex 8280fc2a64..be3e5a4279 100644--- a/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx@@ -102,4 +102,10 @@ describe('AgentSubagents', () => {),);});++ it('uses the semantic warning role for an empty configuration', () => {+ render(<Harness />);++ expect(screen.getByText('com_ui_agent_subagents_empty')).toHaveClass('text-text-warning');+ });});diff --git a/client/src/components/SidePanel/Agents/Advanced/ui.tsx b/client/src/components/SidePanel/Agents/Advanced/ui.tsxindex 1b46cd7892..aed8c1b3f9 100644--- a/client/src/components/SidePanel/Agents/Advanced/ui.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/ui.tsx@@ -23,11 +23,18 @@ export function CountPill({ children }: { children: ReactNode }) {);}-/** "Beta" accent pill. */+/**+ * "Beta" accent pill.+ *+ * Semantic `brand-purple` rather than the raw purple ramp: the label renders at+ * 10px on a tinted fill, so it has to keep clearing the text floor on every+ * canvas, and `purple-600/40` edges sit at 1.89:1 on the high contrast light+ * page. A palette utility does not move when the theme does.+ */export function BetaPill() {const localize = useLocalize();return (- <span className="rounded-full border border-purple-600/40 bg-purple-500/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-purple-700 dark:text-purple-400">+ <span className="rounded-full border border-brand-purple/40 bg-brand-purple/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-brand-purple">{localize('com_ui_beta')}</span>);diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsxindex febfae371a..c5a19a5c46 100644--- a/client/src/components/SidePanel/Agents/AgentConfig.tsx+++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx@@ -65,7 +65,11 @@ export default function AgentConfig() {aria-describedby={errors.name ? 'agent-name-error' : undefined}/>{errors.name && (- <div id="agent-name-error" className="mt-1 text-xs text-red-500" role="alert">+ <div+ id="agent-name-error"+ className="mt-1 text-xs text-text-destructive"+ role="alert"+ >{errors.name.message}</div>)}@@ -98,7 +102,7 @@ export default function AgentConfig() {className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary"htmlFor="provider">- {localize('com_ui_model')} <span className="text-red-500">*</span>+ {localize('com_ui_model')} <span className="text-text-destructive">*</span></Label><buttonid="provider"@@ -132,7 +136,7 @@ export default function AgentConfig() {className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary"htmlFor="category-selector">- {localize('com_ui_category')} <span className="text-red-500">*</span>+ {localize('com_ui_category')} <span className="text-text-destructive">*</span></Label><AgentCategorySelector className="w-full rounded-lg" /></div>@@ -171,7 +175,7 @@ export default function AgentConfig() {<Input{...field}value={field.value ?? ''}- className={cn(fieldClass, error && 'border-2 border-red-500')}+ className={cn(fieldClass, error && 'border-2 border-border-destructive')}id="support-contact-name"type="text"placeholder={localize('com_ui_support_contact_name_placeholder')}@@ -182,7 +186,7 @@ export default function AgentConfig() {{error && (<spanid="support-contact-name-error"- className="mt-1 text-xs text-red-500"+ className="mt-1 text-xs text-text-destructive"role="alert"aria-live="polite">@@ -204,7 +208,7 @@ export default function AgentConfig() {<Input{...field}value={field.value ?? ''}- className={cn(fieldClass, error && 'border-2 border-red-500')}+ className={cn(fieldClass, error && 'border-2 border-border-destructive')}id="support-contact-email"type="email"placeholder={localize('com_ui_support_contact_email_placeholder')}@@ -215,7 +219,7 @@ export default function AgentConfig() {{error && (<spanid="support-contact-email-error"- className="mt-1 text-xs text-red-500"+ className="mt-1 text-xs text-text-destructive"role="alert"aria-live="polite">diff --git a/client/src/components/SidePanel/Agents/AgentSelect.tsx b/client/src/components/SidePanel/Agents/AgentSelect.tsxindex 9dfcd466c8..21190c5f3b 100644--- a/client/src/components/SidePanel/Agents/AgentSelect.tsx+++ b/client/src/components/SidePanel/Agents/AgentSelect.tsx@@ -64,7 +64,7 @@ function AgentSelect({provider: createProviderOption(fullAgent.provider),label: fullAgent.name ?? '',value: fullAgent.id || '',- icon: isGlobal ? <EarthIcon className={'icon-lg text-green-400'} /> : null,+ icon: isGlobal ? <EarthIcon className="icon-lg text-status-success" /> : null,};const capabilities: TAgentCapabilities = {diff --git a/client/src/components/SidePanel/Agents/AgentTool.tsx b/client/src/components/SidePanel/Agents/AgentTool.tsxindex b20ae74461..3e0f56b3ce 100644--- a/client/src/components/SidePanel/Agents/AgentTool.tsx+++ b/client/src/components/SidePanel/Agents/AgentTool.tsx@@ -140,7 +140,8 @@ export default function AgentTool({}selection={{selectHandler: () => removeTool(tool),- selectClasses: 'bg-surface-destructive hover:bg-surface-destructive-hover text-white',+ selectClasses:+ 'bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Agents/DeleteButton.tsx b/client/src/components/SidePanel/Agents/DeleteButton.tsxindex 93da129175..357b3d2daf 100644--- a/client/src/components/SidePanel/Agents/DeleteButton.tsx+++ b/client/src/components/SidePanel/Agents/DeleteButton.tsx@@ -125,7 +125,8 @@ function DeleteButton({}selection={{selectHandler: () => deleteAgent.mutate({ agent_id }),- selectClasses: 'bg-surface-destructive hover:bg-surface-destructive-hover text-white',+ selectClasses:+ 'bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Agents/MCPToolItem.tsx b/client/src/components/SidePanel/Agents/MCPToolItem.tsxindex b8d971de06..4ba7fb4c7c 100644--- a/client/src/components/SidePanel/Agents/MCPToolItem.tsx+++ b/client/src/components/SidePanel/Agents/MCPToolItem.tsx@@ -88,7 +88,7 @@ export default function MCPToolItem({pressed={isDeferred}label={localize('com_ui_mcp_defer_loading')}tooltip={localize('com_ui_mcp_click_to_defer')}- activeClass="text-text-warning"+ activeBorderClass="border-series-4"onToggle={onToggleDefer}/>)}@@ -102,7 +102,7 @@ export default function MCPToolItem({? 'com_ui_mcp_click_to_programmatic': 'com_ui_mcp_programmatic_requires_code',)}- activeClass="text-violet-500"+ activeBorderClass="border-series-6"disabled={!programmaticToolsAvailable && !isProgrammatic}onToggle={onToggleProgrammatic}/>@@ -113,7 +113,7 @@ export default function MCPToolItem({pressed={isBackground}label={localize('com_ui_mcp_background')}tooltip={localize('com_ui_mcp_click_to_background')}- activeClass="text-sky-500"+ activeBorderClass="border-series-1"onToggle={onToggleBackground}/>)}@@ -126,7 +126,7 @@ export default function MCPToolItem({tooltip={localize(intentDisabled ? 'com_ui_mcp_intent_programmatic' : 'com_ui_mcp_click_to_intent',)}- activeClass="text-teal-500"+ activeBorderClass="border-series-3"onToggle={onToggleIntent}/>)}diff --git a/client/src/components/SidePanel/Agents/ModelPanel.tsx b/client/src/components/SidePanel/Agents/ModelPanel.tsxindex ed5442641c..cb4478062b 100644--- a/client/src/components/SidePanel/Agents/ModelPanel.tsx+++ b/client/src/components/SidePanel/Agents/ModelPanel.tsx@@ -128,7 +128,7 @@ export default function ModelPanel({)}htmlFor="provider">- {localize('com_ui_provider')} <span className="text-red-500">*</span>+ {localize('com_ui_provider')} <span className="text-text-destructive">*</span></label><Controllername="provider"@@ -171,14 +171,14 @@ export default function ModelPanel({label: typeof provider === 'string' ? provider : provider.label,value: typeof provider === 'string' ? provider : provider.value,}))}- className={cn(error ? 'border-2 border-red-500' : '')}+ className={cn(error ? 'border-2 border-border-destructive' : '')}ariaLabel={localize('com_ui_provider')}disabled={selectionDisabled}isCollapsed={false}showCarat={true}/>{error && (- <span className="mt-1 text-xs text-red-500" role="alert">+ <span className="mt-1 text-xs text-text-destructive" role="alert">{localize('com_ui_field_required')}</span>)}@@ -197,7 +197,7 @@ export default function ModelPanel({)}htmlFor="model">- {localize('com_ui_model')} <span className="text-red-500">*</span>+ {localize('com_ui_model')} <span className="text-text-destructive">*</span></label><Controllername="model"@@ -225,13 +225,16 @@ export default function ModelPanel({value: model,}))}disabled={!provider || selectionDisabled}- className={cn('disabled:opacity-50', error ? 'border-2 border-red-500' : '')}+ className={cn(+ 'disabled:opacity-50',+ error ? 'border-2 border-border-destructive' : '',+ )}ariaLabel={localize('com_ui_model')}isCollapsed={false}showCarat={true}/>{provider && error && (- <span className="mt-1 text-xs text-red-500" role="alert">+ <span className="mt-1 text-xs text-text-destructive" role="alert">{localize('com_ui_field_required')}</span>)}diff --git a/client/src/components/SidePanel/Agents/OptionToggle.tsx b/client/src/components/SidePanel/Agents/OptionToggle.tsxindex e45dc5a333..f6bd19c23a 100644--- a/client/src/components/SidePanel/Agents/OptionToggle.tsx+++ b/client/src/components/SidePanel/Agents/OptionToggle.tsx@@ -8,8 +8,8 @@ interface OptionToggleProps {label: string;/** Defaults to `label` (bulk toggles use the same text for both). */tooltip?: string;- /** Text color applied directly to the icon when pressed. */- activeClass: string;+ /** Semantic series border applied to the pressed button. */+ activeBorderClass: string;onToggle: () => void;size?: 'sm' | 'md';/**@@ -30,11 +30,35 @@ export default function OptionToggle({pressed,label,tooltip,- activeClass,+ activeBorderClass,onToggle,size = 'sm',disabled = false,}: OptionToggleProps) {+ /**+ * Pressed and disabled compose rather than override each other: a tool the+ * user switched to programmatic-only keeps its stored Intent state, and+ * `aria-pressed` keeps reporting it, so the control has to keep looking+ * pressed. Collapsing to the unpressed treatment would hide a setting that+ * becomes active again the moment programmatic mode is lifted.+ */+ let stateClass: string;+ if (pressed) {+ stateClass = cn(+ activeBorderClass,+ 'bg-surface-active text-text-primary',+ disabled+ ? 'cursor-not-allowed opacity-60 hover:bg-surface-active hover:text-text-primary'+ : 'hover:bg-surface-active-alt hover:text-text-primary',+ );+ } else if (disabled) {+ stateClass =+ 'cursor-not-allowed border-transparent text-text-tertiary opacity-60 hover:bg-transparent hover:text-text-tertiary';+ } else {+ stateClass =+ 'border-transparent text-text-secondary hover:bg-surface-hover hover:text-text-secondary';+ }+return (<TooltipAnchordescription={tooltip ?? label}@@ -47,15 +71,9 @@ export default function OptionToggle({aria-pressed={pressed}aria-label={label}aria-disabled={disabled || undefined}- className={cn(- 'rounded-md',- size === 'sm' ? 'size-6' : 'size-7',- disabled- ? 'cursor-not-allowed text-text-tertiary opacity-60 hover:bg-transparent hover:text-text-tertiary'- : 'text-text-secondary hover:bg-surface-hover hover:text-text-secondary',- )}+ className={cn('rounded-md border', size === 'sm' ? 'size-6' : 'size-7', stateClass)}>- <Icon className={cn('size-4', pressed && activeClass)} aria-hidden="true" />+ <Icon className="size-4" aria-hidden="true" /></Button>}/>diff --git a/client/src/components/SidePanel/Agents/Search/Action.tsx b/client/src/components/SidePanel/Agents/Search/Action.tsxindex 638f55d124..fb5dc8d9cf 100644--- a/client/src/components/SidePanel/Agents/Search/Action.tsx+++ b/client/src/components/SidePanel/Agents/Search/Action.tsx@@ -65,7 +65,7 @@ export default function Action({><MorphIconicon={isToolAuthenticated ? CircleCheck : KeyRound}- className={cn('h-4 w-4', isToolAuthenticated && 'text-green-500')}+ className={cn('h-4 w-4', isToolAuthenticated && 'text-status-success')}/>{localize(isToolAuthenticateddiff --git a/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.test.tsx b/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.test.tsxindex 8db1f888c1..fca0ca3fc1 100644--- a/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.test.tsx+++ b/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.test.tsx@@ -141,10 +141,18 @@ describe('ApiKeyDialog', () => {mockUseGetStartupConfig.mockReturnValue({ data: {} });render(<ApiKeyDialog {...defaultProps} />);// Default is Jina- expect(screen.getByText('com_ui_web_search_reranker_jina_key')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'com_ui_web_search_reranker_jina_key' })).toHaveClass(+ 'text-link',+ 'underline',+ 'hover:text-link-hover',+ );// Switch to CoherefireEvent.click(screen.getByText('com_ui_web_search_reranker_cohere'));- expect(screen.getByText('com_ui_web_search_reranker_cohere_key')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'com_ui_web_search_reranker_cohere_key' })).toHaveClass(+ 'text-link',+ 'underline',+ 'hover:text-link-hover',+ );});it('does not render provider section if SYSTEM_DEFINED', () => {diff --git a/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsx b/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsxindex c7f7a86e39..90eb729223 100644--- a/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsx+++ b/client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsx@@ -358,7 +358,7 @@ export default function ApiKeyDialog({}selection={{selectHandler: handleSubmit(handleVisibleSubmit),- selectClasses: 'bg-surface-submit hover:bg-surface-submit-hover text-white',+ selectClasses: 'bg-surface-submit hover:bg-surface-submit-hover text-text-on-status',selectText: localize('com_ui_save'),}}buttons={diff --git a/client/src/components/SidePanel/Agents/Search/InputSection.tsx b/client/src/components/SidePanel/Agents/Search/InputSection.tsxindex 8dfc40e920..166e13564b 100644--- a/client/src/components/SidePanel/Agents/Search/InputSection.tsx+++ b/client/src/components/SidePanel/Agents/Search/InputSection.tsx@@ -103,7 +103,7 @@ export default function InputSection({href={config.link.url}target="_blank"rel="noopener noreferrer"- className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"+ className="text-link underline hover:text-link-hover">{config.link.text}</a>diff --git a/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsx b/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsxindex 244605a395..baa248b6d7 100644--- a/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsx@@ -132,7 +132,7 @@ export default function ActionEditor({});},selectClasses:- 'bg-surface-destructive text-white transition-colors duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-colors duration-200 hover:bg-surface-destructive-hover',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsxindex 8b03aa2443..72cee824ed 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx@@ -14,6 +14,7 @@ const mockIsConnectionDeferred = jest.fn((): boolean => false);const mockToggleIntentAll = jest.fn();const mockIsToolProgrammaticOnly = jest.fn((_toolId: string): boolean => false);const mockAreAllToolsProgrammatic = jest.fn((): boolean => false);+const mockAreAllToolsBackground = jest.fn((): boolean => false);const mockCapabilities = {codeEnabled: false,deferredToolsEnabled: false,@@ -76,7 +77,7 @@ jest.mock('~/hooks', () => ({toggleToolIntent: jest.fn(),areAllToolsDeferred: () => false,areAllToolsProgrammatic: mockAreAllToolsProgrammatic,- areAllToolsBackground: () => false,+ areAllToolsBackground: mockAreAllToolsBackground,areAllToolsIntent: () => false,toggleDeferAll: jest.fn(),toggleProgrammaticAll: jest.fn(),@@ -182,6 +183,8 @@ describe('McpSection', () => {mockIsToolProgrammaticOnly.mockReturnValue(false);mockAreAllToolsProgrammatic.mockReset();mockAreAllToolsProgrammatic.mockReturnValue(false);+ mockAreAllToolsBackground.mockReset();+ mockAreAllToolsBackground.mockReturnValue(false);mockGetToolOptions.mockReset();mockGetToolOptions.mockReturnValue(undefined);mockMcpServersMap.mockReset();@@ -477,6 +480,19 @@ describe('McpSection', () => {).not.toHaveAttribute('aria-disabled');});+ test('bulk background toggle uses the shared semantic pressed state', () => {+ mockCapabilities.backgroundToolsEnabled = true;+ mockAreAllToolsBackground.mockReturnValue(true);++ render(<McpSection item={item} />);++ expect(screen.getByRole('button', { name: 'com_ui_mcp_unbackground_all' })).toHaveClass(+ 'border-series-1',+ 'bg-surface-active',+ 'text-text-primary',+ );+ });+test('bulk intent skips programmatic-only tools (label can never reach them)', () => {mockCapabilities.toolIntentsEnabled = true;mockIsToolProgrammaticOnly.mockImplementation((toolId: string) => toolId === 'mcp:srv:a');diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsxindex accc7941b3..204915bd7a 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx@@ -494,7 +494,7 @@ export default function McpSection({ item }: Props) {size="md"pressed={allDeferred}label={localize(allDeferred ? 'com_ui_mcp_undefer_all' : 'com_ui_mcp_defer_all')}- activeClass="text-amber-600 dark:text-amber-500"+ activeBorderClass="border-series-4"onToggle={() => toggleDeferAll(tools)}/>)}@@ -504,7 +504,7 @@ export default function McpSection({ item }: Props) {size="md"pressed={allProgrammatic}label={programmaticBulkLabel}- activeClass="text-violet-600 dark:text-violet-500"+ activeBorderClass="border-series-6"tooltip={programmaticBulkTooltip}disabled={!programmaticToolsAvailable && !allProgrammatic}onToggle={() => toggleProgrammaticAll(tools)}@@ -518,7 +518,7 @@ export default function McpSection({ item }: Props) {label={localize(allBackground ? 'com_ui_mcp_unbackground_all' : 'com_ui_mcp_background_all',)}- activeClass="text-sky-600 dark:text-sky-500"+ activeBorderClass="border-series-1"onToggle={() => toggleBackgroundAll(tools)}/>)}@@ -529,7 +529,7 @@ export default function McpSection({ item }: Props) {pressed={allIntent}disabled={intentEligibleTools.length === 0}label={localize(allIntent ? 'com_ui_mcp_unintent_all' : 'com_ui_mcp_intent_all')}- activeClass="text-teal-600 dark:text-teal-500"+ activeBorderClass="border-series-3"onToggle={() => toggleIntentAll(intentEligibleTools)}/>)}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsxindex 228764e550..e6311b6b92 100644--- a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsx@@ -81,7 +81,7 @@ export default function ToolSection({ item }: Props) {{showConfigured && (<div className="flex items-center justify-between rounded-xl border border-border-light bg-surface-secondary px-3 py-2.5"><span className="flex items-center gap-2 text-sm font-medium text-text-primary">- <CheckCircle2 className="size-4 text-emerald-500" aria-hidden="true" />+ <CheckCircle2 className="size-4 text-status-success" aria-hidden="true" />{localize('com_ui_tools_info_configured')}</span><Buttondiff --git a/client/src/components/SidePanel/Agents/Tools/ToolCard.tsx b/client/src/components/SidePanel/Agents/Tools/ToolCard.tsxindex 6bb5779db6..d3faf7541a 100644--- a/client/src/components/SidePanel/Agents/Tools/ToolCard.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ToolCard.tsx@@ -108,7 +108,7 @@ function ToolCardImpl({className={cn('group relative flex h-32 w-full flex-col overflow-hidden rounded-2xl border',selected- ? 'border-emerald-500/60 bg-emerald-500/[0.06] shadow-sm'+ ? 'border-status-success bg-status-success/10 shadow-sm': 'border-border-light bg-transparent hover:border-border-medium hover:bg-surface-tertiary hover:shadow-sm',)}>@@ -129,7 +129,7 @@ function ToolCardImpl({<span className="truncate">{name}</span>{isNative && (<BadgeCheck- className="size-4 shrink-0 fill-emerald-500 text-white dark:text-surface-primary"+ className="size-4 shrink-0 fill-status-success-strong text-text-on-status"strokeWidth={2}aria-label={localize('com_ui_tools_native')}/>@@ -137,7 +137,7 @@ function ToolCardImpl({</p>{selected && (<span- className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500 text-white"+ className="flex size-5 shrink-0 items-center justify-center rounded-full bg-status-success-strong text-text-on-status"aria-hidden="true"><Check className="size-3" strokeWidth={3} />@@ -226,8 +226,7 @@ function ToolCardImpl({'opacity-0 transition duration-150 hover:bg-surface-hover hover:text-text-primary','group-focus-within:opacity-100 group-hover:opacity-100','focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary',- isFavorited &&- 'text-amber-600 opacity-100 hover:text-amber-500 dark:text-amber-500 dark:hover:text-amber-400',+ isFavorited && 'text-series-4 opacity-100 hover:text-series-4',)}><Star className={cn('size-4', isFavorited && 'fill-current')} aria-hidden="true" />diff --git a/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsxindex 4e7634a5d8..46c0a4a5fd 100644--- a/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx@@ -443,7 +443,7 @@ export default function ToolsSection({ agentId }: Props) {selection={{selectHandler: confirmActionRemoval,selectClasses:- 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>@@ -468,7 +468,7 @@ export default function ToolsSection({ agentId }: Props) {selection={{selectHandler: confirmMcpRemoval,selectClasses:- 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx b/client/src/components/SidePanel/Agents/Version/VersionItem.tsxindex 8756b60474..317247c528 100644--- a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionItem.tsx@@ -95,7 +95,7 @@ export default function VersionItem({<divclassName={cn('absolute -bottom-3 top-0 w-px',- isActive ? 'bg-green-500/40' : 'bg-border-light',+ isActive ? 'bg-status-success-strong' : 'bg-border-light',)}/>)}@@ -103,7 +103,7 @@ export default function VersionItem({className={cn('relative z-10 mt-4 flex size-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors',isActive- ? 'border-green-500 bg-green-500 text-white'+ ? 'border-status-success-strong bg-status-success-strong text-text-on-status': 'border-border-medium bg-surface-primary text-text-secondary',)}aria-hidden="true"@@ -121,7 +121,7 @@ export default function VersionItem({className={cn('group relative mb-2 ml-2 flex flex-1 flex-col rounded-xl border p-3 transition-colors',isActive- ? 'border-green-500/40 bg-green-50/60 dark:border-green-500/30 dark:bg-green-950/20'+ ? 'border-status-success-border bg-status-success-subtle': 'border-border-light bg-transparent hover:border-border-medium hover:bg-surface-secondary',)}>@@ -131,14 +131,17 @@ export default function VersionItem({<spanclassName={cn('truncate text-sm font-semibold',- isActive ? 'text-green-700 dark:text-green-300' : 'text-text-primary',+ isActive ? 'text-status-success' : 'text-text-primary',)}>{versionTitle}</span>{isActive && (- <span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-green-700 dark:text-green-300">- <span className="size-1.5 rounded-full bg-green-500" aria-hidden="true" />+ <span className="inline-flex items-center gap-1 rounded-full bg-status-success-subtle px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-status-success">+ <span+ className="size-1.5 rounded-full bg-status-success-strong"+ aria-hidden="true"+ />{localize('com_ui_agent_version_current')}</span>)}@@ -203,7 +206,7 @@ export default function VersionItem({selection={{selectHandler: () => onRestore(index),selectClasses:- 'bg-green-600 hover:bg-green-700 dark:hover:bg-green-700 text-white',+ 'bg-surface-submit hover:bg-surface-submit-hover text-text-on-status',selectText: localize('com_ui_agent_version_restore'),}}/>diff --git a/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsxindex deedff10a7..951c27486c 100644--- a/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsx@@ -24,6 +24,42 @@ const tool = {metadata: { name: 'execute', description: 'Runs JavaScript code against the API.' },} as unknown as AgentToolType;+const pressedOptions: Array<{+ name: string;+ overrides: Partial<React.ComponentProps<typeof MCPToolItem>>;+ label: string;+ border: string;+}> = [+ {+ name: 'deferred',+ overrides: { deferredToolsEnabled: true, isDeferred: true },+ label: 'com_ui_mcp_defer_loading',+ border: 'border-series-4',+ },+ {+ name: 'programmatic',+ overrides: {+ programmaticToolsEnabled: true,+ programmaticToolsAvailable: true,+ isProgrammatic: true,+ },+ label: 'com_ui_mcp_programmatic',+ border: 'border-series-6',+ },+ {+ name: 'background',+ overrides: { backgroundToolsEnabled: true, isBackground: true },+ label: 'com_ui_mcp_background',+ border: 'border-series-1',+ },+ {+ name: 'intent',+ overrides: { toolIntentsEnabled: true, isIntent: true },+ label: 'com_ui_mcp_intent',+ border: 'border-series-3',+ },+];+function setup(overrides: Partial<React.ComponentProps<typeof MCPToolItem>> = {}) {const props = {tool,@@ -94,11 +130,19 @@ describe('MCPToolItem', () => {expect(props.onToggleDefer).toHaveBeenCalledTimes(1);});- test('deferred tool keeps its warning color while hovered', () => {- setup({ deferredToolsEnabled: true, isDeferred: true });- const deferButton = screen.getByRole('button', { name: 'com_ui_mcp_defer_loading' });- expect(deferButton).toHaveClass('hover:text-text-secondary');- expect(deferButton.querySelector('svg')).toHaveClass('text-text-warning');+ test.each(pressedOptions)('$name option uses a semantic pressed-state border', (option) => {+ setup(option.overrides);+ const button = screen.getByRole('button', { name: option.label });++ expect(button).toHaveClass(+ option.border,+ 'bg-surface-active',+ 'text-text-primary',+ 'hover:bg-surface-active-alt',+ );+ expect(button.querySelector('svg')?.className.baseVal).not.toMatch(+ /text-(?:amber|violet|sky|teal)-/,+ );});test('defer button is absent when deferred tools are disabled', () => {diff --git a/client/src/components/SidePanel/Agents/__tests__/OptionToggle.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/OptionToggle.spec.tsxnew file mode 100644index 0000000000..32baa11f3d--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/OptionToggle.spec.tsx@@ -0,0 +1,81 @@+import '@testing-library/jest-dom/extend-expect';+import React from 'react';+import { Circle } from 'lucide-react';+import { render, screen } from '@testing-library/react';+import OptionToggle from '../OptionToggle';++jest.mock('@librechat/client', () => ({+ TooltipAnchor: ({ render }: { render: React.ReactElement }) => render,+ Button: ({+ children,+ variant: _variant,+ size: _size,+ ...props+ }: React.ComponentProps<'button'> & { variant?: string; size?: string }) => (+ <button {...props}>{children}</button>+ ),+}));++describe('OptionToggle', () => {+ it('gives the pressed state a semantic surface, foreground, and series border', () => {+ render(+ <OptionToggle+ icon={Circle}+ pressed={true}+ label="Background"+ activeBorderClass="border-series-1"+ onToggle={jest.fn()}+ />,+ );++ const button = screen.getByRole('button', { name: 'Background' });+ expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(button).toHaveClass(+ 'border',+ 'border-series-1',+ 'bg-surface-active',+ 'text-text-primary',+ 'hover:bg-surface-active-alt',+ );+ expect(button.querySelector('svg')).toHaveClass('size-4');+ expect(button.querySelector('svg')).not.toHaveClass('text-series-1');+ });++ it('keeps the unpressed state neutral and transparent', () => {+ render(+ <OptionToggle+ icon={Circle}+ pressed={false}+ label="Background"+ activeBorderClass="border-series-1"+ onToggle={jest.fn()}+ />,+ );++ const button = screen.getByRole('button', { name: 'Background' });+ expect(button).toHaveAttribute('aria-pressed', 'false');+ expect(button).toHaveClass('border-transparent', 'text-text-secondary');+ expect(button).not.toHaveClass('border-series-1', 'bg-surface-active');+ });++ /** A tool switched to programmatic-only keeps its stored Intent state and+ * keeps reporting it through `aria-pressed`, so the disabled treatment has to+ * layer over the pressed one instead of replacing it. */+ it('keeps the pressed treatment while disabled', () => {+ render(+ <OptionToggle+ icon={Circle}+ pressed={true}+ disabled={true}+ label="Intent"+ activeBorderClass="border-series-1"+ onToggle={jest.fn()}+ />,+ );++ const button = screen.getByRole('button', { name: 'Intent' });+ expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(button).toHaveClass('border-series-1', 'bg-surface-active', 'cursor-not-allowed');+ expect(button).not.toHaveClass('border-transparent');+ });+});diff --git a/client/src/components/SidePanel/Bookmarks/BookmarkCardActions.tsx b/client/src/components/SidePanel/Bookmarks/BookmarkCardActions.tsxindex 2afdf49814..70a4d179f3 100644--- a/client/src/components/SidePanel/Bookmarks/BookmarkCardActions.tsx+++ b/client/src/components/SidePanel/Bookmarks/BookmarkCardActions.tsx@@ -108,7 +108,7 @@ export default function BookmarkCardActions({ bookmark }: BookmarkCardActionsProselection={{selectHandler: confirmDelete,selectClasses:- 'bg-surface-destructive text-white transition-all duration-200 hover:bg-surface-destructive-hover',+ 'bg-surface-destructive text-text-on-status transition-all duration-200 hover:bg-surface-destructive-hover',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Builder/ActionsInput.tsx b/client/src/components/SidePanel/Builder/ActionsInput.tsxindex 86ace5efca..785af4aa67 100644--- a/client/src/components/SidePanel/Builder/ActionsInput.tsx+++ b/client/src/components/SidePanel/Builder/ActionsInput.tsx@@ -249,7 +249,7 @@ export default function ActionsInput({{/* TODO: format input button */}</div>{validationResult && validationResult.message !== 'OpenAPI spec is valid.' && (- <div className="border-token-border-light border-t p-2 text-red-500">+ <div className="border-token-border-light border-t p-2 text-text-destructive">{validationResult.message.split('\n').map((line: string, i: number) => (<div key={i}>{line}</div>))}@@ -286,7 +286,7 @@ export default function ActionsInput({<buttondisabled={!functions || !functions.length}onClick={saveAction}- className="mt-1 flex min-w-[100px] items-center justify-center rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0 disabled:bg-green-400"+ className="mt-1 flex min-w-[100px] items-center justify-center rounded bg-surface-submit px-4 py-2 font-semibold text-text-on-status hover:bg-surface-submit-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:opacity-50"type="button">{submitContext()}diff --git a/client/src/components/SidePanel/Builder/ActionsPanel.tsx b/client/src/components/SidePanel/Builder/ActionsPanel.tsxindex d6d0d4d725..424c420a47 100644--- a/client/src/components/SidePanel/Builder/ActionsPanel.tsx+++ b/client/src/components/SidePanel/Builder/ActionsPanel.tsx@@ -149,7 +149,7 @@ export default function ActionsPanel({});},selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-color duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Builder/AssistantPanel.tsx b/client/src/components/SidePanel/Builder/AssistantPanel.tsxindex 67e4735053..3f93b87027 100644--- a/client/src/components/SidePanel/Builder/AssistantPanel.tsx+++ b/client/src/components/SidePanel/Builder/AssistantPanel.tsx@@ -281,7 +281,7 @@ export default function AssistantPanel({{/* Select Button */}{assistant_id && (<button- className="btn btn-primary mx-2 mt-1 h-[40px] rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0"+ className="btn mx-2 mt-1 h-[40px] rounded bg-surface-submit px-4 py-2 font-semibold text-text-on-status hover:bg-surface-submit-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary"type="button"disabled={!assistant_id}onClick={(e) => {@@ -415,10 +415,13 @@ export default function AssistantPanel({cardStyle,'flex h-[40px] w-full flex-none items-center justify-center px-4 hover:cursor-pointer',)}- containerClassName={cn('rounded-md', error ? 'border-red-500 border-2' : '')}+ containerClassName={cn(+ 'rounded-md',+ error ? 'border-border-destructive border-2' : '',+ )}/>{error && (- <span className="text-sm text-red-500 transition duration-300 ease-in-out">+ <span className="text-sm text-text-destructive transition duration-300 ease-in-out">{localize('com_ui_field_required')}</span>)}@@ -505,7 +508,7 @@ export default function AssistantPanel({/>{/* Submit Button */}<button- className="btn btn-primary flex w-full items-center justify-center px-4 py-2 font-semibold text-white hover:bg-green-600 focus:border-green-500"+ className="btn flex w-full items-center justify-center bg-surface-submit px-4 py-2 font-semibold text-text-on-status hover:bg-surface-submit-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary"type="submit">{submitContext}diff --git a/client/src/components/SidePanel/Builder/AssistantTool.tsx b/client/src/components/SidePanel/Builder/AssistantTool.tsxindex bd60216f91..6a794c8b08 100644--- a/client/src/components/SidePanel/Builder/AssistantTool.tsx+++ b/client/src/components/SidePanel/Builder/AssistantTool.tsx@@ -101,7 +101,7 @@ export default function AssistantTool({selection={{selectHandler: () => removeTool(currentTool.pluginKey),selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-colors duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Builder/ContextButton.tsx b/client/src/components/SidePanel/Builder/ContextButton.tsxindex e2522e0eca..a75220ad6c 100644--- a/client/src/components/SidePanel/Builder/ContextButton.tsx+++ b/client/src/components/SidePanel/Builder/ContextButton.tsx@@ -116,7 +116,8 @@ export default function ContextButton({selection={{selectHandler: () =>deleteAssistant.mutate({ assistant_id, model: activeModel, endpoint }),- selectClasses: 'bg-red-600 hover:bg-red-700 dark:hover:bg-red-800 text-white',+ selectClasses:+ 'bg-surface-destructive hover:bg-surface-destructive-hover text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Memories/MemoryCardActions.tsx b/client/src/components/SidePanel/Memories/MemoryCardActions.tsxindex 3e2574fb54..4b8b24bcde 100644--- a/client/src/components/SidePanel/Memories/MemoryCardActions.tsx+++ b/client/src/components/SidePanel/Memories/MemoryCardActions.tsx@@ -130,7 +130,8 @@ export default function MemoryCardActions({ memory }: MemoryCardActionsProps) {}selection={{selectHandler: confirmDelete,- selectClasses: 'bg-surface-destructive text-white hover:bg-surface-destructive-hover',+ selectClasses:+ 'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/SidePanel/Parameters/DynamicCheckbox.tsx b/client/src/components/SidePanel/Parameters/DynamicCheckbox.tsxindex 61ccd0e0d7..4e04dec854 100644--- a/client/src/components/SidePanel/Parameters/DynamicCheckbox.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicCheckbox.tsx@@ -64,7 +64,7 @@ function DynamicCheckbox({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default')}:{' '}{defaultValue != null ? localize('com_ui_yes') : localize('com_ui_no')})</small>diff --git a/client/src/components/SidePanel/Parameters/DynamicCombobox.tsx b/client/src/components/SidePanel/Parameters/DynamicCombobox.tsxindex 8dd352aff3..f708b44d18 100644--- a/client/src/components/SidePanel/Parameters/DynamicCombobox.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicCombobox.tsx@@ -1,6 +1,6 @@import { useMemo, useState, useCallback } from 'react';-import type { DynamicSettingProps } from 'librechat-data-provider';import { Label, HoverCard, HoverCardTrigger, ControlCombobox } from '@librechat/client';+import type { DynamicSettingProps } from 'librechat-data-provider';import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';import { useChatContext } from '~/Providers';import OptionHover from './OptionHover';@@ -86,7 +86,7 @@ function DynamicCombobox({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default')}: {defaultValue})</small>)}diff --git a/client/src/components/SidePanel/Parameters/DynamicDropdown.tsx b/client/src/components/SidePanel/Parameters/DynamicDropdown.tsxindex 47f81ea180..95325924f9 100644--- a/client/src/components/SidePanel/Parameters/DynamicDropdown.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicDropdown.tsx@@ -80,7 +80,7 @@ function DynamicDropdown({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default')}: {defaultValue})</small>)}diff --git a/client/src/components/SidePanel/Parameters/DynamicInput.tsx b/client/src/components/SidePanel/Parameters/DynamicInput.tsxindex 4bdf7c29b4..096c8a0313 100644--- a/client/src/components/SidePanel/Parameters/DynamicInput.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicInput.tsx@@ -178,7 +178,7 @@ function DynamicInput({>{labelCode ? localize(label as TranslationKeys) || label : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({typeof defaultValue === 'undefined' || !(defaultValue as string).length? localize('com_endpoint_default_blank')diff --git a/client/src/components/SidePanel/Parameters/DynamicSlider.tsx b/client/src/components/SidePanel/Parameters/DynamicSlider.tsxindex 76adba8c3f..665c5055ed 100644--- a/client/src/components/SidePanel/Parameters/DynamicSlider.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicSlider.tsx@@ -179,7 +179,7 @@ function DynamicSlider({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default')}: {getDefaultDisplayValue()})</small>)}diff --git a/client/src/components/SidePanel/Parameters/DynamicSwitch.tsx b/client/src/components/SidePanel/Parameters/DynamicSwitch.tsxindex 99e7713a15..07d2a7b3db 100644--- a/client/src/components/SidePanel/Parameters/DynamicSwitch.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicSwitch.tsx@@ -1,6 +1,6 @@import { useState } from 'react';-import type { DynamicSettingProps } from 'librechat-data-provider';import { Label, Switch, HoverCard, HoverCardTrigger } from '@librechat/client';+import type { DynamicSettingProps } from 'librechat-data-provider';import { TranslationKeys, useLocalize, useParameterEffects } from '~/hooks';import { useChatContext } from '~/Providers';import OptionHover from './OptionHover';@@ -54,7 +54,7 @@ function DynamicSwitch({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({localize('com_endpoint_default')}:{' '}{defaultValue != null ? localize('com_ui_on') : localize('com_ui_off')})</small>diff --git a/client/src/components/SidePanel/Parameters/DynamicTags.tsx b/client/src/components/SidePanel/Parameters/DynamicTags.tsxindex 6b8300e5d0..d61ec18ee6 100644--- a/client/src/components/SidePanel/Parameters/DynamicTags.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicTags.tsx@@ -114,7 +114,7 @@ function DynamicTags({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({typeof defaultValue === 'undefined' || !(defaultValue as string).length? localize('com_endpoint_default_blank')diff --git a/client/src/components/SidePanel/Parameters/DynamicTextarea.tsx b/client/src/components/SidePanel/Parameters/DynamicTextarea.tsxindex a6092555e8..46ffb1bd04 100644--- a/client/src/components/SidePanel/Parameters/DynamicTextarea.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicTextarea.tsx@@ -62,7 +62,7 @@ function DynamicTextarea({>{labelCode ? (localize(label as TranslationKeys) ?? label) : label || settingKey}{' '}{showDefault && (- <small className="opacity-40">+ <small className="opacity-40 high-contrast:opacity-100">({typeof defaultValue === 'undefined' || !(defaultValue as string).length? localize('com_endpoint_default_blank')diff --git a/client/src/components/Skills/dialogs/DeleteSkill.tsx b/client/src/components/Skills/dialogs/DeleteSkill.tsxindex 2734ac1d54..85a6ece659 100644--- a/client/src/components/Skills/dialogs/DeleteSkill.tsx+++ b/client/src/components/Skills/dialogs/DeleteSkill.tsx@@ -82,7 +82,7 @@ function DeleteSkill({ skillId, skillName, disabled, onDelete }: DeleteSkillPropselection={{selectHandler: handleDelete,selectClasses:- 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-white',+ 'bg-surface-destructive hover:bg-surface-destructive-hover transition-colors duration-200 text-text-on-status',selectText: localize('com_ui_delete'),}}/>diff --git a/client/src/components/Skills/display/SkillDetailHeader.tsx b/client/src/components/Skills/display/SkillDetailHeader.tsxindex c55d8f2579..4c06132996 100644--- a/client/src/components/Skills/display/SkillDetailHeader.tsx+++ b/client/src/components/Skills/display/SkillDetailHeader.tsx@@ -54,7 +54,7 @@ const SkillDetailHeader = ({ skill, showActions = true }: SkillDetailHeaderPropsside="top"render={<Pin- className="h-5 w-5 shrink-0 text-cyan-500"+ className="h-5 w-5 shrink-0 text-status-info"aria-label={localize('com_ui_skills_always_apply_pin_title')}/>}diff --git a/client/src/components/Skills/lists/SkillListItem.tsx b/client/src/components/Skills/lists/SkillListItem.tsxindex bf97bfc7a9..cfb0ceadcf 100644--- a/client/src/components/Skills/lists/SkillListItem.tsx+++ b/client/src/components/Skills/lists/SkillListItem.tsx@@ -327,7 +327,7 @@ function SkillListItem({<span className="truncate">{skill.name}</span>{skill.alwaysApply === true && (<Pin- className="size-3 shrink-0 text-cyan-500"+ className="size-3 shrink-0 text-status-info"aria-label={localize('com_ui_skills_always_apply_pin_title')}/>)}diff --git a/client/src/components/UnifiedSidebar/Sidebar.tsx b/client/src/components/UnifiedSidebar/Sidebar.tsxindex 642378dec9..778d584209 100644--- a/client/src/components/UnifiedSidebar/Sidebar.tsx+++ b/client/src/components/UnifiedSidebar/Sidebar.tsx@@ -39,7 +39,12 @@ function Sidebar({/><navclassName={cn(- 'min-h-0 flex-1 overflow-hidden bg-surface-primary-alt',+ /** The resize separator to the right is transparent until hovered, so+ * the panel has no resting right edge. That is deliberate in the+ * standard themes, where `surface-primary-alt` carries the boundary+ * on its own; in high contrast both sides are the same pure white or+ * pure black, so the edge has to be drawn. */+ 'min-h-0 flex-1 overflow-hidden bg-surface-primary-alt high-contrast:border-r high-contrast:border-border-light',expanded ? 'opacity-100' : 'pointer-events-none opacity-0',)}style={{ transition: expanded ? 'opacity 200ms ease 80ms' : 'opacity 150ms ease' }}diff --git a/client/src/components/Web/Citation.tsx b/client/src/components/Web/Citation.tsxindex 67f3ffafba..d80c0348c7 100644--- a/client/src/components/Web/Citation.tsx+++ b/client/src/components/Web/Citation.tsx@@ -386,7 +386,7 @@ export const HighlightedText = memo(function HighlightedText({return (<span- className={`rounded px-0 py-0.5 transition-colors ${isHighlighted ? 'bg-amber-300/20' : ''}`}+ className={`rounded px-0 py-0.5 transition-colors ${isHighlighted ? 'bg-surface-active' : ''}`}>{children}</span>diff --git a/client/src/components/Web/__tests__/Citation.test.tsx b/client/src/components/Web/__tests__/Citation.test.tsxindex d25cb2d761..ba5e383440 100644--- a/client/src/components/Web/__tests__/Citation.test.tsx+++ b/client/src/components/Web/__tests__/Citation.test.tsx@@ -2,7 +2,7 @@ import React from 'react';import { render, screen, fireEvent } from '@testing-library/react';import '@testing-library/jest-dom';import type { SearchResultData } from 'librechat-data-provider';-import { Citation, CompositeCitation } from '~/components/Web/Citation';+import { Citation, CompositeCitation, HighlightedText } from '~/components/Web/Citation';import { CitationContext } from '~/components/Web/Context';import { SearchContext } from '~/Providers';@@ -74,6 +74,19 @@ function renderWithProviders(}describe('Citation', () => {+ it('uses the semantic active surface for a highlighted passage', () => {+ const highlightedPassage = 'Highlighted passage';+ render(+ <CitationContext.Provider+ value={{ hoveredCitationId: 'cite-highlight', setHoveredCitationId: jest.fn() }}+ >+ <HighlightedText citationId="cite-highlight">{highlightedPassage}</HighlightedText>+ </CitationContext.Provider>,+ );++ expect(screen.getByText(highlightedPassage)).toHaveClass('bg-surface-active');+ });+it('renders composite file citations as buttons and opens the preview dialog', () => {const searchResults = {'0': {diff --git a/client/src/hooks/Artifacts/useArtifactProps.ts b/client/src/hooks/Artifacts/useArtifactProps.tsindex f76093a997..017bdb195d 100644--- a/client/src/hooks/Artifacts/useArtifactProps.ts+++ b/client/src/hooks/Artifacts/useArtifactProps.ts@@ -1,5 +1,5 @@import { useContext, useMemo } from 'react';-import { ThemeContext, isDark } from '@librechat/client';+import { ThemeContext } from '@librechat/client';import { removeNullishValues } from 'librechat-data-provider';import type { Artifact } from '~/common';import {@@ -11,19 +11,20 @@ import {wrapAsFencedCodeBlock,TOOL_ARTIFACT_TYPES,} from '~/utils/artifacts';+import { withOfficeContrast } from '~/utils/officePreview';import { getMarkdownFiles } from '~/utils/markdown';import { getMermaidFiles } from '~/utils/mermaid';export default function useArtifactProps({ artifact }: { artifact: Artifact }) {- const { theme } = useContext(ThemeContext);- const isDarkMode = isDark(theme);+ const { resolvedMode, highContrast } = useContext(ThemeContext);+ const isDarkMode = resolvedMode === 'dark';const [fileKey, files] = useMemo(() => {const key = getKey(artifact.type ?? '', artifact.language);const type = artifact.type ?? '';if (key.includes('mermaid')) {- return ['diagram.mmd', getMermaidFiles(artifact.content ?? '', isDarkMode)];+ return ['diagram.mmd', getMermaidFiles(artifact.content ?? '', isDarkMode, highContrast)];}/* CODE bucket: source files render through the same static-markdown@@ -38,11 +39,11 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) {if (type === TOOL_ARTIFACT_TYPES.CODE) {const lang = artifact.language ?? languageForFilename(artifact.title);const wrapped = wrapAsFencedCodeBlock(artifact.content ?? '', lang);- return ['content.md', getMarkdownFiles(wrapped)];+ return ['content.md', getMarkdownFiles(wrapped, isDarkMode, highContrast)];}if (type === 'text/markdown' || type === 'text/md' || type === 'text/plain') {- return ['content.md', getMarkdownFiles(artifact.content ?? '')];+ return ['content.md', getMarkdownFiles(artifact.content ?? '', isDarkMode, highContrast)];}/* Office preview buckets (DOCX/SPREADSHEET/PRESENTATION): the backend@@ -50,14 +51,20 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) {* `bufferToOfficeHtml` and shipped it as `attachment.text`. Hand it* to the Sandpack `static` template's `index.html` slot directly —* no wrapping, no transformation, no client-side parsing libs. The- * empty-text gate in `detectArtifactTypeFromFile` guarantees we+ * contrast override is injected client-side because the document is+ * generated server-side with no knowledge of the viewer's appearance+ * mode. The empty-text gate in `detectArtifactTypeFromFile` guarantees we* never reach this branch with an empty content payload. */if (type === TOOL_ARTIFACT_TYPES.DOCX ||type === TOOL_ARTIFACT_TYPES.SPREADSHEET ||type === TOOL_ARTIFACT_TYPES.PRESENTATION) {- return ['index.html', { 'index.html': artifact.content ?? '' }];+ const content = artifact.content ?? '';+ return [+ 'index.html',+ { 'index.html': highContrast ? withOfficeContrast(content, isDarkMode) : content },+ ];}const fileKey = getArtifactFilename(artifact.type ?? '', artifact.language);@@ -65,7 +72,14 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) {[fileKey]: artifact.content,});return [fileKey, files];- }, [artifact.type, artifact.content, artifact.language, artifact.title, isDarkMode]);+ }, [+ artifact.type,+ artifact.content,+ artifact.language,+ artifact.title,+ isDarkMode,+ highContrast,+ ]);const template = useMemo(() => getTemplate(artifact.type ?? '', artifact.language),diff --git a/client/src/hooks/Mermaid/__tests__/useMermaid.spec.tsx b/client/src/hooks/Mermaid/__tests__/useMermaid.spec.tsxnew file mode 100644index 0000000000..51496ef168--- /dev/null+++ b/client/src/hooks/Mermaid/__tests__/useMermaid.spec.tsx@@ -0,0 +1,121 @@+import React from 'react';+import mermaid from 'mermaid';+import { SWRConfig } from 'swr';+import { ThemeContext } from '@librechat/client';+import { renderHook, waitFor } from '@testing-library/react';+import useMermaid from '../useMermaid';++jest.mock('mermaid', () => ({+ __esModule: true,+ default: {+ parse: jest.fn(),+ initialize: jest.fn(),+ render: jest.fn(),+ },+}));++const mermaidMock = mermaid as unknown as {+ parse: jest.Mock;+ initialize: jest.Mock;+ render: jest.Mock;+};++const CONTENT = 'graph TD;\nA-->B;';++type Appearance = { resolvedMode: 'light' | 'dark'; highContrast: boolean };++let appearance: Appearance = { resolvedMode: 'light', highContrast: false };++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>+ <ThemeContext.Provider+ value={+ {+ theme: 'system',+ setTheme: () => undefined,+ resolvedMode: appearance.resolvedMode,+ highContrast: appearance.highContrast,+ setThemeRGB: () => undefined,+ setThemeDefinition: () => undefined,+ setThemeName: () => undefined,+ resetTheme: () => undefined,+ } as React.ContextType<typeof ThemeContext>+ }+ >+ {children}+ </ThemeContext.Provider>+ </SWRConfig>+);++describe('useMermaid cache key', () => {+ beforeEach(() => {+ appearance = { resolvedMode: 'light', highContrast: false };+ mermaidMock.parse.mockResolvedValue(true);+ mermaidMock.initialize.mockImplementation(() => undefined);+ mermaidMock.render.mockResolvedValue({ svg: '<svg id="d"><g></g></svg>' });+ });++ /** The cache key used to short-circuit to `customTheme` alone, so switching+ * into a contrast mode replayed the SVG rendered with the old palette even+ * though `mermaidConfig` had already rebuilt its theme variables. */+ it('rerenders a custom-themed diagram when contrast changes', async () => {+ const { rerender } = renderHook(() => useMermaid({ content: CONTENT, theme: 'forest' }), {+ wrapper,+ });++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(1));++ appearance = { resolvedMode: 'light', highContrast: true };+ rerender();++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(2));++ const [first, second] = mermaidMock.initialize.mock.calls;+ expect(first[0].theme).toBe('forest');+ expect(first[0].themeVariables).toBeUndefined();+ /** `base` is the only built-in theme mermaid applies `themeVariables` to, so+ * the contrast palette has to outrank the caller's theme. */+ expect(second[0].theme).toBe('base');+ expect(second[0].themeVariables).toEqual(expect.objectContaining({ primaryColor: '#ffffff' }));+ });++ it('keeps the contrast palette ahead of a caller-supplied config theme', async () => {+ appearance = { resolvedMode: 'dark', highContrast: true };+ renderHook(+ () => useMermaid({ content: CONTENT, theme: 'forest', config: { theme: 'forest' } }),+ { wrapper },+ );++ await waitFor(() => expect(mermaidMock.initialize).toHaveBeenCalledTimes(1));++ const [config] = mermaidMock.initialize.mock.calls[0];+ expect(config.theme).toBe('base');+ expect(config.themeVariables).toEqual(expect.objectContaining({ primaryColor: '#000000' }));+ });++ it('rerenders a custom-themed diagram when the scheme changes', async () => {+ const { rerender } = renderHook(() => useMermaid({ content: CONTENT, theme: 'forest' }), {+ wrapper,+ });++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(1));++ appearance = { resolvedMode: 'dark', highContrast: false };+ rerender();++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(2));+ });++ it('reuses the cached SVG while the appearance holds still', async () => {+ const { rerender } = renderHook(() => useMermaid({ content: CONTENT, theme: 'forest' }), {+ wrapper,+ });++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(1));++ rerender();+ rerender();++ await waitFor(() => expect(mermaidMock.render).toHaveBeenCalledTimes(1));+ });+});diff --git a/client/src/hooks/Mermaid/useMermaid.ts b/client/src/hooks/Mermaid/useMermaid.tsindex be74ed037a..fc267fccb6 100644--- a/client/src/hooks/Mermaid/useMermaid.ts+++ b/client/src/hooks/Mermaid/useMermaid.ts@@ -1,9 +1,13 @@import { useContext, useMemo, useState } from 'react';import useSWR from 'swr';import { Md5 } from 'ts-md5';-import { ThemeContext, isDark } from '@librechat/client';+import { ThemeContext } from '@librechat/client';import type { MermaidConfig } from 'mermaid';-import { inlineFlowchartConfig, sanitizeMermaidSvg } from '~/utils/mermaid';+import {+ contrastMermaidVariables,+ inlineFlowchartConfig,+ sanitizeMermaidSvg,+} from '~/utils/mermaid';// Constantsconst MD5_LENGTH_THRESHOLD = 10_000;@@ -55,8 +59,11 @@ export const useMermaid = ({config,enabled = true,}: UseMermaidOptions): UseMermaidReturn => {- const { theme } = useContext(ThemeContext);- const isDarkMode = isDark(theme);+ /** Read from context rather than derived here: under `system` both the scheme+ * and the contrast come from media queries, so deriving either locally would+ * keep whatever this hook computed on its last render. */+ const { resolvedMode, highContrast } = useContext(ThemeContext);+ const isDarkMode = resolvedMode === 'dark';// Store last valid SVG for fallback on errorsconst [validContent, setValidContent] = useState<string>('');@@ -70,11 +77,13 @@ export const useMermaid = ({// For large diagrams, use MD5 hash instead of full contentconst contentHash = content.length < MD5_LENGTH_THRESHOLD ? content : Md5.hashStr(content);- // Include theme mode in cache key to handle theme switches- const themeKey = customTheme || (isDarkMode ? 'd' : 'l');+ /** Scheme and contrast belong in the key even when a custom theme is set:+ * `mermaidConfig` still rebuilds `themeVariables` per appearance, so a+ * key that stopped at `customTheme` would replay the stale SVG. */+ const appearanceKey = `${isDarkMode ? 'd' : 'l'}${highContrast ? 'h' : ''}`;- return [id, themeKey, contentHash].filter(Boolean).join('-');- }, [content, enabled, id, isDarkMode, customTheme]);+ return [id, customTheme, appearanceKey, contentHash].filter(Boolean).join('-');+ }, [content, enabled, id, isDarkMode, highContrast, customTheme]);// Generate unique diagram ID (mermaid requires unique IDs in the DOM)// Include cacheKey to regenerate when content/theme changes, preventing mermaid internal conflicts@@ -88,18 +97,24 @@ export const useMermaid = ({// Build mermaid configurationconst mermaidConfig = useMemo((): MermaidConfig => {const defaultTheme = isDarkMode ? 'dark' : 'neutral';+ const themeVariables = contrastMermaidVariables(isDarkMode, highContrast);return {startOnLoad: false,theme: (customTheme as MermaidConfig['theme']) || defaultTheme,...config,flowchart: { ...inlineFlowchartConfig, ...config?.flowchart, htmlLabels: false },+ /** A contrast mode is an accessibility need rather than a caller+ * preference, and mermaid honours `themeVariables` only under `base`, so+ * both MUST come after the `config` spread and outrank `customTheme`.+ * Otherwise the diagram keeps a built-in palette no token can reach. */+ ...(themeVariables ? { theme: 'base' as const, themeVariables } : {}),// Security hardening: MUST come after ...config spread to prevent overridesecurityLevel: 'strict',maxTextSize: config?.maxTextSize ?? 50000,maxEdges: config?.maxEdges ?? 500,};- }, [customTheme, isDarkMode, config]);+ }, [customTheme, isDarkMode, highContrast, config]);// Fetch/render functionconst fetchSvg = async (): Promise<string> => {diff --git a/client/src/hooks/ScreenshotContext.tsx b/client/src/hooks/ScreenshotContext.tsxindex 5e4418e025..ff31f4454f 100644--- a/client/src/hooks/ScreenshotContext.tsx+++ b/client/src/hooks/ScreenshotContext.tsx@@ -58,7 +58,15 @@ export const useScreenshot = () => {);}- const backgroundColor = isDark(theme) ? '#171717' : 'white';+ /** Read the canvas the app is actually painting rather than a fixed pair, so+ * an export matches the selected appearance and the state colours keep the+ * contrast they were calibrated against. The token is a channel triplet,+ * not a colour, so it has to be wrapped before html-to-image sees it. */+ const canvasTriplet = getComputedStyle(document.documentElement)+ .getPropertyValue('--surface-primary')+ .trim();+ const fallbackBackground = isDark(theme) ? '#171717' : 'white';+ const backgroundColor = canvasTriplet ? `rgb(${canvasTriplet})` : fallbackBackground;const canvas = await toCanvas(node, {backgroundColor,pixelRatio,diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 2d599a3aad..34a86710b0 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -656,6 +656,8 @@"com_nav_text_to_speech": "Text to Speech","com_nav_theme": "Theme","com_nav_theme_dark": "Dark",+ "com_nav_theme_high_contrast_dark": "High contrast dark",+ "com_nav_theme_high_contrast_light": "High contrast light","com_nav_theme_light": "Light","com_nav_theme_system": "System","com_nav_tool_dialog": "Assistant Tools",@@ -1406,6 +1408,8 @@"com_ui_hide_n_files": "Hide {{0}} files","com_ui_hide_qr": "Hide QR Code","com_ui_high": "High",+ "com_ui_high_contrast_dark_theme_enabled": "High contrast dark theme enabled",+ "com_ui_high_contrast_light_theme_enabled": "High contrast light theme enabled","com_ui_host": "Host","com_ui_icon": "Icon","com_ui_icon_too_large": "That image is too large to save as an icon. Please choose a file under {{0}} KB.",@@ -2352,6 +2356,7 @@"com_ui_thinking": "Thinking...","com_ui_thoughts": "Thoughts","com_ui_thoughts_unavailable": "Reasoning happened here, but background agents keep only this marker",+ "com_ui_toggle_high_contrast": "Toggle high contrast","com_ui_toggle_theme": "Toggle theme","com_ui_token": "token","com_ui_token_exchange_method": "Token Exchange Method",diff --git a/client/src/routes/Search.tsx b/client/src/routes/Search.tsxindex 78110408c4..e99528012c 100644--- a/client/src/routes/Search.tsx+++ b/client/src/routes/Search.tsx@@ -317,7 +317,7 @@ export default function Search() {}return (- <div className="relative flex h-full w-full flex-col bg-white pt-4 dark:bg-gray-800">+ <div className="relative flex h-full w-full flex-col bg-presentation pt-4"><div className="sr-only" role="alert" aria-atomic="true">{resultsAnnouncement}</div>@@ -333,7 +333,10 @@ export default function Search() {onRowsRendered={handleRowsRendered}overscanRowCount={10}aria-label={localize('com_nav_search_placeholder')}- className={cn('outline-none', showingStale && 'opacity-70')}+ className={cn(+ 'outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary',+ showingStale && 'opacity-70',+ )}style={{ outline: 'none' }}/></div>@@ -342,7 +345,7 @@ export default function Search() {<Spinner className="text-text-primary" /></div>)}- <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-[5%] bg-gradient-to-t from-gray-50 to-transparent dark:from-gray-800" />+ <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-[5%] bg-gradient-to-t from-presentation to-transparent" /></div>);}diff --git a/client/src/routes/__tests__/Search.spec.tsx b/client/src/routes/__tests__/Search.spec.tsxindex 99a10f39c1..3a2b1fa13c 100644--- a/client/src/routes/__tests__/Search.spec.tsx+++ b/client/src/routes/__tests__/Search.spec.tsx@@ -24,6 +24,7 @@ jest.mock('react-virtualized', () => ({rowCount,rowRenderer,onRowsRendered,+ className,}: {rowCount: number;rowRenderer: (p: {@@ -33,12 +34,13 @@ jest.mock('react-virtualized', () => ({style: object;}) => React.ReactNode;onRowsRendered?: (p: { startIndex: number; stopIndex: number }) => void;+ className?: string;}) => {// expose the near-bottom trigger for the pagination test(globalThis as Record<string, unknown>).__triggerRowsRendered = () =>onRowsRendered?.({ startIndex: 0, stopIndex: rowCount - 1 });return (- <div data-testid="virtual-list">+ <div data-testid="virtual-list" className={className}>{Array.from({ length: rowCount }, (_, i) =>rowRenderer({ index: i, key: String(i), parent: {}, style: {} }),)}@@ -99,9 +101,15 @@ describe('Search route', () => {it('renders result rows when data is present', () => {mockUseRecoilValue.mockReturnValue(searchState());mockUseQuery.mockReturnValue(queryResult());- render(<Search />);+ const { container } = render(<Search />);expect(screen.getByText('row one')).toBeInTheDocument();expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();+ expect(screen.getByTestId('virtual-list')).toHaveClass(+ 'focus-visible:ring-2',+ 'focus-visible:ring-ring-primary',+ );+ expect(container.firstElementChild).toHaveClass('bg-presentation');+ expect(container.querySelector('.bg-gradient-to-t')).toHaveClass('from-presentation');});it('keeps results mounted while typing (does NOT flash the full spinner)', () => {diff --git a/client/src/style.css b/client/src/style.cssindex a63845e6f0..d877c5bb8b 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -230,6 +230,16 @@ html {--series-6: 126 35 205;--series-7: 1 131 1;+ /* Code syntax highlighting */+ --syntax-text: var(--gray-800);+ --syntax-comment: var(--gray-500);+ --syntax-meta: var(--gray-600);+ --syntax-builtin: 154 103 0;+ --syntax-keyword: 5 80 174;+ --syntax-string: 10 123 98;+ --syntax-attr: 154 47 106;+ --syntax-title: 180 35 24;+--surface-inverted: var(--gray-850);--surface-inverted-hover: var(--gray-700);--text-inverted: var(--white);@@ -248,7 +258,7 @@ html {--theme-elevation-surface: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);--theme-motion-fast: 150ms;--theme-motion-normal: 200ms;- --switch-unchecked: 0 0% 58%;+ --switch-unchecked: 148 148 148;--provider-openai: #19c37d;--provider-openai-gpt4: #ab68ff;--provider-openai-reasoning: #000000;@@ -311,7 +321,7 @@ html {--status-success: var(--green-300);--status-success-subtle: var(--green-950);--status-success-border: var(--green-800);- --status-success-strong: var(--green-800);+ --status-success-strong: 8 135 89;--status-info: var(--blue-300);--status-info-subtle: var(--blue-950);--status-info-border: var(--blue-800);@@ -338,13 +348,24 @@ html {--series-6: 171 104 254;--series-7: 80 167 49;+ /* Code syntax highlighting. Comment and meta are the flattened equivalents of+ the 50% and 60% alpha whites this palette used before it was tokenized. */+ --syntax-text: var(--white);+ --syntax-comment: 144 144 144;+ --syntax-meta: 166 166 166;+ --syntax-builtin: 233 149 12;+ --syntax-keyword: 46 149 211;+ --syntax-string: 0 166 125;+ --syntax-attr: 223 48 121;+ --syntax-title: 242 44 61;+--surface-inverted: var(--white);--surface-inverted-hover: var(--gray-100);--text-inverted: var(--gray-850);--surface-fixed: var(--white);--surface-fixed-hover: var(--gray-100);--text-fixed: var(--gray-800);- --switch-unchecked: 0 0% 40%;+ --switch-unchecked: 102 102 102;--provider-openai: #19c37d;--provider-openai-gpt4: #ab68ff;--provider-openai-reasoning: #000000;@@ -388,6 +409,155 @@ html {--border-xheavy: 217 217 227;}+/* High contrast appearance modes.+ *+ * Every `IThemeRGB` token is delivered by the theme registry as an inline custom+ * property on <html> (see packages/client/src/theme/themes/highContrast.ts), so+ * this block only covers what the token layer cannot reach: the CSS-only+ * variables and hard-coded literals elsewhere in this stylesheet. Every ratio+ * quoted below is measured against the mode's own canvas, pure white or pure+ * black. */+html.high-contrast {+ /* A 0.5rem bar is a small target to hit and a thin thing to see. */+ --scrollbar-size: 0.75rem;+ /* Keep both animated text stops at the AAA ratios declared by the palette. */+ --shimmer-base-alpha: 1;+ --shimmer-dip-alpha: 1;+}+html.high-contrast ::-webkit-scrollbar-thumb {+ /* The 10%-alpha thumb is invisible against a pure black or white canvas. */+ background-color: rgb(var(--border-heavy));+}+html.high-contrast ::-webkit-scrollbar-track {+ border: 1px solid rgb(var(--border-light));+}+html.high-contrast * {+ scrollbar-color: rgb(var(--border-heavy)) rgb(var(--surface-primary));+ /* Controls that halve their own ring (`ring-opacity-50`, `ring-opacity-20`)+ * keep it at full strength here. The outline rules below cover the controls+ * that blank it outright. */+ --tw-ring-opacity: 1;+}+/* `.dark body`/`.dark html` pin the page to #212121, which would leave a+ * near-black canvas behind the pure black surfaces. */+html.high-contrast,+html.high-contrast body,+html.high-contrast.dark,+html.high-contrast.dark body {+ background-color: rgb(var(--surface-primary));+}+/* Selection is otherwise left to the UA's system colours, which no theme+ * controls. Inverting the canvas guarantees 21:1 for the selected run. */+html.high-contrast ::selection {+ background-color: rgb(var(--text-primary));+ color: rgb(var(--surface-primary));+}+/* WCAG 2.4.13 wants a 2px perimeter as the floor; a contrast mode should exceed+ * it. The global pair below hard-codes #000/#fff instead of reading the ink+ * token, and the keyboard-modality rule for text fields sits at 2px. */+html.high-contrast :focus-visible,+html.high-contrast.dark :focus-visible {+ outline: 3px solid rgb(var(--text-primary));+ outline-offset: 2px;+}+/* Selection perimeters and placeholder ink used to live here, but they complete+ * the exported palettes rather than this app: a package primitive rendered by+ * an external consumer of `ThemeProvider` needs them too, and the published+ * stylesheet is built only from package-owned CSS. They now ship from+ * `packages/client/src/theme/highContrast.css`, which `main.jsx` pulls in with+ * `@librechat/client/style.css`. What stays below is genuinely SPA-only. */+html[data-input-modality='keyboard'].high-contrast+ :where(+ input:not([type]),+ input:is(+ [type='text'],+ [type='search'],+ [type='email'],+ [type='password'],+ [type='url'],+ [type='tel'],+ [type='number'],+ [type='date'],+ [type='datetime-local'],+ [type='month'],+ [type='week'],+ [type='time']+ ),+ textarea+ ):not(.lc-field):focus-visible {+ outline: 3px solid rgb(var(--text-primary)) !important;+ outline-offset: 2px !important;+}+/* The WCAG 1.4.1 link treatment moved to+ * `packages/client/src/theme/highContrast.css` with the other rules that+ * complete the exported palettes: `text-link` is a shared role, so a package+ * primitive rendering a link needs the same non-colour cue. */+/* The whole `@tailwindcss/typography` variable block is hard-coded hex, and+ * message content carries `prose dark:prose-invert`, so the invert half is what+ * dark mode reads. Both halves are remapped: the light set puts prose links at+ * #0066cc, which is 3.77:1 on a black canvas and 5.40:1 on a white one, and+ * every rule and border in the set (#cdcdcd, #e5e7eb, #424242, #4b5563) sits+ * below the 3:1 non-text floor in one mode or the other. */+html.high-contrast .prose {+ --tw-prose-body: rgb(var(--text-primary));+ --tw-prose-headings: rgb(var(--text-primary));+ --tw-prose-lead: rgb(var(--text-primary));+ --tw-prose-links: rgb(var(--link));+ --tw-prose-bold: rgb(var(--text-primary));+ --tw-prose-counters: rgb(var(--text-primary));+ --tw-prose-bullets: rgb(var(--text-primary));+ --tw-prose-hr: rgb(var(--border-medium));+ --tw-prose-quotes: rgb(var(--text-primary));+ --tw-prose-quote-borders: rgb(var(--border-medium));+ --tw-prose-captions: rgb(var(--text-primary));+ --tw-prose-code: rgb(var(--text-primary));+ --tw-prose-pre-code: rgb(var(--text-primary));+ --tw-prose-pre-bg: rgb(var(--surface-code));+ --tw-prose-th-borders: rgb(var(--border-medium));+ --tw-prose-td-borders: rgb(var(--border-medium));+ --tw-prose-invert-body: rgb(var(--text-primary));+ --tw-prose-invert-headings: rgb(var(--text-primary));+ --tw-prose-invert-lead: rgb(var(--text-primary));+ --tw-prose-invert-links: rgb(var(--link));+ --tw-prose-invert-bold: rgb(var(--text-primary));+ --tw-prose-invert-counters: rgb(var(--text-primary));+ --tw-prose-invert-bullets: rgb(var(--text-primary));+ --tw-prose-invert-hr: rgb(var(--border-medium));+ --tw-prose-invert-quotes: rgb(var(--text-primary));+ --tw-prose-invert-quote-borders: rgb(var(--border-medium));+ --tw-prose-invert-captions: rgb(var(--text-primary));+ --tw-prose-invert-code: rgb(var(--text-primary));+ --tw-prose-invert-pre-code: rgb(var(--text-primary));+ --tw-prose-invert-pre-bg: rgb(var(--surface-code));+ --tw-prose-invert-th-borders: rgb(var(--border-medium));+ --tw-prose-invert-td-borders: rgb(var(--border-medium));+}+/* Markdown structure borders are drawn from the raw grey palette, which lands+ * at 1.6:1 on white and 2.1:1 on black, under the 3:1 non-text floor. */+html.high-contrast .markdown blockquote,+html.high-contrast .markdown th,+html.high-contrast .markdown th:last-child,+html.high-contrast .markdown td,+html.high-contrast .markdown td:last-child {+ border-color: rgb(var(--border-medium));+}+/* `.btn-neutral` (the Builder's Knowledge, Code Files and Assistant selectors+ * and the delete trigger) predates the token layer and hard-codes its edge,+ * label and hover fill. On white, `rgba(0, 0, 0, 0.1)` and #ececf1 sit at 1.1:1+ * and 1.05:1; on black, #424242 sits at 2.09:1 for both the edge and the hover+ * fill. All four are under the 3:1 non-text floor, which leaves the control+ * boundary and its hover state unreadable. */+html.high-contrast .btn-neutral,+html.high-contrast.dark .btn-neutral {+ background-color: rgb(var(--surface-primary));+ border-color: rgb(var(--border-medium));+ color: rgb(var(--text-primary));+}+html.high-contrast .btn-neutral:hover,+html.high-contrast.dark .btn-neutral:hover {+ background-color: rgb(var(--surface-hover));+}+.text-token-text-primary {color: #171717;color: rgb(var(--text-primary));@@ -1073,7 +1243,7 @@ code[class*='language-'],pre[class*='language-'] {word-wrap: normal;background: none;- color: rgb(var(--gray-800));+ color: rgb(var(--syntax-text));-webkit-hyphens: none;hyphens: none;font-size: 0.85rem;@@ -1095,27 +1265,27 @@ pre[class*='language-'] {white-space: normal;}.hljs-comment {- color: rgb(var(--gray-500));+ color: rgb(var(--syntax-comment));}.hljs-meta {- color: rgb(var(--gray-600));+ color: rgb(var(--syntax-meta));}.hljs-built_in,.hljs-class .hljs-title {- color: #9a6700;+ color: rgb(var(--syntax-builtin));}.hljs-doctag,.hljs-formula,.hljs-keyword,.hljs-literal {- color: #0550ae;+ color: rgb(var(--syntax-keyword));}.hljs-addition,.hljs-attribute,.hljs-meta-string,.hljs-regexp,.hljs-string {- color: #0a7b62;+ color: rgb(var(--syntax-string));}.hljs-attr,.hljs-number,@@ -1125,59 +1295,14 @@ pre[class*='language-'] {.hljs-template-variable,.hljs-type,.hljs-variable {- color: #9a2f6a;+ color: rgb(var(--syntax-attr));}.hljs-bullet,.hljs-link,.hljs-selector-id,.hljs-symbol,.hljs-title {- color: #b42318;-}-.dark code.hljs,-.dark code[class*='language-'],-.dark pre[class*='language-'] {- color: #fff;-}-.dark .hljs-comment {- color: hsla(0, 0%, 100%, 0.5);-}-.dark .hljs-meta {- color: hsla(0, 0%, 100%, 0.6);-}-.dark .hljs-built_in,-.dark .hljs-class .hljs-title {- color: #e9950c;-}-.dark .hljs-doctag,-.dark .hljs-formula,-.dark .hljs-keyword,-.dark .hljs-literal {- color: #2e95d3;-}-.dark .hljs-addition,-.dark .hljs-attribute,-.dark .hljs-meta-string,-.dark .hljs-regexp,-.dark .hljs-string {- color: #00a67d;-}-.dark .hljs-attr,-.dark .hljs-number,-.dark .hljs-selector-attr,-.dark .hljs-selector-class,-.dark .hljs-selector-pseudo,-.dark .hljs-template-variable,-.dark .hljs-type,-.dark .hljs-variable {- color: #df3079;-}-.dark .hljs-bullet,-.dark .hljs-link,-.dark .hljs-selector-id,-.dark .hljs-symbol,-.dark .hljs-title {- color: #f22c3d;+ color: rgb(var(--syntax-title));}[role='button'],@@ -2233,13 +2358,11 @@ html {padding-right: 0.5rem;font-size: 1rem;line-height: 1.5rem;- color: black;+ color: rgb(var(--text-primary));box-shadow: 0 2px 4px 0 rgb(0 0 0 / 0.25);}.tooltip:where(.dark, .dark *) {- background-color: rgb(var(--surface-primary));- color: white;box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.35);}@@ -2343,7 +2466,7 @@ html[data-input-modality='keyboard'].popover-ui:focus-visible,.popover-ui[data-focus-visible] {- outline: var(--bg-surface-hover);+ outline: 2px solid rgb(var(--text-primary));outline-offset: -1px;}diff --git a/client/src/utils/__tests__/markdown.test.ts b/client/src/utils/__tests__/markdown.test.tsindex 9834f034e9..d084409ddb 100644--- a/client/src/utils/__tests__/markdown.test.ts+++ b/client/src/utils/__tests__/markdown.test.ts@@ -136,6 +136,76 @@ describe('markdown artifacts', () => {expect(files['index.html']).toContain('prefers-color-scheme: dark');});+ /** The base sheet picks its palette from the iframe's own+ * `prefers-color-scheme`, so the contrast block is appended unconditionally+ * and therefore also overrides that media query. */+ it('appends a contrast override that outranks the media query', () => {+ const standard = getMarkdownFiles('# Test')['index.html'];+ expect(standard).toContain('prefers-color-scheme: dark');+ expect(standard).not.toContain('background-color: #000000');++ const contrastDark = getMarkdownFiles('# Test', true, true)['index.html'];+ const overrideIndex = contrastDark.lastIndexOf('.markdown-body { color: #ffffff');+ expect(overrideIndex).toBeGreaterThan(contrastDark.indexOf('prefers-color-scheme: dark'));+ expect(contrastDark).toContain('background-color: #000000');+ expect(contrastDark).toContain('color: #8cc8ff');++ const contrastLight = getMarkdownFiles('# Test', false, true)['index.html'];+ expect(contrastLight).toContain('.markdown-body { color: #000000');+ expect(contrastLight).toContain('color: #0000cc');+ });++ /** Anything the base sheet colours inside the media query has to be answered+ * by the appended block, or an explicit contrast choice keeps a GitHub+ * palette value wherever the override forgot to reach. */+ it('answers every media-query colour in the contrast block', () => {+ const styleOf = (html: string) =>+ html.slice(html.indexOf('<style>') + '<style>'.length, html.indexOf('</style>'));+ const baseStyle = styleOf(getMarkdownFiles('# Test')['index.html']);+ const override = styleOf(getMarkdownFiles('# Test', true, true)['index.html']).slice(+ baseStyle.length,+ );++ /** `selector -> property` pairs, one per selector in a comma-separated list. */+ const declarations = (css: string): string[] =>+ [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].flatMap(([, selectors, body]) =>+ selectors.split(',').flatMap((selector) =>+ body+ .split(';')+ .map((declaration) => declaration.split(':')[0].trim())+ .filter(Boolean)+ .map((property) => `${selector.trim()} -> ${property}`),+ ),+ );++ const answered = new Set(declarations(override));+ const mediaBlocks = [+ ...baseStyle.matchAll(/@media \(prefers-color-scheme: dark\) \{([\s\S]*?)\n\}/g),+ ];+ expect(mediaBlocks.length).toBeGreaterThan(0);++ const unanswered = mediaBlocks+ .flatMap(([, block]) => declarations(block))+ .filter((declaration) => !answered.has(declaration));+ expect(unanswered).toEqual([]);+ });++ /** A CDN outage inside a contrast mode is exactly when the message matters,+ * and an inline style would be the one colour the override cannot reach. */+ it('themes the renderer failure message', () => {+ const standard = getMarkdownFiles('# Test')['index.html'];+ expect(standard).toContain('class="markdown-error"');+ expect(standard).not.toMatch(/style="color:/);+ expect(standard).toContain('color: #e53e3e');++ expect(getMarkdownFiles('# Test', true, true)['index.html']).toContain(+ '.markdown-error { color: #ff8f8f; }',+ );+ expect(getMarkdownFiles('# Test', false, true)['index.html']).toContain(+ '.markdown-error { color: #a10000; }',+ );+ });+describe('content escaping', () => {it('should escape backticks in markdown content', () => {const markdown = 'Here is some `inline code`';@@ -270,7 +340,7 @@ describe('markdown artifacts', () => {expect(html).toContain("typeof marked === 'undefined'");expect(html).toContain('failed to load');- expect(html).toContain('style="color:#e53e3e;padding:1rem"');+ expect(html).toContain('class="markdown-error"');});it('should strip raw HTML blocks via renderer override', () => {diff --git a/client/src/utils/__tests__/mermaid.test.ts b/client/src/utils/__tests__/mermaid.test.tsindex bd08370190..0a54a6c380 100644--- a/client/src/utils/__tests__/mermaid.test.ts+++ b/client/src/utils/__tests__/mermaid.test.ts@@ -3,6 +3,7 @@ import {sanitizeMermaidSvg,artifactFlowchartConfig,inlineFlowchartConfig,+ contrastMermaidVariables,getMermaidFiles,} from '~/utils/mermaid';@@ -269,3 +270,170 @@ describe('mermaid config', () => {});});});++describe('high contrast mermaid palette', () => {+ it('stays out of the way in the standard themes', () => {+ expect(contrastMermaidVariables(false, false)).toBeUndefined();+ expect(contrastMermaidVariables(true, false)).toBeUndefined();+ });++ /** Mermaid's own `neutral` and `dark` palettes are unreachable from a theme+ * token, so a contrast mode has to drive them through themeVariables. */+ it('puts diagrams on the canvas with ink marks in both contrast modes', () => {+ const light = contrastMermaidVariables(false, true)!;+ expect(light.background).toBe('#ffffff');+ expect(light.mainBkg).toBe('#ffffff');+ expect(light.lineColor).toBe('#000000');+ expect(light.textColor).toBe('#000000');+ expect(light.nodeBorder).toBe('#000000');++ const dark = contrastMermaidVariables(true, true)!;+ expect(dark.background).toBe('#000000');+ expect(dark.mainBkg).toBe('#000000');+ expect(dark.lineColor).toBe('#ffffff');+ expect(dark.textColor).toBe('#ffffff');+ expect(dark.nodeBorder).toBe('#ffffff');+ });++ it('switches the artifact document to the base theme and the contrast canvas', () => {+ const standard = getMermaidFiles('graph TD; a-->b', true, false);+ const component = standard['/components/ui/MermaidDiagram.tsx'];+ expect(component).toContain('theme: "dark"');+ expect(component).not.toContain('themeVariables');+ expect(standard['mermaid.css']).toContain('#212121');++ const contrast = getMermaidFiles('graph TD; a-->b', true, true);+ const contrastComponent = contrast['/components/ui/MermaidDiagram.tsx'];+ expect(contrastComponent).toContain('theme: "base"');+ expect(contrastComponent).toContain('"lineColor":"#ffffff"');+ expect(contrast['mermaid.css']).toContain('#000000');+ });++ it('builds the artifact controls from the contrast palette', () => {+ const standard = getMermaidFiles('graph TD; a-->b', false, false)[+ '/components/ui/MermaidDiagram.tsx'+ ];+ expect(standard).toContain('rgba(0, 0, 0, 0.1)');++ const contrast = getMermaidFiles('graph TD; a-->b', false, true)[+ '/components/ui/MermaidDiagram.tsx'+ ];+ /** Fixed greys and 10%-alpha borders cannot clear the floors on a pure+ * canvas, so none of them may survive into the contrast document. */+ expect(contrast).not.toContain('rgba(0, 0, 0, 0.1)');+ expect(contrast).not.toContain('#374151');+ expect(contrast).not.toContain('#6B7280');+ expect(contrast).toContain('2px solid #000000');+ expect(contrast).toContain('color: "#000000"');+ });++ it('maps Gantt tasks and labels to contrast-safe semantic colors', () => {+ const light = contrastMermaidVariables(false, true)!;+ expect(light).toMatchObject({+ taskBkgColor: '#0b4fa0',+ activeTaskBkgColor: '#8f3b00',+ doneTaskBkgColor: '#005c2e',+ doneTaskBorderColor: '#005c2e',+ critBkgColor: '#a10000',+ critBorderColor: '#a10000',+ gridColor: '#000000',+ taskTextColor: '#ffffff',+ taskTextDarkColor: '#ffffff',+ taskTextOutsideColor: '#000000',+ });++ const dark = contrastMermaidVariables(true, true)!;+ expect(dark).toMatchObject({+ taskBkgColor: '#6bb8ff',+ activeTaskBkgColor: '#ffb366',+ doneTaskBkgColor: '#7ff0b3',+ doneTaskBorderColor: '#7ff0b3',+ critBkgColor: '#ff8f8f',+ critBorderColor: '#ff8f8f',+ gridColor: '#ffffff',+ taskTextColor: '#000000',+ taskTextDarkColor: '#000000',+ taskTextOutsideColor: '#ffffff',+ });+ });++ /** Eight branch slots against a seven-slot ramp. The contract is that no two+ * branches share a colour and none of them disappears into the canvas, which+ * is exactly what wrapping the eighth slot back to the first would break. */+ it('gives every Git branch a distinct, visible colour', () => {+ for (const isDarkMode of [false, true]) {+ const vars = contrastMermaidVariables(isDarkMode, true)!;+ const branches = Array.from({ length: 8 }, (_, index) => vars[`git${index}`]);++ expect(new Set(branches).size).toBe(8);+ expect(branches).not.toContain(vars.background);+ /** The first seven are the palette's categorical ramp, the same one the+ * pie slots draw from; the eighth falls back to the ink. */+ expect(branches.slice(0, 7)).toEqual(+ Array.from({ length: 7 }, (_, index) => vars[`pie${index + 1}`]),+ );+ expect(branches[7]).toBe(vars.textColor);+ /** Branch labels are drawn on the branch colour, not on the canvas, and+ * the ramp sits on the far side of the canvas, so the canvas is the+ * readable label here. */+ expect(Array.from({ length: 8 }, (_, index) => vars[`gitBranchLabel${index}`])).toEqual(+ Array(8).fill(vars.background),+ );+ expect(Array.from({ length: 8 }, (_, index) => vars[`gitInv${index}`])).toEqual(+ Array(8).fill(vars.textColor),+ );+ expect(vars).toMatchObject({+ commitLabelColor: vars.textColor,+ commitLabelBackground: vars.background,+ tagLabelColor: vars.textColor,+ tagLabelBackground: vars.background,+ tagLabelBorder: isDarkMode ? '#ffffff' : '#000000',+ });+ }+ });++ it('themes artifact render errors with the semantic destructive color', () => {+ const light = getMermaidFiles('invalid', false, true);+ const lightComponent = light['/components/ui/MermaidDiagram.tsx'];+ expect(lightComponent).toContain('class="mermaid-error"');+ expect(light['mermaid.css']).toContain('color: #a10000');++ const dark = getMermaidFiles('invalid', true, true);+ const darkComponent = dark['/components/ui/MermaidDiagram.tsx'];+ expect(darkComponent).toContain('class="mermaid-error"');+ expect(dark['mermaid.css']).toContain('color: #ff8f8f');+ });++ /** Every node fill is the canvas here, and mermaid derives `pie1..pie3` from+ * the primary, secondary and tertiary colours, so without the series ramp a+ * pie chart loses its encoding entirely. */+ it('keeps pie slices distinct from each other and the canvas', () => {+ for (const isDarkMode of [false, true]) {+ const vars = contrastMermaidVariables(isDarkMode, true)!;+ const slices = Array.from({ length: 12 }, (_, index) => vars[`pie${index + 1}`]);++ expect(slices.every(Boolean)).toBe(true);+ expect(slices.some((slice) => slice === vars.background)).toBe(false);+ /** Seven distinct slots, wrapping after that, so no neighbour repeats. */+ expect(new Set(slices).size).toBe(7);+ slices.slice(0, 6).forEach((slice, index) => {+ expect(slice).not.toBe(slices[index + 1]);+ });+ }+ });++ /** Slice labels sit on a series colour, and the ramp lives on the far side of+ * the canvas so the slices are visible, so the canvas ink is the wrong ink+ * for them. Title and legend are drawn on the canvas and keep it. */+ it('labels slices with the opposing ink and titles with the canvas ink', () => {+ const light = contrastMermaidVariables(false, true)!;+ expect(light.pieSectionTextColor).toBe('#ffffff');+ expect(light.pieTitleTextColor).toBe('#000000');+ expect(light.pieLegendTextColor).toBe('#000000');++ const dark = contrastMermaidVariables(true, true)!;+ expect(dark.pieSectionTextColor).toBe('#000000');+ expect(dark.pieTitleTextColor).toBe('#ffffff');+ expect(dark.pieLegendTextColor).toBe('#ffffff');+ });+});diff --git a/client/src/utils/__tests__/officePreview.spec.ts b/client/src/utils/__tests__/officePreview.spec.tsnew file mode 100644index 0000000000..4ea5af1585--- /dev/null+++ b/client/src/utils/__tests__/officePreview.spec.ts@@ -0,0 +1,62 @@+import { withOfficeContrast } from '../officePreview';++/** A trimmed stand-in for what `wrapAsDocument` in `packages/api` emits: a+ * `:root` palette plus the `prefers-color-scheme` block that used to be the+ * only thing deciding an Office preview's colours. */+const backendDocument = `<!DOCTYPE html>+<html><head><style>+:root { color-scheme: light dark; --bg: #ffffff; --fg: #1f2937; --link: #2563eb; }+@media (prefers-color-scheme: dark) { :root { --bg: #1a1a2e; --fg: #e5e7eb; } }+</style></head><body>Preview</body></html>`;++describe('withOfficeContrast', () => {+ /** Both `:root` blocks have the same specificity, so order is the only thing+ * that decides the winner — the override has to come last, and still inside+ * the head where the document's own styles live. */+ it('overrides the document palette from inside the head', () => {+ const rendered = withOfficeContrast(backendDocument, true);+ const mediaRule = rendered.indexOf('prefers-color-scheme: dark');+ const override = rendered.lastIndexOf('<style>');++ expect(override).toBeGreaterThan(mediaRule);+ expect(rendered.indexOf('</head>')).toBeGreaterThan(override);+ });++ /** The bug this closes: the preview followed the OS, so an explicit dark+ * contrast mode still rendered light whenever the OS was light. Pinning+ * `color-scheme` is what stops the iframe consulting the OS at all. */+ it.each([+ ['dark', true, '#000000', '#ffffff'],+ ['light', false, '#ffffff', '#000000'],+ ] as const)('resolves %s mode against the OS preference', (mode, isDarkMode, canvas, ink) => {+ const rendered = withOfficeContrast(backendDocument, isDarkMode);++ expect(rendered.match(/color-scheme:\s*[^;]+/g)?.at(-1)).toBe(`color-scheme: ${mode}`);+ expect(rendered).toContain(`--bg: ${canvas};`);+ expect(rendered).toContain(`--fg: ${ink};`);+ });++ /** Zebra rows, row hover and the sticky header are three separate cues in the+ * backend document; collapsing them onto one fill would silently merge them. */+ it('keeps the row, hover and header fills distinct', () => {+ const rendered = withOfficeContrast(backendDocument, false);+ const fills = ['--row-alt', '--row-hover', '--header-bg'].map(+ (name) => rendered.match(new RegExp(`${name}:\\s*(#[0-9a-f]{6})`))?.[1],+ );++ expect(fills.every(Boolean)).toBe(true);+ expect(new Set(fills).size).toBe(3);+ expect(fills).not.toContain('#ffffff');+ });++ it('still applies to a fragment with no head to close', () => {+ const rendered = withOfficeContrast('<body>Preview</body>', true);++ expect(rendered.startsWith('<style>')).toBe(true);+ expect(rendered).toContain('<body>Preview</body>');+ });++ it('returns empty content unchanged', () => {+ expect(withOfficeContrast('', true)).toBe('');+ });+});diff --git a/client/src/utils/forms.spec.tsx b/client/src/utils/forms.spec.tsxindex 477c3c5f2e..a36f108e87 100644--- a/client/src/utils/forms.spec.tsx+++ b/client/src/utils/forms.spec.tsx@@ -1,4 +1,6 @@-import { getDefaultAgentFormValues } from './forms';+import React from 'react';+import type { Agent } from 'librechat-data-provider';+import { getDefaultAgentFormValues, processAgentOption } from './forms';describe('getDefaultAgentFormValues', () => {it('uses the scalable user workspace by default', () => {@@ -8,4 +10,15 @@ describe('getDefaultAgentFormValues', () => {it('seeds a new agent with the user workspace preference', () => {expect(getDefaultAgentFormValues('agent-user').stateful_code_environment).toBe('agent-user');});++ it('uses the semantic success marker for public agent options', () => {+ const option = processAgentOption({+ agent: { id: 'public-agent', name: 'Public agent', isPublic: true } as Agent,+ });++ expect(React.isValidElement(option.icon)).toBe(true);+ expect((option.icon as React.ReactElement<{ className: string }>).props.className).toContain(+ 'text-status-success',+ );+ });});diff --git a/client/src/utils/markdown.ts b/client/src/utils/markdown.tsindex 52d3363132..9427d50ec4 100644--- a/client/src/utils/markdown.ts+++ b/client/src/utils/markdown.ts@@ -1,3 +1,6 @@+import { highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';+import type { IThemeRGB } from '@librechat/client';+const SAFE_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);/**@@ -169,6 +172,13 @@ const markdownCSS = `box-sizing: content-box;}+/* Rendered in place of the document when the marked CDN does not load. Its own+ rule rather than an inline style so a contrast mode can reach it. */+.markdown-error {+ color: #e53e3e;+ padding: 1rem;+}+/* Dark theme */@media (prefers-color-scheme: dark) {.markdown-body {@@ -255,7 +265,53 @@ const isSafeUrl = (url) => {try { return SAFE_PROTOCOLS.has(new URL(trimmed).protocol); } catch(e) { return false; }};`;-function generateMarkdownHtml(content: string): string {+/**+ * The stylesheet above is a fixed GitHub palette selected by the iframe's own+ * `prefers-color-scheme`, which no app token reaches. In a contrast mode this+ * block is appended unconditionally, so it also overrides that media query and+ * an explicit contrast choice is honoured whatever the OS is set to. Every+ * colour the media query sets has to be answered here, including the `thead`+ * tint: leaving it would strand #f6f8fa or #161b22 under the new ink. Contrast+ * palettes collapse subtle fills onto the canvas, so the header reads through+ * its bold cells and its border rather than a tint of its own.+ */+function contrastMarkdownCSS(isDarkMode: boolean): string {+ const palette = isDarkMode ? highContrastDarkTheme : highContrastLightTheme;+ const hex = (token: keyof IThemeRGB, fallback: string): string => {+ const channels = palette[token]?.trim().split(/\s+/).map(Number);+ if (channels?.length !== 3 || channels.some(Number.isNaN)) {+ return fallback;+ }+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;+ };++ const canvas = hex('rgb-surface-primary', isDarkMode ? '#000000' : '#ffffff');+ const ink = hex('rgb-text-primary', isDarkMode ? '#ffffff' : '#000000');+ const link = hex('rgb-link', isDarkMode ? '#8cc8ff' : '#0000cc');+ const border = hex('rgb-border-medium', ink);+ const codeFill = hex('rgb-surface-secondary', canvas);+ /** The renderer-failure notice is the one message this document paints itself,+ * and it has to survive a CDN outage inside a contrast mode. */+ const destructive = hex('rgb-text-destructive', isDarkMode ? '#ff8f8f' : '#a10000');++ return `+.markdown-body { color: ${ink}; background-color: ${canvas}; }+body { background-color: ${canvas}; }+.markdown-body h1, .markdown-body h2 { border-bottom-color: ${border}; }+.markdown-body a, .markdown-body a:hover { color: ${link}; text-decoration: underline; }+.markdown-body table th, .markdown-body table td { border-color: ${border}; }+.markdown-body table thead { background-color: ${canvas}; }+.markdown-body blockquote { border-left-color: ${border}; color: ${ink}; }+.markdown-body hr { background-color: ${border}; }+.markdown-body code, .markdown-body pre { color: ${ink}; background-color: ${codeFill}; }+.markdown-body pre { border: 1px solid ${border}; }+::-webkit-scrollbar-thumb { background-color: ${ink}; }+* { scrollbar-color: ${ink} ${canvas}; }+.markdown-error { color: ${destructive}; }+`;+}++function generateMarkdownHtml(content: string, contrastCSS = ''): string {const normalizedContent = content.replace(/^( {2})(-|\d+\.)/gm, ' $2');const escapedContent = escapeForTemplateLiteral(normalizedContent);@@ -265,7 +321,7 @@ function generateMarkdownHtml(content: string): string {<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Markdown Preview</title>-<style>${markdownCSS}</style>+<style>${markdownCSS}${contrastCSS}</style></head><body><div class="markdown-body" id="content" style="padding:2rem;margin:1rem;min-height:100vh"></div>@@ -273,7 +329,7 @@ function generateMarkdownHtml(content: string): string {<script>if (typeof marked === 'undefined') {document.getElementById('content').innerHTML =- '<p style="color:#e53e3e;padding:1rem">Markdown renderer failed to load. Check network connectivity.</p>';+ '<p class="markdown-error">Markdown renderer failed to load. Check network connectivity.</p>';} else {${EMBEDDED_IS_SAFE_URL}marked.use({@@ -298,10 +354,14 @@ document.getElementById('content').innerHTML = marked.parse(\`${escapedContent}\</html>`;}-export const getMarkdownFiles = (content: string): Record<string, string> => {+export const getMarkdownFiles = (+ content: string,+ isDarkMode = false,+ highContrast = false,+): Record<string, string> => {const md = content || '# No content provided';return {'content.md': md,- 'index.html': generateMarkdownHtml(md),+ 'index.html': generateMarkdownHtml(md, highContrast ? contrastMarkdownCSS(isDarkMode) : ''),};};diff --git a/client/src/utils/mermaid.ts b/client/src/utils/mermaid.tsindex 679c41544d..c1a08316fb 100644--- a/client/src/utils/mermaid.ts+++ b/client/src/utils/mermaid.ts@@ -1,5 +1,7 @@import dedent from 'dedent';import DOMPurify from 'dompurify';+import { highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';+import type { IThemeRGB } from '@librechat/client';interface MermaidButtonStyles {bg: string;@@ -31,8 +33,35 @@ const lightButtonStyles: MermaidButtonStyles = {divider: 'rgba(0, 0, 0, 0.1)',};-const getButtonStyles = (isDarkMode: boolean): MermaidButtonStyles =>- isDarkMode ? darkButtonStyles : lightButtonStyles;+/**+ * The standard control palettes hold fixed greys and 10%-alpha borders, which+ * leave the zoom label below AAA and the border and divider below the 3:1+ * non-text floor against a pure canvas, so a contrast mode builds its controls+ * from the same tokens the diagram uses.+ */+const contrastButtonStyles = (isDarkMode: boolean): MermaidButtonStyles => {+ const palette = isDarkMode ? highContrastDarkTheme : highContrastLightTheme;+ const canvas = tokenHex(palette['rgb-surface-primary'], isDarkMode ? '#000000' : '#ffffff');+ const ink = tokenHex(palette['rgb-text-primary'], isDarkMode ? '#ffffff' : '#000000');+ const active = tokenHex(palette['rgb-surface-active'], isDarkMode ? '#5c5c5c' : '#8c8c8c');++ return {+ bg: canvas,+ bgHover: active,+ border: `2px solid ${ink}`,+ text: ink,+ textSecondary: ink,+ shadow: 'none',+ divider: ink,+ };+};++const getButtonStyles = (isDarkMode: boolean, highContrast = false): MermaidButtonStyles => {+ if (highContrast) {+ return contrastButtonStyles(isDarkMode);+ }+ return isDarkMode ? darkButtonStyles : lightButtonStyles;+};const baseFlowchartConfig = {curve: 'basis' as const,@@ -58,6 +87,147 @@ const inlineFlowchartConfig = {export { inlineFlowchartConfig, artifactFlowchartConfig };+const tokenHex = (triplet: string | undefined, fallback: string): string => {+ const channels = triplet?.trim().split(/\s+/).map(Number);+ if (channels?.length !== 3 || channels.some(Number.isNaN)) {+ return fallback;+ }+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;+};++const seriesColors = (palette: IThemeRGB): string[] =>+ Array.from({ length: 7 }, (_, index) =>+ tokenHex(palette[`rgb-series-${index + 1}` as keyof IThemeRGB], '#000000'),+ );++/** Mermaid reads twelve pie slots; the palette ships seven, so they wrap. */+const seriesVariables = (slots: string[]): Record<string, string> => {+ return Object.fromEntries(+ Array.from({ length: 12 }, (_, index) => [`pie${index + 1}`, slots[index % slots.length]]),+ );+};++/**+ * Mermaid keeps a Git branch palette (`git0`-`git7`) separate from the pie and+ * Gantt ones, so the base theme's bright green, yellow, cyan and white survive+ * into a contrast mode unless these slots are populated too.+ *+ * Eight slots against a seven-slot ramp. Wrapping would give branch 8 the same+ * colour as branch 1, which is the one thing a categorical scale must not do,+ * so the last slot takes the ink instead: 21:1 on the canvas and outside the+ * ramp, therefore distinct from all seven. `gitBranchLabel*` is the label drawn+ * ON the branch colour, so it takes the canvas rather than the ink — the ramp+ * lives on the far side of the canvas precisely so the branches are visible.+ */+const gitVariables = (slots: string[], canvas: string, ink: string): Record<string, string> =>+ Object.fromEntries(+ Array.from({ length: 8 }, (_, index) => [+ [`git${index}`, slots[index] ?? ink],+ [`gitBranchLabel${index}`, canvas],+ [`gitInv${index}`, ink],+ ]).flat(),+ );++/**+ * Mermaid's built-in `neutral` and `dark` themes carry their own palette, which+ * no app token can reach, so a diagram keeps mid-grey nodes and mid-grey edges+ * in a contrast mode. These variables put the diagram on the canvas with ink+ * nodes, ink edges and ink labels, which is 21:1 for every mark and every+ * label. Returns undefined outside the contrast modes so the standard themes+ * keep rendering exactly as they do today.+ */+export const contrastMermaidVariables = (+ isDarkMode: boolean,+ highContrast: boolean,+): Record<string, string> | undefined => {+ if (!highContrast) {+ return undefined;+ }++ const palette = isDarkMode ? highContrastDarkTheme : highContrastLightTheme;+ const canvas = tokenHex(palette['rgb-surface-primary'], isDarkMode ? '#000000' : '#ffffff');+ const ink = tokenHex(palette['rgb-text-primary'], isDarkMode ? '#ffffff' : '#000000');+ /** The label colour for anything drawn on a solid fill rather than the canvas. */+ const onFill = tokenHex(palette['rgb-text-on-status'], isDarkMode ? '#000000' : '#ffffff');+ const series = seriesColors(palette);+ const active = tokenHex(palette['rgb-surface-active'], ink);+ const successFill = tokenHex(palette['rgb-status-success-strong'], series[2]);+ const successBorder = tokenHex(palette['rgb-status-success-border'], successFill);+ const errorFill = tokenHex(palette['rgb-status-error-strong'], series[4]);+ const errorBorder = tokenHex(palette['rgb-status-error-border'], errorFill);+ const errorText = tokenHex(palette['rgb-text-destructive'], errorBorder);++ return {+ background: canvas,+ mainBkg: canvas,+ primaryColor: canvas,+ secondaryColor: canvas,+ tertiaryColor: canvas,+ clusterBkg: canvas,+ edgeLabelBackground: canvas,+ primaryTextColor: ink,+ secondaryTextColor: ink,+ tertiaryTextColor: ink,+ textColor: ink,+ titleColor: ink,+ primaryBorderColor: ink,+ secondaryBorderColor: ink,+ tertiaryBorderColor: ink,+ nodeBorder: ink,+ clusterBorder: ink,+ lineColor: ink,+ errorBkgColor: canvas,+ errorTextColor: errorText,+ sectionBkgColor: series[2],+ sectionBkgColor2: series[3],+ altSectionBkgColor: series[4],+ excludeBkgColor: active,+ taskBkgColor: series[0],+ taskBorderColor: series[0],+ activeTaskBkgColor: series[1],+ activeTaskBorderColor: series[1],+ doneTaskBkgColor: successFill,+ doneTaskBorderColor: successBorder,+ critBkgColor: errorFill,+ critBorderColor: errorBorder,+ todayLineColor: errorBorder,+ vertLineColor: errorBorder,+ gridColor: ink,+ taskTextColor: onFill,+ taskTextOutsideColor: ink,+ taskTextLightColor: onFill,+ taskTextDarkColor: onFill,+ taskTextClickableColor: onFill,+ /**+ * `pie1`..`pie12` otherwise derive from the primary, secondary and tertiary+ * colours, which are all the canvas here, so every slice would collapse+ * into the background and into its neighbours. The series scale is the+ * palette's own categorical ramp: seven slots that clear the 3:1 mark floor+ * on this canvas and stay separable under simulated deuteranopia. Slices+ * beyond the seventh wrap, which mermaid's own palettes do as well.+ */+ ...seriesVariables(series),+ ...gitVariables(series, canvas, ink),+ commitLabelColor: ink,+ commitLabelBackground: canvas,+ tagLabelColor: ink,+ tagLabelBackground: canvas,+ tagLabelBorder: tokenHex(palette['rgb-border-medium'], ink),+ pieStrokeColor: ink,+ pieOuterStrokeColor: ink,+ pieTitleTextColor: ink,+ /**+ * Labels drawn inside a slice sit on a series colour, not on the canvas, and+ * the series ramp deliberately lives on the far side of the canvas so the+ * slices are visible. So this one takes the opposing ink, the same+ * `text-on-status` the palette uses for a label on a solid fill. Title and+ * legend stay on the canvas ink, since they are drawn on the canvas.+ */+ pieSectionTextColor: onFill,+ pieLegendTextColor: ink,+ };+};+/** Perceived luminance (0 = black, 1 = white) via BT.601 luma coefficients */const hexLuminance = (hex: string): number => {let h = hex.replace('#', '');@@ -143,6 +313,7 @@ const buildMermaidComponent = (mermaidTheme: string,bgColor: string,btnStyles: MermaidButtonStyles,+ themeVariables?: Record<string, string>,) =>dedent(`import React, { useEffect, useRef, useState, useCallback } from "react";import {@@ -289,6 +460,7 @@ const MermaidDiagram: React.FC<MermaidDiagramProps> = ({ content }) => {mermaid.initialize({startOnLoad: false,theme: "${mermaidTheme}",+ ${themeVariables ? `themeVariables: ${JSON.stringify(themeVariables)},` : ''}securityLevel: "strict",flowchart: ${JSON.stringify(artifactFlowchartConfig, null, 8)},});@@ -310,7 +482,7 @@ const MermaidDiagram: React.FC<MermaidDiagramProps> = ({ content }) => {} catch (error) {console.error("Mermaid rendering error:", error);if (mermaidRef.current) {- mermaidRef.current.innerHTML = "Error rendering diagram";+ mermaidRef.current.innerHTML = '<p class="mermaid-error">Error rendering diagram</p>';}}};@@ -461,14 +633,21 @@ export default App;`);};-export const getMermaidFiles = (content: string, isDarkMode = true) => {- const mermaidTheme = isDarkMode ? 'dark' : 'neutral';- const btnStyles = getButtonStyles(isDarkMode);- const bgColor = isDarkMode ? '#212121' : '#FFFFFF';+export const getMermaidFiles = (content: string, isDarkMode = true, highContrast = false) => {+ const themeVariables = contrastMermaidVariables(isDarkMode, highContrast);+ const standardTheme = isDarkMode ? 'dark' : 'neutral';+ /** `base` is the only built-in mermaid theme that honours themeVariables. */+ const mermaidTheme = themeVariables ? 'base' : standardTheme;+ const btnStyles = getButtonStyles(isDarkMode, highContrast);+ const bgColor = themeVariables?.background ?? (isDarkMode ? '#212121' : '#FFFFFF');+ const errorTextColor = themeVariables?.errorTextColor ?? btnStyles.text;const mermaidCSS = `body {background-color: ${bgColor};}+.mermaid-error {+ color: ${errorTextColor};+}`;return {@@ -484,7 +663,12 @@ import App from "./App";const root = createRoot(document.getElementById("root"));root.render(<App />);;`),- '/components/ui/MermaidDiagram.tsx': buildMermaidComponent(mermaidTheme, bgColor, btnStyles),+ '/components/ui/MermaidDiagram.tsx': buildMermaidComponent(+ mermaidTheme,+ bgColor,+ btnStyles,+ themeVariables,+ ),'mermaid.css': mermaidCSS,};};diff --git a/client/src/utils/officePreview.ts b/client/src/utils/officePreview.tsnew file mode 100644index 0000000000..28a8a5bf21--- /dev/null+++ b/client/src/utils/officePreview.ts@@ -0,0 +1,64 @@+import { highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';+import type { IThemeRGB } from '@librechat/client';++/**+ * Re-declares the backend document's palette tokens for the selected contrast+ * mode. The document is generated server-side, so its theme cannot know the+ * viewer's explicit appearance choice.+ */+export function withOfficeContrast(html: string, isDarkMode: boolean): string {+ if (!html) {+ return html;+ }++ const palette = isDarkMode ? highContrastDarkTheme : highContrastLightTheme;+ const hex = (token: keyof IThemeRGB, fallback: string): string => {+ const channels = palette[token]?.trim().split(/\s+/).map(Number);+ if (channels?.length !== 3 || channels.some(Number.isNaN)) {+ return fallback;+ }+ return `#${channels.map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;+ };++ const canvas = hex('rgb-surface-primary', isDarkMode ? '#000000' : '#ffffff');+ /** Every ink token collapses to one pure ink in these palettes, so `--muted`+ * has no softer colour available to it and takes the same value as `--fg`. */+ const ink = hex('rgb-text-primary', isDarkMode ? '#ffffff' : '#000000');+ const border = hex('rgb-border-medium', ink);+ /** Three separable steps off the canvas, so zebra striping, row hover and the+ * header keep telling each other apart. Each still carries ink at AAA, and+ * the header and active sheet tab additionally get the ink `--border` the+ * backend already draws around them, which is what marks them at 3:1. */+ const subtle = hex('rgb-surface-active', canvas);+ const hover = hex('rgb-surface-hover', canvas);+ const raised = hex('rgb-surface-hover-alt', hover);+ const link = hex('rgb-link', isDarkMode ? '#8cc8ff' : '#0000cc');+ const scheme = isDarkMode ? 'dark' : 'light';+ const contrastCSS = `+:root {+ color-scheme: ${scheme};+ --bg: ${canvas};+ --fg: ${ink};+ --muted: ${ink};+ --border: ${border};+ --row-alt: ${subtle};+ --row-hover: ${hover};+ --header-bg: ${raised};+ --tab-active-bg: ${raised};+ --tab-bg: ${canvas};+ --link: ${link};+}+/** WCAG 1.4.1: a link in running text must not be colour alone. */+a { text-decoration: underline; }+`;+ const style = `<style>${contrastCSS}</style>`;+ const headClose = html.toLowerCase().indexOf('</head>');++ // Keep this block last in <head> so it wins the backend stylesheet's equal-specificity media query.+ if (headClose >= 0) {+ return `${html.slice(0, headClose)}${style}${html.slice(headClose)}`;+ }++ // Malformed/partial previews may omit <head>; prepend because there is no head boundary to insert before.+ return `${style}${html}`;+}diff --git a/packages/client/src/components/AlertDialog.tsx b/packages/client/src/components/AlertDialog.tsxindex 09d72590c3..b917237c9e 100644--- a/packages/client/src/components/AlertDialog.tsx+++ b/packages/client/src/components/AlertDialog.tsx@@ -47,7 +47,9 @@ const AlertDialogContent: React.ForwardRefExoticComponent<<AlertDialogPrimitive.Contentref={ref}className={cn(- 'fixed z-50 grid w-full max-w-lg scale-100 gap-4 bg-surface-dialog p-6 opacity-100 animate-in fade-in-90 slide-in-from-bottom-10 sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full',+ /** The dialog surface is otherwise borderless: in high contrast it sits on+ * a canvas of its own colour, so it needs a drawn edge. */+ 'fixed z-50 grid w-full max-w-lg scale-100 gap-4 bg-surface-dialog p-6 opacity-100 animate-in fade-in-90 slide-in-from-bottom-10 high-contrast:border high-contrast:border-solid high-contrast:border-border-medium sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full',className,)}{...props}diff --git a/packages/client/src/components/Dialog.tsx b/packages/client/src/components/Dialog.tsxindex 38fe8ea404..e05d536e80 100644--- a/packages/client/src/components/Dialog.tsx+++ b/packages/client/src/components/Dialog.tsx@@ -60,7 +60,9 @@ const DialogContent: React.ForwardRefExoticComponent<<DialogPrimitive.Contentref={ref}className={cn(- 'fixed z-[999] grid w-full gap-4 rounded-b-lg bg-surface-dialog pb-6 animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:rounded-lg',+ /** The dialog surface is otherwise borderless: in high contrast it sits+ * on a canvas of its own colour, so it needs a drawn edge. */+ 'fixed z-[999] grid w-full gap-4 rounded-b-lg bg-surface-dialog pb-6 animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 high-contrast:border high-contrast:border-solid high-contrast:border-border-medium sm:rounded-lg',isSmallScreen? 'fixed left-1/2 top-1/2 z-[999] m-auto grid w-11/12 -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-surface-dialog pb-6': '',diff --git a/packages/client/src/components/DialogTemplate.tsx b/packages/client/src/components/DialogTemplate.tsxindex 197574ba61..ab3f02930e 100644--- a/packages/client/src/components/DialogTemplate.tsx+++ b/packages/client/src/components/DialogTemplate.tsx@@ -54,7 +54,10 @@ const DialogTemplate: ForwardRefExoticComponent<<DialogContentshowCloseButton={showCloseButton}ref={ref}- className={cn('bg-surface-dialog shadow-2xl', className || '')}+ className={cn(+ 'bg-surface-dialog shadow-2xl high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none',+ className || '',+ )}onClick={(e) => e.stopPropagation()}><DialogHeader className={cn(headerClassName ?? '')}>diff --git a/packages/client/src/components/Dropdown.css b/packages/client/src/components/Dropdown.cssindex 9728604bf6..8f43d01df5 100644--- a/packages/client/src/components/Dropdown.css+++ b/packages/client/src/components/Dropdown.css@@ -24,6 +24,14 @@margin-right: -2px;}+/* Elevation here is a black shadow, which carries no separation at all against+ * a pure black surface. Lives with the primitive rather than in the app+ * stylesheet, which the published package does not include. */+html.high-contrast .popover-ui {+ border: 1px solid rgb(var(--border-medium));+ box-shadow: none;+}+.popover-animate {opacity: 0;transform: scale(0.95) translateY(-0.5rem);@@ -38,7 +46,7 @@.popover-ui:focus-visible,.popover-ui[data-focus-visible] {- outline: var(--bg-surface-hover);+ outline: 2px solid rgb(var(--text-primary));outline-offset: -1px;}diff --git a/packages/client/src/components/OGDialogTemplate.tsx b/packages/client/src/components/OGDialogTemplate.tsxindex f78f689457..b42570278a 100644--- a/packages/client/src/components/OGDialogTemplate.tsx+++ b/packages/client/src/components/OGDialogTemplate.tsx@@ -121,7 +121,12 @@ const OGDialogTemplate: ForwardRefExoticComponent<overlayClassName={overlayClassName}showCloseButton={showCloseButton}ref={ref}- className={cn('w-11/12 border-none bg-surface-dialog text-text-primary', className ?? '')}+ className={cn(+ /** `border-none` clears the default edge; the contrast variant has to+ * restore the style as well as the width to survive it. */+ 'w-11/12 border-none bg-surface-dialog text-text-primary high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none',+ className ?? '',+ )}onClick={(e) => e.stopPropagation()}><OGDialogHeader className={cn(headerClassName ?? '')}>diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsxindex 53dc3a08cf..895a14b62b 100644--- a/packages/client/src/components/OriginalDialog.tsx+++ b/packages/client/src/components/OriginalDialog.tsx@@ -170,7 +170,9 @@ const DialogContent: React.ForwardRefExoticComponent<style={{ ...style, zIndex: contentZIndex }}onEscapeKeyDown={handleEscapeKeyDown}className={cn(- 'max-w-11/12 fixed left-[50%] top-[50%] grid max-h-[90vh] w-full translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-2xl bg-surface-dialog p-6 text-text-primary shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]',+ /** `shadow-lg` is a black shadow, which carries no separation against+ * a pure black surface, so high contrast trades it for a real edge. */+ 'max-w-11/12 fixed left-[50%] top-[50%] grid max-h-[90vh] w-full translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto rounded-2xl bg-surface-dialog p-6 text-text-primary shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] high-contrast:border high-contrast:border-solid high-contrast:border-border-medium high-contrast:shadow-none',className,)}{...props}diff --git a/packages/client/src/components/ThemeSelector.spec.tsx b/packages/client/src/components/ThemeSelector.spec.tsxindex 915b658e60..1cf93b13a2 100644--- a/packages/client/src/components/ThemeSelector.spec.tsx+++ b/packages/client/src/components/ThemeSelector.spec.tsx@@ -1,45 +1,79 @@+import '@testing-library/jest-dom';import React from 'react';-import { render, screen, fireEvent } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import ThemeSelector from './ThemeSelector';import { ThemeContext } from '../theme';jest.mock('./MorphIcon', () => {const { createMorphIconMock } = jest.requireActual('../test/mockMorphIcon');- const { Sun, Moon, Monitor } = jest.requireActual('lucide');+ const { Sun, Moon, Monitor, Contrast } = jest.requireActual('lucide');return {MorphIcon: createMorphIconMock([[Sun, 'sun'],[Moon, 'moon'],[Monitor, 'monitor'],+ [Contrast, 'contrast'],]),};});-function renderTheme(theme: string, setTheme = jest.fn()) {- return render(+jest.mock('../hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++const renderWith = (+ theme: string,+ highContrast: boolean,+ setTheme: jest.Mock,+ children: React.ReactElement,+) => {+ const view = render(<ThemeContext.Provider- value={{- theme,- setTheme,- setThemeRGB: jest.fn(),- setThemeName: jest.fn(),- resetTheme: jest.fn(),- }}+ value={+ {+ theme,+ setTheme,+ resolvedMode: 'light',+ highContrast,+ setThemeRGB: () => undefined,+ setThemeDefinition: () => undefined,+ setThemeName: () => undefined,+ resetTheme: () => undefined,+ } as React.ContextType<typeof ThemeContext>+ }>- <ThemeSelector returnThemeOnly />+ {children}</ThemeContext.Provider>,);-}+ return { setTheme, unmount: view.unmount };+};-describe('ThemeSelector MorphIcon map', () => {- beforeEach(() => {- Object.defineProperty(window, 'lastThemeChange', {- writable: true,- configurable: true,- value: 0,- });- });+const renderTheme = (theme: string, highContrast = false, setTheme = jest.fn()) =>+ renderWith(theme, highContrast, setTheme, <ThemeSelector returnThemeOnly />);+/** The form the auth routes render: both appearance controls, no host chrome. */+const renderAuthControls = (theme: string, highContrast = false, setTheme = jest.fn()) =>+ renderWith(theme, highContrast, setTheme, <ThemeSelector />);++beforeEach(() => {+ /** `changeTheme` throttles itself through this global for 500ms. */+ window.lastThemeChange = undefined;+ window.matchMedia = jest.fn().mockImplementation(+ (media: string) =>+ ({+ matches: false,+ media,+ onchange: null,+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ addListener: jest.fn(),+ removeListener: jest.fn(),+ dispatchEvent: jest.fn(),+ }) as unknown as MediaQueryList,+ );+});++describe('ThemeSelector MorphIcon map', () => {it('shows monitor for system, moon for dark, sun for light', () => {const system = renderTheme('system');expect(screen.getByTestId('monitor')).toBeInTheDocument();@@ -54,11 +88,100 @@ describe('ThemeSelector MorphIcon map', () => {expect(screen.getByTestId('sun')).toBeInTheDocument();});+ /** An unmapped icon falls back to `morph-icon`, so a missing high contrast+ * entry in the icon record would surface here rather than as a blank glyph.+ * The contrast modes show their scheme, because the contrast toggle beside+ * them owns the contrast glyph. */+ it('shows the scheme icon for both high contrast modes', () => {+ const light = renderTheme('high-contrast-light', true);+ expect(screen.getByTestId('sun')).toBeInTheDocument();+ light.unmount();++ renderTheme('high-contrast-dark', true);+ expect(screen.getByTestId('moon')).toBeInTheDocument();+ });+it('toggles theme when the button is activated', () => {- const setTheme = jest.fn();// isDark('light') is false → next is dark- renderTheme('light', setTheme);+ const { setTheme } = renderTheme('light');fireEvent.click(screen.getByRole('button', { name: 'com_ui_toggle_theme' }));expect(setTheme).toHaveBeenCalledWith('dark');});});++describe('ThemeSelector scheme toggle', () => {+ it('flips the scheme and keeps an explicit contrast choice', () => {+ const { setTheme } = renderTheme('high-contrast-light', true);+ fireEvent.click(screen.getByRole('button'));+ expect(setTheme).toHaveBeenCalledWith('high-contrast-dark');+ });++ /** Under `system` the contrast comes from `prefers-contrast`, so the stored+ * mode never names it and only the resolved value can carry it forward. */+ it('keeps an OS-requested contrast when the stored mode is system', () => {+ const { setTheme } = renderTheme('system', true);+ fireEvent.click(screen.getByRole('button'));+ expect(setTheme).toHaveBeenCalledWith('high-contrast-dark');+ });++ it('leaves an ordinary system mode on the plain schemes', () => {+ const { setTheme } = renderTheme('system', false);+ fireEvent.click(screen.getByRole('button'));+ expect(setTheme).toHaveBeenCalledWith('dark');+ });++ it('answers Ctrl+Shift+T with the same choice', () => {+ const { setTheme } = renderTheme('system', true);+ fireEvent.keyDown(window, { key: 'T', ctrlKey: true, shiftKey: true });+ expect(setTheme).toHaveBeenCalledWith('high-contrast-dark');+ });+});++/** The auth routes render this selector alone, so contrast has to be reachable+ * from it — the scheme toggle preserves a contrast choice but never makes one. */+describe('ThemeSelector contrast toggle', () => {+ it('turns contrast on for the scheme currently rendered', () => {+ const { setTheme } = renderAuthControls('dark');+ const toggle = screen.getByRole('button', { name: 'com_ui_toggle_high_contrast' });+ expect(toggle).toHaveAttribute('aria-pressed', 'false');+ fireEvent.click(toggle);+ expect(setTheme).toHaveBeenCalledWith('high-contrast-dark');+ });++ it('turns an explicit contrast mode back off', () => {+ const { setTheme } = renderAuthControls('high-contrast-light', true);+ const toggle = screen.getByRole('button', { name: 'com_ui_toggle_high_contrast' });+ expect(toggle).toHaveAttribute('aria-pressed', 'true');+ fireEvent.click(toggle);+ expect(setTheme).toHaveBeenCalledWith('light');+ });++ /** Under `system` the OS supplies the contrast, so opting out has to name an+ * explicit mode rather than leave `system` to switch it straight back on. */+ it('opts out of an OS-requested contrast explicitly', () => {+ const { setTheme } = renderAuthControls('system', true);+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_toggle_high_contrast' }));+ expect(setTheme).toHaveBeenCalledWith('light');+ });++ /** The two controls are independent settings, so a single gesture that flips+ * both — plain light to high-contrast dark — has to land twice. A throttle+ * shared across the pair swallowed whichever click came second. */+ it('accepts both controls inside one throttle window', () => {+ const { setTheme } = renderAuthControls('light');+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_toggle_theme' }));+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_toggle_high_contrast' }));+ expect(setTheme).toHaveBeenNthCalledWith(1, 'dark');+ expect(setTheme).toHaveBeenNthCalledWith(2, 'high-contrast-light');+ });++ /** The throttle still does its job within a control: Ctrl+Shift+T auto-repeats+ * while held, and a held key must not stream theme writes. */+ it('still throttles repeats of the same control', () => {+ const { setTheme } = renderAuthControls('light');+ const toggle = screen.getByRole('button', { name: 'com_ui_toggle_high_contrast' });+ fireEvent.click(toggle);+ fireEvent.click(toggle);+ expect(setTheme).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/client/src/components/ThemeSelector.tsx b/packages/client/src/components/ThemeSelector.tsxindex 9ed3b83ac9..00666e36bf 100644--- a/packages/client/src/components/ThemeSelector.tsx+++ b/packages/client/src/components/ThemeSelector.tsx@@ -1,30 +1,56 @@import { useContext, useCallback, useEffect, useState } from 'react';import { JSX } from 'react/jsx-runtime';-import { Sun, Moon, Monitor } from 'lucide';+import { Sun, Moon, Monitor, Contrast } from 'lucide';import type { IconNode } from './MorphIcon';-import { ThemeContext, isDark } from '../theme';+import { ThemeContext, isDark, isHighContrast } from '../theme';import { MorphIcon } from './MorphIcon';import { useLocalize } from '../hooks';import { Button } from './Button';declare global {interface Window {- lastThemeChange?: number;+ /** Last accepted change per appearance control. Global rather than a ref so+ * the throttle survives the selector remounting, which the auth routes do+ * on every navigation between login, register and verification. */+ lastThemeChange?: Record<string, number>;}}-type ThemeType = 'system' | 'dark' | 'light';+/** Ctrl+Shift+T auto-repeats while held, which is what this throttle is for.+ * Keyed per control, because the scheme and contrast toggles are independent+ * settings: going from plain light to high-contrast dark is one flip of each,+ * and a shared window would silently swallow the second click. */+const CHANGE_THROTTLE_MS = 500;+type ThemeType = 'system' | 'dark' | 'light' | 'high-contrast-light' | 'high-contrast-dark';++/** Each control shows what it controls: the scheme toggle shows the scheme it+ * is currently on, and the contrast toggle below owns the `Contrast` glyph. */const themeIcons: Record<ThemeType, IconNode> = {system: Monitor,dark: Moon,light: Sun,+ 'high-contrast-light': Sun,+ 'high-contrast-dark': Moon,};-const Theme = ({ theme, onChange }: { theme: string; onChange: (value: string) => void }) => {+const Theme = ({+ theme,+ highContrast,+ onChange,+}: {+ theme: string;+ highContrast: boolean;+ onChange: (value: string) => void;+}) => {const localize = useLocalize();- const nextTheme = isDark(theme) ? 'light' : 'dark';+ const nextScheme = isDark(theme) ? 'light' : 'dark';+ /** The toggle flips the colour scheme without discarding a contrast choice.+ * Resolved contrast rather than `isHighContrast(theme)`: under `system` the+ * contrast comes from `prefers-contrast`, which the stored mode never names,+ * so keying off the mode alone would silently drop an OS-requested need. */+ const nextTheme = highContrast ? `high-contrast-${nextScheme}` : nextScheme;useEffect(() => {const handleKeyPress = (e: KeyboardEvent) => {@@ -54,20 +80,73 @@ const Theme = ({ theme, onChange }: { theme: string; onChange: (value: string) =);};+/**+ * Contrast toggle, rendered beside the scheme toggle. On the login,+ * registration and email-verification routes this selector is the only+ * appearance control, and the scheme toggle above preserves a contrast choice+ * but can never introduce one — the full appearance dropdown lives behind auth.+ * Without this button a logged-out user who needs the high contrast palette+ * could reach it only by editing local storage or turning on an OS-wide+ * preference.+ */+const ContrastToggle = ({+ theme,+ highContrast,+ onChange,+}: {+ theme: string;+ highContrast: boolean;+ onChange: (value: string) => void;+}) => {+ const localize = useLocalize();++ const scheme = isDark(theme) ? 'dark' : 'light';+ /** Turning contrast off lands on the plain mode for the scheme currently+ * rendered, so `system` under an OS contrast request becomes an explicit+ * opt-out rather than silently snapping back on. */+ const nextTheme = highContrast ? scheme : `high-contrast-${scheme}`;++ return (+ <Button+ variant="ghost"+ size="icon"+ className="h-auto w-auto p-2 text-text-primary"+ aria-label={localize('com_ui_toggle_high_contrast')}+ aria-pressed={highContrast}+ onClick={(e) => {+ e.preventDefault();+ onChange(nextTheme);+ }}+ >+ <MorphIcon icon={Contrast} size={24} />+ </Button>+ );+};+const ThemeSelector = ({ returnThemeOnly }: { returnThemeOnly?: boolean }): JSX.Element => {- const { theme, setTheme } = useContext(ThemeContext);+ const { theme, highContrast, setTheme } = useContext(ThemeContext);const [announcement, setAnnouncement] = useState('');const localize = useLocalize();const changeTheme = useCallback(- (value: string) => {+ (value: string, control: string) => {const now = Date.now();- if (typeof window.lastThemeChange === 'number' && now - window.lastThemeChange < 500) {+ const changes = window.lastThemeChange ?? {};+ const last = changes[control];+ if (typeof last === 'number' && now - last < CHANGE_THROTTLE_MS) {return;}- window.lastThemeChange = now;+ window.lastThemeChange = { ...changes, [control]: now };setTheme(value);+ if (isHighContrast(value)) {+ setAnnouncement(+ isDark(value)+ ? localize('com_ui_high_contrast_dark_theme_enabled')+ : localize('com_ui_high_contrast_light_theme_enabled'),+ );+ return;+ }setAnnouncement(isDark(value)? localize('com_ui_dark_theme_enabled')@@ -77,6 +156,12 @@ const ThemeSelector = ({ returnThemeOnly }: { returnThemeOnly?: boolean }): JSX.[setTheme, localize],);+ const changeScheme = useCallback((value: string) => changeTheme(value, 'scheme'), [changeTheme]);+ const changeContrast = useCallback(+ (value: string) => changeTheme(value, 'contrast'),+ [changeTheme],+ );+useEffect(() => {if (announcement) {const timeout = setTimeout(() => setAnnouncement(''), 1000);@@ -85,13 +170,14 @@ const ThemeSelector = ({ returnThemeOnly }: { returnThemeOnly?: boolean }): JSX.}, [announcement]);if (returnThemeOnly === true) {- return <Theme theme={theme} onChange={changeTheme} />;+ return <Theme theme={theme} highContrast={highContrast} onChange={changeScheme} />;}return (<div className="flex flex-col items-center justify-center bg-surface-primary pt-6 sm:pt-0">- <div className="absolute bottom-0 left-0 m-4">- <Theme theme={theme} onChange={changeTheme} />+ <div className="absolute bottom-0 left-0 m-4 flex items-center">+ <Theme theme={theme} highContrast={highContrast} onChange={changeScheme} />+ <ContrastToggle theme={theme} highContrast={highContrast} onChange={changeContrast} /></div><div role="alert" aria-live="assertive" aria-atomic="true" className="sr-only">{announcement}diff --git a/packages/client/src/components/Tooltip.css b/packages/client/src/components/Tooltip.cssindex 81b83e7788..adf350ff7a 100644--- a/packages/client/src/components/Tooltip.css+++ b/packages/client/src/components/Tooltip.css@@ -10,7 +10,7 @@padding-right: 0.5rem;font-size: 1rem;line-height: 1.5rem;- color: black;+ color: rgb(var(--text-primary));box-shadow: 0 2px 4px 0 rgb(0 0 0 / 0.25);/* Enhanced layout for longer descriptions */max-width: 320px;@@ -25,7 +25,15 @@}.tooltip:where(.dark, .dark *) {- background-color: rgb(var(--surface-primary));- color: white;box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.35);}++/* The contrast edge ships with the primitive: the app stylesheet is not part of+ * the published package, so a consumer importing this file has to get the+ * boundary too. In a contrast mode the `surface-primary` fill is the canvas+ * itself, and the black shadow the tooltip otherwise leans on carries no+ * separation against pure black. */+html.high-contrast .tooltip {+ border: 1px solid rgb(var(--border-medium));+ box-shadow: none;+}diff --git a/packages/client/src/locales/en/translation.json b/packages/client/src/locales/en/translation.jsonindex 3591abe297..7cedf2b9ba 100644--- a/packages/client/src/locales/en/translation.json+++ b/packages/client/src/locales/en/translation.json@@ -28,5 +28,7 @@"com_ui_disabled": "Disabled","com_ui_toggle_theme": "Toggle theme","com_ui_dark_theme_enabled": "Dark theme enabled",- "com_ui_light_theme_enabled": "Light theme enabled"+ "com_ui_light_theme_enabled": "Light theme enabled",+ "com_ui_high_contrast_dark_theme_enabled": "High contrast dark theme enabled",+ "com_ui_high_contrast_light_theme_enabled": "High contrast light theme enabled"}diff --git a/packages/client/src/locales/i18n.ts b/packages/client/src/locales/i18n.tsindex 42ec38b2ea..6c366498d5 100644--- a/packages/client/src/locales/i18n.ts+++ b/packages/client/src/locales/i18n.ts@@ -66,6 +66,8 @@ export const resources: {com_ui_toggle_theme: string;com_ui_dark_theme_enabled: string;com_ui_light_theme_enabled: string;+ com_ui_high_contrast_dark_theme_enabled: string;+ com_ui_high_contrast_light_theme_enabled: string;};};readonly ar: {diff --git a/packages/client/src/theme/README.md b/packages/client/src/theme/README.mdindex 46e74e4113..f5dfd395a5 100644--- a/packages/client/src/theme/README.md+++ b/packages/client/src/theme/README.md@@ -340,7 +340,30 @@ function ThemeToggle() {- `'light'` - Force light mode- `'dark'` - Force dark mode-- `'system'` - Follow system preference+- `'system'` - Follow system preference, for both colour scheme and contrast+- `'high-contrast-light'` - Accessibility mode: black on white, WCAG AAA+- `'high-contrast-dark'` - Accessibility mode: white on black, WCAG AAA++High contrast applies the built-in `highContrastTheme` definition+(`themes/highContrast.ts`), which outranks a deployment's custom theme, and adds+a `high-contrast` class to `<html>` for the CSS-only variables the token layer+cannot reach.++Three predicates, and they answer different questions:++- `isDark(theme)` - which colour scheme to render. `high-contrast-dark` is dark.+- `isHighContrast(theme)` - did the user _pick_ a contrast mode. This is what the+ theme toggle preserves when it flips the scheme, so `system` is never included.+- `resolvesToHighContrast(theme)` - will the contrast palette actually apply.+ True for the two explicit modes, and for `system` when the OS asks for more+ contrast through any of `prefers-contrast: more`, `prefers-contrast: custom`+ or `forced-colors: active`.++Because `system` resolves contrast from the OS, a user who has switched on+"Increase contrast" (macOS) or "Contrast themes" (Windows) gets the accessible+palette without first finding this setting. Windows is why the list has three+queries: a Contrast Theme surfaces as `forced-colors: active` with+`prefers-contrast: custom`, never `more`.## Migration Guidediff --git a/packages/client/src/theme/context/ThemeProvider.spec.tsx b/packages/client/src/theme/context/ThemeProvider.spec.tsxindex 48991884b5..657efd0506 100644--- a/packages/client/src/theme/context/ThemeProvider.spec.tsx+++ b/packages/client/src/theme/context/ThemeProvider.spec.tsx@@ -1,6 +1,13 @@import '@testing-library/jest-dom';import { act, render, screen, waitFor } from '@testing-library/react';-import { ThemeProvider, useTheme } from './ThemeProvider';+import {+ ThemeProvider,+ isDark,+ isHighContrast,+ resolvesToHighContrast,+ useTheme,+} from './ThemeProvider';+import { highContrastDarkTheme, highContrastLightTheme } from '../themes/highContrast';const matchMedia = (matches: boolean): MediaQueryList =>({@@ -15,12 +22,25 @@ const matchMedia = (matches: boolean): MediaQueryList =>}) as MediaQueryList;function Controls() {- const { resetTheme, setTheme, setThemeDefinition, setThemeName, setThemeRGB, themeName } =- useTheme();+ const {+ resetTheme,+ setTheme,+ setThemeDefinition,+ setThemeName,+ setThemeRGB,+ themeName,+ highContrast,+ resolvedMode,+ } = useTheme();return (<><output>{themeName}</output>+ <output data-testid="high-contrast">{String(highContrast)}</output>+ <output data-testid="resolved-mode">{resolvedMode}</output><button onClick={() => setTheme('dark')}>Dark</button>+ <button onClick={() => setTheme('light')}>Light</button>+ <button onClick={() => setTheme('high-contrast-light')}>HC light</button>+ <button onClick={() => setTheme('high-contrast-dark')}>HC dark</button><button onClick={() => setThemeName('renamed')}>Rename</button><button onClick={() => setThemeName(undefined)}>Clear name</button><button onClick={() => setThemeRGB({ 'rgb-accent-primary': '4 5 6' })}>Set legacy</button>@@ -723,4 +743,292 @@ describe('ThemeProvider', () => {expect(localStorage.getItem('theme-colors')).toBeNull();expect(localStorage.getItem('theme-source')).toBeNull();});++ it('applies the high contrast light palette and marks the root element', async () => {+ render(+ <ThemeProvider initialTheme="light">+ <Controls />+ </ThemeProvider>,+ );++ act(() => screen.getByRole('button', { name: 'HC light' }).click());++ await waitFor(() => {+ expect(document.documentElement.dataset.theme).toBe('high-contrast');+ });+ const root = document.documentElement;+ expect(root).toHaveClass('high-contrast', 'light');+ expect(root).not.toHaveClass('dark');+ expect(root.style.getPropertyValue('--surface-primary')).toBe(+ highContrastLightTheme['rgb-surface-primary'],+ );+ expect(root.style.getPropertyValue('--text-primary')).toBe(+ highContrastLightTheme['rgb-text-primary'],+ );+ expect(root.style.getPropertyValue('color-scheme')).toBe('light');+ expect(localStorage.getItem('color-theme')).toBe('high-contrast-light');+ });++ it('treats high contrast dark as a dark colour scheme', async () => {+ render(+ <ThemeProvider initialTheme="light">+ <Controls />+ </ThemeProvider>,+ );++ act(() => screen.getByRole('button', { name: 'HC dark' }).click());++ await waitFor(() => {+ expect(document.documentElement).toHaveClass('dark');+ });+ const root = document.documentElement;+ expect(root).toHaveClass('high-contrast');+ expect(root).not.toHaveClass('light');+ expect(root.style.getPropertyValue('--surface-primary')).toBe(+ highContrastDarkTheme['rgb-surface-primary'],+ );+ expect(root.style.getPropertyValue('color-scheme')).toBe('dark');+ expect(isDark('high-contrast-dark')).toBe(true);+ expect(isDark('high-contrast-light')).toBe(false);+ expect(isHighContrast('high-contrast-dark')).toBe(true);+ expect(isHighContrast('dark')).toBe(false);+ });++ it('restores the standard palette when leaving high contrast', async () => {+ const root = document.documentElement;+ root.style.setProperty('color-scheme', 'only light', 'important');+ render(+ <ThemeProvider initialTheme="light">+ <Controls />+ </ThemeProvider>,+ );++ act(() => screen.getByRole('button', { name: 'HC dark' }).click());+ await waitFor(() => {+ expect(document.documentElement).toHaveClass('high-contrast');+ });+ expect(root.style.getPropertyValue('color-scheme')).toBe('dark');+ expect(root.style.getPropertyPriority('color-scheme')).toBe('');++ act(() => screen.getByRole('button', { name: 'Light' }).click());++ await waitFor(() => {+ expect(document.documentElement).not.toHaveClass('high-contrast');+ });+ expect(root.style.getPropertyValue('--surface-primary')).toBe('');+ expect(root.style.getPropertyValue('--text-primary')).toBe('');+ expect(root.style.getPropertyValue('color-scheme')).toBe('only light');+ expect(root.style.getPropertyPriority('color-scheme')).toBe('important');+ expect(root.hasAttribute('data-theme')).toBe(false);+ });++ it('outranks a deployment custom theme, because contrast is an accessibility need', async () => {+ render(+ <ThemeProvider+ initialTheme="light"+ themeName="brand"+ themeRGB={{ 'rgb-surface-primary': '1 2 3' }}+ >+ <Controls />+ </ThemeProvider>,+ );++ await waitFor(() => {+ expect(document.documentElement.style.getPropertyValue('--surface-primary')).toBe('1 2 3');+ });++ act(() => screen.getByRole('button', { name: 'HC light' }).click());++ await waitFor(() => {+ expect(document.documentElement.dataset.theme).toBe('high-contrast');+ });+ expect(document.documentElement.style.getPropertyValue('--surface-primary')).toBe(+ highContrastLightTheme['rgb-surface-primary'],+ );++ act(() => screen.getByRole('button', { name: 'Light' }).click());++ await waitFor(() => {+ expect(document.documentElement.dataset.theme).toBe('brand');+ });+ expect(document.documentElement.style.getPropertyValue('--surface-primary')).toBe('1 2 3');+ });++ it('follows the OS contrast preference under the system mode', async () => {+ window.matchMedia = jest.fn((query: string) => matchMedia(query.includes('contrast')));+ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ );++ await waitFor(() => {+ expect(document.documentElement).toHaveClass('high-contrast');+ });+ const root = document.documentElement;+ expect(root).toHaveClass('light');+ expect(root.style.getPropertyValue('--surface-primary')).toBe(+ highContrastLightTheme['rgb-surface-primary'],+ );+ expect(resolvesToHighContrast('system')).toBe(true);+ /** The stored mode stays `system`; contrast is resolved, not chosen. */+ expect(isHighContrast('system')).toBe(false);+ expect(localStorage.getItem('color-theme')).toBe('system');+ });++ it('leaves an explicit colour scheme alone when the OS asks for more contrast', async () => {+ window.matchMedia = jest.fn((query: string) => matchMedia(query.includes('contrast')));+ render(+ <ThemeProvider initialTheme="light">+ <Controls />+ </ThemeProvider>,+ );++ await waitFor(() => {+ expect(document.documentElement).toHaveClass('light');+ });+ expect(document.documentElement).not.toHaveClass('high-contrast');+ expect(resolvesToHighContrast('light')).toBe(false);+ });++ it('reacts when the OS contrast preference changes under the system mode', async () => {+ const listeners: Array<() => void> = [];+ let prefersContrast = false;+ window.matchMedia = jest.fn((query: string) => {+ const isContrastQuery = query.includes('contrast');+ return {+ ...matchMedia(isContrastQuery && prefersContrast),+ addEventListener: (_event: string, listener: () => void) => {+ if (isContrastQuery) {+ listeners.push(listener);+ }+ },+ removeEventListener: jest.fn(),+ } as unknown as MediaQueryList;+ });++ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ );+ expect(document.documentElement).not.toHaveClass('high-contrast');+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('false');++ prefersContrast = true;+ act(() => listeners.forEach((listener) => listener()));++ await waitFor(() => {+ expect(document.documentElement).toHaveClass('high-contrast');+ });+ expect(document.documentElement.dataset.theme).toBe('high-contrast');+ /** The DOM alone is not enough: a consumer keying off the resolved contrast,+ * such as the Mermaid cache, only recomputes if the context value moves. */+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('true');+ });++ /** Windows Contrast Themes reach the browser as `forced-colors: active` with+ * `prefers-contrast: custom`; `more` never matches, so resolving contrast+ * from `more` alone left the palette off on the platform the README names. */+ it('treats a forced-colors palette as an OS contrast request', async () => {+ window.matchMedia = jest.fn((query: string) => matchMedia(query === '(forced-colors: active)'));+ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ );++ await waitFor(() => {+ expect(document.documentElement).toHaveClass('high-contrast');+ });+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('true');+ expect(resolvesToHighContrast('system')).toBe(true);+ });++ /** The same staleness for the scheme: with contrast already on, flipping the+ * OS colour scheme leaves `theme` at `system` and `setHighContrast` a no-op,+ * so nothing rerendered until the resolved mode was published too. */+ it('reacts when the OS colour scheme changes under the system mode', async () => {+ const listeners: Array<() => void> = [];+ let prefersDark = false;+ window.matchMedia = jest.fn((query: string) => {+ const isSchemeQuery = query.includes('color-scheme');+ return {+ ...matchMedia(isSchemeQuery ? prefersDark : true),+ addEventListener: (_event: string, listener: () => void) => {+ if (isSchemeQuery) {+ listeners.push(listener);+ }+ },+ removeEventListener: jest.fn(),+ } as unknown as MediaQueryList;+ });++ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ );+ expect(screen.getByTestId('resolved-mode')).toHaveTextContent('light');+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('true');++ prefersDark = true;+ act(() => listeners.forEach((listener) => listener()));++ await waitFor(() => {+ expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark');+ });+ expect(document.documentElement).toHaveClass('dark', 'high-contrast');+ });++ /** The provider reads both media queries during render now, so it has to+ * tolerate the absence of a window the way the storage helpers already do. */+ it('renders without a window, as under server rendering', () => {+ const restore = window.matchMedia;+ /** jsdom's property is non-configurable, so assign rather than redefine. */+ window.matchMedia = undefined as unknown as typeof window.matchMedia;++ try {+ expect(() =>+ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ ),+ ).not.toThrow();+ expect(screen.getByTestId('resolved-mode')).toHaveTextContent('light');+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('false');+ } finally {+ window.matchMedia = restore;+ }+ });++ /** A media query read during render would make the server's markup and the+ * first client render disagree, so the seed comes from the mode string only+ * and the OS-resolved values arrive from the effect. */+ it('seeds the published values from the mode alone, not from a media query', () => {+ const matchMediaSpy = jest.fn(() => matchMedia(true));+ window.matchMedia = matchMediaSpy;++ /** An explicit mode needs no query to resolve, so it is published at once. */+ const explicit = render(+ <ThemeProvider initialTheme="high-contrast-dark">+ <Controls />+ </ThemeProvider>,+ );+ expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark');+ expect(screen.getByTestId('high-contrast')).toHaveTextContent('true');+ explicit.unmount();++ /** `system` cannot resolve without a query, so it seeds light with no+ * contrast and the effect corrects it, which is what keeps hydration+ * deterministic even though this environment reports dark and more. */+ render(+ <ThemeProvider initialTheme="system">+ <Controls />+ </ThemeProvider>,+ );+ expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark');+ expect(matchMediaSpy).toHaveBeenCalled();+ });});diff --git a/packages/client/src/theme/context/ThemeProvider.tsx b/packages/client/src/theme/context/ThemeProvider.tsxindex c0cfc7a565..231ad9942d 100644--- a/packages/client/src/theme/context/ThemeProvider.tsx+++ b/packages/client/src/theme/context/ThemeProvider.tsx@@ -9,15 +9,28 @@ import React, {} from 'react';import { JSX } from 'react/jsx-runtime';import type { IThemeRGB, ThemeDefinition, ThemeMode } from '../types';+import {+ fromLegacyTheme,+ highContrastTheme,+ resolveTheme,+ validateThemeDefinition,+} from '../registry';import applyTheme, { applyResolvedTheme, themeOwnedProperties } from '../utils/applyTheme';-import { fromLegacyTheme, resolveTheme, validateThemeDefinition } from '../registry';+import '../highContrast.css';const THEME_KEY = 'color-theme';const THEME_COLORS_KEY = 'theme-colors';const THEME_NAME_KEY = 'theme-name';const THEME_DEFINITION_KEY = 'theme-definition';const THEME_SOURCE_KEY = 'theme-source';-const themeModes = ['light', 'dark', 'system'] as const;+const HIGH_CONTRAST_CLASS = 'high-contrast';+const themeModes = [+ 'light',+ 'dark',+ 'system',+ 'high-contrast-light',+ 'high-contrast-dark',+] as const;type AppearanceMode = (typeof themeModes)[number];@@ -28,12 +41,14 @@ type InitialThemeState = {type ThemeDOMSnapshot = {properties: Map<string, { value: string; priority: string }>;+ colorScheme: { value: string; priority: string };dataTheme: string | null;};type ThemeClassSnapshot = {dark: boolean;light: boolean;+ highContrast: boolean;};type ThemePropSnapshot = Pick<@@ -44,6 +59,15 @@ type ThemePropSnapshot = Pick<type ThemeContextType = {theme: AppearanceMode;setTheme: (theme: string) => void;+ /**+ * The scheme and contrast actually in effect. Both are published as state+ * rather than derived by consumers, because under `system` they come from+ * media queries React cannot observe: `theme` stays `'system'` when an OS+ * preference flips, so anything deriving from `theme` alone never rerenders+ * and keeps whatever it computed on its last render.+ */+ resolvedMode: ThemeMode;+ highContrast: boolean;themeRGB?: IThemeRGB;setThemeRGB: (colors?: IThemeRGB) => void;themeDefinition?: ThemeDefinition;@@ -56,6 +80,8 @@ type ThemeContextType = {export const ThemeContext: React.Context<ThemeContextType> = createContext<ThemeContextType>({theme: 'system',setTheme: () => undefined,+ resolvedMode: 'light',+ highContrast: false,setThemeRGB: () => undefined,setThemeDefinition: () => undefined,setThemeName: () => undefined,@@ -72,13 +98,58 @@ export interface ThemeProviderProps {initialTheme?: string;}+/**+ * Media queries are read during render by the provider's state initializers and+ * by consumers, so they have to tolerate the absence of a window the same way+ * the storage helpers do. On the server both preferences resolve to false, which+ * renders the light palette with no contrast override; the effects that apply+ * the real values run on hydration.+ */+const matchesMedia = (query: string): boolean =>+ typeof window !== 'undefined' && typeof window.matchMedia === 'function'+ ? window.matchMedia(query).matches+ : false;+export const isDark = (theme: string): boolean => {if (theme === 'system') {- return window.matchMedia('(prefers-color-scheme: dark)').matches;+ return matchesMedia('(prefers-color-scheme: dark)');}- return theme === 'dark';+ return theme === 'dark' || theme === 'high-contrast-dark';};+/**+ * Whether the appearance mode explicitly asks for high contrast. `system` is+ * excluded here and resolved separately through `prefers-contrast`, because+ * this predicate answers "what did the user pick", which is what the theme+ * toggle has to preserve when it flips the colour scheme.+ */+export const isHighContrast = (theme: string): boolean =>+ theme === 'high-contrast-light' || theme === 'high-contrast-dark';++/**+ * The media queries that mean "the OS asked for more contrast". Windows Contrast+ * Themes are the reason there are three: the browser turns them into+ * `forced-colors: active` and reports `prefers-contrast: custom` for a palette+ * whose own ratio is neither clearly more nor less, so keying off+ * `prefers-contrast: more` alone misses the platform the README names.+ */+const CONTRAST_QUERIES = [+ '(prefers-contrast: more)',+ '(prefers-contrast: custom)',+ '(forced-colors: active)',+] as const;++/**+ * `system` follows the OS for contrast the same way it already follows it for+ * the colour scheme, so a user who has switched on "Increase contrast" gets the+ * accessible palette without first discovering this setting.+ */+const prefersMoreContrast = (): boolean => CONTRAST_QUERIES.some(matchesMedia);++/** The resolved contrast for an appearance mode, explicit choice or OS request. */+export const resolvesToHighContrast = (theme: string): boolean =>+ isHighContrast(theme) || (theme === 'system' && prefersMoreContrast());+const isAppearanceMode = (value: string): value is AppearanceMode =>themeModes.includes(value as AppearanceMode);@@ -201,6 +272,10 @@ const captureThemeDOM = (root: HTMLElement): ThemeDOMSnapshot => ({},]),),+ colorScheme: {+ value: root.style.getPropertyValue('color-scheme'),+ priority: root.style.getPropertyPriority('color-scheme'),+ },dataTheme: root.getAttribute('data-theme'),});@@ -213,6 +288,16 @@ const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void =>root.style.setProperty(property, value, priority);});+ if (snapshot.colorScheme.value) {+ root.style.setProperty(+ 'color-scheme',+ snapshot.colorScheme.value,+ snapshot.colorScheme.priority,+ );+ } else {+ root.style.removeProperty('color-scheme');+ }+if (snapshot.dataTheme === null) {root.removeAttribute('data-theme');} else {@@ -253,9 +338,19 @@ export function ThemeProvider({}}- const [theme, setThemeState] = useState<AppearanceMode>(() =>- initialTheme && isAppearanceMode(initialTheme) ? initialTheme : getInitialTheme(),+ const initialAppearance =+ initialTheme && isAppearanceMode(initialTheme) ? initialTheme : getInitialTheme();+ const [theme, setThemeState] = useState<AppearanceMode>(initialAppearance);+ /**+ * Seeded from the mode string alone, never from a media query, so a server+ * render and the first client render agree. `system` therefore starts at the+ * light palette with no contrast override on both sides, and `applyThemeMode`+ * publishes the OS-resolved values in its effect, after hydration.+ */+ const [resolvedMode, setResolvedMode] = useState<ThemeMode>(+ initialAppearance !== 'system' && isDark(initialAppearance) ? 'dark' : 'light',);+ const [highContrast, setHighContrast] = useState<boolean>(isHighContrast(initialAppearance));const [themeDefinition, setThemeDefinitionState] = useState<ThemeDefinition | undefined>(initialThemeState.current.definition,);@@ -498,32 +593,46 @@ export function ThemeProvider({(currentTheme: AppearanceMode) => {const root = window.document.documentElement;const mode: ThemeMode = isDark(currentTheme) ? 'dark' : 'light';+ const highContrast = resolvesToHighContrast(currentTheme);+ /** Publish both so consumers rerender when an OS preference flips under+ * `system`, where `theme` itself never changes. */+ setResolvedMode(mode);+ setHighContrast(highContrast);if (!themeClassSnapshot.current) {themeClassSnapshot.current = {dark: root.classList.contains('dark'),light: root.classList.contains('light'),+ highContrast: root.classList.contains(HIGH_CONTRAST_CLASS),};}root.classList.toggle('dark', mode === 'dark');root.classList.toggle('light', mode === 'light');+ root.classList.toggle(HIGH_CONTRAST_CLASS, highContrast);++ /** A contrast mode is an accessibility need, so it outranks both a+ * deployment's custom definition and the legacy RGB colors. */+ const definition = highContrast ? highContrastTheme : themeDefinition;- if (!themeDefinition) {+ if (!definition) {restoreAppliedTheme(root);return;}prepareThemeDOM(root);+ if (highContrast) {+ root.style.setProperty('color-scheme', mode);+ }- if (legacyThemeRGB) {+ if (!highContrast && legacyThemeRGB) {applyTheme(legacyThemeRGB, root);- root.dataset.theme = themeDefinition.name;+ root.dataset.theme = definition.name;return;}try {- applyResolvedTheme(resolveTheme(themeDefinition, mode), root);+ applyResolvedTheme(resolveTheme(definition, mode), root);} catch (error) {restoreAppliedTheme(root);console.error('Unable to apply theme definition', error);@@ -541,10 +650,18 @@ export function ThemeProvider({return;}- const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');+ /** `system` tracks both OS preferences it resolves against, when the host+ * provides matchMedia at all. */+ if (typeof window.matchMedia !== 'function') {+ return;+ }+ const queries = [+ window.matchMedia('(prefers-color-scheme: dark)'),+ ...CONTRAST_QUERIES.map((query) => window.matchMedia(query)),+ ];const handleChange = () => applyThemeMode('system');- mediaQuery.addEventListener('change', handleChange);- return () => mediaQuery.removeEventListener('change', handleChange);+ queries.forEach((query) => query.addEventListener('change', handleChange));+ return () => queries.forEach((query) => query.removeEventListener('change', handleChange));}, [applyThemeMode, theme]);useEffect(@@ -554,6 +671,7 @@ export function ThemeProvider({if (themeClassSnapshot.current) {root.classList.toggle('dark', themeClassSnapshot.current.dark);root.classList.toggle('light', themeClassSnapshot.current.light);+ root.classList.toggle(HIGH_CONTRAST_CLASS, themeClassSnapshot.current.highContrast);themeClassSnapshot.current = undefined;}},@@ -572,6 +690,8 @@ export function ThemeProvider({() => ({theme,setTheme,+ resolvedMode,+ highContrast,themeRGB,setThemeRGB,themeDefinition,@@ -586,6 +706,8 @@ export function ThemeProvider({setThemeDefinition,setThemeName,setThemeRGB,+ resolvedMode,+ highContrast,theme,themeDefinition,themeName,diff --git a/packages/client/src/theme/highContrast.css b/packages/client/src/theme/highContrast.cssnew file mode 100644index 0000000000..ca67bf3e28--- /dev/null+++ b/packages/client/src/theme/highContrast.css@@ -0,0 +1,95 @@+/**+ * Contrast-mode treatments that belong to the exported theme rather than to the+ * SPA, so a consumer of the published `ThemeProvider` gets them with the+ * palettes they complete.+ *+ * `ThemeProvider` puts `high-contrast` on <html> and paints the palette as+ * inline custom properties (see `themes/highContrast.ts`). Two of those tokens+ * are not self-sufficient, and the rules below are what make them correct:+ * the selected fills are deliberately light so their label clears AAA, which+ * only works because selection is marked by a perimeter; and `::placeholder`+ * has no token at all, so it falls through to Tailwind preflight's raw+ * `gray-400`. Both defects reach package primitives — `TimePicker`,+ * `SelectDropDown`, `MultiSelect`, `InputWithDropDown`, `Badge`, `DataTable`,+ * `Input`, `Textarea` — so shipping the palette without these rules ships a+ * broken palette.+ *+ * `client/src/style.css` keeps the treatments that really are SPA-only: the+ * legacy `.btn-neutral` chrome, the markdown and `@tailwindcss/typography`+ * blocks, scrollbars, and the keyboard-modality field outlines.+ */++/**+ * Selection and navigation are conveyed by a fill alone almost everywhere, and+ * these palettes keep fills light on purpose so the label on them can clear AAA+ * (see the `surface-active` note in `themes/highContrast.ts`). The cue is+ * therefore a perimeter: `text-primary` is 21:1 against either canvas, and it+ * is what discharges WCAG 1.4.11 for the fill.+ *+ * Four families need it. `.select-item` blanks its own outline with+ * `!important`, so this has to match that to land. Ariakit marks the navigated+ * row of every composite — menu, select, combobox — with `data-active-item`;+ * those rows otherwise carry only a `surface-hover` fill at 1.48:1 on white.+ * A selected data-table row is marked with `data-state="selected"`. And any row+ * painted with the selected-surface role marks itself with that fill and+ * nothing else. Inset so the ring reads inside the row's own radius; `span` is+ * excluded because the one inline user of the role is a highlighted passage+ * that wraps across lines and would box every fragment.+ */+html.high-contrast [data-active-item],+html.high-contrast .select-item:focus-visible,+html.high-contrast [data-state='selected'],+html.high-contrast :is(.bg-surface-active, .bg-surface-active-alt):not(span) {+ outline: 3px solid rgb(var(--text-primary)) !important;+ outline-offset: -3px;+}++/**+ * The one inline user of the selected-surface role is a highlighted source+ * passage, which the perimeter above skips: an outline would box each wrapped+ * fragment separately. It still needs a cue, so it inverts instead — the same+ * treatment the mode gives `::selection`, 21:1 and with no geometry to wrap.+ */+html.high-contrast span:is(.bg-surface-active, .bg-surface-active-alt) {+ background-color: rgb(var(--text-primary));+ color: rgb(var(--surface-primary));+}++/**+ * WCAG 1.4.1: a link in running text must not be told apart by colour alone,+ * and `link` against `text-primary` is under 3:1 in both palettes. Prose links+ * plus anything carrying the shared `text-link` role, which is how the auth+ * resend actions and in-dialog help links are styled — including the ones+ * rendered as a `button`. App chrome stays excluded: a nav row is not a link in+ * running text, and it is identified by its own position and perimeter.+ */+html.high-contrast :is(.markdown, .prose) a,+html.high-contrast .text-link {+ text-decoration: underline;+ text-underline-offset: 0.15em;+}++/**+ * Radix tab triggers mark selection with a `surface-tertiary` fill, which is the+ * plain canvas in both palettes — a selected tab computes to the same colour as+ * its unselected siblings, leaving the current section unmarked. Same remedy,+ * inset so it reads inside the row's own radius.+ */+html.high-contrast [role='tab'][data-state='active'] {+ outline: 3px solid rgb(var(--text-primary));+ outline-offset: -3px;+}++/**+ * Placeholder text is real text, so it answers to WCAG 1.4.3 like any other.+ * Tailwind's preflight paints `::placeholder` with the raw `gray-400` #999696,+ * which is what every field that forgets a `placeholder:` utility inherits:+ * 4.06:1 on the black canvas and 3.08:1 on the white one, both under the floor.+ * Setting it here catches those fields rather than the handful that remembered,+ * and matches the utilities that did, since every text role is pure ink in+ * these palettes.+ */+html.high-contrast ::placeholder {+ color: rgb(var(--text-secondary));+ opacity: 1;+}diff --git a/packages/client/src/theme/index.ts b/packages/client/src/theme/index.tsindex ac4c561984..e6727c1d7b 100644--- a/packages/client/src/theme/index.ts+++ b/packages/client/src/theme/index.ts@@ -1,8 +1,15 @@// Export typesexport * from './types';-// Export ThemeProvider, ThemeContext, useTheme hook, and isDark-export { ThemeProvider, ThemeContext, useTheme, isDark } from './context/ThemeProvider';+// Export ThemeProvider, ThemeContext, useTheme hook, and the mode predicates+export {+ ThemeProvider,+ ThemeContext,+ useTheme,+ isDark,+ isHighContrast,+ resolvesToHighContrast,+} from './context/ThemeProvider';// Export utility functionsexport {@@ -13,10 +20,12 @@ export {} from './utils/applyTheme';export {+ HIGH_CONTRAST_THEME_NAME,THEME_VERSION,defaultAppearance,defaultBrands,fromLegacyTheme,+ highContrastTheme,libreChatTheme,resolveTheme,themeAppearanceProperties,diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.tsindex f778d89c91..114b1bd6c4 100644--- a/packages/client/src/theme/registry.ts+++ b/packages/client/src/theme/registry.ts@@ -8,6 +8,7 @@ import type {ThemeDefinition,ThemeMode,} from './types';+import { highContrastDarkTheme, highContrastLightTheme } from './themes/highContrast';import { defaultTheme } from './themes/default';import { darkTheme } from './themes/dark';export const THEME_VERSION = 1 as const;@@ -91,6 +92,51 @@ export const libreChatTheme: ThemeDefinition = Object.freeze({brands: defaultBrands,});+/**+ * Built-in accessibility theme behind the `high-contrast-light` and+ * `high-contrast-dark` appearance modes. `HIGH_CONTRAST_THEME_NAME` is what+ * `applyResolvedTheme` stamps onto `data-theme`, and what the `high-contrast`+ * class on `<html>` mirrors for the CSS-only variables the token layer cannot+ * reach (see the `html.high-contrast` block in `client/src/style.css`).+ */+export const HIGH_CONTRAST_THEME_NAME = 'high-contrast' as const;++/**+ * A brand fill carries a glyph and has to stand out from the canvas, and both+ * flip between the modes, so the brands are declared per mode: dark tints under+ * a white glyph on white, bright tints under a black glyph on black. Hue is kept+ * so a provider stays recognisable; the worst pair measures 8.76:1 for both the+ * glyph and the silhouette, against 2.30:1 for the standard brand set.+ */+const highContrastLightBrands: Partial<IThemeBrands> = Object.freeze({+ 'provider-openai': '#00563d',+ 'provider-openai-gpt4': '#4d1a99',+ 'provider-openai-reasoning': '#000000',+ 'provider-anthropic': '#6b3d00',+ 'provider-azure': '#00417a',+ 'provider-bedrock': '#00504d',+ 'provider-foreground': '#ffffff',+});++const highContrastDarkBrands: Partial<IThemeBrands> = Object.freeze({+ 'provider-openai': '#7ff0b3',+ 'provider-openai-gpt4': '#c8a3ff',+ 'provider-openai-reasoning': '#ffffff',+ 'provider-anthropic': '#ffc94d',+ 'provider-azure': '#8cc8ff',+ 'provider-bedrock': '#5ce6db',+ 'provider-foreground': '#000000',+});++export const highContrastTheme: ThemeDefinition = Object.freeze({+ version: THEME_VERSION,+ name: HIGH_CONTRAST_THEME_NAME,+ modes: {+ light: { colors: highContrastLightTheme, brands: highContrastLightBrands },+ dark: { colors: highContrastDarkTheme, brands: highContrastDarkBrands },+ },+});+const rgbPattern = /^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})$/;const cssLengthPattern = /^(0|\d*\.?\d+(px|rem|em))$/;const cssDurationPattern = /^\d*\.?\d+(ms|s)$/;@@ -159,6 +205,27 @@ const appearanceValidators: Record<keyof IThemeAppearance, (value: unknown) => bmotionNormal: isDuration,};+/** Shared by the theme-wide `brands` and each mode's override block. */+function collectBrandErrors(brands: unknown): string[] {+ if (!isPlainRecord(brands)) {+ return [];+ }++ return Object.entries(brands).flatMap(([key, value]) => {+ if (!themeBrandTokens.includes(key as keyof IThemeBrands)) {+ return [`Unknown brand token: ${key}`];+ }+ /** Only the glyph is a flat colour; a fill may also be a gradient. */+ const isColorOnly = key === 'provider-foreground';+ const isValidBrand =+ typeof value === 'string' &&+ (isColorOnly+ ? hexColorPattern.test(value)+ : hexColorPattern.test(value) || isLinearGradient(value));+ return value !== undefined && !isValidBrand ? [`Invalid brand value for ${key}: ${value}`] : [];+ });+}+export function validateThemeDefinition(theme: ThemeDefinition): string[] {const errors: string[] = [];@@ -201,7 +268,7 @@ export function validateThemeDefinition(theme: ThemeDefinition): string[] {}Object.keys(definition).forEach((key) => {- if (key !== 'colors' && key !== 'appearance') {+ if (key !== 'colors' && key !== 'appearance' && key !== 'brands') {errors.push(`Unknown ${mode} theme field: ${key}`);}});@@ -235,31 +302,39 @@ export function validateThemeDefinition(theme: ThemeDefinition): string[] {}});}++ if (definition.brands !== undefined && !isPlainRecord(definition.brands)) {+ errors.push(`Theme brands for ${mode} must be an object`);+ } else {+ errors.push(...collectBrandErrors(definition.brands));+ }});if (theme.brands !== undefined && !isPlainRecord(theme.brands)) {errors.push('Theme brands must be an object');} else {- Object.entries(theme.brands ?? {}).forEach(([key, value]) => {- if (!themeBrandTokens.includes(key as keyof IThemeBrands)) {- errors.push(`Unknown brand token: ${key}`);- return;- }- const isColorOnly = key === 'provider-foreground';- const isValidBrand =- typeof value === 'string' &&- (isColorOnly- ? hexColorPattern.test(value)- : hexColorPattern.test(value) || isLinearGradient(value));- if (value !== undefined && !isValidBrand) {- errors.push(`Invalid brand value for ${key}: ${value}`);- }- });+ errors.push(...collectBrandErrors(theme.brands));}return errors;}+/**+ * A partial theme promises that an omitted value falls back, and+ * `Partial<IThemeBrands>` lets a key be present with `undefined`. Spreading+ * that would overwrite the inherited brand with nothing, and unlike colors,+ * which `mapColors` skips when undefined, every brand token is written to the+ * DOM unconditionally, so the avatar would lose its fill entirely.+ */+function definedBrands(brands?: Partial<IThemeBrands>): Partial<IThemeBrands> {+ if (!brands) {+ return {};+ }+ return Object.fromEntries(+ Object.entries(brands).filter(([, value]) => value !== undefined),+ ) as Partial<IThemeBrands>;+}+export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedThemeDefinition {const errors = validateThemeDefinition(theme);if (errors.length > 0) {@@ -317,7 +392,12 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT...chartWidgetStrokeFallback,} as Required<IThemeRGB>,appearance: { ...defaultAppearance, ...definition?.appearance },- brands: { ...defaultBrands, ...theme.brands },+ /** Mode last: a mode override is more specific than the theme-wide set. */+ brands: {+ ...defaultBrands,+ ...definedBrands(theme.brands),+ ...definedBrands(definition?.brands),+ },};}diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.tsindex 0b9cc25a19..ec7f1f4150 100644--- a/packages/client/src/theme/semanticTokens.spec.ts+++ b/packages/client/src/theme/semanticTokens.spec.ts@@ -1,6 +1,7 @@import { join } from 'node:path';import { readFileSync } from 'node:fs';import type { IThemeRGB } from './types';+import { highContrastDarkTheme, highContrastLightTheme } from './themes/highContrast';import { createTailwindColors } from './utils/createTailwindColors';import { defaultTheme } from './themes/default';import { darkTheme } from './themes/dark';@@ -220,6 +221,8 @@ function belowAA(describe.each([['default', defaultTheme],['dark', darkTheme],+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],])('%s theme text contrast', (_name, theme: IThemeRGB) => {it('keeps neutral text at WCAG AA on every surface it renders on', () => {expect(belowAA(theme, neutralTextTokens, [...canvasSurfaces, 'rgb-surface-tertiary'])).toEqual(@@ -244,12 +247,20 @@ describe.each([});/** The meter paints segments on `surface-tertiary`; the swatch and popover chrome- * sit on `surface-secondary`. Both have to clear the 3:1 mark-contrast floor. */+ * sit on `surface-secondary`; prompt categories sit on `surface-primary`;+ * checked capability badges sit on `surface-chat`; dialog option toggles sit+ * on `surface-dialog`. All have to clear the 3:1 mark-contrast floor. */const seriesTokens = Array.from({ length: 7 },(_, index) => `rgb-series-${index + 1}` as keyof IThemeRGB,);-const seriesSurfaces: Array<keyof IThemeRGB> = ['rgb-surface-tertiary', 'rgb-surface-secondary'];+const seriesSurfaces: Array<keyof IThemeRGB> = [+ 'rgb-surface-primary',+ 'rgb-surface-tertiary',+ 'rgb-surface-secondary',+ 'rgb-surface-chat',+ 'rgb-surface-dialog',+];const WCAG_MARK_MIN = 3;describe('categorical series scale', () => {@@ -304,8 +315,10 @@ describe('categorical series scale', () => {describe.each([['default', defaultTheme],['dark', darkTheme],+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],])('%s series contrast', (_name, theme: IThemeRGB) => {- it('keeps every series slot at the 3:1 mark floor on the track and the panel', () => {+ it('keeps every series slot at the 3:1 mark floor on its consumer surfaces', () => {const failures = seriesTokens.flatMap((token) =>seriesSurfaces.flatMap((surface) => {const ratio = contrast(toRgb(theme, token), toRgb(theme, surface));@@ -315,4 +328,177 @@ describe.each([expect(failures).toEqual([]);});++ /** A series slot is not only a chart mark: the file-source badges fill a chip+ * with one and drop a glyph on top, so a slot has to carry `text-on-status`+ * at the same 3:1 floor. */+ it('lets every series slot carry the status label at the 3:1 mark floor', () => {+ const failures = seriesTokens.flatMap((token) => {+ const ratio = contrast(toRgb(theme, token), toRgb(theme, 'rgb-text-on-status'));+ return ratio < WCAG_MARK_MIN ? [`${token} under text-on-status: ${ratio.toFixed(2)}:1`] : [];+ });++ expect(failures).toEqual([]);+ });+});++describe.each([+ ['default', defaultTheme],+ ['dark', darkTheme],+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],+])('%s skill indicators', (_name, theme: IThemeRGB) => {+ it('keeps informational marks at the 3:1 floor on every skill surface', () => {+ const indicator = toRgb(theme, 'rgb-status-info');+ const surfaces: Array<keyof IThemeRGB> = [+ 'rgb-presentation',+ 'rgb-surface-secondary',+ 'rgb-surface-active',+ ];++ const failures = surfaces.flatMap((surface) => {+ const ratio = contrast(indicator, toRgb(theme, surface));+ return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : [];+ });++ expect(failures).toEqual([]);+ });+});++/** `status-success-strong` is the one status fill that also paints bare marks:+ * the selected-tool check, the version timeline rail and its "current" dot, and+ * the selected prompt-version chip. It owes two ratios at once, AA under the+ * `text-on-status` label it carries and the 3:1 mark floor against the panel it+ * sits on. `surface-secondary` is that panel in every mode. */+describe.each([+ ['default', defaultTheme],+ ['dark', darkTheme],+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],+])('%s success fill', (_name, theme: IThemeRGB) => {+ it('carries its label at WCAG AA', () => {+ const ratio = contrast(+ toRgb(theme, 'rgb-status-success-strong'),+ toRgb(theme, 'rgb-text-on-status'),+ );+ expect(ratio).toBeGreaterThanOrEqual(WCAG_AA_NORMAL);+ });++ it('keeps its silhouette at the 3:1 mark floor on the panel', () => {+ const ratio = contrast(+ toRgb(theme, 'rgb-status-success-strong'),+ toRgb(theme, 'rgb-surface-secondary'),+ );+ expect(ratio).toBeGreaterThanOrEqual(WCAG_MARK_MIN);+ });+});++describe('success fill defaults', () => {+ /** Both copies have to move together: the value is a tuned hex rather than a+ * palette step, so the stylesheet cannot alias it to a `--green-*` step. */+ it('keeps the app CSS in step with the runtime themes', () => {+ const appStyles = readFileSync(+ join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),+ 'utf8',+ );++ const declared = [...appStyles.matchAll(/--status-success-strong:\s*([^;]+);/g)].map((match) =>+ match[1].trim(),+ );++ /** One declaration for `html`, one for `.dark`, and both must match. */+ expect(declared).toEqual([+ defaultTheme['rgb-status-success-strong'],+ darkTheme['rgb-status-success-strong'],+ ]);+ });+});++/** The shared `Switch` paints this track, so it travels with the package rather+ * than the app stylesheet. It is a UI component boundary under WCAG 1.4.11 and+ * has to stay distinct from the `surface-primary` thumb on it and from the+ * `surface-inverted` fill it swaps with when checked. */+describe.each([+ ['default', defaultTheme],+ ['dark', darkTheme],+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],+])('%s switch track', (_name, theme: IThemeRGB) => {+ it('keeps the unchecked track at the 3:1 mark floor against thumb and checked fill', () => {+ const track = toRgb(theme, 'rgb-switch-unchecked');+ (['rgb-surface-primary', 'rgb-surface-inverted'] as Array<keyof IThemeRGB>).forEach(+ (surface) => {+ expect({ surface, ok: contrast(track, toRgb(theme, surface)) >= WCAG_MARK_MIN }).toEqual({+ surface,+ ok: true,+ });+ },+ );+ });+});++describe('switch track defaults', () => {+ /** The app stylesheet only restates the registry now: the contrast modes used+ * to carry their own `html.high-contrast` overrides here, which the published+ * package never shipped. */+ it('keeps the app CSS in step with the runtime themes', () => {+ const appStyles = readFileSync(+ join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),+ 'utf8',+ );++ const declared = [...appStyles.matchAll(/--switch-unchecked:\s*([^;]+);/g)].map((match) =>+ match[1].trim(),+ );++ expect(declared).toEqual([+ defaultTheme['rgb-switch-unchecked'],+ darkTheme['rgb-switch-unchecked'],+ ]);+ });+});++/** The syntax palette used to live as raw hex in `style.css`, which meant a+ * change had to be made twice and neither copy was checked. It is a registry+ * token map now, so the stylesheet is only allowed to restate it. */+describe('syntax highlighting palette', () => {+ const syntaxTokens = (+ ['comment', 'meta', 'builtin', 'keyword', 'string', 'attr', 'title'] as const+ ).map((role) => `rgb-syntax-${role}` as keyof IThemeRGB);++ it('is declared in both bundled themes', () => {+ syntaxTokens.forEach((token) => {+ expect(() => toRgb(defaultTheme, token)).not.toThrow();+ expect(() => toRgb(darkTheme, token)).not.toThrow();+ });+ });++ it('keeps the app CSS defaults in step with the runtime themes', () => {+ const appStyles = readFileSync(+ join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),+ 'utf8',+ );++ syntaxTokens.forEach((token) => {+ const property = token.slice(4);+ const declared = [...appStyles.matchAll(new RegExp(`--${property}:\\s*([^;]+);`, 'g'))].map(+ (match) => match[1].trim(),+ );++ /** `html` may alias a raw palette entry; `.dark` states the triplet. */+ expect(declared).toHaveLength(2);+ expect(declared[1]).toBe(darkTheme[token]);+ });+ });++ it('leaves no hard-coded syntax hex behind in the stylesheet', () => {+ const appStyles = readFileSync(+ join(__dirname, '..', '..', '..', '..', 'client', 'src', 'style.css'),+ 'utf8',+ );+ const hljsRules = [...appStyles.matchAll(/^\.hljs[^{]*\{([^}]*)\}/gm)].map((match) => match[1]);++ expect(hljsRules.length).toBeGreaterThan(0);+ expect(hljsRules.filter((body) => /#[0-9a-f]{3,8}|hsla?\(/i.test(body))).toEqual([]);+ });});diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.tsindex 5179b1f3d5..e4960c78d5 100644--- a/packages/client/src/theme/themes/dark.ts+++ b/packages/client/src/theme/themes/dark.ts@@ -72,7 +72,12 @@ export const darkTheme: IThemeRGB = {'rgb-status-success': '110 231 183', // #6ee7b7 (green-300)'rgb-status-success-subtle': '2 44 34', // #022c22 (green-950)'rgb-status-success-border': '6 95 70', // #065f46 (green-800)- 'rgb-status-success-strong': '6 95 70', // #065f46 (green-800)+ /** Not `green-800` like its border twin: this fill also paints bare marks+ * (selection checks, the version timeline rail, prompt chips) that have to+ * clear 3:1 against the #212121 panel, and green-800 reached only 2.10:1+ * there. Balanced instead, the same way light's `#02855e` is: 4.55:1 under+ * the white `text-on-status` label and 3.54:1 against the panel. */+ 'rgb-status-success-strong': '8 135 89', // #088759'rgb-status-info': '147 197 253', // #93c5fd (blue-300)'rgb-status-info-subtle': '23 37 84', // #172554 (blue-950)'rgb-status-info-border': '30 64 175', // #1e40af (blue-800)@@ -93,6 +98,19 @@ export const darkTheme: IThemeRGB = {// Brand colors'rgb-brand-purple': '171 104 255', // #ab68ff+ /** Code syntax highlighting, measured against the `surface-code` fill. The+ * comment and meta values are the flattened equivalents of the alpha-blended+ * whites this palette used before it was tokenized: 50% and 60% white over+ * the #212121 code surface. */+ 'rgb-syntax-text': '255 255 255', // #fff (white)+ 'rgb-syntax-comment': '144 144 144', // #909090+ 'rgb-syntax-meta': '166 166 166', // #a6a6a6+ 'rgb-syntax-builtin': '233 149 12', // #e9950c+ 'rgb-syntax-keyword': '46 149 211', // #2e95d3+ 'rgb-syntax-string': '0 166 125', // #00a67d+ 'rgb-syntax-attr': '223 48 121', // #df3079+ 'rgb-syntax-title': '242 44 61', // #f22c3d+/** Categorical series scale — the same seven hues stepped for the #212121* surface: worst adjacent CVD ΔE 13.0, normal-vision ΔE 19.0, all ≥ 3:1. */'rgb-series-1': '9 140 238', // #098cee (cerulean)@@ -103,6 +121,10 @@ export const darkTheme: IThemeRGB = {'rgb-series-6': '171 104 254', // #ab68fe (violet)'rgb-series-7': '80 167 49', // #50a731 (green)+ /** Unchecked switch track. 3.38:1 against the page and the `surface-primary`+ * thumb, 5.74:1 against the checked `surface-inverted` track. */+ 'rgb-switch-unchecked': '102 102 102', // #666666+// Presentation'rgb-presentation': '33 33 33', // #212121 (gray-800)};diff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.tsindex dcc72b7220..2bf971582b 100644--- a/packages/client/src/theme/themes/default.ts+++ b/packages/client/src/theme/themes/default.ts@@ -93,6 +93,16 @@ export const defaultTheme: IThemeRGB = {// Brand colors'rgb-brand-purple': '126 34 206', // #7e22ce (purple-700)+ /** Code syntax highlighting, measured against the `surface-code` fill. */+ 'rgb-syntax-text': '33 33 33', // #212121 (gray-800)+ 'rgb-syntax-comment': '89 89 89', // #595959 (gray-500)+ 'rgb-syntax-meta': '66 66 66', // #424242 (gray-600)+ 'rgb-syntax-builtin': '154 103 0', // #9a6700+ 'rgb-syntax-keyword': '5 80 174', // #0550ae+ 'rgb-syntax-string': '10 123 98', // #0a7b62+ 'rgb-syntax-attr': '154 47 106', // #9a2f6a+ 'rgb-syntax-title': '180 35 24', // #b42318+/** Categorical series scale. Steps clear 3:1 against BOTH the popover surface* and the #ececec meter track, with worst adjacent CVD ΔE 12.4 and worst* adjacent normal-vision ΔE 19.0. Slot order is the CVD-safety mechanism. */@@ -104,6 +114,11 @@ export const defaultTheme: IThemeRGB = {'rgb-series-6': '126 35 205', // #7e23cd (violet)'rgb-series-7': '1 131 1', // #018301 (green)+ /** Unchecked switch track. 3.03:1 against the white page and the+ * `surface-primary` thumb, 5.91:1 against the checked `surface-inverted`+ * track, so the control reads in either state. */+ 'rgb-switch-unchecked': '148 148 148', // #949494+// Presentation'rgb-presentation': '255 255 255', // #fff (white)};diff --git a/packages/client/src/theme/themes/highContrast.spec.ts b/packages/client/src/theme/themes/highContrast.spec.tsnew file mode 100644index 0000000000..3ddd161dd6--- /dev/null+++ b/packages/client/src/theme/themes/highContrast.spec.ts@@ -0,0 +1,400 @@+import type { IThemeRGB } from '../types';+import {+ HIGH_CONTRAST_THEME_NAME,+ defaultBrands,+ highContrastTheme,+ resolveTheme,+ themeBrandTokens,+ themeColorTokens,+ validateThemeDefinition,+} from '../registry';+import { highContrastDarkTheme, highContrastLightTheme } from './highContrast';++type Rgb = [number, number, number];++/** Brands are hex rather than channel triplets, so they need their own parser. */+function hexToRgb(value: string): Rgb {+ const hex = value.replace('#', '');+ const full =+ hex.length === 3+ ? hex+ .split('')+ .map((channel) => channel + channel)+ .join('')+ : hex.slice(0, 6);+ return [+ parseInt(full.slice(0, 2), 16),+ parseInt(full.slice(2, 4), 16),+ parseInt(full.slice(4, 6), 16),+ ];+}++/** WCAG 1.4.6 enhanced contrast, the reason these modes exist. */+const WCAG_AAA_NORMAL = 7;+/** WCAG 1.4.11 non-text contrast, for borders, rings, marks and fills. */+const WCAG_NON_TEXT = 3;++/** Surfaces body copy renders on, including hover, which is transient and so+ * carries no state-contrast duty of its own and can afford AAA text. */+const surfaces: Array<keyof IThemeRGB> = [+ 'rgb-surface-primary',+ 'rgb-chart-widget-surface',+ 'rgb-surface-primary-alt',+ 'rgb-surface-primary-contrast',+ 'rgb-surface-secondary',+ 'rgb-surface-secondary-alt',+ 'rgb-surface-tertiary',+ 'rgb-surface-tertiary-alt',+ 'rgb-surface-dialog',+ 'rgb-surface-chat',+ 'rgb-presentation',+ 'rgb-surface-hover',+ 'rgb-surface-hover-alt',+ 'rgb-surface-composer-hover',+ 'rgb-header-primary',+ 'rgb-header-hover',+ 'rgb-header-button-hover',+];++/** The selected state. The fill no longer discharges WCAG 1.4.11 by itself: the+ * contrast block rings every selected row and navigated menu item in+ * `text-primary` at 21:1 (`html.high-contrast :is(...)` in+ * `client/src/style.css`). That is what lets the fill stay light enough to+ * carry an AAA label, which a fill dark enough to mark itself could not. */+const activeFills: Array<keyof IThemeRGB> = ['rgb-surface-active', 'rgb-surface-active-alt'];++const textTokens: Array<keyof IThemeRGB> = [+ 'rgb-text-primary',+ 'rgb-text-secondary',+ 'rgb-text-secondary-alt',+ 'rgb-text-tertiary',+ 'rgb-text-muted',+];++/** `--surface-code` resolves to `surface-primary-alt` in light mode and+ * `presentation` in dark, so asserting against both covers either mode without+ * the table needing to know which one it is holding. */+const codeSurfaces: Array<keyof IThemeRGB> = ['rgb-surface-primary-alt', 'rgb-presentation'];++const syntaxTokens: Array<keyof IThemeRGB> = [+ 'rgb-syntax-text',+ 'rgb-syntax-comment',+ 'rgb-syntax-meta',+ 'rgb-syntax-builtin',+ 'rgb-syntax-keyword',+ 'rgb-syntax-string',+ 'rgb-syntax-attr',+ 'rgb-syntax-title',+];++/** Painted with `text-text-on-status`, the per-mode label colour. Every feature+ * call site reads that token; none hard-codes `text-white` any more. */+const solidFills: Array<keyof IThemeRGB> = [+ 'rgb-surface-submit',+ 'rgb-surface-submit-hover',+ 'rgb-surface-destructive',+ 'rgb-surface-destructive-hover',+ 'rgb-status-success-strong',+ 'rgb-status-info-strong',+ 'rgb-status-warning-strong',+ 'rgb-status-error-strong',+];++const borderTokens: Array<keyof IThemeRGB> = [+ 'rgb-border-light',+ 'rgb-border-medium',+ 'rgb-border-medium-alt',+ 'rgb-border-heavy',+ 'rgb-border-xheavy',+ 'rgb-border-destructive',+ 'rgb-chart-widget-stroke',+ 'rgb-ring-primary',+];++const accentTokens: Array<keyof IThemeRGB> = [+ 'rgb-accent-primary',+ 'rgb-accent-primary-hover',+ 'rgb-link',+ 'rgb-link-hover',+ 'rgb-link-visited',+ 'rgb-brand-purple',+];++const statusHues = ['success', 'info', 'warning', 'error', 'neutral'] as const;++function toRgb(theme: IThemeRGB, token: keyof IThemeRGB): Rgb {+ const parts = theme[token]?.trim().split(/\s+/).map(Number);+ if (parts?.length !== 3 || parts.some(Number.isNaN)) {+ throw new Error(`theme token "${token}" is not an "R G B" triplet`);+ }+ return [parts[0], parts[1], parts[2]];+}++function channel(value: number): number {+ const c = value / 255;+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);+}++function luminance([r, g, b]: Rgb): number {+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+}++function contrast(a: Rgb, b: Rgb): number {+ const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x);+ return (lighter + 0.05) / (darker + 0.05);+}++function below(+ theme: IThemeRGB,+ minimum: number,+ foregrounds: Array<keyof IThemeRGB>,+ backgrounds: Array<keyof IThemeRGB>,+): string[] {+ return foregrounds.flatMap((foreground) =>+ backgrounds.flatMap((background) => {+ const ratio = contrast(toRgb(theme, foreground), toRgb(theme, background));+ return ratio < minimum+ ? [`${foreground} on ${background}: ${ratio.toFixed(2)}:1 (needs ${minimum}:1)`]+ : [];+ }),+ );+}++describe.each([+ ['high contrast light', highContrastLightTheme],+ ['high contrast dark', highContrastDarkTheme],+])('%s palette', (_name, theme: IThemeRGB) => {+ it('declares every registry token, so nothing falls back to a mid-grey default', () => {+ expect(Object.keys(theme).sort()).toEqual([...themeColorTokens].sort());+ });++ it('keeps neutral text at WCAG AAA on every canvas and hover fill', () => {+ expect(below(theme, WCAG_AAA_NORMAL, textTokens, surfaces)).toEqual([]);+ });++ it('keeps both shimmer stops at WCAG AAA on the page', () => {+ expect(+ below(+ theme,+ WCAG_AAA_NORMAL,+ ['rgb-shimmer-base', 'rgb-shimmer-dip'],+ ['rgb-surface-primary'],+ ),+ ).toEqual([]);+ });++ it('keeps the selected fill light enough for an AAA label', () => {+ expect(below(theme, WCAG_AAA_NORMAL, textTokens, activeFills)).toEqual([]);+ });++ /** The standard palettes are deliberately not held to this: their dark+ * `syntax-attr` and `syntax-title` measure 3.71:1 and 3.99:1 on the code+ * surface, a pre-existing gap that restyling every dark-mode code block+ * inside a contrast PR would not be the right way to close. */+ it('keeps every syntax colour at WCAG AAA on the code surface', () => {+ expect(below(theme, WCAG_AAA_NORMAL, syntaxTokens, codeSurfaces)).toEqual([]);+ });++ it('keeps warning and destructive text at WCAG AAA on the page', () => {+ expect(+ below(+ theme,+ WCAG_AAA_NORMAL,+ ['rgb-text-warning', 'rgb-text-destructive'],+ ['rgb-surface-primary', 'rgb-surface-secondary', 'rgb-surface-dialog'],+ ),+ ).toEqual([]);+ });++ it('keeps every status hue at WCAG AAA against its own subtle fill', () => {+ const failures = statusHues.flatMap((hue) =>+ below(+ theme,+ WCAG_AAA_NORMAL,+ [`rgb-status-${hue}` as keyof IThemeRGB],+ [`rgb-status-${hue}-subtle` as keyof IThemeRGB],+ ),+ );+ expect(failures).toEqual([]);+ });++ it('keeps accents and links at WCAG AAA on the page', () => {+ expect(+ below(theme, WCAG_AAA_NORMAL, accentTokens, ['rgb-surface-primary', 'rgb-surface-secondary']),+ ).toEqual([]);+ });++ it('keeps inverted and fixed pairs at WCAG AAA', () => {+ expect(below(theme, WCAG_AAA_NORMAL, ['rgb-text-inverted'], ['rgb-surface-inverted'])).toEqual(+ [],+ );+ expect(+ below(theme, WCAG_AAA_NORMAL, ['rgb-text-inverted'], ['rgb-surface-inverted-hover']),+ ).toEqual([]);+ expect(+ below(+ theme,+ WCAG_AAA_NORMAL,+ ['rgb-text-fixed'],+ ['rgb-surface-fixed', 'rgb-surface-fixed-hover'],+ ),+ ).toEqual([]);+ });++ it('keeps borders and rings above the 3:1 non-text floor on every canvas', () => {+ expect(+ below(theme, WCAG_NON_TEXT, borderTokens, [+ 'rgb-surface-primary',+ 'rgb-surface-secondary',+ 'rgb-surface-tertiary',+ 'rgb-surface-dialog',+ ]),+ ).toEqual([]);+ });++ /** Each mode paints its fills on the far side of its own canvas, so the label+ * ratio and the silhouette ratio are the same number and both reach AAA.+ * Getting here is exactly what the per-mode `text-on-status` token buys: a+ * literal white label would cap dark-mode fills at 6.66:1 with a 3.15:1+ * silhouette, because those two would then pull in opposite directions. */+ it('keeps solid fills at WCAG AAA against both their label and the page', () => {+ expect(below(theme, WCAG_AAA_NORMAL, ['rgb-text-on-status'], solidFills)).toEqual([]);+ expect(below(theme, WCAG_AAA_NORMAL, solidFills, ['rgb-surface-primary'])).toEqual([]);+ });++ it('paints its status labels in the ink of the opposing canvas', () => {+ expect(theme['rgb-text-on-status']).toBe(+ theme === highContrastDarkTheme ? '0 0 0' : '255 255 255',+ );+ });++ /** The track is a UI component boundary under WCAG 1.4.11, and it has to stay+ * distinct from the thumb riding on it and from the checked fill it swaps+ * with, or the control loses its state as well as its outline. */+ it('keeps the unchecked switch track distinct from the page, thumb and checked fill', () => {+ expect(+ below(+ theme,+ WCAG_NON_TEXT,+ ['rgb-switch-unchecked'],+ ['rgb-surface-primary', 'rgb-surface-inverted'],+ ),+ ).toEqual([]);+ });++ it('never reuses a reserved status colour for series identity', () => {+ const reserved = new Set(+ statusHues.map((hue) => theme[`rgb-status-${hue}` as keyof IThemeRGB]),+ );+ for (let slot = 1; slot <= 7; slot += 1) {+ expect(reserved.has(theme[`rgb-series-${slot}` as keyof IThemeRGB])).toBe(false);+ }+ });+});++describe('high contrast theme definition', () => {+ it('resolves both modes without falling back to the standard palettes', () => {+ expect(resolveTheme(highContrastTheme, 'light').colors).toEqual(highContrastLightTheme);+ expect(resolveTheme(highContrastTheme, 'dark').colors).toEqual(highContrastDarkTheme);+ expect(resolveTheme(highContrastTheme, 'light').name).toBe(HIGH_CONTRAST_THEME_NAME);+ });++ it('inverts the canvas and the ink between its two modes', () => {+ expect(highContrastLightTheme['rgb-surface-primary']).toBe('255 255 255');+ expect(highContrastLightTheme['rgb-text-primary']).toBe('0 0 0');+ expect(highContrastDarkTheme['rgb-surface-primary']).toBe('0 0 0');+ expect(highContrastDarkTheme['rgb-text-primary']).toBe('255 255 255');+ });++ /** A provider avatar is a brand fill carrying a glyph, so it owes the same two+ * ratios a status fill does: the glyph against the fill, and the fill against+ * the canvas. The standard brand set leaves the white glyph at 2.30:1 on+ * OpenAI green, which is why these are declared per mode. */+ it('keeps every provider avatar at WCAG AAA in both modes', () => {+ const providerFills = themeBrandTokens.filter((token) => token !== 'provider-foreground');++ (+ [+ ['light', '255 255 255'],+ ['dark', '0 0 0'],+ ] as const+ ).forEach(([mode, canvas]) => {+ const resolved = resolveTheme(highContrastTheme, mode);+ const glyph = hexToRgb(resolved.brands['provider-foreground']);+ const canvasRgb = canvas.split(' ').map(Number) as Rgb;++ providerFills.forEach((token) => {+ const fill = hexToRgb(resolved.brands[token]);+ expect({+ token: `${mode} ${token} glyph`,+ ratio: contrast(glyph, fill) >= WCAG_AAA_NORMAL,+ }).toEqual({ token: `${mode} ${token} glyph`, ratio: true });+ expect({+ token: `${mode} ${token} silhouette`,+ ratio: contrast(fill, canvasRgb) >= WCAG_AAA_NORMAL,+ }).toEqual({ token: `${mode} ${token} silhouette`, ratio: true });+ });+ });+ });++ it('lets a mode override the theme-wide brand set', () => {+ const themed = resolveTheme(+ {+ version: 1,+ name: 'per-mode-brands',+ modes: { dark: { brands: { 'provider-openai': '#123456' } } },+ brands: { 'provider-openai': '#abcdef' },+ },+ 'dark',+ );+ expect(themed.brands['provider-openai']).toBe('#123456');++ const inherited = resolveTheme(+ {+ version: 1,+ name: 'per-mode-brands',+ modes: { dark: { brands: { 'provider-openai': '#123456' } } },+ brands: { 'provider-openai': '#abcdef' },+ },+ 'light',+ );+ expect(inherited.brands['provider-openai']).toBe('#abcdef');+ });++ /** A key present with `undefined` is what `Partial` permits and what+ * validation accepts, and every brand token is written to the DOM+ * unconditionally, so spreading it would blank the avatar's fill. */+ it('falls back rather than blanking a brand set to undefined', () => {+ const resolved = resolveTheme(+ {+ version: 1,+ name: 'holes',+ modes: { dark: { brands: { 'provider-openai': undefined } } },+ brands: { 'provider-openai': '#abcdef', 'provider-anthropic': undefined },+ },+ 'dark',+ );++ expect(resolved.brands['provider-openai']).toBe('#abcdef');+ expect(resolved.brands['provider-anthropic']).toBe(defaultBrands['provider-anthropic']);+ expect(Object.values(resolved.brands).every((value) => typeof value === 'string')).toBe(true);+ });++ it('validates a mode brand block the same way as the theme-wide one', () => {+ expect(+ validateThemeDefinition({+ version: 1,+ name: 'invalid',+ modes: { light: { brands: { 'provider-openai': 'rgb(var(--text-primary))' } } },+ }),+ ).toContain('Invalid brand value for provider-openai: rgb(var(--text-primary))');+ expect(+ validateThemeDefinition({+ version: 1,+ name: 'invalid',+ // @ts-expect-error the unknown token is the point of the assertion+ modes: { light: { brands: { 'provider-nope': '#000000' } } },+ }),+ ).toContain('Unknown brand token: provider-nope');+ });+});diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.tsnew file mode 100644index 0000000000..e5e6fc2f7c--- /dev/null+++ b/packages/client/src/theme/themes/highContrast.ts@@ -0,0 +1,290 @@+import { IThemeRGB } from '../types';++/**+ * High contrast accessibility themes.+ *+ * Selected through the appearance modes `high-contrast-light` and+ * `high-contrast-dark`, and by `system` when the OS reports+ * `prefers-contrast: more`. They resolve as a built-in `ThemeDefinition`+ * (`highContrastTheme`) that outranks a deployment's custom theme, because a+ * contrast choice is an accessibility need rather than a branding preference.+ *+ * Both maps are complete rather than partial overrides: a token left to fall+ * back to `defaultTheme`/`darkTheme` would silently reintroduce a mid-grey the+ * mode exists to eliminate.+ *+ * Contrast contract, enforced by `highContrast.spec.ts`:+ * - text clears WCAG AAA (7:1) on every surface it can render on, including the+ * hover and active fills;+ * - solid fills (`surface-submit`, `surface-destructive`, `status-*-strong`)+ * clear AAA against `text-on-status` AND AAA against the page. The label and+ * the silhouette are the same ratio here, because each mode paints its fills+ * on the far side of its own canvas: dark fills under a white label on white,+ * bright fills under a black label on black. That is the whole reason+ * `text-on-status` is a per-mode token rather than a literal white;+ * - borders, rings and series marks clear the 3:1 non-text floor (WCAG 1.4.11).+ */++/**+ * Black ink on a white canvas, black borders on every edge, and accents dark+ * enough (relative luminance <= 0.1) that they clear 7:1 both against the canvas+ * and against white text placed on them.+ */+export const highContrastLightTheme: IThemeRGB = {+ // Text colors+ 'rgb-text-primary': '0 0 0', // #000000+ 'rgb-text-secondary': '0 0 0', // #000000+ 'rgb-text-secondary-alt': '0 0 0', // #000000+ 'rgb-text-tertiary': '0 0 0', // #000000+ 'rgb-text-muted': '0 0 0', // #000000+ 'rgb-text-warning': '122 61 0', // #7a3d00+ 'rgb-text-destructive': '161 0 0', // #a10000+ 'rgb-shimmer-base': '0 0 0', // #000000, 21:1 on white+ 'rgb-shimmer-dip': '77 77 77', // #4d4d4d, 8.45:1 on white++ // Link and accent colors+ 'rgb-link': '0 0 204', // #0000cc+ 'rgb-link-hover': '0 0 128', // #000080+ 'rgb-link-visited': '107 0 179', // #6b00b3+ 'rgb-accent-primary': '0 80 77', // #00504d+ 'rgb-accent-primary-hover': '0 51 48', // #003330++ // Ring colors+ 'rgb-ring-primary': '0 0 0', // #000000++ // Header colors+ 'rgb-header-primary': '255 255 255', // #ffffff+ 'rgb-header-hover': '212 212 212', // #d4d4d4+ 'rgb-header-button-hover': '212 212 212', // #d4d4d4++ // Surface colors+ /** Selected state. The fill does not carry WCAG 1.4.11 on its own: the+ * contrast block in `client/src/style.css` rings every selected row and+ * navigated menu item in `text-primary`, which is 21:1 against either canvas.+ * That perimeter is what frees these fills to stay light, so a selected row's+ * black label clears AAA (15.8:1 and 14.6:1) instead of the 6.25:1 a fill+ * dark enough to mark itself used to cap it at. `-alt` meets `surface-hover`,+ * the same place the standard light palette puts it. */+ 'rgb-surface-active': '227 227 227', // #e3e3e3+ 'rgb-surface-active-alt': '212 212 212', // #d4d4d4+ 'rgb-surface-hover': '212 212 212', // #d4d4d4+ 'rgb-surface-hover-alt': '184 184 184', // #b8b8b8+ 'rgb-surface-composer-hover': '212 212 212', // #d4d4d4+ 'rgb-surface-primary': '255 255 255', // #ffffff+ /** The chart widget canvas and its edge, which default to `surface-primary`+ * and `border-light` elsewhere: here the panel is the plain canvas and its+ * outline is pure ink, so a widget stays legible without a grey wash. */+ 'rgb-chart-widget-surface': '255 255 255', // #ffffff+ 'rgb-chart-widget-stroke': '0 0 0', // #000000+ 'rgb-surface-primary-alt': '255 255 255', // #ffffff+ 'rgb-surface-primary-contrast': '255 255 255', // #ffffff+ 'rgb-surface-secondary': '255 255 255', // #ffffff+ 'rgb-surface-secondary-alt': '255 255 255', // #ffffff+ 'rgb-surface-tertiary': '255 255 255', // #ffffff+ 'rgb-surface-tertiary-alt': '255 255 255', // #ffffff+ 'rgb-surface-dialog': '255 255 255', // #ffffff+ 'rgb-surface-overlay': '0 0 0', // #000000+ 'rgb-surface-submit': '0 92 46', // #005c2e+ 'rgb-surface-submit-hover': '0 61 30', // #003d1e+ 'rgb-surface-destructive': '161 0 0', // #a10000+ 'rgb-surface-destructive-hover': '122 0 0', // #7a0000+ 'rgb-surface-chat': '255 255 255', // #ffffff+ 'rgb-surface-inverted': '0 0 0', // #000000+ 'rgb-surface-inverted-hover': '51 51 51', // #333333+ 'rgb-text-inverted': '255 255 255', // #ffffff+ 'rgb-surface-fixed': '255 255 255', // #ffffff+ 'rgb-surface-fixed-hover': '212 212 212', // #d4d4d4+ 'rgb-text-fixed': '0 0 0', // #000000++ // Border colors+ 'rgb-border-light': '0 0 0', // #000000+ 'rgb-border-medium': '0 0 0', // #000000+ 'rgb-border-medium-alt': '0 0 0', // #000000+ 'rgb-border-heavy': '0 0 0', // #000000+ 'rgb-border-xheavy': '0 0 0', // #000000+ 'rgb-border-destructive': '161 0 0', // #a10000++ // Status colors+ 'rgb-status-success': '0 92 46', // #005c2e+ 'rgb-status-success-subtle': '255 255 255', // #ffffff+ 'rgb-status-success-border': '0 92 46', // #005c2e+ 'rgb-status-success-strong': '0 92 46', // #005c2e+ 'rgb-status-info': '0 65 122', // #00417a+ 'rgb-status-info-subtle': '255 255 255', // #ffffff+ 'rgb-status-info-border': '0 65 122', // #00417a+ 'rgb-status-info-strong': '0 65 122', // #00417a+ 'rgb-status-warning': '122 61 0', // #7a3d00+ 'rgb-status-warning-subtle': '255 255 255', // #ffffff+ 'rgb-status-warning-border': '122 61 0', // #7a3d00+ 'rgb-status-warning-strong': '122 61 0', // #7a3d00+ 'rgb-status-error': '161 0 0', // #a10000+ 'rgb-status-error-subtle': '255 255 255', // #ffffff+ 'rgb-status-error-border': '161 0 0', // #a10000+ 'rgb-status-error-strong': '161 0 0', // #a10000+ 'rgb-status-neutral': '0 0 0', // #000000+ 'rgb-status-neutral-subtle': '255 255 255', // #ffffff+ 'rgb-status-neutral-border': '0 0 0', // #000000+ 'rgb-text-on-status': '255 255 255', // #ffffff++ // Brand colors+ 'rgb-brand-purple': '107 0 179', // #6b00b3++ /** Code syntax highlighting at AAA on the white code surface. */+ 'rgb-syntax-text': '0 0 0', // #000000+ 'rgb-syntax-comment': '77 77 77', // #4d4d4d+ 'rgb-syntax-meta': '77 77 77', // #4d4d4d+ 'rgb-syntax-builtin': '107 61 0', // #6b3d00+ 'rgb-syntax-keyword': '0 61 153', // #003d99+ 'rgb-syntax-string': '0 86 61', // #00563d+ 'rgb-syntax-attr': '122 20 82', // #7a1452+ 'rgb-syntax-title': '143 26 16', // #8f1a10++ /** Categorical series scale. Every slot clears 7:1 on the white canvas and no+ * two adjacent slots sit closer than CIE76 dE 50 under normal vision or dE 45+ * under simulated deuteranopia. */+ 'rgb-series-1': '11 79 160', // #0b4fa0+ 'rgb-series-2': '143 59 0', // #8f3b00+ 'rgb-series-3': '0 82 79', // #00524f+ 'rgb-series-4': '92 74 0', // #5c4a00+ 'rgb-series-5': '148 0 92', // #94005c+ 'rgb-series-6': '77 26 153', // #4d1a99+ 'rgb-series-7': '15 92 15', // #0f5c0f++ /** Unchecked switch track. The stock 58%/40% greys land at 2.9:1 and 2.2:1+ * against these canvases. This clears 3:1 three ways at once: 5.74:1 against+ * the page and the `surface-primary` thumb, 3.66:1 against the checked+ * `surface-inverted` track. */+ 'rgb-switch-unchecked': '102 102 102', // #666666++ // Presentation+ 'rgb-presentation': '255 255 255', // #ffffff+};++/**+ * White ink on a black canvas with white borders, and accents bright enough+ * (relative luminance >= 0.3) that they clear 7:1 both against the canvas and+ * against the black `text-on-status` label placed on them.+ */+export const highContrastDarkTheme: IThemeRGB = {+ // Text colors+ 'rgb-text-primary': '255 255 255', // #ffffff+ 'rgb-text-secondary': '255 255 255', // #ffffff+ 'rgb-text-secondary-alt': '255 255 255', // #ffffff+ 'rgb-text-tertiary': '255 255 255', // #ffffff+ 'rgb-text-muted': '255 255 255', // #ffffff+ 'rgb-text-warning': '255 201 77', // #ffc94d+ 'rgb-text-destructive': '255 143 143', // #ff8f8f+ 'rgb-shimmer-base': '255 255 255', // #ffffff, 21:1 on black+ 'rgb-shimmer-dip': '179 179 179', // #b3b3b3, 10.02:1 on black++ // Link and accent colors+ 'rgb-link': '140 200 255', // #8cc8ff+ 'rgb-link-hover': '194 224 255', // #c2e0ff+ 'rgb-link-visited': '224 179 255', // #e0b3ff+ 'rgb-accent-primary': '92 230 219', // #5ce6db+ 'rgb-accent-primary-hover': '163 242 236', // #a3f2ec++ // Ring colors+ 'rgb-ring-primary': '255 255 255', // #ffffff++ // Header colors+ 'rgb-header-primary': '0 0 0', // #000000+ 'rgb-header-hover': '61 61 61', // #3d3d3d+ 'rgb-header-button-hover': '61 61 61', // #3d3d3d++ // Surface colors+ /** Selected state, the mirror of the light note: the perimeter marks the row,+ * so these step off the canvas only as far as an AAA white label allows —+ * 14.2:1 and 10.9:1, against the 6.69:1 and 5.49:1 a self-marking fill used+ * to force. `-alt` meets `surface-hover`, as it does in the light palette. */+ 'rgb-surface-active': '43 43 43', // #2b2b2b+ 'rgb-surface-active-alt': '61 61 61', // #3d3d3d+ 'rgb-surface-hover': '61 61 61', // #3d3d3d+ 'rgb-surface-hover-alt': '87 87 87', // #575757+ 'rgb-surface-composer-hover': '61 61 61', // #3d3d3d+ 'rgb-surface-primary': '0 0 0', // #000000+ /** See the light mode note: the widget takes the plain canvas and a pure-ink+ * edge rather than the dimmed panel the standard themes use. */+ 'rgb-chart-widget-surface': '0 0 0', // #000000+ 'rgb-chart-widget-stroke': '255 255 255', // #ffffff+ 'rgb-surface-primary-alt': '0 0 0', // #000000+ 'rgb-surface-primary-contrast': '0 0 0', // #000000+ 'rgb-surface-secondary': '0 0 0', // #000000+ 'rgb-surface-secondary-alt': '0 0 0', // #000000+ 'rgb-surface-tertiary': '0 0 0', // #000000+ 'rgb-surface-tertiary-alt': '0 0 0', // #000000+ 'rgb-surface-dialog': '0 0 0', // #000000+ 'rgb-surface-overlay': '0 0 0', // #000000+ 'rgb-surface-submit': '127 240 179', // #7ff0b3+ 'rgb-surface-submit-hover': '163 245 204', // #a3f5cc+ 'rgb-surface-destructive': '255 143 143', // #ff8f8f+ 'rgb-surface-destructive-hover': '255 179 179', // #ffb3b3+ 'rgb-surface-chat': '0 0 0', // #000000+ 'rgb-surface-inverted': '255 255 255', // #ffffff+ 'rgb-surface-inverted-hover': '212 212 212', // #d4d4d4+ 'rgb-text-inverted': '0 0 0', // #000000+ 'rgb-surface-fixed': '255 255 255', // #ffffff+ 'rgb-surface-fixed-hover': '212 212 212', // #d4d4d4+ 'rgb-text-fixed': '0 0 0', // #000000++ // Border colors+ 'rgb-border-light': '255 255 255', // #ffffff+ 'rgb-border-medium': '255 255 255', // #ffffff+ 'rgb-border-medium-alt': '255 255 255', // #ffffff+ 'rgb-border-heavy': '255 255 255', // #ffffff+ 'rgb-border-xheavy': '255 255 255', // #ffffff+ 'rgb-border-destructive': '255 143 143', // #ff8f8f++ // Status colors+ 'rgb-status-success': '127 240 179', // #7ff0b3+ 'rgb-status-success-subtle': '0 0 0', // #000000+ 'rgb-status-success-border': '127 240 179', // #7ff0b3+ 'rgb-status-success-strong': '127 240 179', // #7ff0b3+ 'rgb-status-info': '140 200 255', // #8cc8ff+ 'rgb-status-info-subtle': '0 0 0', // #000000+ 'rgb-status-info-border': '140 200 255', // #8cc8ff+ 'rgb-status-info-strong': '140 200 255', // #8cc8ff+ 'rgb-status-warning': '255 201 77', // #ffc94d+ 'rgb-status-warning-subtle': '0 0 0', // #000000+ 'rgb-status-warning-border': '255 201 77', // #ffc94d+ 'rgb-status-warning-strong': '255 201 77', // #ffc94d+ 'rgb-status-error': '255 143 143', // #ff8f8f+ 'rgb-status-error-subtle': '0 0 0', // #000000+ 'rgb-status-error-border': '255 143 143', // #ff8f8f+ 'rgb-status-error-strong': '255 143 143', // #ff8f8f+ 'rgb-status-neutral': '255 255 255', // #ffffff+ 'rgb-status-neutral-subtle': '0 0 0', // #000000+ 'rgb-status-neutral-border': '255 255 255', // #ffffff+ 'rgb-text-on-status': '0 0 0', // #000000++ // Brand colors+ 'rgb-brand-purple': '224 179 255', // #e0b3ff++ /** Code syntax highlighting at AAA on the black code surface. */+ 'rgb-syntax-text': '255 255 255', // #ffffff+ 'rgb-syntax-comment': '179 179 179', // #b3b3b3+ 'rgb-syntax-meta': '179 179 179', // #b3b3b3+ 'rgb-syntax-builtin': '255 201 77', // #ffc94d+ 'rgb-syntax-keyword': '140 200 255', // #8cc8ff+ 'rgb-syntax-string': '127 240 179', // #7ff0b3+ 'rgb-syntax-attr': '255 153 194', // #ff99c2+ 'rgb-syntax-title': '255 143 143', // #ff8f8f++ /** Categorical series scale. Every slot clears 9.9:1 on the black canvas and no+ * two adjacent slots sit closer than CIE76 dE 37 under normal vision or dE 42+ * under simulated deuteranopia. */+ 'rgb-series-1': '107 184 255', // #6bb8ff+ 'rgb-series-2': '255 179 102', // #ffb366+ 'rgb-series-3': '92 230 219', // #5ce6db+ 'rgb-series-4': '255 224 102', // #ffe066+ 'rgb-series-5': '255 153 194', // #ff99c2+ 'rgb-series-6': '200 163 255', // #c8a3ff+ 'rgb-series-7': '140 230 140', // #8ce68c++ /** Unchecked switch track: 5.32:1 against the page and the `surface-primary`+ * thumb, 3.95:1 against the checked `surface-inverted` track. */+ 'rgb-switch-unchecked': '128 128 128', // #808080++ // Presentation+ 'rgb-presentation': '0 0 0', // #000000+};diff --git a/packages/client/src/theme/themes/index.ts b/packages/client/src/theme/themes/index.tsindex 89b1b0e251..39d5d1631e 100644--- a/packages/client/src/theme/themes/index.ts+++ b/packages/client/src/theme/themes/index.ts@@ -1,2 +1,3 @@export { defaultTheme } from './default';export { darkTheme } from './dark';+export { highContrastDarkTheme, highContrastLightTheme } from './highContrast';diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.tsindex 074c6e29ff..5848850b58 100644--- a/packages/client/src/theme/types/index.ts+++ b/packages/client/src/theme/types/index.ts@@ -94,6 +94,20 @@ export interface IThemeRGB {// Brand colors'rgb-brand-purple'?: string;+ /**+ * Code syntax highlighting. Declared here rather than left as literals in the+ * stylesheet so a palette stays in one place, is covered by the registry's+ * completeness check, and can be contrast-tested.+ */+ 'rgb-syntax-text'?: string;+ 'rgb-syntax-comment'?: string;+ 'rgb-syntax-meta'?: string;+ 'rgb-syntax-builtin'?: string;+ 'rgb-syntax-keyword'?: string;+ 'rgb-syntax-string'?: string;+ 'rgb-syntax-attr'?: string;+ 'rgb-syntax-title'?: string;+/*** Categorical data-visualisation scale. Slots carry series identity only — the* order is the colour-vision-deficiency safety mechanism and must not be@@ -107,6 +121,14 @@ export interface IThemeRGB {'rgb-series-6'?: string;'rgb-series-7'?: string;+ /**+ * Unchecked track of the shared `Switch`. A control state rather than a+ * palette entry, but it lives here because the package's own control renders+ * it: left in the application stylesheet, a consumer of `@librechat/client`+ * got a switch with no track at all.+ */+ 'rgb-switch-unchecked'?: string;+// Presentation'rgb-presentation'?: string;}@@ -192,6 +214,15 @@ export interface IThemeVariables {'--text-on-status': string;'--brand-purple': string;+ '--syntax-text': string;+ '--syntax-comment': string;+ '--syntax-meta': string;+ '--syntax-builtin': string;+ '--syntax-keyword': string;+ '--syntax-string': string;+ '--syntax-attr': string;+ '--syntax-title': string;+'--series-1': string;'--series-2': string;'--series-3': string;@@ -200,6 +231,8 @@ export interface IThemeVariables {'--series-6': string;'--series-7': string;+ '--switch-unchecked': string;+'--presentation': string;}@@ -285,6 +318,7 @@ export interface IThemeColors {'series-5'?: string;'series-6'?: string;'series-7'?: string;+ 'switch-unchecked'?: string;presentation?: string;// Retained for excluded SidePanel/Agents + SidePanel/Builder (pending migration)@@ -318,6 +352,13 @@ export interface IThemeAppearance {export interface ThemeModeDefinition {colors?: IThemeRGB;appearance?: Partial<IThemeAppearance>;+ /**+ * Brand overrides for this mode only, applied over the theme-wide `brands`.+ * A brand fill carries a glyph and has to stand out from the canvas, and both+ * of those flip between light and dark, so a single set cannot serve both at+ * enhanced contrast.+ */+ brands?: Partial<IThemeBrands>;}export interface IThemeBrands {diff --git a/packages/client/src/theme/utils/createTailwindColors.js b/packages/client/src/theme/utils/createTailwindColors.jsindex d065a73457..c4e31cfe25 100644--- a/packages/client/src/theme/utils/createTailwindColors.js+++ b/packages/client/src/theme/utils/createTailwindColors.js@@ -12,10 +12,9 @@* bare `R G B` channel triplets, so `cssVar` wraps them as* `rgb(var(--x) / <alpha-value>)`. This makes opacity modifiers work, e.g.* `bg-surface-primary/50`. Tokens with an intrinsic alpha use a companion- * `--x-alpha` variable that is multiplied by Tailwind's opacity modifier.- * shadcn-compatible tokens still hold HSL triplets, so they are wrapped in- * `hsl(...)`; any direct `var(--token)` usage in plain CSS must wrap the channel- * triplet itself, e.g. `color: rgb(var(--text-primary))`.+ * `--x-alpha` variable that is multiplied by Tailwind's opacity modifier. Every+ * token is an `R G B` triplet, so a direct `var(--token)` usage in plain CSS+ * must wrap the channel triplet itself, e.g. `color: rgb(var(--text-primary))`.*/const palette = {@@ -51,7 +50,6 @@ const palette = {const cssVar = (name) => `rgb(var(${name}) / <alpha-value>)`;const cssVarWithAlpha = (name) => `rgb(var(${name}) / calc(var(${name}-alpha, 1) * <alpha-value>))`;-const hslVar = (name) => `hsl(var(${name}))`;/*** Creates the Tailwind `theme.extend.colors` object backed by CSS variables.@@ -152,7 +150,7 @@ function createTailwindColors() {'series-6': cssVar('--series-6'),'series-7': cssVar('--series-7'),- 'switch-unchecked': hslVar('--switch-unchecked'),+ 'switch-unchecked': cssVar('--switch-unchecked'),};}diff --git a/packages/client/tailwind.preset.cjs b/packages/client/tailwind.preset.cjsindex a25b41b8b0..53c11d5175 100644--- a/packages/client/tailwind.preset.cjs+++ b/packages/client/tailwind.preset.cjs@@ -29,4 +29,25 @@ module.exports = {},},},+ plugins: [+ /**+ * A bare function rather than `plugin()` from `tailwindcss/plugin`, because+ * this preset ships as a raw file through the `./tailwind-preset` export and+ * `tailwindcss` is a devDependency here. Requiring it would fail to resolve+ * for an external consumer under pnpm or Yarn PnP. Tailwind accepts a plain+ * function in `plugins`; the wrapper only adds option and config handling+ * this variant does not need.+ */+ ({ addVariant }) => {+ /**+ * Styling that applies only in the high contrast appearance modes, the+ * same way `dark:` applies only under the `dark` class. Distinct from+ * Tailwind's built-in `contrast-more:`, which is the raw+ * `prefers-contrast: more` media query: this follows the resolved app+ * mode, so it covers an explicit `high-contrast-light` /+ * `high-contrast-dark` choice as well as the OS preference.+ */+ addVariant('high-contrast', 'html.high-contrast &');+ },+ ],};