Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(skills): isolate discovery failures and reconcile failed imports

yuxinoe7118c9c648c
diff --git a/apps/desktop/electron/main/pi-skill-discovery.ts b/apps/desktop/electron/main/pi-skill-discovery.ts
index b17566af0..dba90fa48 100644
--- a/apps/desktop/electron/main/pi-skill-discovery.ts
+++ b/apps/desktop/electron/main/pi-skill-discovery.ts
@@ -1,10 +1,10 @@
import { createHash } from "node:crypto";
+import type { Dirent } from "node:fs";
import { lstat, readdir, readFile, realpath } from "node:fs/promises";
import { join } from "node:path";
import type { PiSkillDiscovery, PiSkillPackageCandidate } from "@pi-desktop/shared";
import { discoverImportedPackageSkills } from "./imported-package-skills";
-const MAX_PACKAGES = 256;
const MAX_METADATA_BYTES = 256 * 1024;
async function readMetadata(path: string): Promise<string> {
@@ -21,24 +21,33 @@ export async function discoverPiSkillPackages(modules: string, importedDescripti
const errors: string[] = [];
const importedSources = new Set(importedDescriptions);
const paths: string[] = [];
+ let entries: Dirent[];
try {
const info = await lstat(modules);
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error("pi npm directory must not be a symbolic link");
modules = await realpath(modules);
- for (const entry of await readdir(modules, { withFileTypes: true })) {
- if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(".")) continue;
- if (entry.name.startsWith("@")) {
- for (const child of await readdir(join(modules, entry.name), { withFileTypes: true })) {
- if (child.isDirectory() && !child.isSymbolicLink()) paths.push(join(modules, entry.name, child.name));
- if (paths.length > MAX_PACKAGES) throw new Error("pi npm discovery exceeds 256 packages");
- }
- } else paths.push(join(modules, entry.name));
- if (paths.length > MAX_PACKAGES) throw new Error("pi npm discovery exceeds 256 packages");
- }
+ entries = await readdir(modules, { withFileTypes: true });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { candidates, errors };
throw error;
}
+ // npm hoists ordinary dependencies beside installed pi packages. Their count
+ // must not hide valid skills; metadata reads below yield between packages.
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name.startsWith(".")) continue;
+ const path = join(modules, entry.name);
+ if (!entry.name.startsWith("@")) {
+ paths.push(path);
+ continue;
+ }
+ try {
+ for (const child of await readdir(path, { withFileTypes: true })) {
+ if (child.isDirectory() && !child.isSymbolicLink()) paths.push(join(path, child.name));
+ }
+ } catch (error) {
+ errors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
for (const path of paths.sort()) {
try {
const raw = await readMetadata(join(path, "package.json"));
diff --git a/apps/desktop/src/components/settings/PiSkillDiscoveryPanel.tsx b/apps/desktop/src/components/settings/PiSkillDiscoveryPanel.tsx
index d72dbf107..b4b450636 100644
--- a/apps/desktop/src/components/settings/PiSkillDiscoveryPanel.tsx
+++ b/apps/desktop/src/components/settings/PiSkillDiscoveryPanel.tsx
@@ -31,7 +31,12 @@ export function PiSkillDiscoveryPanel() {
}
setRefresh(value => value + 1);
}
- } catch (reason) { setError(String(reason)); }
+ } catch (reason) {
+ setError(String(reason));
+ // Host registration can succeed before the runtime fails to start.
+ // Rediscover so a registered import stays manageable through Plugins.
+ setRefresh(value => value + 1);
+ }
finally { setBusy(false); }
}
return <section className="settings-card-block pi-skill-discovery" aria-label={t("plugins.piSkillsTitle")}>
diff --git a/apps/desktop/test/pi-skill-discovery.test.mjs b/apps/desktop/test/pi-skill-discovery.test.mjs
index 8d0911164..57cbee7bd 100644
--- a/apps/desktop/test/pi-skill-discovery.test.mjs
+++ b/apps/desktop/test/pi-skill-discovery.test.mjs
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { register } from 'node:module';
-import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync, symlinkSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, writeFileSync, existsSync, rmSync, symlinkSync, chmodSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
register(new URL('./helpers/ts-import-hooks.mjs', import.meta.url));
@@ -24,6 +24,19 @@ test('discovers installed plain and scoped packages without importing or executi
assert.ok(result.candidates.every(c => c.skills.length === 1 && !c.hasExtensions && !c.imported));
assert.equal(existsSync(f.imports), false);
});
+test('hoisted npm dependencies do not prevent discovery of installed skills', async t => {
+ const f = fixture(t);
+ for (let index = 0; index < 300; index++) {
+ const name = `dependency-${index}`;
+ f.write(name, 'package.json', JSON.stringify({ name, version: '1.0.0' }));
+ }
+ f.pkg('planning-with-files');
+ f.pkg('@scope/skills');
+ const result = await discoverPiSkillPackages(f.modules);
+ assert.deepEqual(result.candidates.map(candidate => candidate.name), ['@scope/skills', 'planning-with-files']);
+ assert.deepEqual(result.errors, []);
+ assert.equal(existsSync(f.imports), false);
+});
test('one malformed package does not hide healthy candidates; links are not followed', async t => {
const f = fixture(t); f.pkg('healthy'); f.write('broken', 'package.json', '{');
symlinkSync(join(f.modules, 'healthy'), join(f.modules, 'linked'), process.platform === 'win32' ? 'junction' : 'dir');
@@ -31,6 +44,16 @@ test('one malformed package does not hide healthy candidates; links are not foll
assert.deepEqual(result.candidates.map(c => c.name), ['healthy']);
assert.ok(result.errors.some(e => e.includes('broken')));
});
+test('an unreadable scope reports a diagnostic without hiding healthy packages', { skip: process.platform === 'win32' || process.getuid?.() === 0 }, async t => {
+ const f = fixture(t); f.pkg('healthy');
+ const blocked = join(f.modules, '@blocked');
+ mkdirSync(blocked); chmodSync(blocked, 0);
+ try {
+ const result = await discoverPiSkillPackages(f.modules);
+ assert.deepEqual(result.candidates.map(candidate => candidate.name), ['healthy']);
+ assert.ok(result.errors.some(error => error.includes('@blocked') && error.includes('EACCES')));
+ } finally { chmodSync(blocked, 0o755); }
+});
test('existing imports remain recognized after rediscovery without a second registry', async t => {
const f = fixture(t); f.pkg('planning-with-files');
const imported = generateImportedExtensionPlugin(join(f.modules, 'planning-with-files'), f.imports);
@@ -67,7 +90,13 @@ function harness(f, t, confirm = async () => ({ response: 1 })) {
dialogs: { showMessageBox: confirm }, getLocale: () => 'en',
getNpmPath: () => undefined, setNpmPath: () => {},
getImportedDescriptions: async () => descriptions,
- loadDevPlugin: async path => { const result = await runtime.loadFromPath(path); const { readFileSync } = await import("node:fs"); descriptions.push(JSON.parse(readFileSync(join(path, "manifest.json"), "utf8")).description); return result; }, runCommand: async () => ({ handled: false }),
+ loadDevPlugin: async path => {
+ const { readFileSync } = await import("node:fs");
+ // Production persists host registration before starting the plugin child.
+ descriptions.push(JSON.parse(readFileSync(join(path, "manifest.json"), "utf8")).description);
+ return runtime.loadFromPath(path);
+ },
+ runCommand: async () => ({ handled: false }),
}, f.modules);
return { runtime, discover: () => handlers.get(IPC.invoke.piSkillDiscover)(), enable: id => handlers.get(IPC.invoke.piSkillImport)({ id }) };
}
diff --git a/docs/adr/pi-npm-skill-discovery.md b/docs/adr/pi-npm-skill-discovery.md
index 08ac3c2f7..b4b7d38b6 100644
--- a/docs/adr/pi-npm-skill-discovery.md
+++ b/docs/adr/pi-npm-skill-discovery.md
@@ -17,9 +17,11 @@ packages that also contain executable extensions.
The Skills page requests read-only candidates from the installed package level
of `~/.pi/agent/npm/node_modules`, including scoped packages. Electron main
reuses the existing `pi.skills` declaration parser. Discovery neither imports
-nor executes code. Package metadata is bounded to 256 KiB, package enumeration
-to 256 entries, and contribution traversal retains the importer's bounds and
-path validation. Invalid packages produce diagnostics without hiding valid peers.
+nor executes code. Package metadata is bounded to 256 KiB and contribution
+traversal retains the importer's bounds and path validation. Metadata reads
+are asynchronous; hoisted npm dependencies do not impose a skill-discovery
+cutoff. Invalid packages and unreadable scopes produce diagnostics without
+hiding valid peers.
The renderer sends a candidate identifier, never a source path. Main rediscovers
the candidate, displays native confirmation including its source and whether it
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index ac67c6a8f..deb7881ed 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14354,11 +14354,15 @@ the latest destination. These assertions measure work counts, not device FPS.
a package declaring `pi.skills`, optionally executable extensions. No provider.
- **Steps:** Open Skills, discover the candidate, cancel import, confirm import,
read the registered skill body and resources, reload, and attempt a duplicate.
- Change metadata during confirmation; retry discovery after an error.
+ Change metadata during confirmation; retry discovery after an error; discover
+ with more than 256 hoisted dependencies and an unreadable scope. Simulate a
+ runtime load failure after host registration and inspect the refreshed state.
- **Expected:** No implicit import/execution, native explicit consent, preserved
resources and runtime skill body, stable imported state, no duplicate import,
stale consent refusal, and visible/recoverable errors. Unregistered leftover
- directories do not count as imports; scoped packages are discovered.
+ directories do not count as imports; scoped packages are discovered. Unrelated
+ dependencies and unreadable scopes do not hide healthy skills. A registered
+ import remains marked imported after runtime failure while its error stays visible.
- **Specs:** 07-plugins/16-trusted-extensions; ADR pi-npm-skill-discovery.
- **Acceptance:** Plugin skill discovery and explicit trust boundary.
- **Milestone:** Post-MVP compatibility.
diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.md
index 282b6fe1c..8a3706275 100644
--- a/docs/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/spec/07-plugins/16-trusted-extensions.md
@@ -208,8 +208,9 @@ Settings → Skills lists read-only candidates from
package name, source path, declared skill paths, and a warning when executable
extensions are included. Discovery grants no permissions and does not execute
package code. Refresh retries discovery; invalid packages show diagnostics
-without suppressing healthy candidates. Enumeration is limited to 256 packages;
-package metadata must be a regular file no larger than 256 KiB. Symbolic package
+without suppressing healthy candidates, including when a scoped directory is
+unreadable. Hoisted npm dependencies do not cap discovery; metadata reads are
+asynchronous and must read a regular file no larger than 256 KiB. Symbolic package
links are not followed. The existing contribution parser enforces path bounds.
Import and enable asks for native confirmation (Cancel is the default), then
@@ -218,14 +219,14 @@ import. The renderer sends only a candidate id. Main rediscovers before and
after confirmation, rejecting stale metadata, changed declarations, arbitrary
paths and concurrent imports. Registered imported packages are marked Already
imported, including when disabled; manage them in Plugins. Unregistered leftover
-directories do not block retry. No second persisted enablement registry exists.
+directories do not block retry. If host registration succeeds but runtime loading
+fails, the error remains visible and the panel refreshes the registered state;
+recovery uses Plugins reload or app restart. No second persisted enablement registry exists.
No schema or host RPC version changes. General CLI configuration discovery and
source-update synchronization remain outside scope. See ADR pi-npm-skill-discovery.
## 4. Loading and runtime
-## 4. Loading and runtime
-
### 4.1 Where extensions run
Extensions load inside the Agent sidecar process (`packages/agent-runtime`),
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 0b383bd98..2e1d5f713 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -8520,11 +8520,15 @@ the latest destination. These assertions measure work counts, not device FPS.
a package declaring `pi.skills`, optionally executable extensions. No provider.
- **Steps:** Open Skills, discover the candidate, cancel import, confirm import,
read the registered skill body and resources, reload, and attempt a duplicate.
- Change metadata during confirmation; retry discovery after an error.
+ Change metadata during confirmation; retry discovery after an error; discover
+ with more than 256 hoisted dependencies and an unreadable scope. Simulate a
+ runtime load failure after host registration and inspect the refreshed state.
- **Expected:** No implicit import/execution, native explicit consent, preserved
resources and runtime skill body, stable imported state, no duplicate import,
stale consent refusal, and visible/recoverable errors. Unregistered leftover
- directories do not count as imports; scoped packages are discovered.
+ directories do not count as imports; scoped packages are discovered. Unrelated
+ dependencies and unreadable scopes do not hide healthy skills. A registered
+ import remains marked imported after runtime failure while its error stays visible.
- **Specs:** 07-plugins/16-trusted-extensions; ADR pi-npm-skill-discovery.
- **Acceptance:** Plugin skill discovery and explicit trust boundary.
- **Milestone:** Post-MVP compatibility.
diff --git a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
index badcfb5b7..a4fcde313 100644
--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
@@ -121,8 +121,9 @@ Agent 扩展。
设置 → 技能只读扫描 `~/.pi/agent/npm/node_modules` 下的普通包和作用域包,
展示包名、来源、技能路径以及可执行扩展警告。扫描不导入、不执行、不授予权限。
-包数量上限为 256,元数据必须是至多 256 KiB 的普通文件,不跟随包符号链接;
-技能声明沿用已有路径校验。损坏包显示诊断,不影响其他有效候选;刷新可重试。
+逐包异步读取元数据,提升到同级目录的 npm 依赖数量不会截断技能发现;
+元数据必须是至多 256 KiB 的普通文件,不跟随包符号链接;
+技能声明沿用已有路径校验。损坏包和不可读的作用域目录显示诊断,不影响其他有效候选;刷新可重试。
“导入并启用”先显示原生确认,默认取消,再复用手动导入、受限依赖安装、宿主注册
及插件运行时。渲染层只提交候选标识,主进程在确认前后重新发现,拒绝声明变更、
@@ -131,6 +132,8 @@ Agent 扩展。
RPC 版本。通用 CLI 配置扫描和来源更新同步不在本次范围。参见
[ADR pi-npm-skill-discovery](/adr/pi-npm-skill-discovery)。
+若主机登记成功但运行时加载失败,页面保留错误并刷新登记状态;可在 Plugins 中重新加载或重启应用恢复。
+
## 4. 加载与运行时
### 4.1 扩展在哪里运行
diff --git a/scripts/e2e/pi-skill-discovery-ui.tsx b/scripts/e2e/pi-skill-discovery-ui.tsx
index 153d3d89a..643047709 100644
--- a/scripts/e2e/pi-skill-discovery-ui.tsx
+++ b/scripts/e2e/pi-skill-discovery-ui.tsx
@@ -22,6 +22,7 @@ globalThis.piSkillDiscoveryProbe = async () => {
let calls = 0;
let cancel = true;
let fail = false;
+ let runtimeFailure = false;
api.discoverPiSkills = async () => {
if (fail) throw new Error("Discovery unavailable");
return { candidates: [{ ...candidate }], errors: [] };
@@ -29,6 +30,7 @@ globalThis.piSkillDiscoveryProbe = async () => {
api.importPiSkills = async id => {
assert(id === candidate.id, "wrong candidate"); calls++;
if (!cancel) candidate.imported = true;
+ if (runtimeFailure) throw new Error("Plugin process failed");
return { canceled: cancel };
};
const container = document.createElement("div"); document.body.append(container);
@@ -53,6 +55,16 @@ globalThis.piSkillDiscoveryProbe = async () => {
flushSync(() => button("Refresh pi CLI skills").click());
await until(() => !button("Refresh pi CLI skills").disabled);
assert(!container.querySelector('[role="alert"]'), "retry must clear previous failure");
+ candidate.imported = false;
+ flushSync(() => button("Refresh pi CLI skills").click());
+ await until(() => Boolean(button("Import and enable")));
+ runtimeFailure = true;
+ flushSync(() => button("Import and enable").click());
+ await until(() => Boolean(container.querySelector('[role="alert"]')));
+ await until(() => Boolean(button("Already imported")));
+ assert(button("Already imported").disabled, "host registration must survive a runtime failure");
+ assert(container.textContent?.includes("Plugin process failed"), "rediscovery must not hide the import error");
+ assert(container.textContent?.includes("manage imported packages in Plugins"), "recovery location must remain visible");
root.unmount(); container.remove();
- return { ok: true, scenarios: ["discover without import", "cancel", "enable", "duplicate", "failure and retry"] };
+ return { ok: true, scenarios: ["discover without import", "cancel", "enable", "duplicate", "failure and retry", "registered import runtime failure"] };
};