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): retry project-scoped server connections
Aulia Aisyah61add8835b5b
diff --git a/apps/desktop/electron/main/ipc/mcp-ipc.ts b/apps/desktop/electron/main/ipc/mcp-ipc.tsindex 224bd95e8..bfe9a5ee2 100644--- a/apps/desktop/electron/main/ipc/mcp-ipc.ts+++ b/apps/desktop/electron/main/ipc/mcp-ipc.ts@@ -78,7 +78,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>sendToRenderer(IPC.event.pluginChanged, { reason: "mcp", pluginId: res.server?.id });if (res.server && res.server.enabled !== false) {void userMcp- .test(res.server.id)+ .test(res.server.id, currentWorkspacePath()).then(() => {sendToRenderer(IPC.event.pluginChanged, { reason: "mcp", pluginId: res.server.id });})@@ -155,7 +155,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>...userMcp.listRecords().filter((record) => !listed.servers.some((item) => item.id === record.id)),...(listed.servers ?? []),]);- const status = await userMcp.test(payload.id);+ const status = await userMcp.test(payload.id, payload.projectPath ?? currentWorkspacePath());await refreshUserMcp(currentWorkspacePath());sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: payload.id });const hasOauth = oauth ? await oauth.hasOAuth(payload.id) : false;diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.tsindex 8aee65164..7d1738fb4 100644--- a/apps/desktop/electron/main/user-mcp.ts+++ b/apps/desktop/electron/main/user-mcp.ts@@ -304,7 +304,10 @@ export class UserMcpRuntime {* button. The connection is kept: a user who just tested a server is about to* use it.*/- async test(serverId: string): Promise<McpServerStatus> {+ async test(+ serverId: string,+ projectPath: string | null | undefined = null,+ ): Promise<McpServerStatus> {const record = this.records.find((entry) => entry.id === serverId);if (!record) {return {@@ -315,13 +318,26 @@ export class UserMcpRuntime {updatedAt: Date.now(),};}- // Force a fresh handshake so a fixed command is retried rather than- // reporting the cached failure.- const key = connectionKey(record, null);- this.entries.get(key)?.client.close();- this.entries.delete(key);- await this.connect(record, null);- return this.statusFor(serverId);+ // Retry the requested workspace and clear this server's other failed+ // workspace caches. A successful home test must not leave project sessions+ // stuck on an earlier failure. Never interrupt a handshake or tool call.+ const targetKey = connectionKey(record, projectPath);+ for (const [key, entry] of [...this.entries]) {+ if (+ entry.record.id !== serverId || entry.connecting || entry.activeCalls > 0 ||+ (key !== targetKey && entry.status.state !== "failed")+ ) continue;+ entry.client.close();+ this.entries.delete(key);+ }+ const { entry } = await this.connect(record, projectPath);+ return entry ? { ...entry.status } : {+ serverId,+ state: "failed",+ toolCount: 0,+ message: "connection cache is full; try again after active calls finish",+ updatedAt: Date.now(),+ };}/** Drop a cached connection and tools for a server. */@@ -375,7 +391,12 @@ export class UserMcpRuntime {const key = connectionKey(record, projectPath);let existing = this.entries.get(key);- if (existing && record.transport === "http" && existing.oauthToken !== oauthToken) {+ // Token refresh can run while Test connection or another session arrives.+ // Let existing calls/handshakes finish; rotate the transport when idle.+ if (+ existing && record.transport === "http" && existing.oauthToken !== oauthToken &&+ !existing.connecting && existing.activeCalls === 0+ ) {existing.client.close();this.entries.delete(key);existing = undefined;diff --git a/apps/desktop/test/mcp-project-retry.test.mjs b/apps/desktop/test/mcp-project-retry.test.mjsnew file mode 100644index 000000000..75853e296--- /dev/null+++ b/apps/desktop/test/mcp-project-retry.test.mjs@@ -0,0 +1,91 @@+import assert from "node:assert/strict";+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { rm } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { IPC } from "@pi-desktop/shared";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { UserMcpRuntime } = await import("../electron/main/user-mcp.ts");+const { McpServerClient } = await import("../electron/main/plugin-mcp.ts");+const { registerMcpIpc } = await import("../electron/main/ipc/mcp-ipc.ts");++const SERVER = `+import { existsSync } from "node:fs";+if (!existsSync(process.env.READY_FILE)) process.exit(1);+let input = "";+process.stdin.setEncoding("utf8");+process.stdin.on("data", (chunk) => {+ input += chunk;+ for (let index; (index = input.indexOf("\\n")) >= 0;) {+ const line = input.slice(0, index); input = input.slice(index + 1);+ if (!line) continue;+ const request = JSON.parse(line);+ let result;+ if (request.method === "initialize") result = { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} } };+ else if (request.method === "tools/list") result = { tools: [{ name: "cwd" }] };+ else if (request.method === "tools/call") result = { content: [{ type: "text", text: process.cwd() }] };+ else continue;+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\\n");+ }+});+`;++for (const explicitProject of [false, true]) {+ test(`MCP Test connection restores the ${explicitProject ? "selected" : "current"} project's real stdio tools`, async (t) => {+ const root = mkdtempSync(join(tmpdir(), "pi-mcp-retry-ipc-"));+ const project = mkdtempSync(join(root, "project-"));+ const otherProject = mkdtempSync(join(root, "other-"));+ const server = join(root, "server.mjs");+ const readyFile = join(root, "ready");+ writeFileSync(server, SERVER);+ const record = {+ id: "retry", label: "Retry", transport: "stdio", command: "node", args: [server],+ env: { READY_FILE: readyFile }, enabled: true, scope: { mode: "global", projects: [] },+ };+ const rt = new UserMcpRuntime({+ createClient: (config) => new McpServerClient(config), connectTimeoutMs: 5_000, callTimeoutMs: 5_000,+ });+ t.after(async () => {+ rt.disposeAll();+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 25 });+ });+ rt.setRecords([record]);+ assert.deepEqual(await rt.toolsForProject(project), []);+ assert.deepEqual(await rt.toolsForProject(otherProject), []);+ writeFileSync(readyFile, "ready");++ const handlers = new Map();+ const events = [];+ const currentProject = explicitProject ? otherProject : project;+ registerMcpIpc({+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },+ getHost: () => ({ call: async (method) => {+ assert.equal(method, "mcp.list");+ return { servers: [record] };+ } }),+ userMcp: rt,+ currentWorkspacePath: () => currentProject,+ refreshUserMcp: async (projectPath) => {+ rt.setRecords([record]);+ await rt.toolsForProject(projectPath);+ return [record];+ },+ describeError: (error) => error.message,+ sendToRenderer: (channel, payload) => events.push([channel, payload]),+ searchMcpMarket: async () => ({ entries: [] }),+ });+ const response = await handlers.get(IPC.invoke.mcpTest)({+ id: record.id, ...(explicitProject ? { level: "project", projectPath: project } : {}),+ });+ assert.equal(response.status.state, "ready");+ assert.deepEqual(response.status.toolNames, ["cwd"]);+ assert.ok(events.some(([channel]) => channel === IPC.event.pluginChanged));+ assert.equal((await rt.toolsForProject(project))[0].fullName, "mcp_retry_cwd");+ assert.equal((await rt.toolsForProject(otherProject))[0].fullName, "mcp_retry_cwd");+ const result = await rt.callTool("mcp_retry_cwd", {}, project);+ assert.equal(result.content[0].text.toLowerCase(), project.toLowerCase());+ assert.equal(readFileSync(readyFile, "utf8"), "ready");+ });+}diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjsindex 7e55cdd93..afba53136 100644--- a/apps/desktop/test/user-mcp.test.mjs+++ b/apps/desktop/test/user-mcp.test.mjs@@ -560,6 +560,175 @@ test("testing a server retries it and reports the tools it found", async (t) =>assert.deepEqual(ready.toolNames, ["lookup", "ping"]);});+test("testing a server clears failed workspace caches without an enable toggle", async (t) => {+ const dir = stubDir();+ const firstProject = projectDir("retry-a");+ const secondProject = projectDir("retry-b");+ const readyFile = join(dir, "ready");+ const original = readFileSync(join(dir, "server.mjs"), "utf8");+ writeFileSync(join(dir, "server.mjs"),+ `import { existsSync } from "node:fs";+if (!existsSync(${JSON.stringify(readyFile)})) process.exit(1);+${original}`);+ const rt = runtime(t);+ rt.setRecords([stubRecord(dir, { env: { STUB_REPORT_CWD: "1" } })]);+ assert.deepEqual(await rt.toolsForProject(firstProject), []);+ assert.deepEqual(await rt.toolsForProject(secondProject), []);+ writeFileSync(readyFile, "ready");++ // The default settings test used to repair only the home-directory cache.+ const status = await rt.test("stub");+ assert.equal(status.state, "ready");+ assert.ok((await rt.toolsForProject(firstProject)).some((tool) => tool.fullName === "mcp_stub_cwd"));+ assert.ok((await rt.toolsForProject(secondProject)).some((tool) => tool.fullName === "mcp_stub_cwd"));+ assert.equal((await rt.callTool("mcp_stub_cwd", {}, firstProject)).content[0].text.split("|")[0], firstProject);+ assert.equal((await rt.callTool("mcp_stub_cwd", {}, secondProject)).content[0].text.split("|")[0], secondProject);+});++test("testing a server handshakes its requested workspace", async (t) => {+ const dir = stubDir();+ const projectPath = projectDir("requested");+ const rt = runtime(t);+ rt.setRecords([stubRecord(dir, { env: { STUB_TOOL_ONLY_IN_CWD: projectPath } })]);++ const status = await rt.test("stub", projectPath);+ assert.equal(status.state, "ready");+ assert.ok(status.toolNames.includes("project_only"), "the test must not discover a home-directory catalog");+ assert.equal(await rt.callTool("mcp_stub_project_only", {}, projectPath).then((value) => value.content[0].text), "untagged:project_only");+});++for (const sameProject of [false, true]) {+test(`testing a server does not interrupt a tool call in ${sameProject ? "the same" : "another"} workspace`, async (t) => {+ const firstProject = projectDir("active");+ const testedProject = sameProject ? firstProject : projectDir("tested");+ let started;+ let finish;+ const callStarted = new Promise((resolve) => { started = resolve; });+ const clients = new Map();+ const rt = new UserMcpRuntime({+ createClient: ({ rootPath }) => {+ let connected = false;+ const tools = [{ name: "lookup" }];+ const client = {+ connect: async () => { connected = true; return tools; },+ getTools: () => connected ? tools : [],+ isConnected: () => connected,+ callTool: async () => new Promise((resolve, reject) => {+ finish = resolve;+ client.failCall = reject;+ started();+ }),+ close: () => { connected = false; client.failCall?.(new Error("active call interrupted")); },+ ping: async () => {},+ };+ clients.set(rootPath, client);+ return client;+ },+ });+ t.after(() => rt.disposeAll());+ rt.setRecords([stubRecord("/unused")]);+ await rt.toolsForProject(firstProject);+ const activeClient = clients.get(firstProject);+ const pending = rt.callTool("mcp_stub_lookup", {}, firstProject);+ await callStarted;++ assert.equal((await rt.test("stub", testedProject)).state, "ready");+ assert.equal(activeClient.isConnected(), true);+ finish("completed");+ assert.equal(await pending, "completed");+ assert.equal(clients.get(firstProject), activeClient);+});++}++test("testing a server reuses its pending workspace handshake", async (t) => {+ const projectPath = projectDir("connecting");+ let release;+ let closeCount = 0;+ let handshakes = 0;+ let connected = false;+ const gate = new Promise((resolve) => { release = resolve; });+ const tools = [{ name: "lookup" }];+ const rt = new UserMcpRuntime({+ createClient: () => ({+ connect: async () => { handshakes += 1; await gate; connected = true; return tools; },+ getTools: () => connected ? tools : [],+ isConnected: () => connected,+ close: () => { closeCount += 1; connected = false; },+ callTool: async () => "called",+ ping: async () => {},+ }),+ });+ t.after(() => rt.disposeAll());+ rt.setRecords([stubRecord("/unused")]);+ const pendingTools = rt.toolsForProject(projectPath);+ const pendingTest = rt.test("stub", projectPath);+ assert.equal(closeCount, 0);+ release();+ assert.equal((await pendingTools)[0].fullName, "mcp_stub_lookup");+ assert.equal((await pendingTest).state, "ready");+ assert.equal(handshakes, 1);+});++for (const pendingHandshake of [false, true]) {+ test(`testing HTTP MCP during token rotation preserves a pending ${pendingHandshake ? "handshake" : "call"}`, async (t) => {+ let token = "first";+ let release;+ let markStarted;+ const gate = new Promise((resolve) => { release = resolve; });+ const started = new Promise((resolve) => { markStarted = resolve; });+ const clients = [];+ const tools = [{ name: "lookup" }];+ const rt = new UserMcpRuntime({+ oauth: { getValidAccessToken: async () => token, hasOAuth: async () => true },+ createClient: ({ server }) => {+ let connected = false;+ let rejectCall;+ const client = {+ token: server.headers.Authorization,+ closes: 0,+ connect: async () => {+ if (pendingHandshake && clients.length === 1) { markStarted(); await gate; }+ connected = true;+ return tools;+ },+ getTools: () => connected ? tools : [],+ isConnected: () => connected,+ callTool: () => new Promise((resolve, reject) => {+ rejectCall = reject;+ markStarted();+ gate.then(() => resolve("completed"));+ }),+ close: () => { client.closes += 1; connected = false; rejectCall?.(new Error("call interrupted")); },+ ping: async () => {},+ };+ clients.push(client);+ return client;+ },+ });+ t.after(() => rt.disposeAll());+ rt.setRecords([stubRecord("/unused", { transport: "http", command: undefined, args: undefined, url: "http://127.0.0.1:9999/mcp" })]);+ let pending;+ if (pendingHandshake) pending = rt.toolsForProject("/repo");+ else {+ await rt.toolsForProject("/repo");+ pending = rt.callTool("mcp_stub_lookup", {}, "/repo");+ }+ await started;+ token = "second";+ const tested = rt.test("stub", "/repo");+ // Explicitly release the old operation, then verify no replacement killed it.+ release();+ assert.equal((await tested).state, "ready");+ if (pendingHandshake) assert.equal((await pending)[0].fullName, "mcp_stub_lookup");+ else assert.equal(await pending, "completed");+ assert.equal(clients[0].closes, 0);+ await rt.toolsForProject("/repo");+ assert.equal(clients.at(-1).token, "Bearer second");+ assert.equal(clients[0].closes, 1, "rotation is deferred until the original operation is idle");+ });+}+test("testing a server that is not saved reports it instead of throwing", async (t) => {const rt = runtime(t);rt.setRecords([]);diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 4b361dee2..0acefc299 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,10 @@# Unreleased changes+- Fixed MCP servers staying unavailable in project sessions after Test connection+ reported success. Testing now uses the selected project's working directory+ and clears that server's idle failed workspace connections without interrupting+ active tool calls or handshakes.+- Fixed the composer context ring staying at the pre-compaction figure after`/compact` or an automatic compaction until another turn ran (#2015). Thering now shows the compacted context's estimated size as soon as thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex f7347948c..52e4845cb 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -9400,7 +9400,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.override so the next connection uses the default handshake timeout.- The broken command records `failed` with a message, contributes no tools,and is not re-dialled on the following session assembly; pressing Test- retries it.+ retries it. After a transient failure in two projects, repair the stub+ without editing its saved record and test the server. Both projects regain+ tools on their next session without an enable toggle. Testing a selected+ project uses that project's cwd and tool catalog; an active call or+ handshake in another project completes without interruption.- A stopped HTTP server loses its `ready` status on settings refresh andreports `failed`; Test connection restores `ready` after it restarts.- **Specs linked**: `07-plugins/01-plugin-system.md` §12,diff --git a/docs/spec/07-plugins/01-plugin-system.md b/docs/spec/07-plugins/01-plugin-system.mdindex 849fddd8f..4ab326822 100644--- a/docs/spec/07-plugins/01-plugin-system.md+++ b/docs/spec/07-plugins/01-plugin-system.md@@ -538,6 +538,12 @@ Rules the control encodes:policy (edit or Test connection to retry), rather than repeatedly connectingon each call. Removed tools return `TOOL_NOT_FOUND`. Recovery never replays afailed `tools/call`, which may already have performed a mutation.+- Test connection uses the requested settings project, or the currently open+ project when no project is supplied. It retries that workspace and clears the+ same server's other idle failed workspace connections, so a successful test+ cannot leave later project sessions stuck on an earlier failure. Healthy+ connections in other projects, active tool calls, and ongoing handshakes are+ preserved. The returned test status describes the tested workspace.- Streamable HTTP `202 Accepted` acknowledgements for notifications and clientresponses are not JSON-RPC replies. Any acknowledgement body is discarded,diff --git a/scripts/e2e-composer-mcp.mjs b/scripts/e2e-composer-mcp.mjsindex 59a083297..3f7e13f73 100644--- a/scripts/e2e-composer-mcp.mjs+++ b/scripts/e2e-composer-mcp.mjs@@ -15,7 +15,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";import { createServer } from "node:http";import { tmpdir } from "node:os";import { join } from "node:path";-import { fileURLToPath } from "node:url";+import { fileURLToPath, pathToFileURL } from "node:url";import { AgentSidecar } from "../packages/host-runtime/dist/agent-sidecar.js";import { DEEPSEEK_MODELS } from "../packages/agent-runtime/node_modules/@earendil-works/pi-ai/dist/providers/deepseek.models.js";import { modelConfigFromPi } from "../packages/agent-runtime/dist/model-capabilities.js";@@ -100,7 +100,7 @@ try {launch: { command: process.execPath,args: [fileURLToPath(new URL("../packages/agent-runtime/dist/sidecar.js", import.meta.url))],cwd: workspace,- env: { ...process.env, NODE_OPTIONS: `--import=${fetchHook}`, PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_COMPACTION_STRATEGY: "fresh_window" },+ env: { ...process.env, NODE_OPTIONS: `--import=${pathToFileURL(fetchHook).href}`, PI_DESKTOP_PLAN_UI_PROBE: "1", PI_DESKTOP_COMPACTION_STRATEGY: "fresh_window" },},onStderr: (chunk) => { stderr += chunk; },});@@ -167,7 +167,11 @@ try {assert.equal((await detail()).messages.find(row=>row.id==="mcp-user").command,expansion.command);console.log("PASS: composer catalog → exact server selection → production sidecar → Host permission gate → real stdio MCP tools/call → provider follow-up");console.log("PASS: sixth selected tool executes without ToolSearch; server-only nonce reaches the model; original slash command persists");- } finally { await sidecar.dispose(); await writes; }+ } finally {+ await sidecar.dispose();+ await writes;+ await mcp.disposeAll();+ }}, resolveHostBinary(), root, PROTOCOL_VERSION);} finally {await mcp.disposeAll();