Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(notes): abort local transcription and diarization when an upload is cancelled — fixes #1401
Gabriel Stein7bbc04c4ad34
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsxindex c4333171c..a228c13ca 100644--- a/src/components/notes/UploadAudioView.tsx+++ b/src/components/notes/UploadAudioView.tsx@@ -590,8 +590,8 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa};const cancelTranscription = () => {- // True backend abort for cloud uploads; the run-id bump still discards any- // late result from providers that can't be aborted.+ // True backend abort for cloud and local uploads; the run-id bump still+ // discards any late result from providers that can't be aborted (BYOK).if (activeRequestIdRef.current) {window.electronAPI.cancelUploadTranscription?.(activeRequestIdRef.current);activeRequestIdRef.current = null;diff --git a/src/helpers/diarization.js b/src/helpers/diarization.jsindex f8906a0d5..53fe0effe 100644--- a/src/helpers/diarization.js+++ b/src/helpers/diarization.js@@ -284,7 +284,9 @@ class DiarizationManager {}async diarize(wavPath, options = {}) {- const { numSpeakers = -1, threshold = 0.55 } = options;+ const { numSpeakers = -1, threshold = 0.55, signal = null } = options;++ if (signal?.aborted) return [];const binaryPath = this.getBinaryPath();if (!binaryPath) {@@ -361,6 +363,15 @@ class DiarizationManager {resolve([]);}, timeoutMs);+ // A cancelled upload kills the child immediately (same stop the timeout+ // path uses); the close handler below still fires and cleans up.+ const onAbort = () => {+ debugLogger.info("Diarization cancelled, stopping process");+ gracefulStopProcess(proc);+ resolve([]);+ };+ signal?.addEventListener("abort", onAbort, { once: true });+proc.stdout.on("data", (data) => {stdout += data.toString();});@@ -371,6 +382,7 @@ class DiarizationManager {proc.on("close", (code) => {clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);untrack();if (code !== 0) {@@ -389,6 +401,7 @@ class DiarizationManager {proc.on("error", (err) => {clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);untrack();debugLogger.warn("Diarization process error", { error: err.message });resolve([]);diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 00df09ea5..f73e3c267 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -142,6 +142,7 @@ const CLOUD_INLINE_LIMIT = 4 * 1024 * 1024;const CLOUD_CHUNK_SEGMENT_SECONDS = 240;const { createAbortError } = require("./abortError");+const { createUploadCancelRegistry } = require("./uploadCancelRegistry");const { applyOpenWhisprOriginHeader } = require("./sessionHeaders");const {CLOUD_UPLOAD_TIMEOUT_MS,@@ -559,9 +560,10 @@ class IPCHandlers {this.oauthProtocolRegistered = managers.oauthProtocolRegistered === true;this.oauthProtocol = managers.oauthProtocol || "openwhispr";this.sessionId = crypto.randomUUID();- // requestId -> AbortController for in-flight audio-upload transcriptions,- // so a cancel can abort the exact job.- this._uploadTranscriptionControllers = new Map();+ // requestId -> AbortControllers for in-flight audio-upload work (cloud+ // upload, or local transcription + diarization sharing one id), so a+ // cancel can abort the exact job.+ this._uploadCancelRegistry = createUploadCancelRegistry();// webContents id -> its release listener, for renderers holding the mic open.this._micHoldSenders = new Map();this.assemblyAiStreaming = null;@@ -2392,6 +2394,9 @@ class IPCHandlers {ipcMain.handle("transcribe-audio-file", async (event, filePath, options = {}) => {const fs = require("fs");+ // Uploads pass a requestId so cancel-upload-transcription can abort the+ // local decode; flows without one (voice drafts) register nothing.+ const { signal, release } = this._uploadCancelRegistry.register(options.requestId);try {if (typeof filePath !== "string") {return { success: false, error: "Invalid file path" };@@ -2400,18 +2405,30 @@ class IPCHandlers {if (!real) return { success: false, error: "File path not allowed" };const audioBuffer = fs.readFileSync(real);if (options.provider === "nvidia") {- const result = await this.parakeetManager.transcribeLocalParakeet(audioBuffer, options);+ const result = await this.parakeetManager.transcribeLocalParakeet(audioBuffer, {+ ...options,+ signal,+ });return result;}const vadOptions = this._resolveWhisperVadOptions("noteRecording");const result = await this.whisperManager.transcribeLocalWhisper(audioBuffer, {...options,...vadOptions,+ signal,});return result;} catch (error) {+ if (error?.name === "AbortError" || signal?.aborted) {+ debugLogger.debug("Local audio file transcription cancelled", {+ requestId: options.requestId,+ });+ return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };+ }debugLogger.error("Audio file transcription error", { error: error.message });return { success: false, error: error.message };+ } finally {+ release();}});@@ -3089,6 +3106,9 @@ class IPCHandlers {});ipcMain.handle("diarize-audio-file", async (event, filePath, options = {}) => {+ // Registered under the same requestId as the upload's transcription, so+ // one cancel kills both the decode and the diarization child process.+ const { signal, release } = this._uploadCancelRegistry.register(options.requestId);try {if (!this.diarizationManager) {return { success: false, error: "Diarization not available" };@@ -3117,12 +3137,22 @@ class IPCHandlers {try {await convertToWav(filePath, wavPath, { sampleRate: 16000, channels: 1 });+ if (signal?.aborted) {+ return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };+ }// Auto-clustering over-splits long single-mic audio at the 0.55// default, so the threshold ramps with duration unless pinned.const durationSeconds = fs.statSync(wavPath).size / PCM16_MONO_16K_BYTES_PER_SECOND;const threshold = resolveClusterThreshold(durationSeconds, options.threshold);- let segments = await this.diarizationManager.diarize(wavPath, { numSpeakers, threshold });+ let segments = await this.diarizationManager.diarize(wavPath, {+ numSpeakers,+ threshold,+ signal,+ });+ if (signal?.aborted) {+ return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };+ }// The meeting path caps clusters via its expectation resolver; this// path fed raw sherpa output to the merge, which is how a 2-person// voice memo surfaced 46 speakers.@@ -3140,8 +3170,14 @@ class IPCHandlers {} catch {}}} catch (error) {+ if (error?.name === "AbortError" || signal?.aborted) {+ debugLogger.debug("Diarization cancelled", { requestId: options.requestId });+ return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };+ }debugLogger.error("Diarization error", { error: error.message });return { success: false, error: error.message };+ } finally {+ release();}});@@ -8189,8 +8225,7 @@ class IPCHandlers {ipcMain.handle("transcribe-audio-file-cloud", async (event, filePath, opts = {}) => {const requestId = typeof opts?.requestId === "string" ? opts.requestId : null;- const controller = new AbortController();- if (requestId) this._uploadTranscriptionControllers.set(requestId, controller);+ const { signal, release } = this._uploadCancelRegistry.register(requestId);try {if (typeof filePath !== "string") {return { success: false, error: "Invalid file path" };@@ -8225,7 +8260,7 @@ class IPCHandlers {policyHeaders: withPolicyHeaders(authHeader),multipartFields,onProgress: (payload) => event.sender.send("upload-transcription-progress", payload),- signal: controller.signal,+ signal,});return {success: true,@@ -8248,7 +8283,7 @@ class IPCHandlers {const url = new URL(`${apiUrl}/api/transcribe`);const data = await postMultipart(url, body, boundary, withPolicyHeaders(authHeader), {signal: AbortSignal.any([- controller.signal,+ ...(signal ? [signal] : []),AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),]),session: getInlineCloudUploadSession(),@@ -8257,23 +8292,21 @@ class IPCHandlers {return { success: true, text: result.text };} catch (error) {- if (controller.signal.aborted) {+ if (signal?.aborted) {debugLogger.debug("Cloud audio file transcription cancelled", { requestId });return { success: false, error: "Cancelled", code: "UPLOAD_CANCELLED" };}debugLogger.error("Cloud audio file transcription error", { error: error.message });return toPolicyFailure(error);} finally {- if (requestId) this._uploadTranscriptionControllers.delete(requestId);+ release();}});- // Unknown ids are a no-op: providers other than OpenWhispr cloud don't- // register a controller, and the renderer fires this for every cancel.+ // Unknown ids are a no-op: BYOK providers don't register a controller,+ // and the renderer fires this for every cancel.ipcMain.handle("cancel-upload-transcription", async (_event, requestId) => {- const controller = this._uploadTranscriptionControllers.get(requestId);- controller?.abort();- return { success: !!controller };+ return { success: this._uploadCancelRegistry.cancel(requestId) > 0 };});ipcMain.handle(diff --git a/src/helpers/parakeet.js b/src/helpers/parakeet.jsindex a18d61c7b..cd4547882 100644--- a/src/helpers/parakeet.js+++ b/src/helpers/parakeet.js@@ -240,7 +240,10 @@ class ParakeetManager {});const startTime = Date.now();- const result = await this.serverManager.transcribe(audioBuffer, { modelName: model });+ const result = await this.serverManager.transcribe(audioBuffer, {+ modelName: model,+ signal: options.signal,+ });const elapsed = Date.now() - startTime;debugLogger.logSTTPipeline("transcribeLocalParakeet - completed", {diff --git a/src/helpers/parakeetServer.js b/src/helpers/parakeetServer.jsindex 5cc0ce1db..4ae620417 100644--- a/src/helpers/parakeetServer.js+++ b/src/helpers/parakeetServer.js@@ -11,6 +11,7 @@ const {computeFloat32RMS,} = require("./ffmpegUtils");const { getSafeTempDir } = require("./safeTempDir");+const { createAbortError } = require("./abortError");const ParakeetWsServer = require("./parakeetWsServer");const { getModelRuntime, REQUIRED_MODEL_FILES } = require("./parakeetModelInfo");@@ -88,7 +89,12 @@ class ParakeetServerManager {}async transcribe(audioBuffer, options = {}) {- const { modelName = "parakeet-tdt-0.6b-v3" } = options;+ // signal is optional; only cancellable uploads pass one. Aborting stops+ // scheduling further segments — the in-flight one finishes server-side.+ const { modelName = "parakeet-tdt-0.6b-v3", signal } = options;+ const throwIfAborted = () => {+ if (signal?.aborted) throw createAbortError("Parakeet transcription cancelled");+ };const modelDir = path.join(this.getModelsDir(), modelName);if (!this.isModelDownloaded(modelName)) {@@ -103,6 +109,7 @@ class ParakeetServerManager {const { wavBuffer, filesToCleanup } = await this._ensureWav(audioBuffer);try {+ throwIfAborted();const runtime = getModelRuntime(modelName);// Awaiting unconditionally also covers a startup's warm-up completion.await this.wsServer.start(modelName, modelDir, runtime);@@ -121,8 +128,9 @@ class ParakeetServerManager {const maxSegmentBytes = maxSegmentSeconds * SAMPLE_RATE * BYTES_PER_SAMPLE;if (samples.length <= maxSegmentBytes) {- const result = await this.wsServer.transcribe(samples, SAMPLE_RATE);+ const result = await this.wsServer.transcribe(samples, SAMPLE_RATE, { signal });if (result.text?.trim()) return result;+ throwIfAborted();// The RMS gate above already established audible audio, so an empty// decode here loses the whole dictation — retry once before giving up.debugLogger.warn("Parakeet returned empty text for non-silent audio, retrying", {@@ -130,7 +138,7 @@ class ParakeetServerManager {rms,samplesBytes: samples.length,});- const retry = await this.wsServer.transcribe(samples, SAMPLE_RATE);+ const retry = await this.wsServer.transcribe(samples, SAMPLE_RATE, { signal });return { ...retry, elapsed: (result.elapsed || 0) + (retry.elapsed || 0) };}@@ -144,18 +152,20 @@ class ParakeetServerManager {let truncated = false;for (let offset = 0; offset < samples.length; offset += maxSegmentBytes) {+ throwIfAborted();const end = Math.min(offset + maxSegmentBytes, samples.length);const segment = samples.subarray(offset, end);- let result = await this.wsServer.transcribe(segment, SAMPLE_RATE);+ let result = await this.wsServer.transcribe(segment, SAMPLE_RATE, { signal });totalElapsed += result.elapsed || 0;if (!result.text && computeFloat32RMS(segment) >= SILENCE_RMS_THRESHOLD) {+ throwIfAborted();// An empty decode of audible audio silently amputates the transcript// (#1435: dictation openings dropped); retry once before conceding.debugLogger.warn("Parakeet segment returned empty text, retrying", {segmentIndex: offset / maxSegmentBytes,segmentDuration: segment.length / BYTES_PER_SAMPLE / SAMPLE_RATE,});- result = await this.wsServer.transcribe(segment, SAMPLE_RATE);+ result = await this.wsServer.transcribe(segment, SAMPLE_RATE, { signal });totalElapsed += result.elapsed || 0;if (!result.text) {truncated = true;diff --git a/src/helpers/parakeetWsServer.js b/src/helpers/parakeetWsServer.jsindex 7fec46d73..1a773dcd5 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 { createAbortError } = require("./abortError");const sidecarPidFile = require("./sidecarPidFile");const { parseOfflineMessage, createOnlineAccumulator } = require("./parakeetWsResult");const { pcm16ToFloat32 } = require("../utils/audioUtils");@@ -253,24 +254,30 @@ class ParakeetWsServer {}}- transcribe(samplesBuffer, sampleRate) {+ // signal is optional; dictation and warm-up flows never pass one.+ transcribe(samplesBuffer, sampleRate, { signal } = {}) {if (!this.ready || !this.process) {throw new Error("parakeet-ws server is not running");}if (this.modelRuntime === "online") {- return this._transcribeOnline(samplesBuffer);+ return this._transcribeOnline(samplesBuffer, signal);}- return this._transcribeOffline(samplesBuffer, sampleRate);+ return this._transcribeOffline(samplesBuffer, sampleRate, signal);}- _transcribeOffline(samplesBuffer, sampleRate) {+ _transcribeOffline(samplesBuffer, sampleRate, signal) {const timeoutMs = computeTranscriptionTimeoutMs(samplesBuffer.length / FLOAT32_BYTES_PER_SAMPLE / sampleRate);return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(createAbortError("parakeet-ws transcription cancelled"));+ return;+ }+const startTime = Date.now();let result = "";@@ -283,6 +290,17 @@ class ParakeetWsServer {const ws = new WebSocket(`ws://127.0.0.1:${this.port}`);+ // Closing the socket drops this request; the server finishes its+ // in-flight decode of the segment on its own (bounded by the 15s cap).+ const onAbort = () => {+ clearTimeout(timeout);+ try {+ ws.close();+ } catch {}+ reject(createAbortError("parakeet-ws transcription cancelled"));+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ws.on("open", () => {// sherpa-onnx offline WS binary protocol:// [int32LE sample_rate][int32LE num_audio_bytes][float32 samples...]@@ -310,6 +328,7 @@ class ParakeetWsServer {ws.on("close", (code) => {clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);const elapsed = Date.now() - startTime;// The offline server always sends one result message (even for silence),@@ -331,13 +350,16 @@ class ParakeetWsServer {ws.on("error", (error) => {clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);reject(new Error(`parakeet-ws transcription failed: ${error.message}`));});});}// samplesBuffer must already be 16kHz float32.- async _transcribeOnline(samplesBuffer) {+ async _transcribeOnline(samplesBuffer, signal) {+ if (signal?.aborted) throw createAbortError("parakeet-ws transcription cancelled");+const startTime = Date.now();let streamError = null;let timedOut = false;@@ -365,9 +387,12 @@ class ParakeetWsServer {},Math.max(TRANSCRIPTION_TIMEOUT_FLOOR_MS, audioSeconds * ONLINE_TIMEOUT_PER_AUDIO_SECOND_MS));+ const onAbort = () => stream.abort();+ signal?.addEventListener("abort", onAbort, { once: true });try {const idleTimeoutMs = Math.max(ONLINE_FINISH_IDLE_TIMEOUT_MS, audioSeconds * 500);const { text, truncated } = await stream.finish({ idleTimeoutMs });+ if (signal?.aborted) throw createAbortError("parakeet-ws transcription cancelled");if (timedOut) throw new Error("parakeet-ws transcription timed out");if (streamError) {throw new Error(`parakeet-ws transcription failed: ${streamError.message}`);@@ -383,6 +408,7 @@ class ParakeetWsServer {return truncated ? { text, elapsed, truncated } : { text, elapsed };} finally {clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);}}diff --git a/src/helpers/uploadCancelRegistry.js b/src/helpers/uploadCancelRegistry.jsnew file mode 100644index 000000000..f1974a434--- /dev/null+++ b/src/helpers/uploadCancelRegistry.js@@ -0,0 +1,49 @@+// In-flight audio-upload work keyed by requestId, so one cancel aborts every+// operation the upload spawned (transcription and diarization run in parallel+// under the same id). Pure seam: no Electron imports, unit-tested in+// test/helpers/uploadCancelRegistry.test.js.+function createUploadCancelRegistry() {+ // requestId -> Set<AbortController>, one controller per in-flight operation.+ const controllers = new Map();++ return {+ // Registers one operation. Missing/invalid ids are inert — flows without a+ // requestId (dictation, voice drafts, warm-ups) get no signal and a no-op+ // release, so their behavior is untouched.+ register(requestId) {+ if (typeof requestId !== "string" || !requestId) {+ return { signal: undefined, release: () => {} };+ }+ let set = controllers.get(requestId);+ if (!set) {+ set = new Set();+ controllers.set(requestId, set);+ }+ const controller = new AbortController();+ set.add(controller);+ return {+ signal: controller.signal,+ release: () => {+ set.delete(controller);+ // Guard against deleting a successor set registered after a cancel.+ if (set.size === 0 && controllers.get(requestId) === set) {+ controllers.delete(requestId);+ }+ },+ };+ },++ // Aborts every operation registered under the id and returns how many were+ // aborted. Unknown or already-finished ids are a safe no-op — the renderer+ // fires a cancel for every provider, including ones that never register.+ cancel(requestId) {+ const set = controllers.get(requestId);+ if (!set) return 0;+ controllers.delete(requestId);+ for (const controller of set) controller.abort();+ return set.size;+ },+ };+}++module.exports = { createUploadCancelRegistry };diff --git a/src/helpers/whisper.js b/src/helpers/whisper.jsindex 1709a5922..e2b9af9f0 100644--- a/src/helpers/whisper.js+++ b/src/helpers/whisper.js@@ -388,6 +388,7 @@ class WhisperManager {return await this.transcribeViaServer(audioBlob, model, language, initialPrompt, {vadEnabled,vadConfig,+ signal: options.signal,});}@@ -447,7 +448,11 @@ class WhisperManager {});const startTime = Date.now();- const result = await this.serverManager.transcribe(audioBuffer, { language, initialPrompt });+ const result = await this.serverManager.transcribe(audioBuffer, {+ language,+ initialPrompt,+ signal: options.signal,+ });const elapsed = Date.now() - startTime;debugLogger.logWhisperPipeline("transcribeViaServer - completed", {diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.jsindex ca8e8746f..5d678dcc1 100644--- a/src/helpers/whisperServer.js+++ b/src/helpers/whisperServer.js@@ -10,6 +10,7 @@ const { killProcess } = require("../utils/process");const { isPortAvailable } = require("../utils/serverUtils");const { getSafeTempDir } = require("./safeTempDir");const { convertToWav } = require("./ffmpegUtils");+const { createAbortError } = require("./abortError");const sidecarPidFile = require("./sidecarPidFile");const { BIN_SUBDIR: CUDA_BIN_SUBDIR } = require("./whisperCudaManager");const { BIN_SUBDIR: VULKAN_BIN_SUBDIR } = require("./whisperVulkanManager");@@ -826,7 +827,9 @@ class WhisperServerManager extends EventEmitter {: "too short",});- const { language, initialPrompt } = options;+ // signal is optional; only cancellable uploads pass one.+ const { language, initialPrompt, signal } = options;+ if (signal?.aborted) throw createAbortError("whisper-server transcription cancelled");// Always convert to 16kHz mono WAV - whisper.cpp requires this exact formatlet finalBuffer = audioBuffer;@@ -878,17 +881,25 @@ class WhisperServerManager extends EventEmitter {const modelPath = this.modelPath;try {- return await this._postInference(body, boundary);+ return await this._postInference(body, boundary, signal);} catch (err) {+ // A cancel is not a server failure: rethrow before the retry/CPU-fallback+ // logic so it never triggers a server restart.+ if (err?.name === "AbortError") throw err;return await this._retryAfterRequestFailure(err, body, boundary, generation, modelPath);}}- _postInference(body, boundary) {+ _postInference(body, boundary, signal) {// Multipart boilerplate adds under a kilobyte, so body length tracks audio length.const timeoutMs = computeTranscriptionTimeoutMs(body.length / PCM16_MONO_16K_BYTES_PER_SECOND);return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(createAbortError("whisper-server request cancelled"));+ return;+ }+const startTime = Date.now();const req = http.request(@@ -909,6 +920,7 @@ class WhisperServerManager extends EventEmitter {data += chunk;});res.on("end", () => {+ removeAbortListener();debugLogger.debug("whisper-server transcription completed", {statusCode: res.statusCode,elapsed: Date.now() - startTime,@@ -930,13 +942,25 @@ class WhisperServerManager extends EventEmitter {});+ // whisper-server has no mid-inference cancellation: destroying the+ // request frees this pipeline immediately, but the server finishes its+ // in-flight decode on its own.+ const onAbort = () => {+ req.destroy();+ reject(createAbortError("whisper-server request cancelled"));+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ const removeAbortListener = () => signal?.removeEventListener("abort", onAbort);+req.on("error", (error) => {+ removeAbortListener();const err = new Error(`whisper-server request failed: ${error.message}`);err.isConnectionError = true;err.code = error.code;reject(err);});req.on("timeout", () => {+ removeAbortListener();req.destroy();reject(new Error("whisper-server request timed out"));});diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.tsindex 9e2024765..ce870ffc6 100644--- a/src/services/fileTranscription.ts+++ b/src/services/fileTranscription.ts@@ -94,6 +94,7 @@ export async function transcribeFile(return window.electronAPI.transcribeAudioFile(filePath, {provider: cfg.localTranscriptionProvider as "whisper" | "nvidia",model: cfg.localTranscriptionProvider === "nvidia" ? cfg.parakeetModel : cfg.whisperModel,+ requestId: opts.requestId,});}@@ -169,6 +170,7 @@ export async function transcribeFileWithSpeakers(? (window.electronAPI.diarizeAudioFile?.(filePath, {numSpeakers: diarization.numSpeakers ?? undefined,+ requestId: opts.requestId,}).catch(() => null) ?? Promise.resolve(null)): Promise.resolve(null);diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.tsindex dac4b3da9..b73bf4f9e 100644--- a/src/stores/batchQueueStore.ts+++ b/src/stores/batchQueueStore.ts@@ -44,10 +44,11 @@ export const useBatchQueueStore = create<BatchQueueStoreState>()(() => ({isProcessing: false,}));-// Bumping the run id soft-cancels the drain loop; cloud uploads additionally-// get a true backend abort via cancel-upload-transcription (other providers'-// in-flight IPC still can't be aborted). Either way the orphaned run's late-// results are discarded on arrival while the UI unlocks immediately.+// Bumping the run id soft-cancels the drain loop; cloud and local uploads+// additionally get a true backend abort via cancel-upload-transcription+// (BYOK providers' in-flight IPC still can't be aborted). Either way the+// orphaned run's late results are discarded on arrival while the UI unlocks+// immediately.let runId = 0;let activeUploadRequestId: string | null = null;diff --git a/src/types/electron.ts b/src/types/electron.tsindex 771ef09bb..0e49ab2fc 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -1244,9 +1244,10 @@ declare global {provider?: "whisper" | "nvidia";model?: string;language?: string;+ requestId?: string;[key: string]: unknown;}- ) => Promise<{ success: boolean; text?: string; error?: string }>;+ ) => Promise<{ success: boolean; text?: string; error?: string; code?: string }>;getPathForFile: (file: File) => string;// URL audio download@@ -2449,12 +2450,13 @@ declare global {) => Promise<{ success: boolean; text?: string; error?: string }>;diarizeAudioFile?: (filePath: string,- options?: { numSpeakers?: number; threshold?: number }+ options?: { numSpeakers?: number; threshold?: number; requestId?: string }) => Promise<{success: boolean;segments?: Array<{ start: number; end: number; speaker: string }>;durationSeconds?: number;error?: string;+ code?: string;}>;onDiarizationDownloadProgress?: (callback: (data: any) => void) => () => void;onMeetingDiarizationComplete?: (diff --git a/test/helpers/parakeetOnlineStream.test.js b/test/helpers/parakeetOnlineStream.test.jsindex 2a77652a5..20428278c 100644--- a/test/helpers/parakeetOnlineStream.test.js+++ b/test/helpers/parakeetOnlineStream.test.js@@ -242,6 +242,64 @@ test("finish is idempotent and returns the same result", async () => {}});+test("offline transcription rejects with AbortError when cancelled mid-flight", async () => {+ const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });+ await once(wss, "listening");+ const controller = new AbortController();+ // The server holds the request open; only the abort can settle it.+ wss.on("connection", () => controller.abort());++ try {+ const server = onlineWsServerAt(wss.address().port);+ server.modelRuntime = "offline";+ await assert.rejects(+ () => server.transcribe(Buffer.alloc(3200), 16000, { signal: controller.signal }),+ (err) => {+ assert.equal(err.name, "AbortError");+ return true;+ }+ );+ } finally {+ await new Promise((resolve) => wss.close(resolve));+ }+});++test("offline transcription rejects immediately on a pre-aborted signal", async () => {+ const controller = new AbortController();+ controller.abort();++ const server = onlineWsServerAt(1);+ server.modelRuntime = "offline";+ await assert.rejects(+ () => server.transcribe(Buffer.alloc(3200), 16000, { signal: controller.signal }),+ (err) => {+ assert.equal(err.name, "AbortError");+ return true;+ }+ );+});++test("online transcription rejects with AbortError when cancelled mid-flight", async () => {+ // The server never acknowledges Done, so only the abort settles the stream.+ const mock = await startMockOnlineServer({});+ mock.ignoreDone();++ try {+ const server = onlineWsServerAt(mock.port);+ const controller = new AbortController();+ setTimeout(() => controller.abort(), 20);+ await assert.rejects(+ () => server.transcribe(Buffer.alloc(3200), 16000, { signal: controller.signal }),+ (err) => {+ assert.equal(err.name, "AbortError");+ return true;+ }+ );+ } finally {+ await mock.close();+ }+});+test("offline transcription rejects when the connection closes without a result", async () => {const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });await once(wss, "listening");diff --git a/test/helpers/parakeetServer.test.js b/test/helpers/parakeetServer.test.jsindex a24526412..7cc77d88f 100644--- a/test/helpers/parakeetServer.test.js+++ b/test/helpers/parakeetServer.test.js@@ -35,7 +35,7 @@ function wavFromSeconds(spans) {return buf;}-function fakeWsServer(responses) {+function fakeWsServer(responses, { onCall } = {}) {const calls = [];return {calls,@@ -44,11 +44,17 @@ function fakeWsServer(responses) {calls.push(samplesBuffer.length);const next = responses.shift();assert.ok(next, "unexpected extra transcribe call");+ onCall?.(calls.length);return { elapsed: 1, ...next };},};}+function isAbortError(err) {+ assert.equal(err.name, "AbortError");+ return true;+}+function managerWith(fake) {const manager = new ParakeetServerManager();manager.isModelDownloaded = () => true;@@ -124,3 +130,54 @@ test("a silent segment decoding to empty is not retried or flagged", async () =>assert.ok(!result.truncated, "silence is not data loss");assert.equal(fake.calls.length, 3);});++test("a pre-aborted signal rejects before any decode is issued", async () => {+ const fake = fakeWsServer([]);+ const manager = managerWith(fake);+ const controller = new AbortController();+ controller.abort();++ await assert.rejects(+ () => manager.transcribe(wavFromSeconds([{ seconds: 10 }]), { signal: controller.signal }),+ isAbortError+ );+ assert.equal(fake.calls.length, 0);+});++test("an abort during the first segment stops the segment loop", async () => {+ const controller = new AbortController();+ const fake = fakeWsServer([{ text: "one" }, { text: "two" }, { text: "three" }], {+ onCall: () => controller.abort(),+ });+ const manager = managerWith(fake);++ await assert.rejects(+ () => manager.transcribe(wavFromSeconds([{ seconds: 31 }]), { signal: controller.signal }),+ isAbortError+ );+ assert.equal(fake.calls.length, 1, "no further segments may be scheduled after the abort");+});++test("an abort between an empty decode and its retry suppresses the retry", async () => {+ const controller = new AbortController();+ const fake = fakeWsServer([{ text: "" }, { text: "recovered" }], {+ onCall: () => controller.abort(),+ });+ const manager = managerWith(fake);++ await assert.rejects(+ () => manager.transcribe(wavFromSeconds([{ seconds: 10 }]), { signal: controller.signal }),+ isAbortError+ );+ assert.equal(fake.calls.length, 1, "the empty-decode retry must not run after a cancel");+});++test("transcribe without a signal is unchanged", async () => {+ const fake = fakeWsServer([{ text: "one" }, { text: "two" }, { text: "three" }]);+ const manager = managerWith(fake);++ const result = await manager.transcribe(wavFromSeconds([{ seconds: 31 }]));++ assert.equal(result.text, "one two three");+ assert.equal(fake.calls.length, 3);+});diff --git a/test/helpers/uploadCancelRegistry.test.js b/test/helpers/uploadCancelRegistry.test.jsnew file mode 100644index 000000000..11184f397--- /dev/null+++ b/test/helpers/uploadCancelRegistry.test.js@@ -0,0 +1,85 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { createUploadCancelRegistry } = require("../../src/helpers/uploadCancelRegistry");++test("cancel aborts every operation registered under one requestId", () => {+ const registry = createUploadCancelRegistry();+ const transcribe = registry.register("req-1");+ const diarize = registry.register("req-1");++ const aborted = registry.cancel("req-1");++ assert.equal(aborted, 2);+ assert.equal(transcribe.signal.aborted, true);+ assert.equal(diarize.signal.aborted, true);+});++test("release removes only its own controller", () => {+ const registry = createUploadCancelRegistry();+ const first = registry.register("req-1");+ const second = registry.register("req-1");++ first.release();+ const aborted = registry.cancel("req-1");++ assert.equal(aborted, 1);+ assert.equal(first.signal.aborted, false);+ assert.equal(second.signal.aborted, true);+});++test("releasing every operation makes a later cancel a no-op", () => {+ const registry = createUploadCancelRegistry();+ const first = registry.register("req-1");+ const second = registry.register("req-1");++ first.release();+ second.release();++ assert.equal(registry.cancel("req-1"), 0);+ assert.equal(first.signal.aborted, false);+ assert.equal(second.signal.aborted, false);+});++test("cancel of an unknown id is a no-op", () => {+ const registry = createUploadCancelRegistry();+ assert.equal(registry.cancel("never-registered"), 0);+});++test("register without a requestId is inert", () => {+ const registry = createUploadCancelRegistry();++ for (const id of [undefined, null, "", 42]) {+ const { signal, release } = registry.register(id);+ assert.equal(signal, undefined);+ assert.doesNotThrow(release);+ }+ assert.equal(registry.cancel(undefined), 0);+});++test("double release is safe", () => {+ const registry = createUploadCancelRegistry();+ const first = registry.register("req-1");+ const second = registry.register("req-1");++ first.release();+ first.release();++ assert.equal(registry.cancel("req-1"), 1);+ assert.equal(second.signal.aborted, true);+});++test("a registration after cancel starts a fresh set for the same id", () => {+ const registry = createUploadCancelRegistry();+ const first = registry.register("req-1");+ registry.cancel("req-1");++ const second = registry.register("req-1");+ assert.equal(second.signal.aborted, false);++ assert.equal(registry.cancel("req-1"), 1);+ assert.equal(second.signal.aborted, true);++ // The pre-cancel registration's release must not disturb the successor set.+ assert.doesNotThrow(() => first.release());+});diff --git a/test/helpers/whisperCudaRequestFallback.test.js b/test/helpers/whisperCudaRequestFallback.test.jsindex 65f4c4cd5..c8aa88789 100644--- a/test/helpers/whisperCudaRequestFallback.test.js+++ b/test/helpers/whisperCudaRequestFallback.test.js@@ -604,6 +604,68 @@ test("rejects immediately for a CPU server without waiting for process exit", asassert.equal(fallbackEvents, 0);});+test("an aborted request rejects with AbortError and never triggers CPU fallback", async (t) => {+ let manager;+ const controller = new AbortController();+ const gotRequest = createDeferred();++ const { server, port } = await startServer(() => {+ // Hold the request open and simulate the crash-like state that would arm+ // the fallback path if the abort were treated as a connection error.+ manager.process = null;+ gotRequest.resolve();+ });+ t.after(() => server.close());++ manager = createManager(port, { useCuda: true });++ let startCalled = false;+ manager.start = async () => {+ startCalled = true;+ };++ let fallbackEvents = 0;+ manager.on("cuda-fallback", () => {+ fallbackEvents += 1;+ });++ const pending = assert.rejects(+ () => manager.transcribe(Buffer.from("audio"), { signal: controller.signal }),+ (err) => {+ assert.equal(err.name, "AbortError");+ return true;+ }+ );+ await gotRequest.promise;+ controller.abort();+ await pending;++ assert.equal(startCalled, false, "a cancel must never restart the server");+ assert.equal(fallbackEvents, 0);+});++test("a pre-aborted signal rejects before any request is sent", async (t) => {+ let requestCount = 0;+ const { server, port } = await startServer(() => {+ requestCount += 1;+ });+ t.after(() => server.close());++ const manager = createManager(port, { useCuda: false });+ const controller = new AbortController();+ controller.abort();++ await assert.rejects(+ () => manager.transcribe(Buffer.from("audio"), { signal: controller.signal }),+ (err) => {+ assert.equal(err.name, "AbortError");+ return true;+ }+ );++ assert.equal(requestCount, 0);+});+test("does not fall back after an intentional stop", async (t) => {let manager;let requestCount = 0;diff --git a/test/services/uploadDiarizationPersistence.test.js b/test/services/uploadDiarizationPersistence.test.jsindex 41e6641e8..213c36451 100644--- a/test/services/uploadDiarizationPersistence.test.js+++ b/test/services/uploadDiarizationPersistence.test.js@@ -100,10 +100,12 @@ test("a diarized file upload persists the diarization metadata", async (t) => {assert.equal(audioDuration, 4359.87);// The persisted count is the same one the diarizer was invoked with.- assert.deepEqual(calls.diarize, [{ numSpeakers: 2 }]);- assert.deepEqual(calls.updateNote, [- [7, { diarization_enabled: 1, expected_speaker_count: 2 }],- ]);+ assert.equal(calls.diarize.length, 1);+ assert.equal(calls.diarize[0].numSpeakers, 2);+ // The diarizer runs under the same cancellable requestId as the+ // transcription, so one cancel-upload-transcription aborts both.+ assert.equal(typeof calls.diarize[0].requestId, "string");+ assert.deepEqual(calls.updateNote, [[7, { diarization_enabled: 1, expected_speaker_count: 2 }]]);});test("a diarized URL ingest persists the diarization metadata", async (t) => {@@ -139,9 +141,7 @@ test("a diarized URL ingest persists the diarization metadata", async (t) => {assert.equal(sourceFile, "Board Meeting Recording");assert.equal(audioDuration, 4359.87);- assert.deepEqual(calls.updateNote, [- [7, { diarization_enabled: 1, expected_speaker_count: 2 }],- ]);+ assert.deepEqual(calls.updateNote, [[7, { diarization_enabled: 1, expected_speaker_count: 2 }]]);assert.deepEqual(calls.deletedTempFiles, ["/tmp/ow-url-download.m4a"]);});