From 498e3dbc1be551a6d58c16be731a0261ea5f9a24 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 25 Nov 2026 16:05:29 +0100 Subject: [PATCH] Add lightweight i18n foundation; route new strings through catalogs - Backend src/i18n.rs: embedded locales/.json, t(key,params) with {placeholder} interpolation, process-wide language from config.language (default it), English-then-key fallback. Applied to the identity reminder and name-lock/empty errors. - Frontend: web/assets/locales/.json + t()/loadI18n()/applyI18n() (data-i18n attributes); language follows the browser; async bootstrap. Applied to the settings panel. - Convention: new user-facing and model-facing strings use the catalog; wire/JSON/identifiers never translated. Existing strings migrate in a later round. it+en catalogs; 115 tests; verified live (catalog error messages) + node --check + HTTP. README documents the convention. --- README.md | 17 +++++- locales/en.json | 7 +++ locales/it.json | 7 +++ src/api/sessions.rs | 11 ++-- src/config.rs | 9 ++++ src/i18n.rs | 108 +++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 1 + web/assets/app.js | 48 ++++++++++++++--- web/assets/locales/en.json | 21 ++++++++ web/assets/locales/it.json | 21 ++++++++ web/index.html | 24 ++++----- 12 files changed, 248 insertions(+), 27 deletions(-) create mode 100644 locales/en.json create mode 100644 locales/it.json create mode 100644 src/i18n.rs create mode 100644 web/assets/locales/en.json create mode 100644 web/assets/locales/it.json diff --git a/README.md b/README.md index a83ae40..073ec02 100644 --- a/README.md +++ b/README.md @@ -193,9 +193,24 @@ optional `startup_timeout_secs` / `silence_timeout_secs`. Everything else (`arch `mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored — unknown keys never break startup. +### Localization (i18n) + +User-facing strings are externalized into embedded per-language catalogs and +looked up by key with `{placeholder}` interpolation: + +- **Backend** (`src/i18n.rs`): `locales/.json`, `t(key, params)`, language + from the `language` config key (default `it`), English fallback then the key. +- **Frontend** (`web/assets/locales/.json`): `t(key, params)` for dynamic + strings and `data-i18n` attributes for static HTML; language follows the browser. + +Convention: new code routes user-facing strings (and model-facing prompts such as +the identity reminder) through the catalog. Wire-protocol fields, JSON keys and +identifiers are **never** translated. Existing hardcoded strings are migrated in a +later adaptation round. + ## Status -Working and tested (114 tests, plus 2 real-file tests run on demand). Text, images, +Working and tested (115 tests, plus 2 real-file tests run on demand). Text, images, the full client-side tool loop, the Anthropic endpoint, the web GUI (session context, streaming, stats) and **agent mode** (the model using `shell_exec` on the host) have been validated live against the real Inkling engine. diff --git a/locales/en.json b/locales/en.json new file mode 100644 index 0000000..93553ad --- /dev/null +++ b/locales/en.json @@ -0,0 +1,7 @@ +{ + "identity.name": "Your name is {name}.", + "identity.folder": " Your personal folder is {folder}.", + "error.name_locked": "The session name is immutable after the first interaction.", + "error.name_empty": "The name must not be empty.", + "error.session_not_found": "Session not found." +} \ No newline at end of file diff --git a/locales/it.json b/locales/it.json new file mode 100644 index 0000000..56b5d24 --- /dev/null +++ b/locales/it.json @@ -0,0 +1,7 @@ +{ + "identity.name": "Il tuo nome è {name}.", + "identity.folder": " La tua cartella personale è {folder}.", + "error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.", + "error.name_empty": "Il nome non può essere vuoto.", + "error.session_not_found": "Sessione non trovata." +} \ No newline at end of file diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 554b25d..8fbd788 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -19,6 +19,7 @@ use super::routes::{AppState, Error}; use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage}; use crate::agent::shell::{HostShell, ShellRunner}; use crate::agent::{self, AgentEvent}; +use crate::i18n::t; use crate::name; use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMessage}; use tokio_stream::wrappers::UnboundedReceiverStream; @@ -137,13 +138,11 @@ pub(crate) async fn patch_session( .ok_or_else(|| Error::not_found("session not found"))?; if let Some(title) = body.title { if sess.name_locked { - return Err(Error::bad_request( - "the session name is immutable after the first interaction", - )); + return Err(Error::bad_request(t("error.name_locked", &[]))); } let title = title.trim().to_string(); if title.is_empty() { - return Err(Error::bad_request("name must not be empty")); + return Err(Error::bad_request(t("error.name_empty", &[]))); } with_store(&st, { let id = id.clone(); @@ -213,9 +212,9 @@ fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) let mut messages = Vec::new(); // Structural identity reminder: always present, not an editable setting. It // tells the agent its name and personal workspace folder. - let mut identity = format!("Il tuo nome è {}.", sess.title); + let mut identity = t("identity.name", &[("name", &sess.title)]); if let Some(folder) = &sess.folder { - identity.push_str(&format!(" La tua cartella personale è {folder}.")); + identity.push_str(&t("identity.folder", &[("folder", folder)])); } messages.push(text_message(Role::System, identity)); if let Some(sp) = &sess.settings.system_prompt { diff --git a/src/config.rs b/src/config.rs index f3b0d14..f96b075 100644 --- a/src/config.rs +++ b/src/config.rs @@ -88,6 +88,10 @@ pub struct Config { #[serde(default)] pub workspace_root: Option, + /// UI / model-prompt language (catalog key, e.g. "it", "en"). Defaults to Italian. + #[serde(default)] + pub language: Option, + /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Optional: both default to 600s when absent. #[serde(default)] @@ -238,6 +242,11 @@ impl Config { PathBuf::from(home).join(".strata-ctl") } + /// Effective language: config > `it`. + pub fn language(&self) -> String { + self.language.clone().unwrap_or_else(|| "it".to_string()) + } + /// The top-level keys present in the file that we are not acting on — /// reported by `--check` so the shared-file contract stays visible. pub fn ignored_keys(&self) -> Vec<&str> { diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..ee7a980 --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,108 @@ +//! Lightweight internationalization for user-facing strings. +//! +//! Convention: every string shown to a human (or injected as a model-facing +//! prompt, like the identity reminder) goes through [`t`] with a catalog key and +//! `{placeholder}` parameters. Wire-protocol fields, JSON keys and identifiers +//! are NEVER translated. Catalogs are embedded per-language JSON files +//! (`locales/.json`); the active language is process-wide, set from config +//! at startup. Missing keys fall back to English, then to the key itself, so a +//! missing translation can never crash a request. +//! +//! New code must use `t(key, params)`; existing hardcoded strings are migrated in +//! a later adaptation round. + +use std::collections::HashMap; +use std::sync::OnceLock; + +use rust_embed::RustEmbed; + +#[derive(RustEmbed)] +#[folder = "locales/"] +struct Locales; + +/// A loaded language catalog plus an English fallback. +pub struct I18n { + lang: String, + map: HashMap, + fallback: HashMap, +} + +fn load(lang: &str) -> HashMap { + Locales::get(&format!("{lang}.json")) + .and_then(|f| serde_json::from_slice::>(&f.data).ok()) + .unwrap_or_default() +} + +impl I18n { + /// Load the catalog for `lang` (default Italian) with an English fallback. + pub fn new(lang: &str) -> Self { + let lang = if lang.is_empty() { "it" } else { lang }; + Self { + map: load(lang), + fallback: load("en"), + lang: lang.to_string(), + } + } + + pub fn lang(&self) -> &str { + &self.lang + } + + /// Look up `key` and substitute `{name}`-style parameters. Unknown keys + /// resolve to the English fallback, then to the key itself. + pub fn translate(&self, key: &str, params: &[(&str, &str)]) -> String { + let template = self + .map + .get(key) + .or_else(|| self.fallback.get(key)) + .map(|s| s.as_str()) + .unwrap_or(key); + let mut out = template.to_string(); + for (k, v) in params { + out = out.replace(&format!("{{{k}}}"), v); + } + out + } +} + +static I18N: OnceLock = OnceLock::new(); + +/// Set the process-wide language once at startup (from config). +pub fn init(lang: &str) { + let _ = I18N.set(I18n::new(lang)); +} + +/// Translate a key with `{placeholder}` parameters. Defaults to Italian when +/// [`init`] has not been called (e.g. in unit tests). +pub fn t(key: &str, params: &[(&str, &str)]) -> String { + I18N.get_or_init(|| I18n::new("it")).translate(key, params) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lookup_interpolation_and_fallback() { + let it = I18n::new("it"); + assert_eq!( + it.translate("identity.name", &[("name", "Pippo")]), + "Il tuo nome è Pippo." + ); + let en = I18n::new("en"); + assert_eq!( + en.translate("identity.name", &[("name", "Pippo")]), + "Your name is Pippo." + ); + // Missing key returns the key itself (never panics). + assert_eq!(it.translate("does.not.exist", &[]), "does.not.exist"); + // Unknown language falls back to the English catalog. + let xx = I18n::new("xx"); + assert_eq!( + xx.translate("identity.name", &[("name", "X")]), + "Your name is X." + ); + // Empty language defaults to Italian. + assert_eq!(I18n::new("").lang(), "it"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 2fd0fc7..83a3c76 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod agent; pub mod api; pub mod config; pub mod engine; +pub mod i18n; pub mod inkling; pub mod name; pub mod store; diff --git a/src/main.rs b/src/main.rs index 849c751..dd3d71b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,6 +114,7 @@ async fn main() -> ExitCode { /// Start the engine from the config and serve the OpenAI-compatible API. async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> ExitCode { + strata_ctl::i18n::init(&cfg.language()); let dir = match &cfg.tokenizer { Some(d) => d.clone(), None => { diff --git a/web/assets/app.js b/web/assets/app.js index 016eaa5..eb133d6 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -7,6 +7,34 @@ const $ = (sel) => document.querySelector(sel); const state = { sessions: [], current: null, busy: false, agent: false }; +// ---- i18n: new user-facing strings go through t(key, params) -------------- +// Catalogs are served at /assets/locales/.json; language follows the +// browser. Static HTML uses data-i18n attributes; dynamic strings use t(). +const I18N = { lang: "it", map: {} }; +function t(key, params = {}) { + let s = I18N.map[key] ?? key; + for (const [k, v] of Object.entries(params)) s = s.replaceAll(`{${k}}`, v); + return s; +} +async function loadI18n() { + const nav = (navigator.language || "it").slice(0, 2).toLowerCase(); + const lang = ["it", "en"].includes(nav) ? nav : "it"; + for (const l of [lang, "it"]) { + try { + const r = await fetch(`/assets/locales/${l}.json`); + if (r.ok) { I18N.map = await r.json(); I18N.lang = l; return; } + } catch { /* try next */ } + } +} +function applyI18n() { + document.querySelectorAll("[data-i18n]").forEach((n) => { + n.textContent = t(n.getAttribute("data-i18n")); + }); + document.querySelectorAll("[data-i18n-ph]").forEach((n) => { + n.placeholder = t(n.getAttribute("data-i18n-ph")); + }); +} + // ---- API helpers ---------------------------------------------------------- async function getJSON(url) { const r = await fetch(url); @@ -382,11 +410,11 @@ function fillSettingsForm(data, scope) { const locked = sess ? sess.name_locked : false; $("#set-name").disabled = locked; $("#set-name-hint").textContent = locked - ? "Il nome è bloccato dopo la prima interazione." - : "Puoi rinominare finché non invii il primo messaggio."; - $("#set-hint").textContent = "Modifiche valide solo per questa sessione."; + ? t("settings.name.locked") + : t("settings.name.unlocked"); + $("#set-hint").textContent = t("settings.hint.session"); } else { - $("#set-hint").textContent = "Default generali: si applicano solo alle sessioni future."; + $("#set-hint").textContent = t("settings.hint.general"); } $("#set-notes").value = data.notes || ""; $("#set-sp").value = data.system_prompt || ""; @@ -416,7 +444,7 @@ async function openSettings(scope) { $("#set-scope-session").classList.toggle("active", scope === "session"); $("#set-scope-general").classList.toggle("active", scope === "general"); $("#settings-title").textContent = - scope === "session" ? "Impostazioni sessione" : "Impostazioni generali"; + scope === "session" ? t("settings.title.session") : t("settings.title.general"); settingsBase = scope === "session" ? { ...(currentSession()?.settings || {}) } @@ -445,7 +473,7 @@ async function saveSettings() { } $("#settings-modal").hidden = true; } catch (e) { - $("#set-hint").textContent = `Errore: ${e.message}`; + $("#set-hint").textContent = t("settings.error", { msg: e.message }); } } @@ -567,8 +595,12 @@ function wire() { }); } -wire(); -loadSessions().catch((e) => { +(async () => { + await loadI18n(); + applyI18n(); + wire(); + await loadSessions(); +})().catch((e) => { $("#transcript").textContent = ""; $("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`)); }); \ No newline at end of file diff --git a/web/assets/locales/en.json b/web/assets/locales/en.json new file mode 100644 index 0000000..ed2fca0 --- /dev/null +++ b/web/assets/locales/en.json @@ -0,0 +1,21 @@ +{ + "settings.title.session": "Session settings", + "settings.title.general": "General settings", + "settings.scope.session": "Session", + "settings.scope.general": "General", + "settings.name": "Name", + "settings.notes": "Notes (chat purpose)", + "settings.sp": "System Prompt", + "settings.temp": "Temperature", + "settings.topp": "Top-p", + "settings.topk": "Top-k", + "settings.minp": "Min-p", + "settings.maxtokens": "Max tokens", + "settings.save": "Save", + "settings.cancel": "Cancel", + "settings.hint.session": "Changes apply only to this session.", + "settings.hint.general": "General defaults: apply only to future sessions.", + "settings.name.locked": "The name is locked after the first interaction.", + "settings.name.unlocked": "You can rename until you send the first message.", + "settings.error": "Error: {msg}" +} \ No newline at end of file diff --git a/web/assets/locales/it.json b/web/assets/locales/it.json new file mode 100644 index 0000000..d49b4fb --- /dev/null +++ b/web/assets/locales/it.json @@ -0,0 +1,21 @@ +{ + "settings.title.session": "Impostazioni sessione", + "settings.title.general": "Impostazioni generali", + "settings.scope.session": "Sessione", + "settings.scope.general": "Generali", + "settings.name": "Nome", + "settings.notes": "Note (scopo della chat)", + "settings.sp": "System Prompt", + "settings.temp": "Temperature", + "settings.topp": "Top-p", + "settings.topk": "Top-k", + "settings.minp": "Min-p", + "settings.maxtokens": "Max token", + "settings.save": "Salva", + "settings.cancel": "Annulla", + "settings.hint.session": "Modifiche valide solo per questa sessione.", + "settings.hint.general": "Default generali: si applicano solo alle sessioni future.", + "settings.name.locked": "Il nome è bloccato dopo la prima interazione.", + "settings.name.unlocked": "Puoi rinominare finché non invii il primo messaggio.", + "settings.error": "Errore: {msg}" +} \ No newline at end of file diff --git a/web/index.html b/web/index.html index 60515df..3e31169 100644 --- a/web/index.html +++ b/web/index.html @@ -73,30 +73,30 @@