Bug fixing and debugs (#5704)

Co-authored-by: ConnorYoh <[email protected]>
This commit is contained in:
Anthony Stirling
2026-02-11 18:43:29 +00:00
committed by GitHub
co-authored by ConnorYoh
parent 5df466266a
commit f9d2f36ab7
20 changed files with 385 additions and 54 deletions
@@ -37,7 +37,6 @@ export default class ErrorBoundary extends React.Component<ErrorBoundaryProps, E
console.error('Current search:', window.location.search);
console.error('Timestamp:', new Date().toISOString());
console.error('User agent:', navigator.userAgent);
// Check for React error codes
if (error.message.includes('Minified React error')) {
const errorCodeMatch = error.message.match(/#(\d+)/);
@@ -108,4 +107,4 @@ export default class ErrorBoundary extends React.Component<ErrorBoundaryProps, E
return this.props.children;
}
}
}
@@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
import { Menu, Button, ActionIcon } from '@mantine/core';
import { Tooltip } from '@app/components/shared/Tooltip';
import { useTranslation } from 'react-i18next';
import { supportedLanguages } from '@app/i18n';
import { supportedLanguages, setUserLanguage } from '@app/i18n';
import LocalIcon from '@app/components/shared/LocalIcon';
import styles from '@app/components/shared/LanguageSelector.module.css';
import { Z_INDEX_CONFIG_MODAL } from '@app/styles/zIndex';
@@ -206,7 +206,8 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({
// Simulate processing time for smooth transition
setTimeout(() => {
i18n.changeLanguage(value);
// Use setUserLanguage to properly set priority (ensures user choice persists across sessions)
setUserLanguage(value);
setTimeout(() => {
setPendingLanguage(null);
@@ -122,6 +122,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
}
setError(null);
const startTime = performance.now();
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const testConfig = getSimulatedAppConfig();
@@ -142,6 +143,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
// apiClient automatically adds JWT header if available via interceptors
// Always suppress error toast - we handle 401 errors locally
console.debug('[AppConfig] Fetching app config', { attempt, force, path: window.location.pathname });
const response = await apiClient.get<AppConfig>(
'/api/v1/config/app-config',
{
@@ -152,6 +154,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const data = response.data;
console.debug('[AppConfig] Config fetched successfully:', data);
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
setConfig(data);
setHasResolvedConfig(true);
setLoading(false);
@@ -163,6 +166,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
// This allows the app to work even without authentication
if (status === 401) {
console.debug('[AppConfig] 401 error - using default config (login enabled)');
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
setConfig({ enableLogin: true });
setHasResolvedConfig(true);
setLoading(false);
@@ -181,6 +185,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
const errorMessage = err?.response?.data?.message || err?.message || 'Unknown error occurred';
setError(errorMessage);
console.error(`[AppConfig] Failed to fetch app config after ${attempt + 1} attempts:`, err);
console.debug('[AppConfig] Fetch duration ms:', (performance.now() - startTime).toFixed(2));
// Preserve existing config (initial default or previous fetch). If nothing is set, assume login enabled.
setConfig((current) => current ?? { enableLogin: true });
setHasResolvedConfig(true);
@@ -203,7 +208,7 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
// On auth pages, always skip the config fetch
// The config will be fetched after authentication via jwt-available event
if (isAuthPage) {
console.debug('[AppConfig] On auth page - using default config, skipping fetch');
console.debug('[AppConfig] On auth page - using default config, skipping fetch', { path: currentPath });
setConfig({ enableLogin: true });
setHasResolvedConfig(true);
setLoading(false);
@@ -30,6 +30,7 @@ export function useEndpointEnabled(endpoint: string): {
try {
setLoading(true);
setError(null);
console.debug('[useEndpointConfig] Fetch endpoint status', { endpoint });
const response = await apiClient.get<boolean>(`/api/v1/config/endpoint-enabled?endpoint=${encodeURIComponent(endpoint)}`);
const isEnabled = response.data;
@@ -102,6 +103,7 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
try {
setLoading(true);
setError(null);
console.debug('[useEndpointConfig] Fetching endpoint statuses', { count: endpoints.length, force });
// Check which endpoints we haven't fetched yet
const newEndpoints = endpoints.filter(ep => !(ep in globalEndpointCache));
+73 -10
View File
@@ -50,6 +50,23 @@ export const supportedLanguages = {
// RTL languages (based on your existing language.direction property)
export const rtlLanguages = ['ar-AR', 'fa-IR'];
// LocalStorage keys for i18next
export const I18N_STORAGE_KEYS = {
LANGUAGE: 'i18nextLng',
LANGUAGE_SOURCE: 'i18nextLng-source',
} as const;
/**
* Language selection priority levels
* Higher number = higher priority (cannot be overridden by lower priority)
*/
export enum LanguageSource {
Fallback = 0,
Browser = 1,
ServerDefault = 2,
User = 3,
}
i18n
.use(TomlBackend)
.use(LanguageDetector)
@@ -79,7 +96,7 @@ i18n
detection: {
order: ['localStorage', 'navigator', 'htmlTag'],
caches: ['localStorage'],
caches: [], // Don't cache auto-detected language - only cache when user manually selects
convertDetectedLanguage: (lng: string) => {
// Map en and en-US to en-GB
if (lng === 'en' || lng === 'en-US') return 'en-GB';
@@ -105,6 +122,18 @@ i18n.on('languageChanged', (lng) => {
document.documentElement.lang = lng;
});
// Track browser-detected language on first initialization
i18n.on('initialized', () => {
// If no source is set yet, mark current language as browser-detected
if (!localStorage.getItem(I18N_STORAGE_KEYS.LANGUAGE_SOURCE)) {
const detectedLang = i18n.language;
if (detectedLang) {
localStorage.setItem(I18N_STORAGE_KEYS.LANGUAGE, detectedLang);
localStorage.setItem(I18N_STORAGE_KEYS.LANGUAGE_SOURCE, String(LanguageSource.Browser));
}
}
});
export function normalizeLanguageCode(languageCode: string): string {
// Replace underscores with hyphens to align with i18next/translation file naming
const hyphenated = languageCode.replace(/_/g, '-');
@@ -133,6 +162,42 @@ export function toUnderscoreLanguages(languages: string[]): string[] {
return languages.map(toUnderscoreFormat);
}
/**
* Get the current language source priority
*/
function getCurrentSourcePriority(): LanguageSource {
const sourceStr = localStorage.getItem(I18N_STORAGE_KEYS.LANGUAGE_SOURCE);
const sourceNum = sourceStr ? parseInt(sourceStr, 10) : null;
return (sourceNum !== null && !isNaN(sourceNum)) ? sourceNum as LanguageSource : LanguageSource.Fallback;
}
/**
* Set language with priority tracking
* Only updates if new source has equal or higher priority than current
*/
function setLanguageWithPriority(language: string, source: LanguageSource): boolean {
const currentPriority = getCurrentSourcePriority();
const newPriority = source;
// Only apply if new source has higher priority
if (newPriority >= currentPriority) {
i18n.changeLanguage(language);
localStorage.setItem(I18N_STORAGE_KEYS.LANGUAGE, language);
localStorage.setItem(I18N_STORAGE_KEYS.LANGUAGE_SOURCE, String(source));
return true;
}
return false;
}
/**
* Set user-selected language (highest priority)
* Call this from the UI language selector
*/
export function setUserLanguage(language: string): void {
setLanguageWithPriority(language, LanguageSource.User);
}
/**
* Updates the supported languages list dynamically based on config
* If configLanguages is null/empty, all languages remain available
@@ -178,22 +243,20 @@ export function updateSupportedLanguages(configLanguages?: string[] | null, defa
// If current language is not in the new supported list, switch to fallback
const currentLang = normalizeLanguageCode(i18n.language || '');
if (currentLang && !validLanguages.includes(currentLang)) {
i18n.changeLanguage(fallback);
} else if (validDefault && !localStorage.getItem('i18nextLng')) {
// User has no saved preference - apply server default
i18n.changeLanguage(validDefault);
setLanguageWithPriority(fallback, LanguageSource.Fallback);
} else if (validDefault) {
// Apply server default (respects user choice if already set)
setLanguageWithPriority(validDefault, LanguageSource.ServerDefault);
}
}
/**
* Apply server default locale when user has no saved language preference
* This respects the priority: localStorage > defaultLocale > browser detection > fallback
* This respects the priority: user-selected language > defaultLocale > browser detection > fallback
*/
function applyDefaultLocale(defaultLocale: string) {
// Only apply if user has no saved preference
if (!localStorage.getItem('i18nextLng')) {
i18n.changeLanguage(defaultLocale);
}
// Apply server default (respects user choice if already set)
setLanguageWithPriority(defaultLocale, LanguageSource.ServerDefault);
}
export default i18n;