Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(sidecars): reap children on quit and on next launch (#683) (#694)

Gabriel Steinc18139e96b09
diff --git a/CLAUDE.md b/CLAUDE.md
index db09ae384..c71bb1270 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -560,7 +560,7 @@ const { t } = useTranslation();
3. **New UI Component**: Follow shadcn/ui patterns in src/components/ui
4. **New Manager**: Create in src/helpers/, initialize in main.js
5. **New UI Strings**: Add translation keys to all 10 language files (see i18n section above)
-6. **New Sidecar Binary**: Add download script in `scripts/`, add to `prebuild*` scripts in package.json, add manager in `src/helpers/`, initialize in `main.js`, shutdown in `will-quit` handler
+6. **New Sidecar Binary**: Add download script in `scripts/`, add to `prebuild*` scripts in package.json, add manager in `src/helpers/`, initialize in `main.js`. Spawn the child with `detached: process.platform !== "win32"` so it has its own process group on Unix. Right after spawn call `sidecarPidFile.write(name, child.pid)` and on `close` call `sidecarPidFile.clear(name)`. Add the binary fragment to `EXPECTED_BINARY_FRAGMENTS` in `sidecarReaper.js`. Register a stop function via `sidecarRegistry.register(name, () => manager.stop())` in `registerSidecars()` — that single registration replaces the old `will-quit` line.
### Testing Checklist
diff --git a/main.js b/main.js
index 2676e28d8..7bf728749 100644
--- a/main.js
+++ b/main.js
@@ -263,6 +263,8 @@ const MeetingAecManager = require("./src/helpers/meetingAecManager");
const MeetingDetectionEngine = require("./src/helpers/meetingDetectionEngine");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
const { ensureYdotool } = require("./src/helpers/ensureYdotool");
+const sidecarRegistry = require("./src/helpers/sidecarRegistry");
+const { reapStaleSidecars } = require("./src/helpers/sidecarReaper");
// Manager instances - initialized after app.whenReady()
let debugLogger = null;
@@ -396,6 +398,18 @@ function initializeCoreManagers() {
});
}
+function registerSidecars() {
+ if (whisperManager) sidecarRegistry.register("whisper", () => whisperManager.stopServer());
+ if (parakeetManager) sidecarRegistry.register("parakeet", () => parakeetManager.stopServer());
+ if (diarizationManager) {
+ sidecarRegistry.register("diarization", () => diarizationManager.shutdown());
+ }
+ const modelManager = require("./src/helpers/modelManagerBridge").default;
+ sidecarRegistry.register("llama", () => modelManager.stopServer());
+ const onnxWorkerClient = require("./src/helpers/onnxWorkerClient");
+ sidecarRegistry.register("onnx", () => onnxWorkerClient.stop());
+}
+
// Phase 2: Non-critical setup after windows are visible
function initializeDeferredManagers() {
ensureYdotool().catch((err) => {
@@ -611,8 +625,11 @@ function startAuthBridgeServer() {
// Main application startup
async function startApp() {
+ reapStaleSidecars();
+
// Phase 1: Core managers + IPC handlers before windows
initializeCoreManagers();
+ registerSidecars();
startAuthBridgeServer();
cliBridge = new CliBridge(ipcHandlers);
@@ -810,6 +827,7 @@ async function startApp() {
const QdrantManager = require("./src/helpers/qdrantManager");
qdrantManager = new QdrantManager();
+ sidecarRegistry.register("qdrant", () => qdrantManager.stop());
if (qdrantManager.isAvailable()) {
qdrantManager
.start()
@@ -1367,77 +1385,45 @@ if (gotSingleInstanceLock) {
}
});
- app.on("will-quit", () => {
- if (authBridgeServer) {
- authBridgeServer.close();
- authBridgeServer = null;
- }
- if (cliBridge) {
- cliBridge.stop().catch(() => {});
- cliBridge = null;
- }
- if (windowManager && isLiveWindow(windowManager.agentWindow)) {
- windowManager.agentWindow.destroy();
- }
- if (windowManager && isLiveWindow(windowManager.transcriptionPreviewWindow)) {
- windowManager.transcriptionPreviewWindow.destroy();
- }
- if (hotkeyManager) {
- hotkeyManager.unregisterAll();
- } else {
- globalShortcut.unregisterAll();
- }
- if (globeKeyManager) {
- globeKeyManager.stop();
- }
- if (windowsKeyManager) {
- windowsKeyManager.stop();
- }
- if (linuxKeyManager) {
- linuxKeyManager.stop();
- }
- if (meetingDetectionEngine) {
- meetingDetectionEngine.stop();
- }
- if (googleCalendarManager) {
- googleCalendarManager.stop();
- }
- if (audioTapManager) {
- audioTapManager.stop().catch(() => {});
- }
- if (linuxPortalAudioManager) {
- linuxPortalAudioManager.stop().catch(() => {});
- }
- if (meetingAecManager) {
- meetingAecManager.stop().catch(() => {});
- }
- if (ipcHandlers) {
- ipcHandlers._cleanupTextEditMonitor();
- }
- if (textEditMonitor) {
- textEditMonitor.stopMonitoring();
- }
- if (updateManager) {
- updateManager.cleanup();
- }
- // Stop whisper server if running
- if (whisperManager) {
- whisperManager.stopServer().catch(() => {});
- }
- // Stop parakeet WS server if running
- if (parakeetManager) {
- parakeetManager.stopServer().catch(() => {});
- }
- if (diarizationManager) {
- diarizationManager.shutdown().catch(() => {});
- }
- // Stop llama-server if running
- const modelManager = require("./src/helpers/modelManagerBridge").default;
- modelManager.stopServer().catch(() => {});
- if (qdrantManager) {
- qdrantManager.stop().catch(() => {});
- }
- const onnxWorkerClient = require("./src/helpers/onnxWorkerClient");
- onnxWorkerClient.stop().catch(() => {});
+ let isShuttingDown = false;
+ app.on("before-quit", (event) => {
+ if (isShuttingDown) return;
+ isShuttingDown = true;
+ event.preventDefault();
+ performSyncTeardown();
+ sidecarRegistry.shutdownAll().finally(() => app.exit(0));
});
}
+
+function performSyncTeardown() {
+ if (authBridgeServer) {
+ authBridgeServer.close();
+ authBridgeServer = null;
+ }
+ if (cliBridge) {
+ cliBridge.stop().catch(() => {});
+ cliBridge = null;
+ }
+ if (windowManager && isLiveWindow(windowManager.agentWindow)) {
+ windowManager.agentWindow.destroy();
+ }
+ if (windowManager && isLiveWindow(windowManager.transcriptionPreviewWindow)) {
+ windowManager.transcriptionPreviewWindow.destroy();
+ }
+ if (hotkeyManager) {
+ hotkeyManager.unregisterAll();
+ } else {
+ globalShortcut.unregisterAll();
+ }
+ if (globeKeyManager) globeKeyManager.stop();
+ if (windowsKeyManager) windowsKeyManager.stop();
+ if (linuxKeyManager) linuxKeyManager.stop();
+ if (meetingDetectionEngine) meetingDetectionEngine.stop();
+ if (googleCalendarManager) googleCalendarManager.stop();
+ if (audioTapManager) audioTapManager.stop().catch(() => {});
+ if (linuxPortalAudioManager) linuxPortalAudioManager.stop().catch(() => {});
+ if (meetingAecManager) meetingAecManager.stop().catch(() => {});
+ if (ipcHandlers) ipcHandlers._cleanupTextEditMonitor();
+ if (textEditMonitor) textEditMonitor.stopMonitoring();
+ if (updateManager) updateManager.cleanup();
+}
diff --git a/src/helpers/diarization.js b/src/helpers/diarization.js
index 55facd02f..5d962f248 100644
--- a/src/helpers/diarization.js
+++ b/src/helpers/diarization.js
@@ -9,6 +9,7 @@ const { getModelsDirForService } = require("./modelDirUtils");
const { convertToWav } = require("./ffmpegUtils");
const { getSafeTempDir } = require("./safeTempDir");
const { applyProvisionalSpeaker, applyConfirmedSpeaker } = require("./speakerAssignmentPolicy");
+const sidecarPidFile = require("./sidecarPidFile");
const {
transcriptsOverlap,
transcriptsLooselyOverlap,
@@ -348,9 +349,11 @@ class DiarizationManager {
const proc = spawn(binaryPath, args, {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
+ detached: process.platform !== "win32",
});
this._process = proc;
+ sidecarPidFile.write("diarization", proc.pid);
const timeout = setTimeout(() => {
debugLogger.warn("Diarization timed out", { timeoutMs: DIARIZATION_TIMEOUT_MS });
@@ -370,6 +373,7 @@ class DiarizationManager {
proc.on("close", (code) => {
clearTimeout(timeout);
this._process = null;
+ sidecarPidFile.clear("diarization");
if (code !== 0) {
debugLogger.warn("Diarization process exited with error", {
@@ -388,6 +392,7 @@ class DiarizationManager {
proc.on("error", (err) => {
clearTimeout(timeout);
this._process = null;
+ sidecarPidFile.clear("diarization");
debugLogger.warn("Diarization process error", { error: err.message });
resolve([]);
});
diff --git a/src/helpers/llamaServer.js b/src/helpers/llamaServer.js
index a8751fc60..755e29153 100644
--- a/src/helpers/llamaServer.js
+++ b/src/helpers/llamaServer.js
@@ -7,6 +7,7 @@ const debugLogger = require("./debugLogger");
const { killProcess } = require("../utils/process");
const { getSafeTempDir } = require("./safeTempDir");
const { app } = require("electron");
+const sidecarPidFile = require("./sidecarPidFile");
const PORT_RANGE_START = 8200;
const PORT_RANGE_END = 8220;
@@ -231,7 +232,9 @@ class LlamaServerManager {
windowsHide: true,
cwd: getSafeTempDir(),
env,
+ detached: process.platform !== "win32",
});
+ sidecarPidFile.write("llama", this.process.pid);
let stderrBuffer = "";
let exitCode = null;
@@ -266,6 +269,7 @@ class LlamaServerManager {
this.ready = false;
this.process = null;
this.stopHealthCheck();
+ sidecarPidFile.clear("llama");
});
const getProcessInfo = () => ({ stderr: stderrBuffer, exitCode, exitSignal });
diff --git a/src/helpers/parakeetWsServer.js b/src/helpers/parakeetWsServer.js
index e71b82c5e..564aec96d 100644
--- a/src/helpers/parakeetWsServer.js
+++ b/src/helpers/parakeetWsServer.js
@@ -10,6 +10,7 @@ const {
gracefulStopProcess,
} = require("../utils/serverUtils");
const { getSafeTempDir } = require("./safeTempDir");
+const sidecarPidFile = require("./sidecarPidFile");
const PORT_RANGE_START = 6006;
const PORT_RANGE_END = 6029;
@@ -85,7 +86,9 @@ class ParakeetWsServer {
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
cwd: getSafeTempDir(),
+ detached: process.platform !== "win32",
});
+ sidecarPidFile.write("parakeet", this.process.pid);
let stderrBuffer = "";
let exitCode = null;
@@ -118,6 +121,7 @@ class ParakeetWsServer {
this.ready = false;
this.process = null;
this.stopHealthCheck();
+ sidecarPidFile.clear("parakeet");
readyResolve(false);
});
diff --git a/src/helpers/qdrantManager.js b/src/helpers/qdrantManager.js
index ed3ce27bc..0d4967c79 100644
--- a/src/helpers/qdrantManager.js
+++ b/src/helpers/qdrantManager.js
@@ -9,6 +9,7 @@ const {
resolveBinaryPath,
gracefulStopProcess,
} = require("../utils/serverUtils");
+const sidecarPidFile = require("./sidecarPidFile");
const PORT_RANGE_START = 6333;
const PORT_RANGE_END = 6350;
@@ -91,7 +92,9 @@ class QdrantManager {
cwd: STORAGE_DIR,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
+ detached: process.platform !== "win32",
});
+ sidecarPidFile.write("qdrant", this.process.pid);
let stderrBuffer = "";
let exitCode = null;
@@ -116,6 +119,7 @@ class QdrantManager {
this.ready = false;
this.process = null;
this._stopHealthCheck();
+ sidecarPidFile.clear("qdrant");
});
await this._waitForReady(() => ({ stderr: stderrBuffer, exitCode }));
diff --git a/src/helpers/sidecarPidFile.js b/src/helpers/sidecarPidFile.js
new file mode 100644
index 000000000..e801ef437
--- /dev/null
+++ b/src/helpers/sidecarPidFile.js
@@ -0,0 +1,48 @@
+const fs = require("fs");
+const path = require("path");
+const { app } = require("electron");
+
+const SUBDIR = "sidecar-pids";
+
+function pidDir() {
+ return path.join(app.getPath("userData"), SUBDIR);
+}
+
+function pidPath(name) {
+ return path.join(pidDir(), `${name}.pid`);
+}
+
+function write(name, pid) {
+ if (!Number.isInteger(pid)) return;
+ try {
+ fs.mkdirSync(pidDir(), { recursive: true });
+ fs.writeFileSync(pidPath(name), String(pid), "utf-8");
+ } catch {
+ // Best-effort; the registry is the primary shutdown path.
+ }
+}
+
+function clear(name) {
+ try {
+ fs.unlinkSync(pidPath(name));
+ } catch {
+ // Already gone.
+ }
+}
+
+function readAll() {
+ const dir = pidDir();
+ if (!fs.existsSync(dir)) return [];
+ const entries = [];
+ for (const file of fs.readdirSync(dir)) {
+ if (!file.endsWith(".pid")) continue;
+ const name = path.basename(file, ".pid");
+ const raw = fs.readFileSync(path.join(dir, file), "utf-8").trim();
+ const pid = Number(raw);
+ if (!Number.isInteger(pid) || pid <= 0) continue;
+ entries.push({ name, pid });
+ }
+ return entries;
+}
+
+module.exports = { write, clear, readAll };
diff --git a/src/helpers/sidecarReaper.js b/src/helpers/sidecarReaper.js
new file mode 100644
index 000000000..6e9633b38
--- /dev/null
+++ b/src/helpers/sidecarReaper.js
@@ -0,0 +1,58 @@
+const { execFileSync } = require("child_process");
+const debugLogger = require("./debugLogger");
+const sidecarPidFile = require("./sidecarPidFile");
+
+const EXPECTED_BINARY_FRAGMENTS = {
+ parakeet: "sherpa-onnx-ws",
+ whisper: "whisper-server",
+ llama: "llama-server",
+ qdrant: "qdrant",
+ diarization: "sherpa-onnx-diarize",
+};
+
+function isProcessAlive(pid) {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return err.code === "EPERM";
+ }
+}
+
+function processCommand(pid) {
+ try {
+ if (process.platform === "win32") {
+ const out = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], {
+ stdio: ["ignore", "pipe", "ignore"],
+ windowsHide: true,
+ }).toString();
+ const match = out.match(/^"([^"]+)"/);
+ return match ? match[1] : "";
+ }
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], {
+ stdio: ["ignore", "pipe", "ignore"],
+ })
+ .toString()
+ .trim();
+ } catch {
+ return "";
+ }
+}
+
+function reapStaleSidecars() {
+ const entries = sidecarPidFile.readAll();
+ for (const { name, pid } of entries) {
+ const fragment = EXPECTED_BINARY_FRAGMENTS[name];
+ if (fragment && isProcessAlive(pid) && processCommand(pid).includes(fragment)) {
+ debugLogger.warn("Reaping stale sidecar", { name, pid });
+ try {
+ process.kill(pid, "SIGTERM");
+ } catch {
+ // Already dead.
+ }
+ }
+ sidecarPidFile.clear(name);
+ }
+}
+
+module.exports = { reapStaleSidecars };
diff --git a/src/helpers/sidecarRegistry.js b/src/helpers/sidecarRegistry.js
new file mode 100644
index 000000000..549670f41
--- /dev/null
+++ b/src/helpers/sidecarRegistry.js
@@ -0,0 +1,27 @@
+const debugLogger = require("./debugLogger");
+
+const SHUTDOWN_DEADLINE_MS = 8000;
+
+const sidecars = [];
+
+function register(name, stopFn) {
+ sidecars.push({ name, stop: stopFn });
+}
+
+async function shutdownAll() {
+ if (sidecars.length === 0) return;
+
+ const deadline = new Promise((resolve) => setTimeout(resolve, SHUTDOWN_DEADLINE_MS));
+ const stops = Promise.allSettled(
+ sidecars.map(async ({ name, stop }) => {
+ try {
+ await stop();
+ } catch (err) {
+ debugLogger.error("sidecar stop failed", { name, error: err?.message });
+ }
+ })
+ );
+ await Promise.race([stops, deadline]);
+}
+
+module.exports = { register, shutdownAll };
diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.js
index 10d3a21c8..6edcbc639 100644
--- a/src/helpers/whisperServer.js
+++ b/src/helpers/whisperServer.js
@@ -9,6 +9,7 @@ const debugLogger = require("./debugLogger");
const { killProcess } = require("../utils/process");
const { getSafeTempDir } = require("./safeTempDir");
const { convertToWav } = require("./ffmpegUtils");
+const sidecarPidFile = require("./sidecarPidFile");
const PORT_RANGE_START = 8178;
const PORT_RANGE_END = 8199;
@@ -315,7 +316,9 @@ class WhisperServerManager extends EventEmitter {
windowsHide: true,
env: spawnEnv,
cwd: serverBinaryDir,
+ detached: process.platform !== "win32",
});
+ sidecarPidFile.write("whisper", this.process.pid);
let stderrBuffer = "";
let exitCode = null;
@@ -342,6 +345,7 @@ class WhisperServerManager extends EventEmitter {
this.ready = false;
this.process = null;
this.stopHealthCheck();
+ sidecarPidFile.clear("whisper");
});
try {
diff --git a/src/utils/process.js b/src/utils/process.js
index d16d2eac1..8d5de3cf1 100644
--- a/src/utils/process.js
+++ b/src/utils/process.js
@@ -28,6 +28,21 @@ function killProcess(proc, signal = "SIGTERM") {
}
}
+// Signals the whole process group on Unix so grandchildren get reaped too.
+// Windows' killProcess already passes /T, which covers the descendant tree.
+function killProcessGroup(proc, signal = "SIGTERM") {
+ if (!proc || proc.exitCode !== null) return;
+ if (process.platform === "win32") {
+ killProcess(proc, signal);
+ return;
+ }
+ try {
+ process.kill(-proc.pid, signal);
+ } catch {
+ killProcess(proc, signal);
+ }
+}
+
// Timeout constants
const TIMEOUTS = {
QUICK_CHECK: 5000, // 5 seconds for quick checks
@@ -142,5 +157,6 @@ async function runCommand(cmd, args = [], options = {}) {
module.exports = {
runCommand,
killProcess,
+ killProcessGroup,
TIMEOUTS,
};
diff --git a/src/utils/serverUtils.js b/src/utils/serverUtils.js
index b28550895..6d2e43d26 100644
--- a/src/utils/serverUtils.js
+++ b/src/utils/serverUtils.js
@@ -1,7 +1,7 @@
const fs = require("fs");
const net = require("net");
const path = require("path");
-const { killProcess } = require("./process");
+const { killProcessGroup } = require("./process");
const GRACEFUL_STOP_TIMEOUT_MS = 5000;
@@ -49,11 +49,11 @@ function resolveBinaryPath(binaryName) {
}
async function gracefulStopProcess(proc) {
- killProcess(proc, "SIGTERM");
+ killProcessGroup(proc, "SIGTERM");
await new Promise((resolve) => {
const timeout = setTimeout(() => {
- if (proc) killProcess(proc, "SIGKILL");
+ if (proc) killProcessGroup(proc, "SIGKILL");
resolve();
}, GRACEFUL_STOP_TIMEOUT_MS);