diff --git a/.github/guard-specs.json b/.github/guard-specs.json index 20f4e09d1d..fe1b9e86ad 100644 --- a/.github/guard-specs.json +++ b/.github/guard-specs.json @@ -23,6 +23,7 @@ "client/src/Providers/__tests__/handoff.spec.tsx": ["client/index.html"], "client/src/__tests__/hosts.test.tsx": ["client/src/App.jsx"], "client/src/__tests__/loadingCanvas.spec.ts": ["client/index.html"], + "client/src/__tests__/loadingSpinner.spec.tsx": ["client/index.html"], "client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts": [ "client/src/components/Chat/", "client/src/hooks/Input/usePaletteEntries.tsx", diff --git a/client/index.html b/client/index.html index ca68ab0dee..f454cbe7a0 100644 --- a/client/index.html +++ b/client/index.html @@ -26,6 +26,32 @@ padding: 0; height: 100%; } + + /* On a slow connection the bundle can take tens of seconds, and an empty canvas reads as + * a broken page. The indicator is the shared Spinner's markup (packages/client + * src/svgs/Spinner.tsx); its rotation and reduced-motion rule come from the `.spinner` + * class in the main stylesheet, which loads before this canvas paints. It waits a second, + * so a fast load never shows it, and SVG shapes are never a contentful-paint candidate. */ + .boot-indicator { + display: flex; + opacity: 0; + animation: boot-indicator-in 0.3s ease-out 1s forwards; + } + + .boot-indicator-label { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } + + @keyframes boot-indicator-in { + to { + opacity: 1; + } + } + diff --git a/client/src/__tests__/loadingSpinner.spec.tsx b/client/src/__tests__/loadingSpinner.spec.tsx new file mode 100644 index 0000000000..46a31dbb1f --- /dev/null +++ b/client/src/__tests__/loadingSpinner.spec.tsx @@ -0,0 +1,51 @@ +import React from 'react'; +import { join } from 'node:path'; +import { readFileSync } from 'node:fs'; +import { Spinner } from '@librechat/client'; +import { render } from '@testing-library/react'; + +/** The shell paints before the bundle runs, so it copies the shared Spinner's markup instead of + * rendering it. This holds the copy to the component, so the two never drift apart. */ +const shellSpinner = (() => { + const html = readFileSync(join(__dirname, '..', '..', 'index.html'), 'utf8'); + const document = new DOMParser().parseFromString(html, 'text/html'); + const svg = document.querySelector('#loading-container svg'); + if (!svg) { + throw new Error('index.html no longer carries the loading spinner'); + } + return svg; +})(); + +const CIRCLE_ATTRIBUTES = [ + 'cx', + 'cy', + 'r', + 'pathLength', + 'stroke-width', + 'fill', + 'stroke', + 'stroke-opacity', + 'stroke-dasharray', + 'stroke-linecap', +]; + +const describeSvg = (svg: Element) => ({ + viewBox: svg.getAttribute('viewBox'), + width: svg.getAttribute('width'), + height: svg.getAttribute('height'), + spins: svg.classList.contains('spinner'), + hidden: svg.getAttribute('aria-hidden'), + circles: [...svg.querySelectorAll('circle')].map((circle) => + Object.fromEntries(CIRCLE_ATTRIBUTES.map((name) => [name, circle.getAttribute(name)])), + ), +}); + +describe('loading shell spinner', () => { + it('matches the shared Spinner at the size the shell uses', () => { + const { container } = render(); + const component = container.querySelector('svg'); + expect(component).not.toBeNull(); + + expect(describeSvg(shellSpinner)).toEqual(describeSvg(component!)); + }); +}); diff --git a/client/src/components/Chat/Input/Composer/Files.tsx b/client/src/components/Chat/Input/Composer/Files.tsx index 485a2bdf39..e9c01020ca 100644 --- a/client/src/components/Chat/Input/Composer/Files.tsx +++ b/client/src/components/Chat/Input/Composer/Files.tsx @@ -11,8 +11,8 @@ import FilePreviewDialog, { getDisplayType, } from '~/components/Chat/Messages/Content/FilePreviewDialog'; import { useGetFiles, useFilePreviewBlob } from '~/data-provider'; +import { useLocalize, useOnline, useAuthContext } from '~/hooks'; import { toAbsoluteFilePath, triggerDownload } from '~/utils'; -import { useLocalize, useAuthContext } from '~/hooks'; export type FileView = 'all' | 'images' | 'documents'; @@ -148,6 +148,7 @@ function EmptyState({ text?: string; }) { const localize = useLocalize(); + const online = useOnline(); if (loading) { return (
@@ -160,7 +161,7 @@ function EmptyState({ return (

- {localize('com_ui_error_connection')} + {localize(online ? 'com_ui_error_connection' : 'com_ui_error_offline')}

{/* The files query does not refetch on mount, focus or reconnect, so reopening the dialog would not recover without this. */} diff --git a/client/src/components/Chat/Input/Composer/__tests__/Files.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Files.spec.tsx index 5d4e794f7e..3fd1b6283d 100644 --- a/client/src/components/Chat/Input/Composer/__tests__/Files.spec.tsx +++ b/client/src/components/Chat/Input/Composer/__tests__/Files.spec.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { RecoilRoot } from 'recoil'; -import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import type { TFile } from 'librechat-data-provider'; import FileGrid from '../Files'; @@ -37,6 +37,7 @@ jest.mock('~/hooks', () => ({ useLocalize: () => (key: string, options?: Record) => options ? `${key}:${options['0']}` : key, useAuthContext: () => ({ user: { id: 'user-1' } }), + useOnline: jest.requireActual('~/hooks/useOnline').default, })); const renderGrid = (props: Partial> = {}) => { @@ -128,6 +129,21 @@ describe('FileGrid', () => { expect(mockRefetch).toHaveBeenCalledTimes(1); }); + it('names a lost connection as the cause and follows it coming back', () => { + const onLine = jest.spyOn(window.navigator, 'onLine', 'get').mockReturnValue(false); + mockFiles = undefined; + mockQueryState = { isLoading: false, isError: true }; + renderGrid(); + expect(screen.getByRole('alert')).toHaveTextContent('com_ui_error_offline'); + + onLine.mockReturnValue(true); + act(() => { + window.dispatchEvent(new Event('online')); + }); + expect(screen.getByRole('alert')).toHaveTextContent('com_ui_error_connection'); + onLine.mockRestore(); + }); + it('stays on the grid when an image has nothing to preview', async () => { mockFiles = [file({ file_id: 'bare', filename: 'bare.png', type: 'image/png', filepath: '' })]; renderGrid(); diff --git a/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx b/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx index bd8ea054a6..94d1537495 100644 --- a/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx +++ b/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx @@ -57,7 +57,9 @@ const SettingsButton = ({ onClick={handleClick} onKeyDown={handleKeyDown} className={cn( - 'group/button flex items-center gap-1.5 rounded-md px-1.5', + 'group/button -my-0.5 flex min-h-6 items-center justify-center gap-1.5 rounded-md px-1.5', + /* Both targets (24px, 32px on touch) spill into the row's padding instead of growing it. */ + 'any-pointer-coarse:-my-1.5 any-pointer-coarse:min-h-8 any-pointer-coarse:min-w-8', 'text-text-secondary transition-colors duration-150', 'hover:bg-surface-tertiary hover:text-text-primary', 'focus-visible:bg-surface-tertiary focus-visible:text-text-primary', diff --git a/client/src/components/Chat/Messages/Content/MessageContent.tsx b/client/src/components/Chat/Messages/Content/MessageContent.tsx index a36017f4ed..01b11764a5 100644 --- a/client/src/components/Chat/Messages/Content/MessageContent.tsx +++ b/client/src/components/Chat/Messages/Content/MessageContent.tsx @@ -13,10 +13,10 @@ import AttachmentRecoveryActions from '~/components/Messages/Content/Error/recov import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext'; import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming'; import Error from '~/components/Messages/Content/Error'; +import { useLocalize, useOnline } from '~/hooks'; import MarkdownLite from './MarkdownLite'; import EditMessage from './EditMessage'; import Thinking from './Parts/Thinking'; -import { useLocalize } from '~/hooks'; import Markdown from './Markdown'; import { cn } from '~/utils'; @@ -51,6 +51,7 @@ const ErrorBox = ({ const ConnectionError = ({ message }: { message?: TMessage }) => { const localize = useLocalize(); + const online = useOnline(); return ( }> @@ -65,7 +66,7 @@ const ConnectionError = ({ message }: { message?: TMessage }) => { elevation="raised" className="text-text-secondary mt-2 transition-all" > - {localize('com_ui_error_connection')} + {localize(online ? 'com_ui_error_connection' : 'com_ui_error_offline')} diff --git a/client/src/components/Projects/ProjectResources.spec.tsx b/client/src/components/Projects/ProjectResources.spec.tsx index 6f45b42545..4c2bf13ca2 100644 --- a/client/src/components/Projects/ProjectResources.spec.tsx +++ b/client/src/components/Projects/ProjectResources.spec.tsx @@ -87,6 +87,7 @@ jest.mock('~/hooks', () => ({ useGetAgentsConfig: () => ({ agentsConfig: { capabilities: ['file_search'] } }), useHasAccess: () => mockCanUseFileSearch(), useAuthContext: () => ({ user: { id: 'user-1' } }), + useOnline: jest.requireActual('~/hooks/useOnline').default, useToolFavorites: () => ({ favoriteKeys: new Set(), toggle: jest.fn() }), useLocalize: () => (key: string, options?: { count?: number; name?: string }) => { const translations: Record = { diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.ts index dbf888120a..e6172a49bf 100644 --- a/client/src/hooks/index.ts +++ b/client/src/hooks/index.ts @@ -25,6 +25,7 @@ export * from './Endpoint'; export type { TranslationKeys } from './useLocalize'; +export { default as useOnline } from './useOnline'; export { default as useTimeout } from './useTimeout'; export { default as useNewConvo } from './useNewConvo'; export { default as useLocalize } from './useLocalize'; diff --git a/client/src/hooks/useOnline.ts b/client/src/hooks/useOnline.ts new file mode 100644 index 0000000000..9315c738db --- /dev/null +++ b/client/src/hooks/useOnline.ts @@ -0,0 +1,19 @@ +import { useSyncExternalStore } from 'react'; + +const subscribe = (onChange: () => void) => { + window.addEventListener('online', onChange); + window.addEventListener('offline', onChange); + return () => { + window.removeEventListener('online', onChange); + window.removeEventListener('offline', onChange); + }; +}; + +/** `navigator.onLine` is only trustworthy when false: a captive portal or a dead + * route still reports true. Use it to name the cause of a failure, never to block a request. */ +const getSnapshot = () => navigator.onLine; +const getServerSnapshot = () => true; + +export default function useOnline(): boolean { + return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); +} diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index 8a4d825215..78bb1f9784 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -1938,6 +1938,7 @@ "com_ui_enter_value": "Enter value", "com_ui_error": "Error", "com_ui_error_connection": "Error connecting to server, try refreshing the page.", + "com_ui_error_offline": "You're offline. Check your connection and try again.", "com_ui_error_details": "Error details", "com_ui_error_message_prefix": "Error Message:", "com_ui_error_save_admin_settings": "There was an error saving your admin settings.", diff --git a/client/src/locales/i18n.ts b/client/src/locales/i18n.ts index e1862165fc..d1b7e440f6 100644 --- a/client/src/locales/i18n.ts +++ b/client/src/locales/i18n.ts @@ -1,58 +1,14 @@ import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; - +import type { SupportedLocale } from './resolve'; +import { resolveLocale, supportedLocales } from './resolve'; import translationEn from './en/translation.json'; +export { supportedLocales }; +export type { SupportedLocale }; + export const defaultNS = 'translation'; -export const supportedLocales = [ - 'ar', - 'bo', - 'bs', - 'ca', - 'cs', - 'da', - 'de', - 'en', - 'es', - 'et', - 'fa', - 'fi', - 'fr', - 'he', - 'hi', - 'hu', - 'hy', - 'id', - 'is', - 'it', - 'ja', - 'ka', - 'ko', - 'lt', - 'lv', - 'mr', - 'nb', - 'nl', - 'nn', - 'pl', - 'pt-BR', - 'pt-PT', - 'ru', - 'sk', - 'sl', - 'sv', - 'ta', - 'th', - 'tr', - 'ug', - 'uk', - 'vi', - 'zh-Hans', - 'zh-Hant', -] as const; - -export type SupportedLocale = (typeof supportedLocales)[number]; export type TranslationResource = Record; export const resources = { @@ -108,54 +64,6 @@ const localeLoaders: Record< 'zh-Hant': () => import('./zh-Hant/translation.json'), }; -const localeByLowercase = supportedLocales.reduce>( - (acc, locale) => { - acc[locale.toLowerCase()] = locale; - return acc; - }, - {}, -); - -const localeAliases: Record = { - 'ar-eg': 'ar', - 'ca-es': 'ca', - 'cs-cz': 'cs', - 'da-dk': 'da', - 'de-de': 'de', - 'en-us': 'en', - 'es-es': 'es', - 'et-ee': 'et', - 'fa-ir': 'fa', - 'fi-fi': 'fi', - 'fr-fr': 'fr', - 'he-he': 'he', - 'he-il': 'he', - 'hu-hu': 'hu', - 'hy-am': 'hy', - 'id-id': 'id', - 'it-it': 'it', - 'ja-jp': 'ja', - 'ka-ge': 'ka', - 'ko-kr': 'ko', - 'lt-lt': 'lt', - 'lv-lv': 'lv', - 'nl-nl': 'nl', - 'pl-pl': 'pl', - pt: 'pt-PT', - 'ru-ru': 'ru', - 'sv-se': 'sv', - 'th-th': 'th', - 'tr-tr': 'tr', - 'uk-ua': 'uk', - 'vi-vn': 'vi', - zh: 'zh-Hans', - 'zh-cn': 'zh-Hans', - 'zh-sg': 'zh-Hans', - 'zh-tw': 'zh-Hant', - 'zh-hk': 'zh-Hant', - 'zh-mo': 'zh-Hant', -}; - const loadedLocales = new Set(['en']); const loadingLocales: Partial>> = {}; let languageRequestId = 0; @@ -201,24 +109,7 @@ function getNavigatorLanguage() { } export function normalizeLocale(locale?: string | null): SupportedLocale { - const requested = locale === 'auto' ? getNavigatorLanguage() : locale; - if (!requested) { - return 'en'; - } - - const normalized = requested.replace(/_/g, '-').toLowerCase(); - const exact = localeByLowercase[normalized]; - if (exact) { - return exact; - } - - const alias = localeAliases[normalized]; - if (alias) { - return alias; - } - - const base = normalized.split('-')[0]; - return localeByLowercase[base] ?? localeAliases[base] ?? 'en'; + return resolveLocale(locale === 'auto' ? getNavigatorLanguage() : locale); } export function detectInitialLanguage() { diff --git a/client/src/locales/resolve.ts b/client/src/locales/resolve.ts new file mode 100644 index 0000000000..52a83d1fc1 --- /dev/null +++ b/client/src/locales/resolve.ts @@ -0,0 +1,122 @@ +/** + * Which supported locale a requested language resolves to. Kept free of side effects and of + * i18next, so the build can resolve the HTML shell's loading label with the same rules + * (`bootLoadingLabels` in vite.config.ts). + */ +export const supportedLocales = [ + 'ar', + 'bo', + 'bs', + 'ca', + 'cs', + 'da', + 'de', + 'en', + 'es', + 'et', + 'fa', + 'fi', + 'fr', + 'he', + 'hi', + 'hu', + 'hy', + 'id', + 'is', + 'it', + 'ja', + 'ka', + 'ko', + 'lt', + 'lv', + 'mr', + 'nb', + 'nl', + 'nn', + 'pl', + 'pt-BR', + 'pt-PT', + 'ru', + 'sk', + 'sl', + 'sv', + 'ta', + 'th', + 'tr', + 'ug', + 'uk', + 'vi', + 'zh-Hans', + 'zh-Hant', +] as const; + +export type SupportedLocale = (typeof supportedLocales)[number]; + +const localeByLowercase = supportedLocales.reduce>( + (acc, locale) => { + acc[locale.toLowerCase()] = locale; + return acc; + }, + {}, +); + +export const localeAliases: Record = { + 'ar-eg': 'ar', + 'ca-es': 'ca', + 'cs-cz': 'cs', + 'da-dk': 'da', + 'de-de': 'de', + 'en-us': 'en', + 'es-es': 'es', + 'et-ee': 'et', + 'fa-ir': 'fa', + 'fi-fi': 'fi', + 'fr-fr': 'fr', + 'he-he': 'he', + 'he-il': 'he', + 'hu-hu': 'hu', + 'hy-am': 'hy', + 'id-id': 'id', + 'it-it': 'it', + 'ja-jp': 'ja', + 'ka-ge': 'ka', + 'ko-kr': 'ko', + 'lt-lt': 'lt', + 'lv-lv': 'lv', + 'nl-nl': 'nl', + 'pl-pl': 'pl', + pt: 'pt-PT', + 'ru-ru': 'ru', + 'sv-se': 'sv', + 'th-th': 'th', + 'tr-tr': 'tr', + 'uk-ua': 'uk', + 'vi-vn': 'vi', + zh: 'zh-Hans', + 'zh-cn': 'zh-Hans', + 'zh-sg': 'zh-Hans', + 'zh-tw': 'zh-Hant', + 'zh-hk': 'zh-Hant', + 'zh-mo': 'zh-Hant', +}; + +/** A requested language (`de-DE`, `zh_TW`, `pt`) to the supported locale the app loads. */ +export function resolveLocale(requested?: string | null): SupportedLocale { + if (!requested) { + return 'en'; + } + + const normalized = requested.replace(/_/g, '-').toLowerCase(); + const exact = localeByLowercase[normalized]; + if (exact) { + return exact; + } + + const alias = localeAliases[normalized]; + if (alias) { + return alias; + } + + const base = normalized.split('-')[0]; + return localeByLowercase[base] ?? localeAliases[base] ?? 'en'; +} diff --git a/client/vite.config.ts b/client/vite.config.ts index 1c1982cfef..64eeebed77 100644 --- a/client/vite.config.ts +++ b/client/vite.config.ts @@ -12,6 +12,7 @@ import { compression, defineAlgorithm } from 'vite-plugin-compression2'; import type { Plugin } from 'vite'; import { sandpackConsoleIsolation } from './src/lib/sandpack.ts'; import { bundledThemeBoot, injectThemeCacheVersion } from './src/Providers/bootVersion.ts'; +import { localeAliases, resolveLocale, supportedLocales } from './src/locales/resolve.ts'; const require = createRequire(import.meta.url); @@ -95,9 +96,14 @@ export default defineConfig(({ command }) => ({ }, }, themeCacheVersion(), + bootLoadingLabels(), copyPublicAssets(), VitePWA({ - injectRegister: 'auto', // 'auto' | 'manual' | 'disabled' + /** `auto` emits a parser-blocking `