Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(speech): end capture when the Electron owner dies

Sebastian B25e5d9b4248f
diff --git a/electron/resources/speech-helper.swift b/electron/resources/speech-helper.swift
index 9633beeedf..a01aa7c855 100644
--- a/electron/resources/speech-helper.swift
+++ b/electron/resources/speech-helper.swift
@@ -16,6 +16,7 @@
// listed modifiers (control, option, shift, command) is no longer held.
import AVFoundation
import CoreGraphics
+import Darwin
import Foundation
import Speech
@@ -91,6 +92,35 @@ let finishOnRelease: CGEventFlags? = {
return flags
}()
+let lifelineFile: String = {
+ let args = CommandLine.arguments
+ guard let index = args.firstIndex(of: "--lifeline-file"), index + 1 < args.count else {
+ fail("missing-lifeline")
+ }
+ return args[index + 1]
+}()
+let lifelineFD = Darwin.open(lifelineFile, O_RDONLY | O_NONBLOCK)
+guard lifelineFD >= 0 else { fail("lifeline-unavailable") }
+
+func checkOwner() {
+ var byte: UInt8 = 0
+ let count = Darwin.read(lifelineFD, &byte, 1)
+ guard count == 0 || (count < 0 && errno != EAGAIN && errno != EINTR) else { return }
+ let sessionDir = (lifelineFile as NSString).deletingLastPathComponent
+ // Owner death leaves private transcripts behind. Remove only this session's known files, never a directory tree.
+ for name in ["stdout.ndjson", "stderr.log", "stop", "finish", "owner.pipe"] {
+ _ = unlink((sessionDir as NSString).appendingPathComponent(name))
+ }
+ _ = rmdir(sessionDir)
+ exit(0)
+}
+
+// LaunchServices reparents the helper. FIFO EOF binds capture to Electron's lifetime without trusting a reusable PID.
+checkOwner()
+let ownerSource = DispatchSource.makeReadSource(fileDescriptor: lifelineFD, queue: .global(qos: .userInitiated))
+ownerSource.setEventHandler { checkOwner() }
+ownerSource.resume()
+
// LaunchServices gives the helper the bundle identity TCC needs, but it also
// means the parent cannot terminate it by killing the `open -W` process. A
// per-session stop marker keeps intentional mute/hang-up deterministic.
diff --git a/electron/speech-helper-release.node-test.mjs b/electron/speech-helper-release.node-test.mjs
index 6c1f70fd41..8a2dd40322 100644
--- a/electron/speech-helper-release.node-test.mjs
+++ b/electron/speech-helper-release.node-test.mjs
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
-import { mkdtempSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
@@ -36,3 +36,27 @@ test("the helper finishes when any of the chosen modifiers is let go", { skip: !
rmSync(dir, { recursive: true, force: true });
}
});
+
+test("the helper removes an orphan session before requesting speech authorization", { skip: !swiftc && "needs macOS with swiftc" }, () => {
+ const dir = mkdtempSync(join(tmpdir(), "speech-helper-owner-"));
+ try {
+ const bin = join(dir, "speech-helper");
+ execFileSync(
+ "xcrun",
+ ["swiftc", "-Onone", fileURLToPath(new URL("./resources/speech-helper.swift", import.meta.url)), "-o", bin],
+ { timeout: 180_000 },
+ );
+ const session = join(dir, "session");
+ mkdirSync(session, { mode: 0o700 });
+ for (const name of ["stdout.ndjson", "stderr.log", "finish"]) writeFileSync(join(session, name), "fixture");
+ const lifeline = join(session, "owner.pipe");
+ execFileSync("/usr/bin/mkfifo", ["-m", "600", lifeline]);
+ const result = spawnSync(bin, ["--lifeline-file", lifeline], { encoding: "utf8", timeout: 10_000 });
+ assert.equal(result.error, undefined);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, "");
+ assert.equal(existsSync(session), false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/electron/speech-owner.node-test.mjs b/electron/speech-owner.node-test.mjs
new file mode 100644
index 0000000000..a7035635ae
--- /dev/null
+++ b/electron/speech-owner.node-test.mjs
@@ -0,0 +1,111 @@
+import assert from "node:assert/strict";
+import { fork } from "node:child_process";
+import { once } from "node:events";
+import { closeSync, constants, existsSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ownerSource = `
+ import { registerHooks } from 'node:module';
+ const moduleURL = source => 'data:text/javascript,' + encodeURIComponent(source);
+ registerHooks({ resolve(specifier, context, next) {
+ if (context.parentURL?.endsWith('/speech.mjs')) {
+ if (specifier === 'electron') return { shortCircuit: true, url: moduleURL(
+ 'export const app = { isPackaged: true, getPath: () => process.argv[1] };') };
+ if (specifier === 'node:child_process') return { shortCircuit: true, url: moduleURL(\`
+ export { execFileSync } from 'node:child_process';
+ import { EventEmitter } from 'node:events';
+ export function spawn(file, args, options) {
+ if (process.argv[2] === 'throw') throw new Error('launch failed');
+ globalThis.speechProc = new EventEmitter();
+ process.send({ type: 'launch', file, args, options });
+ return globalThis.speechProc;
+ }
+ \`) };
+ }
+ return next(specifier, context);
+ } });
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ process.resourcesPath = '/synthetic-speech-resources';
+ const speech = await import(${JSON.stringify(new URL('./speech.mjs', import.meta.url).href)});
+ const sink = { transcript() {}, end(info) { process.send({ type: 'end', info }); }, replaced() {} };
+ process.on('message', command => {
+ if (command === 'close') globalThis.speechProc.emit('close', 0);
+ if (command === 'error') globalThis.speechProc.emit('error', new Error('launch failed'));
+ if (command === 'stop') speech.stopSpeech();
+ if (command === 'finish') speech.finishSpeech();
+ process.send({ type: 'done', command });
+ });
+ speech.startSpeech(sink);
+`;
+
+async function owner(t, mode = "ok") {
+ const dir = mkdtempSync(path.join(tmpdir(), "speech-owner-"));
+ const proc = fork("--eval", [ownerSource, dir, mode], {
+ execArgv: ["--input-type=module"], silent: true,
+ });
+ const exit = once(proc, "exit");
+ t.after(async () => {
+ if (proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL");
+ await exit;
+ rmSync(dir, { recursive: true, force: true });
+ });
+ const [message] = await once(proc, "message");
+ return { proc, dir, message, exit };
+}
+
+function readLifeline(t, message) {
+ assert.equal(message.type, "launch");
+ const index = message.args.indexOf("--lifeline-file");
+ assert.ok(index >= 0, "the helper must receive an owner lifeline");
+ const file = message.args[index + 1];
+ assert.equal(statSync(file).isFIFO(), true);
+ assert.equal(statSync(file).mode & 0o777, 0o600);
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK);
+ t.after(() => closeSync(fd));
+ return () => readSync(fd, Buffer.alloc(1), 0, 1, null);
+}
+
+const options = { skip: process.platform === "win32" && "needs POSIX FIFO", timeout: 10_000 };
+
+test("a speech helper's lifeline reaches EOF when its Electron owner is SIGKILLed", options, async t => {
+ const { proc, message, exit } = await owner(t);
+ const read = readLifeline(t, message);
+ assert.throws(read, { code: "EAGAIN" }, "an active owner keeps the pipe open without sending data");
+ proc.kill("SIGKILL");
+ await exit;
+ assert.equal(read(), 0, "owner death must close the only writer");
+});
+
+for (const command of ["close", "error"]) {
+ test(`speech ${command} closes the lifeline and removes the session`, options, async t => {
+ const { proc, dir, message } = await owner(t);
+ const read = readLifeline(t, message);
+ proc.send(command);
+ await once(proc, "message");
+ assert.equal(read(), 0);
+ assert.deepEqual(readdirSync(dir), []);
+ });
+}
+
+test("stop and finish retain their markers while the owner lifeline stays open", options, async t => {
+ const { proc, message } = await owner(t);
+ const read = readLifeline(t, message);
+ const flag = name => message.args[message.args.indexOf(name) + 1];
+ proc.send("finish");
+ await once(proc, "message");
+ assert.equal(readFileSync(flag("--finish-file"), "utf8"), "finish");
+ assert.equal(existsSync(flag("--stop-file")), false);
+ assert.throws(read, { code: "EAGAIN" });
+ proc.send("stop");
+ await once(proc, "message");
+ assert.equal(readFileSync(flag("--stop-file"), "utf8"), "stop");
+ assert.throws(read, { code: "EAGAIN" });
+});
+
+test("a synchronous launch failure removes the session and its lifeline", options, async t => {
+ const { dir, message } = await owner(t, "throw");
+ assert.deepEqual(message, { type: "end", info: { code: 1, reason: "helper-start-failed" } });
+ assert.deepEqual(readdirSync(dir), []);
+});
diff --git a/electron/speech.mjs b/electron/speech.mjs
index 110f6a0a13..3778f75d91 100644
--- a/electron/speech.mjs
+++ b/electron/speech.mjs
@@ -1,8 +1,11 @@
// macOS privacy enforcement requires the code calling Speech/AVFoundation to launch with its own Info.plist identity.
-import { spawn } from "node:child_process";
+import { execFileSync, spawn } from "node:child_process";
import {
+ closeSync,
+ constants,
existsSync,
mkdtempSync,
+ openSync,
readFileSync,
rmSync,
statSync,
@@ -109,11 +112,21 @@ export function startSpeech(target, options = {}) {
const errorPath = path.join(sessionDir, "stderr.log");
const stopPath = path.join(sessionDir, "stop");
const finishPath = path.join(sessionDir, "finish");
+ const lifelinePath = path.join(sessionDir, "owner.pipe");
writeFileSync(outputPath, "");
writeFileSync(errorPath, "");
let proc;
+ let lifeline;
try {
+ execFileSync("/usr/bin/mkfifo", ["-m", "600", lifelinePath], { timeout: 5_000 });
+ const reader = openSync(lifelinePath, constants.O_RDONLY | constants.O_NONBLOCK);
+ try {
+ // Only Electron holds a writer; LaunchServices cannot inherit a lifeline through `open`.
+ lifeline = openSync(lifelinePath, constants.O_WRONLY | constants.O_NONBLOCK);
+ } finally {
+ closeSync(reader);
+ }
proc = spawn(
"/usr/bin/open",
[
@@ -131,10 +144,13 @@ export function startSpeech(target, options = {}) {
stopPath,
"--finish-file",
finishPath,
+ "--lifeline-file",
+ lifelinePath,
],
{ stdio: "ignore" },
);
} catch {
+ if (lifeline !== undefined) closeSync(lifeline);
rmSync(sessionDir, { recursive: true, force: true });
sink.end({ code: 1, reason: "helper-start-failed" });
return;
@@ -183,6 +199,7 @@ export function startSpeech(target, options = {}) {
const cleanup = () => {
if (cleaned) return;
cleaned = true;
+ closeSync(lifeline);
forgetWindow();
unwatchFile(outputPath, drain);
rmSync(sessionDir, { recursive: true, force: true });
diff --git a/electron/speech.test.mjs b/electron/speech.test.mjs
index db3498101e..a74b181aa1 100644
--- a/electron/speech.test.mjs
+++ b/electron/speech.test.mjs
@@ -5,7 +5,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const fixture = vi.hoisted(() => ({ launches: [], windows: [] }));
vi.mock("electron", () => ({ app: { isPackaged: true, getPath: () => tmpdir() } }));
-vi.mock("node:child_process", () => ({
+vi.mock("node:child_process", async (importOriginal) => ({
+ ...await importOriginal(),
spawn: (_file, args) => {
const proc = new EventEmitter();
const arg = flag => args[args.indexOf(flag) + 1];