Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(plugins): resolve plugin labels in the app language
vastsae4ffbfe45672
diff --git a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts b/apps/desktop/electron/main/bootstrap/app-lifecycle.tsindex afc177ed7..fb4bdbf02 100644--- a/apps/desktop/electron/main/bootstrap/app-lifecycle.ts+++ b/apps/desktop/electron/main/bootstrap/app-lifecycle.ts@@ -18,6 +18,8 @@ import type { BrowserPane } from "../browser-view";import type { Logger } from "../logger";import type { PluginRuntime } from "../plugin-runtime";import type { PluginViewHost } from "../plugin-view-host";+import type { HostProcess } from "../host-process";+import { syncPluginDisplayLocale } from "../plugin-display-locale";import type { PluginAppearance } from "../../shared/plugin-panel-chrome";export type ApplicationLifecycleState = {@@ -64,6 +66,7 @@ export type ApplicationLifecycleDependencies = {applyPluginLauncherShortcut: (keybindings?: KeybindingOverrides) => void;applySummonWindowShortcut: (keybindings?: KeybindingOverrides) => void;broadcastPluginPanelEvent: (event: string, payload: unknown) => void;+ getHost: () => HostProcess | null;};export function createApplicationLifecycle({@@ -96,6 +99,7 @@ export function createApplicationLifecycle({applyPluginLauncherShortcut,applySummonWindowShortcut,broadcastPluginPanelEvent,+ getHost,}: ApplicationLifecycleDependencies) {function applyDevelopmentBranding() {@@ -457,6 +461,15 @@ export function createApplicationLifecycle({if (locale !== appearanceState.updaterLocale) {appearanceState.updaterLocale = locale;refreshReleaseNotes();+ // Plugin labels are resolved in the host (a plugin ships them per+ // locale), so the change is pushed there before the surfaces re-read.+ // `pluginChanged` is also what makes the Extensions page re-list, so a+ // language switch localizes the rows without a restart (ADR 0160).+ void syncPluginDisplayLocale(getHost(), locale)+ .then(() => sendToRenderer(IPC.event.pluginChanged, { reason: "locale" }))+ // Notifying is best-effort: a window that is already gone must not turn+ // a language change into an unhandled rejection.+ .catch(() => {});}applyAppThemePreference(settings?.theme);const keybindings =diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex b6cad92f6..35d3ea34c 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -929,6 +929,7 @@ applicationLifecycle = createApplicationLifecycle({applyPluginLauncherShortcut: applyPluginLauncherShortcutForLifecycle,applySummonWindowShortcut: applySummonWindowShortcutForLifecycle,broadcastPluginPanelEvent,+ getHost: () => host,});const {applyDevelopmentBranding,@@ -1240,6 +1241,7 @@ runtimeLifecycle = createRuntimeLifecycle({rememberPluginScopes,refreshUserMcp,isQuitting: () => quitting,+ getDisplayLocale: () => applicationAppearanceState.updaterLocale,});const { bootHostStatus, runtimeArch, bootBackends } = runtimeLifecycle;diff --git a/apps/desktop/electron/main/plugin-display-locale.ts b/apps/desktop/electron/main/plugin-display-locale.tsnew file mode 100644index 000000000..75ba65ed2--- /dev/null+++ b/apps/desktop/electron/main/plugin-display-locale.ts@@ -0,0 +1,27 @@+import type { HostProcess } from "./host-process";++/**+ * Tell the host which language the app is displaying, so plugin rows resolve+ * their labels in it.+ *+ * A plugin ships its display strings per locale (`manifest.i18n`, and the same+ * block on a marketplace catalog entry) and the host picks the entry that+ * matches the app language. The host keeps that language itself because rows+ * are read long after a request was answered, and because no plugin RPC carries+ * a locale.+ *+ * A failure is deliberately swallowed: the host then falls back to English,+ * which is the source language of the plugin contract, and no language change+ * may turn a settings write into an error.+ */+export async function syncPluginDisplayLocale(+ host: HostProcess | null,+ locale: string,+): Promise<void> {+ if (!host) return;+ try {+ await host.call("plugins.setLocale", { locale });+ } catch {+ // A host that predates this RPC keeps its English labels.+ }+}diff --git a/apps/desktop/electron/main/runtime/lifecycle.ts b/apps/desktop/electron/main/runtime/lifecycle.tsindex d5c191c96..a693b34f2 100644--- a/apps/desktop/electron/main/runtime/lifecycle.ts+++ b/apps/desktop/electron/main/runtime/lifecycle.ts@@ -18,9 +18,9 @@ import {import type { Logger } from "../logger";import type { PluginRuntime } from "../plugin-runtime";import type { RuntimeState } from "./context";+import { syncPluginDisplayLocale } from "../plugin-display-locale";type RestartKind = "host" | "sidecar";-export type RuntimeLifecycleDependencies = {runtimeState: RuntimeState;dataDir: string;@@ -37,6 +37,12 @@ export type RuntimeLifecycleDependencies = {) => void;refreshUserMcp: () => Promise<unknown>;isQuitting: () => boolean;+ /**+ * App language the plugin rows resolve their labels in. The host holds it,+ * and a fresh host process starts in English, so it is pushed again whenever+ * a host is (re)started.+ */+ getDisplayLocale: () => string;};export function createRuntimeLifecycle({@@ -53,6 +59,7 @@ export function createRuntimeLifecycle({rememberPluginScopes,refreshUserMcp,isQuitting,+ getDisplayLocale,}: RuntimeLifecycleDependencies): {superviseRestart: (kind: RestartKind) => Promise<void>;bootHostStatus: (bootError: unknown) => HostStatusEvent;@@ -111,6 +118,10 @@ export function createRuntimeLifecycle({const sidecar = runtimeState.sidecar;const host = runtimeState.host;if (sidecar && host) sidecar.setHost(host);+ // A fresh host process starts in English, so the app language and+ // the language-dependent rows it draws have to be restored here:+ // nothing else re-applies settings after a crash.+ await syncPluginDisplayLocale(host, getDisplayLocale());} else {await startSidecar();}@@ -121,6 +132,9 @@ export function createRuntimeLifecycle({component: kind,restarted: true,});+ // The plugin rows were drawn from the dead process: re-read them so a+ // restart is invisible in the Extensions page and the launcher.+ sendToRenderer(IPC.event.pluginChanged, { reason: "hostRestart" });return;} catch (error) {const schema = schemaTooNewOf(error);@@ -208,6 +222,10 @@ export function createRuntimeLifecycle({data: { protocolVersion: PROTOCOL_VERSION },});await startHost();+ // Plugin rows are resolved in the host, so the app language is pushed once+ // the process answers. The startup sequence re-applies it with the stored+ // settings; this keeps a host that boots without that write honest.+ await syncPluginDisplayLocale(runtimeState.host, getDisplayLocale());try {const stored = await runtimeState.host!.call("settings.get");await applyNetworkProxyFromAppSettings(stored);diff --git a/apps/desktop/resources/plugins/pi.browser/manifest.json b/apps/desktop/resources/plugins/pi.browser/manifest.jsonindex 363a19036..6177577ed 100644--- a/apps/desktop/resources/plugins/pi.browser/manifest.json+++ b/apps/desktop/resources/plugins/pi.browser/manifest.json@@ -4,6 +4,16 @@"name": "Browser","version": "1.0.0","description": "Work-panel browser chrome and agent CDP against the host guest page.",+ "i18n": {+ "en": {+ "name": "Browser",+ "description": "Work-panel browser chrome and agent CDP against the host guest page."+ },+ "zh-CN": {+ "name": "浏览器",+ "description": "工作面板里的浏览器外壳,并为 Agent 提供针对宿主访客页的 CDP 调试能力。"+ }+ },"author": "PI-Desktop","main": "main.js","contributes": {diff --git a/apps/desktop/src/features/plugins/usePluginsPage.ts b/apps/desktop/src/features/plugins/usePluginsPage.tsindex 76a974db9..bcaf38538 100644--- a/apps/desktop/src/features/plugins/usePluginsPage.ts+++ b/apps/desktop/src/features/plugins/usePluginsPage.ts@@ -163,6 +163,15 @@ export function usePluginsPage() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [tab, query]);+ // Plugin and catalog labels are resolved in the host, so a language switch+ // has to re-read the marketplace list; otherwise the previous language stays+ // on the cards until the user happens to type (ADR 0160).+ useEffect(() => {+ if (tab !== "market") return;+ void refreshMarket(query);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [locale]);+// Escape closes the detail sheet, but only while it owns the top layer: the// permission dialog in front of it handles its own dismissal.useEffect(() => {diff --git a/crates/host-core/src/plugins.rs b/crates/host-core/src/plugins.rsindex dfdecaef8..768083561 100644--- a/crates/host-core/src/plugins.rs+++ b/crates/host-core/src/plugins.rs@@ -32,10 +32,15 @@ pub use marketplace::{};pub use model::{InstallOptions, InstallResult, MarketDownloadInfo, MarketPluginDetail, MarketPluginSummary,- MarketProvenance, MarketReview, MarketVersion, PluginMarketplaceMeta, PluginSettingDefinition,- PluginSettingOption, PluginSummary, PluginUiMeta, PluginUpdateInfo, PluginYankNotice,+ MarketProvenance, MarketReview, MarketVersion, PluginDisplayI18n, PluginI18nMap,+ PluginMarketplaceMeta, PluginSettingDefinition, PluginSettingOption, PluginSummary,+ PluginUiMeta, PluginUpdateInfo, PluginYankNotice,};pub(crate) use model::{MarketCatalogEntry, MarketCatalogFile};++/// Locale resolution for plugin/catalog display strings, shared by the+/// registry and the marketplace readers.+pub(crate) use model::localized_field;pub use registry::PluginManager;// Domain modules share a small set of crate-private helpers. Re-exporting themdiff --git a/crates/host-core/src/plugins/install.rs b/crates/host-core/src/plugins/install.rsindex 5994efe20..a63ce53e7 100644--- a/crates/host-core/src/plugins/install.rs+++ b/crates/host-core/src/plugins/install.rs@@ -135,6 +135,7 @@ impl PluginManager {ui: manifest.ui.clone(),fs: manifest.fs.clone(),settings: derive_settings(&manifest),+ i18n: manifest.i18n.clone(),};let plugin = self.upsert_summary(summary)?;Ok(InstallResult {diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rsindex 7961c38b0..4f9a1377f 100644--- a/crates/host-core/src/plugins/manifest.rs+++ b/crates/host-core/src/plugins/manifest.rs@@ -10,6 +10,12 @@ pub struct PluginManifest {pub main: String,#[serde(default)]pub description: Option<String>,+ /// Display strings per locale — `{ "en": { name, description, safetyNotes },+ /// "zh-CN": { … } }` — resolved against the application locale whenever a+ /// row is read. The flat `name`/`description` above stay the author's own+ /// language and are the last-resort fallback.+ #[serde(default)]+ pub i18n: Option<PluginI18nMap>,#[serde(default)]pub author: Option<String>,#[serde(default)]diff --git a/crates/host-core/src/plugins/marketplace.rs b/crates/host-core/src/plugins/marketplace.rsindex 42dd6e201..8a75277f4 100644--- a/crates/host-core/src/plugins/marketplace.rs+++ b/crates/host-core/src/plugins/marketplace.rs@@ -300,8 +300,12 @@ impl PluginManager {}if !q.is_empty() {let hay = format!(- "{} {} {} {}",- entry.id, entry.name, entry.description, entry.author+ "{} {} {} {} {}",+ entry.id,+ entry.name,+ entry.description,+ entry.author,+ localized_search_haystack(entry.i18n.as_ref()),).to_lowercase();if !hay.contains(&q) {@@ -328,6 +332,14 @@ impl PluginManager {let permissions = latest_market_version(&entry.versions).map(|v| v.permissions.clone()).unwrap_or_default();+ // Resolved before the fields move out of `entry`; the flat field stays+ // the fallback for a catalog without an `i18n` block, and a partial+ // translation falls back per field.+ let safety_notes = localized_field(entry.i18n.as_ref(), &self.locale, |text| {+ text.safety_notes.as_ref()+ })+ .cloned()+ .or(entry.safety_notes.clone());Ok(MarketPluginDetail {summary,readme_markdown: entry.readme_markdown,@@ -336,7 +348,7 @@ impl PluginManager {homepage: entry.homepage,repository: entry.repository,permissions,- safety_notes: entry.safety_notes,+ safety_notes,})}@@ -488,8 +500,14 @@ impl PluginManager {let catalog_url = self.market_source_url();MarketPluginSummary {id: entry.id.clone(),- name: entry.name.clone(),- description: entry.description.clone(),+ name: localized_field(entry.i18n.as_ref(), &self.locale, |text| text.name.as_ref())+ .cloned()+ .unwrap_or_else(|| entry.name.clone()),+ description: localized_field(entry.i18n.as_ref(), &self.locale, |text| {+ text.description.as_ref()+ })+ .cloned()+ .unwrap_or_else(|| entry.description.clone()),author: entry.author.clone(),icon_url: entry.icon_url.clone(),latest_version: latest.clone(),@@ -693,3 +711,16 @@ impl PartialOrd for ParsedPluginVersion<'_> {Some(self.cmp(other))}}++/// Every locale's name and description, so a search matches whatever language+/// the user typed rather than only the one currently displayed.+fn localized_search_haystack(map: Option<&PluginI18nMap>) -> String {+ let Some(map) = map else {+ return String::new();+ };+ map.values()+ .flat_map(|entry| [entry.name.as_deref(), entry.description.as_deref()])+ .flatten()+ .collect::<Vec<_>>()+ .join(" ")+}diff --git a/crates/host-core/src/plugins/model.rs b/crates/host-core/src/plugins/model.rsindex 8b6d3bbec..d6af92975 100644--- a/crates/host-core/src/plugins/model.rs+++ b/crates/host-core/src/plugins/model.rs@@ -89,6 +89,103 @@ pub struct PluginSummary {pub fs: Option<Value>,#[serde(default, skip_serializing_if = "Vec::is_empty")]pub settings: Vec<PluginSettingDefinition>,+ /// `manifest.i18n`, held in memory only.+ ///+ /// Display metadata that the host resolves before a row leaves the+ /// process, so it is neither persisted in the registry nor sent over RPC:+ /// the renderer keeps reading finished strings (ADR 0160 §4). Every path+ /// that rebuilds a row from a manifest refills it.+ #[serde(default, skip_serializing)]+ pub i18n: Option<PluginI18nMap>,+}++/// One locale's display strings for a plugin (`manifest.i18n`, catalog `i18n`).+///+/// Every field is optional so a partially translated block still falls back+/// per field instead of losing the author's own language.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PluginDisplayI18n {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub safety_notes: Option<String>,+}++/// Locale id → display strings. Plugins ship `en` plus `zh-CN`; other keys are+/// kept but never selected, so a manifest may carry more than the contract+/// requires without the host having to understand them.+pub type PluginI18nMap = std::collections::BTreeMap<String, PluginDisplayI18n>;++/// Which entry of a [`PluginI18nMap`] a shell locale reads.+///+/// Mirrors `resolvePluginLocalizedString` in `@pi-desktop/plugin-sdk`: every+/// Chinese shell locale reads `zh-CN`, everything else reads `en`. Plugins are+/// not required to translate themselves into every shipped shell locale, so+/// `zh-TW` deliberately reads English rather than half a `zh-CN` guess+/// (ADR 0182).+pub(crate) fn plugin_display_locale(locale: &str) -> &'static str {+ let lower = locale.trim().replace('_', "-").to_lowercase();+ let simplified_chinese = lower == "zh"+ || lower == "zh-cn"+ || lower.starts_with("zh-cn-")+ || lower == "zh-hans"+ || lower.starts_with("zh-hans-")+ || lower == "zh-sg"+ || lower.starts_with("zh-sg-");+ if simplified_chinese {+ "zh-CN"+ } else {+ "en"+ }+}++/// One localized field: the locale's entry, else English, else whichever block+/// is there. An empty string counts as missing — a half-filled translation+/// must not blank out a row that has a usable author-written name.+pub(crate) fn localized_field<'a>(+ map: Option<&'a PluginI18nMap>,+ locale: &str,+ pick: impl Fn(&'a PluginDisplayI18n) -> Option<&'a String>,+) -> Option<&'a String> {+ let map = map?;+ let mut order = vec![plugin_display_locale(locale)];+ for key in ["en", "zh-CN"] {+ if !order.contains(&key) {+ order.push(key);+ }+ }+ for key in order {+ if let Some(value) = map.get(key).and_then(&pick) {+ if !value.trim().is_empty() {+ return Some(value);+ }+ }+ }+ None+}++impl PluginSummary {+ /// The row as the active locale should read it.+ ///+ /// Only display text moves: ids, versions, permissions and state are+ /// language-independent, and a plugin without an `i18n` block keeps the+ /// strings its author wrote.+ pub(crate) fn localized(&self, locale: &str) -> PluginSummary {+ let mut out = self.clone();+ if let Some(name) = localized_field(self.i18n.as_ref(), locale, |entry| entry.name.as_ref())+ {+ out.name = name.clone();+ }+ if let Some(description) = localized_field(self.i18n.as_ref(), locale, |entry| {+ entry.description.as_ref()+ }) {+ out.description = Some(description.clone());+ }+ out+ }}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -328,6 +425,10 @@ pub(crate) struct MarketCatalogEntry {pub(crate) repository: Option<String>,#[serde(default)]pub(crate) readme_markdown: Option<String>,+ /// Display strings per locale, resolved against the app language before a+ /// card or detail view is built.+ #[serde(default)]+ pub(crate) i18n: Option<PluginI18nMap>,#[serde(default)]pub(crate) safety_notes: Option<String>,pub(crate) versions: Vec<MarketVersion>,diff --git a/crates/host-core/src/plugins/registry.rs b/crates/host-core/src/plugins/registry.rsindex de6fe3b77..7b3db3981 100644--- a/crates/host-core/src/plugins/registry.rs+++ b/crates/host-core/src/plugins/registry.rs@@ -25,6 +25,12 @@ pub struct PluginManager {pub(crate) bundled_ids: BTreeSet<String>,/// Catalog URL pinned by app settings; `None` keeps the official default.pub(crate) market_source: Option<String>,+ /// Locale a row's display fields are resolved against.+ ///+ /// The desktop shell owns the app language — `settings.language`, or the+ /// OS locale while it is `auto` — and pushes it here. Until it does, rows+ /// read English, which is the source language of the plugin contract.+ pub(crate) locale: String,}impl PluginManager {@@ -39,6 +45,7 @@ impl PluginManager {runtime: Vec::new(),bundled_ids: BTreeSet::new(),market_source,+ locale: "en".into(),};let _ = mgr.ensure_dirs();let _ = mgr.ensure_default_catalog();@@ -125,6 +132,7 @@ impl PluginManager {ui: manifest.ui.clone(),fs: manifest.fs.clone(),settings: derive_settings(&manifest),+ i18n: manifest.i18n.clone(),});}}@@ -201,11 +209,38 @@ impl PluginManager {}pub fn list(&self) -> Vec<PluginSummary> {- self.runtime.clone()+ self.runtime+ .iter()+ .map(|plugin| plugin.localized(&self.locale))+ .collect()}pub fn get(&self, id: &str) -> Option<PluginSummary> {- self.runtime.iter().find(|p| p.id == id).cloned()+ self.runtime+ .iter()+ .find(|p| p.id == id)+ .map(|plugin| plugin.localized(&self.locale))+ }++ /// Follow the app language pushed down by the desktop shell.+ ///+ /// Stored rows keep the author's own strings; only reads are resolved, so+ /// switching language never rewrites the registry.+ pub fn set_locale(&mut self, locale: &str) {+ let next = locale.trim();+ // `auto` is a setting, not a locale: the desktop shell resolves it+ // before pushing. Storing it would only make every lookup read English.+ if next.is_empty() || next.eq_ignore_ascii_case("auto") {+ return;+ }+ if next != self.locale {+ self.locale = next.to_string();+ }+ }++ /// Locale a row's display text is resolved against.+ pub fn locale(&self) -> &str {+ &self.locale}pub fn reload_from_disk(&mut self) -> Result<()> {@@ -228,6 +263,7 @@ impl PluginManager {continue;};plugin.settings = derive_settings(&manifest);+ plugin.i18n = manifest.i18n.clone();}Ok(())}@@ -243,9 +279,13 @@ impl PluginManager {pub(crate) fn upsert_summary(&mut self, summary: PluginSummary) -> Result<PluginSummary> {self.runtime.retain(|p| p.id != summary.id);- self.runtime.push(summary.clone());+ // The row is stored as the author wrote it and localized on the way+ // out, so every reader of this summary gets the same treatment as+ // `list()` and `get()`.+ let response = summary.localized(&self.locale);+ self.runtime.push(summary);self.save()?;- Ok(summary)+ Ok(response)}pub fn load_dev(&mut self, plugin_path: &str) -> Result<PluginSummary> {@@ -276,6 +316,7 @@ impl PluginManager {ui: manifest.ui.clone(),fs: manifest.fs.clone(),settings: derive_settings(&manifest),+ i18n: manifest.i18n.clone(),};self.upsert_summary(summary)}@@ -289,7 +330,7 @@ impl PluginManager {"disabled".into()};plugin.updated_at = Some(Utc::now().to_rfc3339());- let out = plugin.clone();+ let out = plugin.localized(&self.locale);self.save()?;return Ok(Some(out));}@@ -302,7 +343,7 @@ impl PluginManager {if let Some(plugin) = self.runtime.iter_mut().find(|p| p.id == id) {plugin.scope = scope.normalized();plugin.updated_at = Some(Utc::now().to_rfc3339());- let out = plugin.clone();+ let out = plugin.localized(&self.locale);self.save()?;return Ok(Some(out));}@@ -313,7 +354,7 @@ impl PluginManager {if let Some(plugin) = self.runtime.iter_mut().find(|p| p.id == id) {plugin.auto_update = Some(enabled);plugin.updated_at = Some(Utc::now().to_rfc3339());- let out = plugin.clone();+ let out = plugin.localized(&self.locale);self.save()?;return Ok(Some(out));}@@ -368,7 +409,7 @@ impl PluginManager {}}plugin.updated_at = Some(Utc::now().to_rfc3339());- let out = plugin.clone();+ let out = plugin.localized(&self.locale);self.save()?;return Ok(Some(out));}@@ -385,7 +426,7 @@ impl PluginManager {.permissions.retain(|p| !permissions.iter().any(|x| x == p));plugin.updated_at = Some(Utc::now().to_rfc3339());- let out = plugin.clone();+ let out = plugin.localized(&self.locale);self.save()?;return Ok(Some(out));}diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rsindex 5f24c317f..98b583748 100644--- a/crates/host-core/src/plugins/tests.rs+++ b/crates/host-core/src/plugins/tests.rs@@ -1769,3 +1769,201 @@ fn global_shortcut_entries_are_validated() {assert!(read_manifest_err(¬_an_object).contains("contributes.globalShortcuts entry must be an object"));}++#[test]+fn plugin_rows_read_the_i18n_block_for_the_active_locale() {+ let _env = lock_market_env();+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ write_plugin(+ &root,+ json!({+ "schemaVersion": 1,+ "id": "acme.todo",+ "name": "小清新待办",+ "version": "0.1.0",+ "description": "作者原话",+ "main": "main.js",+ "i18n": {+ "en": { "name": "Todo List", "description": "A calm todo list" },+ "zh-CN": { "name": "小清新待办", "description": "轻盈的待办清单" }+ }+ }),+ &[],+ );+ let mut mgr = offline_manager(dir.path());+ mgr.set_locale("en");+ let row = mgr.load_dev(root.to_str().unwrap()).unwrap();+ assert_eq!(row.name, "Todo List");+ assert_eq!(row.description.as_deref(), Some("A calm todo list"));++ // Every reader resolves the same way: `list()` and `get()` are what the+ // Extensions page and the plugin launcher actually draw.+ mgr.set_locale("zh-CN");+ assert_eq!(mgr.get("acme.todo").unwrap().name, "小清新待办");+ let listed = mgr+ .list()+ .into_iter()+ .find(|candidate| candidate.id == "acme.todo")+ .expect("row missing from the list");+ assert_eq!(listed.description.as_deref(), Some("轻盈的待办清单"));++ // `zh-Hans` is Simplified Chinese. `zh-TW` is not part of the plugin+ // contract, so it reads English rather than half a translation (ADR 0182).+ mgr.set_locale("zh-Hans");+ assert_eq!(mgr.get("acme.todo").unwrap().name, "小清新待办");+ mgr.set_locale("zh-TW");+ assert_eq!(mgr.get("acme.todo").unwrap().name, "Todo List");+ mgr.set_locale("de");+ assert_eq!(mgr.get("acme.todo").unwrap().name, "Todo List");+}++#[test]+fn a_partial_translation_falls_back_per_field() {+ let _env = lock_market_env();+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ write_plugin(+ &root,+ json!({+ "schemaVersion": 1,+ "id": "acme.partial",+ "name": "Author name",+ "version": "0.1.0",+ "description": "Author description",+ "main": "main.js",+ "i18n": { "en": { "name": "English name", "description": " " } }+ }),+ &[],+ );+ let mut mgr = offline_manager(dir.path());+ mgr.set_locale("en");+ let row = mgr.load_dev(root.to_str().unwrap()).unwrap();+ assert_eq!(row.name, "English name");+ // A blank translation must not blank out a usable author description.+ assert_eq!(row.description.as_deref(), Some("Author description"));++ // A locale with no entry at all falls back to English, not to nothing.+ mgr.set_locale("fr");+ assert_eq!(mgr.get("acme.partial").unwrap().name, "English name");+}++#[test]+fn a_plugin_without_an_i18n_block_keeps_the_authors_strings() {+ let _env = lock_market_env();+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ write_plugin(+ &root,+ json!({+ "schemaVersion": 1,+ "id": "acme.plain",+ "name": "Plain",+ "version": "0.1.0",+ "description": "Plain description",+ "main": "main.js"+ }),+ &[],+ );+ let mut mgr = offline_manager(dir.path());+ mgr.set_locale("zh-CN");+ let row = mgr.load_dev(root.to_str().unwrap()).unwrap();+ assert_eq!(row.name, "Plain");+ assert_eq!(row.description.as_deref(), Some("Plain description"));+}++#[test]+fn the_registry_never_persists_the_i18n_block() {+ let _env = lock_market_env();+ let dir = tempdir().unwrap();+ let root = dir.path().join("plugin");+ write_plugin(+ &root,+ json!({+ "schemaVersion": 1,+ "id": "acme.stored",+ "name": "Stored",+ "version": "0.1.0",+ "main": "main.js",+ "i18n": { "en": { "name": "Stored" }, "zh-CN": { "name": "已存" } }+ }),+ &[],+ );+ let mut mgr = offline_manager(dir.path());+ mgr.set_locale("zh-CN");+ mgr.load_dev(root.to_str().unwrap()).unwrap();++ // The registry keeps the author's own language; only reads are localized,+ // so switching language never rewrites persisted rows.+ let raw = fs::read_to_string(mgr.registry_path()).unwrap();+ assert!(!raw.contains("\"i18n\""), "registry persisted i18n: {raw}");+ assert!(raw.contains("Stored"));++ // A restart re-reads each manifest, so rows are localized again without+ // the registry having carried anything.+ let mut reloaded = PluginManager::new(dir.path(), None);+ reloaded.set_locale("zh-CN");+ assert_eq!(reloaded.get("acme.stored").unwrap().name, "已存");+}++#[test]+fn market_cards_and_details_read_the_catalog_i18n_block() {+ let _env = lock_market_env();+ let dir = tempdir().unwrap();+ let mut mgr = offline_manager(dir.path());+ let mut entry = v2_entry();+ entry.safety_notes = Some("Reads nothing else".into());+ entry.i18n = Some(+ [+ (+ "en".to_string(),+ PluginDisplayI18n {+ name: Some("Todo".into()),+ description: Some("Publisher-owned plugin".into()),+ safety_notes: Some("Reads nothing else".into()),+ },+ ),+ (+ "zh-CN".to_string(),+ PluginDisplayI18n {+ name: Some("待办".into()),+ description: Some("发布者自有的插件".into()),+ safety_notes: Some("不读取其他内容".into()),+ },+ ),+ ]+ .into_iter()+ .collect(),+ );+ fs::write(+ mgr.catalog_path(),+ serde_json::to_string(&v2_catalog(entry)).unwrap(),+ )+ .unwrap();++ mgr.set_locale("zh-CN");+ let card = mgr.market_search(None, None).unwrap().remove(0);+ assert_eq!(card.name, "待办");+ assert_eq!(card.description, "发布者自有的插件");+ assert_eq!(+ mgr.market_get("acme.todo").unwrap().safety_notes.as_deref(),+ Some("不读取其他内容")+ );+ // Search matches either language: the card is drawn in one of them, and a+ // user typing the other must still find it.+ assert_eq!(+ mgr.market_search(Some("Publisher-owned"), None)+ .unwrap()+ .len(),+ 1+ );++ mgr.set_locale("en");+ let card = mgr.market_search(None, None).unwrap().remove(0);+ assert_eq!(card.name, "Todo");+ assert_eq!(card.description, "Publisher-owned plugin");+ assert_eq!(+ mgr.market_get("acme.todo").unwrap().safety_notes.as_deref(),+ Some("Reads nothing else")+ );+}diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 47c4fb2e6..dfbee8de0 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -1625,6 +1625,15 @@ async fn handle_request(// `market.refresh` after switching sources.let market_source = crate::plugins::market_source_from_settings(Some(&settings));st.plugins.set_market_source(market_source);+ // A concrete app language pins the plugin display locale here, so a+ // shell that only writes settings still gets localized plugin rows.+ // `auto` is resolved by the shell and pushed through+ // `plugins.setLocale`.+ if let Some(language) = settings.get("language").and_then(Value::as_str) {+ if language != "auto" {+ st.plugins.set_locale(language);+ }+ }crate::network_proxy::apply_from_settings(Some(&settings));Ok(json!({ "ok": true }))}@@ -3747,6 +3756,18 @@ async fn handle_request(Ok(json!({ "requests": st.permissions.pending_requests(session_id) }))}+ "plugins.setLocale" => {+ // The desktop shell owns the app language — `settings.language`, or+ // the OS locale while that is `auto` — so it pushes the resolved+ // locale here whenever it changes. Rows then read their display+ // strings from the matching `i18n` entry, and a locale change needs+ // no registry rewrite.+ let locale = params.get("locale").and_then(Value::as_str).unwrap_or("");+ let mut st = state.lock().await;+ st.plugins.set_locale(locale);+ Ok(json!({ "ok": true, "locale": st.plugins.locale() }))+ }+"plugins.list" => {let st = state.lock().await;Ok(json!({ "plugins": st.plugins.list() }))@@ -7880,4 +7901,70 @@ mod tests {.unwrap();assert_eq!(remaining, 0);}++ #[tokio::test]+ async fn plugin_labels_follow_the_pushed_app_language() {+ let data_dir = tempfile::tempdir().unwrap();+ let mut app_state = AppState::open(data_dir.path()).unwrap();+ app_state.handshook = true;+ let state = Arc::new(Mutex::new(app_state));+ let tx = mpsc::unbounded_channel().0;++ // A concrete app language in settings pins the locale even before the+ // shell pushes one.+ handle_request(+ state.clone(),+ "settings.set",+ json!({ "language": "zh-CN" }),+ tx.clone(),+ )+ .await+ .unwrap();+ {+ let st = state.lock().await;+ assert_eq!(st.plugins.locale(), "zh-CN");+ }++ // `auto` is a setting, not a locale: the shell resolves it, and the+ // host must not start reading `zh-CN` off the raw value.+ handle_request(+ state.clone(),+ "settings.set",+ json!({ "language": "auto" }),+ tx.clone(),+ )+ .await+ .unwrap();+ {+ let st = state.lock().await;+ assert_eq!(st.plugins.locale(), "zh-CN");+ }++ let pushed = handle_request(+ state.clone(),+ "plugins.setLocale",+ json!({ "locale": "en-US" }),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(pushed["locale"], "en-US");+ {+ let st = state.lock().await;+ assert_eq!(st.plugins.locale(), "en-US");+ }++ // Neither an empty value nor `auto` overwrites the resolved locale.+ for value in [+ json!({ "locale": "" }),+ json!({ "locale": "auto" }),+ json!({}),+ ] {+ handle_request(state.clone(), "plugins.setLocale", value, tx.clone())+ .await+ .unwrap();+ }+ let st = state.lock().await;+ assert_eq!(st.plugins.locale(), "en-US");+ }}diff --git a/docs/adr/0267-plugin-labels-follow-the-app-language.md b/docs/adr/0267-plugin-labels-follow-the-app-language.mdnew file mode 100644index 000000000..4bb31665d--- /dev/null+++ b/docs/adr/0267-plugin-labels-follow-the-app-language.md@@ -0,0 +1,81 @@+# ADR 0267: Plugin Labels Follow the App Language++- **Status**: Accepted+- **Date**: 2026-09-16+- **Related**: [ADR 0009](0009-english-first-globalization.md) ·+ [ADR 0160](0160-shipped-locale-registry-and-language-picker.md) ·+ [ADR 0182](0182-traditional-chinese-shell-locale.md) ·+ [07-plugins/02-plugin-manifest-schema](../spec/07-plugins/02-plugin-manifest-schema.md) ·+ [07-plugins/07-plugin-marketplace](../spec/07-plugins/07-plugin-marketplace.md)++## Context++A plugin's display name and description come from its manifest, and a+marketplace card's from its catalog entry. Both are single strings written in+whatever language the author used, so the Extensions page, the plugin launcher,+and the marketplace drew Chinese names under an English shell and English names+under a Chinese one. The plugin repository's own validator had been requiring a+top-level `i18n` block — `{ "en": { name, description, safetyNotes }, "zh-CN": {+… } }` — since its first release, and the catalog ships the same block on every+entry. The desktop shell read none of it: rows rendered `name` and+`description` verbatim, so a plugin translated by its author into the user's+language still arrived in the wrong one.++The shell already has every piece the fix needs: `@pi-desktop/i18n` owns the+shipped locale registry, the app language is resolved in the main process+(`settings.language`, or the OS locale while it is `auto`), and localized+manifest fields (`ui.title`, view titles, command and destination labels) are+already resolved by the host through `resolvePluginLocalizedString` with English+fallback.++## Decision++1. `manifest.i18n` and the same block on a marketplace catalog entry become part+ of the plugin contract, with `name`, `description`, and `safetyNotes`.+ `en` and `zh-CN` are the contract locales; a plugin is not required to+ translate itself into the other shipped shell locales.+2. Every Chinese shell locale reads `zh-CN`; every other locale reads `en`.+ `zh-TW` therefore reads English rather than a half-shared `zh-CN` guess,+ matching `resolvePluginLocalizedString` (ADR 0182).+3. Resolution happens in the **host**, not the renderer: rows leave the process+3. Resolution happens in the **host**, not the renderer: rows leave the process+ as finished strings, exactly like a plugin view title. A missing locale, a+ missing field, or an empty string falls back per field to the other contract+ locale, and from there to the author's flat `name` / `description`, so a+ partial translation never blanks a row.+4. The desktop shell pushes the app language down (`plugins.setLocale`) whenever+ it changes and then emits `pluginChanged`, so the surfaces re-read. The+ registry keeps the author's own strings: a language change never rewrites+ persisted rows, and the `i18n` block is neither persisted nor sent over RPC.+5. A malformed block (not an object of locale → object, or a non-string+ `name`/`description`/`safetyNotes`) fails `validateManifest`. Unknown locales+ and unknown fields inside an entry are ignored, so a publisher may carry more+ than the contract requires.++## Consequences++- A translated plugin now reads in the user's language on the Extensions page,+ the plugin launcher, and the marketplace, and its `safetyNotes` — the text+ that explains what an install can touch — reads in that language too.+- Catalog search matches every locale's name and description, so a user who+ types what they saw in one language still finds the entry after switching.+- Plugin authors keep shipping a single-language manifest if they want to: the+ flat fields remain the fallback, and no field of the block is mandatory to+ load.+- The host holds one more piece of state (the display locale). It is pushed by+ the shell rather than read per request, so a row does not depend on which RPC+ happens to carry a locale.++## Alternatives++- **Resolve in the renderer**: the renderer knows `i18n.language` and would+ switch instantly, but it would have to receive every manifest's `i18n` block,+ which contradicts the rule that the renderer never reads a manifest, and it+ would duplicate the fallback rules the host already owns.+- **Per-request locale parameter on every plugin RPC**: works for `plugins.list`+ but leaves the summaries the host itself returns (install results, permission+ changes, marketplace update checks) unlocalized, and adds a locale to every+ call site.+- **Leave names to the author's language**: the plugin repository already+ requires the block, so the shell would keep ignoring data its ecosystem+ publishes — the reported bug.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 9a2bb2a04..69f967352 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -293,3 +293,4 @@ Each ADR includes:| session-content-search | [Discover sessions by indexed message text](session-content-search.md) | Accepted || transcript-reading-ownership | [Share renderer history and search views](transcript-reading-ownership.md) | Accepted || 0266 | [Plugin fs roots follow the calling session](0266-plugin-fs-root-follows-the-calling-session.md) | Accepted (D093) |+| 0267 | [Plugin labels follow the app language](0267-plugin-labels-follow-the-app-language.md) | Accepted (amends 0160; ADR 0182) |diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex 8669ca78a..f55d222bf 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -35,6 +35,18 @@ type PluginManifestV1 = {description?: string;author?: string | { name: string; url?: string; email?: string };homepage?: string;+ /**+ * Display strings per locale, shown in place of `name`/`description` when the+ * shell's language matches one of the declared locales (see §3.1). The flat+ * fields stay the author's own language and remain the fallback.+ */+ i18n?: {+ [locale: string]: {+ name?: string;+ description?: string;+ safetyNotes?: string;+ };+ };repository?: string;icon?: string; // relative pathmain?: string; // plugin runtime entry@@ -79,6 +91,44 @@ type PluginUiConfig = {};```+### 3.1 Localized labels (`i18n`)++`name`, `description`, and `safetyNotes` are display text, so a plugin may+declare them per locale in a top-level `i18n` block. The Extensions page, the+plugin launcher, and the marketplace (which reads the same block from a catalog+entry) show the entry matching the **app language** rather than the author's own+language:++```json+{+ "name": "小清新待办",+ "description": "作者原话",+ "i18n": {+ "en": { "name": "Todo List", "description": "A calm todo list" },+ "zh-CN": { "name": "小清新待办", "description": "轻盈的待办清单", "safetyNotes": "只写自己的数据" }+ }+}+```++Rules:++1. `en` and `zh-CN` are the contract locales. Every Chinese shell locale+ (`zh`, `zh-CN`, `zh-Hans`, `zh-SG`) reads `zh-CN`; every other locale reads+ `en`. A plugin is not required to translate itself into the other shipped+ shell locales, so `zh-TW` reads English rather than half a `zh-CN` guess+ (ADR 0182).+2. Both locales and all three fields are required by the plugin repository's+ validator, but the host is permissive: a missing locale, a missing field, or+ an empty string falls back per field to the other contract locale, and from+ there to the author's flat `name` / `description`.+3. Resolution happens in the host, against the language the desktop shell+ pushes down (`settings.language`, or the OS locale while it is `auto`). The+ stored row keeps the author's strings, so a language change only changes what+ is read and never rewrites the registry.+4. The block is display metadata. A malformed one (not an object of locale →+ object) fails manifest validation; unknown locales and unknown fields inside+ an entry are ignored.+## 4. contributes```tsdiff --git a/docs/spec/07-plugins/07-plugin-marketplace.md b/docs/spec/07-plugins/07-plugin-marketplace.mdindex 3f5bc95f0..f6ccaf7c1 100644--- a/docs/spec/07-plugins/07-plugin-marketplace.md+++ b/docs/spec/07-plugins/07-plugin-marketplace.md@@ -218,6 +218,15 @@ type MarketPluginSummary = {verified?: booleaninstallable?: boolean}+`i18n` is display metadata, not a summary field: the host resolves a card's+`name` / `description` and a detail view's `safetyNotes` against the app+language and falls back per field to the entry's own values, so a translated+plugin reads in the user's language (ADR 0267). A catalog entry declares the+same block as a manifest — `{ en: { name, description, safetyNotes }, "zh-CN":+{ … } }`. Search matches every locale, not only the one currently displayed; a+malformed block fails the catalog parse, while unknown locales and unknown+fields inside an entry are ignored.+```### MarketPluginDetaildiff --git a/docs/zh-CN/adr/index.md b/docs/zh-CN/adr/index.mdindex 0a45c4b8e..6fba453c2 100644--- a/docs/zh-CN/adr/index.md+++ b/docs/zh-CN/adr/index.md@@ -284,6 +284,7 @@ ADR 记录那些不应被静默改变的架构选择。中文入口与英文索| 0251 | [删除项目会一并删除其拥有的会话](/adr/0251-project-delete-with-owned-sessions) | 已接受 || 0253 | [移除子智能体轮次上限](/adr/0253-remove-subagent-turn-limit) | 已接受(取代 0062 / 0063 / 0119 / 0126 / 0166 / 0210 中关于 `maxTurns` 的条款) || 0265 | [排队队列的优先区块与行内操作](/adr/0265-turn-queue-priority-block-and-row-actions) | 已接受待实现(修订 ADR 0213 / 0118) |+ | 0267 | [插件标签跟随应用语言](/adr/0267-plugin-labels-follow-the-app-language) | 已接受(修订 ADR 0160;ADR 0182) |## 什么时候看 ADRdiff --git a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.mdindex 46832b5bb..13f9d6ef3 100644--- a/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/zh-CN/spec/07-plugins/02-plugin-manifest-schema.md@@ -22,6 +22,17 @@ type PluginManifestV1 = {name: string;version: string; // semverdescription?: string;+ /**+ * 展示文案的多语言表:当应用语言命中其中某个 locale 时用它替换+ * `name` / `description`(见 §3.1)。扁平字段仍是作者自己的语言,也是最终回退。+ */+ i18n?: {+ [locale: string]: {+ name?: string;+ description?: string;+ safetyNotes?: string;+ };+ };author?: string | { name: string; url?: string; email?: string };homepage?: string;repository?: string;@@ -64,6 +75,36 @@ type PluginUiConfig = {};```+### 3.1 多语言标签(`i18n`)++`name`、`description` 和 `safetyNotes` 都是展示文案,插件可以用顶层 `i18n` 块按+locale 声明。扩展页、插件启动器和市场(从 catalog 条目读取同一个块)显示的是**应用+语言**对应的条目,而不是作者自己写的那一种:++```json+{+ "name": "小清新待办",+ "description": "作者原话",+ "i18n": {+ "en": { "name": "Todo List", "description": "A calm todo list" },+ "zh-CN": { "name": "小清新待办", "description": "轻盈的待办清单", "safetyNotes": "只写自己的数据" }+ }+}+```++规则:++1. `en` 与 `zh-CN` 是契约 locale。所有中文壳 locale(`zh`、`zh-CN`、`zh-Hans`、+ `zh-SG`)读 `zh-CN`,其余读 `en`。插件不必为其他已发布壳 locale 提供翻译,+ 因此 `zh-TW` 读英文,而不是拿半份 `zh-CN` 猜测(ADR 0182)。+2. 插件仓库的校验器要求两个 locale 与三个字段齐全,但宿主是宽容的:缺 locale、+ 缺字段或空字符串会按字段依次回退到另一个契约 locale,再回退到作者扁平的+ `name` / `description`。+3. 解析发生在宿主里,依据桌面壳下发的语言(`settings.language`,为 `auto` 时是+ 系统语言)。存储行保留作者原文,因此切换语言只改变读取结果,绝不改写注册表。+4. 该块是展示元数据。格式错误(不是 locale → 对象的对象)会让 manifest 校验失败;+ 条目里未知的 locale 与未知字段一律忽略。+## 4. 贡献```tsdiff --git a/packages/plugin-sdk/src/index.test.ts b/packages/plugin-sdk/src/index.test.tsindex 358519d60..825e6c712 100644--- a/packages/plugin-sdk/src/index.test.ts+++ b/packages/plugin-sdk/src/index.test.ts@@ -724,3 +724,45 @@ describe("contributes.providers", () => {);});});++describe("manifest i18n", () => {+ it("keeps a per-locale display block on the manifest", () => {+ const result = validateManifest({+ ...base,+ description: "小清新待办",+ i18n: {+ en: { name: "Todo List", description: "A calm todo list" },+ "zh-CN": {+ name: "小清新待办",+ description: "轻盈的待办清单",+ safetyNotes: "只读写自己的数据",+ },+ },+ });+ expect(result.ok).toBe(true);+ expect(result.manifest?.i18n?.en.name).toBe("Todo List");+ expect(result.manifest?.i18n?.["zh-CN"].name).toBe("小清新待办");+ });++ it("accepts a partial block, which falls back per field", () => {+ expect(validateManifest({ ...base, i18n: { en: { name: "Hello" } } }).ok).toBe(true);+ // A locale the shell does not read, and an unknown display field, are the+ // author's business rather than a load failure.+ expect(validateManifest({ ...base, i18n: { ja: { name: "ハロー" } } }).ok).toBe(true);+ expect(+ validateManifest({ ...base, i18n: { en: { name: "Hello", tagline: "x" } } as never }).ok,+ ).toBe(true);+ });++ it("refuses a malformed block", () => {+ expect(validateManifest({ ...base, i18n: [] as never }).error).toMatch(+ /manifest\.i18n must be an object/,+ );+ expect(validateManifest({ ...base, i18n: { "zh-CN": "小清新待办" } as never }).error).toMatch(+ /manifest\.i18n\.zh-CN must be an object/,+ );+ expect(validateManifest({ ...base, i18n: { en: { name: 7 } } as never }).error).toMatch(+ /manifest\.i18n\.en\.name must be a string/,+ );+ });+});diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.tsindex fc46d98c3..2b80144eb 100644--- a/packages/plugin-sdk/src/index.ts+++ b/packages/plugin-sdk/src/index.ts@@ -26,15 +26,38 @@ export const PLUGIN_ID_PATTERN = /^[a-z0-9]+(\.[a-z0-9_-]+)+$/;/** `author` may be a display string or a contact object (manifest schema §2). */export type PluginManifestAuthor =+ | string| string| { name: string; email?: string; url?: string };+/**+ * One locale's display strings (`manifest.i18n`).+ *+ * `en` and `zh-CN` are the contract locales: the shell reads `zh-CN` for every+ * Chinese locale and English for everything else. Every field is optional, and+ * a partially translated block falls back per field, so a missing one keeps the+ * author's own `name` / `description` instead of blanking it out.+ */+export type PluginDisplayI18n = {+ name?: string;+ description?: string;+ safetyNotes?: string;+};++/** Locale id → display strings, as a plugin declares them in `manifest.i18n`. */+export type PluginI18nMap = Record<string, PluginDisplayI18n>;export type PluginManifest = {schemaVersion: number;id: string;name: string;version: string;description?: string;+ /**+ * Display strings per locale. The flat `name`/`description` above stay the+ * author's own language and remain the fallback; the shell shows the entry+ * matching the app language and only reads these two contract locales.+ */+ i18n?: PluginI18nMap;author?: PluginManifestAuthor;homepage?: string;repository?: string;@@ -1176,6 +1199,8 @@ export function validateManifest(raw: unknown): {return { ok: false, error: `manifest.${field} must be a non-empty string` };}}+ const i18nError = manifestI18nError((m as Record<string, unknown>).i18n);+ if (i18nError) return { ok: false, error: i18nError };const ui = m.ui as| { title?: unknown; panel?: unknown }| null@@ -1729,6 +1754,30 @@ function manifestAuthorError(value: unknown): string | undefined {return undefined;}+/**+ * `manifest.i18n` is display metadata: locale id → the strings that locale+ * shows. Shape errors are refused because a malformed block would silently+ * leave the shell on the author's own language with no way to tell why; a+ * locale or field a plugin does not translate is fine and falls back.+ */+function manifestI18nError(value: unknown): string | undefined {+ if (value === undefined) return undefined;+ if (!value || typeof value !== "object" || Array.isArray(value)) {+ return "manifest.i18n must be an object of locale → { name?, description?, safetyNotes? }";+ }+ for (const [locale, entry] of Object.entries(value as Record<string, unknown>)) {+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {+ return `manifest.i18n.${locale} must be an object`;+ }+ for (const field of ["name", "description", "safetyNotes"] as const) {+ const text = (entry as Record<string, unknown>)[field];+ if (text !== undefined && typeof text !== "string") {+ return `manifest.i18n.${locale}.${field} must be a string`;+ }+ }+ }+ return undefined;+}function relativePathError(value: string, field: string): string | undefined {if (/^[a-zA-Z]:[\\/]/.test(value) || value.startsWith("/") || value.startsWith("\\")) {return `${field} must not be an absolute path`;