Add lightweight i18n foundation; route new strings through catalogs

- Backend src/i18n.rs: embedded locales/<lang>.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/<lang>.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.
This commit is contained in:
adm committed 2026-11-25 16:05:29 +01:00
1 parent 73b665d1a7
commit 498e3dbc1b
12 files changed
+248 -27

No files matched your search

+5 -6
View File
@@ -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 {
+9
View File
@@ -88,6 +88,10 @@ pub struct Config {
#[serde(default)]
pub workspace_root: Option<String>,
/// UI / model-prompt language (catalog key, e.g. "it", "en"). Defaults to Italian.
#[serde(default)]
pub language: Option<String>,
/// 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> {
+108
View File
@@ -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/<lang>.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<String, String>,
fallback: HashMap<String, String>,
}
fn load(lang: &str) -> HashMap<String, String> {
Locales::get(&format!("{lang}.json"))
.and_then(|f| serde_json::from_slice::<HashMap<String, String>>(&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<I18n> = 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");
}
}
+1
View File
@@ -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;
+1
View File
@@ -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<u16>) -> ExitCode {
strata_ctl::i18n::init(&cfg.language());
let dir = match &cfg.tokenizer {
Some(d) => d.clone(),
None => {