Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(procs): actually release PIDs on every explicit kill path

Quentin Schmick2c94a0939938
diff --git a/src/main/hiddenClaude.ts b/src/main/hiddenClaude.ts
index 06d75f78..74a85734 100644
--- a/src/main/hiddenClaude.ts
+++ b/src/main/hiddenClaude.ts
@@ -3,6 +3,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import { resolveCommand, userShellPath } from './shellEnv';
import { projectDir } from './transcript';
+import { ensureKilled } from './procKill';
/**
* Shared helper: run a HIDDEN interactive claude session (ephemeral PTY) and
@@ -150,7 +151,14 @@ export function runHiddenClaude(prompt: string, opts: HiddenClaudeOptions): Prom
let bootMaxTimer: NodeJS.Timeout;
let globalTimer: NodeJS.Timeout;
- const kill = () => { try { ptyProc.kill(); } catch { /* noop */ } };
+ // Hidden sessions are ephemeral CHECKS — nothing they spawn (MCP servers,
+ // helpers) may outlive them. Kill politely, then sweep the process group so
+ // every check releases its PIDs even if `claude` shrugs off the SIGHUP.
+ const kill = () => {
+ const pid = ptyProc.pid;
+ try { ptyProc.kill(); } catch { /* noop */ }
+ ensureKilled(pid);
+ };
const finish = (r: HiddenClaudeResult) => {
if (settled) return;
diff --git a/src/main/memory.ts b/src/main/memory.ts
index fef50fd7..008e680b 100644
--- a/src/main/memory.ts
+++ b/src/main/memory.ts
@@ -16,6 +16,7 @@
import { existsSync, statSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
+import { ensureKilled } from './procKill';
/** Non-memory files `mempalace mine` must not ingest: the Claude Code hooks
* config (a large JSON blob that swamps the wake-up digest), the cursor, and
@@ -54,6 +55,7 @@ export interface MemoryStatus {
}
const MINE_INTERVAL_MS = 180_000; // re-mine changed memories every 3 min
+const MINE_TIMEOUT_MS = 10 * 60_000; // hard cap per mine (first run downloads the embedding model)
export class MemoryManager {
private binCache: string | null | undefined;
@@ -214,38 +216,78 @@ export class MemoryManager {
});
let err = '';
proc.stderr?.on('data', (d) => { err += d.toString(); });
+ // Hard ceiling: a wedged mine used to hold its PID forever AND leave
+ // `mining` stuck true, silently stopping all future passes. Generous cap
+ // because the first run may lazily download the embedding model.
+ const timer = setTimeout(() => {
+ console.error(`[memory] mine ${id} timed out after ${MINE_TIMEOUT_MS / 60000}min — killing`);
+ try { proc.kill('SIGTERM'); } catch { /* gone */ }
+ ensureKilled(proc.pid); // SIGKILL sweep if SIGTERM is ignored
+ }, MINE_TIMEOUT_MS);
+ timer.unref?.();
proc.on('close', (code) => {
+ clearTimeout(timer);
if (code !== 0) {
console.error(`[memory] mine ${id} exited ${code}: ${err.slice(-300)}`);
this.lastMined.delete(id); // let the next tick retry
}
resolve();
});
- proc.on('error', () => { this.lastMined.delete(id); resolve(); });
+ proc.on('error', () => { clearTimeout(timer); this.lastMined.delete(id); resolve(); });
});
}
// — recall (read) —
+ /** Run one mempalace read command asynchronously. These used to be spawnSync
+ * with a 120s timeout — on a cold model load that BLOCKED the Electron main
+ * process (renderer IPC, timers, every window) for up to two minutes. Same
+ * contract, but the event loop keeps breathing and a wedged CLI is swept. */
+ private runCli(args: string[], label: string): Promise<{ ok: boolean; output: string; error?: string }> {
+ return new Promise((resolve) => {
+ const bin = this.bin();
+ if (!this.active() || !bin) { resolve({ ok: false, output: '', error: 'semantic memory not active' }); return; }
+ let proc: ReturnType<typeof spawn>;
+ try {
+ proc = spawn(bin, args, { env: this.childEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (e) {
+ resolve({ ok: false, output: '', error: e instanceof Error ? e.message : String(e) });
+ return;
+ }
+ let out = '', err = '';
+ let settled = false;
+ const settle = (r: { ok: boolean; output: string; error?: string }): void => {
+ if (!settled) { settled = true; clearTimeout(timer); resolve(r); }
+ };
+ proc.stdout?.setEncoding('utf8');
+ proc.stderr?.setEncoding('utf8');
+ proc.stdout?.on('data', (d: string) => { out += d; });
+ proc.stderr?.on('data', (d: string) => { err += d; });
+ const timer = setTimeout(() => {
+ try { proc.kill('SIGTERM'); } catch { /* gone */ }
+ ensureKilled(proc.pid);
+ settle({ ok: false, output: out, error: `${label} timed out` });
+ }, 120_000);
+ timer.unref?.();
+ proc.on('close', (code) => {
+ if (code !== 0) settle({ ok: false, output: out, error: (err || `${label} failed`).trim() });
+ else settle({ ok: true, output: out });
+ });
+ proc.on('error', (e) => settle({ ok: false, output: '', error: e.message }));
+ });
+ }
+
/** Semantic search across the shared palace. Returns the CLI's text output. */
- search(query: string, opts: { wing?: string; results?: number } = {}): { ok: boolean; output: string; error?: string } {
- const bin = this.bin();
- if (!this.active() || !bin) return { ok: false, output: '', error: 'semantic memory not active' };
+ search(query: string, opts: { wing?: string; results?: number } = {}): Promise<{ ok: boolean; output: string; error?: string }> {
const args = ['search', query, '--results', String(opts.results ?? 5)];
if (opts.wing) args.push('--wing', opts.wing);
- const res = spawnSync(bin, args, { env: this.childEnv(), encoding: 'utf8', timeout: 120_000, input: '' });
- if (res.status !== 0) return { ok: false, output: res.stdout ?? '', error: (res.stderr || 'search failed').trim() };
- return { ok: true, output: res.stdout ?? '' };
+ return this.runCli(args, 'search');
}
/** Session-start digest (~600-900 tokens). */
- wakeUp(wing?: string): { ok: boolean; output: string; error?: string } {
- const bin = this.bin();
- if (!this.active() || !bin) return { ok: false, output: '', error: 'semantic memory not active' };
+ wakeUp(wing?: string): Promise<{ ok: boolean; output: string; error?: string }> {
const args = ['wake-up'];
if (wing) args.push('--wing', wing);
- const res = spawnSync(bin, args, { env: this.childEnv(), encoding: 'utf8', timeout: 120_000, input: '' });
- if (res.status !== 0) return { ok: false, output: res.stdout ?? '', error: (res.stderr || 'wake-up failed').trim() };
- return { ok: true, output: res.stdout ?? '' };
+ return this.runCli(args, 'wake-up');
}
}
diff --git a/src/main/procKill.ts b/src/main/procKill.ts
new file mode 100644
index 00000000..9d84599c
--- /dev/null
+++ b/src/main/procKill.ts
@@ -0,0 +1,54 @@
+/**
+ * Process-tree termination helpers (PID-release hardening).
+ *
+ * Every explicit kill path used to be a bare node-pty `proc.kill()` — SIGHUP to
+ * the DIRECT child only. Two leaks follow: (1) a child that ignores/queues
+ * SIGHUP never dies, so its PID lingers for the machine's uptime; (2) even when
+ * the child dies, its own children (MCP servers, helper daemons the session
+ * started) are orphaned to PID 1 and never released. With the breaker/heartbeat
+ * spawning and killing sessions all day, PIDs accumulate steadily.
+ *
+ * The fix: the pty child is a session leader (forkpty does setsid), so its
+ * process GROUP covers its descendants — after a graceful kill, verify and then
+ * SIGKILL the whole group (POSIX) or `taskkill /T /F` the tree (Windows).
+ *
+ * Deliberate scope: callers apply this on EXPLICIT kills (breaker stop, archive,
+ * respawn, app quit, hidden check sessions) — never on a natural exit, where a
+ * daemon the agent intentionally left running (a dev server started via a Bash
+ * tool) must survive its parent session.
+ */
+import { spawnSync } from 'node:child_process';
+
+/** Grace between the polite signal and the SIGKILL escalation. */
+export const KILL_GRACE_MS = 4_000;
+
+/** Is the process still alive? Signal 0 probes without touching it. */
+export function isAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+/** Forcefully kill pid and its descendants NOW. Group-SIGKILL on POSIX (falls
+ * back to the single pid when the group id is gone); `taskkill /T /F` on
+ * Windows. Killing the group of an already-dead leader is exactly the
+ * orphan-reaping case: any surviving members still hold the group id. */
+export function hardKillTree(pid: number): void {
+ if (!Number.isInteger(pid) || pid <= 0) return;
+ if (process.platform === 'win32') {
+ try { spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 10_000 }); } catch { /* gone */ }
+ return;
+ }
+ try { process.kill(-pid, 'SIGKILL'); } catch {
+ try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }
+ }
+}
+
+/** After a graceful kill (node-pty's SIGHUP), make sure the PIDs actually get
+ * released: wait a short grace, then sweep the process tree. Runs even when
+ * the leader died promptly — the sweep is what reaps grandchildren the polite
+ * signal never reached. The timer is unref'd so it can never keep the app
+ * alive during quit. */
+export function ensureKilled(pid: number | undefined, graceMs = KILL_GRACE_MS): void {
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return;
+ const t = setTimeout(() => hardKillTree(pid), graceMs);
+ t.unref?.();
+}
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 278652d7..d8009208 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -2,6 +2,7 @@ import * as pty from 'node-pty';
import type { WebContents } from 'electron';
import { existsSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
+import { ensureKilled } from './procKill';
interface PtySession {
id: string;
@@ -99,7 +100,14 @@ export class PtyManager {
* terminals don't linger as orphaned processes writing to a dead webContents. */
killByOwner(wc: WebContents): void {
for (const [id, s] of [...this.sessions.entries()]) {
- if (s.owner === wc) { try { s.proc.kill(); } catch { /* already gone */ } void id; }
+ if (s.owner === wc) {
+ try {
+ const pid = s.proc.pid;
+ s.proc.kill();
+ ensureKilled(pid);
+ } catch { /* already gone */ }
+ void id;
+ }
}
}
@@ -346,7 +354,9 @@ export class PtyManager {
const s = this.sessions.get(id);
if (!s) return { ok: false, error: `no pty: ${id}` };
try {
+ const pid = s.proc.pid;
s.proc.kill();
+ ensureKilled(pid); // verify + sweep the process group so no PID leaks
this.sessions.delete(id);
return { ok: true };
} catch (e) {
@@ -383,7 +393,11 @@ export class PtyManager {
killAll() {
this.exitHandler = null;
for (const s of this.sessions.values()) {
- try { s.proc.kill(); } catch { /* noop */ }
+ try {
+ const pid = s.proc.pid;
+ s.proc.kill();
+ ensureKilled(pid);
+ } catch { /* noop */ }
}
this.sessions.clear();
}
diff --git a/test/proc-kill.test.cjs b/test/proc-kill.test.cjs
new file mode 100644
index 00000000..76cde113
--- /dev/null
+++ b/test/proc-kill.test.cjs
@@ -0,0 +1,104 @@
+'use strict';
+/**
+ * procKill tests — prove the PID-release hardening works on a REAL process
+ * tree. Self-contained, no framework — run with `node test/proc-kill.test.cjs`
+ * (mirrors test/breaker.test.cjs). POSIX-only assertions (the Windows path is
+ * `taskkill /T /F`, exercised in CI on a Windows runner if ever added); on
+ * win32 this file exits 0 after a smoke import.
+ *
+ * Scenario mirroring the leak: a session leader that IGNORES SIGHUP (like a
+ * wedged TUI) with a live child of its own. A bare pty kill() leaves both
+ * running forever; ensureKilled() must reap the whole group.
+ */
+
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const ts = require('typescript');
+const { spawn, execFileSync } = require('node:child_process');
+
+const SRC = path.join(__dirname, '..', 'src', 'main', 'procKill.ts');
+const out = fs.mkdtempSync(path.join(os.tmpdir(), 'prockill-'));
+const js = ts.transpileModule(fs.readFileSync(SRC, 'utf8'), {
+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }
+}).outputText;
+fs.writeFileSync(path.join(out, 'procKill.js'), js, 'utf8');
+const { isAlive, hardKillTree, ensureKilled } = require(path.join(out, 'procKill.js'));
+
+if (process.platform === 'win32') {
+ console.log(' ok (win32: smoke import only — POSIX group semantics not applicable)');
+ process.exit(0);
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/** Live pids in process group `pgid` (empty when the group is gone). */
+function groupPids(pgid) {
+ try {
+ return execFileSync('pgrep', ['-g', String(pgid)], { encoding: 'utf8' })
+ .split('\n').map((s) => s.trim()).filter(Boolean).map(Number);
+ } catch { return []; } // pgrep exits 1 when no match
+}
+
+/** Spawn a detached (own-process-group) leader that traps HUP, with a child. */
+function spawnStubbornTree() {
+ const proc = spawn('sh', ['-c', 'trap "" HUP; sleep 60 & wait'], { detached: true, stdio: 'ignore' });
+ proc.unref();
+ return proc.pid;
+}
+
+let failures = 0;
+async function test(name, fn) {
+ try { await fn(); console.log(` ok ${name}`); }
+ catch (e) { failures++; console.error(`FAIL ${name}\n ${e.message}`); }
+}
+
+(async () => {
+ await test('isAlive: true for a live process, false after it dies', async () => {
+ const pid = spawnStubbornTree();
+ await sleep(200);
+ assert.ok(isAlive(pid), 'leader should be alive');
+ hardKillTree(pid);
+ await sleep(200);
+ assert.ok(!isAlive(pid), 'leader should be dead after hardKillTree');
+ });
+
+ await test('hardKillTree reaps the WHOLE group, not just the leader', async () => {
+ const pid = spawnStubbornTree();
+ await sleep(300);
+ const before = groupPids(pid);
+ assert.ok(before.length >= 2, `expected leader+child in group, saw: ${before.join(',')}`);
+ hardKillTree(pid);
+ await sleep(300);
+ assert.deepEqual(groupPids(pid), [], 'group should be empty');
+ });
+
+ await test('SIGHUP alone does NOT kill the stubborn leader (the leak)', async () => {
+ const pid = spawnStubbornTree();
+ await sleep(200);
+ try { process.kill(pid, 'SIGHUP'); } catch { /* noop */ }
+ await sleep(300);
+ assert.ok(isAlive(pid), 'a HUP-trapping leader survives a bare SIGHUP — this is the leaked-PID case');
+ hardKillTree(pid); // cleanup
+ });
+
+ await test('ensureKilled escalates after the grace and releases every PID', async () => {
+ const pid = spawnStubbornTree();
+ await sleep(200);
+ try { process.kill(pid, 'SIGHUP'); } catch { /* noop */ } // the polite kill that gets ignored
+ ensureKilled(pid, 400);
+ await sleep(1200);
+ assert.ok(!isAlive(pid), 'leader must be gone after escalation');
+ assert.deepEqual(groupPids(pid), [], 'no survivors in the group');
+ });
+
+ await test('ensureKilled tolerates bad pids', async () => {
+ ensureKilled(undefined);
+ ensureKilled(-5);
+ ensureKilled(0);
+ ensureKilled(1.5);
+ });
+
+ process.exit(failures ? 1 : 0);
+})();