Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(captions): address automated review findings
Vitali Gusatinsky4425c8e147e3
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.tsindex 530839387..f06da2cd8 100644--- a/electron/stt/index.test.ts+++ b/electron/stt/index.test.ts@@ -232,6 +232,42 @@ describe("SttManager", () => {expect(fakeWhisperServer.shutdown).toHaveBeenCalledOnce();});+ it("cancels when shutdown starts as setup rejects", async () => {+ const mgr = new SttManager();+ fakeWhisperServer.start.mockImplementationOnce(async () => {+ await mgr.shutdown();+ throw new Error("connection closed during startup");+ });++ const error = await mgr+ .init({ modelsBaseDir: "/tmp/fake-stt-models" })+ .catch((value: unknown) => value);++ expect((error as Error).name).toBe("AbortError");+ expect(fakeWhisperServer.shutdown).toHaveBeenCalledOnce();+ });++ it("cancels when shutdown starts as the final chunk resolves", async () => {+ const mgr = getSttManager();+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });+ fakeWhisperServer.transcribe.mockImplementationOnce(async () => {+ await shutdownStt();+ return {+ segments: [{ text: "late", startSec: 0, endSec: 0.5 }],+ wordSegments: [{ word: "late", startSec: 0, endSec: 0.5 }],+ detectedLanguage: "en",+ backend: "whispercpp-cpu" as const,+ };+ });++ const error = await mgr+ .transcribe({ samples: new Float32Array(16_000), language: "en" })+ .catch((value: unknown) => value);++ expect((error as Error).name).toBe("AbortError");+ expect(fakeWhisperServer.transcribe).toHaveBeenCalledOnce();+ });+it("retries setup after a failed one instead of caching the rejection", async () => {// First run downloads a 253 MB model. Caching a rejected `prepare()` meant// one dropped connection failed every later transcription in the session —diff --git a/electron/stt/index.ts b/electron/stt/index.tsindex 40c383d6d..a1ed3cb67 100644--- a/electron/stt/index.ts+++ b/electron/stt/index.ts@@ -164,7 +164,12 @@ export class SttManager {const paths = modelPaths(modelsDir);this.modelPath = paths.whisper;- await this.server.start({ modelPath: paths.whisper });+ try {+ await this.server.start({ modelPath: paths.whisper });+ } catch (error) {+ if (this.shuttingDown) throw cancelledError();+ throw error;+ }if (this.shuttingDown) {await this.server.shutdown();throw cancelledError();@@ -270,6 +275,7 @@ export class SttManager {{ cause: error },);});+ if (this.shuttingDown || this.cancelEpoch !== epoch) throw cancelledError();// Chunk-relative timestamps → absolute, the only thing every consumer// (captions, transcript editor, trims) reads.for (const segment of result.segments) {diff --git a/electron/stt/whisperServer.test.ts b/electron/stt/whisperServer.test.tsindex 96d58d659..9f52d5348 100644--- a/electron/stt/whisperServer.test.ts+++ b/electron/stt/whisperServer.test.ts@@ -98,6 +98,34 @@ describe("WhisperServerManager", () => {expect(spawn).not.toHaveBeenCalled();});+ it("bounds a readiness probe that accepts a connection but never responds", async () => {+ vi.useFakeTimers();+ vi.stubGlobal(+ "fetch",+ vi.fn((_url: string, init?: RequestInit) => {+ return new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), {+ once: true,+ });+ });+ }),+ );+ try {+ const pollUntilReady = (+ WhisperServerManager as unknown as {+ pollUntilReady: (baseUrl: string, timeoutMs: number) => Promise<void>;+ }+ ).pollUntilReady;+ const readiness = pollUntilReady("http://127.0.0.1:9999", 2_500);+ const assertion = expect(readiness).rejects.toThrow(/did not respond within 2500ms/);+ await vi.advanceTimersByTimeAsync(3_000);+ await assertion;+ } finally {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ }+ });+it("extracts phrase and word segments from a verbose_json response", async () => {const fakeJson = {task: "transcribe",@@ -288,20 +316,22 @@ describe("WhisperServerManager", () => {const fs = await import("node:fs/promises");const { spawn } = await import("node:child_process");const dir = await mkdtemp(path.join(tmpdir(), "whisper-cpu-fallback-"));+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");try {+ Object.defineProperty(process, "platform", { value: "linux", configurable: true });const modelPath = path.join(dir, "ggml-large-v3-turbo-q5_0.bin");const fakeBinaryPath = path.join(dir, "whisper-stt-server");await fs.writeFile(modelPath, "dummy-ggml");await fs.writeFile(fakeBinaryPath, "x", { mode: 0o755 });const child = () => {- const process = Object.assign(new EventEmitter(), {+ const proc = Object.assign(new EventEmitter(), {stdout: new EventEmitter(),stderr: new EventEmitter(),pid: 1234,kill: vi.fn(),});- return process;+ return proc;};const gpuChild = child();const cpuChild = child();@@ -310,7 +340,7 @@ describe("WhisperServerManager", () => {queueMicrotask(() => {gpuChild.stderr.emit("data",- Buffer.from("ggml_metal_buffer_init: error: failed to allocate buffer"),+ Buffer.from("ggml_metal_buffer_init: initialized\nfailed to allocate GPU buffer"),);gpuChild.emit("exit", 1);});@@ -335,6 +365,47 @@ describe("WhisperServerManager", () => {expect(spawn).toHaveBeenCalledTimes(2);expect(vi.mocked(spawn).mock.calls[0]?.[1]).not.toContain("--cpu");expect(vi.mocked(spawn).mock.calls[1]?.[1]).toContain("--cpu");+ } finally {+ if (originalPlatform) Object.defineProperty(process, "platform", originalPlatform);+ vi.unstubAllGlobals();+ await rm(dir, { recursive: true, force: true });+ }+ });++ it("serializes overlapping start calls onto one helper process", async () => {+ const fs = await import("node:fs/promises");+ const { spawn } = await import("node:child_process");+ const dir = await mkdtemp(path.join(tmpdir(), "whisper-single-start-"));+ try {+ const modelPath = path.join(dir, "ggml-large-v3-turbo-q5_0.bin");+ const fakeBinaryPath = path.join(+ dir,+ process.platform === "win32" ? "whisper-stt-server.exe" : "whisper-stt-server",+ );+ await fs.writeFile(modelPath, "dummy-ggml");+ await fs.writeFile(fakeBinaryPath, "x", { mode: 0o755 });+ const child = Object.assign(new EventEmitter(), {+ stdout: new EventEmitter(),+ stderr: new EventEmitter(),+ pid: 1234,+ kill: vi.fn(),+ });+ vi.mocked(spawn).mockReturnValue(child as never);+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("ok", { status: 200 })),+ );+ const mgr = new WhisperServerManager();+ const options = {+ modelPath,+ binaryPath: fakeBinaryPath,+ backend: "whispercpp-cpu" as const,+ };++ const [first, second] = await Promise.all([mgr.start(options), mgr.start(options)]);++ expect(first).toEqual(second);+ expect(spawn).toHaveBeenCalledOnce();} finally {vi.unstubAllGlobals();await rm(dir, { recursive: true, force: true });diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.tsindex 567b2e05e..4635134ed 100644--- a/electron/stt/whisperServer.ts+++ b/electron/stt/whisperServer.ts@@ -103,6 +103,7 @@ export class WhisperServerManager {private lastError: string | null = null;private startedAtMs: number | null = null;private inFlight: Promise<unknown> = Promise.resolve();+ private starting: Promise<{ port: number; backend: SttBackend }> | null = null;/** Buffered stderr from the helper; surfaced on shutdown + poll failures. */private stderrTail = "";@@ -136,11 +137,18 @@ export class WhisperServerManager {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {if (!shouldContinue()) throw new Error("whisper-stt-server exited before readiness");+ const controller = new AbortController();+ const probeTimeout = setTimeout(+ () => controller.abort(),+ Math.min(2_000, Math.max(1, deadline - Date.now())),+ );try {- const res = await fetch(baseUrl, { method: "GET" });+ const res = await fetch(baseUrl, { method: "GET", signal: controller.signal });if (res.ok) return;} catch {// not up yet+ } finally {+ clearTimeout(probeTimeout);}if (!shouldContinue()) throw new Error("whisper-stt-server exited before readiness");await new Promise((resolve) => setTimeout(resolve, 250));@@ -170,6 +178,16 @@ export class WhisperServerManager {* the cold-start cost twice.*/async start(options: WhisperServerStartOptions): Promise<{ port: number; backend: SttBackend }> {+ if (this.starting) return this.starting;+ this.starting = this.startImpl(options).finally(() => {+ this.starting = null;+ });+ return this.starting;+ }++ private async startImpl(+ options: WhisperServerStartOptions,+ ): Promise<{ port: number; backend: SttBackend }> {if (this.shuttingDown) {throw new Error("whisper-stt-server manager is shutting down");}@@ -286,9 +304,15 @@ export class WhisperServerManager {return await launch(false);} catch (err) {const startupLog = `${err instanceof Error ? err.message : String(err)} ${this.stderrTail}`;+ const startupLines = startupLog.split(/\r?\n/);+ const mentionsGpuBackend = startupLines.some((line) =>+ /(?:ggml_(?:metal|vulkan|cuda)|gpu)/i.test(line),+ );+ const mentionsStartupFailure = startupLines.some((line) =>+ /(?:fail|error|allocat)/i.test(line),+ );const gpuStartupFailed =- resolved.backend !== "whispercpp-cpu" &&- /(?:ggml_(?:metal|vulkan|cuda)|gpu).*(?:fail|error|allocat)/i.test(startupLog);+ resolved.backend !== "whispercpp-cpu" && mentionsGpuBackend && mentionsStartupFailure;if (!gpuStartupFailed) throw err;process.stderr.write("[whisper-stt-server] GPU startup failed; retrying with CPU inference\n",diff --git a/scripts/build-whisper-stt.sh b/scripts/build-whisper-stt.shindex e62c6cc76..ade88df57 100644--- a/scripts/build-whisper-stt.sh+++ b/scripts/build-whisper-stt.sh@@ -217,7 +217,7 @@ build_variant() {# @rpath/libggml.0.dylib and dies in dyld before main(). The `lib` prefix and# the `.so.<N>` version suffixes are what the globs below add.#- # -a preserves the symlink farm (libggml.dylib -> libggml.0.dylib ->+ # -P preserves the symlink farm (libggml.dylib -> libggml.0.dylib -># libggml.0.15.1.dylib); plain `cp` dereferences each one into a full copy of# the same payload, which tripled the staged size for no benefit.local found_libs=0diff --git a/technical-documentation/architecture/transcription-and-captions.md b/technical-documentation/architecture/transcription-and-captions.mdindex a24d0f745..f41ff622c 100644--- a/technical-documentation/architecture/transcription-and-captions.md+++ b/technical-documentation/architecture/transcription-and-captions.md@@ -107,7 +107,7 @@ clickable in the meantime (`phase: "model"` is emitted by the main process butdeliberately not forwarded to the renderer by `transcribeAsset`). Nothing in therenderer imposes a timeout that a slow download could trip: the preload does abare `ipcRenderer.invoke`, `fetchWithRetry` has no per-request deadline, and-whisper-server's 30 s readiness budget only starts once the download resolved.+whisper-server's 60 s readiness budget only starts once the download resolved.Three edges make that promise hold, and each is load-bearing:@@ -145,11 +145,11 @@ per-platform binary name only, and the real backend is corrected from thehelper's `/inference` JSON.Why whisper.cpp, in one paragraph: a single C++ dependency with native DTW-token timestamps for word-level timing, a portable runtime device selection-that covers Metal, Vulkan and CPU in one binary, and self-contained long-form-chunking (`whisper_full()` over recordings longer than 30 s) without manual-windowing on our side. Validation data — backend-by-backend WER and real-time-factors — lives in+token timestamps for word-level timing and portable runtime device selection+that covers Metal, Vulkan and CPU in one binary. OpenScreen supplies bounded,+sequential chunks to `whisper_full()` and restores their absolute timestamps,+so long recordings retain progress and retry boundaries. Validation data —+backend-by-backend WER and real-time factors — lives in[`tools/stt-eval/whispercpp-dtw-poc/REPORT.md`](../../tools/stt-eval/whispercpp-dtw-poc/REPORT.md).### Per-platform backend@@ -187,7 +187,7 @@ it verbatim in the response.array.2. **DTW timestamp** — every non-special token carries `t_dtw` incentiseconds from whisper.cpp's native DTW- (`dtw_token_timestamps=true`, `dtw_aheads_preset=WHISPER_AHEADS_SMALL`,+ (`dtw_token_timestamps=true`, `dtw_aheads_preset=WHISPER_AHEADS_LARGE_V3_TURBO`,`flash_attn=false`, which together are the prerequisites for DTW toactually run). `t_dtw == -1` is the DTW-inactive guardrail: the helperfails the request rather than emit zero-quality timestamps.