mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 15:02:02 +00:00
📶 fix: Show Progress on Slow Connections and Name Offline Failures (#18107)
* perf: Paint the Loading Shell Before the Bundle Arrives * fix: Name a Lost Connection Instead of Suggesting a Refresh * fix: Give the Endpoint Key Button a Usable Touch Target * test: Cover the Loading Shell, Offline Copy and Key Button Target * fix: Announce the Loading Indicator in the User's Language * test: Exercise the Key Button on a Plain Endpoint Row and the Localized Label * test: Measure the Key Button's Layout Size, Not Its Animated Box * fix: Keep the Key Button's Row Height on Fine Pointers Too * fix: Ink the Loading Indicator in the Theme's Text Role * fix: Draw the Loading Indicator With the Shared Spinner * test: List the Loading Spinner Spec as an index.html Guard * fix: Resolve the Loading Label's Language the Way the App Does * test: Cover the Loading Label for an Automatic zh-TW Browser
This commit is contained in:
parent
24da3c92ed
commit
d89ab2887e
15 changed files with 484 additions and 124 deletions
1
.github/guard-specs.json
vendored
1
.github/guard-specs.json
vendored
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
(function () {
|
||||
|
|
@ -60,7 +86,10 @@
|
|||
/* Stored unquoted, or Web Storage denied: the raw value or the browser language. */
|
||||
}
|
||||
}
|
||||
lang = String(lang || navigator.language || '').toLowerCase();
|
||||
/* `auto` is the stored choice to follow the browser, as `normalizeLocale` reads it. */
|
||||
lang = String((lang !== 'auto' && lang) || navigator.language || '').toLowerCase();
|
||||
/* The loading indicator's label reads it below, before i18n loads. */
|
||||
window.__lcBootLang = lang.replace(/_/g, '-');
|
||||
if (['ar', 'he', 'fa', 'ug'].indexOf(lang.split(/[-_]/)[0]) !== -1) {
|
||||
document.documentElement.dir = 'rtl';
|
||||
}
|
||||
|
|
@ -242,6 +271,9 @@
|
|||
justify-content: center;
|
||||
height: 100vh;
|
||||
background-color: ${backgroundColor};
|
||||
/* The theme's own text role (a deployment theme sets it on the root above); the
|
||||
* fallback is the default palette's value, for a stylesheet that has not loaded. */
|
||||
color: rgb(var(--text-primary, ${dark ? '236 236 236' : '33 33 33'}));
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(loadingContainerStyle);
|
||||
|
|
@ -414,7 +446,53 @@
|
|||
</head>
|
||||
<body>
|
||||
<div id="root">
|
||||
<div id="loading-container"></div>
|
||||
<div id="loading-container">
|
||||
<div class="boot-indicator" role="status">
|
||||
<svg
|
||||
class="spinner"
|
||||
width="32"
|
||||
height="32"
|
||||
viewBox="0 0 40 40"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
role="presentation"
|
||||
>
|
||||
<circle
|
||||
cx="20"
|
||||
cy="20"
|
||||
r="14.5"
|
||||
pathLength="100"
|
||||
stroke-width="5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-opacity="0.1"
|
||||
/>
|
||||
<circle
|
||||
cx="20"
|
||||
cy="20"
|
||||
r="14.5"
|
||||
pathLength="100"
|
||||
stroke-width="5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-dasharray="25 75"
|
||||
stroke-linecap="round"
|
||||
/>
|
||||
</svg>
|
||||
<span class="boot-indicator-label" id="boot-indicator-label">Loading...</span>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
/* Each locale's `com_ui_loading`, inlined at build time (`bootLoadingLabels`). */
|
||||
var labels = '__BOOT_LOADING_LABELS__';
|
||||
var lang = String(window.__lcBootLang || '');
|
||||
var label = labels[lang] || labels[lang.split('-')[0]] || labels.en;
|
||||
if (typeof label === 'string') {
|
||||
document.getElementById('boot-indicator-label').textContent = label;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
51
client/src/__tests__/loadingSpinner.spec.tsx
Normal file
51
client/src/__tests__/loadingSpinner.spec.tsx
Normal file
|
|
@ -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(<Spinner size={32} />);
|
||||
const component = container.querySelector('svg');
|
||||
expect(component).not.toBeNull();
|
||||
|
||||
expect(describeSvg(shellSpinner)).toEqual(describeSvg(component!));
|
||||
});
|
||||
});
|
||||
|
|
@ -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 (
|
||||
<div role="status" className="text-text-secondary flex items-center justify-center py-16">
|
||||
|
|
@ -160,7 +161,7 @@ function EmptyState({
|
|||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
|
||||
<p role="alert" className="text-text-secondary text-sm">
|
||||
{localize('com_ui_error_connection')}
|
||||
{localize(online ? 'com_ui_error_connection' : 'com_ui_error_offline')}
|
||||
</p>
|
||||
{/* The files query does not refetch on mount, focus or reconnect, so
|
||||
reopening the dialog would not recover without this. */}
|
||||
|
|
|
|||
|
|
@ -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<string, string | number>) =>
|
||||
options ? `${key}:${options['0']}` : key,
|
||||
useAuthContext: () => ({ user: { id: 'user-1' } }),
|
||||
useOnline: jest.requireActual('~/hooks/useOnline').default,
|
||||
}));
|
||||
|
||||
const renderGrid = (props: Partial<React.ComponentProps<typeof FileGrid>> = {}) => {
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Suspense fallback={<LoadingFallback />}>
|
||||
|
|
@ -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')}
|
||||
</Alert>
|
||||
</Container>
|
||||
</DelayedRender>
|
||||
|
|
|
|||
|
|
@ -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<string, string> = {
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
19
client/src/hooks/useOnline.ts
Normal file
19
client/src/hooks/useOnline.ts
Normal file
|
|
@ -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);
|
||||
}
|
||||
|
|
@ -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.",
|
||||
|
|
|
|||
|
|
@ -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<string, string>;
|
||||
|
||||
export const resources = {
|
||||
|
|
@ -108,54 +64,6 @@ const localeLoaders: Record<
|
|||
'zh-Hant': () => import('./zh-Hant/translation.json'),
|
||||
};
|
||||
|
||||
const localeByLowercase = supportedLocales.reduce<Record<string, SupportedLocale>>(
|
||||
(acc, locale) => {
|
||||
acc[locale.toLowerCase()] = locale;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
const localeAliases: Record<string, SupportedLocale> = {
|
||||
'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<SupportedLocale>(['en']);
|
||||
const loadingLocales: Partial<Record<SupportedLocale, Promise<SupportedLocale>>> = {};
|
||||
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() {
|
||||
|
|
|
|||
122
client/src/locales/resolve.ts
Normal file
122
client/src/locales/resolve.ts
Normal file
|
|
@ -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<Record<string, SupportedLocale>>(
|
||||
(acc, locale) => {
|
||||
acc[locale.toLowerCase()] = locale;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
);
|
||||
|
||||
export const localeAliases: Record<string, SupportedLocale> = {
|
||||
'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';
|
||||
}
|
||||
|
|
@ -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 `<script>` at the end of `<head>`. On a slow
|
||||
* HTTP/1.1 link it queues behind every modulepreload, so the body, and with it
|
||||
* the loading canvas, cannot paint until most of the bundle has downloaded.
|
||||
* Registration itself waits for `load` either way. */
|
||||
injectRegister: 'script-defer',
|
||||
registerType: 'autoUpdate', // 'prompt' | 'autoUpdate'
|
||||
devOptions: {
|
||||
enabled: false, // disable service worker registration in development mode
|
||||
|
|
@ -562,6 +568,44 @@ export function themeCacheVersion(): Plugin {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The shell's loading indicator announces itself before i18n loads, so the build inlines each
|
||||
* locale's `com_ui_loading` and the boot script picks the one for the language it detected.
|
||||
*/
|
||||
export function bootLoadingLabels(): Plugin {
|
||||
return {
|
||||
name: 'boot-loading-labels',
|
||||
transformIndexHtml: (html) =>
|
||||
html.replace(
|
||||
"'__BOOT_LOADING_LABELS__'",
|
||||
JSON.stringify(readLoadingLabels()).replace(/</g, '\\u003c'),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function readLoadingLabels(): Record<string, string> {
|
||||
const localesDir = path.join(import.meta.dirname, 'src/locales');
|
||||
const labelOf = (locale: string): string | undefined => {
|
||||
const file = path.join(localesDir, locale, 'translation.json');
|
||||
const label = fs.existsSync(file)
|
||||
? JSON.parse(fs.readFileSync(file, 'utf8')).com_ui_loading
|
||||
: undefined;
|
||||
return typeof label === 'string' ? label : undefined;
|
||||
};
|
||||
const english = labelOf('en') ?? 'Loading...';
|
||||
/* Every key the app's `resolveLocale` accepts, exact or alias, mapped through it, so the
|
||||
shell announces the locale the app is about to load (`zh-tw` is Traditional, `pt` is
|
||||
European Portuguese). The shell falls back to the base language, then to English. */
|
||||
const labels: Record<string, string> = {};
|
||||
for (const key of [
|
||||
...supportedLocales.map((locale) => locale.toLowerCase()),
|
||||
...Object.keys(localeAliases),
|
||||
]) {
|
||||
labels[key] = labelOf(resolveLocale(key)) ?? english;
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
|
||||
interface SourcemapExclude {
|
||||
excludeNodeModules?: boolean;
|
||||
}
|
||||
|
|
|
|||
131
e2e/specs/mock/scenarios/slow-network.spec.ts
Normal file
131
e2e/specs/mock/scenarios/slow-network.spec.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import type { Page } from '@playwright/test';
|
||||
import {
|
||||
MOCK_ENDPOINTS,
|
||||
NEW_CHAT_PATH,
|
||||
modelSelectorTrigger,
|
||||
selectMockEndpoint,
|
||||
} from '../helpers';
|
||||
import { expect, test } from '../fixtures';
|
||||
|
||||
const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message input' });
|
||||
|
||||
/** Providers A and B show as model specs; C and D are plain endpoint rows with models. */
|
||||
const KEY_ENDPOINT = 'Mock Provider C';
|
||||
const NEIGHBOUR_ENDPOINT = 'Mock Provider D';
|
||||
|
||||
/** No mock endpoint asks for a user key, so the served config marks one as user-provided. */
|
||||
async function requireUserKey(page: Page, label: string): Promise<void> {
|
||||
await page.route(
|
||||
(url) => url.pathname === '/api/endpoints',
|
||||
async (route) => {
|
||||
const response = await route.fetch();
|
||||
const endpoints = await response.json();
|
||||
endpoints[label] = { ...endpoints[label], userProvide: true };
|
||||
await route.fulfill({ response, json: endpoints });
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test.describe('slow and lost connections', () => {
|
||||
test('the loading shell shows progress while the bundle downloads @scenario:loading-shell-shows-progress-on-a-slow-load', async ({
|
||||
page,
|
||||
}) => {
|
||||
/* Hold the worker registration and the entry bundle the way a slow link does. The
|
||||
registration script used to block the parser, so nothing below it could paint. */
|
||||
await page.route(/\/registerSW\.js(\?|$)/, () => undefined);
|
||||
await page.route(/\/assets\/index\.[^/]+\.js(\?|$)/, () => undefined);
|
||||
await page.goto(NEW_CHAT_PATH, { waitUntil: 'commit' });
|
||||
|
||||
const indicator = page.locator('#loading-container').getByRole('status');
|
||||
await expect(indicator).toBeVisible();
|
||||
await expect(indicator).toHaveText('Loading...');
|
||||
await expect
|
||||
.poll(() => indicator.evaluate((el) => Number(getComputedStyle(el).opacity)), {
|
||||
timeout: 5000,
|
||||
})
|
||||
.toBeGreaterThan(0);
|
||||
/* It inks in the theme's text role, not a fixed color. */
|
||||
const [ink, role] = await indicator.evaluate((el) => {
|
||||
const probe = document.createElement('span');
|
||||
probe.style.color = 'rgb(var(--text-primary))';
|
||||
document.body.appendChild(probe);
|
||||
return [getComputedStyle(el).color, getComputedStyle(probe).color];
|
||||
});
|
||||
expect(ink).toBe(role);
|
||||
});
|
||||
|
||||
test('the loading label follows the language chosen before the bundle loads @scenario:loading-shell-label-follows-language', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.addInitScript(() => localStorage.setItem('lang', JSON.stringify('de-DE')));
|
||||
await page.route(/\/assets\/index\.[^/]+\.js(\?|$)/, () => undefined);
|
||||
await page.goto(NEW_CHAT_PATH, { waitUntil: 'commit' });
|
||||
|
||||
await expect(page.locator('#loading-container').getByRole('status')).toHaveText('Lade …');
|
||||
});
|
||||
|
||||
test.describe('with the browser language', () => {
|
||||
test.use({ locale: 'zh-TW' });
|
||||
|
||||
test('the loading label resolves the browser language the way the app does @scenario:loading-shell-label-follows-browser-locale', async ({
|
||||
page,
|
||||
}) => {
|
||||
/* `auto` defers to the browser, and zh-TW resolves to Traditional Chinese, not the first
|
||||
zh variant. */
|
||||
await page.addInitScript(() => localStorage.setItem('lang', JSON.stringify('auto')));
|
||||
await page.route(/\/assets\/index\.[^/]+\.js(\?|$)/, () => undefined);
|
||||
await page.goto(NEW_CHAT_PATH, { waitUntil: 'commit' });
|
||||
|
||||
await expect(page.locator('#loading-container').getByRole('status')).toHaveText('載入中…');
|
||||
});
|
||||
});
|
||||
|
||||
test('a message sent offline names the lost connection @scenario:offline-send-names-the-lost-connection', async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
|
||||
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
|
||||
await expect(messageInput(page)).toBeVisible();
|
||||
|
||||
await context.setOffline(true);
|
||||
await messageInput(page).fill('hello while offline');
|
||||
await messageInput(page).press('Enter');
|
||||
await expect(
|
||||
page.getByText("You're offline. Check your connection and try again."),
|
||||
).toBeVisible({ timeout: 20000 });
|
||||
|
||||
await context.setOffline(false);
|
||||
await expect(
|
||||
page.getByText('Error connecting to server, try refreshing the page.'),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('the endpoint key button is large enough to tap @scenario:endpoint-key-button-touch-target', async ({
|
||||
page,
|
||||
}) => {
|
||||
await requireUserKey(page, KEY_ENDPOINT);
|
||||
await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
|
||||
await modelSelectorTrigger(page).click();
|
||||
|
||||
const keyButton = page.getByRole('button', { name: `Set API Key ${KEY_ENDPOINT}` });
|
||||
await expect(keyButton).toBeVisible();
|
||||
/* Layout size, not the bounding box: the menu scales in, so a box read mid-animation is short. */
|
||||
const size = await keyButton.evaluate((el) => ({
|
||||
width: (el as HTMLElement).offsetWidth,
|
||||
height: (el as HTMLElement).offsetHeight,
|
||||
}));
|
||||
const coarse = await page.evaluate(() => matchMedia('(any-pointer: coarse)').matches);
|
||||
const minimum = coarse ? 32 : 24;
|
||||
expect(size.height).toBeGreaterThanOrEqual(minimum);
|
||||
expect(size.width).toBeGreaterThanOrEqual(minimum);
|
||||
|
||||
/* The larger target spills into the row's padding; the row keeps its neighbours' height. */
|
||||
const rowHeight = (label: string) =>
|
||||
page
|
||||
.getByRole('option', { name: new RegExp(`^${label}`) })
|
||||
.first()
|
||||
.evaluate((el) => (el as HTMLElement).offsetHeight);
|
||||
expect(await rowHeight(KEY_ENDPOINT)).toBe(await rowHeight(NEIGHBOUR_ENDPOINT));
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue