From 18b6937da3521ed0e3eb342bf809bc9263e7d9e5 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Mon, 28 Sep 2026 21:21:53 +0200 Subject: [PATCH 01/21] =?UTF-8?q?=F0=9F=A7=AF=20fix:=20Outlast=20Failed=20?= =?UTF-8?q?Auth=20Cache=20Eviction=20on=20Credential=20Changes=20(#16435)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: outlast failed auth cache eviction on credential changes A credential change committed to MongoDB could report success while a cached auth user document without the new credentialsChangedAt stayed readable, so an old OpenID access token kept authorizing until the cache TTL. The Redis-backed auth cache swallowed every failure (Keyv and KeyvRedis resolve a failed GET as a miss and a failed DEL as a no-op), and the eviction helpers stopped at the first error. - The AUTH_USER_DOC namespace opts into throwOnErrors so a failed read or delete is visible; every caller of that namespace already catches. - evictAuthUserDocs attempts every delete even when another fails and reports whether a document may still be served; the data-schemas and packages/api invalidation paths share it. - updateUser waits out AUTH_USER_DOC_CACHE_TTL_MS before returning a credential change whose eviction was incomplete, so the change is only confirmed once no pre-change document can be served. Other updates stay best effort, and later revocations are delayed, never skipped. * fix: record the reverse index before caching an auth user document A document written before its reverse-index entry was cached without an index naming it when the index write failed, so eviction could not find it. Write the index first with a TTL that outlives the documents it names, and skip the document when the index write fails. * test: keep real data-schemas helpers in the pinned order spec * fix: settle the auth cache after revoking reset credentials Waiting out the cache TTL inside updateUser held the reset before its session and passkey revocations, so a live refresh token or passkey could mint an access token issued after credentialsChangedAt during the wait. updateUser is best effort again; awaitAuthUserDocEviction retries the eviction and waits one TTL only when it is still incomplete, and both the web reset controller and the reset CLI call it after revoking sessions and passkeys, before confirming the reset. * fix: settle the credential barrier with a margin and on CLI revocation errors Timers can fire a millisecond early, so the eviction barrier now waits the cache TTL plus a 100 ms margin. The reset CLI also settles the barrier when revoking passkeys or sessions throws, since the password is already changed. * fix: treat an auth cache that cannot delete as not evicted * fix: keep the reverse index until every document it names is evicted A failed eviction still deleted the reverse index, so the credential barrier's retry found no index and reported the cache clear while the documents an unreadable index or a failed delete left behind stayed cached. The index is now deleted only after it was read and every document it names is gone, so a retry can still find what remains. * fix: treat a malformed auth reverse index as unreadable * fix: treat a reverse index with a non-string entry as unreadable --- api/cache/getLogStores.js | 4 +- api/server/controllers/AuthController.js | 2 + api/server/controllers/AuthController.spec.js | 29 +++++ config/reset-password.js | 12 +- .../mock/scenarios/reset-password.spec.ts | 107 +++++++++++++++- .../api/src/auth/credentials.eviction.spec.ts | 85 +++++++++++++ packages/api/src/auth/passwordReset.ts | 4 + packages/api/src/auth/userDocCache.spec.ts | 26 +++- packages/api/src/auth/userDocCache.ts | 44 +++---- .../standardCache.cache_integration.spec.ts | 15 +++ .../standardCache.namespace_isolation.spec.ts | 2 +- packages/api/src/cache/cacheFactory.ts | 15 ++- packages/api/src/favorites/pinned.spec.ts | 1 + packages/data-provider/src/config.ts | 3 + .../src/methods/user.methods.spec.ts | 119 +++++++++++++++++- packages/data-schemas/src/methods/user.ts | 55 +++++--- .../data-schemas/src/utils/eviction.spec.ts | 111 ++++++++++++++++ packages/data-schemas/src/utils/eviction.ts | 77 ++++++++++++ packages/data-schemas/src/utils/index.ts | 1 + 19 files changed, 655 insertions(+), 57 deletions(-) create mode 100644 packages/api/src/auth/credentials.eviction.spec.ts create mode 100644 packages/data-schemas/src/utils/eviction.spec.ts create mode 100644 packages/data-schemas/src/utils/eviction.ts diff --git a/api/cache/getLogStores.js b/api/cache/getLogStores.js index 1edae18156..53d73125df 100644 --- a/api/cache/getLogStores.js +++ b/api/cache/getLogStores.js @@ -66,7 +66,9 @@ const namespaces = { CacheKeys.OPENID_EXCHANGED_TOKENS, Time.TEN_MINUTES, ), - [CacheKeys.AUTH_USER_DOC]: standardCache(CacheKeys.AUTH_USER_DOC), + [CacheKeys.AUTH_USER_DOC]: standardCache(CacheKeys.AUTH_USER_DOC, undefined, undefined, { + throwOnErrors: true, + }), [CacheKeys.ADMIN_OAUTH_EXCHANGE]: standardCache( CacheKeys.ADMIN_OAUTH_EXCHANGE, Time.THIRTY_SECONDS, diff --git a/api/server/controllers/AuthController.js b/api/server/controllers/AuthController.js index 107f0dbdff..f5e3a230f0 100644 --- a/api/server/controllers/AuthController.js +++ b/api/server/controllers/AuthController.js @@ -24,6 +24,7 @@ const { const { deleteAllUserSessions, deletePasskeysByUser, + awaitAuthUserDocEviction, getUserById, findSession, updateUser, @@ -326,6 +327,7 @@ const resetPasswordController = createResetPasswordController({ resetPassword, deleteAllUserSessions, deletePasskeysByUser, + awaitAuthUserDocEviction, }); const refreshController = async (req, res) => { diff --git a/api/server/controllers/AuthController.spec.js b/api/server/controllers/AuthController.spec.js index 50090636ea..6a1866c1f9 100644 --- a/api/server/controllers/AuthController.spec.js +++ b/api/server/controllers/AuthController.spec.js @@ -42,6 +42,7 @@ jest.mock('~/models', () => ({ deleteSession: jest.fn(), deleteAllUserSessions: jest.fn(), deletePasskeysByUser: jest.fn(), + awaitAuthUserDocEviction: jest.fn(), getUserById: jest.fn(), findSession: jest.fn(), updateUser: jest.fn(), @@ -147,6 +148,7 @@ const { deleteTokens, deleteAllUserSessions, deletePasskeysByUser, + awaitAuthUserDocEviction, } = require('~/models'); const { createRefreshTokenBridgeFlightKey, @@ -2483,6 +2485,7 @@ describe('resetPasswordController', () => { resetPassword.mockReset().mockResolvedValue(serviceResult); deleteAllUserSessions.mockReset().mockResolvedValue(undefined); deletePasskeysByUser.mockReset().mockResolvedValue(undefined); + awaitAuthUserDocEviction.mockReset().mockResolvedValue(undefined); req = { body: { userId: 'user-123', @@ -2511,6 +2514,31 @@ describe('resetPasswordController', () => { expect(res.json).toHaveBeenCalledWith(serviceResult); }); + it('confirms the reset only after revoking and settling the auth cache', async () => { + let finishEviction; + awaitAuthUserDocEviction.mockReturnValue( + new Promise((resolve) => { + finishEviction = resolve; + }), + ); + + const reset = resetPasswordController(req, res); + await new Promise((resolve) => setImmediate(resolve)); + const responseCalls = res.status.mock.calls.length; + finishEviction(); + await reset; + + expect(awaitAuthUserDocEviction).toHaveBeenCalledWith('user-123'); + expect(deleteAllUserSessions.mock.invocationCallOrder[0]).toBeLessThan( + awaitAuthUserDocEviction.mock.invocationCallOrder[0], + ); + expect(deletePasskeysByUser.mock.invocationCallOrder[0]).toBeLessThan( + awaitAuthUserDocEviction.mock.invocationCallOrder[0], + ); + expect(responseCalls).toBe(0); + expect(res.status).toHaveBeenCalledWith(200); + }); + it('does not revoke sessions or passkeys when reset fails', async () => { const resetError = new Error('Invalid token'); resetPassword.mockResolvedValue(resetError); @@ -2519,6 +2547,7 @@ describe('resetPasswordController', () => { expect(deleteAllUserSessions).not.toHaveBeenCalled(); expect(deletePasskeysByUser).not.toHaveBeenCalled(); + expect(awaitAuthUserDocEviction).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(400); expect(res.json).toHaveBeenCalledWith(resetError); }); diff --git a/config/reset-password.js b/config/reset-password.js index 1d239f58b1..3144ade839 100644 --- a/config/reset-password.js +++ b/config/reset-password.js @@ -85,9 +85,15 @@ const resetPassword = async () => { * A passkey signs in on its own, so leaving one in place would keep an attacker * logged in after an administrator believes the account has been recovered. */ - const { deletedCount } = await Passkey.deleteMany({ user: user._id }); - /** A refresh session outlives the stamp: refreshing mints a token issued after it. */ - await Session.deleteMany({ user: user._id }); + let deletedCount; + try { + ({ deletedCount } = await Passkey.deleteMany({ user: user._id })); + /** A refresh session outlives the stamp: refreshing mints a token issued after it. */ + await Session.deleteMany({ user: user._id }); + } finally { + /** The password is already changed, so the cache settles even when a revocation fails. */ + await methods.awaitAuthUserDocEviction(user._id.toString()); + } console.log('Password successfully reset!'); if (deletedCount > 0) { diff --git a/e2e/specs/mock/scenarios/reset-password.spec.ts b/e2e/specs/mock/scenarios/reset-password.spec.ts index fc14e00759..a25739132a 100644 --- a/e2e/specs/mock/scenarios/reset-password.spec.ts +++ b/e2e/specs/mock/scenarios/reset-password.spec.ts @@ -4,7 +4,11 @@ import os from 'os'; import { Keyv } from 'keyv'; import KeyvRedis from '@keyv/redis'; import { expect, test } from '@playwright/test'; -import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider'; +import { + CacheKeys, + AUTH_USER_DOC_BY_ID_PREFIX, + AUTH_USER_DOC_CACHE_TTL_MS, +} from 'librechat-data-provider'; import { spawn } from 'node:child_process'; import { randomInt, randomUUID } from 'node:crypto'; import { withMongo, seedPasskey, deleteUserByEmail } from '../db'; @@ -40,7 +44,13 @@ function runResetCli( email: string, cwd: string, env: NodeJS.ProcessEnv, -): Promise<{ code: number | null; stdout: string; stderr: string }> { +): Promise<{ + code: number | null; + stdout: string; + stderr: string; + /** Milliseconds between confirming the new password and the CLI reporting success. */ + reportDelayMs?: number; +}> { const child = spawn(process.execPath, [path.join(REPO_ROOT, 'config/reset-password.js')], { cwd, env: { @@ -59,14 +69,20 @@ function runResetCli( ['Confirm new password: ', NEW_PASSWORD], ]; let stdout = ''; + let confirmedAt: number | undefined; + let reportedAt: number | undefined; child.stdout?.on('data', (chunk: Buffer) => { stdout += chunk.toString(); answers.forEach((answer, index) => { if (answer !== null && stdout.includes(answer[0])) { child.stdin?.write(`${answer[1]}\n`); answers[index] = null; + confirmedAt = Date.now(); } }); + if (reportedAt === undefined && stdout.includes('Password successfully reset!')) { + reportedAt = Date.now(); + } }); let stderr = ''; child.stderr?.on('data', (chunk: Buffer) => (stderr += chunk.toString())); @@ -82,7 +98,11 @@ function runResetCli( child.on('close', (code) => { clearTimeout(timer); child.stdin?.end(); - resolve({ code, stdout, stderr }); + const reportDelayMs = + confirmedAt !== undefined && reportedAt !== undefined + ? reportedAt - confirmedAt + : undefined; + resolve({ code, stdout, stderr, reportDelayMs }); }); }); } @@ -230,4 +250,85 @@ test.describe('CLI password reset', () => { } }); } + + test('reports the reset only after unevictable cached credentials expire @scenario:cli-reset-outlasts-failed-cache-eviction', async ({ + playwright, + baseURL, + }) => { + test.setTimeout(90_000); + const request = await playwright.request.newContext({ + baseURL, + extraHTTPHeaders: { + 'X-Forwarded-For': `127.${randomInt(1, 255)}.${randomInt(1, 255)}.${randomInt(1, 255)}`, + }, + }); + const email = `cli-evict-${randomUUID().slice(0, 8)}@example.com`; + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'lc-reset-')); + const redisUri = process.env.REDIS_URI ?? 'redis://127.0.0.1:6379'; + const prefix = `cli-evict-${randomUUID()}`; + const adapter = new KeyvRedis(redisUri, { throwOnErrors: true, connectionTimeout: 5000 }); + const cache = new Keyv(adapter, { namespace: CacheKeys.AUTH_USER_DOC }); + adapter.namespace = prefix; + adapter.keyPrefixSeparator = '::'; + const keys: string[] = []; + try { + const register = await request.post('/api/auth/register', { + data: { email, name: 'CLI Evict', password: PASSWORD, confirm_password: PASSWORD }, + }); + expect(register.ok()).toBeTruthy(); + const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } }); + expect(login.ok()).toBeTruthy(); + const { token, user } = (await login.json()) as { token: string; user: { _id: string } }; + await seedPasskey(email, randomUUID(), 'Eviction regression'); + + const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${user._id}`; + const controlKey = 'auth-user-doc:another-user'; + keys.push(indexKey, controlKey); + await cache.set(controlKey, { credentialsChangedAt: null }, 120_000); + /** A hash where the index string belongs makes the CLI's GET fail with WRONGTYPE. */ + const client = await adapter.getClient(); + await client.hSet(`${prefix}::${CacheKeys.AUTH_USER_DOC}:${indexKey}`, 'unreadable', '1'); + await client.pExpire(`${prefix}::${CacheKeys.AUTH_USER_DOC}:${indexKey}`, 120_000); + + const env = { ...process.env }; + Object.assign(env, { + USE_REDIS: 'true', + USE_REDIS_CLUSTER: 'false', + REDIS_URI: redisUri, + REDIS_KEY_PREFIX: prefix, + REDIS_KEY_PREFIX_VAR: '', + AUTH_USER_CACHE_MODE: 'on', + FORCED_IN_MEMORY_CACHE_NAMESPACES: '', + }); + + const cli = await runResetCli(email, cwd, env); + expect(cli.code, cli.stderr.slice(-400)).toBe(0); + expect(cli.stdout).toContain('Password successfully reset!'); + expect(cli.reportDelayMs).toBeGreaterThanOrEqual(AUTH_USER_DOC_CACHE_TTL_MS); + expect(await cache.get(controlKey)).toEqual({ credentialsChangedAt: null }); + await withMongo(async (db) => { + const resetUser = await db.collection('users').findOne({ email }); + expect(resetUser?.credentialsChangedAt).toBeTruthy(); + expect(await db.collection('passkeys').countDocuments({ user: resetUser!._id })).toBe(0); + expect(await db.collection('sessions').countDocuments({ user: resetUser!._id })).toBe(0); + }); + const rejected = await request.get('/api/user', { + headers: { Authorization: `Bearer ${token}` }, + }); + expect(rejected.status()).toBe(401); + const newLogin = await request.post('/api/auth/login', { + data: { email, password: NEW_PASSWORD }, + }); + expect(newLogin.ok()).toBeTruthy(); + } finally { + try { + await Promise.all(keys.map((key) => cache.delete(key))); + } finally { + await cache.disconnect(); + await request.dispose(); + fs.rmSync(cwd, { recursive: true, force: true }); + await deleteUserByEmail(email); + } + } + }); }); diff --git a/packages/api/src/auth/credentials.eviction.spec.ts b/packages/api/src/auth/credentials.eviction.spec.ts new file mode 100644 index 0000000000..db254d9422 --- /dev/null +++ b/packages/api/src/auth/credentials.eviction.spec.ts @@ -0,0 +1,85 @@ +import { Keyv } from 'keyv'; +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { createMethods, createModels } from '@librechat/data-schemas'; +import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider'; +import type { IUser } from '@librechat/data-schemas'; +import { + getCachedAuthUserDoc, + setCachedAuthUserDoc, + buildAuthUserDocCacheKey, + AUTH_USER_DOC_CACHE_TTL_MS, +} from './userDocCache'; +import { isTokenIssuedBeforeCredentialChange } from './credentials'; + +let mongoServer: MongoMemoryServer; +const originalCacheMode = process.env.AUTH_USER_CACHE_MODE; + +beforeAll(async () => { + mongoServer = await MongoMemoryServer.create(); + await mongoose.connect(mongoServer.getUri()); + createModels(mongoose); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongoServer.stop(); +}); + +afterEach(() => { + if (originalCacheMode === undefined) { + delete process.env.AUTH_USER_CACHE_MODE; + } else { + process.env.AUTH_USER_CACHE_MODE = originalCacheMode; + } +}); + +describe('credential change with a failing auth cache', () => { + it('rejects an old OpenID access token once the credential barrier passes, even when the reverse index cannot be read', async () => { + process.env.AUTH_USER_CACHE_MODE = 'on'; + const store = new Keyv(); + /** The index read fails the way a throwing Redis store rejects a WRONGTYPE reply. */ + const failingStore = { + get: async (key: string) => { + if (key.startsWith(AUTH_USER_DOC_BY_ID_PREFIX)) { + throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value'); + } + return store.get(key); + }, + set: (key: string, value: unknown, ttl?: number) => store.set(key, value, ttl), + delete: (key: string) => store.delete(key), + }; + const methods = createMethods(mongoose, { + getCache: (key: string) => (key === CacheKeys.AUTH_USER_DOC ? failingStore : undefined), + }); + const user = (await methods.createUser( + { email: 'oidc@example.com', provider: 'openid', openidId: 'subject-1' }, + undefined, + true, + true, + )) as Partial; + const userId = String(user._id); + const cacheKey = buildAuthUserDocCacheKey({ strategy: 'openid-jwt', subject: 'subject-1' }); + if (!cacheKey) { + throw new Error('expected a cache key'); + } + await setCachedAuthUserDoc(store, cacheKey, user); + const oldToken = { iat: Math.floor(Date.now() / 1000) - 60 }; + expect( + isTokenIssuedBeforeCredentialChange(oldToken, await getCachedAuthUserDoc(store, cacheKey)), + ).toBe(false); + + const updated = await methods.updateUser(userId, { + password: 'new-password-hash', + credentialsChangedAt: new Date(), + }); + const startedAt = Date.now(); + await methods.awaitAuthUserDocEviction(userId); + + expect(Date.now() - startedAt).toBeGreaterThanOrEqual(AUTH_USER_DOC_CACHE_TTL_MS); + expect(updated?.credentialsChangedAt).toBeInstanceOf(Date); + await expect(getCachedAuthUserDoc(store, cacheKey)).resolves.toBeUndefined(); + const current = await methods.findUser({ openidId: 'subject-1' }); + expect(isTokenIssuedBeforeCredentialChange(oldToken, current)).toBe(true); + }, 20_000); +}); diff --git a/packages/api/src/auth/passwordReset.ts b/packages/api/src/auth/passwordReset.ts index 3c3a2bf75b..50fc044b99 100644 --- a/packages/api/src/auth/passwordReset.ts +++ b/packages/api/src/auth/passwordReset.ts @@ -45,6 +45,8 @@ export interface PasswordResetControllerDeps { ) => Promise<{ message: string } | Error>; deleteAllUserSessions: (query: { userId: string }) => Promise<{ deletedCount?: number }>; deletePasskeysByUser: (userId: string) => Promise<{ deletedCount?: number }>; + /** Resolves once no cached auth document from before the reset can be served. */ + awaitAuthUserDocEviction: (userId: string) => Promise; } export type PasswordResetOutcome = @@ -81,6 +83,8 @@ export function createResetPasswordController(deps: PasswordResetControllerDeps) passkeys.reason, ); } + /** After the revocations, so nothing can mint a post-stamp token while it waits. */ + await deps.awaitAuthUserDocEviction(userId); return res.status(200).json(result); } catch (error) { diff --git a/packages/api/src/auth/userDocCache.spec.ts b/packages/api/src/auth/userDocCache.spec.ts index 4c70c438ab..766e33a4d9 100644 --- a/packages/api/src/auth/userDocCache.spec.ts +++ b/packages/api/src/auth/userDocCache.spec.ts @@ -13,6 +13,7 @@ import { import { cacheConfig } from '~/cache/cacheConfig'; jest.mock('@librechat/data-schemas', () => ({ + ...jest.requireActual('@librechat/data-schemas'), logger: { warn: jest.fn(), }, @@ -188,10 +189,33 @@ describe('auth user document cache helpers', () => { expect(store.set).toHaveBeenCalledWith( buildAuthUserDocReverseIndexKey(userId.toString()), [cacheKey], - AUTH_USER_DOC_CACHE_TTL_MS, + AUTH_USER_DOC_CACHE_TTL_MS * 2, ); }); + it('does not cache a document the reverse index could not record', async () => { + const store = makeStore(); + const userId = new Types.ObjectId(); + const indexKey = buildAuthUserDocReverseIndexKey(userId.toString()); + store.set.mockImplementation(async (key: string, value: unknown) => { + if (key === indexKey) { + throw new Error('redis unavailable'); + } + store.values.set(key, value); + return true; + }); + + await setCachedAuthUserDoc(store, 'auth-user-doc:v2:orphan', { + _id: userId, + email: 'user@example.com', + }); + + expect(store.values.has('auth-user-doc:v2:orphan')).toBe(false); + expect(logger.warn).toHaveBeenCalledWith('[authUserDocCache] Cache write failed', { + error: 'redis unavailable', + }); + }); + it('deduplicates reverse-index keys and caps the remembered set', async () => { const store = makeStore(); const objectId = new Types.ObjectId(); diff --git a/packages/api/src/auth/userDocCache.ts b/packages/api/src/auth/userDocCache.ts index 7a308e3823..4fa91a4772 100644 --- a/packages/api/src/auth/userDocCache.ts +++ b/packages/api/src/auth/userDocCache.ts @@ -1,11 +1,15 @@ import { createHash } from 'crypto'; -import { logger } from '@librechat/data-schemas'; -import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider'; +import { logger, evictAuthUserDocs } from '@librechat/data-schemas'; +import { + CacheKeys, + AUTH_USER_DOC_BY_ID_PREFIX, + AUTH_USER_DOC_CACHE_TTL_MS, +} from 'librechat-data-provider'; import type { IUser } from '@librechat/data-schemas'; import { cacheConfig } from '~/cache/cacheConfig'; const AUTH_USER_DOC_CACHE_VERSION = 2; -export const AUTH_USER_DOC_CACHE_TTL_MS = 5000; +export { AUTH_USER_DOC_CACHE_TTL_MS }; export type AuthUserDocCacheMode = 'off' | 'on'; @@ -164,6 +168,10 @@ export async function getCachedAuthUserDoc( } } +/** + * The reverse index is written first and outlives every document it names, so eviction can + * always find a cached document: when the index write fails, the document is not cached. + */ export async function setCachedAuthUserDoc( store: AuthUserDocCacheStore, cacheKey: string, @@ -171,6 +179,10 @@ export async function setCachedAuthUserDoc( ): Promise { try { const sanitized = sanitizeUserForCache(user); + const userId = getUserId(sanitized); + if (userId) { + await rememberUserCacheKey(store, userId, cacheKey, AUTH_USER_DOC_CACHE_TTL_MS * 2); + } await store.set( cacheKey, { @@ -180,10 +192,6 @@ export async function setCachedAuthUserDoc( } satisfies CachedAuthUserDoc, AUTH_USER_DOC_CACHE_TTL_MS, ); - const userId = getUserId(sanitized); - if (userId) { - await rememberUserCacheKey(store, userId, cacheKey, AUTH_USER_DOC_CACHE_TTL_MS); - } } catch (error) { logger.warn('[authUserDocCache] Cache write failed', { error: error instanceof Error ? error.message : String(error), @@ -198,25 +206,5 @@ export async function invalidateCachedAuthUserDoc( if (!store) { return; } - try { - const keys = new Set(); - if (input.cacheKey) { - keys.add(input.cacheKey); - } - if (input.userId) { - const indexKey = buildAuthUserDocReverseIndexKey(input.userId); - const indexed = await store.get(indexKey); - if (Array.isArray(indexed)) { - for (const key of indexed) { - keys.add(key); - } - } - await store.delete(indexKey); - } - await Promise.all([...keys].map((key) => store.delete(key))); - } catch (error) { - logger.warn('[authUserDocCache] Cache invalidation failed', { - error: error instanceof Error ? error.message : String(error), - }); - } + await evictAuthUserDocs(store, input); } diff --git a/packages/api/src/cache/__tests__/cacheFactory/standardCache.cache_integration.spec.ts b/packages/api/src/cache/__tests__/cacheFactory/standardCache.cache_integration.spec.ts index 325bcd3e0f..dc2e77e005 100644 --- a/packages/api/src/cache/__tests__/cacheFactory/standardCache.cache_integration.spec.ts +++ b/packages/api/src/cache/__tests__/cacheFactory/standardCache.cache_integration.spec.ts @@ -189,6 +189,21 @@ describe('standardCache', () => { expect(cacheWithOpts.opts.ttl).toBe(5000); }); + test('rejects failed operations only for a cache created with throwOnErrors', async () => { + const cacheFactory = await import('../../cacheFactory'); + const { ioredisClient } = await import('../../redisClients'); + if (!ioredisClient) throw new Error('ioredisClient is null'); + const strict = cacheFactory.standardCache('strict-namespace', undefined, undefined, { + throwOnErrors: true, + }); + const lenient = cacheFactory.standardCache('lenient-namespace'); + await ioredisClient.hset('strict-namespace:wrong-type', 'f', 'v'); + await ioredisClient.hset('lenient-namespace:wrong-type', 'f', 'v'); + + await expect(strict.get('wrong-type')).rejects.toThrow(/WRONGTYPE/); + await expect(lenient.get('wrong-type')).resolves.toBeUndefined(); + }); + test('should handle TTL correctly', async () => { const cacheFactory = await import('../../cacheFactory'); testCache = cacheFactory.standardCache('ttl-test', 1000); // 1 second TTL diff --git a/packages/api/src/cache/__tests__/cacheFactory/standardCache.namespace_isolation.spec.ts b/packages/api/src/cache/__tests__/cacheFactory/standardCache.namespace_isolation.spec.ts index 32a1492555..0ab85a87aa 100644 --- a/packages/api/src/cache/__tests__/cacheFactory/standardCache.namespace_isolation.spec.ts +++ b/packages/api/src/cache/__tests__/cacheFactory/standardCache.namespace_isolation.spec.ts @@ -67,7 +67,7 @@ describe('standardCache - CONFIG_STORE vs TOOL_CACHE namespace isolation', () => const toolCache = standardCache(CacheKeys.TOOL_CACHE); expect(MockKeyvRedis).toHaveBeenCalledTimes(1); - expect(MockKeyvRedis).toHaveBeenCalledWith(mockKeyvRedisClient); + expect(MockKeyvRedis).toHaveBeenCalledWith(mockKeyvRedisClient, { throwOnErrors: false }); expect(toolCache).toBeDefined(); }); diff --git a/packages/api/src/cache/cacheFactory.ts b/packages/api/src/cache/cacheFactory.ts index 07e443cac8..61e0d6d47a 100644 --- a/packages/api/src/cache/cacheFactory.ts +++ b/packages/api/src/cache/cacheFactory.ts @@ -85,9 +85,17 @@ async function clearRedisNamespace(namespace: string): Promise { * @param namespace - The cache namespace. * @param ttl - Time to live for cache entries. * @param fallbackStore - Optional fallback store if Redis is not used. + * @param options.throwOnErrors - Rejects failed Redis operations instead of resolving them as a + * miss or a no-op delete, for callers that must know an eviction did not happen. The first + * caller's value wins for a shared namespace and TTL. * @returns Cache instance. */ -export const standardCache = (namespace: string, ttl?: number, fallbackStore?: object): Keyv => { +export const standardCache = ( + namespace: string, + ttl?: number, + fallbackStore?: object, + options: { throwOnErrors?: boolean } = {}, +): Keyv => { if (keyvRedisClient && !cacheConfig.FORCED_IN_MEMORY_CACHE_NAMESPACES?.includes(namespace)) { const byTtl = redisCacheMap.get(namespace); const existing = byTtl?.get(ttl); @@ -95,8 +103,9 @@ export const standardCache = (namespace: string, ttl?: number, fallbackStore?: o return existing; } try { - const keyvRedis = new KeyvRedis(keyvRedisClient); - const cache = new Keyv(keyvRedis, { namespace, ttl }); + const { throwOnErrors = false } = options; + const keyvRedis = new KeyvRedis(keyvRedisClient, { throwOnErrors }); + const cache = new Keyv(keyvRedis, { namespace, ttl, throwOnErrors }); keyvRedis.namespace = cacheConfig.REDIS_KEY_PREFIX; keyvRedis.keyPrefixSeparator = cacheConfig.GLOBAL_PREFIX_SEPARATOR; diff --git a/packages/api/src/favorites/pinned.spec.ts b/packages/api/src/favorites/pinned.spec.ts index 26e298db6e..c3a57e27f2 100644 --- a/packages/api/src/favorites/pinned.spec.ts +++ b/packages/api/src/favorites/pinned.spec.ts @@ -11,6 +11,7 @@ import { import { createPinnedOrderHandlers } from './pinned'; jest.mock('@librechat/data-schemas', () => ({ + ...jest.requireActual('@librechat/data-schemas'), logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }, })); diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index 9386ed21b8..ae97949aab 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -4144,6 +4144,9 @@ export enum CacheKeys { export const AUTH_USER_DOC_BY_ID_PREFIX = 'auth-user-doc-byid'; +/** Lifetime of a cached auth user document, and so the longest a stale one can be served. */ +export const AUTH_USER_DOC_CACHE_TTL_MS = 5000; + /** * Enum for violation types, used to identify, log, and cache violations. */ diff --git a/packages/data-schemas/src/methods/user.methods.spec.ts b/packages/data-schemas/src/methods/user.methods.spec.ts index 44df9b4cd4..1ba6b2812d 100644 --- a/packages/data-schemas/src/methods/user.methods.spec.ts +++ b/packages/data-schemas/src/methods/user.methods.spec.ts @@ -1,6 +1,10 @@ import mongoose from 'mongoose'; import { MongoMemoryServer } from 'mongodb-memory-server'; -import { AUTH_USER_DOC_BY_ID_PREFIX, CacheKeys } from 'librechat-data-provider'; +import { + CacheKeys, + AUTH_USER_DOC_BY_ID_PREFIX, + AUTH_USER_DOC_CACHE_TTL_MS, +} from 'librechat-data-provider'; import type * as t from '~/types'; import { createUserMethods, USER_DELETION_FENCE_STALE_MS } from './user'; import balanceSchema from '~/schema/balance'; @@ -480,6 +484,119 @@ describe('User Methods - Database Tests', () => { expect(cache.delete).toHaveBeenCalledWith(indexKey); }); + describe('when auth cache eviction fails', () => { + const cachedKeys = ['auth-cache-key-a', 'auth-cache-key-b']; + + /** Rejects the named operations the way the throwing Redis-backed auth cache does. */ + function makeFailingCache(failing: { indexRead?: boolean; deleteKey?: string }) { + return { + get: jest.fn(async () => { + if (failing.indexRead) { + throw new Error('WRONGTYPE'); + } + return cachedKeys; + }), + set: jest.fn().mockResolvedValue(true), + delete: jest.fn(async (key: string) => { + if (key === failing.deleteKey) { + throw new Error('redis unavailable'); + } + return true; + }), + }; + } + + async function createCachedUser() { + enableAuthUserDocCache(); + const user = await User.create({ + name: 'Credential User', + email: 'credential@example.com', + provider: 'openid', + }); + return user._id?.toString() ?? ''; + } + + test.each<[string, { indexRead?: boolean; deleteKey?: string }]>([ + ['the reverse index read fails', { indexRead: true }], + ['an indexed document delete fails', { deleteKey: 'auth-cache-key-a' }], + ])('waits out the cache TTL at the credential barrier when %s', async (_label, failing) => { + const userId = await createCachedUser(); + const cache = makeFailingCache(failing); + const delay = jest.fn().mockResolvedValue(undefined); + const methodsWithCache = createUserMethods(mongoose, { getCache: () => cache, delay }); + + const updated = await methodsWithCache.updateUser(userId, { + password: 'new-password-hash', + credentialsChangedAt: new Date(), + }); + expect(updated?.credentialsChangedAt).toBeInstanceOf(Date); + expect(delay).not.toHaveBeenCalled(); + + await methodsWithCache.awaitAuthUserDocEviction(userId); + + expect(delay).toHaveBeenCalledTimes(1); + expect(delay.mock.calls[0][0]).toBeGreaterThan(AUTH_USER_DOC_CACHE_TTL_MS); + expect(cache.delete).not.toHaveBeenCalledWith(`${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`); + if (!failing.indexRead) { + expect(cache.delete).toHaveBeenCalledWith('auth-cache-key-b'); + } + }); + + test('passes the barrier at once when only the index delete fails', async () => { + const userId = await createCachedUser(); + const cache = makeFailingCache({ deleteKey: `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}` }); + const delay = jest.fn().mockResolvedValue(undefined); + const methodsWithCache = createUserMethods(mongoose, { getCache: () => cache, delay }); + + await methodsWithCache.awaitAuthUserDocEviction(userId); + + expect(cache.delete).toHaveBeenCalledWith('auth-cache-key-a'); + expect(cache.delete).toHaveBeenCalledWith('auth-cache-key-b'); + expect(delay).not.toHaveBeenCalled(); + }); + + test('passes the barrier at once when a retried eviction succeeds', async () => { + const userId = await createCachedUser(); + const cache = makeFailingCache({ indexRead: true }); + const delay = jest.fn().mockResolvedValue(undefined); + const methodsWithCache = createUserMethods(mongoose, { getCache: () => cache, delay }); + + await methodsWithCache.updateUser(userId, { credentialsChangedAt: new Date() }); + cache.get.mockResolvedValue(cachedKeys); + await methodsWithCache.awaitAuthUserDocEviction(userId); + + expect(cache.delete).toHaveBeenCalledWith('auth-cache-key-a'); + expect(delay).not.toHaveBeenCalled(); + }); + + test('waits at the barrier when the cache can read but not delete', async () => { + const userId = await createCachedUser(); + const delay = jest.fn().mockResolvedValue(undefined); + const methodsWithCache = createUserMethods(mongoose, { + getCache: () => ({ get: jest.fn(), set: jest.fn() }), + delay, + }); + + await methodsWithCache.awaitAuthUserDocEviction(userId); + + expect(delay).toHaveBeenCalledTimes(1); + }); + + test('keeps updates themselves best effort', async () => { + const userId = await createCachedUser(); + const delay = jest.fn().mockResolvedValue(undefined); + const methodsWithCache = createUserMethods(mongoose, { + getCache: () => makeFailingCache({ indexRead: true }), + delay, + }); + + const updated = await methodsWithCache.updateUser(userId, { name: 'Renamed' }); + + expect(updated?.name).toBe('Renamed'); + expect(delay).not.toHaveBeenCalled(); + }); + }); + test('should invalidate cached auth user documents on delete', async () => { enableAuthUserDocCache(); const user = await User.create({ diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts index 07de2ded81..cfa9057a10 100644 --- a/packages/data-schemas/src/methods/user.ts +++ b/packages/data-schemas/src/methods/user.ts @@ -1,14 +1,16 @@ import mongoose, { FilterQuery } from 'mongoose'; import { - AUTH_USER_DOC_BY_ID_PREFIX, + AUTH_USER_DOC_CACHE_TTL_MS, CacheKeys, type RefillIntervalUnit, type StatefulCodeEnvironment, } from 'librechat-data-provider'; import type { IUser, BalanceConfig, CreateUserRequest, UserDeleteResult } from '~/types'; import type { CacheStore } from '~/types'; +import { evictAuthUserDocs } from '~/utils/eviction'; import { escapeRegExp } from '~/utils/string'; import { signPayload } from '~/crypto'; +import logger from '~/config/winston'; /** Default JWT session expiry: 15 minutes in milliseconds */ export const DEFAULT_SESSION_EXPIRY: number = 1000 * 60 * 15; @@ -19,8 +21,15 @@ const MAX_SUBAGENT_ADMISSION_FENCES = 32; interface UserMethodDeps { getCache?: (key: string) => CacheStore | undefined; + /** Resolves after the given milliseconds; tests pass one that need not wait out the cache TTL. */ + delay?: (ms: number) => Promise; } +const wait = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Timers can fire a millisecond early, so the wait outlasts the cache TTL by this much. */ +const AUTH_USER_DOC_EXPIRY_MARGIN_MS = 100; + function isAuthUserDocCacheEnabled(): boolean { return process.env.AUTH_USER_CACHE_MODE === 'on'; } @@ -55,6 +64,7 @@ export function createUserMethods( expectedState?: FilterQuery, options?: { preserveExpiresAt?: boolean }, ) => Promise; + awaitAuthUserDocEviction: (userId: string) => Promise; claimSamlIdentity: ( userId: string, samlId: string, @@ -333,6 +343,24 @@ export function createUserMethods( return updated; } + /** + * The barrier a credential change passes before it is confirmed. A cached document without + * the new credentialsChangedAt keeps pre-change access tokens verifying until it expires, so + * eviction is retried and, when it still cannot remove every document, this resolves only + * after the cache TTL. Callers revoke sessions and passkeys first: during the wait those + * could otherwise mint access tokens issued after the stamp. + */ + async function awaitAuthUserDocEviction(userId: string): Promise { + if (await invalidateAuthUserDocCache(userId)) { + return; + } + logger.warn( + '[awaitAuthUserDocEviction] Cached auth documents were not evicted after a credential change; waiting for them to expire', + { userId, waitMs: AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS }, + ); + await (deps.delay ?? wait)(AUTH_USER_DOC_CACHE_TTL_MS + AUTH_USER_DOC_EXPIRY_MARGIN_MS); + } + /** Atomically updates a SAML user only when the incoming identity can claim the document. */ async function claimSamlIdentity( userId: string, @@ -358,26 +386,20 @@ export function createUserMethods( return updated; } - async function invalidateAuthUserDocCache(userId: string): Promise { + /** Resolves false only when a cached document for the user may still be served. */ + async function invalidateAuthUserDocCache(userId: string): Promise { if (!isAuthUserDocCacheEnabled()) { - return; + return true; } const cache = deps.getCache?.(CacheKeys.AUTH_USER_DOC); - if (!cache?.get || !cache?.delete) { - return; + if (!cache?.get) { + return true; } - try { - const indexKey = `${AUTH_USER_DOC_BY_ID_PREFIX}:${userId}`; - const cachedKeys = await cache.get(indexKey); - if (Array.isArray(cachedKeys)) { - await Promise.all( - cachedKeys.map((key) => (typeof key === 'string' ? cache.delete?.(key) : undefined)), - ); - } - await cache.delete(indexKey); - } catch { - // Cache invalidation must not make a user update fail. + const remove = cache.delete?.bind(cache); + if (!remove) { + return false; } + return evictAuthUserDocs({ get: (key) => cache.get(key), delete: remove }, { userId }); } /** @@ -863,6 +885,7 @@ export function createUserMethods( countUsers, createUser, updateUser, + awaitAuthUserDocEviction, claimSamlIdentity, acceptTerms, searchUsers, diff --git a/packages/data-schemas/src/utils/eviction.spec.ts b/packages/data-schemas/src/utils/eviction.spec.ts new file mode 100644 index 0000000000..4114788ab5 --- /dev/null +++ b/packages/data-schemas/src/utils/eviction.spec.ts @@ -0,0 +1,111 @@ +import { AUTH_USER_DOC_BY_ID_PREFIX } from 'librechat-data-provider'; +import { evictAuthUserDocs } from './eviction'; + +const INDEX_KEY = `${AUTH_USER_DOC_BY_ID_PREFIX}:user-1`; +const OTHER_INDEX_KEY = `${AUTH_USER_DOC_BY_ID_PREFIX}:user-2`; + +/** A Map-backed store that rejects the operations named for a key, as a throwing Redis store does. */ +function makeStore(failures: { get?: string[]; delete?: string[] } = {}) { + const values = new Map([ + [INDEX_KEY, ['doc-a', 'doc-b']], + ['doc-a', { id: 'user-1' }], + ['doc-b', { id: 'user-1' }], + ['doc-c', { id: 'user-1' }], + [OTHER_INDEX_KEY, ['doc-other']], + ['doc-other', { id: 'user-2' }], + ]); + return { + values, + get: jest.fn(async (key: string) => { + if (failures.get?.includes(key)) { + throw new Error(`GET ${key} failed`); + } + return values.get(key); + }), + delete: jest.fn(async (key: string) => { + if (failures.delete?.includes(key)) { + throw new Error(`DEL ${key} failed`); + } + return values.delete(key); + }), + }; +} + +function expectOtherUserCached(store: ReturnType) { + expect(store.values.get(OTHER_INDEX_KEY)).toEqual(['doc-other']); + expect(store.values.get('doc-other')).toEqual({ id: 'user-2' }); +} + +describe('evictAuthUserDocs', () => { + it('lets a retry find a document an earlier failed delete left behind', async () => { + const store = makeStore({ delete: ['doc-a'] }); + await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(false); + + store.delete.mockImplementation(async (key: string) => store.values.delete(key)); + await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(true); + + expect(store.values.has('doc-a')).toBe(false); + expect(store.values.has(INDEX_KEY)).toBe(false); + }); + + it('deletes the indexed and explicit documents and the index', async () => { + const store = makeStore(); + + await expect(evictAuthUserDocs(store, { userId: 'user-1', cacheKey: 'doc-c' })).resolves.toBe( + true, + ); + + for (const key of [INDEX_KEY, 'doc-a', 'doc-b', 'doc-c']) { + expect(store.values.has(key)).toBe(false); + } + expectOtherUserCached(store); + }); + + it('reports a failed index read and keeps the index for a retry', async () => { + const store = makeStore({ get: [INDEX_KEY] }); + + await expect(evictAuthUserDocs(store, { userId: 'user-1', cacheKey: 'doc-c' })).resolves.toBe( + false, + ); + + expect(store.values.has('doc-c')).toBe(false); + expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']); + expect(store.values.has('doc-a')).toBe(true); + expectOtherUserCached(store); + }); + + it.each([ + ['a string', 'doc-a'], + ['a list with a non-string entry', ['doc-a', 42]], + ])('treats a reverse index holding %s as unreadable', async (_label, indexed) => { + const store = makeStore(); + store.values.set(INDEX_KEY, indexed); + + await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(false); + + expect(store.values.get(INDEX_KEY)).toEqual(indexed); + expect(store.values.has('doc-a')).toBe(true); + }); + + it('reports a failed document delete, deletes the others and keeps the index for a retry', async () => { + const store = makeStore({ delete: ['doc-a'] }); + + await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(false); + + expect(store.values.has('doc-a')).toBe(true); + expect(store.values.has('doc-b')).toBe(false); + expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']); + expectOtherUserCached(store); + }); + + it('counts documents as evicted when only the index delete fails', async () => { + const store = makeStore({ delete: [INDEX_KEY] }); + + await expect(evictAuthUserDocs(store, { userId: 'user-1' })).resolves.toBe(true); + + expect(store.values.has('doc-a')).toBe(false); + expect(store.values.has('doc-b')).toBe(false); + expect(store.values.get(INDEX_KEY)).toEqual(['doc-a', 'doc-b']); + expectOtherUserCached(store); + }); +}); diff --git a/packages/data-schemas/src/utils/eviction.ts b/packages/data-schemas/src/utils/eviction.ts new file mode 100644 index 0000000000..f238b38a32 --- /dev/null +++ b/packages/data-schemas/src/utils/eviction.ts @@ -0,0 +1,77 @@ +import { AUTH_USER_DOC_BY_ID_PREFIX } from 'librechat-data-provider'; +import logger from '~/config/winston'; + +/** Store operations eviction needs; a failure is only seen when the store throws it. */ +export interface AuthUserDocEvictionStore { + get: (key: string) => Promise; + delete: (key: string) => Promise; +} + +function isKeyList(value: unknown): value is string[] { + return Array.isArray(value) && value.every((key) => typeof key === 'string'); +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Deletes the cached auth user documents for a user, attempting every delete even when + * another fails. Resolves false when a document may still be served: the reverse index could + * not be read, so its keys are unknown, or a document delete failed. The index is deleted only + * after every document it names is gone, so a retry can still find what an earlier attempt + * left behind. A failed delete of the index alone leaves only the names of deleted keys, so it + * is logged and still counts as evicted. Never throws, so callers keep their own write results. + */ +export async function evictAuthUserDocs( + store: AuthUserDocEvictionStore, + input: { userId?: string; cacheKey?: string }, +): Promise { + const keys = new Set(input.cacheKey ? [input.cacheKey] : []); + const indexKey = input.userId ? `${AUTH_USER_DOC_BY_ID_PREFIX}:${input.userId}` : undefined; + let indexRead = true; + if (indexKey) { + try { + const indexed = await store.get(indexKey); + if (indexed != null && !isKeyList(indexed)) { + throw new Error('Reverse index is not a list of cache keys'); + } + for (const key of indexed ?? []) { + keys.add(key); + } + } catch (error) { + indexRead = false; + logger.warn('[authUserDocCache] Reverse index read failed during eviction', { + userId: input.userId, + error: describeError(error), + }); + } + } + + const results = await Promise.allSettled([...keys].map((key) => store.delete(key))); + let documentsDeleted = true; + for (const result of results) { + if (result.status === 'rejected') { + documentsDeleted = false; + logger.warn('[authUserDocCache] Cached document delete failed during eviction', { + userId: input.userId, + error: describeError(result.reason), + }); + } + } + if (!indexRead || !documentsDeleted) { + return false; + } + + if (indexKey) { + try { + await store.delete(indexKey); + } catch (error) { + logger.warn('[authUserDocCache] Reverse index delete failed during eviction', { + userId: input.userId, + error: describeError(error), + }); + } + } + return true; +} diff --git a/packages/data-schemas/src/utils/index.ts b/packages/data-schemas/src/utils/index.ts index fecdfcc7ed..f5a4c6fd48 100644 --- a/packages/data-schemas/src/utils/index.ts +++ b/packages/data-schemas/src/utils/index.ts @@ -8,5 +8,6 @@ export * from './objectId'; export * from './yaml'; export * from './stripUIResourceMarkers'; export * from './fading'; +export * from './eviction'; export { buildIndexWithRetry, createIndexesWithRetry, isIndexBuildInProgress } from './retry'; export type { IndexBuildOptions } from './retry'; From 7a30d2f08c77ce11f1a694128b6e9bebe040d146 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:01:44 +0200 Subject: [PATCH 02/21] =?UTF-8?q?=F0=9F=A7=AD=20test:=20Pin=20the=20ClickH?= =?UTF-8?q?ouse=20Theme=20to=20Click=20UI=20and=20Route=20Focus=20Through?= =?UTF-8?q?=20the=20Ring=20(#16461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test: Pin the ClickHouse Theme to a Click UI v0.12.0 Snapshot Add clickui.json, the Click UI v0.12.0 tokens the ClickHouse theme cites, and a drift guard that matches every color, radius, font, shadow and motion value to its token, naming both on a mismatch. Correct the citations that did not resolve, set shadow2xs, motionNormal and the light code text from Click UI, and document the dark scrim as a deliberate deviation. Draw the global keyboard focus outline in ring-primary under any theme definition, keeping the default theme's black and white outline and the high-contrast rule unchanged. * test: Anchor the Focus Probe Tab on a Focused Sentinel Tab moves on from the previously focused element after a blur, so it never reached the prepended probe. Focus a sentinel outside the tab order first. * test: Require Three RGB Channels in the Click UI Drift Guard A truncated theme triplet such as '0 138' matched a source whose leading channels agreed. Compare only complete, finite triplets. * fix: Follow the Theme Ring Only When the Theme Names One A theme that leaves rgb-ring-primary to the default resolves it to #595959, which a dark surface carries at about 2.3:1. The provider now marks the root with data-theme-ring when the active mode names its ring, and the global focus outline follows the ring only under that mark; every other theme keeps the default black and white outline. Each e2e mode also gets its own page instead of relying on init-script order. --- client/src/style.css | 13 + .../scenarios/clickhouse-theme-shape.spec.ts | 19 + .../mock/scenarios/focus-outline.spec.ts | 191 +++++++++ .../src/theme/context/ThemeProvider.spec.tsx | 67 +++ .../src/theme/context/ThemeProvider.tsx | 14 +- .../client/src/theme/themes/clickhouse.ts | 27 +- packages/client/src/theme/themes/clickui.json | 146 +++++++ .../client/src/theme/themes/clickui.spec.ts | 389 ++++++++++++++++++ packages/client/src/theme/utils/applyTheme.ts | 8 + 9 files changed, 863 insertions(+), 11 deletions(-) create mode 100644 e2e/specs/mock/scenarios/focus-outline.spec.ts create mode 100644 packages/client/src/theme/themes/clickui.json create mode 100644 packages/client/src/theme/themes/clickui.spec.ts diff --git a/client/src/style.css b/client/src/style.css index 896e176f7e..c5e51201fb 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -2465,11 +2465,20 @@ html[data-input-modality='keyboard'] outline-offset: 2px !important; } +/* Black and white are the default theme's focus outline. A theme that names its + * own `ring-primary` (`data-theme-ring` on the root) draws the outline in it, + * at the same specificity and layer as the rule it recolours, so every utility + * that beat the outline before still does. A theme that leaves the ring to the + * default keeps black and white, and the contrast modes keep their own rule. */ @layer base { :focus-visible { outline: 2px solid #000; outline-offset: 2px; } + + :where(html[data-theme-ring]:not(.high-contrast)) :focus-visible { + outline-color: rgb(var(--ring-primary)); + } } .dark :focus-visible { @@ -2477,6 +2486,10 @@ html[data-input-modality='keyboard'] outline-offset: 2px; } +.dark:where([data-theme-ring]:not(.high-contrast)) :focus-visible { + outline-color: rgb(var(--ring-primary)); +} + .popover-ui { display: flex; max-height: min(var(--popover-available-height, 1700px), 1700px); diff --git a/e2e/specs/mock/scenarios/clickhouse-theme-shape.spec.ts b/e2e/specs/mock/scenarios/clickhouse-theme-shape.spec.ts index c2718b8148..362a63e31f 100644 --- a/e2e/specs/mock/scenarios/clickhouse-theme-shape.spec.ts +++ b/e2e/specs/mock/scenarios/clickhouse-theme-shape.spec.ts @@ -130,6 +130,25 @@ test.describe('ClickHouse theme shape', () => { expect(await probeStyle(page, 'ring-2 ring-ring-primary', 'box-shadow')).toContain(ring); }); + test('code text, the second motion step and the hairline shadow follow Click UI @scenario:clickhouse-code-text-and-motion-follow-click-ui', async ({ + page, + }) => { + await storeClickHouse(page); + + await openMentionMenu(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse'); + const mode = await resolvedMode(page); + + /** `codeblock.lightMode.color.text` and `codeblock.darkMode.color.text`. */ + const code = mode === 'light' ? 'rgb(40, 40, 40)' : 'rgb(255, 255, 255)'; + expect(await probeStyle(page, 'hljs', 'color', 'code')).toBe(code); + /** `transition.duration.smooth`, and `shadow.5` for the lightest shadow step. */ + expect(await probeStyle(page, 'duration-theme-normal', 'transition-duration')).toBe('0.15s'); + expect(await probeStyle(page, 'shadow-2xs', 'box-shadow')).toContain( + 'rgba(0, 0, 0, 0.03) 0px 2px 2px 0px', + ); + }); + test('monospace text under the ClickHouse theme leads with Inconsolata @scenario:clickhouse-mono-font-leads-with-inconsolata', async ({ page, }) => { diff --git a/e2e/specs/mock/scenarios/focus-outline.spec.ts b/e2e/specs/mock/scenarios/focus-outline.spec.ts new file mode 100644 index 0000000000..31c448c7be --- /dev/null +++ b/e2e/specs/mock/scenarios/focus-outline.spec.ts @@ -0,0 +1,191 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse'; +import { NEW_CHAT_PATH } from '../helpers'; + +/** + * The app-wide keyboard focus outline. The default light and dark themes draw it in black and + * white, a theme definition that names its own `ring-primary` draws it in that ring, one that + * leaves the ring to the default keeps black and white, and the contrast modes keep their heavier + * text-colored outline. The probe is a bare button reached with Tab, so nothing but the + * global rule styles its outline. + */ + +type Appearance = 'light' | 'dark' | 'high-contrast-light' | 'high-contrast-dark'; +type Outline = { color: string; style: string; width: string; offset: string }; + +const PROBE = 'focus-outline-probe'; + +const CUSTOM_RING_THEME = { + version: 1, + name: 'e2e-focus-ring', + modes: { + light: { colors: { 'rgb-ring-primary': '10 20 30' } }, + dark: { colors: { 'rgb-ring-primary': '200 210 220' } }, + }, +} as const; + +/** Leaves `rgb-ring-primary` to the default, which resolves to a gray too dim for a dark surface. */ +const RINGLESS_THEME = { + version: 1, + name: 'e2e-ringless', + modes: { + light: { colors: { 'rgb-accent-primary': '10 20 30' } }, + dark: { colors: { 'rgb-accent-primary': '200 210 220' } }, + }, +} as const; + +async function installAppearance(page: Page, appearance: Appearance, definition?: unknown) { + await page.addInitScript( + ([mode, stored]) => { + localStorage.setItem('color-theme', mode as string); + localStorage.removeItem('theme-colors'); + localStorage.removeItem('theme-name'); + if (stored) { + localStorage.setItem('theme-definition', JSON.stringify(stored)); + localStorage.setItem('theme-source', 'definition'); + } else { + localStorage.removeItem('theme-definition'); + localStorage.removeItem('theme-source'); + } + }, + [appearance, definition ?? null] as [string, unknown], + ); +} + +/** + * Tabs onto a bare button and reads the outline it draws. Tab moves on from the focused element, + * so a sentinel that takes script focus but sits outside the tab order anchors the move. + */ +async function keyboardFocusOutline(page: Page): Promise { + await page.evaluate((id) => { + const sentinel = document.createElement('span'); + sentinel.tabIndex = -1; + const probe = document.createElement('button'); + probe.id = id; + probe.textContent = 'Focus probe'; + document.body.prepend(sentinel, probe); + sentinel.focus(); + }, PROBE); + await page.keyboard.press('Tab'); + + const probe = page.locator(`#${PROBE}`); + await expect(probe).toBeFocused(); + expect(await probe.evaluate((node) => node.matches(':focus-visible'))).toBe(true); + + return probe.evaluate((node) => { + const style = getComputedStyle(node); + return { + color: style.outlineColor, + style: style.outlineStyle, + width: style.outlineWidth, + offset: style.outlineOffset, + }; + }); +} + +async function openChat(page: Page, appearance: Appearance, definition?: { name: string }) { + await installAppearance(page, appearance, definition); + await page.goto(NEW_CHAT_PATH, { timeout: 15000 }); + await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({ + timeout: 30000, + }); + const root = page.locator('html'); + if (appearance.startsWith('high-contrast')) { + await expect(root).toHaveClass(/\bhigh-contrast\b/); + } else if (definition) { + await expect(root).toHaveAttribute('data-theme', definition.name); + } else { + await expect(root).not.toHaveAttribute('data-theme'); + } + await expect(root).toHaveClass(appearance.endsWith('dark') ? /\bdark\b/ : /\blight\b/); +} + +const outline = (color: string, width = '2px'): Outline => ({ + color, + style: 'solid', + width, + offset: '2px', +}); + +/** Each tag is written out whole: the runner finds a scenario by its literal tag. */ +const CASES: Array<{ + title: string; + appearance: Appearance; + definition?: { name: string }; + expected: Outline; +}> = [ + { + title: + 'the default light theme keeps its black focus outline @scenario:focus-outline-default-light-unchanged', + appearance: 'light', + expected: outline('rgb(0, 0, 0)'), + }, + { + title: + 'the default dark theme keeps its white focus outline @scenario:focus-outline-default-dark-unchanged', + appearance: 'dark', + expected: outline('rgb(255, 255, 255)'), + }, + { + title: + 'the ClickHouse light theme draws focus in its outline blue @scenario:focus-outline-follows-clickhouse-ring-light', + appearance: 'light', + definition: clickHouseTheme, + expected: outline('rgb(67, 126, 239)'), + }, + { + title: + 'the ClickHouse dark theme draws focus in its brand yellow @scenario:focus-outline-follows-clickhouse-ring-dark', + appearance: 'dark', + definition: clickHouseTheme, + expected: outline('rgb(250, 255, 105)'), + }, + { + title: + 'a dark theme that leaves the ring to the default keeps the white focus outline @scenario:focus-outline-ringless-theme-keeps-default', + appearance: 'dark', + definition: RINGLESS_THEME, + expected: outline('rgb(255, 255, 255)'), + }, + { + title: + 'high contrast light keeps its heavy text-colored focus outline @scenario:focus-outline-high-contrast-light-unchanged', + appearance: 'high-contrast-light', + definition: clickHouseTheme, + expected: outline('rgb(0, 0, 0)', '3px'), + }, + { + title: + 'high contrast dark keeps its heavy text-colored focus outline @scenario:focus-outline-high-contrast-dark-unchanged', + appearance: 'high-contrast-dark', + definition: clickHouseTheme, + expected: outline('rgb(255, 255, 255)', '3px'), + }, +]; + +test.describe('keyboard focus outline', () => { + for (const { title, appearance, definition, expected } of CASES) { + test(title, async ({ page }) => { + await openChat(page, appearance, definition); + + expect(await keyboardFocusOutline(page)).toEqual(expected); + }); + } + + test('a custom theme draws focus in the ring it defines, in both modes @scenario:focus-outline-follows-custom-theme-ring', async ({ + page, + }) => { + const rings: Record<'light' | 'dark', string> = { + light: 'rgb(10, 20, 30)', + dark: 'rgb(200, 210, 220)', + }; + /** One page per mode: a page's init scripts accumulate, and their order is not guaranteed. */ + for (const mode of ['light', 'dark'] as const) { + const modePage = mode === 'light' ? page : await page.context().newPage(); + await openChat(modePage, mode, CUSTOM_RING_THEME); + + expect(await keyboardFocusOutline(modePage)).toEqual(outline(rings[mode])); + } + }); +}); diff --git a/packages/client/src/theme/context/ThemeProvider.spec.tsx b/packages/client/src/theme/context/ThemeProvider.spec.tsx index b7c1e43bb8..288ac43109 100644 --- a/packages/client/src/theme/context/ThemeProvider.spec.tsx +++ b/packages/client/src/theme/context/ThemeProvider.spec.tsx @@ -71,6 +71,7 @@ beforeEach(() => { document.documentElement.removeAttribute('class'); document.documentElement.removeAttribute('style'); document.documentElement.removeAttribute('data-theme'); + document.documentElement.removeAttribute('data-theme-ring'); window.matchMedia = jest.fn(() => matchMedia(false)); }); @@ -1137,4 +1138,70 @@ describe('ThemeProvider', () => { expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark'); expect(matchMediaSpy).toHaveBeenCalled(); }); + describe('the ring mark the global focus outline follows', () => { + it('marks only the modes whose definition names its ring, and clears it on unmount', async () => { + const { unmount } = render( + + + , + ); + + await waitFor(() => { + expect(document.documentElement).toHaveAttribute('data-theme-ring'); + }); + + act(() => screen.getByRole('button', { name: 'Dark' }).click()); + + await waitFor(() => { + expect(document.documentElement).toHaveClass('dark'); + }); + expect(document.documentElement.dataset.theme).toBe('ringed'); + expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + + unmount(); + + expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + }); + + it('marks legacy RGB props only when they carry a ring', async () => { + const { rerender } = render( + + + , + ); + + await waitFor(() => { + expect(document.documentElement).toHaveAttribute('data-theme-ring'); + }); + + rerender( + + + , + ); + + await waitFor(() => { + expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + }); + expect(document.documentElement.dataset.theme).toBe('legacy'); + }); + }); }); diff --git a/packages/client/src/theme/context/ThemeProvider.tsx b/packages/client/src/theme/context/ThemeProvider.tsx index 82467fbe21..2fca707987 100644 --- a/packages/client/src/theme/context/ThemeProvider.tsx +++ b/packages/client/src/theme/context/ThemeProvider.tsx @@ -16,7 +16,11 @@ import { resolveTheme, validateThemeDefinition, } from '../registry'; -import applyTheme, { applyResolvedTheme, themeOwnedProperties } from '../utils/applyTheme'; +import applyTheme, { + applyResolvedTheme, + themeOwnedProperties, + THEME_RING_ATTRIBUTE, +} from '../utils/applyTheme'; import { defaultTheme } from '../themes/default'; import { darkTheme } from '../themes/dark'; import '../highContrast.css'; @@ -48,6 +52,7 @@ type ThemeDOMSnapshot = { properties: Map; colorScheme: { value: string; priority: string }; dataTheme: string | null; + themeRing: boolean; }; type ThemeClassSnapshot = { @@ -282,6 +287,7 @@ const captureThemeDOM = (root: HTMLElement): ThemeDOMSnapshot => ({ priority: root.style.getPropertyPriority('color-scheme'), }, dataTheme: root.getAttribute('data-theme'), + themeRing: root.hasAttribute(THEME_RING_ATTRIBUTE), }); const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => { @@ -308,6 +314,7 @@ const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => } else { root.setAttribute('data-theme', snapshot.dataTheme); } + root.toggleAttribute(THEME_RING_ATTRIBUTE, snapshot.themeRing); }; export function ThemeProvider({ @@ -641,11 +648,16 @@ export function ThemeProvider({ if (!highContrast && legacyThemeRGB) { applyTheme(legacyThemeRGB, root, mode === 'dark' ? darkTheme : defaultTheme); root.dataset.theme = definition.name; + root.toggleAttribute(THEME_RING_ATTRIBUTE, legacyThemeRGB['rgb-ring-primary'] != null); return; } try { applyResolvedTheme(resolveTheme(definition, mode), root); + root.toggleAttribute( + THEME_RING_ATTRIBUTE, + definition.modes[mode]?.colors?.['rgb-ring-primary'] != null, + ); } catch (error) { restoreAppliedTheme(root); console.error('Unable to apply theme definition', error); diff --git a/packages/client/src/theme/themes/clickhouse.ts b/packages/client/src/theme/themes/clickhouse.ts index 28a21a9515..e9819fc62e 100644 --- a/packages/client/src/theme/themes/clickhouse.ts +++ b/packages/client/src/theme/themes/clickhouse.ts @@ -3,12 +3,14 @@ import type { IThemeAppearance, ThemeDefinition, IThemeRGB } from '../types'; /** * ClickHouse reference theme, built from Click UI's design tokens * (github.com/ClickHouse/click-ui, `src/theme/tokens/variables.light.ts` and - * `variables.dark.ts` at 7dad15bb978d03ba63575e1d4abc02b8927ee1cd). + * `variables.dark.ts` at tag v0.12.0, e2b3d213798f4223122581a75ebc8dd91e47fd9f). The tokens it + * cites are pinned in `clickui.json`, and `clickui.spec.ts` fails on drift in either one. * * This is the deliberately different theme that proves the engine repaints the * app from data alone: no component reads it by name, and LibreChat's defaults * are untouched. Each comment names the Click UI token a value comes from; paths - * without a prefix are under `global.color`, `palette.*` is Click UI's ramp. + * without a prefix are under `global.color` (or `click.global.color` for `text.warning` and + * `text.danger`), `palette.*` is Click UI's ramp, and component paths are under `click`. * * Both maps are complete, so nothing falls back to the LibreChat palette. Where * a verbatim Click UI value missed a contrast floor in `clickhouse.spec.ts` or @@ -76,8 +78,8 @@ export const clickHouseLightTheme: IThemeRGB = { 'rgb-surface-destructive': '193 0 0', // #c10000 (palette.danger.600) 'rgb-surface-destructive-hover': '145 0 0', // #910000 (palette.danger.700) 'rgb-surface-chat': '255 255 255', // #ffffff (background.default) - 'rgb-surface-code': '246 247 250', // #f6f7fa (background.muted) - 'rgb-surface-code-body': '246 247 250', // #f6f7fa (background.muted) + 'rgb-surface-code': '246 247 250', // #f6f7fa (codeblock.lightMode.color.background.default) + 'rgb-surface-code-body': '246 247 250', // #f6f7fa (codeblock.lightMode.color.background.default) 'rgb-surface-inverted': '21 21 21', // #151515 (palette.neutral.900) 'rgb-surface-inverted-hover': '50 50 50', // #323232 (palette.neutral.712) 'rgb-text-inverted': '255 255 255', // #ffffff (palette.neutral.0) @@ -121,7 +123,7 @@ export const clickHouseLightTheme: IThemeRGB = { 'rgb-brand-purple': '136 0 204', // #8800cc (palette.violet.600) // Code syntax - 'rgb-syntax-text': '22 21 23', // #161517 (text.default) + 'rgb-syntax-text': '40 40 40', // #282828 (codeblock.lightMode.color.text.default) 'rgb-syntax-comment': '105 110 121', // #696e79 (text.muted) 'rgb-syntax-meta': '83 87 95', // #53575f (palette.slate.700) 'rgb-syntax-builtin': '138 105 0', // #8a6900 (palette.sunrise.700) @@ -190,14 +192,17 @@ export const clickHouseDarkTheme: IThemeRGB = { 'rgb-surface-tertiary': '40 40 40', // #282828 (background.muted) 'rgb-surface-tertiary-alt': '50 50 50', // #323232 (palette.neutral.712) 'rgb-surface-dialog': '31 31 28', // #1f1f1c (background.default) - 'rgb-surface-overlay': '0 0 0', // #000000 (palette.utility black) + /** Not a Click UI value. Its dark scrim, dialog.color.opaqueBackground lch(40.731 0 none), is a + * #606060 gray that lifts the page instead of dimming it, and leaves the dialog surface under the + * 3:1 boundary the scrim gives it; black keeps the dark theme's scrim. */ + 'rgb-surface-overlay': '0 0 0', // #000000 'rgb-surface-submit': '250 255 105', // #faff69 (accent.default) 'rgb-surface-submit-hover': '253 255 163', // #fdffa3 (palette.brand.200) 'rgb-surface-destructive': '255 117 117', // #ff7575 (palette.danger.300) 'rgb-surface-destructive-hover': '255 152 152', // #ff9898 (palette.danger.200) 'rgb-surface-chat': '31 31 28', // #1f1f1c (background.default) - 'rgb-surface-code': '40 40 40', // #282828 (codeblock.darkMode.background.default) - 'rgb-surface-code-body': '40 40 40', // #282828 (codeblock.darkMode.background.default) + 'rgb-surface-code': '40 40 40', // #282828 (codeblock.darkMode.color.background.default) + 'rgb-surface-code-body': '40 40 40', // #282828 (codeblock.darkMode.color.background.default) 'rgb-surface-inverted': '250 255 105', // #faff69 (button.basic.color.primary.background.default) 'rgb-surface-inverted-hover': '252 255 150', // #fcff96 (button.basic.color.primary.background.hover) 'rgb-text-inverted': '31 31 28', // #1f1f1c (button.basic.color.primary.text.default) @@ -241,7 +246,7 @@ export const clickHouseDarkTheme: IThemeRGB = { 'rgb-brand-purple': '204 102 255', // #cc66ff (palette.violet.300) // Code syntax - 'rgb-syntax-text': '255 255 255', // #ffffff (codeblock.darkMode.text.default) + 'rgb-syntax-text': '255 255 255', // #ffffff (codeblock.darkMode.color.text.default) 'rgb-syntax-comment': '179 182 189', // #b3b6bd (text.muted) 'rgb-syntax-meta': '154 158 167', // #9a9ea7 (palette.slate.400) 'rgb-syntax-builtin': '255 195 0', // #ffc300 (chart.default.sunrise) @@ -300,10 +305,12 @@ const clickHouseShape = { '"Inter", "SF Pro Display", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif', monoFontFamily: '"Inconsolata", ui-monospace, SFMono-Regular, Menlo, "Cascadia Mono", "Liberation Mono", Consolas, monospace', + shadow2xs: '0 2px 2px 0 rgb(0 0 0 / 0.03)', // shadow.5 shadowXs: '0 2px 2px 0 rgb(0 0 0 / 0.03)', // shadow.5 shadowSm: '0 2px 2px 0 rgb(0 0 0 / 0.03)', // shadow.5 controlHeight: '2rem', // genericMenu.panel.size.height - motionFast: '100ms', // transition.default + motionFast: '100ms', // transition.duration.medium, the step transition.default runs at + motionNormal: '150ms', // transition.duration.smooth }; const elevation = (alpha: number): string => diff --git a/packages/client/src/theme/themes/clickui.json b/packages/client/src/theme/themes/clickui.json new file mode 100644 index 0000000000..77439130bd --- /dev/null +++ b/packages/client/src/theme/themes/clickui.json @@ -0,0 +1,146 @@ +{ + "source": "https://github.com/ClickHouse/click-ui", + "tag": "v0.12.0", + "commit": "e2b3d213798f4223122581a75ebc8dd91e47fd9f", + "files": { + "light": "src/theme/tokens/variables.light.ts", + "dark": "src/theme/tokens/variables.dark.ts" + }, + "light": { + "border.radii.1": "0.25rem", + "border.radii.2": "0.5rem", + "border.radii.3": "0.75rem", + "border.radii.full": "9999px", + "click.codeblock.lightMode.color.background.default": "#f6f7fa", + "click.codeblock.lightMode.color.text.default": "#282828", + "click.dialog.color.opaqueBackground.default": "lch(6.7738 0 none / 0.75)", + "click.genericMenu.panel.size.height": "2rem", + "click.global.color.text.danger": "#c10000", + "click.global.color.text.warning": "#a33c00", + "global.color.accent.default": "#151515", + "global.color.background.default": "#ffffff", + "global.color.background.muted": "#f6f7fa", + "global.color.background.split": "#f6f7fa", + "global.color.chart.default.blue": "#437eef", + "global.color.chart.default.fuchsia": "#fb32c9", + "global.color.chart.default.teal": "#089b83", + "global.color.chart.default.violet": "#bb33ff", + "global.color.feedback.danger.background": "#ffdddd", + "global.color.feedback.danger.foreground": "#c10000", + "global.color.feedback.info.background": "#e7effd", + "global.color.feedback.neutral.background": "#f6f7fa", + "global.color.feedback.neutral.foreground": "#53575f", + "global.color.feedback.neutral.stroke": "#e6e7e9", + "global.color.feedback.success.background": "#e5ffe8", + "global.color.feedback.success.foreground": "#008a0b", + "global.color.feedback.warning.background": "#ffe2d1", + "global.color.feedback.warning.foreground": "#a33c00", + "global.color.outline.default": "#437eef", + "global.color.stroke.default": "#e6e7e9", + "global.color.stroke.intense": "#b3b6bd", + "global.color.text.default": "#161517", + "global.color.text.link.hover": "#104ec6", + "global.color.text.muted": "#696e79", + "palette.babyblue.600": "#008599", + "palette.danger.200": "#ff9898", + "palette.danger.600": "#c10000", + "palette.danger.700": "#910000", + "palette.fuchsia.700": "#990073", + "palette.info.200": "#a1bef7", + "palette.info.500": "#1d64ec", + "palette.info.600": "#104ec6", + "palette.neutral.0": "#ffffff", + "palette.neutral.712": "#323232", + "palette.neutral.900": "#151515", + "palette.slate.100": "#e6e7e9", + "palette.slate.200": "#cccfd3", + "palette.slate.500": "#808691", + "palette.slate.700": "#53575f", + "palette.slate.900": "#161517", + "palette.success.200": "#99ffa1", + "palette.success.700": "#008a0b", + "palette.success.800": "#006108", + "palette.sunrise.600": "#b28800", + "palette.sunrise.700": "#8a6900", + "palette.violet.600": "#8800cc", + "palette.warning.200": "#ffb88f", + "palette.warning.500": "#f55a00", + "palette.warning.700": "#a33c00", + "shadow.1": "0 4px 6px -1px lch(6.7738 0 none / 0.15), 0 2px 4px -1px lch(6.7738 0 none / 0.15)", + "shadow.5": "0 2px 2px 0 rgba(0, 0, 0, 0.03)", + "transition.duration.medium": "100ms", + "transition.duration.smooth": "150ms", + "typography.font.families.mono": "\"Inconsolata\", Consolas, \"SFMono Regular\", monospace", + "typography.font.families.regular": "\"Inter\", \"SF Pro Display\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Open Sans\", \"Helvetica Neue\", sans-serif;" + }, + "dark": { + "border.radii.1": "0.25rem", + "border.radii.2": "0.5rem", + "border.radii.3": "0.75rem", + "border.radii.full": "9999px", + "click.button.basic.color.primary.background.default": "#faff69", + "click.button.basic.color.primary.background.hover": "rgb(98.627% 100% 58.824%)", + "click.button.basic.color.primary.text.default": "#1f1f1c", + "click.codeblock.darkMode.color.background.default": "#282828", + "click.codeblock.darkMode.color.text.default": "#ffffff", + "click.genericMenu.panel.size.height": "2rem", + "click.global.color.text.danger": "#ffbaba", + "click.global.color.text.warning": "#ffb88f", + "global.color.accent.default": "#faff69", + "global.color.background.default": "#1f1f1c", + "global.color.background.muted": "#282828", + "global.color.background.split": "#282828", + "global.color.chart.default.babyblue": "#00cbeb", + "global.color.chart.default.blue": "#437eef", + "global.color.chart.default.fuchsia": "#fb64d6", + "global.color.chart.default.green": "#33ff44", + "global.color.chart.default.orange": "#ff7729", + "global.color.chart.default.sunrise": "#ffc300", + "global.color.chart.default.teal": "#6df8e1", + "global.color.chart.default.violet": "#bb33ff", + "global.color.feedback.danger.background": "#610000", + "global.color.feedback.danger.foreground": "#ffbaba", + "global.color.feedback.info.background": "#0d3e9b", + "global.color.feedback.info.foreground": "#d0dffb", + "global.color.feedback.neutral.background": "#414141", + "global.color.feedback.neutral.foreground": "#f9f9f9", + "global.color.feedback.neutral.stroke": "#323232", + "global.color.feedback.success.background": "#004206", + "global.color.feedback.success.foreground": "#ccffd0", + "global.color.feedback.warning.background": "#7a2d00", + "global.color.feedback.warning.foreground": "#ffb88f", + "global.color.iconButton.badge.foreground": "#1d1d1d", + "global.color.outline.default": "#faff69", + "global.color.stroke.default": "#323232", + "global.color.stroke.intense": "#414141", + "global.color.text.default": "#ffffff", + "global.color.text.link.default": "#faff69", + "global.color.text.link.hover": "#feffc2", + "global.color.text.muted": "#b3b6bd", + "palette.brand.200": "#fdffa3", + "palette.danger.200": "#ff9898", + "palette.danger.300": "#ff7575", + "palette.danger.700": "#910000", + "palette.info.300": "#6d9bf3", + "palette.info.600": "#104ec6", + "palette.neutral.0": "#ffffff", + "palette.neutral.500": "#808080", + "palette.neutral.700": "#414141", + "palette.neutral.712": "#323232", + "palette.slate.100": "#e6e7e9", + "palette.slate.400": "#9a9ea7", + "palette.slate.900": "#161517", + "palette.success.300": "#66ff73", + "palette.success.500": "#00e513", + "palette.success.800": "#006108", + "palette.violet.300": "#cc66ff", + "palette.warning.300": "#ff9457", + "palette.warning.700": "#a33c00", + "shadow.1": "0 4px 6px -1px rgb(8.2353% 8.2353% 8.2353% / 0.6), 0 2px 4px -1px rgb(8.2353% 8.2353% 8.2353% / 0.6)", + "shadow.5": "0 2px 2px 0 rgba(0, 0, 0, 0.03)", + "transition.duration.medium": "100ms", + "transition.duration.smooth": "150ms", + "typography.font.families.mono": "\"Inconsolata\", Consolas, \"SFMono Regular\", monospace", + "typography.font.families.regular": "\"Inter\", \"SF Pro Display\", -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen, Ubuntu, Cantarell, \"Open Sans\", \"Helvetica Neue\", sans-serif;" + } +} diff --git a/packages/client/src/theme/themes/clickui.spec.ts b/packages/client/src/theme/themes/clickui.spec.ts new file mode 100644 index 0000000000..47bed8cfc8 --- /dev/null +++ b/packages/client/src/theme/themes/clickui.spec.ts @@ -0,0 +1,389 @@ +import type { IThemeAppearance, IThemeRGB, ThemeMode } from '../types'; +import { clickHouseTheme } from './clickhouse'; +import snapshot from './clickui.json'; + +/** + * Drift guard for the ClickHouse theme. `clickui.json` is a snapshot of the Click UI tokens the + * theme cites, copied verbatim from the tag it records; the maps below name the token behind each + * theme value. Editing a theme value, or refreshing the snapshot from a newer Click UI tag, fails + * here with the theme key and the token it no longer matches. + * + * To refresh: check out the new tag, read each token below out of `files` for its mode, write the + * verbatim values, tag and commit into `clickui.json`, then reconcile what this spec reports. + */ + +type Rgba = [number, number, number, number]; +type Snapshot = Record>; + +const tokens: Snapshot = { light: snapshot.light, dark: snapshot.dark }; +const modes: ThemeMode[] = ['light', 'dark']; + +const colorSources: Record>> = { + light: { + 'rgb-text-primary': 'global.color.text.default', + 'rgb-text-secondary': 'palette.slate.700', + 'rgb-text-secondary-alt': 'palette.slate.700', + 'rgb-text-tertiary': 'palette.slate.700', + 'rgb-text-muted': 'global.color.text.muted', + 'rgb-text-warning': 'click.global.color.text.warning', + 'rgb-text-destructive': 'click.global.color.text.danger', + 'rgb-shimmer-base': 'global.color.text.default', + 'rgb-shimmer-dip': 'palette.slate.500', + 'rgb-link': 'palette.info.500', + 'rgb-link-hover': 'global.color.text.link.hover', + 'rgb-link-visited': 'palette.violet.600', + 'rgb-accent-primary': 'global.color.accent.default', + 'rgb-accent-primary-hover': 'palette.neutral.712', + 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-header-primary': 'global.color.background.default', + 'rgb-header-hover': 'global.color.background.muted', + 'rgb-header-button-hover': 'global.color.background.muted', + 'rgb-surface-active': 'palette.slate.100', + 'rgb-surface-active-alt': 'palette.slate.200', + 'rgb-surface-hover': 'palette.slate.100', + 'rgb-surface-hover-alt': 'palette.slate.200', + 'rgb-surface-composer-hover': 'palette.slate.100', + 'rgb-surface-primary': 'global.color.background.default', + 'rgb-chart-widget-surface': 'global.color.background.default', + 'rgb-chart-widget-stroke': 'global.color.stroke.default', + 'rgb-surface-primary-alt': 'global.color.background.split', + 'rgb-surface-primary-contrast': 'palette.slate.100', + 'rgb-surface-secondary': 'global.color.background.muted', + 'rgb-surface-secondary-alt': 'palette.slate.100', + 'rgb-surface-tertiary': 'global.color.background.muted', + 'rgb-surface-tertiary-alt': 'global.color.background.default', + 'rgb-surface-dialog': 'global.color.background.default', + 'rgb-surface-overlay': 'click.dialog.color.opaqueBackground.default', + 'rgb-surface-submit': 'global.color.accent.default', + 'rgb-surface-submit-hover': 'palette.neutral.712', + 'rgb-surface-destructive': 'palette.danger.600', + 'rgb-surface-destructive-hover': 'palette.danger.700', + 'rgb-surface-chat': 'global.color.background.default', + 'rgb-surface-code': 'click.codeblock.lightMode.color.background.default', + 'rgb-surface-code-body': 'click.codeblock.lightMode.color.background.default', + 'rgb-surface-inverted': 'palette.neutral.900', + 'rgb-surface-inverted-hover': 'palette.neutral.712', + 'rgb-text-inverted': 'palette.neutral.0', + 'rgb-surface-fixed': 'palette.neutral.0', + 'rgb-surface-fixed-hover': 'palette.slate.100', + 'rgb-text-fixed': 'palette.slate.900', + 'rgb-border-light': 'global.color.stroke.default', + 'rgb-border-medium': 'global.color.stroke.default', + 'rgb-border-medium-alt': 'global.color.stroke.default', + 'rgb-border-heavy': 'global.color.stroke.intense', + 'rgb-border-xheavy': 'palette.slate.500', + 'rgb-border-destructive': 'palette.danger.600', + 'rgb-border-control': 'palette.slate.500', + 'rgb-status-success': 'palette.success.800', + 'rgb-status-success-subtle': 'global.color.feedback.success.background', + 'rgb-status-success-border': 'palette.success.200', + 'rgb-status-success-strong': 'global.color.feedback.success.foreground', + 'rgb-status-info': 'palette.info.600', + 'rgb-status-info-subtle': 'global.color.feedback.info.background', + 'rgb-status-info-border': 'palette.info.200', + 'rgb-status-info-strong': 'palette.info.600', + 'rgb-status-warning': 'global.color.feedback.warning.foreground', + 'rgb-status-warning-subtle': 'global.color.feedback.warning.background', + 'rgb-status-warning-border': 'palette.warning.200', + 'rgb-status-warning-strong': 'palette.warning.700', + 'rgb-status-error': 'global.color.feedback.danger.foreground', + 'rgb-status-error-subtle': 'global.color.feedback.danger.background', + 'rgb-status-error-border': 'palette.danger.200', + 'rgb-status-error-strong': 'palette.danger.600', + 'rgb-status-neutral': 'global.color.feedback.neutral.foreground', + 'rgb-status-neutral-subtle': 'global.color.feedback.neutral.background', + 'rgb-status-neutral-border': 'global.color.feedback.neutral.stroke', + 'rgb-status-verified': 'palette.info.600', + 'rgb-text-on-status': 'palette.neutral.0', + 'rgb-brand-purple': 'palette.violet.600', + 'rgb-syntax-text': 'click.codeblock.lightMode.color.text.default', + 'rgb-syntax-comment': 'global.color.text.muted', + 'rgb-syntax-meta': 'palette.slate.700', + 'rgb-syntax-builtin': 'palette.sunrise.700', + 'rgb-syntax-keyword': 'palette.info.600', + 'rgb-syntax-string': 'palette.success.800', + 'rgb-syntax-attr': 'palette.fuchsia.700', + 'rgb-syntax-title': 'palette.warning.700', + 'rgb-series-1': 'global.color.chart.default.blue', + 'rgb-series-2': 'palette.warning.500', + 'rgb-series-3': 'palette.success.700', + 'rgb-series-4': 'global.color.chart.default.fuchsia', + 'rgb-series-5': 'palette.sunrise.600', + 'rgb-series-6': 'global.color.chart.default.violet', + 'rgb-series-7': 'palette.babyblue.600', + 'rgb-series-8': 'global.color.chart.default.teal', + 'rgb-switch-unchecked': 'palette.slate.500', + 'rgb-presentation': 'global.color.background.default', + }, + dark: { + 'rgb-text-primary': 'global.color.text.default', + 'rgb-text-secondary': 'global.color.text.muted', + 'rgb-text-secondary-alt': 'global.color.text.muted', + 'rgb-text-tertiary': 'global.color.text.muted', + 'rgb-text-muted': 'global.color.text.muted', + 'rgb-text-warning': 'click.global.color.text.warning', + 'rgb-text-destructive': 'click.global.color.text.danger', + 'rgb-shimmer-base': 'global.color.text.default', + 'rgb-shimmer-dip': 'global.color.text.muted', + 'rgb-link': 'global.color.text.link.default', + 'rgb-link-hover': 'global.color.text.link.hover', + 'rgb-link-visited': 'palette.violet.300', + 'rgb-accent-primary': 'global.color.accent.default', + 'rgb-accent-primary-hover': 'palette.brand.200', + 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-header-primary': 'global.color.background.default', + 'rgb-header-hover': 'global.color.background.muted', + 'rgb-header-button-hover': 'global.color.background.muted', + 'rgb-surface-active': 'palette.neutral.700', + 'rgb-surface-active-alt': 'palette.neutral.712', + 'rgb-surface-hover': 'palette.neutral.712', + 'rgb-surface-hover-alt': 'palette.neutral.700', + 'rgb-surface-composer-hover': 'palette.neutral.712', + 'rgb-surface-primary': 'global.color.background.default', + 'rgb-chart-widget-surface': 'global.color.background.muted', + 'rgb-chart-widget-stroke': 'global.color.stroke.default', + 'rgb-surface-primary-alt': 'global.color.background.split', + 'rgb-surface-primary-contrast': 'palette.neutral.712', + 'rgb-surface-secondary': 'global.color.background.muted', + 'rgb-surface-secondary-alt': 'palette.neutral.712', + 'rgb-surface-tertiary': 'global.color.background.muted', + 'rgb-surface-tertiary-alt': 'palette.neutral.712', + 'rgb-surface-dialog': 'global.color.background.default', + 'rgb-surface-submit': 'global.color.accent.default', + 'rgb-surface-submit-hover': 'palette.brand.200', + 'rgb-surface-destructive': 'palette.danger.300', + 'rgb-surface-destructive-hover': 'palette.danger.200', + 'rgb-surface-chat': 'global.color.background.default', + 'rgb-surface-code': 'click.codeblock.darkMode.color.background.default', + 'rgb-surface-code-body': 'click.codeblock.darkMode.color.background.default', + 'rgb-surface-inverted': 'click.button.basic.color.primary.background.default', + 'rgb-surface-inverted-hover': 'click.button.basic.color.primary.background.hover', + 'rgb-text-inverted': 'click.button.basic.color.primary.text.default', + 'rgb-surface-fixed': 'palette.neutral.0', + 'rgb-surface-fixed-hover': 'palette.slate.100', + 'rgb-text-fixed': 'palette.slate.900', + 'rgb-border-light': 'global.color.stroke.default', + 'rgb-border-medium': 'global.color.stroke.default', + 'rgb-border-medium-alt': 'global.color.stroke.default', + 'rgb-border-heavy': 'global.color.stroke.intense', + 'rgb-border-xheavy': 'palette.neutral.500', + 'rgb-border-destructive': 'palette.danger.300', + 'rgb-border-control': 'palette.neutral.500', + 'rgb-status-success': 'global.color.feedback.success.foreground', + 'rgb-status-success-subtle': 'global.color.feedback.success.background', + 'rgb-status-success-border': 'palette.success.800', + 'rgb-status-success-strong': 'palette.success.500', + 'rgb-status-info': 'global.color.feedback.info.foreground', + 'rgb-status-info-subtle': 'global.color.feedback.info.background', + 'rgb-status-info-border': 'palette.info.600', + 'rgb-status-info-strong': 'palette.info.300', + 'rgb-status-warning': 'global.color.feedback.warning.foreground', + 'rgb-status-warning-subtle': 'global.color.feedback.warning.background', + 'rgb-status-warning-border': 'palette.warning.700', + 'rgb-status-warning-strong': 'palette.warning.300', + 'rgb-status-error': 'global.color.feedback.danger.foreground', + 'rgb-status-error-subtle': 'global.color.feedback.danger.background', + 'rgb-status-error-border': 'palette.danger.700', + 'rgb-status-error-strong': 'palette.danger.300', + 'rgb-status-neutral': 'global.color.feedback.neutral.foreground', + 'rgb-status-neutral-subtle': 'global.color.feedback.neutral.background', + 'rgb-status-neutral-border': 'global.color.feedback.neutral.stroke', + 'rgb-status-verified': 'palette.info.300', + 'rgb-text-on-status': 'global.color.iconButton.badge.foreground', + 'rgb-brand-purple': 'palette.violet.300', + 'rgb-syntax-text': 'click.codeblock.darkMode.color.text.default', + 'rgb-syntax-comment': 'global.color.text.muted', + 'rgb-syntax-meta': 'palette.slate.400', + 'rgb-syntax-builtin': 'global.color.chart.default.sunrise', + 'rgb-syntax-keyword': 'palette.info.300', + 'rgb-syntax-string': 'palette.success.300', + 'rgb-syntax-attr': 'global.color.chart.default.fuchsia', + 'rgb-syntax-title': 'global.color.chart.default.orange', + 'rgb-series-1': 'global.color.chart.default.blue', + 'rgb-series-2': 'global.color.chart.default.orange', + 'rgb-series-3': 'global.color.chart.default.green', + 'rgb-series-4': 'global.color.chart.default.fuchsia', + 'rgb-series-5': 'global.color.chart.default.sunrise', + 'rgb-series-6': 'global.color.chart.default.violet', + 'rgb-series-7': 'global.color.chart.default.babyblue', + 'rgb-series-8': 'global.color.chart.default.teal', + 'rgb-switch-unchecked': 'palette.neutral.500', + 'rgb-presentation': 'global.color.background.default', + }, +}; + +/** Values the theme sets on purpose without a Click UI source, and why. */ +const unsourcedColors: Record>> = { + light: {}, + dark: { + 'rgb-surface-overlay': + 'Click UI dark dialog.color.opaqueBackground is a gray that leaves the dialog under 3:1', + }, +}; + +const appearanceSources: Partial> = { + controlRadius: 'border.radii.1', + radiusSm: 'border.radii.1', + radiusMd: 'border.radii.1', + radiusLg: 'border.radii.1', + surfaceRadius: 'border.radii.2', + radiusXl: 'border.radii.2', + radius2xl: 'border.radii.2', + largeSurfaceRadius: 'border.radii.3', + radius3xl: 'border.radii.3', + roundControlRadius: 'border.radii.full', + fontFamily: 'typography.font.families.regular', + monoFontFamily: 'typography.font.families.mono', + shadow2xs: 'shadow.5', + shadowXs: 'shadow.5', + shadowSm: 'shadow.5', + shadowMd: 'shadow.1', + shadowLg: 'shadow.1', + shadowXl: 'shadow.1', + shadow2xl: 'shadow.1', + elevationSurface: 'shadow.1', + controlHeight: 'click.genericMenu.panel.size.height', + motionFast: 'transition.duration.medium', + motionNormal: 'transition.duration.smooth', +}; + +/** Click UI's gray `lch()` stops, converted through CIE L* to an sRGB channel. Chroma must be zero. */ +function lchGray(lightness: number): number { + const y = lightness > 8 ? ((lightness + 16) / 116) ** 3 : lightness / 903.2962962; + const srgb = y <= 0.0031308 ? 12.92 * y : 1.055 * y ** (1 / 2.4) - 0.055; + return srgb * 255; +} + +function channel(value: string): number { + return value.endsWith('%') ? (parseFloat(value) / 100) * 255 : Number(value); +} + +function parseColor(value: string): Rgba { + const hex = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(value); + if (hex) { + return [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16), 1]; + } + const fn = /^(rgba?|lch)\((.+)\)$/.exec(value.trim()); + if (!fn) { + throw new Error(`Unsupported Click UI color: ${value}`); + } + const [channels, alpha = '1'] = fn[2].split('/').map((part) => part.trim()); + const parts = channels.split(/[\s,]+/).filter(Boolean); + const a = parts.length === 4 ? Number(parts[3]) : Number(alpha); + if (fn[1] !== 'lch') { + return [channel(parts[0]), channel(parts[1]), channel(parts[2]), a]; + } + if (Number(parts[1]) !== 0) { + throw new Error(`Only achromatic lch() is supported: ${value}`); + } + const gray = lchGray(Number(parts[0])); + return [gray, gray, gray, a]; +} + +const formatRgba = ([r, g, b, a]: Rgba) => + `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${Number(a.toFixed(3))})`; + +/** + * Click UI writes derived colors as rounded percentages, so a channel can land between two 8-bit + * values (`98.627%` is 251.5). A theme value within one step of the exact channel is a match. + */ +const sameRgb = (theme: string, source: Rgba) => { + const channels = theme.split(' ').map(Number); + return ( + channels.length === 3 && + channels.every((value, index) => Number.isFinite(value) && Math.abs(value - source[index]) < 1) + ); +}; + +/** Every color function in a shadow list, rewritten to one form so both sides compare. */ +const normalizeShadow = (value: string) => + value + .replace(/(rgba?|lch)\([^)]*\)/g, (color) => formatRgba(parseColor(color))) + .replace(/\s+/g, ' ') + .trim(); + +const firstFamily = (value: string) => value.split(',')[0].trim(); + +/** How a Click UI appearance token compares with the theme value that cites it. */ +function comparable(key: keyof IThemeAppearance, value: string): string { + if (key.startsWith('shadow') || key === 'elevationSurface') { + return normalizeShadow(value); + } + /** Click UI's mono tail names `"SFMono Regular"`, which no platform installs; the theme keeps + * the default theme's metric-matched tail, so only the face it leads with is Click UI's. */ + if (key === 'monoFontFamily') { + return firstFamily(value); + } + return value.replace(/;$/, '').trim(); +} + +describe('ClickHouse theme drift against Click UI', () => { + it('records the Click UI tag and commit the snapshot was taken from', () => { + expect(snapshot.source).toBe('https://github.com/ClickHouse/click-ui'); + expect(snapshot.tag).toMatch(/^v\d+\.\d+\.\d+$/); + expect(snapshot.commit).toMatch(/^[0-9a-f]{40}$/); + }); + + it.each(modes)('names a Click UI source for every %s color, or a reason it has none', (mode) => { + const colors = clickHouseTheme.modes[mode]?.colors ?? {}; + const missing = Object.keys(colors).filter( + (key) => + colorSources[mode][key as keyof IThemeRGB] === undefined && + unsourcedColors[mode][key as keyof IThemeRGB] === undefined, + ); + const stale = [ + ...Object.keys(colorSources[mode]), + ...Object.keys(unsourcedColors[mode]), + ].filter((key) => !(key in colors)); + + expect({ missing, stale }).toEqual({ missing: [], stale: [] }); + }); + + it.each(modes)('matches every sourced %s color to its Click UI token', (mode) => { + const colors = clickHouseTheme.modes[mode]?.colors ?? {}; + const drift = Object.entries(colorSources[mode]).flatMap(([key, token]) => { + const source = tokens[mode][token]; + if (source === undefined) { + return [`${key}: Click UI token ${token} is not in clickui.json`]; + } + const theme = colors[key as keyof IThemeRGB] ?? ''; + return sameRgb(theme, parseColor(source)) + ? [] + : [`${key}: theme ${theme}, Click UI ${token} is ${source}`]; + }); + + expect(drift).toEqual([]); + }); + + it.each(modes)('matches every %s shape, font and motion value to its Click UI token', (mode) => { + const appearance = clickHouseTheme.modes[mode]?.appearance ?? {}; + const unsourced = Object.keys(appearance).filter( + (key) => appearanceSources[key as keyof IThemeAppearance] === undefined, + ); + const drift = Object.entries(appearanceSources).flatMap(([name, token]) => { + const key = name as keyof IThemeAppearance; + const source = tokens[mode][token]; + if (source === undefined) { + return [`${key}: Click UI token ${token} is not in clickui.json`]; + } + const theme = appearance[key]; + if (theme === undefined) { + return [`${key}: the theme does not set it, Click UI ${token} is ${source}`]; + } + return comparable(key, theme) === comparable(key, source) + ? [] + : [`${key}: theme ${theme}, Click UI ${token} is ${source}`]; + }); + + expect({ unsourced, drift }).toEqual({ unsourced: [], drift: [] }); + }); + + it.each(modes)('keeps only the %s tokens the theme cites in the snapshot', (mode) => { + const cited = new Set([ + ...Object.values(colorSources[mode]), + ...Object.values(appearanceSources), + ]); + + expect(Object.keys(tokens[mode]).filter((token) => !cited.has(token))).toEqual([]); + }); +}); diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts index d0978925f9..dacbd0a84a 100644 --- a/packages/client/src/theme/utils/applyTheme.ts +++ b/packages/client/src/theme/utils/applyTheme.ts @@ -104,9 +104,17 @@ function mapAppearance(appearance: IThemeAppearance): Array<[string, string]> { ]); } +/** + * Marks a root whose applied theme names its own `rgb-ring-primary`. The app's global focus + * outline follows the ring only then: a theme that leaves the ring to the default resolves it to a + * mid gray that a dark surface cannot carry at 3:1, so it keeps the default outline instead. + */ +export const THEME_RING_ATTRIBUTE = 'data-theme-ring'; + export function clearAppliedTheme(root: HTMLElement = document.documentElement): void { themeOwnedProperties.forEach((property) => root.style.removeProperty(property)); root.removeAttribute('data-theme'); + root.removeAttribute(THEME_RING_ATTRIBUTE); } export function applyResolvedTheme( From 6ec919e67e29b20a7af9913ed3b4ecd493828378 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:02:46 +0200 Subject: [PATCH 03/21] =?UTF-8?q?=F0=9F=8E=A8=20fix:=20Fall=20Back=20From?= =?UTF-8?q?=20an=20Invalid=20Theme=20in=20librechat.yaml=20Instead=20of=20?= =?UTF-8?q?Exiting=20(#16462)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: Fall Back From an Invalid interface.theme Instead of Exiting A mistake in interface.theme failed the whole librechat.yaml and stopped the server. The loader now checks the theme with the rules the client applies before painting it, drops a theme the client would reject with a warning naming each problem by path, and loads the rest of the config. Unknown appearance tokens only warn, matching the reader. Startup and reload behave the same. The token lists and the validator move to librechat-data-provider so the client registry and the server check against one list. * fix: Reject Unknown Bundled Theme Names at Config Load A misspelled bundled name such as clickhous passed the server and was rejected only in the browser. The bundled names now live in librechat-data-provider; the client's theme map is typed against that list and the loader drops a name outside it with a warning. --- client/src/Providers/DeploymentTheme.tsx | 8 +- .../scenarios/yaml-theme-fallback.spec.ts | 129 +++++ .../src/app/__fixtures__/theme/bad-value.yaml | 13 + .../src/app/__fixtures__/theme/bundled.yaml | 5 + .../src/app/__fixtures__/theme/malformed.yaml | 7 + .../src/app/__fixtures__/theme/spacing.yaml | 11 + .../theme/unknown-appearance.yaml | 12 + .../app/__fixtures__/theme/unknown-name.yaml | 5 + .../app/__fixtures__/theme/unknown-token.yaml | 13 + .../__fixtures__/theme/unrelated-error.yaml | 12 + .../api/src/app/__fixtures__/theme/valid.yaml | 18 + packages/api/src/app/loader.spec.ts | 165 +++++++ packages/api/src/app/loader.ts | 20 + packages/api/src/app/theme.ts | 77 +++ packages/client/src/theme/registry.ts | 332 ++----------- packages/data-provider/src/index.ts | 1 + packages/data-provider/src/theme.ts | 442 ++++++++++++++++++ 17 files changed, 970 insertions(+), 300 deletions(-) create mode 100644 e2e/specs/mock/scenarios/yaml-theme-fallback.spec.ts create mode 100644 packages/api/src/app/__fixtures__/theme/bad-value.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/bundled.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/malformed.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/spacing.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/unknown-appearance.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/unknown-name.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/unknown-token.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/unrelated-error.yaml create mode 100644 packages/api/src/app/__fixtures__/theme/valid.yaml create mode 100644 packages/api/src/app/loader.spec.ts create mode 100644 packages/api/src/app/theme.ts create mode 100644 packages/data-provider/src/theme.ts diff --git a/client/src/Providers/DeploymentTheme.tsx b/client/src/Providers/DeploymentTheme.tsx index fadafaeb2b..d34b310417 100644 --- a/client/src/Providers/DeploymentTheme.tsx +++ b/client/src/Providers/DeploymentTheme.tsx @@ -8,8 +8,8 @@ import { createContext, useLayoutEffect, } from 'react'; -import { QueryKeys } from 'librechat-data-provider'; import { notifyManager, useQueryClient } from '@tanstack/react-query'; +import { QueryKeys, isBundledThemeName } from 'librechat-data-provider'; import { ThemeProvider, clickHouseTheme, @@ -17,15 +17,15 @@ import { fromLegacyTheme, validateThemeDefinition, } from '@librechat/client'; +import type { TInterfaceConfig, BundledThemeName } from 'librechat-data-provider'; import type { IThemeRGB, ThemeDefinition } from '@librechat/client'; -import type { TInterfaceConfig } from 'librechat-data-provider'; import type { ComponentProps } from 'react'; import { getThemeFromEnv } from '~/utils/getThemeFromEnv'; import { useGetStartupConfig } from '~/data-provider'; type DeploymentThemeValue = TInterfaceConfig['theme']; -const bundledThemes: Readonly> = { +const bundledThemes: Readonly> = { librechat: libreChatTheme, clickhouse: clickHouseTheme, }; @@ -41,7 +41,7 @@ export function resolveDeploymentTheme(theme: DeploymentThemeValue): ThemeDefini } if (typeof theme === 'string') { - const definition = Object.hasOwn(bundledThemes, theme) ? bundledThemes[theme] : undefined; + const definition = isBundledThemeName(theme) ? bundledThemes[theme] : undefined; if (!definition) { console.warn(`[DeploymentTheme] Ignoring unknown interface.theme "${theme}"`); } diff --git a/e2e/specs/mock/scenarios/yaml-theme-fallback.spec.ts b/e2e/specs/mock/scenarios/yaml-theme-fallback.spec.ts new file mode 100644 index 0000000000..66c07213b8 --- /dev/null +++ b/e2e/specs/mock/scenarios/yaml-theme-fallback.spec.ts @@ -0,0 +1,129 @@ +import { resolve } from 'node:path'; +import { expect, test } from '@playwright/test'; +import { inOneProject, repoRoot, run } from './lint.helpers'; + +/** + * A mistake in `interface.theme` used to fail the whole librechat.yaml and stop the server. The + * config loader that `/api` wires up now drops only the theme, names each problem by its path, and + * loads everything else. The mock lane serves one shared yaml, so these load their own fixtures + * through that same loader in a child process, the way the server does at startup and on reload. + */ +test.describe.configure({ timeout: 120_000 }); + +const fixtures = resolve(repoRoot, 'packages/api/src/app/__fixtures__/theme'); +const RESULT = '__THEME_SCENARIO_RESULT__'; +/** The logger colours its console output. */ +const ANSI_COLOR = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g'); + +const loadScript = ` +const load = require('./server/services/Config/loadCustomConfig'); +process.exit = (code) => { + console.log('${RESULT}' + JSON.stringify({ exited: code })); + process.reallyExit(0); +}; +load(false, { mode: process.argv[1] }).then( + (config) => { + console.log('${RESULT}' + JSON.stringify({ interface: config && config.interface })); + process.reallyExit(0); + }, + (error) => { + console.log('${RESULT}' + JSON.stringify({ rejected: error.name })); + process.reallyExit(0); + }, +); +`; + +type LoadOutcome = { + interface?: { theme?: unknown; modelSelect?: boolean }; + exited?: number; + rejected?: string; +}; + +function loadFixture(name: string, mode: 'startup' | 'reload' = 'startup') { + process.env.CONFIG_PATH = resolve(fixtures, `${name}.yaml`); + const result = run('node', ['-e', loadScript, mode], { cwd: resolve(repoRoot, 'api') }); + const log = result.output.replace(ANSI_COLOR, ''); + const line = log.split('\n').find((entry) => entry.startsWith(RESULT)); + if (!line) { + throw new Error(`The loader printed no result:\n${log}`); + } + return { outcome: JSON.parse(line.slice(RESULT.length)) as LoadOutcome, log }; +} + +test.describe('interface.theme in librechat.yaml', () => { + test.beforeEach(() => inOneProject()); + test.afterEach(() => { + delete process.env.CONFIG_PATH; + }); + + test('a typo in a theme token leaves the server running on the default theme @scenario:yaml-theme-typo-falls-back', () => { + const { outcome, log } = loadFixture('unknown-token'); + + expect(outcome.exited).toBeUndefined(); + expect(outcome.interface).toEqual({ modelSelect: true }); + expect(log).toContain('the default theme applies instead'); + expect(log).toContain( + 'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token: rgb-surfce-secondary', + ); + expect(log).toContain( + 'interface.theme.modes.light.colors.surface-tertiary: Unknown color token: surface-tertiary', + ); + }); + + test('a bad token value is reported with its path and the theme is dropped @scenario:yaml-theme-bad-value-reported', () => { + const { outcome, log } = loadFixture('bad-value'); + + expect(outcome.exited).toBeUndefined(); + expect(outcome.interface).toEqual({ modelSelect: true }); + expect(log).toContain( + 'interface.theme.modes.dark.colors.rgb-surface-primary: Invalid RGB value for rgb-surface-primary: 300 16 32', + ); + expect(log).toContain( + 'interface.theme.modes.dark.appearance.controlRadius: Invalid appearance value for controlRadius: 4 pixels', + ); + }); + + test('a misspelled bundled theme name falls back with a warning @scenario:yaml-theme-unknown-name-falls-back', () => { + const { outcome, log } = loadFixture('unknown-name'); + + expect(outcome.exited).toBeUndefined(); + expect(outcome.interface).toEqual({ modelSelect: true }); + expect(log).toContain( + 'interface.theme: Unknown bundled theme "clickhous", expected one of: librechat, clickhouse', + ); + expect(loadFixture('bundled').outcome.interface?.theme).toBe('clickhouse'); + }); + + test('a valid inline theme loads exactly as written @scenario:yaml-theme-valid-unchanged', () => { + const { outcome, log } = loadFixture('valid'); + + expect(outcome.interface?.theme).toEqual({ + version: 1, + name: 'acme', + modes: { + light: { + colors: { 'rgb-surface-primary': '240 244 255' }, + appearance: { controlRadius: '0.25rem' }, + }, + dark: { colors: { 'rgb-surface-primary': '12 16 32' } }, + }, + brands: { 'provider-openai': '#10a37f' }, + }); + expect(log).not.toContain('interface.theme'); + }); + + test('a config reload with a broken theme applies the same fallback @scenario:yaml-theme-reload-falls-back', () => { + const { outcome, log } = loadFixture('unknown-token', 'reload'); + + expect(outcome.rejected).toBeUndefined(); + expect(outcome.interface).toEqual({ modelSelect: true }); + expect(log).toContain('interface.theme.modes.light.colors.rgb-surfce-secondary'); + }); + + test('an invalid key outside the theme still stops startup @scenario:yaml-theme-other-errors-still-exit', () => { + const { outcome } = loadFixture('unrelated-error'); + + expect(outcome.exited).toBe(1); + expect(loadFixture('unrelated-error', 'reload').outcome.rejected).toBe('ConfigReloadError'); + }); +}); diff --git a/packages/api/src/app/__fixtures__/theme/bad-value.yaml b/packages/api/src/app/__fixtures__/theme/bad-value.yaml new file mode 100644 index 0000000000..1dd4e4704e --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/bad-value.yaml @@ -0,0 +1,13 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + dark: + colors: + rgb-surface-primary: '300 16 32' + appearance: + controlRadius: 4 pixels diff --git a/packages/api/src/app/__fixtures__/theme/bundled.yaml b/packages/api/src/app/__fixtures__/theme/bundled.yaml new file mode 100644 index 0000000000..7e3a6c8ebb --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/bundled.yaml @@ -0,0 +1,5 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: clickhouse diff --git a/packages/api/src/app/__fixtures__/theme/malformed.yaml b/packages/api/src/app/__fixtures__/theme/malformed.yaml new file mode 100644 index 0000000000..e1ac0b825e --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/malformed.yaml @@ -0,0 +1,7 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + - acme + - clickhouse diff --git a/packages/api/src/app/__fixtures__/theme/spacing.yaml b/packages/api/src/app/__fixtures__/theme/spacing.yaml new file mode 100644 index 0000000000..9f8da1036f --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/spacing.yaml @@ -0,0 +1,11 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + light: + colors: + rgb-surface-primary: '240 244 255' diff --git a/packages/api/src/app/__fixtures__/theme/unknown-appearance.yaml b/packages/api/src/app/__fixtures__/theme/unknown-appearance.yaml new file mode 100644 index 0000000000..690277e45e --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/unknown-appearance.yaml @@ -0,0 +1,12 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + light: + appearance: + controlRadius: 2px + futureSpacing: 3rem diff --git a/packages/api/src/app/__fixtures__/theme/unknown-name.yaml b/packages/api/src/app/__fixtures__/theme/unknown-name.yaml new file mode 100644 index 0000000000..7881ecb482 --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/unknown-name.yaml @@ -0,0 +1,5 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: clickhous diff --git a/packages/api/src/app/__fixtures__/theme/unknown-token.yaml b/packages/api/src/app/__fixtures__/theme/unknown-token.yaml new file mode 100644 index 0000000000..c8cdec00ba --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/unknown-token.yaml @@ -0,0 +1,13 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + light: + colors: + rgb-surface-primary: '240 244 255' + rgb-surfce-secondary: '250 250 250' + surface-tertiary: '245 245 245' diff --git a/packages/api/src/app/__fixtures__/theme/unrelated-error.yaml b/packages/api/src/app/__fixtures__/theme/unrelated-error.yaml new file mode 100644 index 0000000000..353ecee547 --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/unrelated-error.yaml @@ -0,0 +1,12 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + light: + colors: + rgb-surfce-primary: '240 244 255' +notAConfigKey: true diff --git a/packages/api/src/app/__fixtures__/theme/valid.yaml b/packages/api/src/app/__fixtures__/theme/valid.yaml new file mode 100644 index 0000000000..e01463685a --- /dev/null +++ b/packages/api/src/app/__fixtures__/theme/valid.yaml @@ -0,0 +1,18 @@ +version: 1.3.17 +cache: true +interface: + modelSelect: true + theme: + version: 1 + name: acme + modes: + light: + colors: + rgb-surface-primary: '240 244 255' + appearance: + controlRadius: 0.25rem + dark: + colors: + rgb-surface-primary: '12 16 32' + brands: + provider-openai: '#10a37f' diff --git a/packages/api/src/app/loader.spec.ts b/packages/api/src/app/loader.spec.ts new file mode 100644 index 0000000000..d0c523c6f2 --- /dev/null +++ b/packages/api/src/app/loader.spec.ts @@ -0,0 +1,165 @@ +import path from 'path'; +import { logger } from '@librechat/data-schemas'; +import type { TCustomConfig } from 'librechat-data-provider'; +import { createCustomConfigLoader, ConfigReloadError } from './loader'; +import { loadYaml } from '~/utils/yaml'; + +const fixture = (name: string) => path.join(__dirname, '__fixtures__', 'theme', `${name}.yaml`); + +const raw = (name: string) => loadYaml(fixture(name)) as TCustomConfig; + +const createLoader = () => + createCustomConfigLoader({ + loadLocal: loadYaml, + defaultConfigPath: fixture('valid'), + redactConfig: (config: TCustomConfig) => config, + }); + +const warnings = (spy: jest.SpyInstance): string => + spy.mock.calls.map(([message]) => String(message)).join('\n'); + +describe('createCustomConfigLoader interface.theme', () => { + const originalConfigPath = process.env.CONFIG_PATH; + let warn: jest.SpyInstance; + let exit: jest.SpyInstance; + + beforeEach(() => { + warn = jest.spyOn(logger, 'warn'); + jest.spyOn(logger, 'error').mockImplementation(() => logger); + jest.spyOn(logger, 'info').mockImplementation(() => logger); + exit = jest.spyOn(process, 'exit').mockImplementation((code) => { + throw new Error(`process.exit(${code})`); + }); + }); + + afterEach(() => { + jest.restoreAllMocks(); + if (originalConfigPath === undefined) { + delete process.env.CONFIG_PATH; + } else { + process.env.CONFIG_PATH = originalConfigPath; + } + }); + + const load = async (name: string, mode: 'startup' | 'reload' = 'startup') => { + process.env.CONFIG_PATH = fixture(name); + return createLoader()(false, { mode }); + }; + + it('returns a valid theme exactly as written, without warnings', async () => { + const config = await load('valid'); + + expect(config?.interface?.theme).toEqual(raw('valid').interface?.theme); + expect(config?.interface?.modelSelect).toBe(true); + expect(warn).not.toHaveBeenCalled(); + expect(exit).not.toHaveBeenCalled(); + }); + + it('drops a theme naming an unknown color token and keeps the rest of the config', async () => { + const config = await load('unknown-token'); + + expect(exit).not.toHaveBeenCalled(); + expect(config).not.toBeNull(); + expect(config?.interface).not.toHaveProperty('theme'); + expect(config?.interface?.modelSelect).toBe(true); + expect(config?.cache).toBe(true); + expect(warnings(warn)).toContain( + 'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token: rgb-surfce-secondary', + ); + expect(warnings(warn)).toContain( + 'interface.theme.modes.light.colors.surface-tertiary: Unknown color token: surface-tertiary', + ); + expect(warnings(warn)).toContain('the default theme applies instead'); + }); + + it('reports every bad value with its path and drops the theme', async () => { + const config = await load('bad-value'); + + expect(exit).not.toHaveBeenCalled(); + expect(config?.interface).not.toHaveProperty('theme'); + const logged = warnings(warn); + expect(logged).toContain( + 'interface.theme.modes.dark.colors.rgb-surface-primary: Invalid RGB value for rgb-surface-primary: 300 16 32', + ); + expect(logged).toContain( + 'interface.theme.modes.dark.appearance.controlRadius: Invalid appearance value for controlRadius: 4 pixels', + ); + }); + + it('drops a theme that is neither a name nor a definition', async () => { + const config = await load('malformed'); + + expect(exit).not.toHaveBeenCalled(); + expect(config?.interface).not.toHaveProperty('theme'); + expect(config?.interface?.modelSelect).toBe(true); + expect(warnings(warn)).toContain( + 'interface.theme: Expected a bundled theme name or an inline theme definition', + ); + }); + + it('drops a value the client reads but the config schema rejects, citing the schema path', async () => { + const config = await load('spacing'); + + expect(exit).not.toHaveBeenCalled(); + expect(config?.interface).not.toHaveProperty('theme'); + expect(warnings(warn)).toContain('interface.theme.modes.light.colors.rgb-surface-primary:'); + }); + + it('drops a bundled theme name that does not exist', async () => { + const config = await load('unknown-name'); + + expect(exit).not.toHaveBeenCalled(); + expect(config?.interface).not.toHaveProperty('theme'); + expect(config?.interface?.modelSelect).toBe(true); + expect(warnings(warn)).toContain( + 'interface.theme: Unknown bundled theme "clickhous", expected one of: librechat, clickhouse', + ); + }); + + it('keeps a bundled theme name', async () => { + const config = await load('bundled'); + + expect(config?.interface?.theme).toBe('clickhouse'); + expect(warn).not.toHaveBeenCalled(); + }); + + it('keeps a theme whose only problem is an appearance token this version ignores', async () => { + const config = await load('unknown-appearance'); + + expect(config?.interface?.theme).toEqual(raw('unknown-appearance').interface?.theme); + expect(warnings(warn)).toContain( + 'interface.theme.modes.light.appearance.futureSpacing: Unknown light appearance token ignored: futureSpacing', + ); + expect(warnings(warn)).not.toContain('the default theme applies instead'); + }); + + it('still exits at startup when something other than the theme is invalid', async () => { + await expect(load('unrelated-error')).rejects.toThrow('process.exit(1)'); + expect(exit).toHaveBeenCalledWith(1); + expect(warnings(warn)).toContain('interface.theme.modes.light.colors.rgb-surfce-primary'); + }); + + describe('reload mode', () => { + it('applies the same fallback instead of rejecting the reload', async () => { + const config = await load('unknown-token', 'reload'); + + expect(config?.interface).not.toHaveProperty('theme'); + expect(config?.interface?.modelSelect).toBe(true); + expect(warnings(warn)).toContain( + 'interface.theme.modes.light.colors.rgb-surfce-secondary: Unknown color token', + ); + }); + + it('returns a valid theme unchanged', async () => { + const config = await load('valid', 'reload'); + + expect(config?.interface?.theme).toEqual(raw('valid').interface?.theme); + expect(warn).not.toHaveBeenCalled(); + }); + + it('still rejects a reload whose other keys are invalid', async () => { + await expect(load('unrelated-error', 'reload')).rejects.toBeInstanceOf(ConfigReloadError); + expect(exit).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/api/src/app/loader.ts b/packages/api/src/app/loader.ts index 6365450c4e..25cdad6cdc 100644 --- a/packages/api/src/app/loader.ts +++ b/packages/api/src/app/loader.ts @@ -14,6 +14,7 @@ import { } from 'librechat-data-provider'; import type { TCustomConfig, TEndpoint } from 'librechat-data-provider'; import type { ZodIssue } from 'zod'; +import { checkConfigTheme } from './theme'; type CustomParams = NonNullable; type CustomParamDefinition = NonNullable[number]; @@ -154,6 +155,21 @@ function isRemoteConfigPath(configPath: string): boolean { return /^https?:\/\//.test(configPath); } +function reportThemeCheck(configPath: string, errors: string[], warnings: string[]): void { + if (errors.length > 0) { + logger.warn( + `Ignoring interface.theme in ${configPath}; the default theme applies instead:\n` + + errors.map((error) => `- ${error}`).join('\n'), + ); + } + if (warnings.length > 0) { + logger.warn( + `interface.theme in ${configPath} names tokens this version ignores:\n` + + warnings.map((warning) => `- ${warning}`).join('\n'), + ); + } +} + /** Creates one process-local custom-config reader. */ export function createCustomConfigLoader({ defaultConfigPath, @@ -242,6 +258,10 @@ export function createCustomConfigLoader({ } } + const themeCheck = checkConfigTheme(loadedConfig); + loadedConfig = themeCheck.config; + reportThemeCheck(configPath, themeCheck.errors, themeCheck.warnings); + setMaxSubagents(getConfiguredMaxSubagents(loadedConfig)); const result = configSchema.strict().safeParse(loadedConfig); if ( diff --git a/packages/api/src/app/theme.ts b/packages/api/src/app/theme.ts new file mode 100644 index 0000000000..f604e99078 --- /dev/null +++ b/packages/api/src/app/theme.ts @@ -0,0 +1,77 @@ +import { + bundledThemeNames, + collectThemeIssues, + isBundledThemeName, + isPlainThemeRecord, + deploymentThemeSchema, + collectThemeWarningIssues, +} from 'librechat-data-provider'; +import type { ThemeIssue } from 'librechat-data-provider'; + +const THEME_PATH = ['interface', 'theme']; + +export interface ConfigThemeCheck { + /** The config to validate and return: the input itself unless the theme had to be dropped. */ + config: unknown; + /** Why the theme was dropped, one `path: reason` line per problem. */ + errors: string[]; + /** Tokens the client will ignore while still applying the rest of the theme. */ + warnings: string[]; +} + +const formatIssue = ({ path, message }: ThemeIssue): string => + `${[...THEME_PATH, ...path].join('.')}: ${message}`; + +function collectErrors(theme: unknown): ThemeIssue[] { + if (typeof theme !== 'string' && !isPlainThemeRecord(theme)) { + return [{ path: [], message: 'Expected a bundled theme name or an inline theme definition' }]; + } + if (typeof theme === 'string') { + return isBundledThemeName(theme) + ? [] + : [ + { + path: [], + message: `Unknown bundled theme "${theme}", expected one of: ${bundledThemeNames.join(', ')}`, + }, + ]; + } + const issues = collectThemeIssues(theme); + if (issues.length > 0) { + return issues; + } + const result = deploymentThemeSchema.safeParse(theme); + if (result.success) { + return []; + } + return result.error.errors.map(({ path, message }) => ({ + path: path.map(String), + message, + })); +} + +/** + * Checks `interface.theme` with the rules the client applies before painting it. A theme the + * client would reject is removed, so the deployment falls back to the default theme and the rest + * of the config still loads; unknown appearance tokens, which the client drops on its own, only + * warn. A config without a theme, or with a valid one, is returned as the same object. + */ +export function checkConfigTheme(config: unknown): ConfigThemeCheck { + const unchanged: ConfigThemeCheck = { config, errors: [], warnings: [] }; + if (!isPlainThemeRecord(config) || !isPlainThemeRecord(config.interface)) { + return unchanged; + } + const interfaceConfig = config.interface; + if (!('theme' in interfaceConfig) || interfaceConfig.theme === undefined) { + return unchanged; + } + + const theme = interfaceConfig.theme; + const errors = collectErrors(theme).map(formatIssue); + if (errors.length === 0) { + return { config, errors, warnings: collectThemeWarningIssues(theme).map(formatIssue) }; + } + + const { theme: _dropped, ...rest } = interfaceConfig; + return { config: { ...config, interface: rest }, errors, warnings: [] }; +} diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.ts index 3c8fac068e..5a45609723 100644 --- a/packages/client/src/theme/registry.ts +++ b/packages/client/src/theme/registry.ts @@ -1,3 +1,17 @@ +import { + THEME_VERSION, + isThemeRGB, + collectThemeIssues, + isThemeAppearanceToken, + collectThemeWarningIssues, + themeColorTokens as sharedColorTokens, + themeBrandTokens as sharedBrandTokens, +} from 'librechat-data-provider'; +import type { + ThemeColorToken, + ThemeBrandToken, + ThemeAppearanceToken, +} from 'librechat-data-provider'; import type { IThemeAppearance, IThemeBrands, @@ -11,7 +25,8 @@ import type { import { highContrastDarkTheme, highContrastLightTheme } from './themes/highContrast'; import { defaultTheme } from './themes/default'; import { darkTheme } from './themes/dark'; -export const THEME_VERSION = 1 as const; + +export { THEME_VERSION }; /** * Compile-time guard: the categorical series scale is declared across three @@ -28,9 +43,21 @@ export type SeriesTokensAreDeclared = [ Assert>, ]; -export const themeColorTokens: readonly (keyof IThemeRGB)[] = Object.freeze( - Object.keys(defaultTheme) as Array, -); +type SameKeys = [A] extends [B] + ? [B] extends [A] + ? true + : false + : false; + +/** The token lists live in `librechat-data-provider` so the server validates against the same + * set; these fail the build when the client types drift from them. */ +export type SharedTokensMatchTypes = [ + Assert>, + Assert>, + Assert>, +]; + +export const themeColorTokens: readonly (keyof IThemeRGB)[] = sharedColorTokens; /** * What the verified mark is measured against: the fill it wore before it had a @@ -120,15 +147,7 @@ export const defaultAppearance: IThemeAppearance = Object.freeze({ motionNormal: '200ms', }); -export const themeBrandTokens: readonly (keyof IThemeBrands)[] = Object.freeze([ - 'provider-openai', - 'provider-openai-gpt4', - 'provider-openai-reasoning', - 'provider-anthropic', - 'provider-azure', - 'provider-bedrock', - 'provider-foreground', -]); +export const themeBrandTokens: readonly (keyof IThemeBrands)[] = sharedBrandTokens; export const defaultBrands: IThemeBrands = Object.freeze({ 'provider-openai': '#19C37D', @@ -195,295 +214,16 @@ export const highContrastTheme: ThemeDefinition = Object.freeze({ }, }); -const rgbPattern = /^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})$/; -const cssLengthPattern = /^(0|\d*\.?\d+(px|rem|em))$/; -const cssLengthDifferencePattern = - /^calc\(\s*\d*\.?\d+(px|rem|em)\s+[-+]\s+\d*\.?\d+(px|rem|em)\s*\)$/; -const cssDurationPattern = /^\d*\.?\d+(ms|s)$/; -const hexColorPattern = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; -const shadowLengthPattern = /^(-?(0|\d*\.?\d+[a-z]+)|(calc|min|max|clamp)\(.*\))$/i; -const shadowColorPattern = /^(#[0-9a-f]{3,8}|[a-z]+|[a-z-]+\(.*\))$/i; /** Tailwind composes `--tw-shadow` into one list with the ring layers, where `none` is invalid. */ const disabledShadow = '0 0 #0000'; -function isLinearGradient(value: string): boolean { - if (!value.startsWith('linear-gradient(') || /url\s*\(|image-set/i.test(value)) { - return false; - } - let depth = 0; - for (let i = 0; i < value.length; i++) { - const char = value[i]; - if (char === '(') { - depth += 1; - } else if (char === ')') { - depth -= 1; - if (depth === 0) { - return i === value.length - 1; - } - if (depth < 0) { - return false; - } - } - } - return false; -} - -const isRGB = (value: unknown): value is string => { - if (typeof value !== 'string') { - return false; - } - const match = value.match(rgbPattern); - return match !== null && match.slice(1).every((channel) => Number(channel) <= 255); -}; - -/** The bare form, or one `calc()` of two unit-bearing lengths (a bare `0` is a number there): - * the small radius defaults keep a px offset. */ -const isLength = (value: unknown): value is string => - typeof value === 'string' && - (cssLengthPattern.test(value) || cssLengthDifferencePattern.test(value)); -const isFontFamily = (value: unknown): value is string => - typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value); -/** Splits on `separator` outside parentheses, so `rgb(0, 0, 0)` stays one part. Empty parts are - * kept, so a stray comma stays visible to the caller. */ -function splitTopLevel(value: string, separator: RegExp): string[] { - const parts: string[] = []; - let depth = 0; - let current = ''; - for (const char of value) { - if (char === '(') { - depth += 1; - } else if (char === ')') { - depth -= 1; - } - if (depth === 0 && separator.test(char)) { - parts.push(current); - current = ''; - continue; - } - current += char; - } - parts.push(current); - return parts.map((part) => part.trim()); -} - -/** A named color is indistinguishable from any other word without the browser's color parser. */ -const isShadowColor = (token: string): boolean => - globalThis.CSS?.supports?.('color', token) ?? shadowColorPattern.test(token); - -/** One layer: two to four lengths, optionally `inset` and one color, per the box-shadow grammar. */ -function isShadowLayer(layer: string): boolean { - const tokens = splitTopLevel(layer, /\s/).filter((token) => token.length > 0); - const lengths = tokens.filter((token) => shadowLengthPattern.test(token)).length; - const insets = tokens.filter((token) => token.toLowerCase() === 'inset').length; - const colors = tokens.filter( - (token) => !shadowLengthPattern.test(token) && token.toLowerCase() !== 'inset', - ); - return ( - lengths >= 2 && lengths <= 4 && insets <= 1 && colors.length <= 1 && colors.every(isShadowColor) - ); -} - -/** - * A shadow must be concrete: a browser defers its check of any value holding `var()`, `env()` or - * `attr()` until substitution, so such a value could never be validated before it reaches the - * ring layers. - */ -const isShadow = (value: unknown): value is string => { - if (typeof value !== 'string' || /[;{}]|url\s*\(|(var|env|attr)\s*\(/i.test(value)) { - return false; - } - if (value.trim().toLowerCase() === 'none') { - return true; - } - const layers = splitTopLevel(value, /,/); - if (layers.some((layer) => layer.length === 0) || !layers.every(isShadowLayer)) { - return false; - } - return globalThis.CSS?.supports?.('box-shadow', value) ?? true; -}; -const isDuration = (value: unknown): value is string => - typeof value === 'string' && cssDurationPattern.test(value); - -const isPlainRecord = (value: unknown): value is Record => { - if (typeof value !== 'object' || value === null || Array.isArray(value)) { - return false; - } - try { - const prototype = Object.getPrototypeOf(value); - return prototype === null || prototype.constructor?.name === 'Object'; - } catch { - return false; - } -}; - -const appearanceValidators: Record boolean> = { - controlRadius: isLength, - roundControlRadius: isLength, - surfaceRadius: isLength, - largeSurfaceRadius: isLength, - radiusSm: isLength, - radiusMd: isLength, - radiusLg: isLength, - radiusXl: isLength, - radius2xl: isLength, - radius3xl: isLength, - controlHeight: isLength, - spaceCompact: isLength, - spaceNormal: isLength, - fontFamily: isFontFamily, - monoFontFamily: isFontFamily, - /** Released themes may hold `var()` here, so this role keeps its original, looser check. */ - elevationSurface: (value) => - typeof value === 'string' && value.trim().length > 0 && !/[;{}]|url\s*\(/i.test(value), - shadow2xs: isShadow, - shadowXs: isShadow, - shadowSm: isShadow, - shadowMd: isShadow, - shadowLg: isShadow, - shadowXl: isShadow, - shadow2xl: isShadow, - motionFast: isDuration, - motionNormal: isDuration, -}; - -const isAppearanceKey = (key: string): key is keyof IThemeAppearance => - Object.prototype.hasOwnProperty.call(appearanceValidators, key); - -/** - * A token added after this reader shipped is ignored rather than rejected, so a newer definition - * degrades to the defaults for what this version cannot paint instead of losing every value it - * can. It never reaches the DOM, but it must still look like a token: a camelCase name and a - * plain CSS value, never a declaration or rule break. - */ -const isFutureAppearance = (key: string, value: unknown): boolean => - /^[a-z][a-zA-Z0-9]*$/.test(key) && typeof value === 'string' && !/[;{}<>]|url\s*\(/i.test(value); - /** The appearance tokens this reader does not know, which `resolveTheme` leaves out. */ export function collectThemeWarnings(theme: ThemeDefinition): string[] { - if (!isPlainRecord(theme) || !isPlainRecord(theme.modes)) { - return []; - } - return (['light', 'dark'] as const).flatMap((mode) => { - const appearance: unknown = isPlainRecord(theme.modes[mode]) - ? theme.modes[mode]?.appearance - : undefined; - if (!isPlainRecord(appearance)) { - return []; - } - return Object.keys(appearance) - .filter((key) => !isAppearanceKey(key)) - .map((key) => `Unknown ${mode} appearance token ignored: ${key}`); - }); -} - -/** 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}`] : []; - }); + return collectThemeWarningIssues(theme).map(({ message }) => message); } export function validateThemeDefinition(theme: ThemeDefinition): string[] { - const errors: string[] = []; - - if (!isPlainRecord(theme)) { - return ['Theme definition must be an object']; - } - - Object.keys(theme).forEach((key) => { - if (key !== 'version' && key !== 'name' && key !== 'modes' && key !== 'brands') { - errors.push(`Unknown theme field: ${key}`); - } - }); - - if (theme.version !== THEME_VERSION) { - errors.push(`Unsupported theme version: ${theme.version}`); - } - if (typeof theme.name !== 'string' || !theme.name.trim()) { - errors.push('Theme name is required'); - } - if (!isPlainRecord(theme.modes)) { - errors.push('Theme modes must be an object'); - return errors; - } - - Object.keys(theme.modes).forEach((mode) => { - if (mode !== 'light' && mode !== 'dark') { - errors.push(`Unknown theme mode: ${mode}`); - } - }); - - (['light', 'dark'] as const).forEach((mode) => { - const definition = theme.modes[mode]; - if (definition === undefined) { - return; - } - - if (!isPlainRecord(definition)) { - errors.push(`Theme mode ${mode} must be an object`); - return; - } - - Object.keys(definition).forEach((key) => { - if (key !== 'colors' && key !== 'appearance' && key !== 'brands') { - errors.push(`Unknown ${mode} theme field: ${key}`); - } - }); - - if (definition.colors !== undefined && !isPlainRecord(definition.colors)) { - errors.push(`Theme colors for ${mode} must be an object`); - } else { - Object.entries(definition.colors ?? {}).forEach(([key, value]) => { - if (!themeColorTokens.includes(key as keyof IThemeRGB)) { - errors.push(`Unknown color token: ${key}`); - return; - } - if (value !== undefined && !isRGB(value)) { - errors.push(`Invalid RGB value for ${key}: ${value}`); - } - }); - } - - if (definition.appearance !== undefined && !isPlainRecord(definition.appearance)) { - errors.push(`Theme appearance for ${mode} must be an object`); - } else { - Object.entries(definition.appearance ?? {}).forEach(([key, value]) => { - const isKnown = isAppearanceKey(key); - const isValid = isKnown ? appearanceValidators[key](value) : isFutureAppearance(key, value); - if (value !== undefined && !isValid) { - errors.push(`Invalid appearance value for ${key}: ${value}`); - } - }); - } - - 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 { - errors.push(...collectBrandErrors(theme.brands)); - } - - return errors; + return collectThemeIssues(theme).map(({ message }) => message); } /** @@ -503,7 +243,7 @@ function definedEntries(values?: Partial): Partial { function knownAppearance(appearance?: Partial): Partial { return Object.fromEntries( - Object.entries(definedEntries(appearance)).filter(([key]) => isAppearanceKey(key)), + Object.entries(definedEntries(appearance)).filter(([key]) => isThemeAppearanceToken(key)), ); } @@ -679,7 +419,7 @@ export function fromLegacyTheme(colors: IThemeRGB, name = 'custom'): ThemeDefini const legacyName = name.trim() || 'custom'; const sanitizedColors = themeColorTokens.reduce((result, token) => { const value = colors[token]; - if (isRGB(value)) { + if (isThemeRGB(value)) { result[token] = value; } return result; diff --git a/packages/data-provider/src/index.ts b/packages/data-provider/src/index.ts index 9987174975..c480ad92b7 100644 --- a/packages/data-provider/src/index.ts +++ b/packages/data-provider/src/index.ts @@ -4,6 +4,7 @@ export * from './bedrock'; export * from './balance'; export * from './config'; export * from './footer'; +export * from './theme'; export * from './langchain'; export * from './filters'; export * from './file-config'; diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.ts new file mode 100644 index 0000000000..e1b321dea5 --- /dev/null +++ b/packages/data-provider/src/theme.ts @@ -0,0 +1,442 @@ +/** + * The theme token contract shared by the client registry, which paints a definition, and the + * server, which checks `interface.theme` when librechat.yaml loads. Both read these lists, so a + * token added here is accepted everywhere at once. + */ +export const THEME_VERSION = 1 as const; + +/** The names `interface.theme` may give instead of an inline definition. */ +export const bundledThemeNames = Object.freeze(['librechat', 'clickhouse'] as const); + +export type BundledThemeName = (typeof bundledThemeNames)[number]; + +export const isBundledThemeName = (value: string): value is BundledThemeName => + (bundledThemeNames as readonly string[]).includes(value); + +export const themeColorTokens = Object.freeze([ + 'rgb-text-primary', + 'rgb-text-secondary', + 'rgb-text-secondary-alt', + 'rgb-text-tertiary', + 'rgb-text-muted', + 'rgb-text-warning', + 'rgb-text-destructive', + 'rgb-shimmer-base', + 'rgb-shimmer-dip', + 'rgb-link', + 'rgb-link-hover', + 'rgb-link-visited', + 'rgb-accent-primary', + 'rgb-accent-primary-hover', + 'rgb-ring-primary', + 'rgb-header-primary', + 'rgb-header-hover', + 'rgb-header-button-hover', + 'rgb-surface-active', + 'rgb-surface-active-alt', + 'rgb-surface-hover', + 'rgb-surface-hover-alt', + 'rgb-surface-composer-hover', + 'rgb-surface-primary', + 'rgb-chart-widget-surface', + 'rgb-chart-widget-stroke', + '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-overlay', + 'rgb-surface-submit', + 'rgb-surface-submit-hover', + 'rgb-surface-destructive', + 'rgb-surface-destructive-hover', + 'rgb-surface-chat', + 'rgb-surface-code', + 'rgb-surface-code-body', + 'rgb-surface-inverted', + 'rgb-surface-inverted-hover', + 'rgb-text-inverted', + 'rgb-surface-fixed', + 'rgb-surface-fixed-hover', + 'rgb-text-fixed', + 'rgb-border-light', + 'rgb-border-medium', + 'rgb-border-medium-alt', + 'rgb-border-heavy', + 'rgb-border-xheavy', + 'rgb-border-destructive', + 'rgb-border-control', + 'rgb-status-success', + 'rgb-status-success-subtle', + 'rgb-status-success-border', + 'rgb-status-success-strong', + 'rgb-status-info', + 'rgb-status-info-subtle', + 'rgb-status-info-border', + 'rgb-status-info-strong', + 'rgb-status-warning', + 'rgb-status-warning-subtle', + 'rgb-status-warning-border', + 'rgb-status-warning-strong', + 'rgb-status-error', + 'rgb-status-error-subtle', + 'rgb-status-error-border', + 'rgb-status-error-strong', + 'rgb-status-neutral', + 'rgb-status-neutral-subtle', + 'rgb-status-neutral-border', + 'rgb-status-verified', + 'rgb-text-on-status', + 'rgb-brand-purple', + 'rgb-syntax-text', + 'rgb-syntax-comment', + 'rgb-syntax-meta', + 'rgb-syntax-builtin', + 'rgb-syntax-keyword', + 'rgb-syntax-string', + 'rgb-syntax-attr', + 'rgb-syntax-title', + 'rgb-series-1', + 'rgb-series-2', + 'rgb-series-3', + 'rgb-series-4', + 'rgb-series-5', + 'rgb-series-6', + 'rgb-series-7', + 'rgb-series-8', + 'rgb-switch-unchecked', + 'rgb-presentation', +] as const); + +export type ThemeColorToken = (typeof themeColorTokens)[number]; + +export const themeBrandTokens = Object.freeze([ + 'provider-openai', + 'provider-openai-gpt4', + 'provider-openai-reasoning', + 'provider-anthropic', + 'provider-azure', + 'provider-bedrock', + 'provider-foreground', +] as const); + +export type ThemeBrandToken = (typeof themeBrandTokens)[number]; + +/** One problem in a theme definition: where it is, relative to the definition, and what it is. */ +export interface ThemeIssue { + path: string[]; + message: string; +} + +const rgbPattern = /^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})$/; +const cssLengthPattern = /^(0|\d*\.?\d+(px|rem|em))$/; +const cssLengthDifferencePattern = + /^calc\(\s*\d*\.?\d+(px|rem|em)\s+[-+]\s+\d*\.?\d+(px|rem|em)\s*\)$/; +const cssDurationPattern = /^\d*\.?\d+(ms|s)$/; +const hexColorPattern = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; +const shadowLengthPattern = /^(-?(0|\d*\.?\d+[a-z]+)|(calc|min|max|clamp)\(.*\))$/i; +const shadowColorPattern = /^(#[0-9a-f]{3,8}|[a-z]+|[a-z-]+\(.*\))$/i; + +function isLinearGradient(value: string): boolean { + if (!value.startsWith('linear-gradient(') || /url\s*\(|image-set/i.test(value)) { + return false; + } + let depth = 0; + for (let i = 0; i < value.length; i++) { + const char = value[i]; + if (char === '(') { + depth += 1; + } else if (char === ')') { + depth -= 1; + if (depth === 0) { + return i === value.length - 1; + } + if (depth < 0) { + return false; + } + } + } + return false; +} + +export const isThemeRGB = (value: unknown): value is string => { + if (typeof value !== 'string') { + return false; + } + const match = value.match(rgbPattern); + return match !== null && match.slice(1).every((channel) => Number(channel) <= 255); +}; + +/** The bare form, or one `calc()` of two unit-bearing lengths (a bare `0` is a number there): + * the small radius defaults keep a px offset. */ +const isLength = (value: unknown): value is string => + typeof value === 'string' && + (cssLengthPattern.test(value) || cssLengthDifferencePattern.test(value)); +const isFontFamily = (value: unknown): value is string => + typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value); + +/** Splits on `separator` outside parentheses, so `rgb(0, 0, 0)` stays one part. Empty parts are + * kept, so a stray comma stays visible to the caller. */ +function splitTopLevel(value: string, separator: RegExp): string[] { + const parts: string[] = []; + let depth = 0; + let current = ''; + for (let i = 0; i < value.length; i++) { + const char = value[i]; + if (char === '(') { + depth += 1; + } else if (char === ')') { + depth -= 1; + } + if (depth === 0 && separator.test(char)) { + parts.push(current); + current = ''; + continue; + } + current += char; + } + parts.push(current); + return parts.map((part) => part.trim()); +} + +/** A named color is indistinguishable from any other word without the browser's color parser, + * so outside a browser the pattern decides. */ +const isShadowColor = (token: string): boolean => + globalThis.CSS?.supports?.('color', token) ?? shadowColorPattern.test(token); + +/** One layer: two to four lengths, optionally `inset` and one color, per the box-shadow grammar. */ +function isShadowLayer(layer: string): boolean { + const tokens = splitTopLevel(layer, /\s/).filter((token) => token.length > 0); + const lengths = tokens.filter((token) => shadowLengthPattern.test(token)).length; + const insets = tokens.filter((token) => token.toLowerCase() === 'inset').length; + const colors = tokens.filter( + (token) => !shadowLengthPattern.test(token) && token.toLowerCase() !== 'inset', + ); + return ( + lengths >= 2 && lengths <= 4 && insets <= 1 && colors.length <= 1 && colors.every(isShadowColor) + ); +} + +/** + * A shadow must be concrete: a browser defers its check of any value holding `var()`, `env()` or + * `attr()` until substitution, so such a value could never be validated before it reaches the + * ring layers. + */ +const isShadow = (value: unknown): value is string => { + if (typeof value !== 'string' || /[;{}]|url\s*\(|(var|env|attr)\s*\(/i.test(value)) { + return false; + } + if (value.trim().toLowerCase() === 'none') { + return true; + } + const layers = splitTopLevel(value, /,/); + if (layers.some((layer) => layer.length === 0) || !layers.every(isShadowLayer)) { + return false; + } + return globalThis.CSS?.supports?.('box-shadow', value) ?? true; +}; +const isDuration = (value: unknown): value is string => + typeof value === 'string' && cssDurationPattern.test(value); + +export const isPlainThemeRecord = (value: unknown): value is Record => { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false; + } + try { + const prototype = Object.getPrototypeOf(value); + return prototype === null || prototype.constructor?.name === 'Object'; + } catch { + return false; + } +}; + +const appearanceValidators = { + controlRadius: isLength, + roundControlRadius: isLength, + surfaceRadius: isLength, + largeSurfaceRadius: isLength, + radiusSm: isLength, + radiusMd: isLength, + radiusLg: isLength, + radiusXl: isLength, + radius2xl: isLength, + radius3xl: isLength, + controlHeight: isLength, + spaceCompact: isLength, + spaceNormal: isLength, + fontFamily: isFontFamily, + monoFontFamily: isFontFamily, + /** Released themes may hold `var()` here, so this role keeps its original, looser check. */ + elevationSurface: (value: unknown) => + typeof value === 'string' && value.trim().length > 0 && !/[;{}]|url\s*\(/i.test(value), + shadow2xs: isShadow, + shadowXs: isShadow, + shadowSm: isShadow, + shadowMd: isShadow, + shadowLg: isShadow, + shadowXl: isShadow, + shadow2xl: isShadow, + motionFast: isDuration, + motionNormal: isDuration, +} satisfies Record boolean>; + +export type ThemeAppearanceToken = keyof typeof appearanceValidators; + +export const themeAppearanceTokens = Object.freeze( + Object.keys(appearanceValidators) as ThemeAppearanceToken[], +); + +export const isThemeAppearanceToken = (key: string): key is ThemeAppearanceToken => + Object.prototype.hasOwnProperty.call(appearanceValidators, key); + +const colorTokenSet: ReadonlySet = new Set(themeColorTokens); +const brandTokenSet: ReadonlySet = new Set(themeBrandTokens); +const themeModes = ['light', 'dark'] as const; + +/** + * A token added after this reader shipped is ignored rather than rejected, so a newer definition + * degrades to the defaults for what this version cannot paint instead of losing every value it + * can. It never reaches the DOM, but it must still look like a token: a camelCase name and a + * plain CSS value, never a declaration or rule break. + */ +const isFutureAppearance = (key: string, value: unknown): boolean => + /^[a-z][a-zA-Z0-9]*$/.test(key) && typeof value === 'string' && !/[;{}<>]|url\s*\(/i.test(value); + +const issue = (path: string[], message: string): ThemeIssue => ({ path, message }); + +/** The appearance tokens this reader does not know, which a resolved theme leaves out. */ +export function collectThemeWarningIssues(theme: unknown): ThemeIssue[] { + if (!isPlainThemeRecord(theme) || !isPlainThemeRecord(theme.modes)) { + return []; + } + const modes = theme.modes; + return themeModes.flatMap((mode) => { + const definition = modes[mode]; + const appearance = isPlainThemeRecord(definition) ? definition.appearance : undefined; + if (!isPlainThemeRecord(appearance)) { + return []; + } + return Object.keys(appearance) + .filter((key) => !isThemeAppearanceToken(key)) + .map((key) => + issue( + ['modes', mode, 'appearance', key], + `Unknown ${mode} appearance token ignored: ${key}`, + ), + ); + }); +} + +/** Shared by the theme-wide `brands` and each mode's override block. */ +function collectBrandIssues(brands: unknown, path: string[]): ThemeIssue[] { + if (!isPlainThemeRecord(brands)) { + return []; + } + + return Object.entries(brands).flatMap(([key, value]) => { + if (!brandTokenSet.has(key)) { + return [issue([...path, key], `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 + ? [issue([...path, key], `Invalid brand value for ${key}: ${value}`)] + : []; + }); +} + +function collectModeIssues(mode: 'light' | 'dark', definition: unknown): ThemeIssue[] { + const base = ['modes', mode]; + if (definition === undefined) { + return []; + } + if (!isPlainThemeRecord(definition)) { + return [issue(base, `Theme mode ${mode} must be an object`)]; + } + + const issues: ThemeIssue[] = Object.keys(definition) + .filter((key) => key !== 'colors' && key !== 'appearance' && key !== 'brands') + .map((key) => issue([...base, key], `Unknown ${mode} theme field: ${key}`)); + + const { colors, appearance, brands } = definition; + if (colors !== undefined && !isPlainThemeRecord(colors)) { + issues.push(issue([...base, 'colors'], `Theme colors for ${mode} must be an object`)); + } else { + Object.entries(colors ?? {}).forEach(([key, value]) => { + const path = [...base, 'colors', key]; + if (!colorTokenSet.has(key)) { + issues.push(issue(path, `Unknown color token: ${key}`)); + return; + } + if (value !== undefined && !isThemeRGB(value)) { + issues.push(issue(path, `Invalid RGB value for ${key}: ${value}`)); + } + }); + } + + if (appearance !== undefined && !isPlainThemeRecord(appearance)) { + issues.push(issue([...base, 'appearance'], `Theme appearance for ${mode} must be an object`)); + } else { + Object.entries(appearance ?? {}).forEach(([key, value]) => { + const isValid = isThemeAppearanceToken(key) + ? appearanceValidators[key](value) + : isFutureAppearance(key, value); + if (value !== undefined && !isValid) { + issues.push( + issue([...base, 'appearance', key], `Invalid appearance value for ${key}: ${value}`), + ); + } + }); + } + + if (brands !== undefined && !isPlainThemeRecord(brands)) { + issues.push(issue([...base, 'brands'], `Theme brands for ${mode} must be an object`)); + } else { + issues.push(...collectBrandIssues(brands, [...base, 'brands'])); + } + return issues; +} + +/** Every reason a definition cannot be painted; empty when it can. */ +export function collectThemeIssues(theme: unknown): ThemeIssue[] { + if (!isPlainThemeRecord(theme)) { + return [issue([], 'Theme definition must be an object')]; + } + + const issues: ThemeIssue[] = Object.keys(theme) + .filter((key) => key !== 'version' && key !== 'name' && key !== 'modes' && key !== 'brands') + .map((key) => issue([key], `Unknown theme field: ${key}`)); + + if (theme.version !== THEME_VERSION) { + issues.push(issue(['version'], `Unsupported theme version: ${theme.version}`)); + } + if (typeof theme.name !== 'string' || !theme.name.trim()) { + issues.push(issue(['name'], 'Theme name is required')); + } + const modes = theme.modes; + if (!isPlainThemeRecord(modes)) { + issues.push(issue(['modes'], 'Theme modes must be an object')); + return issues; + } + + Object.keys(modes) + .filter((mode) => mode !== 'light' && mode !== 'dark') + .forEach((mode) => issues.push(issue(['modes', mode], `Unknown theme mode: ${mode}`))); + + themeModes.forEach((mode) => issues.push(...collectModeIssues(mode, modes[mode]))); + + if (theme.brands !== undefined && !isPlainThemeRecord(theme.brands)) { + issues.push(issue(['brands'], 'Theme brands must be an object')); + } else { + issues.push(...collectBrandIssues(theme.brands, ['brands'])); + } + + return issues; +} From 1d5062cd95c0ecf5ac2d50a91f68e9e59b59a517 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:04:23 +0200 Subject: [PATCH 04/21] =?UTF-8?q?=F0=9F=8E=9B=EF=B8=8F=20refactor:=20Suppl?= =?UTF-8?q?y=20App-Global=20Chat=20Settings=20From=20the=20Host=20(#16466)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Supply App-Global Chat Settings From the Host The chat hooks read the during-run default, steer interrupts, save drafts, temporary chat and the artifacts reset from a ChatSettings context that Root fills from the existing Recoil atoms. liveAppliedSteerIds moves to Jotai with its reader and writer, and manual compaction submits through the useChat facade. * fix: Keep Compaction Off the Message Frame and Read One Interrupt Default Compaction reads status through useChatActions, which re-renders only when the status changes instead of mapping every stream frame. The during-run send button reads the interrupt default from the steering controls instead of a second store read. * fix: Supply Only Preferences Every Chat Reader Can Take From the Host saveDrafts and isTemporary are also read by useNewConvo, useAutoSave and the upload path, and by ChatView, ChatForm and the resume hook, so a host value for them would split one preference across two sources. They stay on the store until all of their readers can move together. --- client/src/Providers/ChatSettingsContext.tsx | 32 ++++ .../Chat/Input/DuringRunSendButton.tsx | 4 +- .../__tests__/DuringRunSendButton.test.tsx | 10 +- .../Chat/Messages/Content/Parts/SteerPart.tsx | 8 +- .../Parts/__tests__/SteerPart.test.tsx | 54 +++---- .../src/hooks/Chat/__tests__/facade.spec.tsx | 143 +++++++++++++++++- .../__tests__/useCompactConversation.spec.tsx | 35 ++++- .../hooks/Chat/__tests__/useSteering.spec.tsx | 3 +- client/src/hooks/Chat/facade.ts | 138 +++++++++++++---- client/src/hooks/Chat/index.ts | 1 - .../src/hooks/Chat/useCompactConversation.ts | 11 +- client/src/hooks/Chat/useIdChangeEffect.ts | 5 +- client/src/hooks/Chat/useSteering.ts | 13 +- client/src/hooks/SSE/useResumableSSE.ts | 5 +- client/src/routes/ChatSettings.tsx | 32 ++++ client/src/routes/Root.tsx | 11 +- .../routes/__tests__/ChatSettings.spec.tsx | 61 ++++++++ client/src/store/families.ts | 24 --- client/src/store/steer.ts | 15 ++ 19 files changed, 485 insertions(+), 120 deletions(-) create mode 100644 client/src/Providers/ChatSettingsContext.tsx create mode 100644 client/src/routes/ChatSettings.tsx create mode 100644 client/src/routes/__tests__/ChatSettings.spec.tsx diff --git a/client/src/Providers/ChatSettingsContext.tsx b/client/src/Providers/ChatSettingsContext.tsx new file mode 100644 index 0000000000..9034f78789 --- /dev/null +++ b/client/src/Providers/ChatSettingsContext.tsx @@ -0,0 +1,32 @@ +import { createContext, useContext } from 'react'; + +/** Composer action while a run is in flight: fold the text into the run, or queue a new turn. */ +export type DuringRunAction = 'steer' | 'queue'; + +/** + * App-global preferences the chat reads but does not own. The host supplies them, so the chat + * hooks never reach into the app's state store for shell settings. A preference belongs here only + * once every chat reader of it takes it from here: a reader left on the store would act on a + * different value than a host that supplies its own. + */ +export type ChatSettings = { + /** Default composer action while a run is in flight. */ + duringRunDefaultAction: DuringRunAction; + setDuringRunDefaultAction: (action: DuringRunAction) => void; + /** Whether a steer interrupts the running step instead of waiting for the next one. */ + steerInterruptsByDefault: boolean; + /** Closes the artifacts panel, called when the active conversation changes. */ + resetVisibleArtifacts: () => void; +}; + +/** Stock values, used when no host supplies settings (isolated renders and tests). */ +export const defaultChatSettings: ChatSettings = { + duringRunDefaultAction: 'steer', + setDuringRunDefaultAction: () => undefined, + steerInterruptsByDefault: false, + resetVisibleArtifacts: () => undefined, +}; + +export const ChatSettingsContext = createContext(defaultChatSettings); + +export const useChatSettings = () => useContext(ChatSettingsContext); diff --git a/client/src/components/Chat/Input/DuringRunSendButton.tsx b/client/src/components/Chat/Input/DuringRunSendButton.tsx index 5ea20bb259..d2f0e57ace 100644 --- a/client/src/components/Chat/Input/DuringRunSendButton.tsx +++ b/client/src/components/Chat/Input/DuringRunSendButton.tsx @@ -1,5 +1,4 @@ import React, { forwardRef, useMemo } from 'react'; -import { useRecoilValue } from 'recoil'; import { useWatch } from 'react-hook-form'; import { Zap, Clock, OctagonPause, ZapOff } from 'lucide-react'; import { composerSubmitClasses, SendActions, SendIcon } from '@librechat/client'; @@ -10,7 +9,6 @@ import type { SteeringControls } from '~/hooks/Chat/useSteering'; import { isMacPlatform, resolveComposerKeyDown } from '~/utils/shortcuts'; import useComposerBindings from '~/hooks/Input/useComposerBindings'; import { useLocalize } from '~/hooks'; -import store from '~/store'; /** The rows, the popover and the chord chips are shared with every other chat * surface that can submit more than one way — see `SendActions`. */ @@ -40,9 +38,9 @@ type DuringRunSendButtonProps = { const DuringRunSendButton = React.memo( forwardRef((props: DuringRunSendButtonProps, ref: React.ForwardedRef) => { const localize = useLocalize(); - const steerInterruptsByDefault = useRecoilValue(store.steerInterruptsByDefault); const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings(); const { steering, enterToSend } = props; + const { steerInterruptsByDefault } = steering; const data = useWatch({ control: props.control }); const content = data?.text?.trim(); const primary = steering.effectiveAction; diff --git a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx index a727673a2e..571fd5dff0 100644 --- a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx +++ b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx @@ -40,12 +40,14 @@ const steeringStub = ({ pausedOnApproval = false, canSteer = true, canControlGeneration = true, -}: StubOptions) => + steerInterruptsByDefault = false, +}: StubOptions & { steerInterruptsByDefault?: boolean }) => ({ effectiveAction: canSteer ? 'steer' : 'queue', canSteer, canControlGeneration, pausedOnApproval, + steerInterruptsByDefault, interruptSteer: mockInterruptSteer, steerFromComposer: mockSteerFromComposer, queueFromComposer: mockQueueFromComposer, @@ -83,12 +85,14 @@ function openMenu(options: MenuOptions = {}) { render( { - set(store.steerInterruptsByDefault, enterInterrupts); set(store.shortcutsEnabled, shortcutsEnabled); set(store.customShortcuts, customShortcuts); }} > - + , ); expect(screen.getByText('com_ui_interrupt_steer')).toBeInTheDocument(); diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx index 1fb2fe7232..23a99c3f55 100644 --- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx @@ -1,8 +1,10 @@ import { memo, useMemo, useState, useEffect, useCallback } from 'react'; -import { useRecoilValue, useSetRecoilState } from 'recoil'; +import { useRecoilValue } from 'recoil'; +import { useAtomValue, useSetAtom } from 'jotai'; import type { TFile, TMessage } from 'librechat-data-provider'; import SteerReceipt, { type SteerReceiptState } from '~/components/Chat/Steering/Receipt'; import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog'; +import { liveAppliedSteerFamily, liveAppliedSteerIdsAtom } from '~/store/steer'; import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp'; import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes'; import { cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils'; @@ -95,8 +97,8 @@ const SteerPart = memo(function SteerPart({ * identity consumes its id whether it animated or not, so nothing lingers. * The membership selector scopes the subscription to THIS id — stamping or * consuming one steer never re-renders the other mounted parts. */ - const isLiveApplied = useRecoilValue(store.liveAppliedSteerFamily(steerId ?? '')); - const setLiveAppliedIds = useSetRecoilState(store.liveAppliedSteerIds); + const isLiveApplied = useAtomValue(liveAppliedSteerFamily(steerId ?? '')); + const setLiveAppliedIds = useSetAtom(liveAppliedSteerIdsAtom); const [captured, setCaptured] = useState<{ id: string | undefined; animate: boolean }>({ id: steerId, animate: isLiveApplied, 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.tsx index 25b6a15dbc..b47c6c8dca 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 @@ -1,10 +1,12 @@ import React from 'react'; -import { RecoilRoot, useRecoilValue } from 'recoil'; +import { RecoilRoot } from 'recoil'; import { QueryKeys } from 'librechat-data-provider'; +import { Provider, createStore, useAtomValue } from 'jotai'; import { render, screen, fireEvent } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { TMessage } from 'librechat-data-provider'; import { STEER_ICON } from '~/components/Chat/Steering/identity'; +import { liveAppliedSteerIdsAtom } from '~/store/steer'; import SteerPart from '../SteerPart'; import store from '~/store'; @@ -243,21 +245,24 @@ describe('SteerPart presentation', () => { describe('SteerPart live receipt draw-in', () => { function LiveIdsProbe() { - const ids = useRecoilValue(store.liveAppliedSteerIds); + const ids = useAtomValue(liveAppliedSteerIdsAtom); return
{ids.join(',')}
; } + function seededStore(liveIds: string[]) { + const jotaiStore = createStore(); + jotaiStore.set(liveAppliedSteerIdsAtom, liveIds); + return jotaiStore; + } + function renderLive(liveIds: string[]) { return render( - { - set(store.user, SEEDED_USER as never); - set(store.liveAppliedSteerIds, liveIds); - }} - > - - - , + + set(store.user, SEEDED_USER as never)}> + + + + , ); } @@ -286,28 +291,23 @@ describe('SteerPart live receipt draw-in', () => { ); + const jotaiStore = seededStore(['s2']); const { rerender } = render( - { - set(store.user, SEEDED_USER as never); - set(store.liveAppliedSteerIds, ['s2']); - }} - > - {partFor('s1')} - , + + set(store.user, SEEDED_USER as never)}> + {partFor('s1')} + + , ); expect(appliedChecks()).not.toHaveClass('animate-in'); expect(screen.getByTestId('live-ids')).toHaveTextContent('s2'); rerender( - { - set(store.user, SEEDED_USER as never); - set(store.liveAppliedSteerIds, ['s2']); - }} - > - {partFor('s2')} - , + + set(store.user, SEEDED_USER as never)}> + {partFor('s2')} + + , ); expect(appliedChecks()).toHaveClass('animate-in'); expect(screen.getByTestId('live-ids').textContent).toBe(''); diff --git a/client/src/hooks/Chat/__tests__/facade.spec.tsx b/client/src/hooks/Chat/__tests__/facade.spec.tsx index 4b19e0e44d..e6bf42298b 100644 --- a/client/src/hooks/Chat/__tests__/facade.spec.tsx +++ b/client/src/hooks/Chat/__tests__/facade.spec.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import { act, renderHook } from '@testing-library/react'; +import { act, render, renderHook } from '@testing-library/react'; import { QueryKeys, ContentTypes } from 'librechat-data-provider'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; import type { TConversation, TMessage, TMessageContentParts } from 'librechat-data-provider'; import type { ChatContract } from '../contract'; import { ChatContext } from '~/Providers/ChatContext'; -import { useChat } from '../facade'; +import { useChat, useChatActions } from '../facade'; const userMessage: TMessage = { messageId: 'user-1', @@ -65,6 +65,9 @@ const createContract = (overrides: Partial = {}): ChatContract => }; }; +/** The facade delivers cache writes on a microtask, outside the render that caused them. */ +const flushCacheNotify = () => Promise.resolve(); + /** Renders `useChat` under the real `ChatContext`; `rerender` swaps the contract value. */ const renderChat = (initial: ChatContract) => { let contract = initial; @@ -224,7 +227,7 @@ describe('useChat', () => { expect(result.current.messages).toHaveLength(2); }); - it('re-reads messages when the message cache is written', () => { + it('re-reads messages when the message cache is written', async () => { let messages: TMessage[] = [userMessage, response({ text: 'Old' })]; const contract = createContract({ getMessages: jest.fn(() => messages), @@ -236,11 +239,12 @@ describe('useChat', () => { queryClient.setQueryData([QueryKeys.messages, 'convo-1'], next); }); - act(() => { + await act(async () => { result.current.setMessages((views) => [ { ...views[0], parts: [{ type: 'text', text: 'Edited' }] }, views[1], ]); + await flushCacheNotify(); }); expect(result.current.messages[0].parts).toEqual([{ type: 'text', text: 'Edited' }]); @@ -274,7 +278,7 @@ describe('useChat', () => { expect(result.current.messages[1].parts).toEqual([{ type: 'text', text: 'Hello' }]); }); - it('follows each stream frame written to the cache with the same message references', () => { + it('follows each stream frame written to the cache with the same message references', async () => { const key = [QueryKeys.messages, 'convo-1']; const streaming = response({ content: [{ type: ContentTypes.TEXT, text: 'Hel' }] }); const queryClient = new QueryClient(); @@ -292,9 +296,10 @@ describe('useChat', () => { const { result } = renderHook(() => useChat(), { wrapper }); const before = queryClient.getQueryData(key); - act(() => { + await act(async () => { streaming.content = [{ type: ContentTypes.TEXT, text: 'Hello' }]; queryClient.setQueryData(key, [userMessage, streaming]); + await flushCacheNotify(); }); expect(queryClient.getQueryData(key)).toBe(before); @@ -302,15 +307,64 @@ describe('useChat', () => { expect(result.current.status).toBe('streaming'); const findAll = jest.spyOn(queryClient.getQueryCache(), 'findAll'); - act(() => { + await act(async () => { streaming.content = [{ type: ContentTypes.TEXT, text: 'Hello there' }]; queryClient.setQueryData(key, [userMessage, streaming]); + await flushCacheNotify(); }); expect(result.current.messages[1].parts).toEqual([{ type: 'text', text: 'Hello there' }]); expect(findAll).not.toHaveBeenCalled(); }); + it('never updates while another component mounts a query on its messages', async () => { + const key = [QueryKeys.messages, 'convo-1']; + const queryClient = new QueryClient(); + const contract = createContract({ + getMessages: jest.fn(() => queryClient.getQueryData(key)), + }); + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined); + /** Mounting an observer with initial data creates and fills the query inside this render. */ + const Reader = () => { + useQuery({ queryKey: key, queryFn: () => [userMessage], initialData: [userMessage] }); + return null; + }; + const Probe = ({ withReader }: { withReader: boolean }) => { + const { messages } = useChat(); + return ( + <> + {messages.length} + {withReader && } + + ); + }; + const view = render( + + + + + , + ); + + await act(async () => { + view.rerender( + + + + + , + ); + await flushCacheNotify(); + }); + + expect(view.getByTestId('count')).toHaveTextContent('1'); + const renderPhaseUpdates = consoleError.mock.calls.filter(([message]) => + String(message).includes('Cannot update a component'), + ); + consoleError.mockRestore(); + expect(renderPhaseUpdates).toEqual([]); + }); + it('keeps its messages when another conversation is written', () => { const key = [QueryKeys.messages, 'convo-1']; const queryClient = new QueryClient(); @@ -599,3 +653,76 @@ describe('useChat', () => { expect(contract.setMessages).toHaveBeenNthCalledWith(2, [userMessage, answered]); }); }); + +describe('useChatActions', () => { + const renderActions = (messages: TMessage[]) => { + const key = [QueryKeys.messages, 'convo-1']; + const queryClient = new QueryClient(); + queryClient.setQueryData(key, messages); + const contract = createContract({ + getMessages: jest.fn(() => queryClient.getQueryData(key)), + latestMessageId: 'response-1', + isSubmitting: true, + }); + let renders = 0; + const wrapper = ({ children }: { children: React.ReactNode }) => ( + + {children} + + ); + const view = renderHook( + () => { + renders += 1; + return useChatActions(); + }, + { wrapper }, + ); + const write = async (next: TMessage[]) => { + await act(async () => { + queryClient.setQueryData(key, next); + await flushCacheNotify(); + }); + }; + return { ...view, contract, write, renders: () => renders }; + }; + + it('moves from submitted to streaming when the response gets content', async () => { + const { result, write } = renderActions([userMessage, response()]); + expect(result.current.status).toBe('submitted'); + + await write([userMessage, response({ content: [{ type: ContentTypes.TEXT, text: 'Hel' }] })]); + + expect(result.current.status).toBe('streaming'); + }); + + it('does not re-render for stream frames that keep the status', async () => { + const { result, write, renders } = renderActions([ + userMessage, + response({ content: [{ type: ContentTypes.TEXT, text: 'Hel' }] }), + ]); + const first = result.current; + const before = renders(); + + await write([userMessage, response({ content: [{ type: ContentTypes.TEXT, text: 'Hello' }] })]); + await write([ + userMessage, + response({ content: [{ type: ContentTypes.TEXT, text: 'Hello!' }] }), + ]); + + expect(renders()).toBe(before); + expect(result.current).toBe(first); + }); + + it('forwards its actions to the contract', () => { + const { result, contract } = renderActions([userMessage, response()]); + + expect(result.current.sendMessage).toBe(contract.ask); + expect(result.current.stop).toBe(contract.stopGenerating); + result.current.regenerate(); + expect(contract.regenerate).toHaveBeenCalledWith({ + messageId: 'response-1', + parentMessageId: 'user-1', + isCreatedByUser: false, + }); + }); +}); diff --git a/client/src/hooks/Chat/__tests__/useCompactConversation.spec.tsx b/client/src/hooks/Chat/__tests__/useCompactConversation.spec.tsx index 72d74da27b..aef6500bc8 100644 --- a/client/src/hooks/Chat/__tests__/useCompactConversation.spec.tsx +++ b/client/src/hooks/Chat/__tests__/useCompactConversation.spec.tsx @@ -1,10 +1,14 @@ +import React from 'react'; import { getDefaultStore } from 'jotai'; import { ContentTypes } from 'librechat-data-provider'; import { renderHook, act } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { TMessage } from 'librechat-data-provider'; import useCompactConversation, { compactingConversationAtom } from '../useCompactConversation'; const mockAsk = jest.fn(); +/** The message cache hands back one array until it is written, as React Query does. */ +const mockStoredMessages: TMessage[] = []; let mockContext: { index: number; isSubmitting: boolean; @@ -12,8 +16,18 @@ let mockContext: { }; let mockLatestMessage: TMessage | null; -jest.mock('~/Providers', () => ({ - useChatContext: () => ({ ...mockContext, ask: mockAsk }), +/** The hook reads status and submits through the real `useChat` facade over this contract. */ +jest.mock('~/Providers/ChatContext', () => ({ + useChatContext: () => ({ + ...mockContext, + ask: mockAsk, + getMessages: () => mockStoredMessages, + messagesKey: mockContext.conversation?.conversationId ?? '', + setMessages: jest.fn(), + latestMessageId: undefined, + regenerate: jest.fn(), + stopGenerating: jest.fn(), + }), })); jest.mock('~/hooks/Messages/useLatestMessage', () => ({ useLatestMessage: () => mockLatestMessage, @@ -39,6 +53,11 @@ const leaf = (overrides: Partial = {}): TMessage => ...overrides, }) as TMessage; +const queryClient = new QueryClient(); +const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} +); + describe('useCompactConversation', () => { beforeEach(() => { mockAsk.mockClear(); @@ -53,7 +72,7 @@ describe('useCompactConversation', () => { it('drops a marker left by a compaction that finished while the view was away', () => { getDefaultStore().set(compactingConversationAtom, 'convo-1'); - const hook = renderHook(() => useCompactConversation()); + const hook = renderHook(() => useCompactConversation(), { wrapper }); expect(hook.result.current.isCompacting).toBe(false); /** The next ordinary turn in the same conversation is not a compaction. */ @@ -65,7 +84,7 @@ describe('useCompactConversation', () => { it('keeps the marker when it mounts into a compaction still streaming', () => { getDefaultStore().set(compactingConversationAtom, 'convo-1'); mockContext.isSubmitting = true; - const hook = renderHook(() => useCompactConversation()); + const hook = renderHook(() => useCompactConversation(), { wrapper }); expect(hook.result.current.isCompacting).toBe(true); mockContext.isSubmitting = false; @@ -75,7 +94,7 @@ describe('useCompactConversation', () => { }); it('submits a compaction anchored on the leaf itself', () => { - const { result } = renderHook(() => useCompactConversation()); + const { result } = renderHook(() => useCompactConversation(), { wrapper }); expect(result.current.canCompact).toBe(true); act(() => result.current.compact()); @@ -101,7 +120,7 @@ describe('useCompactConversation', () => { ], ])('cannot compact with %s', (_label, arrange) => { arrange(); - const { result } = renderHook(() => useCompactConversation()); + const { result } = renderHook(() => useCompactConversation(), { wrapper }); expect(result.current.canCompact).toBe(false); act(() => result.current.compact()); @@ -114,13 +133,13 @@ describe('useCompactConversation', () => { ['stored without a boundary', summaryPart({ boundary: undefined })], ])('lets an interrupted compaction (summary %s) be retried', (_label, part) => { mockLatestMessage = leaf({ text: '', content: [part] }); - const { result } = renderHook(() => useCompactConversation()); + const { result } = renderHook(() => useCompactConversation(), { wrapper }); expect(result.current.canCompact).toBe(true); }); it('reports compacting only for the conversation it submitted, until the turn settles', () => { - const hook = renderHook(() => useCompactConversation()); + const hook = renderHook(() => useCompactConversation(), { wrapper }); act(() => hook.result.current.compact()); mockContext.isSubmitting = true; diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx index 673049636d..b99d3b24fe 100644 --- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx +++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx @@ -22,6 +22,7 @@ import { clearAllDrafts, getPendingDraftId, getNewConversationDraftId } from '~/ import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery'; import { claimQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent'; import useUpdateFiles from '~/hooks/Files/useUpdateFiles'; +import ChatSettingsProvider from '~/routes/ChatSettings'; import { applyPendingAction } from '~/utils/approval'; import useQueueDrain from '../useQueueDrain'; import store from '~/store'; @@ -134,7 +135,7 @@ function setup(params: HookParams = {}, initialize?: (snapshot: MutableSnapshot) initializeState={withActiveGeneration(initialize, params.conversationId ?? CONVO_ID)} > - {children} + {children} ); const rendered = renderHook( diff --git a/client/src/hooks/Chat/facade.ts b/client/src/hooks/Chat/facade.ts index 5928a61ba1..6db5ac2857 100644 --- a/client/src/hooks/Chat/facade.ts +++ b/client/src/hooks/Chat/facade.ts @@ -8,6 +8,8 @@ import { toUIMessage, } from 'librechat-data-provider'; import type { TMessage, UIMessage, TAttachment, UIMappingOptions } from 'librechat-data-provider'; +import type { QueryCacheNotifyEvent } from '@tanstack/react-query'; +import type { ChatContract } from './contract'; import type { TAskFunction } from '~/common'; import { isMemoryFailureOutput } from '~/components/Chat/Messages/Content/Parts/MemoryCall'; import { getToolMeta } from '~/components/Chat/Messages/Content/outcome'; @@ -225,6 +227,9 @@ export const getChatStatus = (isSubmitting: boolean, latest: TMessage | undefine return latest && isErrorMessage(latest) ? 'error' : 'ready'; }; +/** Cache events that add, drop or rewrite a query's data. */ +const dataEvents = new Set(['added', 'removed', 'updated']); + /** Ids on the active branch: the contract's tail and its ancestors. */ const getActiveBranch = (byId: Map, tailId: string | undefined) => { const branch = new Set(); @@ -236,6 +241,110 @@ const getActiveBranch = (byId: Map, tailId: string | undefined return branch; }; +/** + * Subscribes to writes of one conversation's cached messages. Only events that can change the + * data count: observers mount inside other components' renders and the cache notifies + * synchronously, so the change is delivered after the current task instead of inside someone + * else's render. + */ +const useMessagesSubscription = (messagesKey: string) => { + const queryClient = useQueryClient(); + const queryHash = useMemo(() => hashQueryKey([QueryKeys.messages, messagesKey]), [messagesKey]); + const subscribe = useCallback( + (onChange: () => void) => { + let active = true; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (event.query.queryHash !== queryHash || !dataEvents.has(event.type)) { + return; + } + queueMicrotask(() => { + if (active) { + onChange(); + } + }); + }); + return () => { + active = false; + unsubscribe(); + }; + }, + [queryClient, queryHash], + ); + return { queryClient, queryHash, subscribe }; +}; + +/** Regenerates the response to `messageId`, or the latest message of the branch. */ +const useRegenerate = ( + getMessages: ChatContract['getMessages'], + latestMessageId: string | undefined, + regenerateTarget: ChatContract['regenerate'], +) => + useCallback( + (options?: { messageId?: string }) => { + const messageId = options?.messageId ?? latestMessageId; + const target = getMessages()?.find((message) => message.messageId === messageId); + regenerateTarget( + target + ? { + messageId: target.messageId, + parentMessageId: target.parentMessageId, + isCreatedByUser: target.isCreatedByUser, + } + : { messageId }, + ); + }, + [getMessages, latestMessageId, regenerateTarget], + ); + +/** The latest message, searched from the tail, where it almost always is. */ +const findLatest = (stored: TMessage[] | undefined, latestMessageId: string | undefined) => { + if (!stored || latestMessageId == null) { + return undefined; + } + for (let i = stored.length - 1; i >= 0; i--) { + if (stored[i].messageId === latestMessageId) { + return stored[i]; + } + } + return undefined; +}; + +/** The `useChat` members that need no message list. */ +export type ChatActions = Pick< + UseChatHelpers, + 'id' | 'status' | 'sendMessage' | 'regenerate' | 'stop' +>; + +/** + * `useChat` without `messages`, for controls that submit or read status: it re-renders when the + * status changes, not on every stream frame, and never maps the conversation. + */ +export function useChatActions(): ChatActions { + const { + conversation, + getMessages, + messagesKey, + latestMessageId, + isSubmitting, + ask, + regenerate: regenerateTarget, + stopGenerating, + } = useChatContext(); + const { subscribe } = useMessagesSubscription(messagesKey); + const readStatus = useCallback( + () => getChatStatus(isSubmitting, findLatest(getMessages(), latestMessageId)), + [getMessages, isSubmitting, latestMessageId], + ); + const status = useSyncExternalStore(subscribe, readStatus, readStatus); + const regenerate = useRegenerate(getMessages, latestMessageId, regenerateTarget); + const id = messagesKey || conversation?.conversationId || undefined; + + return useMemo( + () => ({ id, status, sendMessage: ask, regenerate, stop: stopGenerating }), + [id, status, ask, regenerate, stopGenerating], + ); +} + /** * AI SDK `useChat`, read and called through `ChatContext`. It holds no state of its own: * `messages` is `getMessages()` mapped per message, re-read when the message query cache is @@ -254,17 +363,7 @@ export function useChat(): UseChatHelpers { stopGenerating, } = useChatContext(); - const queryClient = useQueryClient(); - const queryHash = useMemo(() => hashQueryKey([QueryKeys.messages, messagesKey]), [messagesKey]); - const subscribe = useCallback( - (onChange: () => void) => - queryClient.getQueryCache().subscribe((event) => { - if (event.query.queryHash === queryHash) { - onChange(); - } - }), - [queryClient, queryHash], - ); + const { queryClient, queryHash, subscribe } = useMessagesSubscription(messagesKey); const snapshot = useRef<{ writes: number; stored?: TMessage[] }>(); /** * A stream frame replaces a response's content on the same object, so structural sharing can @@ -304,22 +403,7 @@ export function useChat(): UseChatHelpers { [errorText], ); - const regenerate = useCallback( - (options?: { messageId?: string }) => { - const messageId = options?.messageId ?? latestMessageId; - const target = getMessages()?.find((message) => message.messageId === messageId); - regenerateTarget( - target - ? { - messageId: target.messageId, - parentMessageId: target.parentMessageId, - isCreatedByUser: target.isCreatedByUser, - } - : { messageId }, - ); - }, - [getMessages, latestMessageId, regenerateTarget], - ); + const regenerate = useRegenerate(getMessages, latestMessageId, regenerateTarget); const setMessages = useCallback( (update: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => { diff --git a/client/src/hooks/Chat/index.ts b/client/src/hooks/Chat/index.ts index c6a7492b58..49afa24333 100644 --- a/client/src/hooks/Chat/index.ts +++ b/client/src/hooks/Chat/index.ts @@ -6,7 +6,6 @@ export { default as useTokenLimits } from './useTokenLimits'; export { default as useTokenUsage } from './useTokenUsage'; export { default as useAddedResponse } from './useAddedResponse'; export { default as useChatFunctions } from './useChatFunctions'; -export { default as useCompactConversation } from './useCompactConversation'; export { default as useGetAddedConvo } from './useGetAddedConvo'; export { default as useIdChangeEffect } from './useIdChangeEffect'; export { default as useFocusChatEffect } from './useFocusChatEffect'; diff --git a/client/src/hooks/Chat/useCompactConversation.ts b/client/src/hooks/Chat/useCompactConversation.ts index 332a94cce1..80afaaf4ca 100644 --- a/client/src/hooks/Chat/useCompactConversation.ts +++ b/client/src/hooks/Chat/useCompactConversation.ts @@ -2,7 +2,8 @@ import { useCallback, useEffect, useRef } from 'react'; import { atom, useAtom } from 'jotai'; import { Constants, isCompactedLeaf, isAssistantsEndpoint } from 'librechat-data-provider'; import { useLatestMessage } from '~/hooks/Messages/useLatestMessage'; -import { useChatContext } from '~/Providers'; +import { useChatContext } from '~/Providers/ChatContext'; +import { useChatActions } from './facade'; /** Conversation whose compaction this client submitted and is still streaming. */ export const compactingConversationAtom = atom(null); @@ -21,7 +22,9 @@ export const supportsCompaction = (endpoint?: string | null): boolean => * and is persisted as the boundary every later turn starts from. */ export default function useCompactConversation() { - const { ask, index, conversation, isSubmitting } = useChatContext(); + const { index, conversation } = useChatContext(); + const { sendMessage, status } = useChatActions(); + const isSubmitting = status === 'submitted' || status === 'streaming'; const latestMessage = useLatestMessage(index); const [compactingConversation, setCompactingConversation] = useAtom(compactingConversationAtom); @@ -61,7 +64,7 @@ export default function useCompactConversation() { setCompactingConversation(conversationId); /** The leaf is both the placeholder's parent and the server-side anchor * (`parentMessageId` is what the controller compacts up to). */ - const accepted = ask( + const accepted = sendMessage( { text: '', conversationId, @@ -73,7 +76,7 @@ export default function useCompactConversation() { if (accepted === false) { setCompactingConversation(null); } - }, [ask, canCompact, conversationId, latestMessage, setCompactingConversation]); + }, [sendMessage, canCompact, conversationId, latestMessage, setCompactingConversation]); return { compact, canCompact, isCompacting }; } diff --git a/client/src/hooks/Chat/useIdChangeEffect.ts b/client/src/hooks/Chat/useIdChangeEffect.ts index 7d0378915d..d36d134d64 100644 --- a/client/src/hooks/Chat/useIdChangeEffect.ts +++ b/client/src/hooks/Chat/useIdChangeEffect.ts @@ -1,7 +1,6 @@ import { useEffect, useRef } from 'react'; -import { useResetRecoilState } from 'recoil'; +import { useChatSettings } from '~/Providers/ChatSettingsContext'; import { logger } from '~/utils'; -import store from '~/store'; /** * Hook to reset visible artifacts when the conversation ID changes @@ -9,7 +8,7 @@ import store from '~/store'; */ export default function useIdChangeEffect(conversationId: string) { const lastConvoId = useRef(null); - const resetVisibleArtifacts = useResetRecoilState(store.visibleArtifacts); + const { resetVisibleArtifacts } = useChatSettings(); useEffect(() => { if (conversationId !== lastConvoId.current) { diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts index a83c74fe4c..bbd919f17b 100644 --- a/client/src/hooks/Chat/useSteering.ts +++ b/client/src/hooks/Chat/useSteering.ts @@ -26,6 +26,7 @@ import type { SettledQueuedTurnReceipt, } from '~/store/families'; import type { AgentQueuedTurnReceipt, GenerationProtocolVersion } from '~/data-provider'; +import type { DuringRunAction } from '~/Providers/ChatSettingsContext'; import type { QueueSendLock } from '~/utils/queueIntent'; import type { ExtendedFile, FileSetter } from '~/common'; import { @@ -60,6 +61,7 @@ import { } from '~/components/Chat/Input/Composer/state'; import { hasQueuedIntent, acquireQueueSendLock, releaseQueueSendLock } from '~/utils/queueIntent'; import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer'; +import { useChatSettings } from '~/Providers/ChatSettingsContext'; import useCodeApprovalMode from '../Agents/useCodeApprovalMode'; import { markComposerFilesTaken } from '~/utils/composerFiles'; import { useSteerRehome } from '~/hooks/Chat/useSteerCancel'; @@ -71,8 +73,7 @@ import { useFileMapContext } from '~/Providers'; import useLocalize from '~/hooks/useLocalize'; import store from '~/store'; -/** During-run submit routes: inject into the live run, or queue for after it. */ -export type DuringRunAction = 'steer' | 'queue'; +export type { DuringRunAction }; /** Composer state consumed into a queued item alongside the text. */ export interface QueuedMessageContext { @@ -595,9 +596,11 @@ export default function useSteering({ const { mutate: markFilesUsage } = useMarkFilesUsageMutation(); const { mutate: enqueueAgentQueuedTurn } = useEnqueueAgentQueuedTurnMutation(); const { mutateAsync: cancelAgentQueuedTurn } = useCancelAgentQueuedTurnMutation(); - const defaultAction = useRecoilValue(store.duringRunDefaultAction); - const setDefaultAction = useSetRecoilState(store.duringRunDefaultAction); - const steerInterruptsByDefault = useRecoilValue(store.steerInterruptsByDefault); + const { + duringRunDefaultAction: defaultAction, + setDuringRunDefaultAction: setDefaultAction, + steerInterruptsByDefault, + } = useChatSettings(); const { selected: codeApprovalMode } = useCodeApprovalMode(conversation, addedConversation); const endpoint = conversation?.endpointType ?? conversation?.endpoint; diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts index a10a4dfca5..723513b8e0 100644 --- a/client/src/hooks/SSE/useResumableSSE.ts +++ b/client/src/hooks/SSE/useResumableSSE.ts @@ -1,6 +1,6 @@ import { useEffect, useState, useRef, useCallback } from 'react'; import { v4 } from 'uuid'; -import { useStore } from 'jotai'; +import { useStore, useSetAtom } from 'jotai'; import { useQueryClient } from '@tanstack/react-query'; import { useSetRecoilState, useRecoilCallback } from 'recoil'; import { @@ -97,6 +97,7 @@ import useEventHandlers, { } from './useEventHandlers'; import { pendingApprovalActionFamily } from '~/components/Chat/approval/state'; import useSteerConvert from '~/hooks/Chat/useSteerConvert'; +import { liveAppliedSteerIdsAtom } from '~/store/steer'; import { useAuthContext } from '~/hooks/AuthContext'; import { createSSETransport } from './transport'; import { useFileMapContext } from '~/Providers'; @@ -965,7 +966,7 @@ export default function useResumableSSE( const setAbortScroll = useSetRecoilState(store.abortScrollFamily(runIndex)); const setSubmission = useSetRecoilState(store.submissionByIndex(runIndex)); const setShowStopButton = useSetRecoilState(store.showStopButtonByIndex(runIndex)); - const setLiveAppliedSteerIds = useSetRecoilState(store.liveAppliedSteerIds); + const setLiveAppliedSteerIds = useSetAtom(liveAppliedSteerIdsAtom); const streamRef = useRef(null); /** Removes the foreground re-attach listener owned by the newest diff --git a/client/src/routes/ChatSettings.tsx b/client/src/routes/ChatSettings.tsx new file mode 100644 index 0000000000..7a62220cb0 --- /dev/null +++ b/client/src/routes/ChatSettings.tsx @@ -0,0 +1,32 @@ +import { useMemo } from 'react'; +import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil'; +import type { ReactNode } from 'react'; +import type { ChatSettings } from '~/Providers/ChatSettingsContext'; +import { ChatSettingsContext } from '~/Providers/ChatSettingsContext'; +import store from '~/store'; + +/** Supplies the chat's app-global preferences from the app's own settings store. */ +export default function ChatSettingsProvider({ children }: { children: ReactNode }) { + const [duringRunDefaultAction, setDuringRunDefaultAction] = useRecoilState( + store.duringRunDefaultAction, + ); + const steerInterruptsByDefault = useRecoilValue(store.steerInterruptsByDefault); + const resetVisibleArtifacts = useResetRecoilState(store.visibleArtifacts); + + const settings = useMemo( + () => ({ + duringRunDefaultAction, + setDuringRunDefaultAction, + steerInterruptsByDefault, + resetVisibleArtifacts, + }), + [ + duringRunDefaultAction, + setDuringRunDefaultAction, + steerInterruptsByDefault, + resetVisibleArtifacts, + ], + ); + + return {children}; +} diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsx index 25c264872f..6cbe66937f 100644 --- a/client/src/routes/Root.tsx +++ b/client/src/routes/Root.tsx @@ -44,6 +44,7 @@ import useSidebarToggle from '~/hooks/Nav/useSidebarToggle'; import useSidebarState from '~/hooks/Nav/useSidebarState'; import { TermsAndConditionsModal } from '~/components/ui'; import useDrawerSwipe from '~/hooks/Nav/useDrawerSwipe'; +import ChatSettingsProvider from './ChatSettings'; import { useHealthCheck } from '~/data-provider'; import { Banner } from '~/components/Banners'; import store from '~/store'; @@ -68,7 +69,7 @@ function KeyboardShortcutsProvider() { ); } -export default function Root() { +function RootLayout() { const [showTerms, setShowTerms] = useState(false); const [bannerHeight, setBannerHeight] = useState(0); /** Shared with the drawer so the two agree on the breakpoint-transition frame. */ @@ -245,3 +246,11 @@ export default function Root() { ); } + +export default function Root() { + return ( + + + + ); +} diff --git a/client/src/routes/__tests__/ChatSettings.spec.tsx b/client/src/routes/__tests__/ChatSettings.spec.tsx new file mode 100644 index 0000000000..91c37a0187 --- /dev/null +++ b/client/src/routes/__tests__/ChatSettings.spec.tsx @@ -0,0 +1,61 @@ +import React from 'react'; +import { act, renderHook } from '@testing-library/react'; +import { RecoilRoot, useRecoilValue, type MutableSnapshot } from 'recoil'; +import { defaultChatSettings, useChatSettings } from '~/Providers/ChatSettingsContext'; +import ChatSettingsProvider from '../ChatSettings'; +import store from '~/store'; + +const renderSettings = (initialize?: (snapshot: MutableSnapshot) => void) => + renderHook( + () => ({ + settings: useChatSettings(), + storedAction: useRecoilValue(store.duringRunDefaultAction), + visibleArtifacts: useRecoilValue(store.visibleArtifacts), + }), + { + wrapper: ({ children }: { children: React.ReactNode }) => ( + + {children} + + ), + }, + ); + +describe('ChatSettingsProvider', () => { + it('supplies the stored preferences to the chat', () => { + const { result } = renderSettings(({ set }) => { + set(store.duringRunDefaultAction, 'queue'); + set(store.steerInterruptsByDefault, true); + }); + + expect(result.current.settings).toMatchObject({ + duringRunDefaultAction: 'queue', + steerInterruptsByDefault: true, + }); + }); + + it('writes the during-run default back to the app store', () => { + const { result } = renderSettings(); + + act(() => result.current.settings.setDuringRunDefaultAction('queue')); + + expect(result.current.storedAction).toBe('queue'); + expect(result.current.settings.duringRunDefaultAction).toBe('queue'); + }); + + it('closes the artifacts panel through the host', () => { + const { result } = renderSettings(({ set }) => { + set(store.visibleArtifacts, { a1: undefined }); + }); + + act(() => result.current.settings.resetVisibleArtifacts()); + + expect(result.current.visibleArtifacts).toBeNull(); + }); + + it('falls back to the stock defaults without a host', () => { + const { result } = renderHook(() => useChatSettings()); + + expect(result.current).toBe(defaultChatSettings); + }); +}); diff --git a/client/src/store/families.ts b/client/src/store/families.ts index ebf4745a9e..466f5575b0 100644 --- a/client/src/store/families.ts +++ b/client/src/store/families.ts @@ -616,28 +616,6 @@ const appliedSteerIdsByConvoId = atomFamily({ default: [], }); -/** - * Steer ids whose applied event landed in THIS session, pending their one-shot - * receipt draw-in. `SteerPart` consumes its id on mount so the animation plays - * exactly once, at the live chip→inline hand-off — never on reload, share, or - * a later revisit. Global rather than per-conversation: steer ids are unique, - * and the applied part renders in surfaces that don't know their convo id. */ -const liveAppliedSteerIds = atom({ - key: 'liveAppliedSteerIds', - default: [], -}); - -/** Membership view of `liveAppliedSteerIds` so each `SteerPart` subscribes to - * its own id only: stamping/consuming one steer re-renders that part, not - * every mounted historical part in a long conversation. */ -const liveAppliedSteerFamily = selectorFamily({ - key: 'liveAppliedSteerFamily', - get: - (steerId) => - ({ get }) => - steerId.length > 0 && get(liveAppliedSteerIds).includes(steerId), -}); - /** Optimistic ids the server has proven accepted via ACK or SYNC. Separate * from `appliedSteerIdsByConvoId`: accepted-but-still-queued steers must not * be suppressed by terminal conversion, but a late POST error must not @@ -836,8 +814,6 @@ export default { pendingRunEndByConvoId, drainAfterAbortByIndex, appliedSteerIdsByConvoId, - liveAppliedSteerIds, - liveAppliedSteerFamily, acceptedSteerClientIdsByConvoId, activeGenerationCreatedAtByConvoId, activeGenerationProtocolVersionByConvoId, diff --git a/client/src/store/steer.ts b/client/src/store/steer.ts index b8c23633fe..380a457f78 100644 --- a/client/src/store/steer.ts +++ b/client/src/store/steer.ts @@ -38,3 +38,18 @@ export const revealedQueuedTurnFamily = atomFamily((_conversationId: string) => export const pendingSteerCancelClientIdsFamily = atomFamily((_conversationId: string) => atom([]), ); + +/** + * Steer ids whose applied event landed in THIS session, pending their one-shot + * receipt draw-in. `SteerPart` consumes its id on mount so the animation plays + * exactly once, at the live chip to inline hand-off, never on reload, share, or + * a later revisit. Global rather than per-conversation: steer ids are unique, + * and the applied part renders in surfaces that don't know their convo id. */ +export const liveAppliedSteerIdsAtom = atom([]); + +/** Membership view of `liveAppliedSteerIdsAtom` so each `SteerPart` subscribes to + * its own id only: stamping/consuming one steer re-renders that part, not + * every mounted historical part in a long conversation. */ +export const liveAppliedSteerFamily = atomFamily((steerId: string) => + atom((get) => steerId.length > 0 && get(liveAppliedSteerIdsAtom).includes(steerId)), +); From 7a99b5cef7405634268cec42e2b36f2c3c3531dd Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 16:11:53 +0200 Subject: [PATCH 05/21] =?UTF-8?q?=F0=9F=8E=AF=20feat:=20Give=20Keyboard=20?= =?UTF-8?q?Focus=20Its=20Own=20Theme=20Roles=20(#16478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Give Keyboard Focus Its Own Theme Roles Add rgb-focus-outline for the app-wide keyboard focus outline and rgb-focus-control for the shared primitives' focus ring. The defaults reproduce the default theme exactly: a black and white outline, and primitive rings in the primary text ink. A theme that names only rgb-ring-primary keeps drawing its outline in that ring, and one that names only rgb-text-primary keeps ringing its controls in that ink, so the data-theme-ring marker is no longer needed. ClickHouse sets both roles to Click UI outline.default, cited in the drift guard. Every bundled palette holds both roles at 3:1 on its canvases. Button keeps its ring until the open PR that owns it lands. * test: Read the Opaque Ring Layer in the Focus Ring Probe * fix: Draw the Popover Focus Outline in the Control Focus Role --- client/src/style.css | 33 ++--- .../mock/scenarios/focus-outline.spec.ts | 130 +++++++++++++++++- .../client/src/components/AlertDialog.tsx | 4 +- .../src/components/AnimatedSearchInput.tsx | 2 +- packages/client/src/components/Checkbox.tsx | 2 +- packages/client/src/components/Combobox.tsx | 2 +- .../DataTable/DataTableErrorBoundary.tsx | 2 +- packages/client/src/components/Dialog.tsx | 8 +- packages/client/src/components/Dropdown.css | 2 +- packages/client/src/components/Field.ts | 2 +- packages/client/src/components/IconButton.tsx | 2 +- .../client/src/components/InfoHoverCard.tsx | 2 +- packages/client/src/components/InputOTP.tsx | 2 +- .../client/src/components/MultiSelect.tsx | 4 +- .../client/src/components/OriginalDialog.tsx | 2 +- packages/client/src/components/Radio.tsx | 2 +- packages/client/src/components/Resizable.tsx | 4 +- .../client/src/components/SelectDropDown.tsx | 2 +- packages/client/src/components/Slider.tsx | 2 +- packages/client/src/components/Switch.tsx | 2 +- packages/client/src/theme/README.md | 9 +- .../src/theme/context/ThemeProvider.spec.tsx | 20 +-- .../src/theme/context/ThemeProvider.tsx | 14 +- packages/client/src/theme/controls.css | 14 +- packages/client/src/theme/registry.spec.ts | 63 +++++++++ packages/client/src/theme/registry.ts | 18 +++ .../client/src/theme/semanticTokens.spec.ts | 53 ++++++- .../client/src/theme/themes/clickhouse.ts | 4 + .../client/src/theme/themes/clickui.spec.ts | 4 + packages/client/src/theme/themes/dark.ts | 2 + packages/client/src/theme/themes/default.ts | 2 + .../client/src/theme/themes/highContrast.ts | 4 + packages/client/src/theme/tokens.css | 2 + packages/client/src/theme/types/index.ts | 6 + packages/client/src/theme/utils/applyTheme.ts | 17 +-- packages/data-provider/src/theme.ts | 2 + 36 files changed, 358 insertions(+), 87 deletions(-) diff --git a/client/src/style.css b/client/src/style.css index c5e51201fb..b02463a00e 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -222,6 +222,7 @@ html { --accent-primary: 18 110 107; --accent-primary-hover: 10 79 83; --ring-primary: var(--gray-500); + --focus-outline: 0 0 0; --header-primary: var(--white); --header-hover: var(--gray-50); --header-button-hover: var(--gray-50); @@ -353,6 +354,7 @@ html { --brand-purple: 171 104 255; --presentation: var(--gray-800); --text-primary: var(--gray-100); + --focus-outline: 255 255 255; --text-secondary: var(--gray-300); --text-secondary-alt: var(--gray-400); --text-tertiary: var(--gray-400); @@ -551,11 +553,10 @@ html.high-contrast ::selection { 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. */ + * it. The global rule and the keyboard-modality rule for text fields sit at 2px. */ html.high-contrast :focus-visible, html.high-contrast.dark :focus-visible { - outline: 3px solid rgb(var(--text-primary)); + outline: 3px solid rgb(var(--focus-outline)); outline-offset: 2px; } /* Selection perimeters and placeholder ink used to live here, but they complete @@ -583,7 +584,7 @@ html[data-input-modality='keyboard'].high-contrast ), textarea ):not(.lc-field):focus-visible { - outline: 3px solid rgb(var(--text-primary)) !important; + outline: 3px solid rgb(var(--focus-control)) !important; outline-offset: 2px !important; } /* The WCAG 1.4.1 link treatment moved to @@ -2461,35 +2462,25 @@ html[data-input-modality='keyboard'] ), textarea ):not(.lc-field):focus-visible { - outline: 2px solid rgb(var(--text-primary)) !important; + outline: 2px solid rgb(var(--focus-control)) !important; outline-offset: 2px !important; } -/* Black and white are the default theme's focus outline. A theme that names its - * own `ring-primary` (`data-theme-ring` on the root) draws the outline in it, - * at the same specificity and layer as the rule it recolours, so every utility - * that beat the outline before still does. A theme that leaves the ring to the - * default keeps black and white, and the contrast modes keep their own rule. */ +/* The focus outline is the theme's `focus-outline` role: black and white in the + * default theme, and whatever a theme names, or its `ring-primary` when it names + * only that (see `resolveTheme`). The contrast modes keep their own 3px rule. */ @layer base { :focus-visible { - outline: 2px solid #000; + outline: 2px solid rgb(var(--focus-outline)); outline-offset: 2px; } - - :where(html[data-theme-ring]:not(.high-contrast)) :focus-visible { - outline-color: rgb(var(--ring-primary)); - } } .dark :focus-visible { - outline: 2px solid #fff; + outline: 2px solid rgb(var(--focus-outline)); outline-offset: 2px; } -.dark:where([data-theme-ring]:not(.high-contrast)) :focus-visible { - outline-color: rgb(var(--ring-primary)); -} - .popover-ui { display: flex; max-height: min(var(--popover-available-height, 1700px), 1700px); @@ -2530,7 +2521,7 @@ html[data-input-modality='keyboard'] .popover-ui:focus-visible, .popover-ui[data-focus-visible] { - outline: 2px solid rgb(var(--text-primary)); + outline: 2px solid rgb(var(--focus-control)); outline-offset: -1px; } diff --git a/e2e/specs/mock/scenarios/focus-outline.spec.ts b/e2e/specs/mock/scenarios/focus-outline.spec.ts index 31c448c7be..3bf1b5085f 100644 --- a/e2e/specs/mock/scenarios/focus-outline.spec.ts +++ b/e2e/specs/mock/scenarios/focus-outline.spec.ts @@ -4,11 +4,13 @@ import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/cl import { NEW_CHAT_PATH } from '../helpers'; /** - * The app-wide keyboard focus outline. The default light and dark themes draw it in black and - * white, a theme definition that names its own `ring-primary` draws it in that ring, one that - * leaves the ring to the default keeps black and white, and the contrast modes keep their heavier - * text-colored outline. The probe is a bare button reached with Tab, so nothing but the - * global rule styles its outline. + * The app-wide keyboard focus outline and the shared primitives' focus ring, the `focus-outline` + * and `focus-control` theme roles. The default light and dark themes draw the outline in black and + * white and the ring in their primary ink, a theme definition that names only its own + * `ring-primary` draws the outline in that ring, one that leaves the ring to the default keeps + * black and white, one that names the roles draws both in them, and the contrast modes keep their + * heavier outline. The probes are bare buttons reached with Tab, so nothing but the global rule + * and the primitives' ring classes styles them. */ type Appearance = 'light' | 'dark' | 'high-contrast-light' | 'high-contrast-dark'; @@ -25,6 +27,28 @@ const CUSTOM_RING_THEME = { }, } as const; +/** Names the roles apart from its ring and ink, so an outline or ring that followed either shows. */ +const FOCUS_ROLE_THEME = { + version: 1, + name: 'e2e-focus-roles', + modes: { + light: { + colors: { + 'rgb-ring-primary': '10 20 30', + 'rgb-focus-outline': '180 0 110', + 'rgb-focus-control': '0 90 160', + }, + }, + dark: { + colors: { + 'rgb-ring-primary': '200 210 220', + 'rgb-focus-outline': '255 140 200', + 'rgb-focus-control': '120 200 255', + }, + }, + }, +} as const; + /** Leaves `rgb-ring-primary` to the default, which resolves to a gray too dim for a dark surface. */ const RINGLESS_THEME = { version: 1, @@ -84,6 +108,36 @@ async function keyboardFocusOutline(page: Page): Promise { }); } +/** The ring classes `Checkbox`, `Switch` and `IconButton` draw keyboard focus with. */ +const CONTROL_RING_CLASSES = + 'focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control'; + +/** Tabs onto a bare button carrying the primitives' ring classes and reads the ring's color. */ +async function keyboardFocusRing(page: Page): Promise { + const id = `${PROBE}-ring`; + await page.evaluate( + ([probeId, classes]) => { + const sentinel = document.createElement('span'); + sentinel.tabIndex = -1; + const probe = document.createElement('button'); + probe.id = probeId; + probe.className = classes; + probe.textContent = 'Ring probe'; + document.body.prepend(sentinel, probe); + sentinel.focus(); + }, + [id, CONTROL_RING_CLASSES], + ); + await page.keyboard.press('Tab'); + + const probe = page.locator(`#${id}`); + await expect(probe).toBeFocused(); + const shadow = await probe.evaluate((node) => getComputedStyle(node).boxShadow); + /** Tailwind lists transparent offset and shadow layers beside the ring; the ring is the opaque one. */ + const layers = shadow.match(/rgba?\([^)]*\)/g) ?? []; + return layers.find((color) => !/,\s*0\)$/.test(color)) ?? shadow; +} + async function openChat(page: Page, appearance: Appearance, definition?: { name: string }) { await installAppearance(page, appearance, definition); await page.goto(NEW_CHAT_PATH, { timeout: 15000 }); @@ -173,6 +227,72 @@ test.describe('keyboard focus outline', () => { }); } + test('a theme that names the focus roles draws the outline and the control ring in them @scenario:focus-roles-follow-reference-theme', async ({ + page, + }) => { + const expected: Record<'light' | 'dark', { outline: string; ring: string }> = { + light: { outline: 'rgb(180, 0, 110)', ring: 'rgb(0, 90, 160)' }, + dark: { outline: 'rgb(255, 140, 200)', ring: 'rgb(120, 200, 255)' }, + }; + for (const mode of ['light', 'dark'] as const) { + const modePage = mode === 'light' ? page : await page.context().newPage(); + await openChat(modePage, mode, FOCUS_ROLE_THEME); + + expect(await keyboardFocusOutline(modePage)).toEqual(outline(expected[mode].outline)); + expect(await keyboardFocusRing(modePage)).toBe(expected[mode].ring); + } + }); + + /** Each tag is written out whole: the runner finds a scenario by its literal tag. */ + const RING_CASES: Array<{ + title: string; + appearance: Appearance; + definition?: { name: string }; + ring: string; + }> = [ + { + title: + 'the default light theme keeps its primitives ring in the primary ink @scenario:focus-control-default-light-unchanged', + appearance: 'light', + ring: 'rgb(33, 33, 33)', + }, + { + title: + 'the default dark theme keeps its primitives ring in the primary ink @scenario:focus-control-default-dark-unchanged', + appearance: 'dark', + ring: 'rgb(236, 236, 236)', + }, + { + title: + 'the ClickHouse light theme rings its primitives in the Click UI outline @scenario:focus-control-clickhouse-light', + appearance: 'light', + definition: clickHouseTheme, + ring: 'rgb(67, 126, 239)', + }, + { + title: + 'the ClickHouse dark theme rings its primitives in the Click UI outline @scenario:focus-control-clickhouse-dark', + appearance: 'dark', + definition: clickHouseTheme, + ring: 'rgb(250, 255, 105)', + }, + { + title: + 'high contrast dark rings its primitives in its white ink @scenario:focus-control-high-contrast-dark', + appearance: 'high-contrast-dark', + definition: clickHouseTheme, + ring: 'rgb(255, 255, 255)', + }, + ]; + + for (const { title, appearance, definition, ring } of RING_CASES) { + test(title, async ({ page }) => { + await openChat(page, appearance, definition); + + expect(await keyboardFocusRing(page)).toBe(ring); + }); + } + test('a custom theme draws focus in the ring it defines, in both modes @scenario:focus-outline-follows-custom-theme-ring', async ({ page, }) => { diff --git a/packages/client/src/components/AlertDialog.tsx b/packages/client/src/components/AlertDialog.tsx index 4b957750fd..6e6bbee22c 100644 --- a/packages/client/src/components/AlertDialog.tsx +++ b/packages/client/src/components/AlertDialog.tsx @@ -147,7 +147,7 @@ const AlertDialogAction: React.ForwardRefExoticComponent< {/* Gradient overlay */} diff --git a/packages/client/src/components/Checkbox.tsx b/packages/client/src/components/Checkbox.tsx index b70a6f81ff..ff0dcfc225 100644 --- a/packages/client/src/components/Checkbox.tsx +++ b/packages/client/src/components/Checkbox.tsx @@ -27,7 +27,7 @@ const Checkbox: React.ForwardRefExoticComponent< span]:w-auto [&>svg]:hidden' : '', - 'bg-surface-secondary text-text-primary hover:bg-surface-hover focus-visible:ring-text-primary focus-visible:ring-2', + 'bg-surface-secondary text-text-primary hover:bg-surface-hover focus-visible:ring-focus-control focus-visible:ring-2', )} > diff --git a/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx b/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx index a75b76243b..009e8debba 100644 --- a/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx +++ b/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx @@ -73,7 +73,7 @@ class DataTableErrorBoundaryInner extends Component< aria-labelledby="datatable-error-title" aria-describedby="datatable-error-desc" tabIndex={-1} - className="border-border-light bg-surface-primary-alt before:bg-surface-destructive/80 focus:ring-text-primary relative w-full max-w-md overflow-hidden rounded-lg border p-6 shadow-xs outline-hidden before:absolute before:top-0 before:left-0 before:h-full before:w-1 focus:ring-2 focus:ring-offset-2" + className="border-border-light bg-surface-primary-alt before:bg-surface-destructive/80 focus:ring-focus-control relative w-full max-w-md overflow-hidden rounded-lg border p-6 shadow-xs outline-hidden before:absolute before:top-0 before:left-0 before:h-full before:w-1 focus:ring-2 focus:ring-offset-2" >
diff --git a/packages/client/src/components/Dialog.tsx b/packages/client/src/components/Dialog.tsx index b8ce440457..49fb1fa2a2 100644 --- a/packages/client/src/components/Dialog.tsx +++ b/packages/client/src/components/Dialog.tsx @@ -73,7 +73,7 @@ const DialogContent: React.ForwardRefExoticComponent< > {children} {showCloseButton && ( - + @@ -147,7 +147,7 @@ const DialogClose: React.ForwardRefExoticComponent< 'border-border-light text-text-primary hover:bg-surface-hover mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', className ?? '', /* Important: for accessibility */ - 'focus:ring-text-primary focus:ring-2 focus:ring-offset-2', + 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', )} {...props} /> @@ -165,10 +165,10 @@ const DialogButton: React.ForwardRefExoticComponent< ref={ref} variant="outline" className={cn( - 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-text-primary mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', + 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-focus-control mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', className ?? '', /* Important: for accessibility */ - 'focus:ring-text-primary focus:ring-2 focus:ring-offset-2', + 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', )} {...props} /> diff --git a/packages/client/src/components/Dropdown.css b/packages/client/src/components/Dropdown.css index 8f43d01df5..62d1d2af7a 100644 --- a/packages/client/src/components/Dropdown.css +++ b/packages/client/src/components/Dropdown.css @@ -46,7 +46,7 @@ html.high-contrast .popover-ui { .popover-ui:focus-visible, .popover-ui[data-focus-visible] { - outline: 2px solid rgb(var(--text-primary)); + outline: 2px solid rgb(var(--focus-control)); outline-offset: -1px; } diff --git a/packages/client/src/components/Field.ts b/packages/client/src/components/Field.ts index de83c9d3c8..c2177e8ffd 100644 --- a/packages/client/src/components/Field.ts +++ b/packages/client/src/components/Field.ts @@ -7,7 +7,7 @@ * palette can raise it to the 3:1 non-text floor without touching separators. */ export const fieldBase: string = - 'lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-text-primary disabled:cursor-not-allowed disabled:opacity-50'; + 'lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control disabled:cursor-not-allowed disabled:opacity-50'; /** A single-line control sized to sit in a form row, matching `Input`. */ export const fieldControl: string = `${fieldBase} h-10 bg-transparent`; diff --git a/packages/client/src/components/IconButton.tsx b/packages/client/src/components/IconButton.tsx index f1910c47b3..b3c2fc8af0 100644 --- a/packages/client/src/components/IconButton.tsx +++ b/packages/client/src/components/IconButton.tsx @@ -19,7 +19,7 @@ type IconButtonVariantProps = { }; const iconButtonVariants: (props?: IconButtonVariantProps & ClassProp) => string = cva( - 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', + 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', { variants: { variant: { diff --git a/packages/client/src/components/InfoHoverCard.tsx b/packages/client/src/components/InfoHoverCard.tsx index 4666d09e11..b4536ca3e0 100644 --- a/packages/client/src/components/InfoHoverCard.tsx +++ b/packages/client/src/components/InfoHoverCard.tsx @@ -28,7 +28,7 @@ const InfoHoverCard = ({
)} diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsx index f8080df1c2..12b66cc65b 100644 --- a/packages/client/src/components/OriginalDialog.tsx +++ b/packages/client/src/components/OriginalDialog.tsx @@ -370,7 +370,7 @@ const DialogContent: React.ForwardRefExoticComponent< aria-hidden="true" /> {showCloseButton && ( - + diff --git a/packages/client/src/components/Radio.tsx b/packages/client/src/components/Radio.tsx index 908c28a157..86070ff093 100644 --- a/packages/client/src/components/Radio.tsx +++ b/packages/client/src/components/Radio.tsx @@ -188,7 +188,7 @@ const Radio: React.NamedExoticComponent = memo(function Radio({ onClick={() => handleChange(option.value)} onKeyDown={(event) => handleKeyDown(event, index)} disabled={disabled} - className={`focus-visible:ring-text-primary relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-hidden ${ + className={`focus-visible:ring-focus-control relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-hidden ${ currentValue === option.value ? 'text-text-primary' : 'text-text-secondary' } ${disabled ? 'cursor-not-allowed opacity-50' : ''} ${fullWidth ? 'flex-1' : ''} ${buttonClassName}`} > diff --git a/packages/client/src/components/Resizable.tsx b/packages/client/src/components/Resizable.tsx index 097228b45e..deef6c61ad 100644 --- a/packages/client/src/components/Resizable.tsx +++ b/packages/client/src/components/Resizable.tsx @@ -22,7 +22,7 @@ const ResizableHandle = ({ }): JSX.Element => ( ( diff --git a/packages/client/src/components/Slider.tsx b/packages/client/src/components/Slider.tsx index dbdf2fe97b..4ae8afba7e 100644 --- a/packages/client/src/components/Slider.tsx +++ b/packages/client/src/components/Slider.tsx @@ -48,7 +48,7 @@ const Slider: React.ForwardRefExoticComponent ( ({ @@ -71,7 +72,6 @@ beforeEach(() => { document.documentElement.removeAttribute('class'); document.documentElement.removeAttribute('style'); document.documentElement.removeAttribute('data-theme'); - document.documentElement.removeAttribute('data-theme-ring'); window.matchMedia = jest.fn(() => matchMedia(false)); }); @@ -1138,8 +1138,10 @@ describe('ThemeProvider', () => { expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark'); expect(matchMediaSpy).toHaveBeenCalled(); }); - describe('the ring mark the global focus outline follows', () => { - it('marks only the modes whose definition names its ring, and clears it on unmount', async () => { + describe('the focus outline a theme paints', () => { + const focusOutline = () => document.documentElement.style.getPropertyValue('--focus-outline'); + + it('follows the ring of the mode that names one, and clears on unmount', async () => { const { unmount } = render( { ); await waitFor(() => { - expect(document.documentElement).toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe('10 20 30'); }); act(() => screen.getByRole('button', { name: 'Dark' }).click()); @@ -1166,14 +1168,14 @@ describe('ThemeProvider', () => { expect(document.documentElement).toHaveClass('dark'); }); expect(document.documentElement.dataset.theme).toBe('ringed'); - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(darkTheme['rgb-focus-outline']); unmount(); - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(''); }); - it('marks legacy RGB props only when they carry a ring', async () => { + it('follows a legacy RGB ring only when the props carry one', async () => { const { rerender } = render( { ); await waitFor(() => { - expect(document.documentElement).toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe('1 2 3'); }); rerender( @@ -1199,7 +1201,7 @@ describe('ThemeProvider', () => { ); await waitFor(() => { - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(''); }); expect(document.documentElement.dataset.theme).toBe('legacy'); }); diff --git a/packages/client/src/theme/context/ThemeProvider.tsx b/packages/client/src/theme/context/ThemeProvider.tsx index 2fca707987..82467fbe21 100644 --- a/packages/client/src/theme/context/ThemeProvider.tsx +++ b/packages/client/src/theme/context/ThemeProvider.tsx @@ -16,11 +16,7 @@ import { resolveTheme, validateThemeDefinition, } from '../registry'; -import applyTheme, { - applyResolvedTheme, - themeOwnedProperties, - THEME_RING_ATTRIBUTE, -} from '../utils/applyTheme'; +import applyTheme, { applyResolvedTheme, themeOwnedProperties } from '../utils/applyTheme'; import { defaultTheme } from '../themes/default'; import { darkTheme } from '../themes/dark'; import '../highContrast.css'; @@ -52,7 +48,6 @@ type ThemeDOMSnapshot = { properties: Map; colorScheme: { value: string; priority: string }; dataTheme: string | null; - themeRing: boolean; }; type ThemeClassSnapshot = { @@ -287,7 +282,6 @@ const captureThemeDOM = (root: HTMLElement): ThemeDOMSnapshot => ({ priority: root.style.getPropertyPriority('color-scheme'), }, dataTheme: root.getAttribute('data-theme'), - themeRing: root.hasAttribute(THEME_RING_ATTRIBUTE), }); const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => { @@ -314,7 +308,6 @@ const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => } else { root.setAttribute('data-theme', snapshot.dataTheme); } - root.toggleAttribute(THEME_RING_ATTRIBUTE, snapshot.themeRing); }; export function ThemeProvider({ @@ -648,16 +641,11 @@ export function ThemeProvider({ if (!highContrast && legacyThemeRGB) { applyTheme(legacyThemeRGB, root, mode === 'dark' ? darkTheme : defaultTheme); root.dataset.theme = definition.name; - root.toggleAttribute(THEME_RING_ATTRIBUTE, legacyThemeRGB['rgb-ring-primary'] != null); return; } try { applyResolvedTheme(resolveTheme(definition, mode), root); - root.toggleAttribute( - THEME_RING_ATTRIBUTE, - definition.modes[mode]?.colors?.['rgb-ring-primary'] != null, - ); } catch (error) { restoreAppliedTheme(root); console.error('Unable to apply theme definition', error); diff --git a/packages/client/src/theme/controls.css b/packages/client/src/theme/controls.css index a2f562e7ff..b1dbd7041b 100644 --- a/packages/client/src/theme/controls.css +++ b/packages/client/src/theme/controls.css @@ -1,9 +1,13 @@ /** - * Stylesheet defaults for `--border-control`, the form-control boundary role. + * Stylesheet defaults for the roles the package's own primitives paint: + * `--border-control`, the form-control boundary, and `--focus-control`, the + * keyboard focus ring of `Checkbox`, `Switch`, `Field` and their siblings. * - * Every other color role is declared by the app stylesheet, but this one ships - * with the package so a consumer rendering `Input`, `Select` or `InputOTP` gets - * an outline without restating it. The stock values match `border-light`. + * Every other color role is declared by the app stylesheet, but these ship + * with the package so a consumer rendering `Input`, `Select` or `Checkbox` gets + * an outline and a focus ring without restating them. The stock boundary + * matches `border-light`, and the stock ring matches `text-primary`, the ink + * the primitives drew their ring in before the role existed. * `ThemeProvider` paints the registry value inline whenever a theme is active, * which outranks these; they only cover the stock palette before and without a * theme definition, and `semanticTokens.spec.ts` keeps them in step with @@ -11,8 +15,10 @@ */ html { --border-control: 227 227 227; + --focus-control: 33 33 33; } .dark { --border-control: 33 33 33; + --focus-control: 236 236 236; } diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.ts index 2dd7e3c5b1..431ec8f89b 100644 --- a/packages/client/src/theme/registry.spec.ts +++ b/packages/client/src/theme/registry.spec.ts @@ -291,6 +291,69 @@ describe('theme registry', () => { expect(resolved.colors['rgb-border-control']).toBe(darkTheme['rgb-border-control']); }); + it('draws the focus outline in the ring of a theme that predates the role', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'ring-only-reference', + modes: { dark: { colors: { 'rgb-ring-primary': '200 210 220' } } }, + }, + 'dark', + ); + + expect(resolved.colors['rgb-focus-outline']).toBe('200 210 220'); + }); + + it('draws the control focus ring in the ink of a theme that predates the role', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'ink-only-reference', + modes: { light: { colors: { 'rgb-text-primary': '20 30 40' } } }, + }, + 'light', + ); + + expect(resolved.colors['rgb-focus-control']).toBe('20 30 40'); + }); + + it('gives a theme that names neither the bundled focus roles', () => { + const light = resolveTheme( + { + version: 1, + name: 'focusless-reference', + modes: { light: { colors: { 'rgb-accent-primary': '1 2 3' } } }, + }, + 'light', + ); + + expect(light.colors['rgb-focus-outline']).toBe('0 0 0'); + expect(light.colors['rgb-focus-control']).toBe(defaultTheme['rgb-text-primary']); + }); + + it('preserves explicit focus roles over the ring and ink they would follow', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'focus-reference', + modes: { + light: { + colors: { + 'rgb-ring-primary': '10 20 30', + 'rgb-text-primary': '40 50 60', + 'rgb-focus-outline': '200 0 120', + 'rgb-focus-control': '0 120 200', + }, + }, + }, + }, + 'light', + ); + + expect(resolved.colors['rgb-focus-outline']).toBe('200 0 120'); + expect(resolved.colors['rgb-focus-control']).toBe('0 120 200'); + }); + it('preserves an explicit control outline', () => { const resolved = resolveTheme( { diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.ts index 5a45609723..78e1a39cdd 100644 --- a/packages/client/src/theme/registry.ts +++ b/packages/client/src/theme/registry.ts @@ -88,6 +88,22 @@ export function controlBorderFallback(colors: IThemeRGB): string | undefined { return colors['rgb-border-light'] ?? colors['rgb-border-medium']; } +/** + * The focus roles for a stored or environment theme that predates them. The + * global outline followed a theme's `rgb-ring-primary` whenever it named one, + * and the shared primitives drew their ring in `rgb-text-primary`, so a theme + * that painted either keeps that focus color. A theme that painted neither + * keeps the bundled roles, and one that names a role keeps it as written. + */ +export function focusFallbacks(colors: IThemeRGB): IThemeRGB { + const outline = colors['rgb-focus-outline'] ?? colors['rgb-ring-primary']; + const control = colors['rgb-focus-control'] ?? colors['rgb-text-primary']; + return { + ...(outline !== undefined ? { 'rgb-focus-outline': outline } : {}), + ...(control !== undefined ? { 'rgb-focus-control': control } : {}), + }; +} + export const themeAppearanceProperties: Readonly< Record > = Object.freeze({ @@ -339,6 +355,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT customColors != null ? controlBorderFallback(customColors) : undefined; const borderControlFallback = borderControlSource !== undefined ? { 'rgb-border-control': borderControlSource } : {}; + const focusFallback = customColors != null ? focusFallbacks(customColors) : {}; /** * Slot 8 arrived after the seven-slot scale shipped, so a stored or * environment theme that paints its own scale cannot name it. Filling the @@ -399,6 +416,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT ...chartWidgetSurfaceFallback, ...chartWidgetStrokeFallback, ...borderControlFallback, + ...focusFallback, ...seriesEightFallback, ...verifiedFallback, } as Required, diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.ts index c2ede2be94..a85356bf56 100644 --- a/packages/client/src/theme/semanticTokens.spec.ts +++ b/packages/client/src/theme/semanticTokens.spec.ts @@ -136,7 +136,7 @@ describe('shared field and dropdown interaction styles', () => { expect(field).toMatch(/\bborder-border-control\b/); expect(field).not.toMatch(/\bborder-border-(?:light|medium)\b/); expect(field).toMatch(/focus-visible:ring-2/); - expect(field).toMatch(/focus-visible:ring-text-primary/); + expect(field).toMatch(/focus-visible:ring-focus-control/); const composers: Array<[string, RegExp]> = [ ['Input.tsx', /\bfieldControl\b/], @@ -161,7 +161,7 @@ describe('shared field and dropdown interaction styles', () => { ); expect(appStyles).toMatch(/html\[data-input-modality='pointer'\]/); expect(appStyles).toMatch(/html\[data-input-modality='keyboard'\]/); - expect(appStyles).toMatch(/outline:\s*2px solid rgb\(var\(--text-primary\)\) !important;/); + expect(appStyles).toMatch(/outline:\s*2px solid rgb\(var\(--focus-control\)\) !important;/); expect(appStyles).not.toMatch(/textarea\s*\n\):hover,/); }); @@ -652,3 +652,52 @@ describe('control border defaults', () => { expect(declared).toEqual([defaultTheme['rgb-border-control'], darkTheme['rgb-border-control']]); }); }); + +/** WCAG 2.4.13 holds a focus indicator to 3:1 against what it is drawn on. The + * global outline and the primitives' ring are theme roles, so every bundled + * palette carries both at that floor on its canvases. */ +describe.each([ + ['default light', defaultTheme], + ['default dark', darkTheme], + ['high contrast light', highContrastLightTheme], + ['high contrast dark', highContrastDarkTheme], + ['clickhouse light', clickHouseLightTheme], + ['clickhouse dark', clickHouseDarkTheme], +])('%s focus roles', (_name, theme: IThemeRGB) => { + it.each(['rgb-focus-outline', 'rgb-focus-control'] as const)( + 'keeps %s at the 3:1 floor on every canvas', + (role) => { + const focus = toRgb(theme, role); + const failures = canvasSurfaces.flatMap((surface) => { + const ratio = contrast(focus, toRgb(theme, surface)); + return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : []; + }); + + expect(failures).toEqual([]); + }, + ); +}); + +describe('focus role defaults', () => { + /** The default theme's outline was literal black and white and its primitives + * drew their ring in the primary ink; the roles reproduce both. */ + it('reproduces the outline and ring the default theme drew before the roles', () => { + expect([defaultTheme['rgb-focus-outline'], darkTheme['rgb-focus-outline']]).toEqual([ + '0 0 0', + '255 255 255', + ]); + expect([defaultTheme['rgb-focus-control'], darkTheme['rgb-focus-control']]).toEqual([ + defaultTheme['rgb-text-primary'], + darkTheme['rgb-text-primary'], + ]); + }); + + it('keeps the package CSS in step with the runtime themes', () => { + const controls = readFileSync(join(__dirname, 'controls.css'), 'utf8'); + const declared = [...controls.matchAll(/--focus-control:\s*([^;]+);/g)].map((match) => + match[1].trim(), + ); + + expect(declared).toEqual([defaultTheme['rgb-focus-control'], darkTheme['rgb-focus-control']]); + }); +}); diff --git a/packages/client/src/theme/themes/clickhouse.ts b/packages/client/src/theme/themes/clickhouse.ts index e9819fc62e..704e336213 100644 --- a/packages/client/src/theme/themes/clickhouse.ts +++ b/packages/client/src/theme/themes/clickhouse.ts @@ -50,6 +50,8 @@ export const clickHouseLightTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '67 126 239', // #437eef (outline.default) + 'rgb-focus-outline': '67 126 239', // #437eef (outline.default) + 'rgb-focus-control': '67 126 239', // #437eef (outline.default) // Header colors 'rgb-header-primary': '255 255 255', // #ffffff (background.default) @@ -170,6 +172,8 @@ export const clickHouseDarkTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '250 255 105', // #faff69 (outline.default) + 'rgb-focus-outline': '250 255 105', // #faff69 (outline.default) + 'rgb-focus-control': '250 255 105', // #faff69 (outline.default) // Header colors 'rgb-header-primary': '31 31 28', // #1f1f1c (background.default) diff --git a/packages/client/src/theme/themes/clickui.spec.ts b/packages/client/src/theme/themes/clickui.spec.ts index 47bed8cfc8..4debd99d6d 100644 --- a/packages/client/src/theme/themes/clickui.spec.ts +++ b/packages/client/src/theme/themes/clickui.spec.ts @@ -35,6 +35,8 @@ const colorSources: Record>> 'rgb-accent-primary': 'global.color.accent.default', 'rgb-accent-primary-hover': 'palette.neutral.712', 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-focus-outline': 'global.color.outline.default', + 'rgb-focus-control': 'global.color.outline.default', 'rgb-header-primary': 'global.color.background.default', 'rgb-header-hover': 'global.color.background.muted', 'rgb-header-button-hover': 'global.color.background.muted', @@ -131,6 +133,8 @@ const colorSources: Record>> 'rgb-accent-primary': 'global.color.accent.default', 'rgb-accent-primary-hover': 'palette.brand.200', 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-focus-outline': 'global.color.outline.default', + 'rgb-focus-control': 'global.color.outline.default', 'rgb-header-primary': 'global.color.background.default', 'rgb-header-hover': 'global.color.background.muted', 'rgb-header-button-hover': 'global.color.background.muted', diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.ts index 1365fba855..56469f4548 100644 --- a/packages/client/src/theme/themes/dark.ts +++ b/packages/client/src/theme/themes/dark.ts @@ -25,6 +25,8 @@ export const darkTheme: IThemeRGB = { // Ring colors (not defined in dark mode, using default) 'rgb-ring-primary': '89 89 89', // #595959 (gray-500) + 'rgb-focus-outline': '255 255 255', // #ffffff + 'rgb-focus-control': '236 236 236', // #ececec (gray-100) // Header colors 'rgb-header-primary': '47 47 47', // #2f2f2f (gray-700) diff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.ts index 29659facff..410a282ca5 100644 --- a/packages/client/src/theme/themes/default.ts +++ b/packages/client/src/theme/themes/default.ts @@ -25,6 +25,8 @@ export const defaultTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '89 89 89', // #595959 (gray-500) + 'rgb-focus-outline': '0 0 0', // #000000 + 'rgb-focus-control': '33 33 33', // #212121 (gray-800) // Header colors 'rgb-header-primary': '255 255 255', // #fff (white) diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.ts index 93d220caab..2893b71863 100644 --- a/packages/client/src/theme/themes/highContrast.ts +++ b/packages/client/src/theme/themes/highContrast.ts @@ -51,6 +51,8 @@ export const highContrastLightTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '0 0 0', // #000000 + 'rgb-focus-outline': '0 0 0', // #000000 + 'rgb-focus-control': '0 0 0', // #000000 // Header colors 'rgb-header-primary': '255 255 255', // #ffffff @@ -197,6 +199,8 @@ export const highContrastDarkTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '255 255 255', // #ffffff + 'rgb-focus-outline': '255 255 255', // #ffffff + 'rgb-focus-control': '255 255 255', // #ffffff // Header colors 'rgb-header-primary': '0 0 0', // #000000 diff --git a/packages/client/src/theme/tokens.css b/packages/client/src/theme/tokens.css index 5df3b7129a..f4b46d75aa 100644 --- a/packages/client/src/theme/tokens.css +++ b/packages/client/src/theme/tokens.css @@ -21,6 +21,8 @@ --color-accent-primary: rgb(var(--accent-primary)); --color-accent-primary-hover: rgb(var(--accent-primary-hover)); --color-ring-primary: rgb(var(--ring-primary)); + --color-focus-outline: rgb(var(--focus-outline)); + --color-focus-control: rgb(var(--focus-control)); --color-header-primary: rgb(var(--header-primary)); --color-header-hover: rgb(var(--header-hover)); --color-header-button-hover: rgb(var(--header-button-hover)); diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.ts index 7ba250a8fa..b782f3dc16 100644 --- a/packages/client/src/theme/types/index.ts +++ b/packages/client/src/theme/types/index.ts @@ -26,6 +26,8 @@ export interface IThemeRGB { // Ring colors 'rgb-ring-primary'?: string; + 'rgb-focus-outline'?: string; + 'rgb-focus-control'?: string; // Header colors 'rgb-header-primary'?: string; @@ -172,6 +174,8 @@ export interface IThemeVariables { '--accent-primary': string; '--accent-primary-hover': string; '--ring-primary': string; + '--focus-outline': string; + '--focus-control': string; '--header-primary': string; '--header-hover': string; '--header-button-hover': string; @@ -278,6 +282,8 @@ export interface IThemeColors { 'accent-primary'?: string; 'accent-primary-hover'?: string; 'ring-primary'?: string; + 'focus-outline'?: string; + 'focus-control'?: string; 'header-primary'?: string; 'header-hover'?: string; 'header-button-hover'?: string; diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts index dacbd0a84a..8eed809fc4 100644 --- a/packages/client/src/theme/utils/applyTheme.ts +++ b/packages/client/src/theme/utils/applyTheme.ts @@ -1,6 +1,7 @@ import type { IThemeAppearance, IThemeBrands, IThemeRGB, ResolvedThemeDefinition } from '../types'; import { controlBorderFallback, + focusFallbacks, MARK_NEIGHBOURHOOD, themeAppearanceProperties, themeBrandTokens, @@ -76,6 +77,14 @@ function mapColors(colors: IThemeRGB, base?: IThemeRGB): Array<[string, string]> variables.push(['--border-control', legacyControlBorder]); } + const focus = focusFallbacks(colors); + if (colors['rgb-focus-outline'] === undefined && focus['rgb-focus-outline'] !== undefined) { + variables.push(['--focus-outline', focus['rgb-focus-outline']]); + } + if (colors['rgb-focus-control'] === undefined && focus['rgb-focus-control'] !== undefined) { + variables.push(['--focus-control', focus['rgb-focus-control']]); + } + /** * Same rule as `resolveTheme`: a theme that paints what the mark is measured * against coordinated the `status-success-strong` the mark wore before it had @@ -104,17 +113,9 @@ function mapAppearance(appearance: IThemeAppearance): Array<[string, string]> { ]); } -/** - * Marks a root whose applied theme names its own `rgb-ring-primary`. The app's global focus - * outline follows the ring only then: a theme that leaves the ring to the default resolves it to a - * mid gray that a dark surface cannot carry at 3:1, so it keeps the default outline instead. - */ -export const THEME_RING_ATTRIBUTE = 'data-theme-ring'; - export function clearAppliedTheme(root: HTMLElement = document.documentElement): void { themeOwnedProperties.forEach((property) => root.style.removeProperty(property)); root.removeAttribute('data-theme'); - root.removeAttribute(THEME_RING_ATTRIBUTE); } export function applyResolvedTheme( diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.ts index e1b321dea5..46ea02e755 100644 --- a/packages/data-provider/src/theme.ts +++ b/packages/data-provider/src/theme.ts @@ -29,6 +29,8 @@ export const themeColorTokens = Object.freeze([ 'rgb-accent-primary', 'rgb-accent-primary-hover', 'rgb-ring-primary', + 'rgb-focus-outline', + 'rgb-focus-control', 'rgb-header-primary', 'rgb-header-hover', 'rgb-header-button-hover', From 83d7afb0d13c7998b5b59d233d0d5dcf90c95523 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 16:12:24 +0200 Subject: [PATCH 06/21] =?UTF-8?q?=F0=9F=9A=A6=20feat:=20Give=20Pressed=20a?= =?UTF-8?q?nd=20Disabled=20States=20Their=20Own=20Theme=20Roles=20(#16487)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Give Pressed and Disabled States Their Own Theme Roles Add surface-pressed and surface-inverted-pressed, which IconButton takes while held under a hover. They default to the hover fills a pointer press has always shown, and a theme that names only its hovers presses in them, so the default theme is unchanged. Add surface-disabled, text-disabled and border-disabled, and a disabledStyle appearance role: dim keeps the half-opacity treatment, fill paints a disabled Checkbox, Switch, Field or IconButton in the disabled roles through the theme-disabled variant. The root mirrors the choice as data-theme-disabled. ClickHouse fills from Click UI's disabled and active tokens, cited in the drift guard. * fix: Ink Disabled Placeholders and Press the Submit Button in the State Roles * fix: Ignore Color Roles a Client Predates and Fill Every Disabled Composer Slot A cached client reading a newer server's inline theme rejected the whole definition over one color role it did not know. The client reader now ignores a well-formed rgb- role holding a triplet with a warning, as it already did for appearance keys; the server keeps rejecting unknown roles, where one is a typo in librechat.yaml. The disabled fill moves into composerSubmitClasses, so the plain send and stop buttons in Composer and DuringRunSendButton take it too. * fix: Share One Disabled Fill Recipe Across Every Shared Control Select, InputNumber, SecretInput, FilterInput and the Slider thumb only dimmed under a fill theme. The theme-disabled classes now live in one disabledFillClasses recipe that every shared control composes, and the variant also matches Radix's data-disabled so a disabled slider thumb takes the fill. The deployment-theme scenario for an invalid theme now serves a malformed color value, since a well-formed role the client predates is ignored rather than rejected. * fix: Fill a Disabled InputNumber Through Its Wrapper rc-input-number puts the component's classes on a wrapper around the disabled input, so the theme-disabled variant never matched it. Add a theme-disabled-within variant for a wrapper that contains a disabled control, and a disabledWithinFillClasses recipe InputNumber composes; the input inherits the ink and shows the fill through its transparent background. The default theme's disabled InputNumber is unchanged. * fix: Carry the Disabled Roles to Every Shared Disabled Surface Sweep every shared component that dims when disabled. Button-like controls (AlertDialog and Dialog footer buttons, DialogTemplate's select, the MultiSelect trigger) compose the fill recipe. Menu items, tabs and the send-actions rows keep their surface and take the ink through disabledInkClasses, as Click UI's genericMenu does, and Label and FilterInput's floating label follow their control through peerDisabledInkClasses. The variant also matches aria-disabled rows. OGDialogTemplate and Button stay with the open PR that owns them. * fix: Gray the Icons of Disabled Menu Rows Under a Fill Theme A send-action or menu row's icon owns its color (text-status-warning, text-text-secondary), so the inherited disabled ink left it bright. The item ink recipe now recolors descendant icons too. * fix: Fill the Dropdown Trigger and the OTP Group Under a Fill Theme The default Dropdown trigger only dimmed, and its disabled:hover resets tied with the fill; the shared recipe now pins the disabled hover fill and ink too, and the trigger composes it. InputOTP dims its group with has-[:disabled], so it takes the wrapper recipe. * fix: Reach Child-Owned Ink and Slot Edges in the Disabled Recipes A disabled control's own children, the SelectDropDown labels or a checkbox glyph, kept their explicit ink, and a disabled OTP group's slots kept their border. The fill and item recipes now carry the disabled ink to descendants, the wrapper recipe carries the disabled edge and ink to the group's parts, and SelectDropDown composes the fill recipe. * test: Probe Disabled Row Icons With the Recipe's Descendant Selector * fix: Give Radio Segments, SecretInput Actions and DropdownPopup Items the Disabled Ink These three dim their disabled state through a JS branch or Ariakit's aria-disabled rather than a disabled: utility, so the earlier sweep missed them. Each composes the item ink recipe, whose opacity reset outranks the branch's opacity-50. --- .../__tests__/DeploymentTheme.spec.tsx | 23 +- client/src/style.css | 1 + .../mock/scenarios/deployment-theme.spec.ts | 2 +- e2e/specs/mock/scenarios/state-roles.spec.ts | 315 ++++++++++++++++++ .../client/src/components/AlertDialog.tsx | 4 +- .../client/src/components/AnimatedTabs.tsx | 8 +- packages/client/src/components/Checkbox.tsx | 3 +- packages/client/src/components/Combobox.tsx | 3 +- packages/client/src/components/Dialog.tsx | 4 +- .../client/src/components/DialogTemplate.tsx | 12 +- packages/client/src/components/Dropdown.tsx | 3 +- .../client/src/components/DropdownMenu.tsx | 5 +- .../client/src/components/DropdownPopup.tsx | 4 +- packages/client/src/components/Field.ts | 5 +- .../client/src/components/FilterInput.tsx | 8 +- packages/client/src/components/IconButton.tsx | 21 +- .../client/src/components/InputNumber.tsx | 3 +- packages/client/src/components/InputOTP.tsx | 3 +- packages/client/src/components/Label.tsx | 3 +- .../client/src/components/MultiSelect.tsx | 3 +- packages/client/src/components/Radio.tsx | 3 +- .../client/src/components/SecretInput.tsx | 5 +- packages/client/src/components/Select.tsx | 4 +- .../client/src/components/SelectDropDown.tsx | 3 +- .../client/src/components/SendActions.tsx | 7 +- packages/client/src/components/Slider.tsx | 6 +- packages/client/src/components/Switch.tsx | 3 +- packages/client/src/components/Tabs.tsx | 3 +- packages/client/src/theme/README.md | 8 + .../src/theme/context/ThemeProvider.tsx | 13 +- packages/client/src/theme/controls.css | 16 +- packages/client/src/theme/registry.spec.ts | 106 +++++- packages/client/src/theme/registry.ts | 42 ++- .../client/src/theme/semanticTokens.spec.ts | 33 ++ .../client/src/theme/themes/clickhouse.ts | 12 + packages/client/src/theme/themes/clickui.json | 10 + .../client/src/theme/themes/clickui.spec.ts | 24 +- packages/client/src/theme/themes/dark.ts | 5 + packages/client/src/theme/themes/default.ts | 5 + .../client/src/theme/themes/highContrast.ts | 10 + packages/client/src/theme/tokens.css | 20 ++ packages/client/src/theme/types/index.ts | 20 ++ .../client/src/theme/utils/applyTheme.spec.ts | 33 ++ packages/client/src/theme/utils/applyTheme.ts | 24 ++ packages/client/src/utils/composer.ts | 2 + packages/client/src/utils/theme.ts | 29 ++ packages/data-provider/src/theme.ts | 76 ++++- 47 files changed, 887 insertions(+), 68 deletions(-) create mode 100644 e2e/specs/mock/scenarios/state-roles.spec.ts diff --git a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx index a38f928782..2972563466 100644 --- a/client/src/Providers/__tests__/DeploymentTheme.spec.tsx +++ b/client/src/Providers/__tests__/DeploymentTheme.spec.tsx @@ -172,10 +172,31 @@ describe('DeploymentTheme', () => { expect(snapshotStorage()).toEqual(before); }); + it('applies an inline definition carrying a color role this build predates', async () => { + serveTheme({ + ...inlineTheme, + modes: { + ...inlineTheme.modes, + light: { + ...inlineTheme.modes.light, + colors: { ...inlineTheme.modes.light.colors, 'rgb-future-role': '1 2 3' }, + }, + }, + }); + renderTheme(queryClient); + + await waitFor(() => expect(root().dataset.theme).toBe('acme')); + expect(root().style.getPropertyValue('--surface-primary')).toBe('10 20 30'); + expect(root().getAttribute('style')).not.toContain('--future-role'); + expect(warn).toHaveBeenCalledWith( + '[ThemeProvider] Unknown light color token ignored: rgb-future-role', + ); + }); + it('ignores an invalid inline definition with a warning and keeps the stored theme', async () => { serveTheme({ ...inlineTheme, - modes: { light: { colors: { 'rgb-not-a-token': '1 2 3' } } }, + modes: { light: { colors: { 'rgb-not-a-token': 'red' } } }, }); renderTheme(queryClient); diff --git a/client/src/style.css b/client/src/style.css index b02463a00e..4a5145a212 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -321,6 +321,7 @@ html { --theme-control-height: 2.25rem; --theme-space-compact: 0.375rem; --theme-space-normal: 0.75rem; + --theme-disabled-style: dim; --theme-font-family: Inter, sans-serif; /* Roboto Mono is self-hosted (the `@font-face` block below), so code renders the same on every * platform with real bold and italic faces. The tail is reached while the font loads, if it diff --git a/e2e/specs/mock/scenarios/deployment-theme.spec.ts b/e2e/specs/mock/scenarios/deployment-theme.spec.ts index 5915f03bad..3a032588b1 100644 --- a/e2e/specs/mock/scenarios/deployment-theme.spec.ts +++ b/e2e/specs/mock/scenarios/deployment-theme.spec.ts @@ -150,7 +150,7 @@ test.describe('deployment theme from librechat.yaml', () => { }); await serveTheme(page, { ...INLINE_THEME, - modes: { light: { colors: { 'rgb-not-a-token': '1 2 3' } } }, + modes: { light: { colors: { 'rgb-not-a-token': 'red' } } }, }); await openLogin(page); diff --git a/e2e/specs/mock/scenarios/state-roles.spec.ts b/e2e/specs/mock/scenarios/state-roles.spec.ts new file mode 100644 index 0000000000..72ec896309 --- /dev/null +++ b/e2e/specs/mock/scenarios/state-roles.spec.ts @@ -0,0 +1,315 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse'; +import { NEW_CHAT_PATH } from '../helpers'; + +/** + * The pressed and disabled state roles. A held control takes `surface-pressed` (or the inverted + * pressed fill), which defaults to the hover fill a pointer press has always shown. A disabled + * control dims to half opacity unless the theme's `disabledStyle` is `fill`, which paints it in + * `surface-disabled` and `text-disabled` at full opacity. The probes carry the class lists the + * shared `IconButton` and `Field` primitives compose, so only those rules style them. + */ + +type Mode = 'light' | 'dark'; + +const PRESS_CLASSES = 'bg-surface-secondary hover:bg-surface-hover hover:active:bg-surface-pressed'; +const DISABLED_CLASSES = + 'bg-transparent text-text-primary disabled:opacity-50 theme-disabled:bg-surface-disabled theme-disabled:text-text-disabled theme-disabled:opacity-100'; + +/** Names every state role apart from the hover and ink it would otherwise follow. */ +const STATE_ROLE_THEME = { + version: 1, + name: 'e2e-state-roles', + modes: { + light: { + colors: { + 'rgb-surface-hover': '200 200 200', + 'rgb-surface-pressed': '150 60 20', + 'rgb-surface-disabled': '20 150 60', + 'rgb-text-disabled': '60 20 150', + }, + appearance: { disabledStyle: 'fill' }, + }, + dark: { + colors: { + 'rgb-surface-hover': '60 60 60', + 'rgb-surface-pressed': '240 160 120', + 'rgb-surface-disabled': '120 240 160', + 'rgb-text-disabled': '160 120 240', + }, + appearance: { disabledStyle: 'fill' }, + }, + }, +} as const; + +async function openChat(page: Page, mode: Mode, definition?: { name: string }) { + await page.addInitScript( + ([appearance, stored]) => { + localStorage.setItem('color-theme', appearance as string); + localStorage.removeItem('theme-colors'); + localStorage.removeItem('theme-name'); + if (stored) { + localStorage.setItem('theme-definition', JSON.stringify(stored)); + localStorage.setItem('theme-source', 'definition'); + } else { + localStorage.removeItem('theme-definition'); + localStorage.removeItem('theme-source'); + } + }, + [mode, definition ?? null] as [string, unknown], + ); + await page.goto(NEW_CHAT_PATH, { timeout: 15000 }); + await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({ + timeout: 30000, + }); + const root = page.locator('html'); + if (definition) { + await expect(root).toHaveAttribute('data-theme', definition.name); + } else { + await expect(root).not.toHaveAttribute('data-theme'); + } + await expect(root).toHaveClass(mode === 'dark' ? /\bdark\b/ : /\blight\b/); +} + +async function addProbe(page: Page, id: string, className: string, disabled = false) { + await page.evaluate( + ([probeId, classes, isDisabled]) => { + const probe = document.createElement('button'); + probe.id = probeId as string; + probe.className = classes as string; + probe.disabled = isDisabled as boolean; + probe.textContent = 'State probe'; + probe.style.position = 'fixed'; + probe.style.top = '8px'; + probe.style.left = '8px'; + probe.style.zIndex = '2147483647'; + document.body.append(probe); + }, + [id, className, disabled] as [string, string, boolean], + ); + return page.locator(`#${id}`); +} + +/** + * Holds the pointer down on a hovered probe and reads its fill. Tailwind gates `hover:` behind + * `(hover: hover)`, so on a touch device neither the hover nor the pressed fill applies and the + * probe keeps its resting fill, as it always has; `null` marks that case. + */ +async function pressedFill(page: Page): Promise { + if (!(await page.evaluate(() => matchMedia('(hover: hover)').matches))) { + return null; + } + const probe = await addProbe(page, 'state-press-probe', PRESS_CLASSES); + const box = await probe.boundingBox(); + if (!box) { + throw new Error('press probe has no box'); + } + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + const fill = await probe.evaluate((node) => getComputedStyle(node).backgroundColor); + await page.mouse.up(); + return fill; +} + +/** The ink an empty disabled field shows is its placeholder, which `Field` colors on its own. */ +const PLACEHOLDER_CLASSES = + 'placeholder:text-text-secondary disabled:opacity-50 theme-disabled:placeholder:text-text-disabled'; + +async function disabledLook(page: Page) { + const probe = await addProbe(page, 'state-disabled-probe', DISABLED_CLASSES, true); + const look = await probe.evaluate((node) => { + const style = getComputedStyle(node); + return { fill: style.backgroundColor, ink: style.color, opacity: style.opacity }; + }); + const placeholder = await page.evaluate((classes) => { + const field = document.createElement('input'); + field.className = classes; + field.placeholder = 'Disabled field'; + field.disabled = true; + document.body.append(field); + const color = getComputedStyle(field, '::placeholder').color; + field.remove(); + return color; + }, PLACEHOLDER_CLASSES); + /** Radix marks a disabled part that is not a form control, a slider thumb, with `data-disabled`. */ + const part = await page.evaluate(() => { + const thumb = document.createElement('span'); + thumb.className = 'bg-surface-primary theme-disabled:bg-surface-disabled'; + thumb.setAttribute('data-disabled', ''); + document.body.append(thumb); + const fill = getComputedStyle(thumb).backgroundColor; + thumb.remove(); + return fill; + }); + /** `InputNumber` styles a wrapper whose disabled input sits inside it. */ + const wrapper = await page.evaluate(() => { + const box = document.createElement('div'); + box.className = + 'bg-transparent text-text-primary theme-disabled-within:bg-surface-disabled theme-disabled-within:text-text-disabled theme-disabled-within:[&_*]:border-border-disabled'; + const field = document.createElement('input'); + field.disabled = true; + const slot = document.createElement('div'); + slot.className = 'border border-border-control'; + box.append(field, slot); + document.body.append(box); + const style = getComputedStyle(box); + const result = `${style.backgroundColor} ${getComputedStyle(field).color} ${getComputedStyle(slot).borderTopColor}`; + box.remove(); + return result; + }); + /** A menu item keeps its surface and grays its text; a label follows its control through `peer`. */ + const items = await page.evaluate(() => { + const item = document.createElement('div'); + item.className = + 'text-text-primary theme-disabled:text-text-disabled theme-disabled:[&_*]:text-text-disabled'; + item.setAttribute('data-disabled', ''); + const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + icon.setAttribute('class', 'text-status-warning'); + item.append(icon); + const field = document.createElement('input'); + field.className = 'peer'; + field.disabled = true; + const label = document.createElement('label'); + label.className = 'text-text-secondary peer-theme-disabled:text-text-disabled'; + document.body.append(item, field, label); + const result = `${getComputedStyle(icon).color} ${getComputedStyle(label).color}`; + item.remove(); + field.remove(); + label.remove(); + return result; + }); + return { ...look, placeholder, part, wrapper, items }; +} + +/** Each tag is written out whole: the runner finds a scenario by its literal tag. */ +const CASES: Array<{ + title: string; + mode: Mode; + definition?: { name: string }; + pressed: string; + disabled: { + fill: string; + ink: string; + opacity: string; + placeholder: string; + part: string; + wrapper: string; + items: string; + }; +}> = [ + { + title: + 'the default light theme presses in its hover fill and dims disabled controls @scenario:state-roles-default-light-unchanged', + mode: 'light', + pressed: 'rgb(227, 227, 227)', + disabled: { + fill: 'rgba(0, 0, 0, 0)', + ink: 'rgb(33, 33, 33)', + opacity: '0.5', + placeholder: 'rgb(66, 66, 66)', + part: 'rgb(255, 255, 255)', + wrapper: 'rgba(0, 0, 0, 0) rgb(33, 33, 33) rgb(227, 227, 227)', + items: 'rgb(180, 83, 9) rgb(66, 66, 66)', + }, + }, + { + title: + 'the default dark theme presses in its hover fill and dims disabled controls @scenario:state-roles-default-dark-unchanged', + mode: 'dark', + pressed: 'rgb(57, 57, 57)', + disabled: { + fill: 'rgba(0, 0, 0, 0)', + ink: 'rgb(236, 236, 236)', + opacity: '0.5', + placeholder: 'rgb(205, 205, 205)', + part: 'rgb(13, 13, 13)', + wrapper: 'rgba(0, 0, 0, 0) rgb(236, 236, 236) rgb(33, 33, 33)', + items: 'rgb(252, 211, 77) rgb(205, 205, 205)', + }, + }, + { + title: + 'the ClickHouse light theme presses and disables in Click UI fills @scenario:state-roles-clickhouse-light', + mode: 'light', + definition: clickHouseTheme, + pressed: 'rgb(221, 222, 225)', + disabled: { + fill: 'rgb(223, 223, 223)', + ink: 'rgb(160, 160, 160)', + opacity: '1', + placeholder: 'rgb(160, 160, 160)', + part: 'rgb(223, 223, 223)', + wrapper: 'rgb(223, 223, 223) rgb(160, 160, 160) rgb(223, 223, 223)', + items: 'rgb(160, 160, 160) rgb(160, 160, 160)', + }, + }, + { + title: + 'the ClickHouse dark theme presses and disables in Click UI fills @scenario:state-roles-clickhouse-dark', + mode: 'dark', + definition: clickHouseTheme, + pressed: 'rgb(36, 36, 36)', + disabled: { + fill: 'rgb(65, 65, 65)', + ink: 'rgb(128, 128, 128)', + opacity: '1', + placeholder: 'rgb(128, 128, 128)', + part: 'rgb(65, 65, 65)', + wrapper: 'rgb(65, 65, 65) rgb(128, 128, 128) rgb(65, 65, 65)', + items: 'rgb(128, 128, 128) rgb(128, 128, 128)', + }, + }, +]; + +test.describe('pressed and disabled state roles', () => { + for (const { title, mode, definition, pressed, disabled } of CASES) { + test(title, async ({ page }) => { + await openChat(page, mode, definition); + + const fill = await pressedFill(page); + if (fill !== null) { + expect(fill).toBe(pressed); + } + expect(await disabledLook(page)).toEqual(disabled); + }); + } + + test('a theme that names the state roles presses and disables in them, in both modes @scenario:state-roles-follow-reference-theme', async ({ + page, + }) => { + const expected: Record = { + light: { + pressed: 'rgb(150, 60, 20)', + fill: 'rgb(20, 150, 60)', + ink: 'rgb(60, 20, 150)', + edge: 'rgb(227, 227, 227)', + }, + dark: { + pressed: 'rgb(240, 160, 120)', + fill: 'rgb(120, 240, 160)', + ink: 'rgb(160, 120, 240)', + edge: 'rgb(57, 57, 57)', + }, + }; + /** One page per mode: a page's init scripts accumulate, and their order is not guaranteed. */ + for (const mode of ['light', 'dark'] as const) { + const modePage = mode === 'light' ? page : await page.context().newPage(); + await openChat(modePage, mode, STATE_ROLE_THEME); + + const fill = await pressedFill(modePage); + if (fill !== null) { + expect(fill).toBe(expected[mode].pressed); + } + expect(await disabledLook(modePage)).toEqual({ + fill: expected[mode].fill, + ink: expected[mode].ink, + opacity: '1', + placeholder: expected[mode].ink, + part: expected[mode].fill, + wrapper: `${expected[mode].fill} ${expected[mode].ink} ${expected[mode].edge}`, + items: `${expected[mode].ink} ${expected[mode].ink}`, + }); + } + }); +}); diff --git a/packages/client/src/components/AlertDialog.tsx b/packages/client/src/components/AlertDialog.tsx index 6e6bbee22c..2607dc8ee9 100644 --- a/packages/client/src/components/AlertDialog.tsx +++ b/packages/client/src/components/AlertDialog.tsx @@ -2,7 +2,7 @@ import * as React from 'react'; import { JSX } from 'react/jsx-runtime'; import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'; import { useDialogDepth } from './OriginalDialog'; -import { cn } from '~/utils'; +import { cn, disabledFillClasses } from '~/utils'; const AlertDialog: React.FC = AlertDialogPrimitive.Root; @@ -148,6 +148,7 @@ const AlertDialogAction: React.ForwardRefExoticComponent< ref={ref} className={cn( 'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover focus:ring-focus-control inline-flex h-10 items-center justify-center rounded-md px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50', + disabledFillClasses, className, )} {...props} @@ -169,6 +170,7 @@ const AlertDialogCancel: React.ForwardRefExoticComponent< ref={ref} className={cn( 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-focus-control mt-2 inline-flex h-10 items-center justify-center rounded-md border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', + disabledFillClasses, className, )} {...props} diff --git a/packages/client/src/components/AnimatedTabs.tsx b/packages/client/src/components/AnimatedTabs.tsx index b58a31f686..2c13fff3ae 100644 --- a/packages/client/src/components/AnimatedTabs.tsx +++ b/packages/client/src/components/AnimatedTabs.tsx @@ -1,7 +1,7 @@ import { forwardRef, useEffect, useRef } from 'react'; import * as Ariakit from '@ariakit/react'; import type { ElementRef } from 'react'; -import { cn } from '~/utils'; +import { cn, disabledInkClasses } from '~/utils'; import './AnimatedTabs.css'; import { JSX } from 'react/jsx-runtime'; @@ -60,7 +60,11 @@ const Tab = forwardRef, Ariakit.TabProps>(functio else if (ref) ref.current = node; }} {...props} - className={`animated-tab aria-selected:text-text-primary flex items-center justify-center gap-2 border-none text-sm font-medium whitespace-nowrap outline-hidden transition-colors select-none aria-disabled:opacity-50 ${props.className || ''}`} + className={cn( + 'animated-tab aria-selected:text-text-primary flex items-center justify-center gap-2 border-none text-sm font-medium whitespace-nowrap outline-hidden transition-colors select-none aria-disabled:opacity-50', + disabledInkClasses, + props.className, + )} /> ); }); diff --git a/packages/client/src/components/Checkbox.tsx b/packages/client/src/components/Checkbox.tsx index ff0dcfc225..f26f44d7d3 100644 --- a/packages/client/src/components/Checkbox.tsx +++ b/packages/client/src/components/Checkbox.tsx @@ -1,7 +1,7 @@ import * as React from 'react'; import { Check } from 'lucide-react'; import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; -import { cn } from '~/utils'; +import { cn, disabledFillClasses } from '~/utils'; type BaseCheckboxProps = Omit< React.ComponentPropsWithoutRef, @@ -28,6 +28,7 @@ const Checkbox: React.ForwardRefExoticComponent< ref={ref} className={cn( 'peer border-border-xheavy ring-offset-surface-primary focus-visible:ring-focus-control data-[state=checked]:bg-surface-inverted data-[state=checked]:text-text-inverted h-4 w-4 shrink-0 rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50', + disabledFillClasses, className, )} {...props} diff --git a/packages/client/src/components/Combobox.tsx b/packages/client/src/components/Combobox.tsx index 47c68fc6b1..aa1b1b9c35 100644 --- a/packages/client/src/components/Combobox.tsx +++ b/packages/client/src/components/Combobox.tsx @@ -13,8 +13,8 @@ import { import type { OptionWithIcon } from '~/common'; import { SelectTrigger, SelectValue, SelectScrollDownButton } from './Select'; import { useNestedPopoverStyle } from './OriginalDialog'; +import { cn, disabledInkClasses } from '~/utils'; import { useCombobox } from '~/hooks'; -import { cn } from '~/utils'; export default function ComboboxComponent({ selectedValue, @@ -145,6 +145,7 @@ export default function ComboboxComponent({ = DialogPrimitive.Root; @@ -145,6 +145,7 @@ const DialogClose: React.ForwardRefExoticComponent< ref={ref} className={cn( 'border-border-light text-text-primary hover:bg-surface-hover mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', + disabledFillClasses, className ?? '', /* Important: for accessibility */ 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', @@ -166,6 +167,7 @@ const DialogButton: React.ForwardRefExoticComponent< variant="outline" className={cn( 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-focus-control mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', + disabledFillClasses, className ?? '', /* Important: for accessibility */ 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', diff --git a/packages/client/src/components/DialogTemplate.tsx b/packages/client/src/components/DialogTemplate.tsx index ab3f02930e..5623067745 100644 --- a/packages/client/src/components/DialogTemplate.tsx +++ b/packages/client/src/components/DialogTemplate.tsx @@ -7,7 +7,7 @@ import { DialogHeader, DialogTitle, } from './Dialog'; -import { cn } from '~/utils/'; +import { cn, disabledFillClasses } from '~/utils'; type SelectionProps = { selectHandler?: () => void; @@ -48,20 +48,22 @@ const DialogTemplate: ForwardRefExoticComponent< const { selectHandler, selectClasses, selectText } = selection || {}; const Cancel = 'cancel'; - const defaultSelect = - 'bg-surface-inverted text-text-inverted transition-colors hover:bg-surface-inverted-hover disabled:cursor-not-allowed disabled:opacity-50'; + const defaultSelect = cn( + 'bg-surface-inverted text-text-inverted transition-colors hover:bg-surface-inverted-hover disabled:cursor-not-allowed disabled:opacity-50', + disabledFillClasses, + ); return ( e.stopPropagation()} > - + {title} {description && ( diff --git a/packages/client/src/components/Dropdown.tsx b/packages/client/src/components/Dropdown.tsx index 79e4495efe..ca9d909c7d 100644 --- a/packages/client/src/components/Dropdown.tsx +++ b/packages/client/src/components/Dropdown.tsx @@ -4,8 +4,8 @@ import { matchSorter } from 'match-sorter'; import * as Select from '@ariakit/react/select'; import * as Combobox from '@ariakit/react/combobox'; import type { Option } from '~/common'; +import { cn, disabledFillClasses } from '~/utils'; import { fieldControl } from './Field'; -import { cn } from '~/utils/'; import './Dropdown.css'; interface DropdownProps { @@ -152,6 +152,7 @@ const Dropdown: React.FC = ({ className={cn( 'border-border-control text-text-primary hover:bg-surface-hover hover:text-text-primary relative inline-flex items-center justify-between rounded-xl border bg-transparent py-2 text-sm transition-all duration-200 ease-in-out', 'disabled:hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent', + disabledFillClasses, /** Horizontal padding would squeeze the icon, which flex-shrinks to fit */ iconOnly ? 'size-10 justify-center px-0' : 'w-fit gap-2 px-3', variant === 'field' && fieldControl, diff --git a/packages/client/src/components/DropdownMenu.tsx b/packages/client/src/components/DropdownMenu.tsx index cdb31b3d25..4bcf059e1b 100644 --- a/packages/client/src/components/DropdownMenu.tsx +++ b/packages/client/src/components/DropdownMenu.tsx @@ -3,7 +3,7 @@ import { JSX } from 'react/jsx-runtime'; import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu'; import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react'; import { usePopoverZIndex } from './OriginalDialog'; -import { cn } from '~/utils'; +import { cn, disabledInkClasses } from '~/utils'; function DropdownMenu({ ...props @@ -68,6 +68,7 @@ function DropdownMenuItem({ data-variant={variant} className={cn( "focus:bg-surface-hover focus:text-text-primary data-[variant=destructive]:text-text-destructive data-[variant=destructive]:focus:bg-status-error-subtle data-[variant=destructive]:focus:text-text-destructive [&_svg:not([class*='text-'])]:text-text-secondary relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + disabledInkClasses, className, )} {...props} @@ -86,6 +87,7 @@ function DropdownMenuCheckboxItem({ data-slot="dropdown-menu-checkbox-item" className={cn( "focus:bg-surface-hover focus:text-text-primary relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + disabledInkClasses, className, )} checked={checked} @@ -117,6 +119,7 @@ function DropdownMenuRadioItem({ data-slot="dropdown-menu-radio-item" className={cn( "focus:bg-surface-hover focus:text-text-primary relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + disabledInkClasses, className, )} {...props} diff --git a/packages/client/src/components/DropdownPopup.tsx b/packages/client/src/components/DropdownPopup.tsx index 038186a2a3..ab6dfd4ad5 100644 --- a/packages/client/src/components/DropdownPopup.tsx +++ b/packages/client/src/components/DropdownPopup.tsx @@ -2,7 +2,7 @@ import React from 'react'; import * as Ariakit from '@ariakit/react'; import type * as t from '~/common'; import { usePopoverZIndex } from './OriginalDialog'; -import { cn } from '~/utils'; +import { cn, disabledInkClasses } from '~/utils'; import './Dropdown.css'; interface DropdownProps { @@ -113,6 +113,7 @@ const Menu: React.FC = ({ = ({ id={item.id} className={cn( 'group text-text-primary hover:bg-surface-hover focus:bg-surface-hover flex w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-3.5 text-sm outline-hidden md:px-2.5 md:py-2', + disabledInkClasses, itemClassName, item.className, )} diff --git a/packages/client/src/components/Field.ts b/packages/client/src/components/Field.ts index c2177e8ffd..377a9a24b3 100644 --- a/packages/client/src/components/Field.ts +++ b/packages/client/src/components/Field.ts @@ -1,3 +1,5 @@ +import { disabledFillClasses } from '~/utils/theme'; + /** * The shared appearance of a form control: border, radius, type scale and focus * treatment. Owned here so `Input`, `Textarea`, and the select/combobox triggers @@ -6,8 +8,7 @@ * border is `border-control` because it is the only edge the control has, so a * palette can raise it to the 3:1 non-text floor without touching separators. */ -export const fieldBase: string = - 'lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control disabled:cursor-not-allowed disabled:opacity-50'; +export const fieldBase: string = `lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control disabled:cursor-not-allowed disabled:opacity-50 ${disabledFillClasses}`; /** A single-line control sized to sit in a form row, matching `Input`. */ export const fieldControl: string = `${fieldBase} h-10 bg-transparent`; diff --git a/packages/client/src/components/FilterInput.tsx b/packages/client/src/components/FilterInput.tsx index 0fc66c2173..43b0620dda 100644 --- a/packages/client/src/components/FilterInput.tsx +++ b/packages/client/src/components/FilterInput.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { cn } from '~/utils'; +import { cn, disabledFillClasses, peerDisabledInkClasses } from '~/utils'; export interface FilterInputProps extends Omit, 'placeholder'> { @@ -48,13 +48,17 @@ const FilterInput: React.ForwardRefExoticComponent< aria-label={label} className={cn( 'peer border-border-light text-text-primary ring-offset-surface-primary placeholder:text-text-secondary flex h-9 w-full rounded-lg border bg-transparent px-3 py-2 text-sm focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50', + disabledFillClasses, className, )} {...props} /> diff --git a/packages/client/src/components/IconButton.tsx b/packages/client/src/components/IconButton.tsx index b3c2fc8af0..9100bb132a 100644 --- a/packages/client/src/components/IconButton.tsx +++ b/packages/client/src/components/IconButton.tsx @@ -2,6 +2,7 @@ import * as React from 'react'; import { cva } from 'class-variance-authority'; import type { ClassProp } from 'class-variance-authority/types'; import { composerSubmitClasses } from '~/utils/composer'; +import { disabledFillClasses } from '~/utils/theme'; import { cn } from '~/utils'; type IconButtonVariantProps = { @@ -19,21 +20,29 @@ type IconButtonVariantProps = { }; const iconButtonVariants: (props?: IconButtonVariantProps & ClassProp) => string = cva( - 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', + [ + 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', + disabledFillClasses, + ], { variants: { variant: { - default: 'bg-surface-secondary hover:bg-surface-hover', - primary: 'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover', - secondary: 'border border-border-light bg-surface-secondary hover:bg-surface-hover', - ghost: 'bg-transparent hover:bg-surface-hover', + default: 'bg-surface-secondary hover:bg-surface-hover hover:active:bg-surface-pressed', + primary: + 'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover hover:active:bg-surface-inverted-pressed', + secondary: + 'border border-border-light bg-surface-secondary hover:bg-surface-hover hover:active:bg-surface-pressed', + ghost: 'bg-transparent hover:bg-surface-hover hover:active:bg-surface-pressed', /** An action inside a list row whose highlight is already `surface-hover`, * so its own hover takes the active fill to stay visible on top of it. */ 'row-action': 'bg-transparent hover:bg-surface-active', destructive: 'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover', /** The composer's submit slot: send, stop and the during-run send share it. */ - submit: cn('hover:bg-surface-inverted-hover', composerSubmitClasses()), + submit: cn( + 'hover:bg-surface-inverted-hover hover:active:bg-surface-inverted-pressed', + composerSubmitClasses(), + ), }, size: { xs: 'size-6', diff --git a/packages/client/src/components/InputNumber.tsx b/packages/client/src/components/InputNumber.tsx index d18f17f563..6d149940ca 100644 --- a/packages/client/src/components/InputNumber.tsx +++ b/packages/client/src/components/InputNumber.tsx @@ -5,7 +5,7 @@ import * as React from 'react'; import RCInputNumber from 'rc-input-number'; import * as InputNumberPrimitive from 'rc-input-number'; import type { ValueType } from '@rc-component/mini-decimal'; -import { cn } from '~/utils'; +import { cn, disabledWithinFillClasses } from '~/utils'; // TODO help needed // React.ElementRef, @@ -19,6 +19,7 @@ const InputNumber: React.ForwardRefExoticComponent< = T | { label: string; value: T }; @@ -147,6 +147,7 @@ export default function MultiSelect({ 'flex items-center justify-between gap-2 rounded-xl px-3 py-2 text-sm', 'bg-surface-tertiary text-text-primary hover:bg-surface-hover shadow-xs hover:cursor-pointer', 'disabled:hover:bg-surface-tertiary disabled:cursor-not-allowed disabled:opacity-60', + disabledFillClasses, 'focus-visible:ring-focus-control outline-hidden focus-visible:ring-2 focus-visible:outline-hidden', selectClassName, selectedValues.length > 0 && selectItemsClassName != null && selectItemsClassName, diff --git a/packages/client/src/components/Radio.tsx b/packages/client/src/components/Radio.tsx index 86070ff093..7f59490ccf 100644 --- a/packages/client/src/components/Radio.tsx +++ b/packages/client/src/components/Radio.tsx @@ -1,4 +1,5 @@ import React, { useState, useRef, useLayoutEffect, useCallback, memo } from 'react'; +import { disabledInkClasses } from '~/utils'; import { useLocalize } from '~/hooks'; /** Matches the `inset-y-1` the single-row indicator uses. */ @@ -190,7 +191,7 @@ const Radio: React.NamedExoticComponent = memo(function Radio({ disabled={disabled} className={`focus-visible:ring-focus-control relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-hidden ${ currentValue === option.value ? 'text-text-primary' : 'text-text-secondary' - } ${disabled ? 'cursor-not-allowed opacity-50' : ''} ${fullWidth ? 'flex-1' : ''} ${buttonClassName}`} + } ${disabled ? 'cursor-not-allowed opacity-50' : ''} ${disabledInkClasses} ${fullWidth ? 'flex-1' : ''} ${buttonClassName}`} > {option.icon && (