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(stt): make the chunked run cancellable, and its failures legible

Etienne Lescotcdc9b38aad24
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index bbac97658..f537dbbe8 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -390,6 +390,7 @@ interface Window {
transcribe: (
request: import("./stt/transcriptionContract").SttTranscribeRequest,
) => Promise<import("./stt/transcriptionContract").SttTranscribeResponse>;
+ cancel: () => Promise<void>;
onStatus: (
callback: (event: import("./stt/transcriptionContract").SttStatusEvent) => void,
) => () => void;
diff --git a/electron/preload.ts b/electron/preload.ts
index f3b44d57d..1fa241719 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -422,6 +422,8 @@ contextBridge.exposeInMainWorld("electronAPI", {
transcribe: (request: SttTranscribeRequest): Promise<SttTranscribeResponse> => {
return ipcRenderer.invoke("stt:transcribe", request) as Promise<SttTranscribeResponse>;
},
+ /** Stop the running transcription at its next chunk boundary. */
+ cancel: (): Promise<void> => ipcRenderer.invoke("stt:cancel") as Promise<void>,
onStatus: (callback: (event: SttStatusEvent) => void) => {
const listener = (_event: unknown, payload: SttStatusEvent) => callback(payload);
ipcRenderer.on("stt:status", listener);
diff --git a/electron/stt/chunking.test.ts b/electron/stt/chunking.test.ts
index eef6d2006..db19cbcfb 100644
--- a/electron/stt/chunking.test.ts
+++ b/electron/stt/chunking.test.ts
@@ -45,18 +45,28 @@ describe("planChunks", () => {
]);
});
- it("always makes progress, even on a fully silent buffer", () => {
- // Every frame ties on energy, so the cut is whatever the scan settles on —
- // what matters is that it never returns a zero-length chunk (infinite loop).
+ it("keeps the target when every frame ties, on a fully silent buffer", () => {
+ // Every frame scores exactly 0, so the tie-break is what decides. Keeping
+ // the earliest one pulled every cut back to `ideal - searchSec` — 5s chunks
+ // here instead of 10s, i.e. twice the requests and twice the seams, on the
+ // audio most likely to tie (a muted track, a gap between takes).
const samples = new Float32Array(60 * RATE);
const chunks = planChunks(samples, RATE, { targetSec: 10, searchSec: 5 });
+ expect(chunks.map((c) => c.endSample / RATE)).toEqual([10, 20, 30, 40, 50, 60]);
for (const chunk of chunks) {
expect(chunk.endSample).toBeGreaterThan(chunk.startSample);
}
- expect(chunks[chunks.length - 1].endSample).toBe(samples.length);
});
it("handles an empty buffer", () => {
expect(planChunks(new Float32Array(0), RATE)).toEqual([]);
});
+
+ it("makes progress even when the target is shorter than one energy frame", () => {
+ // Degenerate but reachable through the options: below one frame the scan has
+ // nothing to measure, and the boundary must still move or the loop spins.
+ const chunks = planChunks(new Float32Array(RATE), RATE, { targetSec: 0.001 });
+ for (const chunk of chunks) expect(chunk.endSample).toBeGreaterThan(chunk.startSample);
+ expect(chunks[chunks.length - 1].endSample).toBe(RATE);
+ });
});
diff --git a/electron/stt/chunking.ts b/electron/stt/chunking.ts
index 8ef743eca..5f36251da 100644
--- a/electron/stt/chunking.ts
+++ b/electron/stt/chunking.ts
@@ -50,14 +50,23 @@ export interface PlanChunksOptions {
const DEFAULT_TARGET_SEC = 90;
/**
- * Index of the quietest frame start in `[from, to)`. Both bounds are clamped by
- * the caller; returns `from` when the range holds less than one full frame.
+ * Index of the quietest frame start in `[from, to)`, breaking ties toward the
+ * frame nearest `preferred`. Both bounds are clamped by the caller; returns
+ * `from` when the range holds less than one full frame.
+ *
+ * The tie-break is not decoration. Digital silence — a muted track, a gap
+ * between takes — makes every frame in the window score exactly 0, and keeping
+ * the first one would pull every boundary back to `from`, i.e. shorten every
+ * chunk by the whole search window (90s → 87s by default, and 10s → 5s in the
+ * silent test case). That is extra requests and extra seams bought for nothing,
+ * against the very context loss `DEFAULT_TARGET_SEC` is sized to limit.
*/
function quietestFrameStart(
samples: Float32Array,
from: number,
to: number,
frameSamples: number,
+ preferred: number,
): number {
let bestStart = from;
let bestEnergy = Number.POSITIVE_INFINITY;
@@ -66,7 +75,10 @@ function quietestFrameStart(
for (let i = start; i < start + frameSamples; i++) {
energy += samples[i] * samples[i];
}
- if (energy < bestEnergy) {
+ if (
+ energy < bestEnergy ||
+ (energy === bestEnergy && Math.abs(start - preferred) < Math.abs(bestStart - preferred))
+ ) {
bestEnergy = energy;
bestStart = start;
}
@@ -85,12 +97,15 @@ export function planChunks(
options: PlanChunksOptions = {},
): SttChunkPlan[] {
if (samples.length === 0 || sampleRate <= 0) return [];
+ const frameSamples = Math.max(1, Math.round((FRAME_MS / 1000) * sampleRate));
+ // One frame is the floor: a target shorter than the unit the scan works in
+ // would put the ideal boundary BEFORE the earliest legal cut, which is the
+ // only way the loop below could fail to make progress.
const targetSamples = Math.max(
- 1,
+ frameSamples,
Math.round((options.targetSec ?? DEFAULT_TARGET_SEC) * sampleRate),
);
const searchSamples = Math.max(0, Math.round((options.searchSec ?? 3) * sampleRate));
- const frameSamples = Math.max(1, Math.round((FRAME_MS / 1000) * sampleRate));
const chunks: SttChunkPlan[] = [];
let start = 0;
@@ -105,8 +120,11 @@ export function planChunks(
// loop forever) and never past the end of the buffer.
const from = Math.max(start + frameSamples, ideal - searchSamples);
const to = Math.min(samples.length, ideal + searchSamples);
- const cut = to > from ? quietestFrameStart(samples, from, to, frameSamples) : ideal;
- const endSample = Math.min(samples.length, Math.max(from, cut));
+ // No clamping needed on either side: `ideal >= from` because `targetSamples`
+ // is at least one frame, and every value the scan can return lies in
+ // `[from, to)` — so the cut is always past `start` and inside the buffer.
+ const endSample =
+ to > from ? quietestFrameStart(samples, from, to, frameSamples, ideal) : ideal;
chunks.push({ startSample: start, endSample });
start = endSample;
}
diff --git a/electron/stt/index.test.ts b/electron/stt/index.test.ts
index 7e255c1ff..ad0eaf976 100644
--- a/electron/stt/index.test.ts
+++ b/electron/stt/index.test.ts
@@ -128,10 +128,16 @@ describe("SttManager", () => {
}
});
- it("pins later chunks to the language detected on the first one", async () => {
+ // Both spellings of "detect it for me". `"auto"` is the one the request
+ // contract documents, and it is truthy — which is exactly how it used to slip
+ // past the pin and let every chunk detect its own language.
+ it.each([
+ ["omitted", undefined] as const,
+ ["auto", "auto"] as const,
+ ])("pins later chunks to the language detected on the first one (%s)", async (_label, language) => {
const mgr = new SttManager();
await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
- await mgr.transcribe({ samples: new Float32Array(200 * 16000) });
+ await mgr.transcribe({ samples: new Float32Array(200 * 16000), language });
const languages = fakeWhisperServer.transcribe.mock.calls.map(([req]) => req.language);
expect(languages[0]).toBeUndefined();
expect(languages.slice(1).every((l) => l === "en")).toBe(true);
@@ -152,13 +158,40 @@ describe("SttManager", () => {
expect(fakeWhisperServer.start.mock.calls.length).toBeGreaterThan(1);
});
- it("fails the request when a chunk never succeeds", async () => {
+ it("fails the request when a chunk never succeeds, saying how far it got", async () => {
fakeWhisperServer.transcribe.mockRejectedValue(new Error("helper wedged"));
const mgr = new SttManager();
await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
- await expect(
- mgr.transcribe({ samples: new Float32Array(16000), language: "en" }),
- ).rejects.toThrow("helper wedged");
+ // 200s in, the failure is on chunk 2 of 3 — "Transcription failed" alone
+ // tells the user nothing about a recording this long.
+ await expect(mgr.transcribe({ samples: new Float32Array(200 * 16000) })).rejects.toThrow(
+ /transcription failed \d+s into a 200s recording \(chunk 1\/3\).*helper wedged/,
+ );
+ });
+
+ it("stops at the next chunk boundary when cancelled", async () => {
+ const mgr = new SttManager();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ // Cancel lands while the first chunk is in flight — the loop must not go on
+ // to the remaining ones, which is what left "regenerate" waiting on a run
+ // nobody wanted any more.
+ fakeWhisperServer.transcribe.mockImplementation(async () => {
+ mgr.cancel();
+ return {
+ segments: [],
+ wordSegments: [],
+ detectedLanguage: "en",
+ backend: "whispercpp-cpu" as const,
+ };
+ });
+ const samples = new Float32Array(300 * 16000);
+ expect(planChunks(samples, 16000).length).toBeGreaterThan(1);
+
+ const error = await mgr.transcribe({ samples }).catch((e: unknown) => e);
+ // `AbortError` by name, so the renderer treats it as "the user asked" and
+ // drops the job silently instead of toasting an engine failure.
+ expect((error as Error).name).toBe("AbortError");
+ expect(fakeWhisperServer.transcribe).toHaveBeenCalledOnce();
});
it("shutdown() stops whisper-stt-server", async () => {
@@ -188,12 +221,25 @@ describe("SttManager", () => {
expect(fakeWhisperServer.start).toHaveBeenCalledOnce();
});
- it("setStatusSink replaces the previous sink (last call wins)", () => {
+ it("fans status out to every sink, and detaching one leaves the others", async () => {
const mgr = new SttManager();
- const a = vi.fn();
- const b = vi.fn();
- mgr.setStatusSink(a);
- mgr.setStatusSink(b);
- expect(mgr.getStatusSink()).toBe(b);
+ const a = vi.fn<(e: SttStatusEvent) => void>();
+ const b = vi.fn<(e: SttStatusEvent) => void>();
+ await mgr.init({ modelsBaseDir: "/tmp/fake-stt-models" });
+ const detachA = mgr.addStatusSink(a);
+ mgr.addStatusSink(b);
+ await mgr.transcribe({ samples: new Float32Array(16000), language: "en" });
+ expect(a).toHaveBeenCalled();
+ expect(b).toHaveBeenCalled();
+
+ // The whole point of the Set. Two overlapping IPC requests each attach a
+ // sink; when the first finishes and detaches, the second must keep getting
+ // its own progress instead of falling silent for the rest of its run.
+ detachA();
+ a.mockClear();
+ b.mockClear();
+ await mgr.transcribe({ samples: new Float32Array(16000), language: "en" });
+ expect(a).not.toHaveBeenCalled();
+ expect(b).toHaveBeenCalled();
});
});
diff --git a/electron/stt/index.ts b/electron/stt/index.ts
index 3cd847c16..aaa597184 100644
--- a/electron/stt/index.ts
+++ b/electron/stt/index.ts
@@ -25,14 +25,15 @@ import { WhisperServerManager } from "./whisperServer";
* technical-documentation/architecture/transcription-and-captions.md § Decision rationale.
* 3. `shutdown()` tears down on app quit.
*
- * Status events fan out via `statusSink` so the renderer can drive its
+ * Status events fan out to every attached sink so the renderer can drive its
* "loading model" / "transcribing" indicator.
*
* Why chunked rather than one request: a 30-minute recording took ~10 minutes
* in a single `/inference` call — no progress to show, no way to recover from a
* transient failure without redoing everything, and long enough that the HTTP
* client's own header timeout killed it before whisper ever answered. Chunks
- * turn that into a progress signal and a retry unit.
+ * turn that into a progress signal, a retry unit, and — via `cancel()` — the
+ * only point where a run in flight can be stopped at all.
*
* Chunks run SEQUENTIALLY, and that is a measured choice, not an omission:
* whisper-stt-server holds a single model context, so concurrent `/inference`
@@ -50,6 +51,16 @@ const SAMPLE_RATE = 16_000;
/** Attempts per chunk before the whole transcription fails. */
const CHUNK_ATTEMPTS = 3;
+/**
+ * `AbortError` by name so the renderer's `isAbortError` recognizes it as "the
+ * user asked for this" rather than an engine failure worth a toast.
+ */
+function cancelledError(): Error {
+ const error = new Error("Transcription cancelled");
+ error.name = "AbortError";
+ return error;
+}
+
export interface SttManagerInitOptions {
statusSink?: (event: SttStatusEvent) => void;
/** Override the models cache directory; defaults to `app.getPath("userData") + "/stt-models"`. */
@@ -59,23 +70,48 @@ export interface SttManagerInitOptions {
export class SttManager {
private readonly server = new WhisperServerManager();
private modelsBaseDir: string | null = null;
- private statusSink: ((event: SttStatusEvent) => void) | null = null;
+ private readonly statusSinks = new Set<(event: SttStatusEvent) => void>();
private initPromise: Promise<void> | null = null;
/** Kept from `prepare()` so a chunk retry can respawn a helper that died mid-run. */
private modelPath: string | null = null;
+ /**
+ * Bumped by `cancel()`. The chunk loop compares it against the value it
+ * captured on entry, so a cancel that lands after a new run started cannot
+ * kill that new run.
+ */
+ private cancelEpoch = 0;
- /** Wire a sink for the renderer status channel. */
- setStatusSink(sink: ((event: SttStatusEvent) => void) | null): void {
- this.statusSink = sink;
+ /**
+ * Attach a sink for the renderer status channel; returns its detach function.
+ *
+ * A SET rather than one slot: this used to be a single field that each IPC
+ * invocation saved and restored, so with two overlapping transcriptions the
+ * first to finish restored the sink captured at ITS start and left the other
+ * one emitting into nothing — no progress for the rest of its run, which
+ * reads as a hang.
+ */
+ addStatusSink(sink: (event: SttStatusEvent) => void): () => void {
+ this.statusSinks.add(sink);
+ return () => {
+ this.statusSinks.delete(sink);
+ };
}
- /** Read the currently-installed status sink (mostly for tests). */
- getStatusSink(): ((event: SttStatusEvent) => void) | null {
- return this.statusSink;
+ private emit(event: SttStatusEvent): void {
+ for (const sink of this.statusSinks) sink(event);
}
- private emit(event: SttStatusEvent): void {
- this.statusSink?.(event);
+ /**
+ * Stop the in-flight transcription at the next chunk boundary.
+ *
+ * ponytail: one epoch for the whole manager, not a handle per request. The
+ * pipeline runs one transcription at a time by construction (the renderer's
+ * queue serializes, and `WhisperServerManager` single-flights on top), so
+ * "cancel what is running" is the only question anyone can ask. Per-request
+ * tokens the day two recordings can transcribe at once.
+ */
+ cancel(): void {
+ this.cancelEpoch++;
}
/**
@@ -83,7 +119,7 @@ export class SttManager {
* means the second caller just awaits the same completion.
*/
init(options: SttManagerInitOptions = {}): Promise<void> {
- if (options.statusSink) this.statusSink = options.statusSink;
+ if (options.statusSink) this.addStatusSink(options.statusSink);
if (options.modelsBaseDir) this.modelsBaseDir = options.modelsBaseDir;
if (!this.initPromise) {
// A REJECTED init must not be cached. `prepare()` downloads a 253 MB
@@ -135,8 +171,14 @@ export class SttManager {
* A failure here is usually the helper process dying (OOM, driver reset)
* rather than a bad chunk, so each retry first re-runs `server.start()` —
* idempotent when the helper is alive, a respawn when it isn't. That is what
- * makes a 30-minute transcription survive one bad minute instead of losing
- * the twenty that already succeeded.
+ * makes a 30-minute transcription survive a helper that dies once mid-run.
+ *
+ * What it does NOT do is salvage a chunk that fails all three attempts: the
+ * request fails whole and the chunks that already succeeded go with it. A
+ * transcript silently missing 90 seconds in the middle is worse than no
+ * transcript, since nothing downstream (captions, trims, the transcript
+ * editor) could tell the gap from a silence. The caller is told how far it
+ * got instead — see the wrapper in `transcribe()`.
*/
private async transcribeChunk(
samples: Float32Array,
@@ -162,6 +204,7 @@ export class SttManager {
async transcribe(req: SttTranscribeRequest): Promise<SttTranscribeResponse> {
await this.init();
+ const epoch = this.cancelEpoch;
const totalSec = req.samples.length / SAMPLE_RATE;
const chunks = planChunks(req.samples, SAMPLE_RATE);
this.emit({ phase: "transcribe", completedSec: 0, totalSec });
@@ -170,18 +213,52 @@ export class SttManager {
const wordSegments: SttWordSegment[] = [];
let detectedLanguage: string | null = null;
let backend = this.server.status.backend ?? "whispercpp-cpu";
- // Only the first chunk auto-detects. Every later chunk is forced onto that
- // language: whisper can otherwise flip mid-recording on a chunk that opens
- // with a proper noun or a silence, and "transcribe" the rest as another
- // language entirely.
- let language = req.language;
+ // Only the first chunk auto-detects; every later chunk is forced onto the
+ // language it resolved, so whisper cannot flip mid-recording on a chunk
+ // that opens with a proper noun or a silence and "transcribe" the rest as
+ // another language.
+ //
+ // `"auto"` must collapse to `undefined` here rather than merely falsy
+ // values: `SttTranscribeRequest` documents it as the explicit way to ask
+ // for detection, and it is TRUTHY — left in place it makes the pin below
+ // unreachable for every caller that spells its intent out.
+ //
+ // This depends on the helper reporting what it RESOLVED rather than
+ // echoing the request, which it only does since cc781806 (30/07/2026,
+ // `whisper_full_lang_id()` in electron/native/whisper-stt/src/main.cpp).
+ // A stale `electron/native/bin/<tag>/whisper-stt-server` — the directory
+ // is gitignored, so a dev tree keeps whatever was last staged there —
+ // silently reverts this to "every chunk detects on its own": the echo
+ // comes back as the literal "auto", the guard below rejects it, and
+ // nothing anywhere says why. `scripts/stage-whisper-stt.sh` refuses to
+ // overwrite a local binary by design, so it will not rescue you either.
+ // Verified end-to-end on 352s of real speech: `[undefined,"en","en","en"]`.
+ let language = req.language && req.language !== "auto" ? req.language : undefined;
- for (const chunk of chunks) {
+ for (const [index, chunk] of chunks.entries()) {
+ // Between chunks is the only place this loop can be interrupted, and it
+ // is enough: a chunk is bounded by `whisperServer`'s own request ceiling.
+ if (this.cancelEpoch !== epoch) throw cancelledError();
const offsetSec = chunk.startSample / SAMPLE_RATE;
const result = await this.transcribeChunk(
req.samples.subarray(chunk.startSample, chunk.endSample),
language,
- );
+ ).catch((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.
+ // `Object.assign` rather than the `{ cause }` constructor option: the
+ // project targets ES2020, where that overload does not exist (see
+ // `BackgroundLoadError` in src/lib/wallpaper.ts for the same dance).
+ throw Object.assign(
+ new Error(
+ `transcription failed ${Math.round(offsetSec)}s into a ${Math.round(totalSec)}s ` +
+ `recording (chunk ${index + 1}/${chunks.length}): ` +
+ `${error instanceof Error ? error.message : String(error)}`,
+ ),
+ { cause: error },
+ );
+ });
// Chunk-relative timestamps → absolute, the only thing every consumer
// (captions, transcript editor, trims) reads.
for (const segment of result.segments) {
@@ -214,7 +291,7 @@ export class SttManager {
return {
segments,
wordSegments,
- detectedLanguage: detectedLanguage ?? req.language ?? "auto",
+ detectedLanguage: detectedLanguage ?? language ?? "auto",
backend,
};
}
@@ -239,10 +316,11 @@ export function _resetSttManagerForTests(): void {
}
/**
- * Wire the IPC channel. Call this from `registerIpcHandlers` so the renderer
- * can `invoke("stt:transcribe", request)` and receive `SttTranscribeResponse`.
- * Status events fan out on `"stt:status"` (main → renderer push), scoped to
- * the calling `webContents` so two windows don't cross-talk.
+ * Wire the IPC channels. Call this from `registerIpcHandlers` so the renderer
+ * can `invoke("stt:transcribe", request)` and receive `SttTranscribeResponse`,
+ * and `invoke("stt:cancel")` to stop a run it no longer wants. Status events
+ * fan out on `"stt:status"` (main → renderer push), scoped to the calling
+ * `webContents` so two windows don't cross-talk.
*/
export function registerSttIpc(ipcMain: IpcMain): void {
const manager = getSttManager();
@@ -250,8 +328,9 @@ export function registerSttIpc(ipcMain: IpcMain): void {
"stt:transcribe",
async (event, req: SttTranscribeRequest): Promise<SttTranscribeResponse> => {
const senderId = event.sender.id;
- const previous = manager.getStatusSink();
- manager.setStatusSink((statusEvent) => {
+ // Attach for the life of THIS request only. Overlapping requests each
+ // own their own sink, so neither can silence the other on the way out.
+ const detach = manager.addStatusSink((statusEvent) => {
if (event.sender.id === senderId && !event.sender.isDestroyed()) {
event.sender.send("stt:status", statusEvent);
}
@@ -259,8 +338,11 @@ export function registerSttIpc(ipcMain: IpcMain): void {
try {
return await manager.transcribe(req);
} finally {
- manager.setStatusSink(previous);
+ detach();
}
},
);
+ ipcMain.handle("stt:cancel", () => {
+ manager.cancel();
+ });
}
diff --git a/electron/stt/whisperServer.ts b/electron/stt/whisperServer.ts
index 217a583ac..087073a2e 100644
--- a/electron/stt/whisperServer.ts
+++ b/electron/stt/whisperServer.ts
@@ -321,19 +321,43 @@ export class WhisperServerManager {
// error and its own header timeout as a bare "fetch failed", which is
// how a too-long request used to reach the user as an unactionable
// "Transcription failed" toast.
- const reason =
- error instanceof Error && error.name === "TimeoutError" ? "timed out" : "failed";
- throw new Error(
- `whisper-stt-server /inference ${reason} after ${Math.round(REQUEST_TIMEOUT_MS / 1000)}s ` +
- `(audio chunk too long for this machine, or the helper is wedged); ` +
- `stderr=${this.stderrTail.slice(-256)}`,
+ //
+ // The timeout wording is reserved for an ACTUAL timeout: a helper that
+ // died a moment ago rejects in a millisecond, and telling the reader it
+ // spent 280s on an over-long chunk sends them to the wrong problem
+ // entirely. Everything else carries its own message, plus `cause` so the
+ // errno survives.
+ // `Object.assign` rather than the `{ cause }` constructor option: the
+ // project targets ES2020, where that overload does not exist.
+ throw Object.assign(
+ new Error(
+ error instanceof Error && error.name === "TimeoutError"
+ ? `whisper-stt-server /inference timed out after ${Math.round(REQUEST_TIMEOUT_MS / 1000)}s ` +
+ `(audio chunk too long for this machine, or the helper is wedged); ` +
+ `stderr=${this.stderrTail.slice(-256)}`
+ : `whisper-stt-server /inference failed: ` +
+ `${error instanceof Error ? error.message : String(error)}; ` +
+ `stderr=${this.stderrTail.slice(-256)}`,
+ ),
+ { cause: error },
);
}
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`whisper-stt-server /inference HTTP ${res.status}: ${text.slice(0, 512)}`);
}
- return (await res.json()) as WhisperJsonResponse;
+ // The same timeout still covers the body: it can fire between the headers
+ // and the last byte, and an unnamed `AbortError` here would read exactly
+ // like the "fetch failed" this whole block exists to replace.
+ return (await res.json().catch((error: unknown) => {
+ throw Object.assign(
+ new Error(
+ `whisper-stt-server /inference response was unreadable: ` +
+ `${error instanceof Error ? error.message : String(error)}`,
+ ),
+ { cause: error },
+ );
+ })) as WhisperJsonResponse;
}
/** Defensive number parse for `verbose_json` values that may arrive as strings. */
diff --git a/src/lib/captioning/transcribe.ts b/src/lib/captioning/transcribe.ts
index 129949c22..0ac43da2b 100644
--- a/src/lib/captioning/transcribe.ts
+++ b/src/lib/captioning/transcribe.ts
@@ -47,6 +47,7 @@ interface RendererSttApi {
detectedLanguage: string;
backend: string;
}>;
+ cancel?: () => Promise<void>;
onStatus?: (callback: (event: SttRendererStatus) => void) => () => void;
}
@@ -80,6 +81,12 @@ export function transcribeMono16kToSegments(
}
const unsubscribe = options?.onStatus && api.onStatus?.((event) => options.onStatus?.(event));
+ // Aborting has to reach the MAIN process: the work is a chunk loop over there,
+ // and a renderer that merely stops awaiting still leaves the helper busy for
+ // minutes — with the replacement request queued behind it, which is what made
+ // "regenerate in another language" look dead.
+ const onAbort = () => void api.cancel?.();
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
const forcedLanguage =
options?.language && options.language !== "auto" ? options.language : undefined;
// ponytail: word timestamps come back already absolute from whisper.cpp
@@ -115,7 +122,15 @@ export function transcribeMono16kToSegments(
}
return { segments, granularity, detectedLanguage: result.detectedLanguage };
})
+ .catch((error: unknown) => {
+ // A run the caller cancelled surfaces as an abort, not as an engine
+ // failure: the store drops it silently instead of toasting the user
+ // about something they asked for.
+ if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");
+ throw error;
+ })
.finally(() => {
+ options?.signal?.removeEventListener("abort", onAbort);
unsubscribe?.();
});
}