ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(i18n): locale runtime, precedence, and a per-user language column
Juan Denisb851f48ef02b
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.pyindex 92dbc08c..5a364a92 100644--- a/backend/app/api/auth.py+++ b/backend/app/api/auth.py@@ -18,6 +18,7 @@ from app.services.audit_service import AuditServicefrom app.services import login_link_servicefrom app.services import auth_throttle_servicefrom app.utils.client_ip import get_client_ip+from app.utils.i18n import normalize_languagelogger = logging.getLogger(__name__)@@ -48,6 +49,9 @@ def get_setup_status():'panel_title': SettingsService.get('panel_title', 'ServerKit'),'public_title': SettingsService.get('public_title', 'Control Panel'),'login_layout': SettingsService.get('login_layout', 'centered'),+ # Panel-default UI language for the sign-in/setup screens, which render+ # before any authenticated call can report the user's own choice.+ 'default_language': SettingsService.get('default_language', 'en'),'needs_migration': migration_status['needs_migration'],'migration_info': {'pending_count': migration_status['pending_count'],@@ -485,8 +489,25 @@ def get_current_user():return jsonify({'user': user.to_dict()}), 200+def _is_preference_only_update():+ """True when PUT /me carries no credential change.++ The 3/minute limit on this route exists for username/email/password edits.+ Cosmetic preferences (sidebar layout, language) go through the same route+ and would otherwise burn that budget: switching language three times in a+ minute returns 429, and since the client applies the change locally either+ way, the preference silently fails to persist and reverts on the next+ sign-in elsewhere. Credential changes stay throttled; the app-wide+ 100/minute default still covers everything else.+ """+ data = request.get_json(silent=True) or {}+ if not isinstance(data, dict) or not data:+ return False+ return not ({'username', 'email', 'password'} & set(data.keys()))++@auth_bp.route('/me', methods=['PUT'])[email protected]("3 per minute")[email protected]("3 per minute", exempt_when=_is_preference_only_update)@jwt_required()def update_current_user():current_user_id = get_jwt_identity()@@ -528,6 +549,17 @@ def update_current_user():return jsonify({'error': 'hiddenItems must be a list'}), 400user.set_sidebar_config({'preset': preset, 'hiddenItems': hidden})+ if 'language' in data:+ raw = data['language']+ if raw in (None, ''):+ # Explicitly clearing the preference: fall back to the panel default.+ user.language = None+ else:+ language = normalize_language(raw)+ if not language:+ return jsonify({'error': f'Unsupported language: {raw}'}), 400+ user.language = language+db.session.commit()return jsonify({'user': user.to_dict()}), 200diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex 285e51c8..c4bc2124 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -46,6 +46,12 @@ class User(JsonColumnMixin, db.Model):# Sidebar preferences: { preset: 'full'|'web'|'email'|'devops'|'minimal'|'custom', hiddenItems: [...] }sidebar_config = db.Column(db.Text, nullable=True)+ # Preferred UI language as a BCP-47 language code (plan 79 B2). NULL means+ # "follow the panel default", which is a genuinely different state from an+ # explicit choice of English -- the same distinction ThemeContext draws+ # between an inherited skin and a picked one.+ language = db.Column(db.String(10), nullable=True)+# Per-user Setup Health item snoozes: JSON { item_key: iso_expiry } (plan 22# Phase 6). Panel-item snoozes live in a SettingsService map instead.setup_snoozes = db.Column(db.Text, nullable=True)@@ -200,6 +206,7 @@ class User(JsonColumnMixin, db.Model):'has_password': self.has_password,'passkey_enabled': self.passkeys.filter_by(is_active=True).count() > 0,'sidebar_config': self.get_sidebar_config(),+ 'language': self.language,'created_at': self.created_at.isoformat(),'updated_at': self.updated_at.isoformat(),'last_login_at': self.last_login_at.isoformat() if self.last_login_at else None,diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.pyindex aa7377a8..e4871aa7 100644--- a/backend/app/services/settings_service.py+++ b/backend/app/services/settings_service.py@@ -34,6 +34,11 @@ class SettingsService:'type': 'string','description': 'Generic name shown on the public sign-in/register pages (kept brand-neutral on purpose)'},+ 'default_language': {+ 'value': 'en',+ 'type': 'string',+ 'description': 'Panel-default UI language (BCP-47 code) for the sign-in/setup screens and for users who have not chosen one'+ },'login_layout': {'value': 'centered','type': 'string',diff --git a/backend/app/utils/i18n.py b/backend/app/utils/i18n.pynew file mode 100644index 00000000..91f3bd1a--- /dev/null+++ b/backend/app/utils/i18n.py@@ -0,0 +1,44 @@+"""Supported UI languages (plan 79 B2).++The **canonical** list is the frontend manifest,+``frontend/src/i18n/languages.json`` — that is what the browser actually loads+bundles for, and shipping a language means putting a JSON file next to it.++This module exists because the API has to validate what it stores: a user row+carrying a code the panel cannot render is a preference that silently does+nothing. Rather than have the backend fetch or parse the frontend at runtime,+the list is restated here and ``tests/test_i18n_language_manifest.py`` fails+the build if the two ever disagree. Two lists with a parity test beats one list+the backend cannot see, and beats validating nothing at all.+"""++import re++# Keep in sync with frontend/src/i18n/languages.json (enforced by test).+SUPPORTED_LANGUAGES = ('en', 'es')++DEFAULT_LANGUAGE = 'en'++# Shape gate applied before the allowlist so a malformed value is rejected for+# being malformed, not for being unknown.+_LANGUAGE_TAG = re.compile(r'^[a-z]{2,3}(-[a-z0-9]{2,8})*$')+++def normalize_language(value):+ """Return a supported language code for ``value``, or ``None``.++ Matches language-only, so ``es-MX`` and ``ES`` both resolve to ``es`` —+ the panel ships no region-specific bundles, and rejecting a region tag+ would reject most real browser values.+ """+ if not isinstance(value, str):+ return None+ # Case-fold first: browsers send `es-MX`, `ES`, and `es-mx` for the same+ # thing, and a case-sensitive shape gate would reject two of the three.+ tag = value.strip().replace('_', '-').lower()+ if not tag or len(tag) > 10 or not _LANGUAGE_TAG.match(tag):+ return None+ if tag in SUPPORTED_LANGUAGES:+ return tag+ base = tag.split('-')[0]+ return base if base in SUPPORTED_LANGUAGES else Nonediff --git a/backend/migrations/versions/089_user_language.py b/backend/migrations/versions/089_user_language.pynew file mode 100644index 00000000..225ce444--- /dev/null+++ b/backend/migrations/versions/089_user_language.py@@ -0,0 +1,34 @@+"""Per-user UI language preference: `users.language`.++Plan 79 B2. Nullable on purpose — NULL means "follow the panel default"+(`default_language` in system settings), which is a different state from an+explicit choice of English, so existing rows are left alone rather than+backfilled to 'en'.++Revision ID: 089_user_language+Revises: 088_soft_delete_managed_databases+"""+import sqlalchemy as sa+from alembic import op++revision = '089_user_language'+down_revision = '088_soft_delete_managed_databases'+branch_labels = None+depends_on = None+++def _has_column(table, column):+ bind = op.get_bind()+ return column in {col['name'] for col in sa.inspect(bind).get_columns(table)}+++def upgrade():+ if _has_column('users', 'language'):+ return+ op.add_column('users', sa.Column('language', sa.String(length=10), nullable=True))+++def downgrade():+ if not _has_column('users', 'language'):+ return+ op.drop_column('users', 'language')diff --git a/backend/tests/test_user_language_preference.py b/backend/tests/test_user_language_preference.pynew file mode 100644index 00000000..0ef0e676--- /dev/null+++ b/backend/tests/test_user_language_preference.py@@ -0,0 +1,146 @@+"""Per-user UI language preference (plan 79 B2).++Two things are proved here:++1. The backend's supported-language list has not drifted from the frontend+ manifest, which is the canonical one. A backend that accepts a code the+ browser has no bundle for stores a preference that silently does nothing.+2. `PUT /api/v1/auth/me` persists the choice, normalises regional tags, clears+ back to "follow the panel default", and refuses junk.+"""++import json+from pathlib import Path++import pytest++from app.utils.i18n import DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES, normalize_language++MANIFEST = (+ Path(__file__).resolve().parents[2]+ / 'frontend' / 'src' / 'i18n' / 'languages.json'+)+++def test_backend_language_list_matches_the_frontend_manifest():+ """The manifest is canonical; this list only exists so the API can validate.++ If this fails, the fix is almost always to update SUPPORTED_LANGUAGES in+ app/utils/i18n.py -- not to edit the manifest, which is what actually+ decides which bundles ship.+ """+ manifest = json.loads(MANIFEST.read_text(encoding='utf-8'))+ manifest_codes = tuple(entry['code'] for entry in manifest['languages'])++ assert manifest_codes == SUPPORTED_LANGUAGES, (+ f'frontend manifest ships {manifest_codes}, '+ f'backend accepts {SUPPORTED_LANGUAGES}'+ )+++def test_manifest_entries_are_complete():+ manifest = json.loads(MANIFEST.read_text(encoding='utf-8'))+ for entry in manifest['languages']:+ assert entry['dir'] in ('ltr', 'rtl'), entry+ assert entry['status'] in ('stable', 'provisional'), entry+ assert entry['name'] and entry['nativeName'], entry++ codes = [entry['code'] for entry in manifest['languages']]+ assert DEFAULT_LANGUAGE in codes+ assert len(codes) == len(set(codes)), 'duplicate language code in manifest'++[email protected]('raw,expected', [+ ('en', 'en'),+ ('es', 'es'),+ ('ES', 'es'),+ ('es-MX', 'es'), # region tags resolve language-only ...+ ('es_419', 'es'), # ... including the underscore form+ ('en-GB', 'en'),+ (' es ', 'es'),+ ('fr', None), # well-formed but not shipped+ ('zz-ZZ', None),+ ('', None),+ (' ', None),+ ('e', None),+ ('en; DROP TABLE users', None),+ ('../../etc/passwd', None),+ ('a' * 40, None),+ (None, None),+ (12, None),+ (['en'], None),+])+def test_normalize_language(raw, expected):+ assert normalize_language(raw) == expected+++def test_put_me_persists_language(client, auth_headers):+ response = client.put('/api/v1/auth/me', json={'language': 'es'},+ headers=auth_headers)+ assert response.status_code == 200+ assert response.get_json()['user']['language'] == 'es'++ # Survives a fresh read -- the point of the column over localStorage.+ response = client.get('/api/v1/auth/me', headers=auth_headers)+ assert response.get_json()['user']['language'] == 'es'+++def test_put_me_normalizes_a_regional_tag(client, auth_headers):+ response = client.put('/api/v1/auth/me', json={'language': 'es-MX'},+ headers=auth_headers)+ assert response.status_code == 200+ assert response.get_json()['user']['language'] == 'es'+++def test_put_me_rejects_an_unsupported_language(client, auth_headers):+ response = client.put('/api/v1/auth/me', json={'language': 'fr'},+ headers=auth_headers)+ assert response.status_code == 400+ assert 'fr' in response.get_json()['error']+++def test_put_me_clears_back_to_the_panel_default(client, auth_headers):+ client.put('/api/v1/auth/me', json={'language': 'es'}, headers=auth_headers)++ response = client.put('/api/v1/auth/me', json={'language': None},+ headers=auth_headers)+ assert response.status_code == 200+ # NULL, not 'en': "follow the panel default" is its own state.+ assert response.get_json()['user']['language'] is None+++def test_new_user_has_no_language_preference(client, auth_headers):+ response = client.get('/api/v1/auth/me', headers=auth_headers)+ assert response.get_json()['user']['language'] is None+++def test_setup_status_exposes_the_panel_default(client):+ """The sign-in screen renders before any authenticated call can answer."""+ response = client.get('/api/v1/auth/setup-status')+ assert response.status_code == 200+ assert response.get_json()['default_language'] == DEFAULT_LANGUAGE+++def test_preference_updates_do_not_burn_the_credential_throttle(client, auth_headers):+ """Switching language repeatedly must not 429.++ PUT /me is throttled at 3/minute for credential edits. Language rides the+ same route, and the client applies the change locally before the request+ lands -- so a throttled write means the UI shows Spanish while the user row+ still says English, and the choice quietly reverts on the next sign-in from+ another browser. That is precisely the promise the column exists to keep.+ """+ for code in ('es', 'en', 'es', 'en', 'es'):+ response = client.put('/api/v1/auth/me', json={'language': code},+ headers=auth_headers)+ assert response.status_code == 200, response.get_json()+++def test_credential_updates_are_still_throttled(client, auth_headers):+ """The exemption must not open the door it was carved out of."""+ statuses = [+ client.put('/api/v1/auth/me', json={'password': 'new-password-123'},+ headers=auth_headers).status_code+ for _ in range(5)+ ]+ assert 429 in statuses, statusesdiff --git a/frontend/eslint.config.js b/frontend/eslint.config.jsindex d5358509..f3da3d56 100644--- a/frontend/eslint.config.js+++ b/frontend/eslint.config.js@@ -9,7 +9,10 @@ export default [{files: ['**/*.{js,jsx}'],languageOptions: {- ecmaVersion: 2022,+ // 'latest' rather than a pinned year: import attributes+ // (`with { type: 'json' }`) are ES2025 and are required by Node's test+ // runner for the i18n manifest imports.+ ecmaVersion: 'latest',sourceType: 'module',globals: {...globals.browser,diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 7a8bc6fb..e06ee364 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -3,6 +3,7 @@ import { BrowserRouter as Router, Routes, Route, Navigate, useLocation, useParamimport { AuthProvider, useAuth } from './contexts/AuthContext';import { ToastProvider } from './contexts/ToastContext';import { ThemeProvider } from './contexts/ThemeContext';+import { LocaleProvider } from './contexts/LocaleContext';import { LayoutProvider } from './contexts/LayoutContext';import { ResourceTierProvider } from './contexts/ResourceTierContext';import { NotificationsProvider } from './contexts/NotificationsContext';@@ -10,6 +11,7 @@ import { WorkspaceProvider } from './contexts/WorkspaceContext';import { rememberRedirect } from './utils/redirectAfterLogin';import { Toaster } from './components/ui/sonner';import ThemeSync from './components/ThemeSync';+import LocaleSync from './components/LocaleSync';import DashboardLayout from './layouts/DashboardLayout';import AppLoader from './components/AppLoader';import TabGroupLayout from './layouts/TabGroupLayout';@@ -242,6 +244,9 @@ function AppRoutes() {function App() {return (<Router>+ {/* Outermost: a toast raised while the theme or workspace is still+ initialising must already be translatable (plan 79 B1). */}+ <LocaleProvider><WorkspaceProvider><ThemeProvider><LayoutProvider>@@ -251,6 +256,7 @@ function App() {the provider. It stays inside Router for useLocation. */}<PageTitleUpdater /><ThemeSync />+ <LocaleSync /><ResourceTierProvider><ToastProvider><NotificationsProvider>@@ -263,6 +269,7 @@ function App() {</LayoutProvider></ThemeProvider></WorkspaceProvider>+ </LocaleProvider></Router>);}diff --git a/frontend/src/components/LocaleSync.jsx b/frontend/src/components/LocaleSync.jsxnew file mode 100644index 00000000..94dd2098--- /dev/null+++ b/frontend/src/components/LocaleSync.jsx@@ -0,0 +1,46 @@+import { useEffect } from 'react';+import { useAuth } from '../contexts/AuthContext';+import { useLocale } from '../contexts/LocaleContext';+import api from '../services/api';++// Bridges auth -> locale (plan 79 B1/B2). LocaleProvider sits above+// AuthProvider so the sign-in screen is translated before anyone is signed in,+// which means it cannot read auth state itself. This renders inside+// AuthProvider and does two things:+//+// 1. Pushes the panel default (pre-auth, from /auth/setup-status) and the+// signed-in user's stored language into the provider.+// 2. Registers the writer that persists an explicit choice to the user row,+// so the preference survives a different browser -- the gap in most+// implementations of this, which only call changeLanguage().+//+// Renders nothing.+const LocaleSync = () => {+ const { user, isAuthenticated, setupStatus } = useAuth();+ const { applyServerPreferences, registerPersist } = useLocale();++ const panelDefault = setupStatus?.defaultLanguage;+ const checked = setupStatus?.checked;+ const userLanguage = user?.language ?? null;++ useEffect(() => {+ // Wait for the pre-auth probe to land, otherwise the panel default is+ // always undefined and the browser language wins a race it should lose.+ if (!checked) return;+ applyServerPreferences({ userLanguage, panelDefault });+ }, [checked, userLanguage, panelDefault, applyServerPreferences]);++ useEffect(() => {+ if (!isAuthenticated) return undefined;+ return registerPersist((code) => {+ api.updateCurrentUser({ language: code }).catch(() => {+ // The choice is already applied and cached locally; failing to+ // record it server-side must not undo it in front of the user.+ });+ });+ }, [isAuthenticated, registerPersist]);++ return null;+};++export default LocaleSync;diff --git a/frontend/src/contexts/AuthContext.jsx b/frontend/src/contexts/AuthContext.jsxindex fd49025a..a40bebdb 100644--- a/frontend/src/contexts/AuthContext.jsx+++ b/frontend/src/contexts/AuthContext.jsx@@ -17,6 +17,10 @@ export function AuthProvider({ children }) {panelTitle: import.meta.env.VITE_PANEL_TITLE || 'ServerKit',publicTitle: 'Control Panel',loginLayout: 'centered',+ // Panel-wide default language for the pre-auth screens (plan 79 A4).+ // null = not fetched yet, so the browser language does not win a race+ // against a panel that has an opinion.+ defaultLanguage: null,needsMigration: false,migrationInfo: null,checked: false@@ -43,6 +47,7 @@ export function AuthProvider({ children }) {panelTitle: status.panel_title || import.meta.env.VITE_PANEL_TITLE || 'ServerKit',publicTitle: status.public_title || 'Control Panel',loginLayout: status.login_layout || 'centered',+ defaultLanguage: status.default_language || null,needsMigration: status.needs_migration || false,migrationInfo: status.migration_info || null,checked: truediff --git a/frontend/src/contexts/LocaleContext.jsx b/frontend/src/contexts/LocaleContext.jsxnew file mode 100644index 00000000..2e7f0016--- /dev/null+++ b/frontend/src/contexts/LocaleContext.jsx@@ -0,0 +1,126 @@+import {+ createContext, useCallback, useContext, useEffect, useMemo, useRef, useState,+} from 'react';+import { activateLocale } from '../i18n';+import {+ DEFAULT_LANGUAGE, LANGUAGES, STORAGE_KEY,+ directionFor, languageInfo, matchSupported, navigatorLanguages, resolveLocale,+} from '../i18n/resolveLocale';++const LocaleContext = createContext(null);++/**+ * Owns the active locale (plan 79 §B1).+ *+ * Sits ABOVE AuthProvider — the login screen has to be translated before+ * anyone is signed in — so it cannot read auth state itself. The bridge is+ * LocaleSync, which renders inside AuthProvider and pushes the user's stored+ * preference and the panel default down through `applyServerPreferences`.+ * Exactly the arrangement ThemeProvider/ThemeSync already uses.+ */+export function LocaleProvider({ children }) {+ // Synchronous first value: whatever the last session stored, else the+ // browser's own languages. Anything that needs a round trip would repaint.+ const [language, setLanguageState] = useState(() => resolveLocale({+ stored: readStored(),+ navigatorLanguages: navigatorLanguages(),+ }));++ // True once the active bundle is in memory. `en` is bundled, so this is+ // only ever false while a non-default locale's chunk is in flight.+ const [ready, setReady] = useState(language === DEFAULT_LANGUAGE);++ // Set by LocaleSync; persists the choice server-side when signed in.+ const persistRef = useRef(null);+ // Guards the one-shot server hydration so a user who switches language+ // during page load does not get overwritten by their own stored value.+ const hydratedRef = useRef(false);++ useEffect(() => {+ let cancelled = false;+ activateLocale(language).then((applied) => {+ if (cancelled) return;+ setReady(true);+ // The bundle we asked for may not exist; follow what took effect.+ if (applied !== language) setLanguageState(applied);+ });+ return () => { cancelled = true; };+ }, [language]);++ useEffect(() => {+ const root = document.documentElement;+ root.setAttribute('lang', language);+ root.setAttribute('dir', directionFor(language));+ }, [language]);++ const setLanguage = useCallback((code) => {+ const next = matchSupported(code) || DEFAULT_LANGUAGE;+ hydratedRef.current = true; // an explicit choice outranks hydration+ setLanguageState(next);+ writeStored(next);+ persistRef.current?.(next);+ }, []);++ /**+ * Server-side preferences arriving after auth resolves.+ *+ * Applied once, and only when the user has not already chosen in this+ * session. `userLanguage` is null for a user who never picked one, which+ * is a different state from "picked English" — that is why the column is+ * nullable.+ */+ const applyServerPreferences = useCallback(({ userLanguage, panelDefault }) => {+ if (hydratedRef.current) return;+ hydratedRef.current = true;+ const resolved = resolveLocale({+ userLanguage,+ stored: readStored(),+ panelDefault,+ navigatorLanguages: navigatorLanguages(),+ });+ setLanguageState(resolved);+ // Cache for the next pre-auth paint, but do NOT write it back to the+ // server: nothing was chosen here, it was only resolved.+ writeStored(resolved);+ }, []);++ const registerPersist = useCallback((fn) => {+ persistRef.current = fn;+ return () => { persistRef.current = null; };+ }, []);++ const value = useMemo(() => ({+ language,+ setLanguage,+ applyServerPreferences,+ registerPersist,+ ready,+ languages: LANGUAGES,+ languageInfo: languageInfo(language),+ direction: directionFor(language),+ }), [language, setLanguage, applyServerPreferences, registerPersist, ready]);++ return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;+}++export function useLocale() {+ const context = useContext(LocaleContext);+ if (!context) throw new Error('useLocale must be used within a LocaleProvider');+ return context;+}++function readStored() {+ try {+ return localStorage.getItem(STORAGE_KEY);+ } catch {+ return null; // private mode / disabled storage: fall through+ }+}++function writeStored(code) {+ try {+ localStorage.setItem(STORAGE_KEY, code);+ } catch {+ /* preference simply will not survive the tab */+ }+}diff --git a/frontend/src/i18n/__tests__/resolveLocale.test.js b/frontend/src/i18n/__tests__/resolveLocale.test.jsnew file mode 100644index 00000000..7fbfb15b--- /dev/null+++ b/frontend/src/i18n/__tests__/resolveLocale.test.js@@ -0,0 +1,108 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ DEFAULT_LANGUAGE, SUPPORTED_CODES,+ directionFor, languageInfo, matchSupported, resolveLocale,+} from '../resolveLocale.js';++const SUPPORTED = ['en', 'es'];++test('matchSupported resolves language-only', () => {+ assert.equal(matchSupported('es', SUPPORTED), 'es');+ assert.equal(matchSupported('es-MX', SUPPORTED), 'es');+ assert.equal(matchSupported('ES', SUPPORTED), 'es');+ assert.equal(matchSupported('es_419', SUPPORTED), 'es');+ assert.equal(matchSupported('en-GB', SUPPORTED), 'en');+});++test('matchSupported rejects what we do not ship', () => {+ assert.equal(matchSupported('fr', SUPPORTED), null);+ assert.equal(matchSupported('', SUPPORTED), null);+ assert.equal(matchSupported(null, SUPPORTED), null);+ assert.equal(matchSupported(undefined, SUPPORTED), null);+ assert.equal(matchSupported(42, SUPPORTED), null);+});++test('the user preference outranks everything', () => {+ assert.equal(resolveLocale({+ userLanguage: 'es',+ stored: 'en',+ panelDefault: 'en',+ navigatorLanguages: ['en-US'],+ supported: SUPPORTED,+ }), 'es');+});++test('the stored value outranks the panel default', () => {+ // This is what stops the sign-in screen flashing the panel language at a+ // returning user who chose otherwise.+ assert.equal(resolveLocale({+ stored: 'es',+ panelDefault: 'en',+ navigatorLanguages: ['en-US'],+ supported: SUPPORTED,+ }), 'es');+});++test('the panel default outranks the browser', () => {+ // A panel that has an opinion must beat the operator's OS language.+ assert.equal(resolveLocale({+ panelDefault: 'es',+ navigatorLanguages: ['en-US', 'en'],+ supported: SUPPORTED,+ }), 'es');+});++test('the browser decides on a first visit', () => {+ assert.equal(resolveLocale({+ navigatorLanguages: ['es-MX', 'en'],+ supported: SUPPORTED,+ }), 'es');+});++test('unsupported candidates are skipped, not fatal', () => {+ // A user row carrying a locale we stopped shipping must not break the app.+ assert.equal(resolveLocale({+ userLanguage: 'fr',+ stored: 'de',+ panelDefault: 'ja',+ navigatorLanguages: ['pt-BR', 'es-ES'],+ supported: SUPPORTED,+ }), 'es');+});++test('falls back to English when nothing matches', () => {+ assert.equal(resolveLocale({+ userLanguage: 'fr',+ navigatorLanguages: ['fr-FR'],+ supported: SUPPORTED,+ }), DEFAULT_LANGUAGE);+ assert.equal(resolveLocale({ supported: SUPPORTED }), DEFAULT_LANGUAGE);+ assert.equal(resolveLocale(), DEFAULT_LANGUAGE);+});++test('null user language is not the same as choosing English', () => {+ // The column is nullable for exactly this: "never chose" must fall through+ // to the panel default, while an explicit 'en' must pin English.+ assert.equal(resolveLocale({+ userLanguage: null, panelDefault: 'es', supported: SUPPORTED,+ }), 'es');+ assert.equal(resolveLocale({+ userLanguage: 'en', panelDefault: 'es', supported: SUPPORTED,+ }), 'en');+});++test('every shipped language has a usable manifest row', () => {+ for (const code of SUPPORTED_CODES) {+ const info = languageInfo(code);+ assert.equal(info.code, code);+ assert.ok(info.name && info.nativeName, `${code} needs both names`);+ assert.ok(['ltr', 'rtl'].includes(directionFor(code)), `${code} direction`);+ }+});++test('an unknown code still yields a usable row', () => {+ assert.equal(languageInfo('zz').code, DEFAULT_LANGUAGE);+ assert.equal(directionFor('zz'), 'ltr');+});diff --git a/frontend/src/i18n/index.js b/frontend/src/i18n/index.jsnew file mode 100644index 00000000..f26bccf2--- /dev/null+++ b/frontend/src/i18n/index.js@@ -0,0 +1,80 @@+// Plan 79 A1/A2 — the i18next instance.+//+// Delivery is deliberately NOT the usual http-backend fetch:+//+// * `en` is bundled into the main chunk. The login and setup screens render+// before any API call succeeds, so a locale that arrives over the network+// either flashes English first or -- when the backend is the thing that is+// broken -- never arrives, on the one screen whose job is to say so.+// * Every other locale is a dynamic import, which Vite emits as its own+// chunk served from the same static origin as the app. No second fetch+// path to 404 behind a misconfigured proxy or a subpath install, and+// nothing to reach for in an air-gapped deployment.+//+// Adding a language is therefore data-only: drop `xx.json` into ./locales and+// add a row to languages.json. `import.meta.glob` picks it up; no loader to+// register.++import i18next from 'i18next';+import { initReactI18next } from 'react-i18next';+import en from './locales/en.json' with { type: 'json' };+import { DEFAULT_LANGUAGE, SUPPORTED_CODES } from './resolveLocale';++// Statically analysable by Vite; guarded so this module can be imported by+// node-side tooling (which has no import.meta.glob) without exploding.+// `en` is excluded: it is statically imported above and belongs in the main+// chunk. Globbing it too would make rollup emit it both ways for no benefit.+const localeModules = typeof import.meta.glob === 'function'+ ? import.meta.glob(['./locales/*.json', '!./locales/en.json'])+ : {};++const loaded = new Set([DEFAULT_LANGUAGE]);++i18next+ .use(initReactI18next)+ .init({+ lng: DEFAULT_LANGUAGE,+ fallbackLng: DEFAULT_LANGUAGE,+ supportedLngs: SUPPORTED_CODES,+ load: 'languageOnly',+ resources: { [DEFAULT_LANGUAGE]: { translation: en } },+ // React escapes on render; escaping here would double-encode.+ interpolation: { escapeValue: false },+ // An empty translation must fall through to the inline English default+ // rather than render as a blank label.+ returnEmptyString: false,+ react: { useSuspense: false },+ });++/**+ * Make a locale's bundle available, importing it on first use.+ * Resolves to the code actually loaded — `en` if the bundle is missing, so a+ * half-shipped locale degrades to English instead of to key paths.+ */+export async function loadLocale(code) {+ if (!SUPPORTED_CODES.includes(code)) return DEFAULT_LANGUAGE;+ if (loaded.has(code)) return code;++ const loader = localeModules[`./locales/${code}.json`];+ if (!loader) return DEFAULT_LANGUAGE;++ try {+ const module = await loader();+ i18next.addResourceBundle(code, 'translation', module.default || module, true, true);+ loaded.add(code);+ return code;+ } catch {+ return DEFAULT_LANGUAGE;+ }+}++/** Load then activate. Returns the code that actually took effect. */+export async function activateLocale(code) {+ const resolved = await loadLocale(code);+ if (i18next.language !== resolved) {+ await i18next.changeLanguage(resolved);+ }+ return resolved;+}++export default i18next;diff --git a/frontend/src/i18n/languages.json b/frontend/src/i18n/languages.jsonnew file mode 100644index 00000000..5f1773d3--- /dev/null+++ b/frontend/src/i18n/languages.json@@ -0,0 +1,18 @@+{+ "languages": [+ {+ "code": "en",+ "name": "English",+ "nativeName": "English",+ "dir": "ltr",+ "status": "stable"+ },+ {+ "code": "es",+ "name": "Spanish",+ "nativeName": "Español",+ "dir": "ltr",+ "status": "provisional"+ }+ ]+}diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonnew file mode 100644index 00000000..0967ef42--- /dev/null+++ b/frontend/src/i18n/locales/en.json@@ -0,0 +1 @@+{}diff --git a/frontend/src/i18n/resolveLocale.js b/frontend/src/i18n/resolveLocale.jsnew file mode 100644index 00000000..54a4731a--- /dev/null+++ b/frontend/src/i18n/resolveLocale.js@@ -0,0 +1,76 @@+// Plan 79 A4 — locale precedence, as pure functions so it can be tested+// without a browser, a store, or i18next.+//+// user.language (server, per-user)+// -> localStorage 'language' (pre-auth cache; stops the login flash)+// -> panel default (system_settings, unauthenticated endpoint)+// -> navigator.language (first visit, matched language-only)+// -> 'en'+//+// This mirrors ThemeContext's precedence (workspace -> user -> skin ->+// default) deliberately: same problem shape, same solution, one thing to+// learn.++// Import attribute required by Node (the test runner); Vite/rollup honour it too.+import manifest from './languages.json' with { type: 'json' };++export const LANGUAGES = manifest.languages;+export const DEFAULT_LANGUAGE = 'en';+export const SUPPORTED_CODES = LANGUAGES.map((language) => language.code);+export const STORAGE_KEY = 'language';++/**+ * Match a requested tag against what we ship, language-only.+ *+ * `es-419`, `es-MX` and `ES` all resolve to `es`. Region-specific bundles are+ * not shipped, so keeping the region would mean a miss on every non-neutral+ * browser tag — which is most of them.+ */+export function matchSupported(tag, supported = SUPPORTED_CODES) {+ if (!tag || typeof tag !== 'string') return null;+ const normalized = tag.trim().toLowerCase().replace('_', '-');+ if (!normalized) return null;+ if (supported.includes(normalized)) return normalized;+ const base = normalized.split('-')[0];+ return supported.includes(base) ? base : null;+}++/**+ * First supported match across an ordered list of candidate tags.+ * Unsupported and malformed entries are skipped rather than failing — a+ * user row carrying a locale we no longer ship must not break the app.+ */+export function resolveLocale({+ userLanguage = null,+ stored = null,+ panelDefault = null,+ navigatorLanguages = [],+ supported = SUPPORTED_CODES,+} = {}) {+ const candidates = [userLanguage, stored, panelDefault, ...navigatorLanguages];+ for (const candidate of candidates) {+ const match = matchSupported(candidate, supported);+ if (match) return match;+ }+ return DEFAULT_LANGUAGE;+}++/** The manifest row for a code, or the English row. */+export function languageInfo(code) {+ return LANGUAGES.find((language) => language.code === code)+ || LANGUAGES.find((language) => language.code === DEFAULT_LANGUAGE);+}++/** Writing direction for a code — drives <html dir> (plan 79 §H). */+export function directionFor(code) {+ return languageInfo(code).dir || 'ltr';+}++/** Browser languages, defensively — `navigator` is absent under node. */+export function navigatorLanguages() {+ if (typeof navigator === 'undefined') return [];+ if (Array.isArray(navigator.languages) && navigator.languages.length) {+ return [...navigator.languages];+ }+ return navigator.language ? [navigator.language] : [];+}