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
+247 -26

No files matched your search

+16 -1
View File
@@ -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/<lang>.json`, `t(key, params)`, language
from the `language` config key (default `it`), English fallback then the key.
- **Frontend** (`web/assets/locales/<lang>.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.
+7
View File
@@ -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."
}
+7
View File
@@ -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."
}
+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 => {
+39 -7
View File
@@ -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/<lang>.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() {
});
}
(async () => {
await loadI18n();
applyI18n();
wire();
loadSessions().catch((e) => {
await loadSessions();
})().catch((e) => {
$("#transcript").textContent = "";
$("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`));
});
+21
View File
@@ -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}"
}
+21
View File
@@ -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}"
}
+12 -12
View File
@@ -73,30 +73,30 @@
<div class="modal-card settings-card">
<h2 id="settings-title">Impostazioni</h2>
<div class="scope-toggle">
<button id="set-scope-session" class="btn ghost active">Sessione</button>
<button id="set-scope-general" class="btn ghost">Generali</button>
<button id="set-scope-session" class="btn ghost active" data-i18n="settings.scope.session">Sessione</button>
<button id="set-scope-general" class="btn ghost" data-i18n="settings.scope.general">Generali</button>
</div>
<p id="set-hint" class="muted"></p>
<label class="field" id="set-name-field"><span>Nome</span>
<label class="field" id="set-name-field"><span data-i18n="settings.name">Nome</span>
<input id="set-name" type="text" autocomplete="off" />
</label>
<p id="set-name-hint" class="muted small"></p>
<label class="field"><span>Note (scopo della chat)</span>
<label class="field"><span data-i18n="settings.notes">Note (scopo della chat)</span>
<textarea id="set-notes" rows="2"></textarea>
</label>
<label class="field"><span>System Prompt</span>
<label class="field"><span data-i18n="settings.sp">System Prompt</span>
<textarea id="set-sp" rows="4"></textarea>
</label>
<div class="field-grid">
<label class="field"><span>Temperature</span><input id="set-temp" type="number" step="0.1" min="0" /></label>
<label class="field"><span>Top-p</span><input id="set-topp" type="number" step="0.05" min="0" max="1" /></label>
<label class="field"><span>Top-k</span><input id="set-topk" type="number" step="1" min="0" /></label>
<label class="field"><span>Min-p</span><input id="set-minp" type="number" step="0.05" min="0" max="1" /></label>
<label class="field"><span>Max token</span><input id="set-maxtokens" type="number" step="1" min="1" /></label>
<label class="field"><span data-i18n="settings.temp">Temperature</span><input id="set-temp" type="number" step="0.1" min="0" /></label>
<label class="field"><span data-i18n="settings.topp">Top-p</span><input id="set-topp" type="number" step="0.05" min="0" max="1" /></label>
<label class="field"><span data-i18n="settings.topk">Top-k</span><input id="set-topk" type="number" step="1" min="0" /></label>
<label class="field"><span data-i18n="settings.minp">Min-p</span><input id="set-minp" type="number" step="0.05" min="0" max="1" /></label>
<label class="field"><span data-i18n="settings.maxtokens">Max token</span><input id="set-maxtokens" type="number" step="1" min="1" /></label>
</div>
<div class="dialog-actions">
<button id="set-cancel" class="btn">Annulla</button>
<button id="set-save" class="btn primary">Salva</button>
<button id="set-cancel" class="btn" data-i18n="settings.cancel">Annulla</button>
<button id="set-save" class="btn primary" data-i18n="settings.save">Salva</button>
</div>
</div>
</div>