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): compare plugin storage names, not raw ids, on install
zszz3ed686dd4cefc
diff --git a/crates/host-core/src/plugins/manifest.rs b/crates/host-core/src/plugins/manifest.rsindex f27d9cfaa..ad35d5e7d 100644--- a/crates/host-core/src/plugins/manifest.rs+++ b/crates/host-core/src/plugins/manifest.rs@@ -86,8 +86,10 @@ impl PluginManager {/// would name a parent or current directory instead of the plugin's own./// Windows also drops a trailing `.` from a path segment and resolves/// device names (`con`, `nul.x`, ...) to devices, so those ids could not-/// name a directory of their own either. Ids that differ only in letter-/// case are a registry-level conflict, see `ensure_storage_identity_free`.+/// name a directory of their own either. Ids that share a storage name with+/// another registered plugin (letter case, or a legacy row stored under its+/// sanitized name) are a registry-level conflict, see+/// `ensure_storage_identity_free`.fn validate_plugin_id(id: &str) -> Result<()> {let allowed = id.chars()diff --git a/crates/host-core/src/plugins/registry.rs b/crates/host-core/src/plugins/registry.rsindex 0b2566caf..cd8d282e0 100644--- a/crates/host-core/src/plugins/registry.rs+++ b/crates/host-core/src/plugins/registry.rs@@ -224,23 +224,31 @@ impl PluginManager {.collect()}- /// Refuses an id that differs from a registered plugin's id only in- /// letter case. Case-insensitive file systems (macOS and Windows- /// defaults) resolve both to the same install and data directory, so the- /// newcomer would overwrite the other plugin's files. Existing rows and- /// directories keep their names; only the new id is refused.+ /// Refuses an id whose install / data directory and session partition+ /// would resolve to those of a different registered plugin. Rows written+ /// by older versions may carry ids the manifest check now refuses (such+ /// as `e2e.foo!bar`, stored under `e2e.foo_bar`), so the comparison runs+ /// on the storage name, not the raw id. Existing rows and directories+ /// keep their names; only the new id is refused.pub(crate) fn ensure_storage_identity_free(&self, id: &str) -> Result<()> {- if let Some(other) = self+ let identity = storage_identity(id);+ let Some(other) = self.runtime.iter()- .find(|p| p.id != id && p.id.eq_ignore_ascii_case(id))- {+ .find(|p| p.id != id && storage_identity(&p.id) == identity)+ else {+ return Ok(());+ };+ if other.id.eq_ignore_ascii_case(id) {bail!("PLUGIN_INVALID: id {id} differs from installed plugin {} only in letter case",other.id);}- Ok(())+ bail!(+ "PLUGIN_INVALID: id {id} would share storage with installed plugin {}",+ other.id+ );}pub fn get(&self, id: &str) -> Option<PluginSummary> {@@ -462,3 +470,11 @@ impl PluginManager {Ok(None)}}++/// Name a plugin id resolves to on disk and in its session partition, folded+/// the way the platforms fold it: characters outside `[A-Za-z0-9._-]` become+/// `_` (`sanitize_id`), Windows drops trailing dots, and case-insensitive file+/// systems ignore letter case. Two ids with the same identity share storage.+fn storage_identity(id: &str) -> String {+ sanitize_id(id).trim_end_matches('.').to_ascii_lowercase()+}diff --git a/crates/host-core/src/plugins/tests.rs b/crates/host-core/src/plugins/tests.rsindex 27d7f357a..3d59df547 100644--- a/crates/host-core/src/plugins/tests.rs+++ b/crates/host-core/src/plugins/tests.rs@@ -2648,3 +2648,61 @@ fn an_id_differing_only_in_case_cannot_take_over_an_installed_plugin() {mgr.install_from_path(first.to_str().unwrap(), local_install("installed")).unwrap();}++#[test]+fn a_valid_id_cannot_take_over_a_legacy_plugin_stored_under_its_sanitized_name() {+ let dir = tempdir().unwrap();+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);+ let first = dir.path().join("src-first");+ write_id_plugin(&first, "e2e.foo_bar", "first");+ mgr.install_from_path(first.to_str().unwrap(), local_install("installed"))+ .unwrap();+ let installed_main = mgr.installed_dir("e2e.foo_bar").join("main.js");+ let owner_file = mgr.data_dir_for("e2e.foo_bar").join("owner.txt");+ fs::write(&owner_file, "legacy data").unwrap();++ // Rewrite the state into what an older build persisted for the id+ // `e2e.foo!bar`: the row and installed manifest keep the raw id, the+ // directories carry its sanitized name.+ let registry_path = dir.path().join("plugins/registry.json");+ let registry = fs::read_to_string(®istry_path)+ .unwrap()+ .replace("\"e2e.foo_bar\"", "\"e2e.foo!bar\"");+ fs::write(®istry_path, ®istry).unwrap();+ let manifest_path = mgr.installed_dir("e2e.foo_bar").join("manifest.json");+ let manifest = fs::read_to_string(&manifest_path)+ .unwrap()+ .replace("\"e2e.foo_bar\"", "\"e2e.foo!bar\"");+ fs::write(&manifest_path, manifest).unwrap();++ // Restart on the new build.+ let mut mgr = PluginManager::new(dir.path(), MarketChannel::Official, None);+ let ids = |mgr: &PluginManager| -> Vec<String> {+ mgr.list()+ .into_iter()+ .map(|plugin| plugin.id)+ .filter(|id| id.starts_with("e2e."))+ .collect()+ };+ assert_eq!(ids(&mgr), ["e2e.foo!bar"]);++ for alias in ["e2e.foo_bar", "e2e.Foo_Bar"] {+ let second = dir.path().join(format!("src-{alias}"));+ write_id_plugin(&second, alias, "second");+ let install = mgr+ .install_from_path(second.to_str().unwrap(), local_install("installed"))+ .unwrap_err();+ let dev = mgr.load_dev(second.to_str().unwrap()).unwrap_err();+ for error in [install, dev] {+ assert_eq!(+ error.to_string(),+ format!("PLUGIN_INVALID: id {alias} would share storage with installed plugin e2e.foo!bar")+ );+ }+ }++ assert_eq!(fs::read_to_string(installed_main).unwrap(), "// first\n");+ assert_eq!(fs::read_to_string(owner_file).unwrap(), "legacy data");+ assert_eq!(fs::read_to_string(®istry_path).unwrap(), registry);+ assert_eq!(ids(&mgr), ["e2e.foo!bar"]);+}diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 72d78b6d3..353bbf643 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4212,8 +4212,8 @@ this does not claim an installed full-app settings journey.#### E2E-PLUGIN-id-cannot-collide: Plugins with look-alike ids never share storage- **Preconditions**: Real host-core binary on a scratch data directory.-- **Steps**: 1) Install a plugin with id `e2e.foo_bar` from a local folder and write a file into its data directory. 2) For each look-alike id `e2e.foo!bar` (character replacement), `e2e.Foo_Bar` (letter case on case-insensitive file systems) and `e2e.foo_bar.` (Windows trailing dot), try to install it, then to load it as a development plugin.-- **Expected**: Every attempt fails with `PLUGIN_INVALID` naming the reason. The first plugin's installed files, data directory, and registry row are unchanged, and no second install directory appears, so two plugins can never share a directory or browser session partition (issue #2297).+- **Steps**: 1) Install a plugin with id `e2e.foo_bar` from a local folder and write a file into its data directory. 2) For each look-alike id `e2e.foo!bar` (character replacement), `e2e.Foo_Bar` (letter case on case-insensitive file systems) and `e2e.foo_bar.` (Windows trailing dot), try to install it, then to load it as a development plugin. 3) Rewrite the state into what an older build persisted for `e2e.foo!bar` (raw id in the registry row and installed manifest, sanitized directory names), restart the host, and try to install and load `e2e.foo_bar`.+- **Expected**: Every attempt fails with `PLUGIN_INVALID` naming the reason, including the legacy case (`would share storage with installed plugin e2e.foo!bar`). The first plugin's installed files, data directory, and registry row are unchanged, and no second install directory appears, so two plugins can never share a directory or browser session partition (issue #2297).- **Specs linked**: `07-plugins/02-plugin-manifest-schema.md` §7- **Status**: Automated (`pnpm test:e2e:plugin-id-collision`, `scripts/e2e-plugin-id-collision.mjs`); unit coverage in `crates/host-core/src/plugins/manifest.rs` and `packages/plugin-sdk/src/index.test.ts`diff --git a/docs/spec/07-plugins/02-plugin-manifest-schema.md b/docs/spec/07-plugins/02-plugin-manifest-schema.mdindex 903b365d7..4e93de2d2 100644--- a/docs/spec/07-plugins/02-plugin-manifest-schema.md+++ b/docs/spec/07-plugins/02-plugin-manifest-schema.md@@ -638,9 +638,12 @@ the oldest host you claim. Export `onLoad` / `onUnload` from `main`; there is noplugin's directory and share its files, storage, and network policy:characters outside `[A-Za-z0-9._-]` (each of those locations maps them to`_`), `.` / `..`, a trailing `.` or a leading Windows device name (`con`,- `nul.x`, ...), and an id that differs from an installed or development- plugin's id only in letter case (case-insensitive file systems resolve both- to one directory). Existing plugins keep their ids and directories.+ `nul.x`, ...), and an id whose storage name matches that of a different+ installed or development plugin. The storage name folds the id the way+ the platforms do (other characters to `_`, trailing dots dropped, letter+ case ignored), so it also covers plugins an older version stored under a+ sanitized name, such as `e2e.foo!bar` under `e2e.foo_bar`. Existing+ plugins keep their ids and directories.`pi-plugin check` still asks for the stricter shape in §13. Opening `ui.panel` requires the explicit declared and granted `ui.panel`permission; a panel path does not implicitly grant itdiff --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 3510d2291..d95c98218 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@@ -579,9 +579,10 @@ OAuth 贡献使用宿主管理的服务商账号界面。`onProviderOAuth` 处2. 需要 `id` / `name` / `version` / `main`。id 决定插件的安装目录、数据目录和浏览器会话分区,因此安装和加载时会拒绝可能落到另一个插件目录、与其共用文件、存储和网络策略的 id:含 `[A-Za-z0-9._-]` 以外的字符(这些位置都会把它们替换为 `_`)、等于 `.` /- `..`、以 `.` 结尾或以 Windows 设备名开头(`con`、`nul.x` 等),以及与已安装或开发中- 插件的 id 仅大小写不同(不区分大小写的文件系统会把两者解析到同一目录)。已有插件的- id 和目录保持不变。`pi-plugin check` 仍要求 §1 中更严格的格式+ `..`、以 `.` 结尾或以 Windows 设备名开头(`con`、`nul.x` 等),以及存储名与另一个+ 已安装或开发中插件相同的 id。存储名按各平台的方式折叠 id(其他字符替换为 `_`、去掉+ 结尾的 `.`、忽略大小写),因此也覆盖旧版本以替换后名称保存的插件,例如以+ `e2e.foo_bar` 保存的 `e2e.foo!bar`。已有插件的 id 和目录保持不变。`pi-plugin check` 仍要求 §1 中更严格的格式3. 打开 `ui.panel` 需要显式声明和用户授予 `ui.panel`,路径不会隐式授权4. 如果存在 `agentTools`,则必须声明 `agent.tool.register`。缺少该权限时`pi-plugin check` 报错(`permission.tools-missing`),安装器不会拒绝,diff --git a/scripts/e2e-plugin-id-collision.mjs b/scripts/e2e-plugin-id-collision.mjsindex 8fa5959b3..1945328db 100644--- a/scripts/e2e-plugin-id-collision.mjs+++ b/scripts/e2e-plugin-id-collision.mjs@@ -9,6 +9,12 @@* `e2e.foo!bar`, `e2e.Foo_Bar` and `e2e.foo_bar.`. Each must be refused with* PLUGIN_INVALID, and the first plugin's installed files, data directory,* and registry row must be untouched.+ *+ * It then rewrites that state into what an older build persisted for the id+ * `e2e.foo!bar` (raw id in the registry row and installed manifest, sanitized+ * directory names), restarts the host, and tries to install and load the+ * valid id `e2e.foo_bar`. Both must be refused and the legacy plugin's+ * files, data, and registry must stay as they were.*/import assert from "node:assert/strict";import { mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";@@ -29,8 +35,29 @@ async function writePlugin(dir, id, marker) {await writeFile(join(dir, "main.js"), `// ${marker}\nexport function onLoad() {}\n`);}+async function expectRefused(host, path, lookAlike, reason) {+ for (const [method, params] of [+ ["plugins.installFromPath", { path, enable: true }],+ ["plugins.loadDev", { path }],+ ]) {+ await assert.rejects(+ host.call(method, params),+ (error) => {+ assert.match(String(error.message), reason);+ return true;+ },+ `${method} must refuse ${lookAlike}, which maps onto another plugin's directory`,+ );+ }+}++async function e2eIds(host) {+ const { plugins } = await host.call("plugins.list", {});+ return plugins.map((plugin) => plugin.id).filter((id) => id.startsWith("e2e."));+}+const attempts = [];-const host = new Host(hostBinary, dataDir, { quiet: true });+let host = new Host(hostBinary, dataDir, { quiet: true });try {await host.start();@@ -53,27 +80,41 @@ try {const second = join(scratch, `src-${attempts.length}`);attempts.push(lookAlike);await writePlugin(second, lookAlike, "second plugin");- for (const [method, params] of [- ["plugins.installFromPath", { path: second, enable: true }],- ["plugins.loadDev", { path: second }],- ]) {- await assert.rejects(- host.call(method, params),- (error) => {- assert.match(String(error.message), reason);- return true;- },- `${method} must refuse ${lookAlike}, which maps onto another plugin's directory`,- );- }+ await expectRefused(host, second, lookAlike, reason);}assert.match(await readFile(installedMain, "utf8"), /first plugin/, "first plugin's files stay its own");assert.equal(await readFile(dataMarker, "utf8"), "first plugin data", "first plugin's data stays its own");assert.deepEqual(await readdir(join(dataDir, "plugins/installed")), ["e2e.foo_bar"]);- const { plugins } = await host.call("plugins.list", {});- const ids = plugins.map((plugin) => plugin.id).filter((id) => id.startsWith("e2e."));- assert.deepEqual(ids, ["e2e.foo_bar"]);+ assert.deepEqual(await e2eIds(host), ["e2e.foo_bar"]);++ // Legacy state: an older build accepted `e2e.foo!bar` and stored it under+ // the sanitized name `e2e.foo_bar`.+ await host.stop();+ const registryPath = join(dataDir, "plugins/registry.json");+ const legacyId = (text) => text.replaceAll('"e2e.foo_bar"', '"e2e.foo!bar"');+ const registry = legacyId(await readFile(registryPath, "utf8"));+ await writeFile(registryPath, registry);+ const manifestPath = join(dataDir, "plugins/installed/e2e.foo_bar/manifest.json");+ await writeFile(manifestPath, legacyId(await readFile(manifestPath, "utf8")));+ await writeFile(dataMarker, "legacy plugin data");++ host = new Host(hostBinary, dataDir, { quiet: true });+ await host.start();+ assert.deepEqual(await e2eIds(host), ["e2e.foo!bar"]);+ const alias = join(scratch, "src-alias");+ await writePlugin(alias, "e2e.foo_bar", "alias plugin");+ await expectRefused(+ host,+ alias,+ "e2e.foo_bar",+ /PLUGIN_INVALID: id e2e\.foo_bar would share storage with installed plugin e2e\.foo!bar/,+ );+ assert.match(await readFile(installedMain, "utf8"), /first plugin/, "legacy plugin's files stay its own");+ assert.equal(await readFile(dataMarker, "utf8"), "legacy plugin data", "legacy plugin's data stays its own");+ assert.equal(await readFile(registryPath, "utf8"), registry, "legacy registry is unchanged");+ assert.deepEqual(await readdir(join(dataDir, "plugins/installed")), ["e2e.foo_bar"]);+ assert.deepEqual(await e2eIds(host), ["e2e.foo!bar"]);console.log("PASS: plugin ids that map onto another plugin's directory are refused");} finally {