AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(desktop): await ACP process closure before workspace cleanup
tianma-if3eaad7150927
diff --git a/.github/workflows/acp-cleanup.yml b/.github/workflows/acp-cleanup.ymlnew file mode 100644index 00000000..5c6b140c--- /dev/null+++ b/.github/workflows/acp-cleanup.yml@@ -0,0 +1,47 @@+name: Test ACP cleanup++on:+ workflow_dispatch:+ pull_request:+ paths:+ - "apps/desktop/src/main/acp-*.mjs"+ - "apps/desktop/src/main/child-process-start.mjs"+ - "scripts/verify-codex-acp-cleanup.mjs"+ - ".github/workflows/acp-cleanup.yml"+ - "package.json"+ - "bun.lock"+ push:+ branches: [main]+ paths:+ - "apps/desktop/src/main/acp-*.mjs"+ - "apps/desktop/src/main/child-process-start.mjs"+ - "scripts/verify-codex-acp-cleanup.mjs"+ - ".github/workflows/acp-cleanup.yml"+ - "package.json"+ - "bun.lock"++permissions:+ contents: read++jobs:+ cleanup:+ if: github.repository == 'tianma-if/edgeever'+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest]+ runs-on: ${{ matrix.os }}+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v5+ - uses: oven-sh/setup-bun@v2+ - uses: actions/setup-node@v4+ with:+ node-version: "24"+ - run: bun install --frozen-lockfile+ - name: Test process closure and Windows cwd locks+ run: bun test --cwd apps/desktop src/main/acp-cleanup.test.mjs+ - name: Install official Codex ACP fixture+ run: npm install --prefix "${{ runner.temp }}/edgeever-codex-acp" --ignore-scripts --no-audit --no-fund --package-lock=false @agentclientprotocol/[email protected]+ - name: Verify official Codex ACP process cleanup+ run: node scripts/verify-codex-acp-cleanup.mjs "${{ runner.temp }}/edgeever-codex-acp/node_modules/@agentclientprotocol/codex-acp/dist/index.js"diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.ymlindex f02f489d..5182efff 100644--- a/.github/workflows/desktop-build.yml+++ b/.github/workflows/desktop-build.yml@@ -457,6 +457,9 @@ jobs:Start-Sleep -Seconds (15 * $attempt)}+ - name: Test ACP process and workspace cleanup+ run: bun test --cwd apps/desktop src/main/acp-cleanup.test.mjs+- name: Build Web rendererenv:EDGE_EVER_DESKTOP_BUILD: "1"diff --git a/apps/desktop/src/main/acp-cleanup.test.mjs b/apps/desktop/src/main/acp-cleanup.test.mjsnew file mode 100644index 00000000..68862657--- /dev/null+++ b/apps/desktop/src/main/acp-cleanup.test.mjs@@ -0,0 +1,170 @@+import { describe, expect, test } from "bun:test";+import { execFile, spawn } from "node:child_process";+import { EventEmitter } from "node:events";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { promisify } from "node:util";+import { createAcpHostRuntime, removeAcpWorkspace, stopAcpChild } from "./acp-host.mjs";++describe("ACP process and workspace cleanup", () => {+ test("waits for process closure and shares repeated stop requests", async () => {+ const child = new EventEmitter();+ const signals = [];+ child.kill = (signal) => { signals.push(signal); };+ const stopped = stopAcpChild(child);+ expect(stopAcpChild(child)).toBe(stopped);+ let resolved = false;+ void stopped.then(() => { resolved = true; });+ await Promise.resolve();+ expect(resolved).toBe(false);+ child.signalCode = "SIGTERM";+ child.emit("exit", null, "SIGTERM");+ await Promise.resolve();+ expect(resolved).toBe(false);+ child.emit("close", null, "SIGTERM");+ await stopped;+ expect(signals).toEqual(["SIGTERM"]);+ expect(child.listenerCount("close")).toBe(0);+ });++ test("waits when stopped after exit while a real descendant retains stdout", async () => {+ // Use Node, matching Electron, rather than Bun's different child-pipe lifecycle.+ const source = `+ import assert from "node:assert/strict";+ import { spawn } from "node:child_process";+ import { once } from "node:events";+ import { spawnAcpChild, stopAcpChild } from ${JSON.stringify(new URL("./acp-host.mjs", import.meta.url).href)};+ const parent = await spawnAcpChild(spawn, {+ command: process.execPath,+ args: ["-e", \`const { spawn } = require("node:child_process");+ const descendant = spawn(process.execPath, ["-e", "setTimeout(() => {}, 1000)"], {+ stdio: ["ignore", process.stdout, "ignore"], windowsHide: true,+ });+ descendant.once("spawn", () => process.exit(0));\`],+ }, process.cwd());+ let closed = false;+ parent.once("close", () => { closed = true; });+ await once(parent, "exit");+ assert.equal(closed, false);+ const stopped = stopAcpChild(parent);+ assert.equal(stopAcpChild(parent), stopped);+ let resolved = false;+ stopped.then(() => { resolved = true; });+ await new Promise(resolve => setTimeout(resolve, 50));+ assert.equal(resolved, false);+ await stopped;+ assert.equal(closed, true);+ assert.equal(stopAcpChild(parent), stopped);+ // Also cover a process that has closed before stop is first requested.+ const finished = await spawnAcpChild(spawn, { command: process.execPath, args: ["-e", ""] }, process.cwd());+ await once(finished, "close");+ await Promise.race([+ stopAcpChild(finished),+ new Promise((_, reject) => { const timer = setTimeout(() => reject(new Error("already closed child was awaited")), 100); timer.unref(); }),+ ]);+ `;+ await promisify(execFile)("node", ["--input-type=module", "-e", source], { windowsHide: true, timeout: 10_000 });+ });++ for (const exited of [{ exitCode: 0 }, { signalCode: "SIGTERM" }]) {+ test(`waits for close after ${Object.keys(exited)[0]} is set without signalling the exited process`, async () => {+ const child = Object.assign(new EventEmitter(), exited);+ let signals = 0;+ child.kill = () => { signals += 1; };+ let resolved = false;+ const stopped = stopAcpChild(child);+ void stopped.then(() => { resolved = true; });+ await Promise.resolve();+ expect(resolved).toBe(false);+ child.emit("close");+ await stopped;+ expect(child.listenerCount("close")).toBe(0);+ expect(signals).toBe(0);+ });+ }++ test("bounds shutdown when a child ignores termination", async () => {+ const child = new EventEmitter();+ const signals = [];+ child.kill = (signal) => { signals.push(signal); };+ await stopAcpChild(child);+ expect(signals).toEqual(["SIGTERM", "SIGKILL"]);+ expect(child.listenerCount("close")).toBe(0);+ });++ test.skipIf(process.platform !== "win32")("retries a real Windows cwd lock until the process releases it", async () => {+ // Electron uses Node's fs.rm implementation. Bun currently ignores its+ // maxRetries option, so exercise the native lock with Node rather than Bun.+ const source = `+ import assert from "node:assert/strict";+ import { spawn } from "node:child_process";+ import { once } from "node:events";+ import { existsSync } from "node:fs";+ import { mkdtemp, rm } from "node:fs/promises";+ import { tmpdir } from "node:os";+ import path from "node:path";+ import { removeAcpWorkspace, stopAcpChild } from ${JSON.stringify(new URL("./acp-host.mjs", import.meta.url).href)};+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-lock-"));+ const child = spawn(process.execPath, ["-e", 'process.stdout.write("ready"); process.stdin.resume()'], {+ cwd: directory, stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false,+ });+ try {+ await once(child.stdout, "data");+ await assert.rejects(rm(directory, { recursive: true, force: true }), { code: "EBUSY" });+ const release = setTimeout(() => { void stopAcpChild(child); }, 150);+ try { await removeAcpWorkspace(directory); } finally { clearTimeout(release); }+ assert.equal(existsSync(directory), false);+ } finally {+ await stopAcpChild(child);+ await removeAcpWorkspace(directory);+ }+ `;+ await promisify(execFile)("node", ["--input-type=module", "-e", source], { windowsHide: true, timeout: 10_000 });+ });++ for (const { needsLogin, connectionFails = false, cleanupFails = false } of [+ { needsLogin: false }, { needsLogin: false, cleanupFails: true }, { needsLogin: true }, { needsLogin: true, cleanupFails: true },+ { needsLogin: false, connectionFails: true, cleanupFails: true },+ ]) {+ test(`closes a real ACP process before cleanup (${connectionFails ? "connection failure" : needsLogin ? "login required" : "connected"}${cleanupFails ? ", cleanup failure preserves probe status" : ""})`, async () => {+ const directory = await mkdtemp(path.join(tmpdir(), "edgeever-acp-lifecycle-"));+ const script = path.join(directory, "agent.mjs");+ await writeFile(script, `+ import { createInterface } from "node:readline";+ createInterface({ input: process.stdin }).on("line", (line) => {+ const request = JSON.parse(line);+ const result = request.method === "initialize"+ ? { protocolVersion: 1, agentCapabilities: {}, authMethods: [{ id: "login", name: "Log in" }] }+ : { sessionId: "test-session" };+ const response = ${needsLogin || connectionFails} && request.method === "session/new"+ ? { error: { code: ${connectionFails ? -32603 : -32000}, message: ${JSON.stringify(connectionFails ? "transport broken" : "Authentication required")} } }+ : { result };+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, ...response }) + "\\n");+ });+ `);+ let child;+ let cleaned = false;+ let closed = false;+ const runtime = createAcpHostRuntime({+ adapterManager: { get: () => ({ version: "2.2.1", command: { command: process.execPath, args: [script] } }) },+ spawnImpl: (...args) => { child = spawn(...args); child.once("close", () => { closed = true; }); return child; },+ rm: async (cwd, options) => {+ expect(closed).toBe(true);+ await rm(cwd, options);+ cleaned = true;+ if (cleanupFails) throw Object.assign(new Error("workspace still locked"), { code: "EBUSY" });+ },+ });+ try {+ const result = await runtime.probeAdapter({ id: "codex" });+ expect(result.state).toBe(connectionFails ? "failed" : needsLogin ? "needs_login" : "available");+ if (connectionFails) expect(result.detail).toContain("transport broken");+ expect(cleaned).toBe(true);+ } finally {+ await stopAcpChild(child);+ await removeAcpWorkspace(directory);+ }+ }, 15_000);+ }+});diff --git a/apps/desktop/src/main/acp-host.mjs b/apps/desktop/src/main/acp-host.mjsindex c529e493..89b1795c 100644--- a/apps/desktop/src/main/acp-host.mjs+++ b/apps/desktop/src/main/acp-host.mjs@@ -34,6 +34,8 @@ const WORKSPACE_MARKER = `${path.sep}edgeever-acp-`;const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);const liveChildren = new Set();+const closedChildren = new WeakSet();+const stoppingChildren = new WeakMap();let exitHooked = false;const clientVersion = () => {@@ -48,6 +50,7 @@ const clientVersion = () => {const trackChild = (child) => {if (!child) return;liveChildren.add(child);+ child.once?.("close", () => closedChildren.add(child));child.once?.("exit", () => liveChildren.delete(child));if (!exitHooked) {exitHooked = true;@@ -611,7 +614,7 @@ export async function removeAcpWorkspace(directory, rmImpl = rm) {if (typeof directory !== "string" || !directory) return;const resolved = path.resolve(directory);if (resolved === path.resolve(homedir()) || !resolved.includes(WORKSPACE_MARKER)) return;- await rmImpl(resolved, { recursive: true, force: true });+ await rmImpl(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });}const normalizePromptCapabilities = (initialized) => {@@ -670,17 +673,34 @@ const createEdgeEverAcpClient = (requestId, emit, allowPermissions, onAuthStatus},});-function stopChild(child) {- if (!child) return;+// exit only describes the direct process; inherited pipes can remain open until close.+export function stopAcpChild(child) {+ if (!child) return Promise.resolve();+ if (stoppingChildren.has(child)) return stoppingChildren.get(child);+ if (closedChildren.has(child)) return Promise.resolve();+ let finish;+ const stopped = new Promise((resolve) => { finish = resolve; });+ stoppingChildren.set(child, stopped);+ const onClose = () => { closedChildren.add(child); settle(); };+ const settle = () => {+ clearTimeout(killTimer);+ clearTimeout(deadline);+ child.off("close", onClose);+ finish();+ };const killTimer = setTimeout(() => {- if (child.exitCode == null) {+ if (child.exitCode == null && child.signalCode == null) {try { child.kill("SIGKILL"); } catch { /* already gone */ }}}, 500);- killTimer.unref?.();- child.once?.("exit", () => clearTimeout(killTimer));+ // Descendants may retain inherited pipes. Bound the wait and let fs.rm retry locks.+ const deadline = setTimeout(settle, 2_000);+ child.once("close", onClose);try { child.stdin?.destroy(); } catch { /* closed */ }- try { child.kill("SIGTERM"); } catch { /* already gone */ }+ if (child.exitCode == null && child.signalCode == null) {+ try { child.kill("SIGTERM"); } catch { /* already gone */ }+ }+ return stopped;}const promptFailureMessage = (failure) => {@@ -705,6 +725,10 @@ export function createAcpHostRuntime(options = {}) {const spawnImpl = options.spawnImpl ?? nodeSpawn;const mkdtempImpl = options.mkdtemp ?? mkdtemp;const rmImpl = options.rm ?? rm;+ // Workspace cleanup must not replace a successful handshake or its original failure.+ const cleanupWorkspace = (directory) => removeAcpWorkspace(directory, rmImpl).catch((error) => {+ console.warn("ACP workspace cleanup failed:", sanitizeFailureDetail(error));+ });const version = options.clientVersion ?? clientVersion();const handshakeTimeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;const authenticationTimeoutMs = options.authenticationTimeoutMs ?? 5 * 60_000;@@ -752,7 +776,7 @@ export function createAcpHostRuntime(options = {}) {resolveAuthStatus();if (connected && status.kind === "none") abort();};- const abort = () => stopChild(child);+ const abort = () => stopAcpChild(child);signal?.addEventListener("abort", abort, { once: true });try {if (signal?.aborted) throw Object.assign(new Error("connection_timeout"), { code: "TIMEOUT" });@@ -848,8 +872,8 @@ export function createAcpHostRuntime(options = {}) {const failure = authStatusKind === "none" && !authenticationPending ? RequestError.authRequired() : error;if (authMethods.length && failure && typeof failure === "object") failure.authMethods = authMethods;if (authenticationPending && failure && typeof failure === "object") failure.authenticationPending = true;- abort();- await removeAcpWorkspace(cwd, rmImpl);+ await abort();+ await cleanupWorkspace(cwd);throw failure;} finally {signal?.removeEventListener("abort", abort);@@ -901,8 +925,8 @@ export function createAcpHostRuntime(options = {}) {return { ...adapterShell(id), ...failureFields(classifyAcpFailure(error)), ...(isAuthRequiredError(error) ? { authMethods: error.authMethods ?? [] } : {}) };} finally {if (connected) {- connected.stop();- await removeAcpWorkspace(connected.cwd, rmImpl);+ await connected.stop();+ await cleanupWorkspace(connected.cwd);}}}, { updateOnly });@@ -975,8 +999,8 @@ export function createAcpHostRuntime(options = {}) {...(resolved.version ? { version: resolved.version, managed: true } : {}),};latestStatus.set(id, adapter);- connected.stop();- await removeAcpWorkspace(connected.cwd, rmImpl);+ await connected.stop();+ await cleanupWorkspace(connected.cwd);return adapter;},@@ -993,8 +1017,8 @@ export function createAcpHostRuntime(options = {}) {return connect(workBuddyAuth?.command ?? resolved.command, `auth-${id}`, () => {}, signal, input.methodId, [], false, workBuddyAuth);}, authenticationTimeoutMs);if (id === "workbuddyCn" || id === "workbuddyIntl") {- connected.stop();- await removeAcpWorkspace(connected.cwd, rmImpl);+ await connected.stop();+ await cleanupWorkspace(connected.cwd);connected = null;// Login is useful only if a fresh chat process can restore credentials.connected = await withHandshakeTimeout((signal) => connect(resolved.command, `auth-check-${id}`, () => {}, signal, undefined, [], false, null, true));@@ -1014,8 +1038,8 @@ export function createAcpHostRuntime(options = {}) {return adapter;} finally {if (connected) {- connected.stop();- await removeAcpWorkspace(connected.cwd, rmImpl);+ await connected.stop();+ await cleanupWorkspace(connected.cwd);}}},@@ -1086,8 +1110,8 @@ export function createAcpHostRuntime(options = {}) {});}} catch (error) {- connected.stop();- await removeAcpWorkspace(connected.cwd, rmImpl);+ await connected.stop();+ await cleanupWorkspace(connected.cwd);await mcpBridge?.close();return fail(promptFailureMessage(classifyAcpFailure(error)));}@@ -1103,9 +1127,8 @@ export function createAcpHostRuntime(options = {}) {if (session.settled) return;session.settled = true;notify(event);- session.stop();active.delete(requestId);- void removeAcpWorkspace(session.cwd, rmImpl);+ void session.stop().then(() => cleanupWorkspace(session.cwd));void session.mcpBridge?.close();};void connected.connection.prompt({ sessionId: connected.sessionId, prompt: content.blocks }).then((result) => {@@ -1137,7 +1160,7 @@ export function createAcpHostRuntime(options = {}) {} catch {// The process may already be gone. Killing it is enough.}- session.stop();+ await session.stop();void session.mcpBridge?.close();return { ok: true };},diff --git a/scripts/verify-codex-acp-cleanup.mjs b/scripts/verify-codex-acp-cleanup.mjsnew file mode 100644index 00000000..9d2b08b1--- /dev/null+++ b/scripts/verify-codex-acp-cleanup.mjs@@ -0,0 +1,100 @@+// Run with Node (Electron's runtime) and an installed official codex-acp entry point.+import assert from "node:assert/strict";+import { execFileSync, spawn } from "node:child_process";+import { existsSync } from "node:fs";+import { mkdir, mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { createAcpHostRuntime, stopAcpChild } from "../apps/desktop/src/main/acp-host.mjs";++const entry = path.resolve(process.argv[2] ?? "");+assert.ok(process.argv[2] && existsSync(entry), "Pass the installed codex-acp dist/index.js");+const root = await mkdtemp(path.join(tmpdir(), "edgeever-acp-codex-smoke-"));+const home = path.join(root, "home");+await mkdir(home);+let child;+let closed = false;+let workspace;+let cleaned = false;++// Capture process IDs only, never command lines (which may contain credentials).+const processTree = (parentPid) => {+ const rows = process.platform === "win32"+ ? JSON.parse(execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command",+ "ConvertTo-Json -Compress -InputObject @(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId)",+ ], { encoding: "utf8", windowsHide: true, timeout: 10_000 })).map((row) => [row.ProcessId, row.ParentProcessId])+ : execFileSync("ps", ["-axo", "pid=,ppid="], { encoding: "utf8", timeout: 10_000 })+ .trim().split("\n").map((line) => line.trim().split(/\s+/).map(Number));+ const descendants = new Set([parentPid]);+ let count;+ do {+ count = descendants.size;+ for (const [pid, ppid] of rows) if (descendants.has(ppid)) descendants.add(pid);+ } while (count !== descendants.size);+ descendants.delete(parentPid);+ return [...descendants];+};+let descendants;+let snapshotError;+const runtime = createAcpHostRuntime({+ tmpRoot: root,+ handshakeTimeoutMs: 30_000,+ adapterManager: { get: () => ({ command: {+ command: process.execPath,+ args: [entry],+ env: { HOME: home, USERPROFILE: home, CODEX_HOME: home },+ unsetEnv: Object.keys(process.env).filter((key) => /API_KEY|TOKEN|SECRET|PASSWORD|AUTHORIZATION/i.test(key)),+ } }) },+ spawnImpl: (...args) => {+ child = spawn(...args);+ child.once("close", () => { closed = true; });+ let output = "";+ child.stdout.on("data", (chunk) => {+ if (descendants || snapshotError) return;+ output += chunk;+ const lines = output.split("\n");+ output = lines.pop();+ for (const line of lines) {+ let message;+ try { message = JSON.parse(line); } catch { continue; }+ if (message.result?.protocolVersion == null) continue;+ try { descendants = processTree(child.pid); } catch (error) { snapshotError = error; }+ }+ });+ return child;+ },+ rm: async (directory, options) => {+ workspace = directory;+ assert.equal(closed, true, "Codex ACP must close before workspace cleanup");+ await rm(directory, options);+ cleaned = true;+ },+});+try {+ const result = await runtime.probeAdapter({ id: "codex" });+ assert.ok(["available", "needs_login"].includes(result.state), JSON.stringify(result));+ assert.ok(child?.pid, "The official adapter must actually start");+ assert.ifError(snapshotError);+ assert.ok(descendants?.length > 0, "Initialization must start the real Codex descendant process chain");+ assert.equal(closed, true);+ assert.equal(cleaned, true);+ assert.equal(existsSync(workspace), false);+ const alive = (pid) => {+ try { process.kill(pid, 0); return true; } catch (error) {+ if (error.code === "ESRCH") return false;+ throw error;+ }+ };+ const deadline = Date.now() + 5_000;+ while (descendants.some(alive) && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ assert.deepEqual(descendants.filter(alive), [], "Codex descendants must exit too");+ console.log(`Official Codex ACP probe: ${result.state}; process chain closed and workspace removed.`);+} finally {+ await stopAcpChild(child);+ for (const pid of descendants ?? []) {+ try { process.kill(pid, "SIGKILL"); } catch { /* already gone */ }+ }+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+}