Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(transcription): timeout, fresh-connection retry, cancel + global cap for chunked cloud uploads (#1330)

Joshua3ec11251954f
diff --git a/main.js b/main.js
index 8aa3d1609..1a8904adf 100644
--- a/main.js
+++ b/main.js
@@ -284,6 +284,7 @@ const LinuxPortalAudioManager = require("./src/helpers/linuxPortalAudioManager")
const WindowsLoopbackAudioManager = require("./src/helpers/windowsLoopbackAudioManager");
const MeetingAecManager = require("./src/helpers/meetingAecManager");
const MeetingDetectionEngine = require("./src/helpers/meetingDetectionEngine");
+const { applyOpenWhisprOriginHeader } = require("./src/helpers/sessionHeaders");
const { i18nMain, changeLanguage } = require("./src/helpers/i18nMain");
const { ensureYdotool } = require("./src/helpers/ensureYdotool");
const sidecarRegistry = require("./src/helpers/sidecarRegistry");
@@ -874,27 +875,7 @@ async function startApp() {
await migrateCookieToBearerToken();
- // Electron's file:// renderer sends Origin: null, which Better Auth's
- // trustedOrigins check rejects. Spoof Origin to the request's own URL so
- // calls to OpenWhispr's auth and API hosts are treated as same-origin.
- session.defaultSession.webRequest.onBeforeSendHeaders(
- {
- urls: [
- "https://auth.openwhispr.com/*",
- "https://api.openwhispr.com/*",
- "http://localhost:3000/*",
- "http://127.0.0.1:3000/*",
- ],
- },
- (details, callback) => {
- try {
- details.requestHeaders["Origin"] = new URL(details.url).origin;
- } catch {
- // malformed URL — leave Origin as-is
- }
- callback({ requestHeaders: details.requestHeaders });
- }
- );
+ applyOpenWhisprOriginHeader(session.defaultSession);
windowManager.setActivationModeCache(environmentManager.getActivationMode());
windowManager.setFloatingIconAutoHide(environmentManager.getFloatingIconAutoHide());
diff --git a/preload.js b/preload.js
index 82ce35ddc..ea4bb161d 100644
--- a/preload.js
+++ b/preload.js
@@ -553,8 +553,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
getNoteRecordingConfig: () => ipcRenderer.invoke("get-note-recording-config"),
// Cloud audio file transcription
- transcribeAudioFileCloud: (filePath) =>
- ipcRenderer.invoke("transcribe-audio-file-cloud", filePath),
+ transcribeAudioFileCloud: (filePath, options) =>
+ ipcRenderer.invoke("transcribe-audio-file-cloud", filePath, options),
+ cancelUploadTranscription: (requestId) =>
+ ipcRenderer.invoke("cancel-upload-transcription", requestId),
transcribeAudioFileByok: (options) => ipcRenderer.invoke("transcribe-audio-file-byok", options),
onUploadTranscriptionProgress: registerListener(
"upload-transcription-progress",
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsx
index 84c894a2d..4d103dcf5 100644
--- a/src/components/notes/UploadAudioView.tsx
+++ b/src/components/notes/UploadAudioView.tsx
@@ -142,6 +142,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
} | null>(null);
const progressCleanupRef = useRef<(() => void) | null>(null);
const runIdRef = useRef(0);
+ const activeRequestIdRef = useRef<string | null>(null);
const mountedRef = useRef(true);
const urlDownloadActiveRef = useRef(false);
@@ -561,6 +562,12 @@ 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.
+ if (activeRequestIdRef.current) {
+ window.electronAPI.cancelUploadTranscription?.(activeRequestIdRef.current);
+ activeRequestIdRef.current = null;
+ }
runIdRef.current++;
reset();
};
@@ -570,6 +577,8 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
const currentFile = file;
const currentTempPath = downloadedTempPath;
const runId = ++runIdRef.current;
+ const requestId = crypto.randomUUID();
+ activeRequestIdRef.current = requestId;
setState("transcribing");
setError(null);
setProgress(0);
@@ -609,8 +618,11 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
localModelsReady: !!diarizationModelsReady,
numSpeakers: diarizationNumSpeakers ? Number(diarizationNumSpeakers) : null,
},
- currentFile.durationSeconds
- );
+ currentFile.durationSeconds,
+ { requestId }
+ ).finally(() => {
+ if (activeRequestIdRef.current === requestId) activeRequestIdRef.current = null;
+ });
if (runId !== runIdRef.current) return;
diff --git a/src/helpers/abortError.js b/src/helpers/abortError.js
new file mode 100644
index 000000000..3d5cd7467
--- /dev/null
+++ b/src/helpers/abortError.js
@@ -0,0 +1,10 @@
+// Mirrors the DOMException `net.fetch` throws on abort, so transports that
+// abort by hand (the ffmpeg child, a queued upload slot) reject with the same
+// shape and callers can branch uniformly on `error.name === "AbortError"`.
+function createAbortError(message = "Aborted") {
+ const error = new Error(message);
+ error.name = "AbortError";
+ return error;
+}
+
+module.exports = { createAbortError };
diff --git a/src/helpers/cloudChunkPolicy.js b/src/helpers/cloudChunkPolicy.js
new file mode 100644
index 000000000..47156736f
--- /dev/null
+++ b/src/helpers/cloudChunkPolicy.js
@@ -0,0 +1,156 @@
+const { createAbortError } = require("./abortError");
+
+// Retry/backoff/concurrency policy for the chunked cloud upload path (#1326).
+// Kept free of electron imports so the rules stay unit-testable.
+//
+// The transient/deterministic split mirrors createApiRetryStrategy in
+// src/utils/retry.ts; the main process is CJS and that module is TS, so the
+// rule is restated rather than imported. It deliberately diverges on 429:
+// there it means rate limiting and retries, here it is the account's word
+// limit and never clears within a job.
+
+// A dead upload must fail well before the peer's 1–4 min idle teardown does it
+// for us, but a healthy ~3.84MB chunk on a slow uplink needs real headroom.
+const CLOUD_UPLOAD_TIMEOUT_MS = 120_000;
+const CLOUD_CHUNK_MAX_ATTEMPTS = 3;
+// Chunk bodies on the wire app-wide. Previously 5 per job with no cross-job
+// ceiling, so a user retry ran ~6 concurrent ~4MB bodies; a lone job is
+// unchanged, and dictation can no longer be starved by a batch upload.
+const CLOUD_CHUNK_GLOBAL_CONCURRENCY = 5;
+
+const CLOUD_CHUNK_BACKOFF_BASE_MS = 5_000;
+const CLOUD_CHUNK_BACKOFF_FACTOR = 3;
+const CLOUD_CHUNK_BACKOFF_MAX_MS = 45_000;
+const CLOUD_CHUNK_BACKOFF_JITTER_MS = 1_000;
+
+// Dropping the connection pool is session-wide, so it also aborts healthy
+// sibling uploads. A wedged connection fails every in-flight chunk at once, so
+// collapse that burst into one teardown instead of letting each failure
+// sacrifice its peers — and its peers' retries in turn.
+const CLOUD_POOL_TEARDOWN_COOLDOWN_MS = 30_000;
+
+// Codes that doom the whole job, not just one chunk: retrying the siblings can
+// only burn time and quota.
+const FATAL_CHUNK_CODES = new Set(["AUTH_EXPIRED", "LIMIT_REACHED"]);
+
+const NON_RETRYABLE_CHUNK_CODES = new Set([...FATAL_CHUNK_CODES, "NO_SPEECH_DETECTED"]);
+
+function isTransientChunkError(err) {
+ if (NON_RETRYABLE_CHUNK_CODES.has(err.code)) return false;
+ return !err.statusCode || err.statusCode >= 500;
+}
+
+// True when the request never got an HTTP answer — the signal that the
+// connection pool (not the server) is the suspect and should be torn down
+// before the next attempt. Errors carrying a statusCode or a business code
+// prove the connection works.
+function isNetworkLevelFailure(err, { timedOut = false } = {}) {
+ return timedOut || (!err.statusCode && !err.code);
+}
+
+function createTeardownGate(cooldownMs = CLOUD_POOL_TEARDOWN_COOLDOWN_MS, now = Date.now) {
+ let lastAt = -Infinity;
+ return () => {
+ const at = now();
+ if (at - lastAt < cooldownMs) return false;
+ lastAt = at;
+ return true;
+ };
+}
+
+function chunkRetryDelayMs(attempt, random = Math.random) {
+ const base = Math.min(
+ CLOUD_CHUNK_BACKOFF_BASE_MS * CLOUD_CHUNK_BACKOFF_FACTOR ** (attempt - 1),
+ CLOUD_CHUNK_BACKOFF_MAX_MS
+ );
+ return base + Math.floor(random() * CLOUD_CHUNK_BACKOFF_JITTER_MS);
+}
+
+function abortableSleep(ms, signal) {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(createAbortError());
+ return;
+ }
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(createAbortError());
+ };
+ const timer = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+// Counting semaphore shared by every chunked job. acquire() resolves to a
+// release function; a queued waiter whose signal aborts rejects and forfeits
+// its place without consuming a slot.
+function createUploadSlots(max) {
+ let active = 0;
+ const waiters = [];
+
+ const admit = () => {
+ while (active < max && waiters.length) {
+ const waiter = waiters.shift();
+ if (waiter.settled) continue;
+ waiter.settled = true;
+ active++;
+ waiter.resolve(makeRelease());
+ }
+ };
+
+ const makeRelease = () => {
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ active--;
+ admit();
+ };
+ };
+
+ return {
+ acquire(signal) {
+ if (signal?.aborted) return Promise.reject(createAbortError());
+ if (active < max) {
+ active++;
+ return Promise.resolve(makeRelease());
+ }
+ return new Promise((resolve, reject) => {
+ const waiter = { settled: false, resolve };
+ if (signal) {
+ const onAbort = () => {
+ if (waiter.settled) return;
+ waiter.settled = true;
+ reject(createAbortError());
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ waiter.resolve = (release) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(release);
+ };
+ }
+ waiters.push(waiter);
+ });
+ },
+ get activeCount() {
+ return active;
+ },
+ };
+}
+
+module.exports = {
+ CLOUD_UPLOAD_TIMEOUT_MS,
+ CLOUD_CHUNK_MAX_ATTEMPTS,
+ CLOUD_CHUNK_GLOBAL_CONCURRENCY,
+ CLOUD_POOL_TEARDOWN_COOLDOWN_MS,
+ FATAL_CHUNK_CODES,
+ isTransientChunkError,
+ isNetworkLevelFailure,
+ chunkRetryDelayMs,
+ abortableSleep,
+ createTeardownGate,
+ createUploadSlots,
+};
diff --git a/src/helpers/ffmpegUtils.js b/src/helpers/ffmpegUtils.js
index 04cd0f050..d051013be 100644
--- a/src/helpers/ffmpegUtils.js
+++ b/src/helpers/ffmpegUtils.js
@@ -3,6 +3,7 @@ const fs = require("fs");
const os = require("os");
const path = require("path");
const debugLogger = require("./debugLogger");
+const { createAbortError } = require("./abortError");
let cachedFFmpegPath = null;
@@ -266,9 +267,14 @@ function computeFloat32RMS(float32Buffer) {
}
function splitAudioFile(inputPath, outputDir, options = {}) {
- const { segmentDuration = 600, audioBitrate = "128k" } = options;
+ const { segmentDuration = 600, audioBitrate = "128k", signal } = options;
return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(createAbortError());
+ return;
+ }
+
const ffmpegPath = getFFmpegPath();
if (!ffmpegPath) {
reject(new Error("FFmpeg not found - required for audio splitting"));
@@ -310,15 +316,31 @@ function splitAudioFile(inputPath, outputDir, options = {}) {
let stderr = "";
+ const onAbort = () => {
+ try {
+ proc.kill("SIGKILL");
+ } catch {
+ // an uncaught throw here would escape the abort dispatch
+ }
+ reject(createAbortError());
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+
proc.stderr.on("data", (data) => {
stderr += data.toString();
});
proc.on("error", (error) => {
+ signal?.removeEventListener("abort", onAbort);
+ if (signal?.aborted) return;
reject(new Error(`FFmpeg split error: ${error.message}`));
});
+ // The kill lands here as a non-zero exit; returning early keeps a cancel
+ // from being logged and reported as an ffmpeg failure.
proc.on("close", (code) => {
+ signal?.removeEventListener("abort", onAbort);
+ if (signal?.aborted) return;
if (code !== 0) {
const stderrPreview = stderr.slice(-500).trim();
debugLogger.debug("FFmpeg split failed", { code, stderr: stderrPreview });
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index b6f1b30c0..f985b5d15 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1,4 +1,4 @@
-const { ipcMain, app, shell, BrowserWindow, systemPreferences, net } = require("electron");
+const { ipcMain, app, shell, BrowserWindow, systemPreferences, net, session } = require("electron");
const path = require("path");
const fs = require("fs");
const os = require("os");
@@ -129,9 +129,48 @@ const AUDIO_MIME_TYPES = {
};
const CLOUD_INLINE_LIMIT = 4 * 1024 * 1024;
-const CLOUD_CHUNK_CONCURRENCY = 5;
const CLOUD_CHUNK_SEGMENT_SECONDS = 240;
-const CLOUD_CHUNK_MAX_ATTEMPTS = 3;
+
+const { createAbortError } = require("./abortError");
+const { applyOpenWhisprOriginHeader } = require("./sessionHeaders");
+const {
+ CLOUD_UPLOAD_TIMEOUT_MS,
+ CLOUD_CHUNK_MAX_ATTEMPTS,
+ CLOUD_CHUNK_GLOBAL_CONCURRENCY,
+ FATAL_CHUNK_CODES,
+ isTransientChunkError,
+ isNetworkLevelFailure,
+ chunkRetryDelayMs,
+ abortableSleep,
+ createTeardownGate,
+ createUploadSlots,
+} = require("./cloudChunkPolicy");
+
+// Every cloud upload rides a dedicated in-memory session so stalled large
+// bodies can't wedge the HTTP/2 connection the rest of the app multiplexes
+// over, and a failed attempt can drop the pool without collateral damage
+// outside the upload path (#1326).
+const CLOUD_UPLOAD_SESSION_PARTITION = "ow-cloud-uploads";
+const cloudUploadSlots = createUploadSlots(CLOUD_CHUNK_GLOBAL_CONCURRENCY);
+const shouldDropUploadPool = createTeardownGate();
+let cloudUploadSession = null;
+
+function getCloudUploadSession() {
+ if (!cloudUploadSession) {
+ cloudUploadSession = session.fromPartition(CLOUD_UPLOAD_SESSION_PARTITION);
+ applyOpenWhisprOriginHeader(cloudUploadSession);
+ }
+ return cloudUploadSession;
+}
+
+async function dropUploadConnections() {
+ if (!shouldDropUploadPool()) return;
+ try {
+ await getCloudUploadSession().closeAllConnections();
+ } catch {
+ // pool teardown is best-effort
+ }
+}
const {
formatTimestamp: formatDiarTime,
@@ -209,8 +248,14 @@ function buildMultipartBody(fileBuffer, fileName, contentType, fields = {}) {
return { body: Buffer.concat(bodyParts), boundary };
}
-async function postMultipart(url, body, boundary, headers = {}) {
- const response = await net.fetch(url.toString(), {
+async function postMultipart(
+ url,
+ body,
+ boundary,
+ headers = {},
+ { signal, session: fetchSession } = {}
+) {
+ const response = await (fetchSession ?? net).fetch(url.toString(), {
method: "POST",
headers: {
"Content-Type": `multipart/form-data; boundary=${boundary}`,
@@ -218,6 +263,7 @@ async function postMultipart(url, body, boundary, headers = {}) {
},
body,
useSessionCookies: false,
+ signal,
});
const text = await response.text();
try {
@@ -257,13 +303,6 @@ function interpretTranscribeResponse(data) {
return data.data;
}
-const NON_RETRYABLE_CHUNK_CODES = new Set(["AUTH_EXPIRED", "LIMIT_REACHED", "NO_SPEECH_DETECTED"]);
-
-function isTransientChunkError(err) {
- if (NON_RETRYABLE_CHUNK_CODES.has(err.code)) return false;
- return !err.statusCode || err.statusCode >= 500;
-}
-
async function chunkedCloudTranscribe({
buffer = null,
filePath = null,
@@ -271,11 +310,19 @@ async function chunkedCloudTranscribe({
authHeader,
multipartFields = {},
onProgress,
- concurrencyLimit = CLOUD_CHUNK_CONCURRENCY,
+ signal,
segmentDuration = CLOUD_CHUNK_SEGMENT_SECONDS,
}) {
const { splitAudioFile } = require("./ffmpegUtils");
+ // Aborted by the caller cancelling or by the first fatal chunk error, so a
+ // doomed job stops uploading its remaining chunks immediately.
+ const jobController = new AbortController();
+ const { signal: jobSignal } = jobController;
+ const abortJob = () => jobController.abort();
+ signal?.addEventListener("abort", abortJob, { once: true });
+ if (signal?.aborted) abortJob();
+
const jobId = `${Date.now()}-${crypto.randomBytes(4).toString("hex")}`;
const chunkDir = path.join(os.tmpdir(), `ow-chunks-${jobId}`);
let tmpInputPath = null;
@@ -292,38 +339,61 @@ async function chunkedCloudTranscribe({
try {
onProgress?.({ stage: "splitting", chunksTotal: 0, chunksCompleted: 0 });
- const chunkPaths = await splitAudioFile(inputPath, chunkDir, { segmentDuration });
+ const chunkPaths = await splitAudioFile(inputPath, chunkDir, {
+ segmentDuration,
+ signal: jobSignal,
+ });
const totalChunks = chunkPaths.length;
onProgress?.({ stage: "transcribing", chunksTotal: totalChunks, chunksCompleted: 0 });
+ const url = new URL(`${apiUrl}/api/transcribe`);
const results = new Array(totalChunks).fill(null);
const failureCodes = new Set();
+ let fatalError = null;
let completedCount = 0;
const transcribeChunk = async (index) => {
- const chunkBuffer = fs.readFileSync(chunkPaths[index]);
- const chunkName = path.basename(chunkPaths[index]);
- const { body, boundary } = buildMultipartBody(
- chunkBuffer,
- chunkName,
- "audio/mpeg",
- multipartFields
- );
- const url = new URL(`${apiUrl}/api/transcribe`);
-
for (let attempt = 1; ; attempt++) {
+ if (jobSignal.aborted) throw createAbortError();
+
+ // Held only while a body is on the wire, so the backoff below never
+ // occupies a slot and queue time never eats the upload timeout.
+ const releaseSlot = await cloudUploadSlots.acquire(jobSignal);
+ const timeoutSignal = AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS);
+ let failure = null;
try {
- const data = await postMultipart(url, body, boundary, authHeader);
+ const { body, boundary } = buildMultipartBody(
+ fs.readFileSync(chunkPaths[index]),
+ path.basename(chunkPaths[index]),
+ "audio/mpeg",
+ multipartFields
+ );
+ const data = await postMultipart(url, body, boundary, authHeader, {
+ signal: AbortSignal.any([jobSignal, timeoutSignal]),
+ session: getCloudUploadSession(),
+ });
results[index] = interpretTranscribeResponse(data);
- break;
} catch (err) {
- if (attempt >= CLOUD_CHUNK_MAX_ATTEMPTS || !isTransientChunkError(err)) throw err;
- debugLogger.warn(`Chunk ${index} attempt ${attempt} failed, retrying`, {
- error: err.message,
- });
- await new Promise((resolve) => setTimeout(resolve, 1000 * attempt + Math.random() * 500));
+ failure = err;
+ } finally {
+ releaseSlot();
}
+ if (!failure) break;
+
+ if (jobSignal.aborted) throw createAbortError();
+ const timedOut = timeoutSignal.aborted;
+ if (attempt >= CLOUD_CHUNK_MAX_ATTEMPTS || !(timedOut || isTransientChunkError(failure))) {
+ throw failure;
+ }
+ // No HTTP answer ever arrived — treat the pool as wedged and drop it so
+ // the retry dials a fresh connection instead of re-entering the dying one.
+ if (isNetworkLevelFailure(failure, { timedOut })) await dropUploadConnections();
+ debugLogger.warn(`Chunk ${index} attempt ${attempt} failed, retrying`, {
+ error: failure.message,
+ timedOut,
+ });
+ await abortableSleep(chunkRetryDelayMs(attempt), jobSignal);
}
completedCount++;
@@ -334,23 +404,27 @@ async function chunkedCloudTranscribe({
});
};
- const executing = new Set();
- for (let index = 0; index < totalChunks; index++) {
- const p = transcribeChunk(index).then(
- () => executing.delete(p),
- (err) => {
- executing.delete(p);
- if (err.code === "AUTH_EXPIRED" || err.code === "LIMIT_REACHED") throw err;
+ await Promise.all(
+ chunkPaths.map((_, index) =>
+ transcribeChunk(index).catch((err) => {
+ // Only aborts the job itself caused, reported once below. A chunk's
+ // own upload timeout also aborts, and that is a real failure.
+ if (jobSignal.aborted && err.name === "AbortError") return;
+ if (FATAL_CHUNK_CODES.has(err.code)) {
+ fatalError ??= err;
+ abortJob();
+ return;
+ }
if (err.code) failureCodes.add(err.code);
debugLogger.warn(`Chunk ${index} failed`, { error: err.message, code: err.code });
- }
- );
- executing.add(p);
- if (executing.size >= concurrencyLimit) {
- await Promise.race(executing);
- }
+ })
+ )
+ );
+
+ if (signal?.aborted) {
+ throw Object.assign(createAbortError("Upload cancelled"), { code: "UPLOAD_CANCELLED" });
}
- await Promise.all(executing);
+ if (fatalError) throw fatalError;
const succeeded = results.filter((r) => r !== null);
if (succeeded.length === 0) {
@@ -377,6 +451,7 @@ async function chunkedCloudTranscribe({
...(failed > 0 ? { warning: `${failed} of ${totalChunks} chunks failed` } : {}),
};
} finally {
+ signal?.removeEventListener("abort", abortJob);
if (tmpInputPath) {
try {
fs.unlinkSync(tmpInputPath);
@@ -417,6 +492,9 @@ 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();
this.assemblyAiStreaming = null;
this.deepgramStreaming = null;
this.cortiStreaming = null;
@@ -4264,7 +4342,10 @@ class IPCHandlers {
multipartFields
);
const url = new URL(`${apiUrl}/api/transcribe`);
- const data = await postMultipart(url, body, boundary, authHeader);
+ const data = await postMultipart(url, body, boundary, authHeader, {
+ signal: AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),
+ session: getCloudUploadSession(),
+ });
debugLogger.debug(
"Cloud transcribe response",
@@ -4411,7 +4492,10 @@ class IPCHandlers {
multipartFields
);
const url = new URL(`${apiUrl}/api/transcribe`);
- const data = await postMultipart(url, body, boundary, authHeader);
+ const data = await postMultipart(url, body, boundary, authHeader, {
+ signal: AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),
+ session: getCloudUploadSession(),
+ });
const responseData = interpretTranscribeResponse(data);
result = {
text: responseData.text,
@@ -7320,7 +7404,10 @@ class IPCHandlers {
}
});
- ipcMain.handle("transcribe-audio-file-cloud", async (event, filePath) => {
+ 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);
try {
if (typeof filePath !== "string") {
return { success: false, error: "Invalid file path" };
@@ -7355,6 +7442,7 @@ class IPCHandlers {
authHeader,
multipartFields,
onProgress: (payload) => event.sender.send("upload-transcription-progress", payload),
+ signal: controller.signal,
});
return { success: true, text, ...(warning ? { warning } : {}) };
}
@@ -7371,19 +7459,39 @@ class IPCHandlers {
multipartFields
);
const url = new URL(`${apiUrl}/api/transcribe`);
- const data = await postMultipart(url, body, boundary, authHeader);
+ const data = await postMultipart(url, body, boundary, authHeader, {
+ signal: AbortSignal.any([
+ controller.signal,
+ AbortSignal.timeout(CLOUD_UPLOAD_TIMEOUT_MS),
+ ]),
+ session: getCloudUploadSession(),
+ });
const result = interpretTranscribeResponse(data);
return { success: true, text: result.text };
} catch (error) {
+ if (controller.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 });
if (error.code) {
return { success: false, error: error.message, code: error.code, ...error };
}
return { success: false, error: error.message };
+ } finally {
+ if (requestId) this._uploadTranscriptionControllers.delete(requestId);
}
});
+ // Unknown ids are a no-op: providers other than OpenWhispr cloud 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 };
+ });
+
ipcMain.handle(
"transcribe-audio-file-byok",
async (
diff --git a/src/helpers/sessionHeaders.js b/src/helpers/sessionHeaders.js
new file mode 100644
index 000000000..5a034092f
--- /dev/null
+++ b/src/helpers/sessionHeaders.js
@@ -0,0 +1,27 @@
+const OPENWHISPR_HOST_PATTERNS = [
+ "https://auth.openwhispr.com/*",
+ "https://api.openwhispr.com/*",
+ "http://localhost:3000/*",
+ "http://127.0.0.1:3000/*",
+];
+
+// Electron's file:// renderer sends Origin: null, which Better Auth's
+// trustedOrigins check rejects. Spoof Origin to the request's own URL so calls
+// to OpenWhispr's auth and API hosts are treated as same-origin. Every session
+// that talks to those hosts needs this — webRequest hooks are per-session, so
+// an isolated partition gets none of the default session's.
+function applyOpenWhisprOriginHeader(targetSession) {
+ targetSession.webRequest.onBeforeSendHeaders(
+ { urls: OPENWHISPR_HOST_PATTERNS },
+ (details, callback) => {
+ try {
+ details.requestHeaders["Origin"] = new URL(details.url).origin;
+ } catch {
+ // malformed URL — leave Origin as-is
+ }
+ callback({ requestHeaders: details.requestHeaders });
+ }
+ );
+}
+
+module.exports = { applyOpenWhisprOriginHeader };
diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.ts
index 860382425..7e6e66d84 100644
--- a/src/services/fileTranscription.ts
+++ b/src/services/fileTranscription.ts
@@ -39,11 +39,12 @@ export interface FileTranscriptionConfig {
export async function transcribeFile(
filePath: string,
cfg: FileTranscriptionConfig,
- diarize: boolean
+ diarize: boolean,
+ opts: { requestId?: string } = {}
): Promise<FileTranscriptionResult> {
if (cfg.isOpenWhisprCloud) {
return withSessionRefresh(async () => {
- const r = await window.electronAPI.transcribeAudioFileCloud!(filePath);
+ const r = await window.electronAPI.transcribeAudioFileCloud!(filePath, opts);
if (!r.success && r.code) {
throw Object.assign(new Error(r.error || "Cloud transcription failed"), {
code: r.code,
@@ -101,7 +102,8 @@ export async function transcribeFileWithSpeakers(
filePath: string,
cfg: FileTranscriptionConfig,
diarization: DiarizationSettings,
- durationSeconds?: number | null
+ durationSeconds?: number | null,
+ opts: { requestId?: string } = {}
): Promise<FileTranscriptionResult> {
const byokDiarize = shouldUseByokDiarize(cfg, diarization.enabled);
const diarizePromise =
@@ -114,7 +116,7 @@ export async function transcribeFileWithSpeakers(
: Promise.resolve(null);
const [result, diar] = await Promise.all([
- transcribeFile(filePath, cfg, byokDiarize),
+ transcribeFile(filePath, cfg, byokDiarize, opts),
diarizePromise,
]);
diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.ts
index 93020e3db..8055ef26f 100644
--- a/src/stores/batchQueueStore.ts
+++ b/src/stores/batchQueueStore.ts
@@ -40,10 +40,12 @@ export const useBatchQueueStore = create<BatchQueueStoreState>()(() => ({
isProcessing: false,
}));
-// Bumping the run id soft-cancels the drain loop: the in-flight transcription
-// IPC can't be aborted, so 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 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.
let runId = 0;
+let activeUploadRequestId: string | null = null;
function updateQueue(updater: (prev: QueueItem[]) => QueueItem[]) {
useBatchQueueStore.setState((s) => ({ queue: updater(s.queue) }));
@@ -84,6 +86,10 @@ export function removeQueueItem(id: string) {
export function cancelBatch() {
runId++;
+ if (activeUploadRequestId) {
+ window.electronAPI.cancelUploadTranscription?.(activeUploadRequestId);
+ activeUploadRequestId = null;
+ }
window.electronAPI.cancelUrlDownload();
useBatchQueueStore.setState((s) => ({
isProcessing: false,
@@ -180,12 +186,17 @@ export function processBatchQueue(
updateItem(item.id, { status: "transcribing", progress: 0 });
+ const requestId = crypto.randomUUID();
+ activeUploadRequestId = requestId;
const transcriptionResult = await transcribeFileWithSpeakers(
filePath,
transcription,
diarization,
- durationSeconds
- );
+ durationSeconds,
+ { requestId }
+ ).finally(() => {
+ if (activeUploadRequestId === requestId) activeUploadRequestId = null;
+ });
if (run !== runId) return;
diff --git a/src/types/electron.ts b/src/types/electron.ts
index baf5f333a..51ab27c9f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1412,7 +1412,10 @@ declare global {
}>;
// Cloud audio file transcription
- transcribeAudioFileCloud?: (filePath: string) => Promise<{
+ transcribeAudioFileCloud?: (
+ filePath: string,
+ options?: { requestId?: string }
+ ) => Promise<{
success: boolean;
text?: string;
warning?: string;
@@ -1420,6 +1423,8 @@ declare global {
code?: string;
}>;
+ cancelUploadTranscription?: (requestId: string) => Promise<{ success: boolean }>;
+
onUploadTranscriptionProgress?: (
callback: (data: { stage: string; chunksTotal: number; chunksCompleted: number }) => void
) => () => void;
diff --git a/test/helpers/cloudChunkPolicy.test.js b/test/helpers/cloudChunkPolicy.test.js
new file mode 100644
index 000000000..d1810b1b3
--- /dev/null
+++ b/test/helpers/cloudChunkPolicy.test.js
@@ -0,0 +1,191 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ CLOUD_UPLOAD_TIMEOUT_MS,
+ CLOUD_CHUNK_MAX_ATTEMPTS,
+ CLOUD_CHUNK_GLOBAL_CONCURRENCY,
+ CLOUD_POOL_TEARDOWN_COOLDOWN_MS,
+ FATAL_CHUNK_CODES,
+ isTransientChunkError,
+ isNetworkLevelFailure,
+ chunkRetryDelayMs,
+ abortableSleep,
+ createTeardownGate,
+ createUploadSlots,
+} = require("../../src/helpers/cloudChunkPolicy");
+const { createAbortError } = require("../../src/helpers/abortError");
+
+// The numbers are the #1326 contract: a dead upload fails within 2 minutes and
+// three attempts, and chunk bodies are capped across ALL jobs so a user retry
+// can't run ~6 concurrent ~4MB bodies. The cap matches the old per-job limit, so
+// a lone job uploads exactly as fast as before the fix.
+test("policy constants match the issue-1326 contract", () => {
+ assert.equal(CLOUD_UPLOAD_TIMEOUT_MS, 120_000);
+ assert.equal(CLOUD_CHUNK_MAX_ATTEMPTS, 3);
+ assert.equal(CLOUD_CHUNK_GLOBAL_CONCURRENCY, 5);
+});
+
+// A wedge fails every in-flight chunk at once, and closeAllConnections is
+// session-wide, so an ungated teardown would let each failure abort its healthy
+// siblings — and their retries in turn.
+test("teardown gate admits one drop per cooldown window", () => {
+ let now = 0;
+ const gate = createTeardownGate(CLOUD_POOL_TEARDOWN_COOLDOWN_MS, () => now);
+
+ assert.equal(gate(), true, "first failure must drop the wedged pool");
+ assert.equal(gate(), false, "a simultaneous sibling failure must not drop it again");
+
+ now += CLOUD_POOL_TEARDOWN_COOLDOWN_MS - 1;
+ assert.equal(gate(), false);
+
+ now += 1;
+ assert.equal(gate(), true, "a later wedge must still be recoverable");
+});
+
+test("auth and quota doom the job; silence dooms only its own chunk", () => {
+ assert.equal(FATAL_CHUNK_CODES.has("AUTH_EXPIRED"), true);
+ assert.equal(FATAL_CHUNK_CODES.has("LIMIT_REACHED"), true);
+ // Silence in one segment says nothing about the rest, so the siblings must
+ // keep uploading.
+ assert.equal(FATAL_CHUNK_CODES.has("NO_SPEECH_DETECTED"), false);
+});
+
+test("createAbortError mirrors the DOMException shape fetch rejects with", () => {
+ const err = createAbortError();
+ assert.equal(err.name, "AbortError");
+ assert.ok(err instanceof Error);
+});
+
+test("errors that never got an HTTP answer are transient", () => {
+ assert.equal(isTransientChunkError(new Error("net::ERR_CONNECTION_CLOSED")), true);
+ assert.equal(isTransientChunkError(Object.assign(new Error("x"), { statusCode: 502 })), true);
+});
+
+test("deterministic HTTP rejections are not transient", () => {
+ assert.equal(isTransientChunkError(Object.assign(new Error("x"), { statusCode: 413 })), false);
+ assert.equal(isTransientChunkError(Object.assign(new Error("x"), { statusCode: 404 })), false);
+});
+
+test("terminal business codes are not transient", () => {
+ for (const code of ["AUTH_EXPIRED", "LIMIT_REACHED", "NO_SPEECH_DETECTED"]) {
+ assert.equal(isTransientChunkError(Object.assign(new Error("x"), { code })), false);
+ }
+});
+
+test("network-level failures are those where no HTTP answer arrived", () => {
+ // Timeout: the upload stalled — network-level even if the error carries extras.
+ assert.equal(isNetworkLevelFailure(new Error("aborted"), { timedOut: true }), true);
+ // Pure transport rejection: no statusCode, no business code.
+ assert.equal(isNetworkLevelFailure(new Error("net::ERR_CONNECTION_CLOSED"), {}), true);
+ // An HTTP answer arrived (5xx) — the connection works; don't tear down the pool.
+ assert.equal(
+ isNetworkLevelFailure(Object.assign(new Error("x"), { statusCode: 502 }), {}),
+ false
+ );
+ // Business rejection (401→AUTH_EXPIRED) — the server answered.
+ assert.equal(
+ isNetworkLevelFailure(Object.assign(new Error("x"), { code: "AUTH_EXPIRED" }), {}),
+ false
+ );
+});
+
+test("backoff is ~5s/15s/45s exponential, capped, with up to 1s jitter", () => {
+ const noJitter = () => 0;
+ assert.equal(chunkRetryDelayMs(1, noJitter), 5_000);
+ assert.equal(chunkRetryDelayMs(2, noJitter), 15_000);
+ assert.equal(chunkRetryDelayMs(3, noJitter), 45_000);
+ assert.equal(chunkRetryDelayMs(4, noJitter), 45_000); // capped
+
+ const fullJitter = () => 0.9999;
+ const jittered = chunkRetryDelayMs(1, fullJitter);
+ assert.ok(jittered > 5_000 && jittered <= 6_000, `jitter out of range: ${jittered}`);
+});
+
+test("abortableSleep resolves normally without a signal", async () => {
+ const start = Date.now();
+ await abortableSleep(10);
+ assert.ok(Date.now() - start >= 5);
+});
+
+test("abortableSleep rejects immediately on an already-aborted signal", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(abortableSleep(10_000, controller.signal), { name: "AbortError" });
+});
+
+test("abortableSleep rejects promptly when aborted mid-wait", async () => {
+ const controller = new AbortController();
+ const start = Date.now();
+ setTimeout(() => controller.abort(), 10);
+ await assert.rejects(abortableSleep(10_000, controller.signal), { name: "AbortError" });
+ assert.ok(Date.now() - start < 5_000, "abort did not interrupt the sleep");
+});
+
+test("upload slots cap concurrent holders across independent acquirers", async () => {
+ const slots = createUploadSlots(2);
+ const r1 = await slots.acquire();
+ const r2 = await slots.acquire();
+ assert.equal(slots.activeCount, 2);
+
+ let thirdAdmitted = false;
+ const third = slots.acquire().then((release) => {
+ thirdAdmitted = true;
+ return release;
+ });
+ await abortableSleep(10);
+ assert.equal(thirdAdmitted, false, "third acquire ran while both slots were held");
+
+ r1();
+ const r3 = await third;
+ assert.equal(thirdAdmitted, true);
+ assert.equal(slots.activeCount, 2);
+
+ r2();
+ r3();
+ assert.equal(slots.activeCount, 0);
+});
+
+test("a queued acquire rejects on abort and never takes a slot afterwards", async () => {
+ const slots = createUploadSlots(1);
+ const r1 = await slots.acquire();
+
+ const abortedWaiter = new AbortController();
+ const waiting = slots.acquire(abortedWaiter.signal);
+ const successor = slots.acquire();
+
+ abortedWaiter.abort();
+ await assert.rejects(waiting, { name: "AbortError" });
+
+ r1();
+ const r2 = await successor; // the aborted waiter must not have consumed the freed slot
+ assert.equal(slots.activeCount, 1);
+ r2();
+ assert.equal(slots.activeCount, 0);
+});
+
+test("acquire with a pre-aborted signal rejects without queueing", async () => {
+ const slots = createUploadSlots(1);
+ const controller = new AbortController();
+ controller.abort();
+ await assert.rejects(slots.acquire(controller.signal), { name: "AbortError" });
+ assert.equal(slots.activeCount, 0);
+});
+
+test("double-release does not mint extra capacity", async () => {
+ const slots = createUploadSlots(1);
+ const release = await slots.acquire();
+ release();
+ release(); // second call must be a no-op
+
+ const r1 = await slots.acquire();
+ let secondAdmitted = false;
+ const second = slots.acquire().then((rel) => {
+ secondAdmitted = true;
+ return rel;
+ });
+ await abortableSleep(10);
+ assert.equal(secondAdmitted, false, "double-release created a phantom slot");
+ r1();
+ (await second)();
+});