Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(captions): block helper respawn during shutdown

Vitali Gusatinsky4f644b70232d
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.ts
index 335df794b..530839387 100644
--- a/electron/stt/index.test.ts
+++ b/electron/stt/index.test.ts
@@ -18,6 +18,7 @@ const fakeWhisperServer = {
},
transcribe: vi.fn(),
stop: vi.fn(),
+ shutdown: vi.fn(),
};
vi.mock("./whisperServer", () => {
@@ -26,6 +27,7 @@ vi.mock("./whisperServer", () => {
status = fakeWhisperServer.status;
transcribe = fakeWhisperServer.transcribe;
stop = fakeWhisperServer.stop;
+ shutdown = fakeWhisperServer.shutdown;
}
return { WhisperServerManager: FakeWhisperServerManager };
});
@@ -52,6 +54,7 @@ describe("SttManager", () => {
fakeWhisperServer.start.mockClear();
fakeWhisperServer.transcribe.mockClear();
fakeWhisperServer.stop.mockClear();
+ fakeWhisperServer.shutdown.mockClear();
fakeWhisperServer.start.mockResolvedValue({ port: 9000, backend: "whispercpp-cpu" });
fakeWhisperServer.transcribe.mockResolvedValue({
segments: [{ text: "hello", startSec: 0, endSec: 0.5 }],
@@ -198,7 +201,7 @@ describe("SttManager", () => {
const mgr = new SttManager();
await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
await mgr.shutdown();
- expect(fakeWhisperServer.stop).toHaveBeenCalledOnce();
+ expect(fakeWhisperServer.shutdown).toHaveBeenCalledOnce();
});
it("shutdownStt() stops and releases the singleton exactly once", async () => {
@@ -208,7 +211,25 @@ describe("SttManager", () => {
await shutdownStt();
await shutdownStt();
- expect(fakeWhisperServer.stop).toHaveBeenCalledOnce();
+ expect(fakeWhisperServer.shutdown).toHaveBeenCalledOnce();
+ expect(() => getSttManager()).toThrowError(/cancel/i);
+ });
+
+ it("does not respawn the helper when shutdown interrupts a failed chunk", async () => {
+ const mgr = getSttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ fakeWhisperServer.transcribe.mockImplementationOnce(async () => {
+ await shutdownStt();
+ throw new Error("connection closed during quit");
+ });
+
+ const error = await mgr
+ .transcribe({ samples: new Float32Array(16000), language: "en" })
+ .catch((value: unknown) => value);
+
+ expect((error as Error).name).toBe("AbortError");
+ expect(fakeWhisperServer.start).toHaveBeenCalledOnce();
+ expect(fakeWhisperServer.shutdown).toHaveBeenCalledOnce();
});
it("retries setup after a failed one instead of caching the rejection", async () => {
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index ee6be4664..40c383d6d 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -69,6 +69,7 @@ export interface SttManagerInitOptions {
export class SttManager {
private readonly server = new WhisperServerManager();
+ private shuttingDown = false;
private modelsBaseDir: string | null = null;
private readonly statusSinks = new Set<(event: SttStatusEvent) => void>();
private initPromise: Promise<void> | null = null;
@@ -119,6 +120,7 @@ export class SttManager {
* means the second caller just awaits the same completion.
*/
init(options: SttManagerInitOptions = {}): Promise<void> {
+ if (this.shuttingDown) return Promise.reject(cancelledError());
if (options.statusSink) this.addStatusSink(options.statusSink);
if (options.modelsBaseDir) this.modelsBaseDir = options.modelsBaseDir;
if (!this.initPromise) {
@@ -158,10 +160,15 @@ export class SttManager {
});
},
});
+ if (this.shuttingDown) throw cancelledError();
const paths = modelPaths(modelsDir);
this.modelPath = paths.whisper;
await this.server.start({ modelPath: paths.whisper });
+ if (this.shuttingDown) {
+ await this.server.shutdown();
+ throw cancelledError();
+ }
this.emit({ phase: "transcribe" });
}
@@ -186,14 +193,17 @@ export class SttManager {
): Promise<Awaited<ReturnType<WhisperServerManager["transcribe"]>>> {
let lastError: unknown;
for (let attempt = 1; attempt <= CHUNK_ATTEMPTS; attempt++) {
+ if (this.shuttingDown) throw cancelledError();
try {
return await this.server.transcribe({ samples, language });
} catch (error) {
lastError = error;
+ if (this.shuttingDown) throw cancelledError();
if (attempt === CHUNK_ATTEMPTS) break;
if (this.modelPath) {
await this.server.start({ modelPath: this.modelPath }).catch(() => undefined);
}
+ if (this.shuttingDown) throw cancelledError();
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
}
}
@@ -244,6 +254,7 @@ export class SttManager {
req.samples.subarray(chunk.startSample, chunk.endSample),
language,
).catch((error) => {
+ if (error instanceof Error && error.name === "AbortError") throw error;
// Say where it died. Without this the user gets "Transcription
// failed" for a 30-minute recording with no hint that 18 of those
// minutes were fine and the helper fell over at one specific spot.
@@ -298,14 +309,19 @@ export class SttManager {
/** Best-effort shutdown; safe to call from `before-quit` hooks. */
async shutdown(): Promise<void> {
- await this.server.stop();
+ if (this.shuttingDown) return;
+ this.shuttingDown = true;
+ this.cancelEpoch++;
+ await this.server.shutdown();
}
}
let singleton: SttManager | null = null;
+let sttShuttingDown = false;
/** Lazy singleton for the IPC layer; processes one transcription at a time. */
export function getSttManager(): SttManager {
+ if (sttShuttingDown) throw cancelledError();
if (!singleton) singleton = new SttManager();
return singleton;
}
@@ -317,14 +333,16 @@ export function getSttManager(): SttManager {
* clearing the slot first also makes repeated quit events idempotent.
*/
export async function shutdownStt(): Promise<void> {
+ sttShuttingDown = true;
const manager = singleton;
- singleton = null;
await manager?.shutdown();
+ singleton = null;
}
/** Reset the singleton — for tests. */
export function _resetSttManagerForTests(): void {
singleton = null;
+ sttShuttingDown = false;
}
/**
diff --git a/electron/stt/whisperServer.test.ts b/electron/stt/whisperServer.test.ts
index 9adc28c42..96d58d659 100644
--- a/electron/stt/whisperServer.test.ts
+++ b/electron/stt/whisperServer.test.ts
@@ -89,6 +89,15 @@ describe("WhisperServerManager", () => {
expect(mgr.status.running).toBe(false);
});
+ it("does not allow a helper to spawn after permanent shutdown", async () => {
+ const mgr = new WhisperServerManager();
+ await mgr.shutdown();
+
+ await expect(mgr.start({ modelPath: "/missing/model.bin" })).rejects.toThrow(/shutting down/);
+ const { spawn } = await import("node:child_process");
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
it("extracts phrase and word segments from a verbose_json response", async () => {
const fakeJson = {
task: "transcribe",
diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.ts
index dd04d144a..567b2e05e 100644
--- a/electron/stt/whisperServer.ts
+++ b/electron/stt/whisperServer.ts
@@ -97,6 +97,7 @@ interface WhisperJsonResponse {
export class WhisperServerManager {
private process: WhisperChild | null = null;
+ private shuttingDown = false;
private port: number | null = null;
private backend: SttBackend | null = null;
private lastError: string | null = null;
@@ -169,6 +170,9 @@ export class WhisperServerManager {
* the cold-start cost twice.
*/
async start(options: WhisperServerStartOptions): Promise<{ port: number; backend: SttBackend }> {
+ if (this.shuttingDown) {
+ throw new Error("whisper-stt-server manager is shutting down");
+ }
if (this.process && this.port) {
return { port: this.port, backend: this.backend ?? options.backend ?? "whispercpp-cpu" };
}
@@ -200,6 +204,9 @@ export class WhisperServerManager {
const launch = async (forceCpu: boolean): Promise<{ port: number; backend: SttBackend }> => {
const port = await WhisperServerManager.pickFreePort();
+ if (this.shuttingDown) {
+ throw new Error("whisper-stt-server manager is shutting down");
+ }
const args = [
"--model",
options.modelPath,
@@ -315,6 +322,12 @@ export class WhisperServerManager {
}
}
+ /** Permanently prevent respawn, then stop the currently owned helper. */
+ async shutdown(): Promise<void> {
+ this.shuttingDown = true;
+ await this.stop();
+ }
+
private baseUrl(): string {
if (!this.port) throw new Error("whisper-stt-server not started");
return `http://127.0.0.1:${this.port}`;