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(mcp): spawn stdio servers with the login-shell PATH
vastsa574c78a996cf
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.tsindex e773ae22f..c4c3615f3 100644--- a/apps/desktop/electron/main/plugin-mcp.ts+++ b/apps/desktop/electron/main/plugin-mcp.ts@@ -1,6 +1,7 @@import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";import { isAbsolute, resolve, sep } from "node:path";import type { PluginMcpServerContrib } from "@pi-desktop/plugin-sdk";+import { userLookupPath } from "./user-login-path.ts";/** MCP revision we advertise during the handshake. */export const MCP_PROTOCOL_VERSION = "2025-06-18";@@ -68,6 +69,9 @@ function mcpError(code: string, message: string): McpError {* and shell secrets, so only the values the caller declared cross over (D018).* `pluginId` is absent for a server the user configured directly, which has no* plugin identity to announce.+ *+ * PATH is the login-shell PATH (ADR 0045 / D600), not the Finder/Dock GUI+ * PATH, so a market-installed `uvx`/`npx` server can spawn (issue #571).*/export function mcpProcessEnv(pluginId: string | undefined,@@ -77,10 +81,12 @@ export function mcpProcessEnv(...(pluginId ? { PI_PLUGIN_ID: pluginId } : {}),NODE_ENV: process.env.NODE_ENV ?? "production",};- for (const key of ["PATH", "SystemRoot", "windir", "TEMP", "TMP", "TMPDIR", "LANG"]) {+ for (const key of ["SystemRoot", "windir", "TEMP", "TMP", "TMPDIR", "LANG"]) {const value = process.env[key];if (value) env[key] = value;}+ const path = userLookupPath(process.env.PATH ?? "");+ if (path) env.PATH = path;return { ...env, ...values };}@@ -178,7 +184,12 @@ function createStdioTransport(});child.on("error", (error: Error) => {closed = true;- handlers.onClose(error.message);+ const code = (error as NodeJS.ErrnoException).code;+ handlers.onClose(+ code === "ENOENT"+ ? `command not found: ${options.command}. Install it or add it to PATH.`+ : error.message,+ );});child.on("exit", (code) => {closed = true;diff --git a/apps/desktop/electron/main/user-login-path.ts b/apps/desktop/electron/main/user-login-path.tsnew file mode 100644index 000000000..c3912f918--- /dev/null+++ b/apps/desktop/electron/main/user-login-path.ts@@ -0,0 +1,91 @@+/**+ * Login-shell PATH for GUI-launched Electron (issue #571).+ *+ * Finder/Dock starts the app with `/usr/bin:/bin:/usr/sbin:/sbin`. MCP stdio+ * spawn uses `shell: false` and that PATH, so `uvx`/`npx` from Homebrew/nvm+ * become `ENOENT`. Host-core already probes the login shell for Bash+ * (ADR 0045); stdio MCP lives in Electron main and needs the same PATH.+ */+import { spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import { delimiter, join } from "node:path";++const PROBE_TIMEOUT_MS = 5_000;++export type LoginPathProbe = () => string | undefined;++/** `null` means not probed yet; `undefined` means the probe produced nothing. */+let cachedProbe: string | undefined | null = null;++export function resetUserLoginPathCacheForTests(): void {+ cachedProbe = null;+}++function defaultProbe(): string | undefined {+ if (process.platform === "win32") return undefined;+ const shell = [process.env.SHELL, "/bin/zsh", "/bin/bash", "/bin/sh"].find(+ (candidate): candidate is string => Boolean(candidate) && existsSync(candidate),+ );+ if (!shell) return undefined;+ try {+ const result = spawnSync(shell, ["-lic", 'printf %s "$PATH"'], {+ encoding: "utf8",+ timeout: PROBE_TIMEOUT_MS,+ stdio: ["ignore", "pipe", "ignore"],+ });+ if (result.status !== 0 || result.error || typeof result.stdout !== "string") {+ return undefined;+ }+ const path = result.stdout.trim().split(/\r?\n/).at(-1)?.trim();+ return path || undefined;+ } catch {+ return undefined;+ }+}++/** Directories a login shell usually puts on PATH, if they exist on disk. */+export function wellKnownUserBinDirs(home = homedir()): string[] {+ if (process.platform === "win32") return [];+ return [+ "/opt/homebrew/bin",+ "/opt/homebrew/sbin",+ "/usr/local/bin",+ join(home, ".local", "bin"),+ join(home, ".cargo", "bin"),+ ].filter((dir) => existsSync(dir));+}++export function mergePathParts(...groups: Array<string | undefined>): string {+ const seen = new Set<string>();+ const out: string[] = [];+ for (const group of groups) {+ if (!group) continue;+ for (const part of group.split(delimiter)) {+ if (!part || seen.has(part)) continue;+ seen.add(part);+ out.push(part);+ }+ }+ return out.join(delimiter);+}++export function probedLoginPath(probe: LoginPathProbe = defaultProbe): string | undefined {+ if (cachedProbe !== null) return cachedProbe;+ cachedProbe = probe() ?? undefined;+ return cachedProbe;+}++/**+ * PATH a GUI-launched stdio child should search: login-shell PATH, then+ * well-known user bins that exist, then the inherited process PATH.+ * Windows keeps the inherited PATH (ADR 0045).+ */+export function userLookupPath(+ inherited = process.env.PATH ?? "",+ probe: LoginPathProbe = defaultProbe,+): string {+ if (process.platform === "win32") return inherited;+ return mergePathParts(probedLoginPath(probe), wellKnownUserBinDirs().join(delimiter), inherited);+}+diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjsindex 6a868721b..35ae130ec 100644--- a/apps/desktop/test/plugin-mcp.test.mjs+++ b/apps/desktop/test/plugin-mcp.test.mjs@@ -3,7 +3,7 @@ import test from "node:test";import { createServer } from "node:http";import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { dirname, join } from "node:path";+import { delimiter, dirname, join } from "node:path";import { fileURLToPath } from "node:url";import {@@ -471,12 +471,22 @@ test("the stdio environment carries no host secrets", () => {assert.equal(env.TOKEN, "t0ken");assert.equal(env.PI_LEAKED_SECRET, undefined);// PATH still crosses, or a bare command name could never be found.- assert.equal(env.PATH, process.env.PATH);+ assert.ok(typeof env.PATH === "string" && env.PATH.length > 0);+ for (const part of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {+ assert.ok(env.PATH.split(delimiter).includes(part), part);+ }} finally {delete process.env.PI_LEAKED_SECRET;}});+test("stdio PATH uses the login-shell lookup and names a missing command", () => {+ const src = readFileSync(join(desktopRoot, "electron/main/plugin-mcp.ts"), "utf8");+ assert.match(src, /import \{ userLookupPath \} from "\.\/user-login-path\.ts"/);+ assert.match(src, /userLookupPath\(process\.env\.PATH/);+ assert.match(src, /command not found: \$\{options\.command\}/);+});+test("a command may not escape the plugin directory", () => {const dir = mkdtempSync(join(tmpdir(), "pi-mcp-cmd-"));assert.equal(resolveMcpCommand(dir, "node"), "node");diff --git a/apps/desktop/test/user-login-path.test.mjs b/apps/desktop/test/user-login-path.test.mjsnew file mode 100644index 000000000..d24ed4326--- /dev/null+++ b/apps/desktop/test/user-login-path.test.mjs@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { delimiter } from "node:path";+import test from "node:test";+import {+ mergePathParts,+ probedLoginPath,+ resetUserLoginPathCacheForTests,+ userLookupPath,+} from "../electron/main/user-login-path.ts";++test("mergePathParts keeps first-seen order and drops empties", () => {+ assert.equal(+ mergePathParts(`/opt/homebrew/bin${delimiter}/usr/bin`, `/usr/bin${delimiter}/bin`, ""),+ `/opt/homebrew/bin${delimiter}/usr/bin${delimiter}/bin`,+ );+ assert.equal(mergePathParts(undefined, "", "/usr/bin"), "/usr/bin");+});++test("a login-shell PATH is searched before the inherited GUI PATH", () => {+ resetUserLoginPathCacheForTests();+ const inherited = `/usr/bin${delimiter}/bin`;+ const path = userLookupPath(inherited, () => `/opt/homebrew/bin${delimiter}/usr/bin`);+ if (process.platform === "win32") {+ assert.equal(path, inherited);+ return;+ }+ const parts = path.split(delimiter);+ assert.equal(parts[0], "/opt/homebrew/bin");+ assert.ok(parts.includes("/usr/bin"));+ assert.ok(parts.includes("/bin"));+ assert.equal(parts.filter((part) => part === "/usr/bin").length, 1);+});++test("a failed probe still keeps the inherited PATH", () => {+ resetUserLoginPathCacheForTests();+ const inherited = `/usr/bin${delimiter}/sbin`;+ const path = userLookupPath(inherited, () => undefined);+ assert.ok(path.split(delimiter).includes("/usr/bin"));+ assert.ok(path.split(delimiter).includes("/sbin"));+});++test("the login-shell probe is cached for the process", () => {+ resetUserLoginPathCacheForTests();+ let calls = 0;+ const probe = () => {+ calls += 1;+ return "/tmp/probed";+ };+ assert.equal(probedLoginPath(probe), "/tmp/probed");+ assert.equal(probedLoginPath(() => "/tmp/other"), "/tmp/probed");+ assert.equal(calls, 1);+});diff --git a/docs/adr/0045-bash-inherits-user-login-path.md b/docs/adr/0045-bash-inherits-user-login-path.mdindex 4bc8308aa..6931b4adc 100644--- a/docs/adr/0045-bash-inherits-user-login-path.md+++ b/docs/adr/0045-bash-inherits-user-login-path.md@@ -1,10 +1,10 @@# ADR 0045: Bash tool inherits the user's login-shell PATH-- Status: Accepted+- Status: Accepted (amended 2026-09-20, D600 / issue #571)- Date: 2026-08-02- Related: [D084](../spec/08-meta/decisions-log.md) ·+ [D181](../spec/08-meta/decisions-log.md) ·[Tools and permissions](../spec/03-runtime/03-tools-and-permissions.md)-## ContextThe Bash tool runs agent commands through `bash -lc` (D084). A login bash@@ -41,6 +41,9 @@ further shrinks the environment to a minimal GUI PATH.overhead; every later Bash call is cache-only.- A slow or interactive-only user rc degrades gracefully to the previousbehavior instead of failing the tool.+- Stdio MCP servers spawned from Electron main use the same login-shell PATH+ (D600 / issue #571), because they share the Finder/Dock GUI PATH problem and+ cannot reuse the host-core probe.## Alternatives rejecteddiff --git a/docs/adr/README.md b/docs/adr/README.mdindex ac9a77a6b..ec968dc24 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -66,7 +66,7 @@ Each ADR includes:| 0042 | Message-scoped inline review cards | Superseded by 0043 || 0043 | Message-owned review snapshots and guarded rollback | Accepted || 0044 | Session-bound project instruction preflight | Accepted |-| 0045 | Bash tool inherits the user's login-shell PATH | Accepted |+| 0045 | Bash tool inherits the user's login-shell PATH | Accepted (amended D600 / issue #571) || 0046 | Categorized process log files | Accepted || 0047 | Context usage inspector with exact and estimated token sources | Accepted || 0048 | Lazy per-turn tool activation | Accepted |diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 2a0bae0f3..489d37915 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -361,6 +361,8 @@ or executable path hash is accepted as shell identity.`~/.zshrc` / `~/.zprofile` would otherwise be invisible to agent commands.The probe is best-effort: missing shell, non-zero exit, or timeout fall backto the host PATH unchanged. Agent commands stay POSIX bash (D181 / ADR 0045).+ Electron main applies the same lookup to stdio MCP spawn (`uvx`/`npx` from+ the market) so a Finder/Dock launch can find them (D600 / issue #571).- No bash bundled in the installer: Git for Windows is the Windows prerequisite (the app requires git anyway)- Resolution failure returns stable `SHELL_NOT_FOUND` with install guidance- Windows PowerShell and cmd use their native non-interactive invocation.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 4f2ed68d0..a30db529d 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1918,6 +1918,22 @@ identify the platform validation still needed.- **Milestone**: M5- **Status**: Automated (host-core unit tests: login-PATH probe + child-PATH injection)+#### E2E-MCP-stdio-login-path: Market stdio MCP finds uvx/npx after a GUI launch (issue #571)++- **Preconditions**: macOS; the app was started from Finder/Dock so `process.env.PATH`+ is the GUI default; `uvx` or `npx` exists on the user's login-shell PATH.+- **Steps**: 1) Install Fetch from the MCP market (`uvx mcp-server-fetch`).+ 2) Test connection. 3) Repeat with an npx catalog entry.+- **Expected**: The stdio child env PATH includes the login-shell PATH (Homebrew /+ nvm / `~/.local/bin`) ahead of the GUI PATH, so spawn succeeds. A truly missing+ binary reports `command not found: uvx` rather than `spawn uvx ENOENT`.+ Windows keeps the inherited PATH.+- **Specs linked**: ADR 0045, D600, `03-runtime/03-tools-and-permissions.md`+- **Acceptance**: Quality+- **Milestone**: M6++- **Status**: Automated (`apps/desktop/test/user-login-path.test.mjs`,+ `apps/desktop/test/plugin-mcp.test.mjs`)+### Session Persistence#### E2E-020: Session survives restartdiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex bf65050fd..6563ad956 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6400,3 +6400,18 @@ that was sitting at the bottom — including after the turn had finished.- `out/renderer` emits no application font face any more; only KaTeX's `woff2`glyphs remain. See ADR 0298, `04-ux/06-settings-ia.md`,`04-ux/07-ui-design-system.md`, and E2E-126.++## 2026-09-20 — Stdio MCP spawn uses the login-shell PATH (D600, issue #571)++- Finder/Dock launches Electron with `/usr/bin:/bin:/usr/sbin:/sbin`. User MCP+ stdio spawn copies that PATH and uses `shell: false`, so a market-installed+ Fetch server (`uvx mcp-server-fetch`) failed with `spawn uvx ENOENT` even+ when `uvx` worked in a terminal. Same hole for `npx`.+- Electron main now probes the login shell the way host-core already does for+ Bash (ADR 0045): `$SHELL -lic 'printf %s "$PATH"'`, 5s-bounded, cached, last+ stdout line only. Well-known user bin dirs that exist (`/opt/homebrew/bin`,+ `~/.local/bin`, `~/.cargo/bin`, …) are merged in. Windows stays on the+ inherited PATH. Command names stay bare; arguments stay literal.+- A missing executable is reported as `command not found: <name>` instead of+ a raw `spawn uvx ENOENT`.+- See ADR 0045, `03-runtime/03-tools-and-permissions.md`, issue #571.