Skip to content

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

feat: URL audio download, batch upload, and speaker diarization (#754)

Alcahest Malus Dienheim7a9d13a5e8d8
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.yml
index fa848e7e9..58d613f9a 100644
--- a/.github/workflows/build-and-notarize.yml
+++ b/.github/workflows/build-and-notarize.yml
@@ -54,6 +54,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN || github.token }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current
env:
@@ -140,6 +143,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN || github.token }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current
env:
@@ -264,6 +270,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN || github.token }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current --platform darwin --arch ${{ matrix.arch }}
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current --platform darwin --arch ${{ matrix.arch }}
env:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ecd3bdc02..473102487 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -53,6 +53,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current
env:
@@ -134,6 +137,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current
env:
@@ -254,6 +260,9 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
+ - name: Download yt-dlp binary
+ run: node scripts/download-yt-dlp.js --current --platform darwin --arch ${{ matrix.arch }}
+
- name: Download Qdrant binary
run: node scripts/download-qdrant.js --current --platform darwin --arch ${{ matrix.arch }}
env:
diff --git a/electron-builder.json b/electron-builder.json
index 706d00fd9..e6228d136 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -104,6 +104,7 @@
"whisper-server-*",
"llama-server-*",
"sherpa-onnx-*",
+ "yt-dlp-*",
"qdrant-*",
"macos-audio-tap",
"macos-globe-listener",
diff --git a/main.js b/main.js
index 7d7137b6a..b6d43ebfa 100644
--- a/main.js
+++ b/main.js
@@ -511,7 +511,7 @@ app.on("open-url", (event, url) => {
return;
}
- if (url.includes("/invitations/")) {
+ if (isInvitationDeepLink(url)) {
handleInvitationDeepLink(url);
return;
}
@@ -524,6 +524,10 @@ app.on("open-url", (event, url) => {
}
});
+function isInvitationDeepLink(url) {
+ return url.slice(`${OAUTH_PROTOCOL}://`.length).startsWith("invitations/");
+}
+
function handleInvitationDeepLink(deepLinkUrl) {
try {
const match = deepLinkUrl.match(/invitations\/([^/?#]+)/);
@@ -1481,7 +1485,7 @@ if (gotSingleInstanceLock) {
if (url) {
if (url.includes("upgrade-success")) {
handleUpgradeDeepLink();
- } else if (url.includes("/invitations/")) {
+ } else if (isInvitationDeepLink(url)) {
handleInvitationDeepLink(url);
} else {
void handleOAuthDeepLink(url);
diff --git a/package.json b/package.json
index 834a84521..25e6e0cb7 100644
--- a/package.json
+++ b/package.json
@@ -20,33 +20,33 @@
"compile:mic-listener": "node scripts/build-macos-mic-listener.js",
"compile:audio-tap": "node scripts/build-macos-audio-tap.js",
"compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linuxkeys && npm run compile:winpaste && npm run compile:linux-paste && npm run compile:linux-system-audio && npm run compile:text-monitor && npm run compile:media-remote && npm run compile:mic-listener && npm run compile:audio-tap",
- "prestart": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
+ "prestart": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
"start": "electron .",
- "predev": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
+ "predev": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
"dev": "concurrently -k -r \"npm:dev:renderer\" \"npm:dev:main\"",
- "predev:main": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
+ "predev:main": "npm run compile:native && npm run download:meeting-aec-helper && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:embedding-model && npm run download:whisper-vad-model",
"dev:main": "cross-env NODE_ENV=development node scripts/run-electron.js --dev",
"dev:renderer": "cd src && vite",
- "prebuild": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:embedding-model -- --for-build && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
+ "prebuild": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:embedding-model -- --for-build && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
"build": "cd src && vite build && cd .. && electron-builder",
"postinstall": "electron-builder install-app-deps",
"build:renderer": "cd src && vite build",
"compile:mac-icon": "node scripts/compile-macos-icon.js",
- "prebuild:mac": "npm run compile:native && npm run compile:mac-icon && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
+ "prebuild:mac": "npm run compile:native && npm run compile:mac-icon && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
"build:mac": "npm run build:renderer && electron-builder --mac",
"build:mac:arm64": "npm run build:renderer && electron-builder --mac --arm64",
"build:mac:x64": "npm run build:renderer && electron-builder --mac --x64",
- "prebuild:win": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models && npm run download:nircmd && npm run download:windows-fast-paste && npm run download:windows-key-listener && npm run download:windows-mic-listener && npm run download:windows-system-audio-helper",
+ "prebuild:win": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models && npm run download:nircmd && npm run download:windows-fast-paste && npm run download:windows-key-listener && npm run download:windows-mic-listener && npm run download:windows-system-audio-helper",
"build:win": "npm run build:renderer && electron-builder --win",
- "prebuild:linux": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
+ "prebuild:linux": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
"build:linux": "npm run build:renderer && electron-builder --linux",
"build:linux:appimage": "npm run build:renderer && electron-builder --linux AppImage",
"build:linux:deb": "npm run build:renderer && electron-builder --linux deb",
"build:linux:rpm": "npm run build:renderer && electron-builder --linux rpm",
"build:linux:tar": "npm run build:renderer && electron-builder --linux tar.gz",
- "prepack": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
+ "prepack": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
"pack": "npm run build:renderer && cross-env CSC_IDENTITY_AUTO_DISCOVERY=false electron-builder --dir",
- "predist": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
+ "predist": "npm run compile:native && npm run download:whisper-cpp && npm run download:llama-server && npm run download:sherpa-onnx && npm run download:yt-dlp && npm run download:qdrant && npm run download:meeting-aec-helper && npm run download:whisper-vad-model && npm run download:diarization-models -- --output-dir resources/bin/diarization-models",
"dist": "npm run build:renderer && electron-builder",
"download:whisper-cpp": "node scripts/download-whisper-cpp.js --current",
"download:whisper-cpp:all": "node scripts/download-whisper-cpp.js --all",
@@ -54,6 +54,8 @@
"download:llama-server:all": "node scripts/download-llama-server.js --all",
"download:sherpa-onnx": "node scripts/download-sherpa-onnx.js --current",
"download:sherpa-onnx:all": "node scripts/download-sherpa-onnx.js --all",
+ "download:yt-dlp": "node scripts/download-yt-dlp.js --current",
+ "download:yt-dlp:all": "node scripts/download-yt-dlp.js --all",
"download:nircmd": "node scripts/download-nircmd.js",
"download:windows-fast-paste": "node scripts/download-windows-fast-paste.js",
"download:windows-key-listener": "node scripts/download-windows-key-listener.js",
diff --git a/preload.js b/preload.js
index 62e374456..ece054b34 100644
--- a/preload.js
+++ b/preload.js
@@ -153,11 +153,25 @@ contextBridge.exposeInMainWorld("electronAPI", {
deleteAction: (id) => ipcRenderer.invoke("db-delete-action", id),
// Audio file operations
- selectAudioFile: () => ipcRenderer.invoke("select-audio-file"),
+ selectAudioFile: (options) => ipcRenderer.invoke("select-audio-file", options),
getFileSize: (filePath) => ipcRenderer.invoke("get-file-size", filePath),
transcribeAudioFile: (filePath, options) =>
ipcRenderer.invoke("transcribe-audio-file", filePath, options),
- getPathForFile: (file) => webUtils.getPathForFile(file),
+ getPathForFile: (file) => {
+ const filePath = webUtils.getPathForFile(file);
+ // Register real dropped-file paths so the main-process audio allowlist accepts them.
+ if (filePath) ipcRenderer.send("approve-audio-path", filePath);
+ return filePath;
+ },
+
+ // URL audio download
+ downloadUrlAudio: (url, downloadId) => ipcRenderer.invoke("download-url-audio", url, downloadId),
+ cancelUrlDownload: (downloadId) => ipcRenderer.invoke("cancel-url-download", downloadId),
+ deleteTempFile: (filePath) => ipcRenderer.invoke("delete-temp-file", filePath),
+ onUrlDownloadProgress: registerListener(
+ "url-download-progress",
+ (callback) => (_event, data) => callback(data)
+ ),
onNoteAdded: (callback) => {
const listener = (_event, note) => callback?.(note);
@@ -284,6 +298,10 @@ contextBridge.exposeInMainWorld("electronAPI", {
getDiarizationModelStatus: () => ipcRenderer.invoke("get-diarization-model-status"),
deleteDiarizationModels: () => ipcRenderer.invoke("delete-diarization-models"),
cancelDiarizationDownload: () => ipcRenderer.invoke("cancel-diarization-download"),
+ diarizeAudioFile: (filePath, options) =>
+ ipcRenderer.invoke("diarize-audio-file", filePath, options),
+ mergeSpeakerText: (segments, text, duration) =>
+ ipcRenderer.invoke("merge-speaker-text", { segments, text, duration }),
onDiarizationDownloadProgress: registerListener(
"diarization-download-progress",
(callback) => (_event, data) => callback(data)
diff --git a/scripts/download-yt-dlp.js b/scripts/download-yt-dlp.js
new file mode 100644
index 000000000..99ffd1ff9
--- /dev/null
+++ b/scripts/download-yt-dlp.js
@@ -0,0 +1,126 @@
+#!/usr/bin/env node
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+const { downloadFile, parseArgs, setExecutable } = require("./lib/download-utils");
+
+const YT_DLP_VERSION = "2026.07.04";
+const GITHUB_RELEASE_URL = `https://github.com/yt-dlp/yt-dlp/releases/download/${YT_DLP_VERSION}`;
+
+// yt-dlp ships single self-contained PyInstaller binaries (no archive to extract).
+// macOS asset is universal2 and serves both arm64 and x64. sha256 values are pinned
+// from the release's SHA2-256SUMS — release assets are mutable, tags aren't enough.
+const BINARIES = {
+ "darwin-arm64": {
+ assetName: "yt-dlp_macos",
+ outputName: "yt-dlp-darwin-arm64",
+ sha256: "498bd0dae17855c599d371d68ec5bafc439a9d8640e838be25c765a9792f261b",
+ },
+ "darwin-x64": {
+ assetName: "yt-dlp_macos",
+ outputName: "yt-dlp-darwin-x64",
+ sha256: "498bd0dae17855c599d371d68ec5bafc439a9d8640e838be25c765a9792f261b",
+ },
+ "win32-x64": {
+ assetName: "yt-dlp.exe",
+ outputName: "yt-dlp-win32-x64.exe",
+ sha256: "52fe3c26dcf71fbdc85b528589020bb0b8e383155cfa81b64dd447bbe35e24b8",
+ },
+ "linux-x64": {
+ assetName: "yt-dlp_linux",
+ outputName: "yt-dlp-linux-x64",
+ sha256: "6bbb3d314cde4febe36e5fa1d55462e29c974f63444e707871834f6d8cc210ae",
+ },
+};
+
+const BIN_DIR = path.join(__dirname, "..", "resources", "bin");
+
+function getDownloadUrl(assetName) {
+ return `${GITHUB_RELEASE_URL}/${assetName}`;
+}
+
+async function downloadBinary(platformArch, config, isForce = false) {
+ if (!config) {
+ console.log(` ${platformArch}: Not supported`);
+ return false;
+ }
+
+ const outputPath = path.join(BIN_DIR, config.outputName);
+
+ if (fs.existsSync(outputPath) && !isForce) {
+ console.log(` ${platformArch}: Already exists (use --force to re-download)`);
+ return true;
+ }
+
+ const url = getDownloadUrl(config.assetName);
+ console.log(` ${platformArch}: Downloading from ${url}`);
+
+ try {
+ await downloadFile(url, outputPath);
+ const actual = crypto.createHash("sha256").update(fs.readFileSync(outputPath)).digest("hex");
+ if (actual !== config.sha256) {
+ throw new Error(`sha256 mismatch: expected ${config.sha256}, got ${actual}`);
+ }
+ setExecutable(outputPath);
+ console.log(` ${platformArch}: Saved to ${config.outputName} (sha256 verified)`);
+ return true;
+ } catch (error) {
+ console.error(` ${platformArch}: Failed - ${error.message}`);
+ if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
+ return false;
+ }
+}
+
+async function main() {
+ console.log(`\nDownloading yt-dlp binaries (${YT_DLP_VERSION})...\n`);
+
+ fs.mkdirSync(BIN_DIR, { recursive: true });
+
+ const args = parseArgs();
+
+ if (args.isCurrent) {
+ if (!BINARIES[args.platformArch]) {
+ console.error(`Unsupported platform/arch: ${args.platformArch}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ console.log(`Downloading for target platform (${args.platformArch}):`);
+ const ok = await downloadBinary(args.platformArch, BINARIES[args.platformArch], args.isForce);
+ if (!ok) {
+ console.error(`Failed to download binary for ${args.platformArch}`);
+ process.exitCode = 1;
+ return;
+ }
+ } else {
+ console.log("Downloading binaries for all platforms:");
+ for (const platformArch of Object.keys(BINARIES)) {
+ await downloadBinary(platformArch, BINARIES[platformArch], args.isForce);
+ }
+ }
+
+ console.log("\n---");
+
+ const files = fs.readdirSync(BIN_DIR).filter((f) => f.startsWith("yt-dlp-"));
+ if (files.length > 0) {
+ console.log("Available yt-dlp binaries:\n");
+ files.forEach((f) => {
+ const stats = fs.statSync(path.join(BIN_DIR, f));
+ console.log(` - ${f} (${Math.round(stats.size / 1024 / 1024)}MB)`);
+ });
+ } else {
+ console.log("No binaries downloaded yet.");
+ console.log(`\nCheck: https://github.com/yt-dlp/yt-dlp/releases/tag/${YT_DLP_VERSION}`);
+ }
+}
+
+module.exports = {
+ YT_DLP_VERSION,
+ BINARIES,
+ BIN_DIR,
+ getDownloadUrl,
+};
+
+if (require.main === module) {
+ main().catch(console.error);
+}
diff --git a/src/components/notes/BatchQueueView.tsx b/src/components/notes/BatchQueueView.tsx
new file mode 100644
index 000000000..62ae07153
--- /dev/null
+++ b/src/components/notes/BatchQueueView.tsx
@@ -0,0 +1,163 @@
+import { useTranslation } from "react-i18next";
+import { AlertTriangle, Check, X, Loader2, Clock, Trash2 } from "lucide-react";
+import { Button } from "../ui/button";
+import { cn } from "../lib/utils";
+import type { QueueItem } from "../../stores/batchQueueStore";
+
+interface BatchQueueViewProps {
+ queue: QueueItem[];
+ completedCount: number;
+ failedCount: number;
+ totalCount: number;
+ isProcessing: boolean;
+ onRemoveItem: (id: string) => void;
+ onCancelAll: () => void;
+ onClearQueue: () => void;
+ onOpenNote?: (noteId: number) => void;
+}
+
+function StatusIcon({ status }: { status: QueueItem["status"] }) {
+ switch (status) {
+ case "done":
+ return <Check size={12} className="text-success/70" />;
+ case "error":
+ return <X size={12} className="text-destructive/70" />;
+ case "queued":
+ return <Clock size={12} className="text-foreground/20" />;
+ default:
+ return <Loader2 size={12} className="text-primary/60 animate-spin" />;
+ }
+}
+
+export default function BatchQueueView({
+ queue,
+ completedCount,
+ failedCount,
+ totalCount,
+ isProcessing,
+ onRemoveItem,
+ onCancelAll,
+ onClearQueue,
+ onOpenNote,
+}: BatchQueueViewProps) {
+ const { t } = useTranslation();
+ const allDone =
+ queue.length > 0 && queue.every((i) => i.status === "done" || i.status === "error");
+ // Failed items still count as settled so the bar reaches 100% when the run ends.
+ const overallProgress =
+ totalCount > 0 ? Math.round(((completedCount + failedCount) / totalCount) * 100) : 0;
+
+ return (
+ <div style={{ animation: "float-up 0.3s ease-out" }}>
+ <div className="mb-3">
+ <div className="flex items-center justify-between mb-1.5">
+ <p className="text-xs text-foreground/50 font-medium">
+ {t("notes.upload.queueProgress", {
+ completed: completedCount,
+ total: totalCount,
+ })}
+ {failedCount > 0 && (
+ <span className="text-destructive/50 font-normal">
+ {" · "}
+ {t("notes.upload.queueFailed", { n: failedCount })}
+ </span>
+ )}
+ </p>
+ {allDone && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onClearQueue}
+ className="h-6 text-[10px] text-foreground/30"
+ >
+ {t("notes.upload.clearQueue")}
+ </Button>
+ )}
+ </div>
+ <div className="w-full h-[3px] rounded-full bg-foreground/5 dark:bg-white/5 overflow-hidden">
+ <div
+ className="h-full rounded-full bg-primary/50 transition-[width] duration-500 ease-out"
+ style={{ width: `${overallProgress}%` }}
+ />
+ </div>
+ </div>
+
+ <div className="space-y-1 max-h-[300px] overflow-y-auto">
+ {queue.map((item) => (
+ <div
+ key={item.id}
+ className={cn(
+ "flex items-center gap-2 px-2.5 py-1.5 rounded-md text-xs",
+ "bg-surface-1/30 dark:bg-white/[0.02] border border-foreground/4 dark:border-white/4",
+ item.status === "error" && "border-destructive/15"
+ )}
+ >
+ <StatusIcon status={item.status} />
+ <span className="flex-1 truncate text-foreground/60">{item.name}</span>
+
+ {item.status === "downloading" && (
+ <div className="w-16 h-[2px] rounded-full bg-foreground/5 overflow-hidden">
+ <div
+ className={cn(
+ "h-full rounded-full bg-primary/50 transition-[width] duration-300",
+ // Percent 0 = size unknown: pulse instead of an empty bar.
+ !item.progress && "animate-pulse"
+ )}
+ style={{ width: item.progress ? `${item.progress}%` : "100%" }}
+ />
+ </div>
+ )}
+
+ {item.status === "done" && item.warning && (
+ <span className="flex shrink-0" title={t("notes.upload.partialWarning")}>
+ <AlertTriangle size={11} className="text-amber-500/60" />
+ </span>
+ )}
+
+ {item.status === "done" && item.noteId && onOpenNote && (
+ <button
+ onClick={() => onOpenNote(item.noteId!)}
+ className="text-[10px] text-primary/50 hover:text-primary/70"
+ aria-label={t("notes.upload.openNote")}
+ >
+ {t("notes.upload.openNote")}
+ </button>
+ )}
+
+ {item.status === "error" && item.error && (
+ <span
+ className="text-[10px] text-destructive/50 truncate max-w-20"
+ title={t(`notes.upload.${item.error}`, { defaultValue: item.error })}
+ >
+ {t(`notes.upload.${item.error}`, { defaultValue: item.error })}
+ </span>
+ )}
+
+ {item.status === "queued" && (
+ <button
+ onClick={() => onRemoveItem(item.id)}
+ className="text-foreground/15 hover:text-foreground/40 transition-colors"
+ aria-label={t("notes.upload.removeFromQueue")}
+ >
+ <Trash2 size={10} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+
+ {isProcessing && !allDone && (
+ <div className="flex justify-center mt-3">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onCancelAll}
+ className="h-7 text-xs text-foreground/30"
+ >
+ {t("notes.upload.cancelAll")}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/notes/UploadAudioView.tsx b/src/components/notes/UploadAudioView.tsx
index 40ebdd01d..c5a6a8bfc 100644
--- a/src/components/notes/UploadAudioView.tsx
+++ b/src/components/notes/UploadAudioView.tsx
@@ -1,6 +1,16 @@
import React, { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
-import { Upload, FileAudio, X, AlertCircle, FolderOpen, Plus, Settings } from "lucide-react";
+import {
+ Upload,
+ FileAudio,
+ X,
+ AlertCircle,
+ ChevronRight,
+ FolderOpen,
+ Plus,
+ Settings,
+ Link2,
+} from "lucide-react";
import { useShallow } from "zustand/react/shallow";
import { Button } from "../ui/button";
import { cn } from "../lib/utils";
@@ -15,12 +25,16 @@ import {
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "../ui/dialog";
import { Input } from "../ui/input";
import type { FolderItem } from "../../types/electron";
-import { findDefaultFolder, MEETINGS_FOLDER_NAME } from "./shared";
+import {
+ findDefaultFolder,
+ findVideosFolder,
+ DOWNLOAD_ERROR_KEYS,
+ MEETINGS_FOLDER_NAME,
+} from "./shared";
import { useAuth } from "../../hooks/useAuth";
import { useUsage } from "../../hooks/useUsage";
import { useSettings } from "../../hooks/useSettings";
import { useStartOnboarding } from "../../hooks/useStartOnboarding";
-import { withSessionRefresh } from "../../lib/auth";
import { getAllReasoningModels, getBatchTranscriptionModel } from "../../models/ModelRegistry";
import {
useSettingsStore,
@@ -28,10 +42,20 @@ import {
selectResolvedUploadTranscription,
getSettings,
} from "../../stores/settingsStore";
+import { useBatchQueue } from "../../stores/batchQueueStore";
+import type { TranscribeOptions } from "../../stores/batchQueueStore";
+import { transcribeFileWithSpeakers, shouldUseByokDiarize } from "../../services/fileTranscription";
+import type {
+ FileTranscriptionConfig,
+ FileTranscriptionResult,
+ DiarizationSettings,
+} from "../../services/fileTranscription";
+import { MAX_SPEAKER_COUNT } from "../../constants/speakerDetection.json";
+import BatchQueueView from "./BatchQueueView";
import { generateNoteTitle } from "../../utils/generateTitle";
import { getBaseLanguageCode } from "../../utils/languageSupport";
-type UploadState = "idle" | "selected" | "transcribing" | "complete" | "error";
+type UploadState = "idle" | "selected" | "downloading" | "transcribing" | "complete" | "error";
const SUPPORTED_EXTENSIONS = ["mp3", "wav", "m4a", "webm", "ogg", "oga", "flac", "aac"];
@@ -39,12 +63,56 @@ const BYOK_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25 MB — hard limit for bring-y
const CLOUD_FREE_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25 MB — free plan cloud limit
const CLOUD_PRO_MAX_FILE_SIZE = 500 * 1024 * 1024; // 500 MB — pro plan cloud limit
+const MAX_BATCH_URLS = 50;
+
+const uploadFieldClass = cn(
+ "rounded-lg text-xs",
+ "bg-surface-1/40 dark:bg-white/[0.03] backdrop-blur-sm",
+ "border border-foreground/6 dark:border-white/6",
+ "text-foreground/70 placeholder:text-foreground/20",
+ "focus:outline-none focus:border-foreground/12 dark:focus:border-white/10",
+ "transition-colors"
+);
+
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
+function isYouTubeUrl(value: string): boolean {
+ try {
+ const host = new URL(value).hostname;
+ return host === "youtu.be" || host === "youtube.com" || host.endsWith(".youtube.com");
+ } catch {
+ return false;
+ }
+}
+
+function parseBatchUrls(text: string): { valid: string[]; skipped: number } {
+ const lines = text
+ .split("\n")
+ .map((l) => l.trim())
+ .filter((l) => l.length > 0);
+ const seen = new Set<string>();
+ const valid: string[] = [];
+ for (const line of lines) {
+ try {
+ const parsed = new URL(line);
+ const httpsOk = parsed.protocol === "https:";
+ const httpYoutubeOk = parsed.protocol === "http:" && isYouTubeUrl(line);
+ if ((httpsOk || httpYoutubeOk) && !seen.has(line)) {
+ seen.add(line);
+ valid.push(line);
+ }
+ } catch {
+ // invalid line, counted as skipped
+ }
+ }
+ const capped = valid.slice(0, MAX_BATCH_URLS);
+ return { valid: capped, skipped: lines.length - capped.length };
+}
+
interface UploadAudioViewProps {
onNoteCreated?: (noteId: number, folderId: number | null) => void;
onOpenSettings?: (section: string) => void;
@@ -58,6 +126,8 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
path: string;
size: string;
sizeBytes: number;
+ fromUrl?: boolean;
+ durationSeconds?: number | null;
} | null>(null);
const [result, setResult] = useState<string | null>(null);
const [partialWarning, setPartialWarning] = useState(false);
@@ -72,9 +142,82 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
} | null>(null);
const progressCleanupRef = useRef<(() => void) | null>(null);
const runIdRef = useRef(0);
+ const mountedRef = useRef(true);
+ const urlDownloadActiveRef = useRef(false);
+
+ const [urlInput, setUrlInput] = useState("");
+ const [downloadProgress, setDownloadProgress] = useState<{
+ stage: string;
+ percent: number;
+ title?: string;
+ } | null>(null);
+ const [downloadedTempPath, setDownloadedTempPath] = useState<string | null>(null);
+ const downloadedTempPathRef = useRef(downloadedTempPath);
+ useEffect(() => {
+ downloadedTempPathRef.current = downloadedTempPath;
+ }, [downloadedTempPath]);
+ const [urlExpanded, setUrlExpanded] = useState(false);
+ const [batchUrlNotice, setBatchUrlNotice] = useState<string | null>(null);
+ const singleDownloadIdRef = useRef<string | null>(null);
+
+ const batch = useBatchQueue();
+
+ const [diarizationEnabled, setDiarizationEnabled] = useState(
+ () => localStorage.getItem("uploadDiarizationEnabled") === "true"
+ );
+ const [diarizationNumSpeakers, setDiarizationNumSpeakers] = useState<string>(
+ () => localStorage.getItem("uploadDiarizationNumSpeakers") || ""
+ );
+ const [diarizationModelsReady, setDiarizationModelsReady] = useState<boolean | null>(null);
+ const [diarizationDownloading, setDiarizationDownloading] = useState(false);
+
+ useEffect(() => {
+ localStorage.setItem("uploadDiarizationEnabled", String(diarizationEnabled));
+ }, [diarizationEnabled]);
+
+ useEffect(() => {
+ localStorage.setItem("uploadDiarizationNumSpeakers", diarizationNumSpeakers);
+ }, [diarizationNumSpeakers]);
+
+ const diarizationDownloadRef = useRef(false);
+ const ensureDiarizationModels = async (): Promise<boolean> => {
+ if (diarizationDownloadRef.current) return false;
+ diarizationDownloadRef.current = true;
+ setDiarizationDownloading(true);
+ try {
+ await window.electronAPI.downloadDiarizationModels?.();
+ const status = await window.electronAPI.getDiarizationModelStatus?.();
+ const ready = status?.modelsDownloaded ?? false;
+ setDiarizationModelsReady(ready);
+ return ready;
+ } finally {
+ diarizationDownloadRef.current = false;
+ setDiarizationDownloading(false);
+ }
+ };
+
+ useEffect(() => {
+ window.electronAPI.getDiarizationModelStatus?.().then((status) => {
+ const ready = status?.modelsDownloaded ?? false;
+ setDiarizationModelsReady(ready);
+ // Heal a persisted-on toggle whose models were removed since; roll it back
+ // if the download fails so it can't sit ON while doing nothing.
+ if (!ready && localStorage.getItem("uploadDiarizationEnabled") === "true") {
+ if (shouldUseByokDiarize(buildTranscriptionConfig(), true)) return;
+ ensureDiarizationModels().then((ok) => {
+ if (!ok) setDiarizationEnabled(false);
+ });
+ }
+ });
+ // Mount-only by design: heals persisted state against the models on disk.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
const [folders, setFolders] = useState<FolderItem[]>([]);
const [selectedFolderId, setSelectedFolderId] = useState<string>("");
+ // Batch destination folder, deliberately separate from the single-flow one:
+ // handleFolderChange moves the already-saved note when noteId is set.
+ const [batchFolderId, setBatchFolderId] = useState<string>("");
const [showNewFolderDialog, setShowNewFolderDialog] = useState(false);
const [newFolderName, setNewFolderName] = useState("");
@@ -167,11 +310,27 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
};
}, []);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ if (urlDownloadActiveRef.current) {
+ window.electronAPI.cancelUrlDownload();
+ }
+ if (downloadedTempPathRef.current) {
+ window.electronAPI.deleteTempFile(downloadedTempPathRef.current);
+ }
+ };
+ }, []);
+
useEffect(() => {
window.electronAPI.getFolders?.().then((f) => {
setFolders(f);
const personal = findDefaultFolder(f);
- if (personal) setSelectedFolderId(String(personal.id));
+ if (personal) {
+ setSelectedFolderId(String(personal.id));
+ setBatchFolderId(String(personal.id));
+ }
});
}, []);
@@ -281,6 +440,33 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
}
};
+ const buildTranscriptionConfig = (): FileTranscriptionConfig => ({
+ useLocalWhisper,
+ localTranscriptionProvider: localTranscriptionProvider as string,
+ whisperModel,
+ parakeetModel,
+ isOpenWhisprCloud,
+ getApiKey: getActiveApiKey,
+ cloudTranscriptionProvider: cloudTranscriptionProvider as string,
+ cloudTranscriptionBaseUrl: cloudTranscriptionBaseUrl || "",
+ cloudTranscriptionModel,
+ language: getBaseLanguageCode(preferredLanguage) || "en",
+ cortiEnvironment,
+ cortiTenant,
+ transcriptionMode,
+ remoteTranscriptionUrl,
+ remoteTranscriptionModel,
+ });
+
+ // Batch counterpart of the single-file size gating above; returns keys under notes.upload.*.
+ const getBatchSizeErrorKey = (sizeBytes: number): string | null => {
+ if (useLocalWhisper || isSelfHosted || cloudTranscriptionProvider === "custom") return null;
+ if (isByok) return sizeBytes > BYOK_MAX_FILE_SIZE ? "byokTooLarge" : null;
+ if (sizeBytes > CLOUD_PRO_MAX_FILE_SIZE) return "fileTooLarge";
+ if (!isProUser && sizeBytes > CLOUD_FREE_MAX_FILE_SIZE) return "paidPlanRequired";
+ return null;
+ };
+
const generateTitle = async (text: string): Promise<string> => {
if (!useCleanupModel) return "";
if (!getSettings().autoGenerateNoteTitle) return "";
@@ -290,33 +476,64 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
};
const handleBrowse = async () => {
- const res = await window.electronAPI.selectAudioFile();
- if (!res.canceled && res.filePath) {
- const name = res.filePath.split(/[/\\]/).pop() || "audio";
- const sizeBytes = (await window.electronAPI.getFileSize?.(res.filePath)) ?? 0;
- setFile({
- name,
- path: res.filePath,
- size: sizeBytes ? formatFileSize(sizeBytes) : "",
- sizeBytes,
- });
+ const res = await window.electronAPI.selectAudioFile({ multiple: true });
+ if (res.canceled) return;
+
+ const filePaths: string[] = res.filePaths || (res.filePath ? [res.filePath] : []);
+ if (filePaths.length === 0) return;
+
+ // While a batch runs (or a queue exists), new files join the queue.
+ if (filePaths.length === 1 && !batch.isProcessing && !batch.hasQueue) {
+ const fp = filePaths[0];
+ const name = fp.split(/[/\\]/).pop() || "audio";
+ const sizeBytes = (await window.electronAPI.getFileSize?.(fp)) ?? 0;
+ setFile({ name, path: fp, size: sizeBytes ? formatFileSize(sizeBytes) : "", sizeBytes });
setState("selected");
setError(null);
+ return;
+ }
+
+ const items: Array<{ name: string; path: string; sizeBytes: number }> = [];
+ for (const fp of filePaths) {
+ const name = fp.split(/[/\\]/).pop() || "audio";
+ const sizeBytes = (await window.electronAPI.getFileSize?.(fp)) ?? 0;
+ items.push({ name, path: fp, sizeBytes });
}
+ batch.addFiles(items);
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
- const f = e.dataTransfer.files[0];
- if (!f) return;
- const ext = f.name.split(".").pop()?.toLowerCase() || "";
- if (SUPPORTED_EXTENSIONS.includes(ext)) {
- const filePath = window.electronAPI.getPathForFile(f);
- if (!filePath) return;
- setFile({ name: f.name, path: filePath, size: formatFileSize(f.size), sizeBytes: f.size });
+ const files = e.dataTransfer.files;
+ if (!files || files.length === 0) return;
+
+ const validFiles: Array<{ name: string; path: string; sizeBytes: number }> = [];
+ for (let i = 0; i < files.length; i++) {
+ const f = files[i];
+ const ext = f.name.split(".").pop()?.toLowerCase() || "";
+ if (SUPPORTED_EXTENSIONS.includes(ext)) {
+ const filePath = window.electronAPI.getPathForFile(f);
+ if (filePath) {
+ validFiles.push({ name: f.name, path: filePath, sizeBytes: f.size });
+ }
+ }
+ }
+
+ if (validFiles.length === 0) return;
+
+ if (validFiles.length === 1 && !batch.isProcessing && !batch.hasQueue) {
+ const f = validFiles[0];
+ setFile({
+ name: f.name,
+ path: f.path,
+ size: formatFileSize(f.sizeBytes),
+ sizeBytes: f.sizeBytes,
+ });
setState("selected");
setError(null);
+ } else {
+ batch.addFiles(validFiles);
}
};
@@ -324,6 +541,10 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
if (progressRef.current) clearInterval(progressRef.current);
if (progressCleanupRef.current) progressCleanupRef.current();
progressCleanupRef.current = null;
+ if (downloadedTempPath) {
+ window.electronAPI.deleteTempFile(downloadedTempPath);
+ setDownloadedTempPath(null);
+ }
setState("idle");
setFile(null);
setResult(null);
@@ -332,6 +553,9 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
setError(null);
setProgress(0);
setChunkProgress(null);
+ setUrlInput("");
+ setDownloadProgress(null);
+ setBatchUrlNotice(null);
const personal = findDefaultFolder(folders);
if (personal) setSelectedFolderId(String(personal.id));
};
@@ -342,7 +566,9 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
};
const handleTranscribe = async () => {
- if (!file) return;
+ if (!file || batch.isProcessing) return;
+ const currentFile = file;
+ const currentTempPath = downloadedTempPath;
const runId = ++runIdRef.current;
setState("transcribing");
setError(null);
@@ -375,40 +601,16 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
}
try {
- let res: { success: boolean; text?: string; error?: string; code?: string; warning?: string };
-
- if (isOpenWhisprCloud) {
- res = await withSessionRefresh(async () => {
- const r = await window.electronAPI.transcribeAudioFileCloud!(file.path);
- if (!r.success && r.code) {
- throw Object.assign(new Error(r.error || "Cloud transcription failed"), {
- code: r.code,
- });
- }
- return r;
- });
- } else if (useLocalWhisper) {
- res = await window.electronAPI.transcribeAudioFile(file.path, {
- provider: localTranscriptionProvider as "whisper" | "nvidia",
- model: localTranscriptionProvider === "nvidia" ? parakeetModel : whisperModel,
- });
- } else {
- // Self-hosted fields make the handler route to the configured server
- // (fail-closed on misconfiguration) instead of stale BYOK settings.
- res = await window.electronAPI.transcribeAudioFileByok!({
- filePath: file.path,
- apiKey: getActiveApiKey(),
- baseUrl: cloudTranscriptionBaseUrl || "",
- model: cloudTranscriptionModel,
- provider: cloudTranscriptionProvider,
- language: getBaseLanguageCode(preferredLanguage) || "en",
- environment: cortiEnvironment,
- tenant: cortiTenant,
- transcriptionMode,
- remoteTranscriptionUrl,
- remoteTranscriptionModel,
- });
- }
+ const res: FileTranscriptionResult = await transcribeFileWithSpeakers(
+ currentFile.path,
+ buildTranscriptionConfig(),
+ {
+ enabled: diarizationEnabled,
+ localModelsReady: !!diarizationModelsReady,
+ numSpeakers: diarizationNumSpeakers ? Number(diarizationNumSpeakers) : null,
+ },
+ currentFile.durationSeconds
+ );
if (runId !== runIdRef.current) return;
@@ -421,25 +623,35 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
setResult(res.text);
setPartialWarning(!!res.warning);
- const textFallback = res.text.trim().split(/\s+/).slice(0, 6).join(" ");
- const fallbackTitle =
- textFallback.length > 0
- ? textFallback + (res.text.trim().split(/\s+/).length > 6 ? "..." : "")
- : file.name.replace(/\.[^.]+$/, "");
- const aiTitle = await generateTitle(res.text);
- if (runId !== runIdRef.current) return;
- const title = aiTitle || fallbackTitle;
+ let title: string;
+ if (currentFile.fromUrl) {
+ title = currentFile.name;
+ } else {
+ const textFallback = res.text.trim().split(/\s+/).slice(0, 6).join(" ");
+ const fallbackTitle =
+ textFallback.length > 0
+ ? textFallback + (res.text.trim().split(/\s+/).length > 6 ? "..." : "")
+ : currentFile.name.replace(/\.[^.]+$/, "");
+ const aiTitle = await generateTitle(res.text);
+ if (runId !== runIdRef.current) return;
+ title = aiTitle || fallbackTitle;
+ }
const folderId = selectedFolderId ? Number(selectedFolderId) : null;
const noteRes = await window.electronAPI.saveNote(
title,
res.text,
"upload",
- file.name,
+ currentFile.name,
null,
folderId
);
+ if (runId !== runIdRef.current) return;
if (noteRes.success && noteRes.note) setNoteId(noteRes.note.id);
+ if (currentTempPath) {
+ window.electronAPI.deleteTempFile(currentTempPath);
+ setDownloadedTempPath(null);
+ }
setState("complete");
} else {
setProgress(0);
@@ -461,6 +673,141 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
}
};
+ const handleUrlSubmit = async () => {
+ const trimmed = urlInput.trim();
+ if (!trimmed) return;
+
+ // While a batch runs (or a queue exists), submitted URLs join the queue.
+ if (batch.isProcessing || batch.hasQueue) {
+ handleBatchUrlSubmit();
+ return;
+ }
+
+ let parsed: URL;
+ try {
+ parsed = new URL(trimmed);
+ } catch {
+ setError(t("notes.upload.urlInvalid"));
+ setState("error");
+ return;
+ }
+
+ // Main enforces HTTPS for direct downloads (YouTube http URLs get coerced),
+ // so reject here instead of surfacing a misleading late failure.
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isYouTubeUrl(trimmed))) {
+ setError(t("notes.upload.urlInvalid"));
+ setState("error");
+ return;
+ }
+
+ setState("downloading");
+ setError(null);
+ setDownloadProgress({ stage: "resolving", percent: 0 });
+
+ const downloadId = crypto.randomUUID();
+ singleDownloadIdRef.current = downloadId;
+ const cleanupProgress = window.electronAPI.onUrlDownloadProgress?.((data) => {
+ if (data.downloadId && data.downloadId !== downloadId) return;
+ setDownloadProgress(data);
+ });
+
+ urlDownloadActiveRef.current = true;
+ try {
+ const res = await window.electronAPI.downloadUrlAudio(trimmed, downloadId);
+
+ if (!mountedRef.current) {
+ // Unmounted mid-download: nothing owns the temp file anymore, delete it.
+ if (res.success) window.electronAPI.deleteTempFile(res.tempPath);
+ return;
+ }
+
+ if (!res.success) {
+ const fail = res as { success: false; error: string; code?: string };
+ if (fail.code === "DOWNLOAD_CANCELLED") {
+ setState("idle");
+ return;
+ }
+ const key = DOWNLOAD_ERROR_KEYS[fail.code || ""];
+ setError(
+ key ? t(`notes.upload.${key}`) : fail.error || t("notes.upload.urlDownloadFailed")
+ );
+ setState("error");
+ return;
+ }
+
+ setDownloadedTempPath(res.tempPath);
+ setFile({
+ name: res.title,
+ path: res.tempPath,
+ size: formatFileSize(res.sizeBytes),
+ sizeBytes: res.sizeBytes,
+ fromUrl: true,
+ durationSeconds: res.durationSeconds,
+ });
+ const videosFolder = findVideosFolder(folders);
+ if (videosFolder) setSelectedFolderId(String(videosFolder.id));
+ setState("selected");
+ } catch (e) {
+ setError(e instanceof Error ? e.message : t("notes.upload.urlDownloadFailed"));
+ setState("error");
+ } finally {
+ urlDownloadActiveRef.current = false;
+ singleDownloadIdRef.current = null;
+ cleanupProgress?.();
+ setDownloadProgress(null);
+ }
+ };
+
+ // Retry re-runs whatever failed: a selected file's transcription, or the URL download.
+ const handleRetry = () => {
+ if (file) {
+ handleTranscribe();
+ } else if (urlInput.trim()) {
+ handleUrlSubmit();
+ } else {
+ reset();
+ }
+ };
+
+ const handleCancelDownload = () => {
+ window.electronAPI.cancelUrlDownload(singleDownloadIdRef.current ?? undefined);
+ };
+
+ const handleBatchUrlSubmit = () => {
+ const { valid, skipped } = parseBatchUrls(urlInput);
+ if (valid.length > 0) {
+ batch.addUrls(valid);
+ // Same default the single-URL flow applies; the selector stays editable.
+ if (!batchFolderId) {
+ const videosFolder = findVideosFolder(folders);
+ if (videosFolder) setBatchFolderId(String(videosFolder.id));
+ }
+ setUrlInput("");
+ setUrlExpanded(false);
+ }
+ setBatchUrlNotice(skipped > 0 ? t("notes.upload.urlsSkipped", { n: skipped }) : null);
+ };
+
+ const startBatchProcessing = () => {
+ if (state === "downloading" || state === "transcribing") return;
+ setBatchUrlNotice(null);
+
+ const transcribeOpts: TranscribeOptions = {
+ transcription: buildTranscriptionConfig(),
+ folderId: batchFolderId ? Number(batchFolderId) : null,
+ validateSize: getBatchSizeErrorKey,
+ generateTitle: async (text) => (await generateTitle(text)) || null,
+ };
+
+ const diarization: DiarizationSettings = {
+ enabled: diarizationEnabled,
+ localModelsReady: !!diarizationModelsReady,
+ numSpeakers: diarizationNumSpeakers ? Number(diarizationNumSpeakers) : null,
+ };
+
+ batch.processQueue(transcribeOpts, diarization);
+ };
+
const handleCreateFolder = async () => {
const trimmed = newFolderName.trim();
if (!trimmed) return;
@@ -519,14 +866,168 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
)}
{state === "idle" && providerReady !== false && (
- <IdleView
- t={t}
- getActiveModelLabel={getActiveModelLabel}
- handleDrop={handleDrop}
- handleBrowse={handleBrowse}
- isDragOver={isDragOver}
- setIsDragOver={setIsDragOver}
- />
+ <>
+ <IdleView
+ t={t}
+ getActiveModelLabel={getActiveModelLabel}
+ handleDrop={handleDrop}
+ handleBrowse={handleBrowse}
+ isDragOver={isDragOver}
+ setIsDragOver={setIsDragOver}
+ />
+
+ <div className="flex items-center gap-3 my-3">
+ <div className="h-px flex-1 bg-foreground/5 dark:bg-white/5" />
+ <span className="text-[10px] text-foreground/20 uppercase tracking-wider">
+ {t("notes.upload.orDivider")}
+ </span>
+ <div className="h-px flex-1 bg-foreground/5 dark:bg-white/5" />
+ </div>
+
+ {urlExpanded ? (
+ <div>
+ <textarea
+ value={urlInput}
+ onChange={(e) => setUrlInput(e.target.value)}
+ placeholder={t("notes.upload.pasteUrls")}
+ rows={4}
+ className={cn(uploadFieldClass, "w-full px-3 py-2 resize-none")}
+ autoFocus
+ />
+ <div className="flex items-center gap-2 mt-2 justify-end">
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ setUrlExpanded(false);
+ setUrlInput("");
+ }}
+ className="h-7 text-xs text-foreground/30"
+ >
+ {t("notes.upload.cancel")}
+ </Button>
+ <Button
+ variant="default"
+ size="sm"
+ onClick={handleBatchUrlSubmit}
+ disabled={!urlInput.trim()}
+ className="h-7 text-xs"
+ >
+ {t("notes.upload.addToQueue")}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="relative">
+ {isYouTubeUrl(urlInput) ? (
+ <svg
+ viewBox="0 0 28 20"
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 w-[18px] h-[13px] z-10 pointer-events-none"
+ >
+ <rect width="28" height="20" rx="4" fill="#FF0000" />
+ <polygon points="11,4 11,16 21,10" fill="white" />
+ </svg>
+ ) : /\.(mp3|wav|m4a|ogg|flac|aac|webm|opus)(\?|$)/i.test(urlInput) ? (
+ <FileAudio
+ size={13}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-foreground/20 z-10 pointer-events-none"
+ />
+ ) : (
+ <Link2
+ size={13}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-foreground/20 z-10 pointer-events-none"
+ />
+ )}
+ <input
+ type="url"
+ value={urlInput}
+ onChange={(e) => setUrlInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleUrlSubmit();
+ }
+ }}
+ onFocus={() => {
+ if (urlInput.includes("\n")) setUrlExpanded(true);
+ }}
+ onPaste={(e) => {
+ const pasted = e.clipboardData.getData("text");
+ if (pasted.includes("\n")) {
+ e.preventDefault();
+ setUrlInput(pasted);
+ setUrlExpanded(true);
+ }
+ }}
+ placeholder={t("notes.upload.urlPlaceholder")}
+ className={cn(uploadFieldClass, "w-full h-8 pl-8 pr-9")}
+ />
+ <button
+ onClick={handleUrlSubmit}
+ disabled={!urlInput.trim()}
+ aria-label={t("notes.upload.urlSubmit")}
+ className={cn(
+ "absolute right-px top-px bottom-px w-7 rounded-r-[7px] flex items-center justify-center transition-colors",
+ "border-l border-foreground/6 dark:border-white/6",
+ urlInput.trim()
+ ? "text-foreground/40 hover:text-foreground/60 hover:bg-foreground/[0.03] dark:hover:bg-white/[0.03]"
+ : "text-foreground/10"
+ )}
+ >
+ <ChevronRight size={14} />
+ </button>
+ </div>
+ )}
+ </>
+ )}
+
+ {batchUrlNotice && (
+ <p className="text-[10px] text-amber-500/60 mt-2 text-center">{batchUrlNotice}</p>
+ )}
+
+ {batch.hasQueue && (
+ <div className="mt-3">
+ <BatchQueueView
+ queue={batch.queue}
+ completedCount={batch.completedCount}
+ failedCount={batch.failedCount}
+ totalCount={batch.totalCount}
+ isProcessing={batch.isProcessing}
+ onRemoveItem={batch.removeItem}
+ onCancelAll={batch.cancelAll}
+ onClearQueue={() => {
+ setBatchUrlNotice(null);
+ batch.clearQueue();
+ }}
+ onOpenNote={(noteId) =>
+ onNoteCreated?.(noteId, batchFolderId ? Number(batchFolderId) : null)
+ }
+ />
+
+ {!batch.isProcessing && batch.queue.some((i) => i.status === "queued") && (
+ <div className="mt-3 space-y-2">
+ {folders.length > 0 && (
+ <FolderSelect
+ t={t}
+ folders={folders}
+ value={batchFolderId}
+ onChange={setBatchFolderId}
+ />
+ )}
+ <div className="flex justify-center">
+ <Button
+ variant="default"
+ size="sm"
+ onClick={startBatchProcessing}
+ disabled={state === "downloading" || state === "transcribing"}
+ className="h-8 text-xs px-5"
+ >
+ {t("notes.upload.transcribe")}
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
)}
{state === "selected" && file && (
@@ -536,6 +1037,7 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
getActiveModelLabel={getActiveModelLabel}
reset={reset}
handleTranscribe={handleTranscribe}
+ transcribeDisabled={batch.isProcessing}
requiresUpgrade={!!requiresUpgrade}
fileTooLarge={fileTooLarge}
isLargeFile={isLargeFile}
@@ -549,6 +1051,66 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
/>
)}
+ {state === "downloading" && downloadProgress && (
+ <div
+ className="flex flex-col items-center"
+ style={{ animation: "float-up 0.3s ease-out" }}
+ >
+ <div className="flex items-end justify-center gap-[3px] h-10 mb-5">
+ {[0, 1, 2, 3, 4, 5, 6].map((i) => (
+ <div
+ key={i}
+ className="w-[3px] rounded-full bg-primary/40 dark:bg-primary/50 origin-bottom"
+ style={{
+ height: "100%",
+ animation: `waveform-bar ${0.8 + i * 0.12}s ease-in-out infinite`,
+ animationDelay: `${i * 0.08}s`,
+ }}
+ />
+ ))}
+ </div>
+
+ <div className="w-full max-w-[200px] h-[3px] rounded-full bg-foreground/5 dark:bg-white/5 overflow-hidden mb-3">
+ <div
+ className={cn(
+ "h-full rounded-full bg-primary/50 transition-[width] duration-500 ease-out",
+ // Percent 0 = size unknown (no content-length): pulse instead
+ // of sitting on an empty bar.
+ (downloadProgress.stage !== "downloading" || !downloadProgress.percent) &&
+ "animate-pulse"
+ )}
+ style={{
+ width:
+ downloadProgress.stage === "downloading" && downloadProgress.percent
+ ? `${Math.min(downloadProgress.percent, 100)}%`
+ : "100%",
+ }}
+ />
+ </div>
+
+ <p className="text-xs text-foreground/50 font-medium">
+ {downloadProgress.stage === "resolving"
+ ? t("notes.upload.urlResolving")
+ : t("notes.upload.urlDownloading")}
+ </p>
+
+ {downloadProgress.title && (
+ <p className="text-xs text-foreground/20 mt-1 truncate max-w-50">
+ {downloadProgress.title}
+ </p>
+ )}
+
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={handleCancelDownload}
+ className="mt-3 h-7 text-xs text-foreground/30"
+ >
+ {t("notes.upload.urlCancelDownload")}
+ </Button>
+ </div>
+ )}
+
{state === "transcribing" && (
<TranscribingView
t={t}
@@ -575,9 +1137,125 @@ export default function UploadAudioView({ onNoteCreated, onOpenSettings }: Uploa
)}
{state === "error" && error && (
- <ErrorView t={t} error={error} reset={reset} handleTranscribe={handleTranscribe} />
+ <ErrorView t={t} error={error} reset={reset} onRetry={handleRetry} />
)}
</div>
+
+ {(state === "idle" || state === "selected") && (
+ <div className="max-w-[320px] mx-auto mt-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <p className="text-xs text-foreground/40 font-medium">
+ {t("notes.upload.speakerDetection")}
+ </p>
+ <p className="text-[10px] text-foreground/20 mt-0.5">
+ {t("notes.upload.speakerDetectionDescription")}
+ </p>
+ </div>
+ <button
+ role="switch"
+ aria-checked={diarizationEnabled}
+ aria-label={t("notes.upload.speakerDetection")}
+ onClick={async () => {
+ if (diarizationDownloading) return;
+ const next = !diarizationEnabled;
+ setDiarizationEnabled(next);
+ // BYOK-native diarization needs no local models — don't download them.
+ if (
+ next &&
+ !diarizationModelsReady &&
+ !shouldUseByokDiarize(buildTranscriptionConfig(), true)
+ ) {
+ const ready = await ensureDiarizationModels();
+ if (!ready) setDiarizationEnabled(false);
+ }
+ }}
+ className={cn(
+ "relative w-7 h-4 rounded-full transition-colors shrink-0",
+ diarizationDownloading
+ ? "bg-primary/50 animate-pulse"
+ : diarizationEnabled
+ ? "bg-primary"
+ : "bg-muted"
+ )}
+ disabled={diarizationDownloading}
+ >
+ <div
+ className={cn(
+ "absolute top-0.5 left-0.5 w-3 h-3 rounded-full bg-white transition-transform",
+ diarizationEnabled ? "translate-x-3" : ""
+ )}
+ />
+ </button>
+ </div>
+
+ {diarizationEnabled &&
+ !useLocalWhisper &&
+ !isOpenWhisprCloud &&
+ !isSelfHosted &&
+ cloudTranscriptionProvider === "openai" && (
+ <p className="text-[10px] text-foreground/25 mt-1.5">
+ {t("notes.upload.openaiDiarizeNote")}
+ </p>
+ )}
+ {diarizationEnabled &&
+ !useLocalWhisper &&
+ !isOpenWhisprCloud &&
+ !isSelfHosted &&
+ cloudTranscriptionProvider === "mistral" && (
+ <p className="text-[10px] text-foreground/25 mt-1.5">
+ {t("notes.upload.mistralDiarizeNote")}
+ </p>
+ )}
+ {diarizationEnabled &&
+ !useLocalWhisper &&
+ !isOpenWhisprCloud &&
+ !isSelfHosted &&
+ cloudTranscriptionProvider === "groq" && (
+ <p className="text-[10px] text-amber-500/60 mt-1.5">
+ {t("notes.upload.groqDiarizeNote")}
+ </p>
+ )}
+
+ {diarizationDownloading && (
+ <p className="text-[10px] text-primary/50 mt-1.5">
+ {t("notes.upload.downloadingModels")}
+ </p>
+ )}
+
+ {diarizationEnabled && isOpenWhisprCloud && (
+ <p className="text-[10px] text-foreground/25 mt-1.5">
+ {t("notes.upload.diarizationRunsLocally")}
+ </p>
+ )}
+
+ {diarizationEnabled && diarizationModelsReady && (
+ <div className="mt-2">
+ <input
+ type="number"
+ min="2"
+ max={MAX_SPEAKER_COUNT}
+ value={diarizationNumSpeakers}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === "") {
+ setDiarizationNumSpeakers("");
+ return;
+ }
+ const n = Math.max(2, Math.min(MAX_SPEAKER_COUNT, Number(raw)));
+ setDiarizationNumSpeakers(String(isNaN(n) ? "" : n));
+ }}
+ placeholder={t("notes.upload.numSpeakersPlaceholder")}
+ aria-label={t("notes.upload.numSpeakersPlaceholder")}
+ className={cn(
+ uploadFieldClass,
+ "w-full h-8 px-2.5 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ )}
+ />
+ </div>
+ )}
+ </div>
+ )}
</div>
<Dialog open={showNewFolderDialog} onOpenChange={setShowNewFolderDialog}>
@@ -778,6 +1456,7 @@ interface SelectedViewProps {
getActiveModelLabel: () => string;
reset: () => void;
handleTranscribe: () => void;
+ transcribeDisabled: boolean;
requiresUpgrade: boolean;
fileTooLarge: boolean;
isLargeFile: boolean;
@@ -796,6 +1475,7 @@ function SelectedView({
getActiveModelLabel,
reset,
handleTranscribe,
+ transcribeDisabled,
requiresUpgrade,
fileTooLarge,
isLargeFile,
@@ -919,6 +1599,7 @@ function SelectedView({
variant="default"
size="sm"
onClick={handleTranscribe}
+ disabled={transcribeDisabled}
className="h-8 text-xs px-5"
>
{t("notes.upload.transcribe")}
@@ -1005,6 +1686,68 @@ function TranscribingView({
);
}
+interface FolderSelectProps {
+ t: (key: string) => string;
+ folders: FolderItem[];
+ value: string;
+ onChange: (val: string) => void;
+ includeCreateNew?: boolean;
+ className?: string;
+}
+
+function FolderSelect({
+ t,
+ folders,
+ value,
+ onChange,
+ includeCreateNew,
+ className,
+}: FolderSelectProps) {
+ return (
+ <div className={cn("flex items-center justify-center gap-2", className)}>
+ <FolderOpen size={12} className="text-foreground/20 shrink-0" />
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger className="h-7 w-44 text-xs rounded-lg px-2.5 [&>svg]:h-3 [&>svg]:w-3">
+ <SelectValue placeholder={t("notes.upload.selectFolder")} />
+ </SelectTrigger>
+ <SelectContent>
+ {folders.map((f) => {
+ const isMeetings = f.name === MEETINGS_FOLDER_NAME && !!f.is_default;
+ return (
+ <SelectItem
+ key={f.id}
+ value={String(f.id)}
+ disabled={isMeetings}
+ className="text-xs py-1.5 pl-2.5 pr-7 rounded-md"
+ >
+ <span className="flex items-center gap-1.5">
+ {f.name}
+ {isMeetings && (
+ <span className="text-[8px] uppercase tracking-wider text-foreground/25 font-medium">
+ {t("notes.folders.soon")}
+ </span>
+ )}
+ </span>
+ </SelectItem>
+ );
+ })}
+ {includeCreateNew && (
+ <>
+ <SelectSeparator />
+ <SelectItem value="__create_new__" className="text-xs py-1.5 pl-2.5 pr-7 rounded-md">
+ <span className="flex items-center gap-1.5 text-primary/60">
+ <Plus size={11} />
+ {t("notes.upload.newFolder")}
+ </span>
+ </SelectItem>
+ </>
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
+
interface CompleteViewProps {
t: (key: string) => string;
result: string;
@@ -1082,43 +1825,14 @@ function CompleteView({
)}
{folders.length > 0 && (
- <div className="flex items-center justify-center gap-2 mb-4">
- <FolderOpen size={12} className="text-foreground/20 shrink-0" />
- <Select value={selectedFolderId} onValueChange={handleFolderChange}>
- <SelectTrigger className="h-7 w-44 text-xs rounded-lg px-2.5 [&>svg]:h-3 [&>svg]:w-3">
- <SelectValue placeholder={t("notes.upload.selectFolder")} />
- </SelectTrigger>
- <SelectContent>
- {folders.map((f) => {
- const isMeetings = f.name === MEETINGS_FOLDER_NAME && !!f.is_default;
- return (
- <SelectItem
- key={f.id}
- value={String(f.id)}
- disabled={isMeetings}
- className="text-xs py-1.5 pl-2.5 pr-7 rounded-md"
- >
- <span className="flex items-center gap-1.5">
- {f.name}
- {isMeetings && (
- <span className="text-[8px] uppercase tracking-wider text-foreground/25 font-medium">
- {t("notes.folders.soon")}
- </span>
- )}
- </span>
- </SelectItem>
- );
- })}
- <SelectSeparator />
- <SelectItem value="__create_new__" className="text-xs py-1.5 pl-2.5 pr-7 rounded-md">
- <span className="flex items-center gap-1.5 text-primary/60">
- <Plus size={11} />
- {t("notes.upload.newFolder")}
- </span>
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
+ <FolderSelect
+ t={t}
+ folders={folders}
+ value={selectedFolderId}
+ onChange={handleFolderChange}
+ includeCreateNew
+ className="mb-4"
+ />
)}
<div className="flex items-center gap-2">
@@ -1151,10 +1865,10 @@ interface ErrorViewProps {
t: (key: string) => string;
error: string;
reset: () => void;
- handleTranscribe: () => void;
+ onRetry: () => void;
}
-function ErrorView({ t, error, reset, handleTranscribe }: ErrorViewProps) {
+function ErrorView({ t, error, reset, onRetry }: ErrorViewProps) {
return (
<div style={{ animation: "float-up 0.3s ease-out" }}>
<div className="rounded-lg border border-destructive/15 dark:border-destructive/20 bg-destructive/[0.03] dark:bg-destructive/[0.05] backdrop-blur-sm p-4 mb-4">
@@ -1174,7 +1888,7 @@ function ErrorView({ t, error, reset, handleTranscribe }: ErrorViewProps) {
<Button
variant="ghost"
size="sm"
- onClick={handleTranscribe}
+ onClick={onRetry}
className="h-7 text-xs text-foreground/40"
>
{t("notes.upload.retry")}
diff --git a/src/components/notes/shared.ts b/src/components/notes/shared.ts
index af1cb6f07..de0760dd6 100644
--- a/src/components/notes/shared.ts
+++ b/src/components/notes/shared.ts
@@ -3,11 +3,30 @@ import type { FolderItem } from "../../types/electron";
export const DEFAULT_FOLDER_NAME = "Personal";
export const MEETINGS_FOLDER_NAME = "Meetings";
+export const VIDEOS_FOLDER_NAME = "Videos";
export function findDefaultFolder(folders: FolderItem[]): FolderItem | undefined {
return folders.find((f) => f.name === DEFAULT_FOLDER_NAME && f.is_default);
}
+// URL downloads route to "Videos" by name: a pre-existing user-created folder with
+// that name is used as-is (the migration never promotes or replaces it).
+export function findVideosFolder(folders: FolderItem[]): FolderItem | undefined {
+ return folders.find((f) => f.name === VIDEOS_FOLDER_NAME);
+}
+
+// URL-download error codes → notes.upload.* i18n keys.
+export const DOWNLOAD_ERROR_KEYS: Record<string, string> = {
+ INVALID_URL: "urlInvalid",
+ VIDEO_UNAVAILABLE: "urlVideoUnavailable",
+ PLAYLIST_URL: "urlPlaylistNotSupported",
+ CONTENT_TYPE_INVALID: "urlContentTypeInvalid",
+ DOWNLOAD_FAILED: "urlDownloadFailed",
+ FILE_TOO_LARGE: "urlFileTooLarge",
+ YOUTUBE_BLOCKED: "urlYoutubeBlocked",
+ SSRF_BLOCKED: "urlDownloadFailed",
+};
+
export const notesInputClass = cn(
"w-full h-8 px-3 rounded-md text-xs",
"bg-foreground/3 dark:bg-white/4 border border-border/30 dark:border-white/6",
diff --git a/src/helpers/database.js b/src/helpers/database.js
index eabfa59a7..426dc4aaa 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -196,6 +196,7 @@ class DatabaseManager {
);
seedFolder.run("Personal", 0);
seedFolder.run("Meetings", 1);
+ seedFolder.run("Videos", 2);
}
try {
@@ -213,6 +214,23 @@ class DatabaseManager {
.run(personalFolder.id);
}
+ // One-time seed (user_version 1): a pre-existing user-created "Videos"
+ // folder stays untouched (never promoted to default); URL downloads route
+ // to it by name. Guarded so a later delete/rename doesn't resurrect it as
+ // an undeletable default on the next launch.
+ if (this.db.pragma("user_version", { simple: true }) < 1) {
+ const videosFolder = this.db.prepare("SELECT id FROM folders WHERE name = 'Videos'").get();
+ if (!videosFolder) {
+ const maxOrder = this.db.prepare("SELECT MAX(sort_order) as m FROM folders").get();
+ this.db
+ .prepare(
+ "INSERT OR IGNORE INTO folders (name, is_default, sort_order) VALUES ('Videos', 1, ?)"
+ )
+ .run((maxOrder?.m ?? 1) + 1);
+ }
+ this.db.pragma("user_version = 1");
+ }
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
diff --git a/src/helpers/debugLogger.js b/src/helpers/debugLogger.js
index 8fbbe7d01..1cb7b4303 100644
--- a/src/helpers/debugLogger.js
+++ b/src/helpers/debugLogger.js
@@ -199,7 +199,8 @@ class DebugLogger {
: console.log;
if (meta !== undefined) {
- consoleFn(`${levelTag}${scopeTag}${sourceTag} ${message}`, meta);
+ // Pass the prefix as a %s arg, not as a format string. See CodeQL js/tainted-format-string.
+ consoleFn("%s", `${levelTag}${scopeTag}${sourceTag} ${message}`, meta);
} else {
consoleFn(`${levelTag}${scopeTag}${sourceTag} ${message}`);
}
diff --git a/src/helpers/diarization.js b/src/helpers/diarization.js
index bbca06802..6cc390e7e 100644
--- a/src/helpers/diarization.js
+++ b/src/helpers/diarization.js
@@ -16,7 +16,7 @@ const {
buildMergedCandidates,
} = require("./transcriptText");
-const DIARIZATION_TIMEOUT_MS = 300000; // 5 minutes
+const DIARIZATION_TIMEOUT_MS = 3600000; // 60 minutes
const POST_MERGE_CONTEXT_WINDOW_MS = 6000;
const POST_MERGE_CONTEXT_MERGE_LIMIT = 3;
@@ -60,7 +60,9 @@ const SILERO_VAD_ONNX = "silero_vad.onnx";
class DiarizationManager {
constructor() {
- this._process = null;
+ // Meeting post-processing and upload/batch diarization can overlap, so
+ // track every live process, not a single slot.
+ this._processes = new Set();
this.currentDownloadProcess = null;
this.cachedBinaryPath = null;
}
@@ -352,13 +354,21 @@ class DiarizationManager {
detached: process.platform !== "win32",
});
- this._process = proc;
+ this._processes.add(proc);
sidecarPidFile.write("diarization", proc.pid);
+ // The single pid-file slot tracks whichever process is still alive; only
+ // the reaper consumes it, and the Set is the real shutdown source.
+ const untrack = () => {
+ this._processes.delete(proc);
+ const survivor = this._processes.values().next().value;
+ if (survivor) sidecarPidFile.write("diarization", survivor.pid);
+ else sidecarPidFile.clear("diarization");
+ };
+
const timeout = setTimeout(() => {
debugLogger.warn("Diarization timed out", { timeoutMs: DIARIZATION_TIMEOUT_MS });
gracefulStopProcess(proc);
- this._process = null;
resolve([]);
}, DIARIZATION_TIMEOUT_MS);
@@ -372,8 +382,7 @@ class DiarizationManager {
proc.on("close", (code) => {
clearTimeout(timeout);
- this._process = null;
- sidecarPidFile.clear("diarization");
+ untrack();
if (code !== 0) {
debugLogger.warn("Diarization process exited with error", {
@@ -391,8 +400,7 @@ class DiarizationManager {
proc.on("error", (err) => {
clearTimeout(timeout);
- this._process = null;
- sidecarPidFile.clear("diarization");
+ untrack();
debugLogger.warn("Diarization process error", { error: err.message });
resolve([]);
});
@@ -517,9 +525,10 @@ class DiarizationManager {
}
const tempDir = getSafeTempDir();
- const timestamp = Date.now();
- const inputWavPath = path.join(tempDir, `ow-diarize-${timestamp}-input.wav`);
- const wavPath = path.join(tempDir, `ow-diarize-${timestamp}.wav`);
+ // Random suffix: concurrent conversions (meeting + upload) must never collide.
+ const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const inputWavPath = path.join(tempDir, `ow-diarize-${runId}-input.wav`);
+ const wavPath = path.join(tempDir, `ow-diarize-${runId}.wav`);
// Stream: write 44-byte WAV header, then pipe raw PCM — avoids loading entire file into memory
const header = this._createWavHeader(stat.size, inputSampleRate, 1);
@@ -591,10 +600,9 @@ class DiarizationManager {
}
async shutdown() {
- if (this._process) {
- await gracefulStopProcess(this._process);
- this._process = null;
- }
+ const procs = [...this._processes];
+ this._processes.clear();
+ await Promise.all(procs.map((p) => gracefulStopProcess(p)));
}
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index b242f4926..142d6de68 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -131,6 +131,54 @@ const CLOUD_CHUNK_CONCURRENCY = 5;
const CLOUD_CHUNK_SEGMENT_SECONDS = 240;
const CLOUD_CHUNK_MAX_ATTEMPTS = 3;
+const {
+ formatTimestamp: formatDiarTime,
+ mergeSpeakersWithText,
+ formatSpeakerTranscript,
+} = require("./speakerMerge");
+
+// Canonicalize allowed dirs so realpath'd inputs match on macOS (/var -> /private/var).
+// Deliberately narrow: user-picked paths anywhere else are approved individually via
+// approvedAudioPaths, so a compromised renderer can't read arbitrary files.
+function getCanonicalAllowedAudioDirs() {
+ const os = require("os");
+ const { getSafeTempDir } = require("./safeTempDir");
+ const dirs = [os.tmpdir(), getSafeTempDir(), app.getPath("userData")];
+ return dirs.map((d) => {
+ try {
+ return fs.realpathSync(d);
+ } catch {
+ return d;
+ }
+ });
+}
+
+// User-picked paths (OS file dialog, real drag-dropped files) may live outside the
+// static dirs (external volumes, /mnt, D:\) and are approved individually.
+const approvedAudioPaths = new Set();
+
+function approveAudioPath(filePath) {
+ if (typeof filePath !== "string" || !filePath) return;
+ try {
+ approvedAudioPaths.add(fs.realpathSync(path.resolve(filePath)));
+ } catch {
+ // File vanished or unreadable; nothing to approve.
+ }
+}
+
+// Returns the realpath'd file path if it lives under an allowed dir, else null.
+function resolveAllowedAudioPath(filePath) {
+ const real = fs.realpathSync(path.resolve(filePath));
+ if (approvedAudioPaths.has(real)) {
+ return real;
+ }
+ const allowed = getCanonicalAllowedAudioDirs();
+ if (allowed.some((dir) => real === dir || real.startsWith(dir + path.sep))) {
+ return real;
+ }
+ return null;
+}
+
function buildMultipartBody(fileBuffer, fileName, contentType, fields = {}) {
const boundary = `----OpenWhispr${Date.now()}`;
const parts = [];
@@ -416,7 +464,17 @@ class IPCHandlers {
}
_setWhisperVadSettings(update = {}) {
- this.whisperVadSettings = { ...this._getWhisperVadSettings(), ...update };
+ const ALLOWED_KEYS = new Set([
+ "dictationSileroEnabled",
+ "noteRecordingSileroEnabled",
+ "meetingSileroEnabled",
+ ...Object.keys(require("../constants/whisperVad.json").DEFAULTS),
+ ]);
+ const filtered = {};
+ for (const [k, v] of Object.entries(update)) {
+ if (ALLOWED_KEYS.has(k)) filtered[k] = v;
+ }
+ this.whisperVadSettings = { ...this._getWhisperVadSettings(), ...filtered };
return this._getWhisperVadSettings();
}
@@ -1634,10 +1692,12 @@ class IPCHandlers {
}
});
- ipcMain.handle("select-audio-file", async () => {
+ ipcMain.handle("select-audio-file", async (event, options = {}) => {
const { dialog } = require("electron");
+ const properties = ["openFile"];
+ if (options.multiple === true) properties.push("multiSelections");
const result = await dialog.showOpenDialog({
- properties: ["openFile"],
+ properties,
filters: [
{
name: "Audio Files",
@@ -1648,23 +1708,122 @@ class IPCHandlers {
if (result.canceled || !result.filePaths.length) {
return { canceled: true };
}
+ result.filePaths.forEach(approveAudioPath);
+ if (options.multiple === true) {
+ return { canceled: false, filePaths: result.filePaths };
+ }
return { canceled: false, filePath: result.filePaths[0] };
});
+ // Fired by the preload's getPathForFile for real drag-dropped files; a
+ // renderer-constructed File yields "" there, so this can't be forged.
+ ipcMain.on("approve-audio-path", (_event, filePath) => {
+ approveAudioPath(filePath);
+ });
+
ipcMain.handle("get-file-size", async (_event, filePath) => {
const fs = require("fs");
try {
- const stats = fs.statSync(filePath);
+ if (typeof filePath !== "string") return 0;
+ const real = resolveAllowedAudioPath(filePath);
+ if (!real) return 0;
+ const stats = fs.statSync(real);
return stats.size;
} catch {
return 0;
}
});
+ const activeUrlDownloads = new Map();
+ let urlDownloadSeq = 0;
+
+ // Sweep ow-url-*/ow-diarize-* orphans from crashes or windows closed mid-download.
+ require("./urlAudioDownloader").sweepStaleTempArtifacts();
+
+ ipcMain.handle("download-url-audio", async (event, url, downloadId) => {
+ if (typeof url !== "string" || url.length > 2048) {
+ return { success: false, error: "Invalid URL", code: "INVALID_URL" };
+ }
+ const { download } = require("./urlAudioDownloader");
+
+ const id =
+ typeof downloadId === "string" && downloadId ? downloadId : `dl-${++urlDownloadSeq}`;
+ const abortController = new AbortController();
+ activeUrlDownloads.set(id, abortController);
+
+ try {
+ const result = await download(
+ url,
+ (progress) => {
+ if (!event.sender.isDestroyed()) {
+ event.sender.send("url-download-progress", { ...progress, downloadId: id });
+ }
+ },
+ abortController.signal
+ );
+ return { success: true, ...result };
+ } catch (error) {
+ debugLogger.error("URL audio download error", { error: error.message, code: error.code });
+ return { success: false, error: error.message, code: error.code || "DOWNLOAD_FAILED" };
+ } finally {
+ if (activeUrlDownloads.get(id) === abortController) {
+ activeUrlDownloads.delete(id);
+ }
+ }
+ });
+
+ // With an id, cancels that download; without, cancels all (unmount cleanup).
+ ipcMain.handle("cancel-url-download", async (_event, downloadId) => {
+ if (typeof downloadId === "string" && downloadId) {
+ const controller = activeUrlDownloads.get(downloadId);
+ if (!controller) return { success: false };
+ controller.abort();
+ activeUrlDownloads.delete(downloadId);
+ return { success: true };
+ }
+ if (activeUrlDownloads.size === 0) return { success: false };
+ for (const controller of activeUrlDownloads.values()) controller.abort();
+ activeUrlDownloads.clear();
+ return { success: true };
+ });
+
+ ipcMain.handle("delete-temp-file", async (event, filePath) => {
+ try {
+ if (typeof filePath !== "string") {
+ return { success: false, error: "Invalid file path" };
+ }
+ const { getSafeTempDir } = require("./safeTempDir");
+ const resolved = path.resolve(filePath);
+ const basename = path.basename(resolved);
+ if (!basename.startsWith("ow-url-") && !basename.startsWith("ow-diarize-")) {
+ return { success: false, error: "Not an OpenWhispr temp file" };
+ }
+ const real = fs.realpathSync(resolved);
+ let tempDir = getSafeTempDir();
+ try {
+ tempDir = fs.realpathSync(tempDir);
+ } catch {}
+ const rel = path.relative(tempDir, real);
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
+ return { success: false, error: "Not an OpenWhispr temp file" };
+ }
+ fs.unlinkSync(real);
+ return { success: true };
+ } catch (error) {
+ debugLogger.warn("Failed to delete temp file", { error: error.message });
+ return { success: false, error: error.message };
+ }
+ });
+
ipcMain.handle("transcribe-audio-file", async (event, filePath, options = {}) => {
const fs = require("fs");
try {
- const audioBuffer = fs.readFileSync(filePath);
+ if (typeof filePath !== "string") {
+ return { success: false, error: "Invalid file path" };
+ }
+ const real = resolveAllowedAudioPath(filePath);
+ 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);
return result;
@@ -2207,6 +2366,75 @@ class IPCHandlers {
}
});
+ ipcMain.handle("diarize-audio-file", async (event, filePath, options = {}) => {
+ try {
+ if (!this.diarizationManager) {
+ return { success: false, error: "Diarization not available" };
+ }
+ if (!this.diarizationManager.isModelDownloaded()) {
+ return { success: false, error: "Diarization models not downloaded" };
+ }
+
+ if (typeof filePath !== "string") {
+ return { success: false, error: "Invalid file path" };
+ }
+ const realPath = resolveAllowedAudioPath(filePath);
+ if (!realPath) return { success: false, error: "File path not allowed" };
+ filePath = realPath;
+
+ const diarOpts = {
+ numSpeakers: Math.min(
+ MAX_SPEAKER_COUNT,
+ Math.max(-1, Math.round(Number(options.numSpeakers) || -1))
+ ),
+ threshold: Math.min(1, Math.max(0, Number(options.threshold) || 0.55)),
+ };
+
+ const { convertToWav } = require("./ffmpegUtils");
+ const { getSafeTempDir } = require("./safeTempDir");
+ const wavPath = path.join(getSafeTempDir(), `ow-diarize-${Date.now()}.wav`);
+
+ try {
+ await convertToWav(filePath, wavPath, { sampleRate: 16000, channels: 1 });
+ const segments = await this.diarizationManager.diarize(wavPath, diarOpts);
+ return { success: true, segments };
+ } finally {
+ try {
+ fs.unlinkSync(wavPath);
+ } catch {}
+ }
+ } catch (error) {
+ debugLogger.error("Diarization error", { error: error.message });
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("merge-speaker-text", async (event, { segments, text, duration }) => {
+ try {
+ if (
+ !Array.isArray(segments) ||
+ typeof text !== "string" ||
+ typeof duration !== "number" ||
+ !isFinite(duration)
+ ) {
+ return { success: false, error: "Invalid arguments" };
+ }
+ if (segments.length > 10000 || text.length > 1_000_000) {
+ return { success: false, error: "Input too large" };
+ }
+ const sanitizedSegments = segments.map((s) => ({
+ speaker: typeof s.speaker === "string" ? s.speaker.slice(0, 100) : "unknown",
+ start: typeof s.start === "number" && isFinite(s.start) ? s.start : 0,
+ end: typeof s.end === "number" && isFinite(s.end) ? s.end : 0,
+ }));
+ const merged = mergeSpeakersWithText(sanitizedSegments, text, duration);
+ return { success: true, text: formatSpeakerTranscript(merged) };
+ } catch (error) {
+ debugLogger.error("Speaker merge error", { error: error.message });
+ return { success: false, error: error.message };
+ }
+ });
+
ipcMain.handle("cancel-diarization-download", async () => {
return this.diarizationManager.cancelDownload();
});
@@ -6800,6 +7028,14 @@ class IPCHandlers {
const apiUrl = getApiUrl();
if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
+ if (typeof opts?.path !== "string" || !opts.path.startsWith("/")) {
+ return { success: false, error: "Invalid API path" };
+ }
+ const targetUrl = new URL(opts.path, apiUrl);
+ if (targetUrl.origin !== new URL(apiUrl).origin) {
+ return { success: false, error: "Invalid API path" };
+ }
+
const authHeader = await getAuthHeader(event);
if (!Object.keys(authHeader).length) throw new Error("Not authenticated");
@@ -6916,6 +7152,12 @@ class IPCHandlers {
ipcMain.handle("transcribe-audio-file-cloud", async (event, filePath) => {
try {
+ if (typeof filePath !== "string") {
+ return { success: false, error: "Invalid file path" };
+ }
+ const realCloud = resolveAllowedAudioPath(filePath);
+ if (!realCloud) return { success: false, error: "File path not allowed" };
+
const apiUrl = getApiUrl();
if (!apiUrl) throw new Error("OpenWhispr API URL not configured");
@@ -6930,15 +7172,15 @@ class IPCHandlers {
sessionId: this.sessionId,
};
- const fileSize = fs.statSync(filePath).size;
+ const fileSize = fs.statSync(realCloud).size;
if (fileSize > CLOUD_INLINE_LIMIT) {
debugLogger.debug("Large file detected, using client-side chunking", {
fileSize,
- filePath: path.basename(filePath),
+ filePath: path.basename(realCloud),
});
const { text, warning } = await chunkedCloudTranscribe({
- filePath,
+ filePath: realCloud,
apiUrl,
authHeader,
multipartFields,
@@ -6947,10 +7189,10 @@ class IPCHandlers {
return { success: true, text, ...(warning ? { warning } : {}) };
}
- const audioBuffer = fs.readFileSync(filePath);
- const ext = path.extname(filePath).toLowerCase().replace(".", "");
+ const audioBuffer = fs.readFileSync(realCloud);
+ const ext = path.extname(realCloud).toLowerCase().replace(".", "");
const contentType = AUDIO_MIME_TYPES[ext] || "audio/mpeg";
- const fileName = path.basename(filePath);
+ const fileName = path.basename(realCloud);
const { body, boundary } = buildMultipartBody(
audioBuffer,
@@ -6981,6 +7223,7 @@ class IPCHandlers {
apiKey,
baseUrl,
model,
+ diarize,
provider,
language,
environment,
@@ -6993,6 +7236,12 @@ class IPCHandlers {
const fs = require("fs");
const BYOK_FILE_SIZE_LIMIT = 25 * 1024 * 1024; // 25 MB
try {
+ if (typeof filePath !== "string") {
+ return { success: false, error: "Invalid file path" };
+ }
+ const realByok = resolveAllowedAudioPath(filePath);
+ if (!realByok) return { success: false, error: "File path not allowed" };
+
const { resolveSelfHostedRetryRoute } = await import("./retryTranscriptionRouting.js");
const selfHostedRoute = resolveSelfHostedRetryRoute({
transcriptionMode,
@@ -7007,10 +7256,10 @@ class IPCHandlers {
if (selfHostedRoute?.kind === "self-hosted") {
// User's own server, so the 25 MB third-party cap does not apply.
- const ext = path.extname(filePath).toLowerCase().replace(".", "");
+ const ext = path.extname(realByok).toLowerCase().replace(".", "");
const { body, boundary } = buildMultipartBody(
- fs.readFileSync(filePath),
- path.basename(filePath),
+ fs.readFileSync(realByok),
+ path.basename(realByok),
AUDIO_MIME_TYPES[ext] || "audio/mpeg",
{ model: selfHostedRoute.model, language }
);
@@ -7025,7 +7274,7 @@ class IPCHandlers {
return { success: true, text: data.data.text };
}
- const fileSize = fs.statSync(filePath).size;
+ const fileSize = fs.statSync(realByok).size;
if (fileSize > BYOK_FILE_SIZE_LIMIT) {
return {
success: false,
@@ -7045,17 +7294,17 @@ class IPCHandlers {
tenant,
clientId,
clientSecret,
- audioBuffer: fs.readFileSync(filePath),
+ audioBuffer: fs.readFileSync(realByok),
language: language || "en",
});
return { success: true, text };
}
if (provider === "tinfoil") {
- const ext = path.extname(filePath).toLowerCase().replace(".", "");
+ const ext = path.extname(realByok).toLowerCase().replace(".", "");
const { text } = await transcribeWithTinfoil({
- audioBuffer: fs.readFileSync(filePath),
- fileName: path.basename(filePath),
+ audioBuffer: fs.readFileSync(realByok),
+ fileName: path.basename(realByok),
contentType: AUDIO_MIME_TYPES[ext] || "audio/mpeg",
language,
apiKey: this.environmentManager.getTinfoilKey(),
@@ -7068,10 +7317,10 @@ class IPCHandlers {
throw new Error("No transcription endpoint configured.");
}
- const audioBuffer = fs.readFileSync(filePath);
- const ext = path.extname(filePath).toLowerCase().replace(".", "");
+ const audioBuffer = fs.readFileSync(realByok);
+ const ext = path.extname(realByok).toLowerCase().replace(".", "");
const contentType = AUDIO_MIME_TYPES[ext] || "audio/mpeg";
- const fileName = path.basename(filePath);
+ const fileName = path.basename(realByok);
let transcriptionUrl;
const multipartFields = {};
@@ -7090,6 +7339,34 @@ class IPCHandlers {
multipartFields.model = model || "whisper-1";
}
+ if (diarize) {
+ let isMistral = false;
+ let isOpenAi = false;
+ try {
+ const h = new URL(baseUrl).hostname;
+ isMistral = h.endsWith(".mistral.ai") || h === "mistral.ai";
+ isOpenAi = h.endsWith(".openai.com") || h === "openai.com";
+ } catch {}
+ if (isMistral) {
+ multipartFields.model = model || "voxtral-mini-latest";
+ multipartFields.diarize = "true";
+ multipartFields.timestamp_granularities = "segment";
+ } else if (isOpenAi) {
+ multipartFields.model = "gpt-4o-transcribe-diarize";
+ // Speaker annotations require diarized_json; verbose_json is not supported by this model.
+ multipartFields.response_format = "diarized_json";
+ multipartFields.chunking_strategy = "auto";
+ } else {
+ // The renderer gates on provider name; this re-check is by hostname.
+ // A non-canonical base URL (Azure/OpenAI-compatible gateway) can
+ // disagree — degrade to a plain transcript, never fail the upload.
+ debugLogger.warn(
+ "BYOK diarization requested but base URL is not OpenAI/Mistral; transcribing without speakers",
+ { baseUrl }
+ );
+ }
+ }
+
const { body, boundary } = buildMultipartBody(
audioBuffer,
fileName,
@@ -7114,6 +7391,38 @@ class IPCHandlers {
);
}
+ if (diarize && data.data?.speakers) {
+ const segments = (data.data.speakers || []).map((s) => ({
+ speaker: s.id || `Speaker ${s.speaker || "?"}`,
+ text: s.text || "",
+ start: s.start || 0,
+ end: s.end || 0,
+ }));
+ const formatted = segments
+ .map(
+ (s) =>
+ `[${s.speaker}] ${formatDiarTime(s.start)} - ${formatDiarTime(s.end)}\n${s.text}`
+ )
+ .join("\n\n");
+ return { success: true, text: formatted, diarized: true };
+ }
+
+ if (diarize && data.data?.segments) {
+ const segments = data.data.segments || [];
+ const formatted = segments
+ .map((s) => {
+ const speaker = s.speaker || "Speaker ?";
+ const start = formatDiarTime(s.start || 0);
+ const end = formatDiarTime(s.end || 0);
+ return `[${speaker}] ${start} - ${end}\n${s.text || ""}`;
+ })
+ .join("\n\n");
+ return { success: true, text: formatted, diarized: true };
+ }
+
+ if (diarize) {
+ debugLogger.warn("BYOK diarization requested but provider returned no speaker data");
+ }
return { success: true, text: data.data.text };
} catch (error) {
debugLogger.error("BYOK audio file transcription error", { error: error.message });
diff --git a/src/helpers/speakerMerge.js b/src/helpers/speakerMerge.js
new file mode 100644
index 000000000..0f43457b0
--- /dev/null
+++ b/src/helpers/speakerMerge.js
@@ -0,0 +1,110 @@
+function splitIntoSentences(text) {
+ if (typeof Intl !== "undefined" && Intl.Segmenter) {
+ try {
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "sentence" });
+ return Array.from(segmenter.segment(text), (s) => s.segment.trim()).filter(
+ (s) => s.length > 0
+ );
+ } catch {
+ // fall through to regex
+ }
+ }
+ return text
+ .split(/(?<=[.!?])\s+/)
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
+}
+
+function formatTimestamp(seconds) {
+ const hrs = Math.floor(seconds / 3600);
+ const mins = Math.floor((seconds % 3600) / 60);
+ const secs = Math.floor(seconds % 60);
+ if (hrs > 0) {
+ return `${hrs}:${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
+ }
+ return `${mins}:${String(secs).padStart(2, "0")}`;
+}
+
+function mergeSpeakersWithText(segments, text, durationSeconds) {
+ if (!segments || segments.length === 0) {
+ return [{ speaker: "speaker_0", text, start: 0, end: durationSeconds || 0 }];
+ }
+
+ // Segments arrive in stdout order, not sorted — never assume the last one ends latest.
+ const maxSegmentEnd = segments.reduce((max, s) => Math.max(max, s.end || 0), 0);
+
+ const sentences = splitIntoSentences(text);
+ if (sentences.length === 0) {
+ return [{ speaker: segments[0].speaker, text, start: segments[0].start, end: maxSegmentEnd }];
+ }
+
+ const totalDuration = durationSeconds || maxSegmentEnd || 1;
+ const totalChars = sentences.reduce((sum, s) => sum + s.length, 0);
+
+ const assigned = [];
+ let charOffset = 0;
+
+ for (const sentence of sentences) {
+ const sentenceMidpoint = ((charOffset + sentence.length / 2) / totalChars) * totalDuration;
+ charOffset += sentence.length;
+
+ let bestSegment = null;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ for (const seg of segments) {
+ const distance =
+ sentenceMidpoint < seg.start
+ ? seg.start - sentenceMidpoint
+ : sentenceMidpoint > seg.end
+ ? sentenceMidpoint - seg.end
+ : 0;
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestSegment = seg;
+ }
+ if (distance === 0) break;
+ }
+
+ assigned.push({
+ speaker: bestSegment.speaker,
+ text: sentence,
+ start: bestSegment.start,
+ end: bestSegment.end,
+ });
+ }
+
+ const consolidated = [];
+ for (const item of assigned) {
+ const prev = consolidated[consolidated.length - 1];
+ if (prev && prev.speaker === item.speaker) {
+ prev.text += " " + item.text;
+ prev.end = Math.max(prev.end, item.end);
+ } else {
+ consolidated.push({ ...item });
+ }
+ }
+
+ return consolidated;
+}
+
+function formatSpeakerTranscript(mergedSegments) {
+ const speakerMap = new Map();
+ let nextIndex = 1;
+
+ return mergedSegments
+ .map((seg) => {
+ if (!speakerMap.has(seg.speaker)) {
+ speakerMap.set(seg.speaker, nextIndex++);
+ }
+ const label = `Speaker ${speakerMap.get(seg.speaker)}`;
+ const timeRange = `${formatTimestamp(seg.start)} - ${formatTimestamp(seg.end)}`;
+ return `[${label}] ${timeRange}\n${seg.text}`;
+ })
+ .join("\n\n");
+}
+
+module.exports = {
+ mergeSpeakersWithText,
+ formatSpeakerTranscript,
+ splitIntoSentences,
+ formatTimestamp,
+};
diff --git a/src/helpers/urlAudioDownloader.js b/src/helpers/urlAudioDownloader.js
new file mode 100644
index 000000000..958927f16
--- /dev/null
+++ b/src/helpers/urlAudioDownloader.js
@@ -0,0 +1,1543 @@
+const https = require("https");
+const http = require("http");
+const dns = require("dns");
+const { isIP } = require("net");
+// Namespaced (not destructured) so tests can monkeypatch childProcess.spawn.
+const childProcess = require("child_process");
+const crypto = require("crypto");
+const fs = require("fs");
+const os = require("os");
+const path = require("path");
+const debugLogger = require("./debugLogger");
+const { getSafeTempDir } = require("./safeTempDir");
+const { getFFmpegPath } = require("./ffmpegUtils");
+
+const YOUTUBE_HOSTS = new Set([
+ "youtube.com",
+ "www.youtube.com",
+ "m.youtube.com",
+ "music.youtube.com",
+ "youtu.be",
+]);
+
+const STALL_TIMEOUT_MS = 30_000;
+const CONNECT_TIMEOUT_MS = 30_000;
+const MAX_DOWNLOAD_BYTES = 500 * 1024 * 1024;
+const MAX_REDIRECTS = 3;
+// Reject absurdly long videos before downloading.
+const MAX_DURATION_SECONDS = 6 * 60 * 60;
+const USER_AGENT = "OpenWhispr/1.0";
+
+// Writable yt-dlp cache, seeded from the read-only bundle so the binary can
+// self-update (the bundled copy is read-only / inside the signed bundle).
+// OPENWHISPR_YTDLP_CACHE_DIR overrides the location (relocate it, or isolate it in tests).
+const YT_DLP_CACHE_DIR =
+ process.env.OPENWHISPR_YTDLP_CACHE_DIR ||
+ path.join(os.homedir(), ".cache", "openwhispr", "yt-dlp");
+const YT_DLP_UPDATE_THROTTLE_MS = 24 * 60 * 60 * 1000;
+// Bound the self-update so a stalled GitHub request can never hang a download
+// or wedge the single-flight flag. Overridable via options.timeoutMs for tests.
+const UPDATE_TIMEOUT_MS = 120_000;
+// Absolute ceilings on yt-dlp runs so a wedged process can never hang a queue item.
+const YT_DLP_METADATA_TIMEOUT_MS = 2 * 60 * 1000;
+const YT_DLP_EXTRACTION_TIMEOUT_MS = 30 * 60 * 1000;
+let ytDlpUpdateInFlight = false;
+let ytDlpBusyCount = 0;
+
+// Decode the IPv4 embedded in the trailing 32 bits of a NAT64 (64:ff9b::/96) address.
+// Handles "::" compression; returns dotted IPv4 or null.
+function nat64EmbeddedV4(lowerAddr) {
+ const parts = lowerAddr.split("::");
+ const head = parts[0].split(":").filter(Boolean);
+ const tail = parts.length > 1 ? parts[1].split(":").filter(Boolean) : [];
+ let groups;
+ if (parts.length > 1) {
+ const missing = 8 - head.length - tail.length;
+ if (missing < 0) return null;
+ groups = [...head, ...Array(missing).fill("0"), ...tail];
+ } else {
+ groups = head;
+ }
+ if (groups.length !== 8) return null;
+ const g6 = parseInt(groups[6], 16);
+ const g7 = parseInt(groups[7], 16);
+ if (Number.isNaN(g6) || Number.isNaN(g7)) return null;
+ return `${(g6 >> 8) & 0xff}.${g6 & 0xff}.${(g7 >> 8) & 0xff}.${g7 & 0xff}`;
+}
+
+function isPrivateIp(ip) {
+ if (ip === "::1" || ip === "::") return true;
+ if (isIP(ip) === 4) {
+ const parts = ip.split(".").map(Number);
+ if (parts[0] === 0) return true;
+ if (parts[0] === 127) return true;
+ if (parts[0] === 10) return true;
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
+ if (parts[0] === 192 && parts[1] === 168) return true;
+ if (parts[0] === 169 && parts[1] === 254) return true;
+ if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
+ if (parts[0] >= 224) return true;
+ return false;
+ }
+ if (isIP(ip) === 6) {
+ const lower = ip.toLowerCase();
+ // NAT64 well-known prefix embeds an IPv4 in the trailing 32 bits.
+ // Match zero-padded first hextet too ("0064:ff9b" == "64:ff9b").
+ if (isNat64Prefix(lower)) {
+ const dottedTail = lower.match(/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
+ if (dottedTail) return isPrivateIp(dottedTail[1]);
+ const embedded = nat64EmbeddedV4(lower);
+ if (embedded) return isPrivateIp(embedded);
+ return false;
+ }
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
+ // Link-local is fe80::/10 (fe80–febf), not just the literal fe80 hextet.
+ if (/^fe[89ab]/.test(lower)) return true;
+ if (lower.startsWith("ff")) return true;
+ const v4mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
+ if (v4mapped) return isPrivateIp(v4mapped[1]);
+ const v4compat = lower.match(/^::(\d+\.\d+\.\d+\.\d+)$/);
+ if (v4compat) return isPrivateIp(v4compat[1]);
+ const v4mappedHex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
+ if (v4mappedHex) {
+ const hi = parseInt(v4mappedHex[1], 16);
+ const lo = parseInt(v4mappedHex[2], 16);
+ const dotted = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
+ return isPrivateIp(dotted);
+ }
+ // Fully-expanded / zero-padded v4-mapped form "<all-zero groups>:ffff:HHHH:HHHH"
+ // (e.g. "0:0:0:0:0:ffff:7f00:1"). The leading [0:]+ ensures only zeros precede ffff.
+ const v4mappedExpanded = lower.match(/^[0:]+:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
+ if (v4mappedExpanded) {
+ const hi = parseInt(v4mappedExpanded[1], 16);
+ const lo = parseInt(v4mappedExpanded[2], 16);
+ const dotted = `${(hi >> 8) & 0xff}.${hi & 0xff}.${(lo >> 8) & 0xff}.${lo & 0xff}`;
+ return isPrivateIp(dotted);
+ }
+ // Same expanded form but with a dotted IPv4 tail (e.g. "0:0:0:0:0:ffff:127.0.0.1").
+ const v4mappedExpandedDotted = lower.match(/^[0:]+:ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
+ if (v4mappedExpandedDotted) {
+ return isPrivateIp(v4mappedExpandedDotted[1]);
+ }
+ return false;
+ }
+ return false;
+}
+
+// True when the first two hextets are the NAT64 well-known prefix 64:ff9b,
+// tolerating zero-padding ("0064:ff9b").
+function isNat64Prefix(lower) {
+ const head = lower.split("::")[0].split(":");
+ if (head.length < 2) return false;
+ const h0 = head[0].replace(/^0+/, "") || "0";
+ const h1 = head[1].replace(/^0+/, "") || "0";
+ return h0 === "64" && h1 === "ff9b";
+}
+
+// Unified accept gate for HEAD and GET so the two stages can never disagree.
+function isAcceptableAudioContentType(contentType) {
+ const ct = (contentType || "").toLowerCase();
+ return ct.startsWith("audio/") || ct.startsWith("video/");
+}
+
+// autoSelectFamily/Happy Eyeballs (default on Node 18+) calls lookup with
+// { all: true }, so dns.lookup yields an ARRAY of { address, family }. Reject if
+// ANY resolved entry is private; forward the original value unchanged on success.
+function ssrfSafeLookup(hostname, options, callback) {
+ dns.lookup(hostname, options, (err, address, family) => {
+ if (err) return callback(err);
+ const entries = Array.isArray(address) ? address : [{ address, family }];
+ for (const e of entries) {
+ if (isPrivateIp(e.address)) {
+ return callback(
+ Object.assign(
+ new Error("Direct downloads from private/internal addresses are not allowed"),
+ { code: "SSRF_BLOCKED" }
+ )
+ );
+ }
+ }
+ callback(null, address, family);
+ });
+}
+
+function firstHeaderValue(headers, name) {
+ const raw = headers[name];
+ return Array.isArray(raw) ? raw[0] : raw;
+}
+
+function detectUrlType(urlString) {
+ if (!urlString || typeof urlString !== "string") {
+ const err = new Error("Invalid URL");
+ err.code = "INVALID_URL";
+ throw err;
+ }
+
+ let parsed;
+ try {
+ parsed = new URL(urlString);
+ } catch {
+ const err = new Error(`Invalid URL: ${urlString}`);
+ err.code = "INVALID_URL";
+ throw err;
+ }
+
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
+ const err = new Error(`Unsupported protocol: ${parsed.protocol}`);
+ err.code = "INVALID_URL";
+ throw err;
+ }
+
+ const host = parsed.hostname.toLowerCase();
+ if (YOUTUBE_HOSTS.has(host)) {
+ return "youtube";
+ }
+
+ return "direct";
+}
+
+function extractYouTubeVideoId(urlString) {
+ let parsed;
+ try {
+ parsed = new URL(urlString);
+ } catch {
+ return null;
+ }
+
+ const host = parsed.hostname.toLowerCase();
+
+ if (host === "youtu.be") {
+ const id = parsed.pathname.slice(1).split("/")[0];
+ if (id && /^[A-Za-z0-9_-]{11}$/.test(id)) return id;
+ return null;
+ }
+
+ if (YOUTUBE_HOSTS.has(host)) {
+ const watchId = parsed.searchParams.get("v");
+ if (watchId && /^[A-Za-z0-9_-]{11}$/.test(watchId)) return watchId;
+
+ const pathMatch = parsed.pathname.match(/^\/(shorts|embed|live)\/([a-zA-Z0-9_-]{11})/);
+ if (pathMatch) return pathMatch[2];
+ }
+
+ return null;
+}
+
+function isPlaylistUrl(urlString) {
+ try {
+ const parsed = new URL(urlString);
+ const host = parsed.hostname.toLowerCase();
+ if (!YOUTUBE_HOSTS.has(host)) return false;
+ return parsed.pathname === "/playlist" && parsed.searchParams.has("list");
+ } catch {
+ return false;
+ }
+}
+
+function createStallChecker(onStall) {
+ let lastDataTime = Date.now();
+ const interval = setInterval(() => {
+ if (Date.now() - lastDataTime > STALL_TIMEOUT_MS) {
+ clearInterval(interval);
+ onStall();
+ }
+ }, 5_000);
+
+ return {
+ touch() {
+ lastDataTime = Date.now();
+ },
+ clear() {
+ clearInterval(interval);
+ },
+ };
+}
+
+function ytDlpBinaryName() {
+ return `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+}
+
+// Resolve the bundled yt-dlp sidecar binary. Mirrors whisper.js resolution.
+function resolveYtDlpPath() {
+ const name = ytDlpBinaryName();
+ const candidates = [];
+ if (process.resourcesPath) {
+ candidates.push(path.join(process.resourcesPath, "bin", name));
+ }
+ candidates.push(path.join(__dirname, "..", "..", "resources", "bin", name));
+ return candidates.find((p) => fs.existsSync(p)) || null;
+}
+
+// Path to the writable (self-updating) yt-dlp copy. Same basename as the bundle.
+function getCacheYtDlpPath() {
+ return path.join(YT_DLP_CACHE_DIR, ytDlpBinaryName());
+}
+
+function sha256File(p) {
+ return crypto.createHash("sha256").update(fs.readFileSync(p)).digest("hex");
+}
+
+// Trust anchors: the signed app bundle (seed) and yt-dlp's SUMS-verified self-update.
+function recordCacheChecksum() {
+ try {
+ const cachePath = getCacheYtDlpPath();
+ fs.writeFileSync(`${cachePath}.sha256`, sha256File(cachePath));
+ verifiedCacheStat = null;
+ } catch (e) {
+ debugLogger.warn("Failed to record yt-dlp cache checksum", { error: e.message });
+ }
+}
+
+// The cache dir is user-writable; verify before executing. Mismatch discards the
+// copy so the next download re-seeds from the signed bundle. Hashing the ~40 MB
+// binary blocks the main process, so remember the last verified (mtime, size) —
+// an attacker who could forge those could also rewrite the sibling .sha256, so
+// the memo adds no new trust.
+let verifiedCacheStat = null;
+
+function cacheChecksumValid(cachePath) {
+ try {
+ const st = fs.statSync(cachePath);
+ if (
+ verifiedCacheStat &&
+ verifiedCacheStat.path === cachePath &&
+ verifiedCacheStat.mtimeMs === st.mtimeMs &&
+ verifiedCacheStat.size === st.size
+ ) {
+ return true;
+ }
+ const expected = fs.readFileSync(`${cachePath}.sha256`, "utf8").trim();
+ if (expected && expected === sha256File(cachePath)) {
+ verifiedCacheStat = { path: cachePath, mtimeMs: st.mtimeMs, size: st.size };
+ return true;
+ }
+ } catch {}
+ verifiedCacheStat = null;
+ try {
+ fs.unlinkSync(cachePath);
+ } catch {}
+ try {
+ fs.unlinkSync(`${cachePath}.sha256`);
+ } catch {}
+ debugLogger.warn("yt-dlp cache failed checksum verification; discarded", { cachePath });
+ return false;
+}
+
+// Best-effort: copy the bundled binary into the writable cache on first use.
+// Never throws — callers fall back to the bundled copy.
+function seedYtDlpFromBundle() {
+ let tempPath;
+ try {
+ const cachePath = getCacheYtDlpPath();
+ if (fs.existsSync(cachePath)) return;
+ const bundled = resolveYtDlpPath();
+ if (!bundled) return;
+ fs.mkdirSync(YT_DLP_CACHE_DIR, { recursive: true, mode: 0o700 });
+ try {
+ fs.chmodSync(YT_DLP_CACHE_DIR, 0o700);
+ } catch {}
+ // Atomic seed: copy to a temp path, chmod, then rename so a crash mid-copy
+ // can never leave a truncated cache binary that would fail to spawn.
+ tempPath = `${cachePath}.tmp-${process.pid}`;
+ fs.copyFileSync(bundled, tempPath);
+ fs.chmodSync(tempPath, 0o755);
+ fs.renameSync(tempPath, cachePath);
+ recordCacheChecksum();
+ } catch (e) {
+ if (tempPath) {
+ try {
+ fs.unlinkSync(tempPath);
+ } catch {}
+ }
+ debugLogger.warn("Failed to seed yt-dlp from bundle", { error: e.message });
+ }
+}
+
+function isExecutableFile(p) {
+ if (process.platform === "win32") return fs.existsSync(p);
+ try {
+ fs.accessSync(p, fs.constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Checksum-verified cache copy, else bundled binary, else null. During an update
+// swap, prefer the bundle so we never spawn a half-replaced file.
+function resolveYtDlpBinary() {
+ if (ytDlpUpdateInFlight) {
+ const bundled = resolveYtDlpPath();
+ if (bundled) return bundled;
+ }
+ const cachePath = getCacheYtDlpPath();
+ if (fs.existsSync(cachePath) && isExecutableFile(cachePath) && cacheChecksumValid(cachePath)) {
+ return cachePath;
+ }
+ return resolveYtDlpPath();
+}
+
+// Wrap runYtDlp so maybeUpdateYtDlp can skip while a download holds the binary.
+async function runYtDlpTracked(binaryPath, args, abortSignal, timeoutMs, onOutput) {
+ ytDlpBusyCount += 1;
+ try {
+ return await runYtDlp(binaryPath, args, abortSignal, timeoutMs, onOutput);
+ } finally {
+ ytDlpBusyCount -= 1;
+ }
+}
+
+// Throttled, single-flight, best-effort background self-update of the CACHE copy
+// only (never the bundled binary). Never throws/rejects to the caller.
+function maybeUpdateYtDlp({ force, abortSignal, timeoutMs } = {}) {
+ return new Promise((resolve) => {
+ const stampPath = path.join(YT_DLP_CACHE_DIR, ".last-update");
+ const touchStamp = () => {
+ try {
+ fs.mkdirSync(YT_DLP_CACHE_DIR, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(stampPath, String(Date.now()));
+ } catch {}
+ };
+
+ try {
+ if (ytDlpUpdateInFlight) return resolve();
+ if (ytDlpBusyCount > 0) return resolve();
+
+ if (!force) {
+ try {
+ const st = fs.statSync(stampPath);
+ if (Date.now() - st.mtimeMs < YT_DLP_UPDATE_THROTTLE_MS) return resolve();
+ } catch {}
+ }
+
+ seedYtDlpFromBundle();
+ const cacheBinary = getCacheYtDlpPath();
+ if (!fs.existsSync(cacheBinary)) return resolve();
+ // Never execute (or later bless) a tampered copy: verify first; a failed
+ // check discards the copy, so reseed from the signed bundle and re-verify.
+ if (!cacheChecksumValid(cacheBinary)) {
+ seedYtDlpFromBundle();
+ if (!fs.existsSync(cacheBinary) || !cacheChecksumValid(cacheBinary)) return resolve();
+ }
+
+ ytDlpUpdateInFlight = true;
+ let child;
+ try {
+ // Nightly: upstream calls stable "prone to external breakage"; the updater
+ // self-verifies against the release's SHA2-256SUMS.
+ child = childProcess.spawn(cacheBinary, ["--update-to", "nightly"], { windowsHide: true });
+ } catch (e) {
+ ytDlpUpdateInFlight = false;
+ debugLogger.warn("yt-dlp self-update failed to start", { error: e.message });
+ touchStamp();
+ return resolve();
+ }
+ // Drain stdio so the child never blocks on a full pipe buffer.
+ if (child.stdout) child.stdout.on("data", () => {});
+ if (child.stderr) child.stderr.on("data", () => {});
+
+ // Bounded kill timer so a stalled -U network request can never hang.
+ const limit = typeof timeoutMs === "number" ? timeoutMs : UPDATE_TIMEOUT_MS;
+ let killTimer = null;
+ let onAbort = null;
+
+ let done = false;
+ // Always clears the timer/listener, resets the in-flight flag, stamps the
+ // throttle, and resolves — never rejects (best-effort contract).
+ const finish = (errMessage) => {
+ if (done) return;
+ done = true;
+ if (killTimer) clearTimeout(killTimer);
+ if (onAbort && abortSignal) abortSignal.removeEventListener("abort", onAbort);
+ ytDlpUpdateInFlight = false;
+ if (errMessage) debugLogger.warn("yt-dlp self-update error", { error: errMessage });
+ touchStamp();
+ resolve();
+ };
+
+ killTimer = setTimeout(() => {
+ try {
+ child.kill("SIGKILL");
+ } catch {}
+ finish("yt-dlp -U timed out");
+ }, limit);
+
+ if (abortSignal) {
+ if (abortSignal.aborted) {
+ try {
+ child.kill("SIGKILL");
+ } catch {}
+ return finish(null);
+ }
+ onAbort = () => {
+ try {
+ child.kill("SIGKILL");
+ } catch {}
+ finish(null);
+ };
+ abortSignal.addEventListener("abort", onAbort, { once: true });
+ }
+
+ child.on("error", (err) => finish(err.message));
+ child.on("close", (code) => {
+ // Only a successful update may move the trust anchor; a failed or killed
+ // run leaves the previously verified binary (and checksum) in place.
+ if (code === 0) recordCacheChecksum();
+ finish(null);
+ });
+ } catch (e) {
+ ytDlpUpdateInFlight = false;
+ debugLogger.warn("yt-dlp self-update unexpected error", { error: e.message });
+ resolve();
+ }
+ });
+}
+
+// Resolve the OS/corporate proxy for a target URL via Electron. Returns a proxy
+// URL string (e.g. "http://host:port") or null for DIRECT / when unavailable.
+async function resolveProxyForUrl(targetUrl) {
+ let session;
+ try {
+ ({ session } = require("electron"));
+ } catch {
+ return null;
+ }
+ if (
+ !session ||
+ !session.defaultSession ||
+ typeof session.defaultSession.resolveProxy !== "function"
+ ) {
+ return null;
+ }
+ let result;
+ try {
+ result = await session.defaultSession.resolveProxy(targetUrl);
+ } catch (e) {
+ debugLogger.warn("resolveProxy failed; falling back to direct", { error: e.message });
+ return null;
+ }
+ return parseProxyResult(result);
+}
+
+function parseProxyResult(result) {
+ if (!result || typeof result !== "string") return null;
+ const first = result.split(";")[0].trim();
+ if (!first || first.toUpperCase() === "DIRECT") return null;
+ const [scheme, hostPort] = first.split(/\s+/);
+ if (!hostPort) return null;
+ const s = scheme.toUpperCase();
+ let proto;
+ if (s === "PROXY") proto = "http";
+ else if (s === "HTTPS") proto = "https";
+ else if (s === "SOCKS" || s === "SOCKS5") proto = "socks5";
+ else if (s === "SOCKS4") proto = "socks4";
+ else return null;
+ return `${proto}://${hostPort}`;
+}
+
+function deriveTitleAndExt(urlPath) {
+ const extMatch = urlPath.match(/\.([a-zA-Z0-9]{2,5})$/);
+ const ext = extMatch ? extMatch[1] : "audio";
+ const fileName = path.basename(urlPath, `.${ext}`) || "audio";
+ let title;
+ try {
+ title = decodeURIComponent(fileName).replace(/[_-]+/g, " ");
+ } catch {
+ title = fileName.replace(/[_-]+/g, " ");
+ }
+ return { title, ext };
+}
+
+// Reject hostnames that resolve (or already are) a private/internal address.
+// Defense-in-depth pre-flight for the proxy path.
+function assertPublicHost(hostname) {
+ return new Promise((resolve, reject) => {
+ const raw = hostname.replace(/^\[|\]$/g, "");
+ if (isIP(raw)) {
+ if (isPrivateIp(raw)) {
+ return reject(
+ Object.assign(
+ new Error("Direct downloads from private/internal addresses are not allowed"),
+ { code: "SSRF_BLOCKED" }
+ )
+ );
+ }
+ return resolve();
+ }
+ dns.lookup(raw, { all: true }, (err, addresses) => {
+ if (err) {
+ return reject(
+ Object.assign(new Error(`DNS lookup failed: ${err.message}`), { code: "DOWNLOAD_FAILED" })
+ );
+ }
+ for (const a of addresses) {
+ if (isPrivateIp(a.address)) {
+ return reject(
+ Object.assign(
+ new Error("Direct downloads from private/internal addresses are not allowed"),
+ { code: "SSRF_BLOCKED" }
+ )
+ );
+ }
+ }
+ resolve();
+ });
+ });
+}
+
+// yt-dlp needs an external JS runtime for YouTube player challenges. Reuse the
+// app's Electron binary in Node mode; the env var is inherited by yt-dlp's child.
+function jsRuntimeSpawnConfig() {
+ return {
+ args: ["--js-runtimes", `node:${process.execPath}`],
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
+ };
+}
+
+// Kill yt-dlp AND its subprocesses (ffmpeg postprocessor, node JS-runtime):
+// the detached process group on Unix, taskkill /T on Windows — a plain kill on
+// the parent orphans them mid-download.
+function killYtDlpTree(child, signal) {
+ if (process.platform === "win32" && child.pid) {
+ try {
+ childProcess.spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
+ windowsHide: true,
+ });
+ return;
+ } catch {}
+ }
+ if (child.pid) {
+ try {
+ process.kill(-child.pid, signal);
+ return;
+ } catch {}
+ }
+ try {
+ child.kill(signal);
+ } catch {}
+}
+
+// Spawn the yt-dlp sidecar, capture stdout/stderr, honor abort and a hard timeout.
+function runYtDlp(binaryPath, args, abortSignal, timeoutMs, onOutput) {
+ return new Promise((resolve, reject) => {
+ if (abortSignal?.aborted) {
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ return;
+ }
+
+ const runtime = jsRuntimeSpawnConfig();
+ let child;
+ try {
+ child = childProcess.spawn(binaryPath, [...runtime.args, ...args], {
+ windowsHide: true,
+ env: runtime.env,
+ detached: process.platform !== "win32",
+ });
+ } catch (e) {
+ reject(
+ Object.assign(new Error(e.message || "Failed to start yt-dlp"), { code: "DOWNLOAD_FAILED" })
+ );
+ return;
+ }
+
+ let stdout = "";
+ let stderr = "";
+ let aborted = false;
+ let timedOut = false;
+
+ const onAbort = () => {
+ aborted = true;
+ killYtDlpTree(child, "SIGTERM");
+ };
+ if (abortSignal) abortSignal.addEventListener("abort", onAbort, { once: true });
+
+ const killTimer = timeoutMs
+ ? setTimeout(() => {
+ timedOut = true;
+ killYtDlpTree(child, "SIGKILL");
+ }, timeoutMs)
+ : null;
+
+ child.stdout.on("data", (d) => {
+ const text = d.toString();
+ stdout += text;
+ onOutput?.(text);
+ });
+ child.stderr.on("data", (d) => {
+ stderr += d.toString();
+ });
+
+ const cleanup = () => {
+ if (killTimer) clearTimeout(killTimer);
+ if (abortSignal) abortSignal.removeEventListener("abort", onAbort);
+ };
+
+ child.on("error", (err) => {
+ cleanup();
+ reject(
+ Object.assign(new Error(err.message || "yt-dlp failed to run"), { code: "DOWNLOAD_FAILED" })
+ );
+ });
+
+ child.on("close", (code) => {
+ cleanup();
+ if (aborted || abortSignal?.aborted) {
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ return;
+ }
+ if (timedOut) {
+ reject(Object.assign(new Error("yt-dlp timed out"), { code: "DOWNLOAD_FAILED", stderr }));
+ return;
+ }
+ if (code !== 0) {
+ reject(
+ Object.assign(new Error(stderr.trim() || `yt-dlp exited with code ${code}`), {
+ code: "DOWNLOAD_FAILED",
+ stderr,
+ })
+ );
+ return;
+ }
+ resolve({ stdout, stderr });
+ });
+ });
+}
+
+// Heuristic: yt-dlp stderr/message that smells like a stale extractor (YouTube
+// changed its player and a newer yt-dlp is needed). Drives the self-heal retry.
+function looksLikeStaleExtractor(message) {
+ return /unable to extract|nsig|signature|player|sig extraction|failed to extract|update yt-dlp|confirm.*latest version|please report/i.test(
+ message || ""
+ );
+}
+
+// YouTube refusing this network/IP (bot checks, 403s, login walls) — transient,
+// hits even fully-updated clients.
+function looksLikeYouTubeBlock(message) {
+ return /sign in to confirm|not a bot|login_required|http error 403|403 forbidden|sabr/i.test(
+ message || ""
+ );
+}
+
+// Single self-heal retry: on stale-extractor failures, force-update and retry once.
+async function runYtDlpWithSelfHeal(binary, args, abortSignal, timeoutMs, onBeforeRetry, onOutput) {
+ try {
+ return await runYtDlpTracked(binary, args, abortSignal, timeoutMs, onOutput);
+ } catch (e) {
+ if (e.code === "DOWNLOAD_CANCELLED") throw e;
+ const text = `${e.message || ""} ${e.stderr || ""}`;
+ if (!looksLikeStaleExtractor(text)) throw e;
+ onBeforeRetry?.();
+ await maybeUpdateYtDlp({ force: true, abortSignal });
+ return runYtDlpTracked(resolveYtDlpBinary() || binary, args, abortSignal, timeoutMs, onOutput);
+ }
+}
+
+// Startup sweep for orphans left by crashes or windows closed mid-download;
+// live downloads are protected by the age cutoff.
+function sweepStaleTempArtifacts(maxAgeMs = 24 * 60 * 60 * 1000) {
+ try {
+ const tempDir = getSafeTempDir();
+ const cutoff = Date.now() - maxAgeMs;
+ for (const f of fs.readdirSync(tempDir)) {
+ if (!f.startsWith("ow-url-") && !f.startsWith("ow-diarize-")) continue;
+ const p = path.join(tempDir, f);
+ try {
+ if (fs.statSync(p).mtimeMs < cutoff) fs.unlinkSync(p);
+ } catch {}
+ }
+ } catch {}
+}
+
+// Remove any temp artifacts produced for a given base path. Best-effort.
+function cleanupTempArtifacts(tempBase) {
+ try {
+ const tempDir = getSafeTempDir();
+ const prefix = path.basename(tempBase);
+ for (const f of fs.readdirSync(tempDir).filter((f) => f.startsWith(prefix))) {
+ try {
+ fs.unlinkSync(path.join(tempDir, f));
+ } catch {}
+ }
+ } catch {}
+}
+
+const YT_DLP_AUDIO_EXTENSIONS = new Set([
+ "m4a",
+ "mp3",
+ "opus",
+ "webm",
+ "ogg",
+ "wav",
+ "aac",
+ "flac",
+]);
+
+// Select the finished audio file yt-dlp left for `prefix`, delete every other
+// prefix-matched file (transient scratch files included), return its absolute path.
+function selectYtDlpOutput(tempDir, prefix) {
+ const all = fs.readdirSync(tempDir).filter((f) => f.startsWith(prefix));
+
+ let best = null;
+ for (const name of all) {
+ // Match on the lowercased suffix after the prefix so the video id can never
+ // trip an artifact pattern; yt-dlp writes these scratch suffixes lowercase.
+ const rest = name.slice(prefix.length).toLowerCase();
+ const isTransient =
+ /-frag\d+/.test(rest) ||
+ /\.(part|ytdl|aria2|meta)$/.test(rest) ||
+ rest.endsWith(".temp") ||
+ rest.includes(".temp.") ||
+ rest.includes(".orig.");
+ if (isTransient) continue;
+
+ let mtimeMs;
+ try {
+ mtimeMs = fs.statSync(path.join(tempDir, name)).mtimeMs;
+ } catch {
+ continue; // vanished between readdir and stat
+ }
+ const knownAudio = YT_DLP_AUDIO_EXTENSIONS.has(path.extname(name).slice(1).toLowerCase());
+ const tier = knownAudio ? (/\.f\d+\./.test(rest) ? 1 : 0) : 2;
+ if (!best || tier < best.tier || (tier === best.tier && mtimeMs > best.mtimeMs)) {
+ best = { name, tier, mtimeMs };
+ }
+ }
+
+ if (!best) {
+ const err = new Error("Download produced no output");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+
+ for (const f of all) {
+ if (f === best.name) continue;
+ try {
+ fs.unlinkSync(path.join(tempDir, f));
+ } catch {}
+ }
+ return path.join(tempDir, best.name);
+}
+
+async function downloadYouTube(url, onProgress, abortSignal) {
+ seedYtDlpFromBundle();
+ const binary = resolveYtDlpBinary();
+ if (!binary) {
+ const err = new Error("yt-dlp binary not found in resources/bin");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+
+ // yt-dlp's -x post-processor needs ffmpeg, which is not on PATH in packaged builds.
+ const ffmpegPath = getFFmpegPath();
+ if (!ffmpegPath) {
+ const err = new Error("FFmpeg not found — required for YouTube audio extraction");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+ const ffmpegDir = path.dirname(ffmpegPath);
+
+ const parsedUrl = new URL(url);
+ if (parsedUrl.protocol !== "https:") {
+ parsedUrl.protocol = "https:";
+ url = parsedUrl.href;
+ }
+
+ onProgress?.({ stage: "resolving", percent: 0 });
+
+ if (isPlaylistUrl(url)) {
+ const err = new Error("Playlists are not supported. Paste a single video URL.");
+ err.code = "PLAYLIST_URL";
+ throw err;
+ }
+
+ const videoId = extractYouTubeVideoId(url);
+ if (!videoId) {
+ const err = new Error("Could not extract video ID from URL");
+ err.code = "INVALID_URL";
+ throw err;
+ }
+
+ const sanitizedUrl = `https://www.youtube.com/watch?v=${videoId}`;
+
+ // Route yt-dlp through the OS proxy when one is configured.
+ const proxyUrl = await resolveProxyForUrl("https://www.youtube.com/");
+ const proxyArgs = proxyUrl ? ["--proxy", proxyUrl] : [];
+
+ let info;
+ try {
+ // Stale-extractor failures usually surface here, so this step self-heals too.
+ const { stdout } = await runYtDlpWithSelfHeal(
+ binary,
+ [...proxyArgs, "--dump-single-json", "--no-warnings", sanitizedUrl],
+ abortSignal,
+ YT_DLP_METADATA_TIMEOUT_MS
+ );
+ info = JSON.parse(stdout);
+ } catch (e) {
+ if (e.code === "DOWNLOAD_CANCELLED" || abortSignal?.aborted) {
+ const err = new Error("Download cancelled");
+ err.code = "DOWNLOAD_CANCELLED";
+ throw err;
+ }
+ const text = `${e.message || ""} ${e.stderr || ""}`;
+ if (looksLikeYouTubeBlock(text)) {
+ const err = new Error(
+ "YouTube is temporarily blocking downloads from your network. Try again later."
+ );
+ err.code = "YOUTUBE_BLOCKED";
+ throw err;
+ }
+ // A network stall is not "video unavailable" — keep it retryable.
+ if (/timed out/i.test(e.message || "")) {
+ const err = new Error("yt-dlp timed out");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+ const err = new Error(e.message || "Video unavailable");
+ err.code = "VIDEO_UNAVAILABLE";
+ throw err;
+ }
+
+ if (info.is_live) {
+ const err = new Error("Live streams are not supported");
+ err.code = "VIDEO_UNAVAILABLE";
+ throw err;
+ }
+
+ const title = info.title || `youtube-${videoId}`;
+ const durationSeconds = info.duration || null;
+
+ if (durationSeconds && durationSeconds > MAX_DURATION_SECONDS) {
+ const err = new Error("Video is too long to download. Maximum length is 6 hours.");
+ err.code = "FILE_TOO_LARGE";
+ throw err;
+ }
+
+ onProgress?.({ stage: "downloading", percent: 0, title });
+
+ if (abortSignal?.aborted) {
+ const err = new Error("Download cancelled");
+ err.code = "DOWNLOAD_CANCELLED";
+ throw err;
+ }
+
+ const tempBase = path.join(getSafeTempDir(), `ow-url-${Date.now()}-${videoId}`);
+
+ const extractionArgs = [
+ ...proxyArgs,
+ "-x",
+ "--audio-format",
+ "best",
+ "--max-filesize",
+ "500M",
+ "--ffmpeg-location",
+ ffmpegDir,
+ "-o",
+ `${tempBase}.%(ext)s`,
+ // Line-buffered progress ("[download] 42.3% of ...") instead of \r rewrites.
+ "--newline",
+ "--no-warnings",
+ sanitizedUrl,
+ ];
+
+ // Cap at 99: after the download hits 100%, ffmpeg still has to extract audio.
+ let lastPercent = 0;
+ const onExtractionOutput = (text) => {
+ const matches = text.match(/\[download\]\s+(\d{1,3}(?:\.\d+)?)%/g);
+ if (!matches) return;
+ const percent = Math.min(
+ 99,
+ Math.round(parseFloat(matches[matches.length - 1].match(/([\d.]+)%/)[1]))
+ );
+ if (percent > lastPercent) {
+ lastPercent = percent;
+ onProgress?.({ stage: "downloading", percent, title });
+ }
+ };
+
+ try {
+ // The metadata step may have self-healed the cache copy; pick up the fresh binary.
+ const { stdout: extractionOut } = await runYtDlpWithSelfHeal(
+ resolveYtDlpBinary() || binary,
+ extractionArgs,
+ abortSignal,
+ YT_DLP_EXTRACTION_TIMEOUT_MS,
+ () => cleanupTempArtifacts(tempBase),
+ onExtractionOutput
+ );
+
+ // --max-filesize makes yt-dlp skip the file and exit 0 with no output.
+ if (/larger than max-filesize/i.test(extractionOut)) {
+ const err = new Error("File too large. Maximum download size is 500 MB.");
+ err.code = "FILE_TOO_LARGE";
+ throw err;
+ }
+
+ const tempPath = selectYtDlpOutput(getSafeTempDir(), path.basename(tempBase));
+ const sizeBytes = fs.statSync(tempPath).size;
+
+ // --max-filesize doesn't enforce for unknown-size streams; re-check after the fact.
+ if (sizeBytes > MAX_DOWNLOAD_BYTES) {
+ try {
+ fs.unlinkSync(tempPath);
+ } catch {}
+ const err = new Error("File too large. Maximum download size is 500 MB.");
+ err.code = "FILE_TOO_LARGE";
+ throw err;
+ }
+
+ // Throttled background self-update for next time (never awaited).
+ maybeUpdateYtDlp();
+
+ onProgress?.({ stage: "ready", percent: 100, title });
+
+ return { tempPath, title, durationSeconds, sizeBytes };
+ } catch (e) {
+ cleanupTempArtifacts(tempBase);
+ if (e.code === "DOWNLOAD_CANCELLED" || e.code === "PLAYLIST_URL") throw e;
+ const text = `${e.message || ""} ${e.stderr || ""}`;
+ if (looksLikeYouTubeBlock(text)) {
+ const err = new Error(
+ "YouTube is temporarily blocking downloads from your network. Try again later."
+ );
+ err.code = "YOUTUBE_BLOCKED";
+ throw err;
+ }
+ const err = new Error(e.stderr || e.message || "Download failed");
+ err.code = e.code || "DOWNLOAD_FAILED";
+ throw err;
+ }
+}
+
+function httpRequest(parsed, options) {
+ const mod = parsed.protocol === "https:" ? https : http;
+ return new Promise((resolve, reject) => {
+ // UA-less requests get bot-walled by common CDN fronts. `signal` lets a
+ // cancel land during the connect phase, not just once data is streaming.
+ const req = mod.request(
+ parsed,
+ { timeout: CONNECT_TIMEOUT_MS, headers: { "User-Agent": USER_AGENT }, ...options },
+ resolve
+ );
+ req.on("error", (err) => {
+ if (options.signal?.aborted) {
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ } else {
+ reject(err);
+ }
+ });
+ req.on("timeout", () => {
+ req.destroy();
+ reject(new Error("Connection timed out"));
+ });
+ req.end();
+ });
+}
+
+// Stream a readable HTTP response to disk under the shared caps (size, stall,
+// abort, progress). Used by both the direct and proxy paths. `abort` tears down
+// the underlying transport. Resolves to byte size; cleans up temp file on failure.
+function streamToFile(
+ response,
+ tempPath,
+ { contentLength, title, onProgress, abortSignal, abort }
+) {
+ return new Promise((resolve, reject) => {
+ // An already-dispatched abort event never re-fires for a late listener.
+ if (abortSignal?.aborted) {
+ try {
+ abort();
+ } catch {}
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ return;
+ }
+ const fileStream = fs.createWriteStream(tempPath);
+ let downloaded = 0;
+ let settled = false;
+
+ const stall = createStallChecker(() => {
+ if (settled) return;
+ try {
+ abort();
+ } catch {}
+ bail(Object.assign(new Error("Download stalled"), { code: "DOWNLOAD_FAILED" }));
+ });
+
+ const cleanupFile = () => {
+ fileStream.destroy();
+ try {
+ fs.unlinkSync(tempPath);
+ } catch {}
+ };
+
+ const bail = (err) => {
+ if (settled) return;
+ settled = true;
+ stall.clear();
+ if (abortSignal) abortSignal.removeEventListener("abort", onAbort);
+ cleanupFile();
+ reject(err);
+ };
+
+ // React to cancel even while stalled (no data events arriving).
+ const onAbort = () => {
+ try {
+ abort();
+ } catch {}
+ bail(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ };
+ if (abortSignal) abortSignal.addEventListener("abort", onAbort, { once: true });
+
+ response.on("data", (chunk) => {
+ if (settled) return;
+
+ stall.touch();
+ downloaded += chunk.length;
+
+ if (downloaded > MAX_DOWNLOAD_BYTES) {
+ try {
+ abort();
+ } catch {}
+ bail(
+ Object.assign(new Error("File too large. Maximum download size is 500 MB."), {
+ code: "FILE_TOO_LARGE",
+ })
+ );
+ return;
+ }
+
+ if (contentLength) {
+ const percent = Math.min(99, Math.round((downloaded / contentLength) * 100));
+ onProgress?.({ stage: "downloading", percent, title });
+ }
+ });
+
+ response.on("error", (e) => {
+ bail(Object.assign(new Error(e.message || "Download failed"), { code: "DOWNLOAD_FAILED" }));
+ });
+
+ response.pipe(fileStream);
+
+ fileStream.on("error", (e) => {
+ bail(Object.assign(new Error(e.message || "Write failed"), { code: "DOWNLOAD_FAILED" }));
+ });
+
+ fileStream.on("finish", () => {
+ if (settled) return;
+ settled = true;
+ stall.clear();
+ if (abortSignal) abortSignal.removeEventListener("abort", onAbort);
+ try {
+ const sizeBytes = fs.statSync(tempPath).size;
+ resolve(sizeBytes);
+ } catch {
+ cleanupFile();
+ reject(
+ Object.assign(new Error("Download produced no output"), { code: "DOWNLOAD_FAILED" })
+ );
+ }
+ });
+ });
+}
+
+// Test seam: electron's net is unavailable under node --test.
+let electronNetOverride = null;
+function getElectronNet() {
+ return electronNetOverride || require("electron").net;
+}
+
+// Internal sentinel: the redirect handler aborts the request and asks the caller
+// to restart the download at the redirect URL (followRedirect must be invoked
+// synchronously inside the redirect event, but our host validation is async).
+const REDIRECT_RESTART = "REDIRECT_RESTART";
+
+// Proxy path: route through Electron net.request (which honors the OS proxy
+// automatically). For defense-in-depth we still pre-flight the target hostname and
+// re-validate each redirect hop against private IPs. With a proxy the corporate
+// egress policy is the primary SSRF control; net.request does not accept a
+// per-request lookup, leaving a narrow DNS-rebinding TOCTOU residual.
+async function downloadViaProxy(url, onProgress, abortSignal, redirectCount = 0) {
+ const net = getElectronNet();
+
+ await assertPublicHost(new URL(url).hostname);
+
+ const settledResponse = await new Promise((resolve, reject) => {
+ if (abortSignal?.aborted) {
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ return;
+ }
+
+ let redirects = redirectCount;
+ let request;
+ try {
+ request = net.request({ url, method: "GET", redirect: "manual" });
+ request.setHeader("User-Agent", USER_AGENT);
+ } catch (e) {
+ reject(Object.assign(new Error(e.message || "Download failed"), { code: "DOWNLOAD_FAILED" }));
+ return;
+ }
+
+ // ClientRequest.abort() emits 'abort'/'close' but never 'error', so an abort
+ // that lands after request.end() must settle the promise itself or it hangs.
+ const onAbort = () => {
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ };
+ if (abortSignal) abortSignal.addEventListener("abort", onAbort, { once: true });
+ // Chromium's net stack has no response-header timeout; without this a proxy
+ // that accepts the connection but never answers wedges the queue forever
+ // (the direct path gets the same bound from httpRequest's socket timeout).
+ const connectTimer = setTimeout(() => {
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(Object.assign(new Error("Connection timed out"), { code: "DOWNLOAD_FAILED" }));
+ }, CONNECT_TIMEOUT_MS);
+ const detach = () => {
+ clearTimeout(connectTimer);
+ if (abortSignal) abortSignal.removeEventListener("abort", onAbort);
+ };
+
+ request.on("redirect", (statusCode, method, redirectUrl) => {
+ redirects += 1;
+ if (redirects > MAX_REDIRECTS) {
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(Object.assign(new Error("Too many redirects"), { code: "DOWNLOAD_FAILED" }));
+ return;
+ }
+ let next;
+ try {
+ next = new URL(redirectUrl);
+ } catch {
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(Object.assign(new Error("Invalid redirect URL"), { code: "INVALID_URL" }));
+ return;
+ }
+ if (next.protocol !== "https:") {
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(
+ Object.assign(new Error("Only HTTPS URLs are supported for direct downloads"), {
+ code: "INVALID_URL",
+ })
+ );
+ return;
+ }
+ // Abort and restart at the redirect URL; the recursive call re-runs assertPublicHost.
+ try {
+ request.abort();
+ } catch {}
+ detach();
+ reject(
+ Object.assign(new Error("Redirected"), {
+ code: REDIRECT_RESTART,
+ url: next.href,
+ redirects,
+ })
+ );
+ });
+
+ request.on("response", (response) => {
+ detach();
+ const statusCode = response.statusCode;
+ if (statusCode !== 200) {
+ response.resume();
+ try {
+ request.abort();
+ } catch {}
+ reject(Object.assign(new Error(`HTTP ${statusCode}`), { code: "DOWNLOAD_FAILED" }));
+ return;
+ }
+
+ const contentType = (firstHeaderValue(response.headers, "content-type") || "").toLowerCase();
+ if (!isAcceptableAudioContentType(contentType)) {
+ response.resume();
+ try {
+ request.abort();
+ } catch {}
+ reject(
+ Object.assign(
+ new Error(`URL does not point to an audio file (content-type: ${contentType})`),
+ { code: "CONTENT_TYPE_INVALID" }
+ )
+ );
+ return;
+ }
+
+ const clHeader = firstHeaderValue(response.headers, "content-length");
+ const contentLength = clHeader ? Number(clHeader) : null;
+ if (contentLength && contentLength > MAX_DOWNLOAD_BYTES) {
+ response.resume();
+ try {
+ request.abort();
+ } catch {}
+ reject(
+ Object.assign(new Error("File too large. Maximum download size is 500 MB."), {
+ code: "FILE_TOO_LARGE",
+ })
+ );
+ return;
+ }
+
+ resolve({ response, contentLength, request });
+ });
+
+ request.on("error", (err) => {
+ detach();
+ if (abortSignal?.aborted) {
+ reject(Object.assign(new Error("Download cancelled"), { code: "DOWNLOAD_CANCELLED" }));
+ } else {
+ reject(
+ Object.assign(new Error(err.message || "Download failed"), { code: "DOWNLOAD_FAILED" })
+ );
+ }
+ });
+
+ request.end();
+ }).catch((err) => {
+ if (err && err.code === REDIRECT_RESTART) return err;
+ throw err;
+ });
+
+ if (settledResponse && settledResponse.code === REDIRECT_RESTART) {
+ return downloadViaProxy(
+ settledResponse.url,
+ onProgress,
+ abortSignal,
+ settledResponse.redirects
+ );
+ }
+
+ const { response, contentLength, request } = settledResponse;
+
+ const { title, ext } = deriveTitleAndExt(new URL(url).pathname);
+ const tempPath = path.join(getSafeTempDir(), `ow-url-${Date.now()}.${ext}`);
+
+ onProgress?.({ stage: "downloading", percent: 0, title });
+
+ const sizeBytes = await streamToFile(response, tempPath, {
+ contentLength,
+ title,
+ onProgress,
+ abortSignal,
+ abort: () => {
+ try {
+ request.abort();
+ } catch {}
+ },
+ });
+
+ onProgress?.({ stage: "ready", percent: 100, title });
+ return { tempPath, title, durationSeconds: null, sizeBytes };
+}
+
+async function downloadDirect(url, onProgress, abortSignal, redirectCount = 0) {
+ onProgress?.({ stage: "resolving", percent: 0 });
+
+ const parsed = new URL(url);
+
+ if (parsed.protocol !== "https:") {
+ const err = new Error("Only HTTPS URLs are supported for direct downloads");
+ err.code = "INVALID_URL";
+ throw err;
+ }
+
+ const rawHost = parsed.hostname.replace(/^\[|\]$/g, "");
+ if (isIP(rawHost) && isPrivateIp(rawHost)) {
+ const err = new Error("Direct downloads from private/internal addresses are not allowed");
+ err.code = "SSRF_BLOCKED";
+ throw err;
+ }
+
+ // When the OS has a proxy configured, raw node-https would bypass it. Route through
+ // Electron net.request instead; keep the airtight node-https + ssrfSafeLookup path
+ // as the default for the common no-proxy case.
+ const proxyUrl = await resolveProxyForUrl(url);
+ if (proxyUrl) {
+ return downloadViaProxy(url, onProgress, abortSignal, redirectCount);
+ }
+
+ // Servers may refuse HEAD (GET-only presigned URLs, 405s): non-2xx or transport
+ // failures fall through to the GET, which is fully re-validated anyway.
+ let headParsed = parsed;
+ let headRedirects = 0;
+ let headResponse = null;
+ try {
+ while (true) {
+ headResponse = await httpRequest(headParsed, {
+ method: "HEAD",
+ lookup: ssrfSafeLookup,
+ signal: abortSignal,
+ });
+ headResponse.resume();
+ if (
+ headResponse.statusCode >= 300 &&
+ headResponse.statusCode < 400 &&
+ headResponse.headers.location
+ ) {
+ // Cumulative redirect bound across alternating GET+HEAD hops.
+ if (redirectCount + ++headRedirects > MAX_REDIRECTS) {
+ const err = new Error("Too many redirects");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+ const nextUrl = new URL(headResponse.headers.location, headParsed.href);
+ if (nextUrl.protocol !== "https:") {
+ const err = new Error("Only HTTPS URLs are supported for direct downloads");
+ err.code = "INVALID_URL";
+ throw err;
+ }
+ const nextRawHost = nextUrl.hostname.replace(/^\[|\]$/g, "");
+ if (isIP(nextRawHost) && isPrivateIp(nextRawHost)) {
+ const err = new Error("Direct downloads from private/internal addresses are not allowed");
+ err.code = "SSRF_BLOCKED";
+ throw err;
+ }
+ headParsed = nextUrl;
+ continue;
+ }
+ break;
+ }
+ } catch (e) {
+ if (
+ e.code === "SSRF_BLOCKED" ||
+ e.code === "INVALID_URL" ||
+ e.code === "DOWNLOAD_FAILED" ||
+ e.code === "DOWNLOAD_CANCELLED"
+ ) {
+ throw e;
+ }
+ headResponse = null;
+ }
+
+ let contentLength = null;
+ if (headResponse && headResponse.statusCode >= 200 && headResponse.statusCode < 300) {
+ const contentType = (headResponse.headers["content-type"] || "").toLowerCase();
+ if (!isAcceptableAudioContentType(contentType)) {
+ const err = new Error(`URL does not point to an audio file (content-type: ${contentType})`);
+ err.code = "CONTENT_TYPE_INVALID";
+ throw err;
+ }
+
+ contentLength = headResponse.headers["content-length"]
+ ? Number(headResponse.headers["content-length"])
+ : null;
+
+ if (contentLength && contentLength > MAX_DOWNLOAD_BYTES) {
+ const err = new Error("File too large. Maximum download size is 500 MB.");
+ err.code = "FILE_TOO_LARGE";
+ throw err;
+ }
+ }
+
+ const { title, ext } = deriveTitleAndExt(headParsed.pathname);
+ const tempPath = path.join(getSafeTempDir(), `ow-url-${Date.now()}.${ext}`);
+
+ onProgress?.({ stage: "downloading", percent: 0, title });
+
+ const response = await httpRequest(headParsed, {
+ method: "GET",
+ lookup: ssrfSafeLookup,
+ signal: abortSignal,
+ });
+
+ if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
+ response.destroy();
+ if (redirectCount + headRedirects >= MAX_REDIRECTS) {
+ const err = new Error("Too many redirects");
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+ const redirectUrl = new URL(response.headers.location, headParsed.href).href;
+ return downloadDirect(redirectUrl, onProgress, abortSignal, redirectCount + headRedirects + 1);
+ }
+
+ if (response.statusCode !== 200) {
+ response.destroy();
+ const err = new Error(`HTTP ${response.statusCode}`);
+ err.code = "DOWNLOAD_FAILED";
+ throw err;
+ }
+
+ const getContentType = (response.headers["content-type"] || "").toLowerCase();
+ if (!isAcceptableAudioContentType(getContentType)) {
+ response.destroy();
+ const err = new Error(`URL does not point to an audio file (content-type: ${getContentType})`);
+ err.code = "CONTENT_TYPE_INVALID";
+ throw err;
+ }
+
+ if (contentLength == null && response.headers["content-length"]) {
+ contentLength = Number(response.headers["content-length"]);
+ if (contentLength > MAX_DOWNLOAD_BYTES) {
+ response.destroy();
+ const err = new Error("File too large. Maximum download size is 500 MB.");
+ err.code = "FILE_TOO_LARGE";
+ throw err;
+ }
+ }
+
+ const sizeBytes = await streamToFile(response, tempPath, {
+ contentLength,
+ title,
+ onProgress,
+ abortSignal,
+ abort: () => {
+ try {
+ response.destroy();
+ } catch {}
+ },
+ });
+
+ onProgress?.({ stage: "ready", percent: 100, title });
+ return { tempPath, title, durationSeconds: null, sizeBytes };
+}
+
+async function download(url, onProgress, abortSignal) {
+ const type = detectUrlType(url);
+ debugLogger.log("URL audio download starting", { url, type });
+
+ if (type === "youtube") {
+ return downloadYouTube(url, onProgress, abortSignal);
+ }
+
+ return downloadDirect(url, onProgress, abortSignal);
+}
+
+module.exports = {
+ detectUrlType,
+ extractYouTubeVideoId,
+ isPlaylistUrl,
+ download,
+ sweepStaleTempArtifacts,
+ isPrivateIp,
+ isAcceptableAudioContentType,
+ ssrfSafeLookup,
+ maybeUpdateYtDlp,
+ downloadViaProxy,
+ // Test-only seam: lets the regression test confirm the single-flight flag is cleared.
+ _isYtDlpUpdateInFlight: () => ytDlpUpdateInFlight,
+ // Test-only seam: injects a fake electron net for downloadViaProxy tests.
+ _setElectronNetForTests: (net) => {
+ electronNetOverride = net;
+ },
+ // Test-only seam: exposes yt-dlp output selection to the regression tests.
+ _selectYtDlpOutput: selectYtDlpOutput,
+ // Test-only seams: cache checksum verification and block-detection heuristics.
+ _resolveYtDlpBinary: resolveYtDlpBinary,
+ _recordCacheChecksum: recordCacheChecksum,
+ _looksLikeYouTubeBlock: looksLikeYouTubeBlock,
+};
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index a314f10ed..7322f79ec 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -2172,7 +2172,40 @@
"switchToCloudForLargeFiles": "Wechsle zu OpenWhispr Cloud, um diese Datei zu transkribieren.",
"createAccount": "Konto erstellen",
"upgrade": "Upgraden",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "oder",
+ "urlPlaceholder": "YouTube- oder Audio-URL einfügen",
+ "urlDownloading": "Audio wird heruntergeladen...",
+ "urlResolving": "URL wird aufgelöst...",
+ "urlInvalid": "Ungültige URL. Fügen Sie einen YouTube-Link oder eine direkte Audio-URL ein.",
+ "urlVideoUnavailable": "Dieses Video ist nicht verfügbar. Es ist möglicherweise privat, entfernt oder geografisch gesperrt.",
+ "urlPlaylistNotSupported": "Playlists werden nicht unterstützt. Fügen Sie die URL eines einzelnen Videos ein.",
+ "urlContentTypeInvalid": "Diese URL verweist nicht auf eine Audio- oder Videodatei.",
+ "urlDownloadFailed": "Download fehlgeschlagen. Überprüfen Sie die URL und versuchen Sie es erneut.",
+ "urlCancelDownload": "Download abbrechen",
+ "addToQueue": "Zur Warteschlange hinzufügen",
+ "queueProgress": "{{completed}}/{{total}} abgeschlossen",
+ "cancelAll": "Alle abbrechen",
+ "clearQueue": "Leeren",
+ "pasteUrls": "URLs einfügen (eine pro Zeile)",
+ "speakerDetection": "Sprechererkennung",
+ "speakerDetectionDescription": "Verschiedene Sprecher im Audio identifizieren",
+ "numSpeakersPlaceholder": "Automatisch erkennen",
+ "downloadingModels": "Modelle werden heruntergeladen...",
+ "openaiDiarizeNote": "Überschreibt Ihr Transkriptionsmodell mit gpt-4o-transcribe-diarize, dem einzigen OpenAI-Modell mit Sprechererkennung. Die Kosten können von Ihrem gewählten Modell abweichen.",
+ "mistralDiarizeNote": "Sprechererkennung ohne Zusatzkosten mit Voxtral enthalten.",
+ "groqDiarizeNote": "Sprechererkennung ist mit Groq nicht verfügbar. Stattdessen wird die lokale Diarisierung verwendet.",
+ "batchCancelled": "Abgebrochen",
+ "batchTranscriptionFailed": "Transkription fehlgeschlagen",
+ "batchSaveFailed": "Notiz konnte nicht gespeichert werden",
+ "batchUnknownError": "Unbekannter Fehler",
+ "removeFromQueue": "Aus Warteschlange entfernen",
+ "diarizationRunsLocally": "Die Sprechererkennung läuft lokal auf Ihrem Gerät.",
+ "urlSubmit": "Link hinzufügen",
+ "urlsSkipped": "Einige Links konnten nicht hinzugefügt werden ({{n}})",
+ "queueFailed": "{{n}} fehlgeschlagen",
+ "urlFileTooLarge": "Die Datei ist zu groß zum Herunterladen. Die maximale Größe beträgt 500 MB.",
+ "urlYoutubeBlocked": "YouTube blockiert Downloads aus Ihrem Netzwerk vorübergehend. Versuchen Sie es später erneut."
},
"meeting": {
"title": "Besprechungsnotizen",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index f68433c60..c7bdc302f 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -2371,7 +2371,40 @@
"switchToCloudForLargeFiles": "Switch to OpenWhispr Cloud to transcribe this file.",
"createAccount": "Create Account",
"upgrade": "Upgrade",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "or",
+ "urlPlaceholder": "Paste a YouTube or audio URL",
+ "urlDownloading": "Downloading audio...",
+ "urlResolving": "Resolving URL...",
+ "urlInvalid": "Not a valid URL. Paste a YouTube link or a direct audio file URL.",
+ "urlVideoUnavailable": "This video is unavailable. It may be private, removed, or geo-blocked.",
+ "urlPlaylistNotSupported": "Playlists are not supported. Paste a single video URL.",
+ "urlContentTypeInvalid": "This URL does not point to an audio or video file.",
+ "urlDownloadFailed": "Download failed. Check the URL and try again.",
+ "urlCancelDownload": "Cancel download",
+ "addToQueue": "Add to queue",
+ "queueProgress": "{{completed}}/{{total}} completed",
+ "cancelAll": "Cancel all",
+ "clearQueue": "Clear",
+ "pasteUrls": "Paste URLs (one per line)",
+ "speakerDetection": "Speaker detection",
+ "speakerDetectionDescription": "Identify different speakers in the audio",
+ "numSpeakersPlaceholder": "Auto-detect",
+ "downloadingModels": "Downloading models...",
+ "openaiDiarizeNote": "Overrides your transcription model with gpt-4o-transcribe-diarize, the only OpenAI model with speaker detection. Costs may differ from your selected model.",
+ "mistralDiarizeNote": "Speaker detection included at no extra cost with Voxtral.",
+ "groqDiarizeNote": "Speaker detection is not available with Groq. Local diarization will be used instead.",
+ "batchCancelled": "Cancelled",
+ "batchTranscriptionFailed": "Transcription failed",
+ "batchSaveFailed": "Failed to save note",
+ "batchUnknownError": "Unknown error",
+ "removeFromQueue": "Remove from queue",
+ "diarizationRunsLocally": "Speaker detection runs locally on your device.",
+ "urlSubmit": "Add link",
+ "urlsSkipped": "Some links couldn't be added ({{n}})",
+ "queueFailed": "{{n}} failed",
+ "urlFileTooLarge": "File is too large to download. The maximum size is 500 MB.",
+ "urlYoutubeBlocked": "YouTube is temporarily blocking downloads from your network. Try again in a little while."
},
"meeting": {
"title": "Meeting Notes",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index a9a04defd..e7e78be58 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -2220,7 +2220,40 @@
"switchToCloudForLargeFiles": "Cambia a OpenWhispr Cloud para transcribir este archivo.",
"createAccount": "Crear cuenta",
"upgrade": "Mejorar plan",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "o",
+ "urlPlaceholder": "Pega una URL de YouTube o de audio",
+ "urlDownloading": "Descargando audio...",
+ "urlResolving": "Resolviendo URL...",
+ "urlInvalid": "URL no válida. Pega un enlace de YouTube o una URL directa de archivo de audio.",
+ "urlVideoUnavailable": "Este video no está disponible. Puede ser privado, eliminado o bloqueado geográficamente.",
+ "urlPlaylistNotSupported": "Las listas de reproducción no son compatibles. Pega la URL de un solo video.",
+ "urlContentTypeInvalid": "Esta URL no apunta a un archivo de audio o video.",
+ "urlDownloadFailed": "Error en la descarga. Verifica la URL e inténtalo de nuevo.",
+ "urlCancelDownload": "Cancelar descarga",
+ "addToQueue": "Agregar a la cola",
+ "queueProgress": "{{completed}}/{{total}} completados",
+ "cancelAll": "Cancelar todo",
+ "clearQueue": "Limpiar",
+ "pasteUrls": "Pegar URLs (una por línea)",
+ "speakerDetection": "Detección de hablantes",
+ "speakerDetectionDescription": "Identificar diferentes hablantes en el audio",
+ "numSpeakersPlaceholder": "Detección automática",
+ "downloadingModels": "Descargando modelos...",
+ "openaiDiarizeNote": "Reemplaza tu modelo de transcripción con gpt-4o-transcribe-diarize, el único modelo de OpenAI con detección de hablantes. Los costos pueden diferir de tu modelo seleccionado.",
+ "mistralDiarizeNote": "Detección de hablantes incluida sin costo adicional con Voxtral.",
+ "groqDiarizeNote": "La detección de hablantes no está disponible con Groq. Se usará la diarización local en su lugar.",
+ "batchCancelled": "Cancelado",
+ "batchTranscriptionFailed": "Error en la transcripción",
+ "batchSaveFailed": "Error al guardar la nota",
+ "batchUnknownError": "Error desconocido",
+ "removeFromQueue": "Eliminar de la cola",
+ "diarizationRunsLocally": "La detección de hablantes se ejecuta localmente en tu dispositivo.",
+ "urlSubmit": "Añadir enlace",
+ "urlsSkipped": "Algunos enlaces no se pudieron añadir ({{n}})",
+ "queueFailed": "{{n}} con error",
+ "urlFileTooLarge": "El archivo es demasiado grande para descargar. El tamaño máximo es 500 MB.",
+ "urlYoutubeBlocked": "YouTube está bloqueando temporalmente las descargas desde tu red. Inténtalo de nuevo más tarde."
},
"meeting": {
"title": "Notas de reunión",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 115f21d50..3c197ec13 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -2283,7 +2283,40 @@
"switchToCloudForLargeFiles": "Passez à OpenWhispr Cloud pour transcrire ce fichier.",
"createAccount": "Créer un compte",
"upgrade": "Mettre à niveau",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "ou",
+ "urlPlaceholder": "Collez une URL YouTube ou audio",
+ "urlDownloading": "Téléchargement de l'audio...",
+ "urlResolving": "Résolution de l'URL...",
+ "urlInvalid": "URL non valide. Collez un lien YouTube ou une URL directe de fichier audio.",
+ "urlVideoUnavailable": "Cette vidéo n'est pas disponible. Elle est peut-être privée, supprimée ou géo-bloquée.",
+ "urlPlaylistNotSupported": "Les playlists ne sont pas prises en charge. Collez l'URL d'une seule vidéo.",
+ "urlContentTypeInvalid": "Cette URL ne pointe pas vers un fichier audio ou vidéo.",
+ "urlDownloadFailed": "Échec du téléchargement. Vérifiez l'URL et réessayez.",
+ "urlCancelDownload": "Annuler le téléchargement",
+ "addToQueue": "Ajouter à la file",
+ "queueProgress": "{{completed}}/{{total}} terminés",
+ "cancelAll": "Tout annuler",
+ "clearQueue": "Effacer",
+ "pasteUrls": "Collez des URLs (une par ligne)",
+ "speakerDetection": "Détection des intervenants",
+ "speakerDetectionDescription": "Identifier les différents intervenants dans l'audio",
+ "numSpeakersPlaceholder": "Détection automatique",
+ "downloadingModels": "Téléchargement des modèles...",
+ "openaiDiarizeNote": "Remplace votre modèle de transcription par gpt-4o-transcribe-diarize, le seul modèle OpenAI avec détection des locuteurs. Les coûts peuvent différer de votre modèle sélectionné.",
+ "mistralDiarizeNote": "Détection des locuteurs incluse sans frais supplémentaires avec Voxtral.",
+ "groqDiarizeNote": "La détection des locuteurs n’est pas disponible avec Groq. La diarisation locale sera utilisée.",
+ "batchCancelled": "Annulé",
+ "batchTranscriptionFailed": "Échec de la transcription",
+ "batchSaveFailed": "Échec de l'enregistrement de la note",
+ "batchUnknownError": "Erreur inconnue",
+ "removeFromQueue": "Retirer de la file",
+ "diarizationRunsLocally": "La détection des locuteurs s'exécute localement sur votre appareil.",
+ "urlSubmit": "Ajouter le lien",
+ "urlsSkipped": "Certains liens n'ont pas pu être ajoutés ({{n}})",
+ "queueFailed": "{{n}} en échec",
+ "urlFileTooLarge": "Le fichier est trop volumineux pour être téléchargé. La taille maximale est de 500 Mo.",
+ "urlYoutubeBlocked": "YouTube bloque temporairement les téléchargements depuis votre réseau. Réessayez dans un moment."
},
"meeting": {
"title": "Notes de réunion",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 8cb7a6a1a..b8f60c5b8 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -2172,7 +2172,40 @@
"switchToCloudForLargeFiles": "Passa a OpenWhispr Cloud per trascrivere questo file.",
"createAccount": "Crea account",
"upgrade": "Aggiorna",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "oppure",
+ "urlPlaceholder": "Incolla un URL di YouTube o audio",
+ "urlDownloading": "Download dell'audio in corso...",
+ "urlResolving": "Risoluzione URL...",
+ "urlInvalid": "URL non valido. Incolla un link di YouTube o un URL diretto a un file audio.",
+ "urlVideoUnavailable": "Questo video non è disponibile. Potrebbe essere privato, rimosso o bloccato geograficamente.",
+ "urlPlaylistNotSupported": "Le playlist non sono supportate. Incolla l'URL di un singolo video.",
+ "urlContentTypeInvalid": "Questo URL non punta a un file audio o video.",
+ "urlDownloadFailed": "Download fallito. Controlla l'URL e riprova.",
+ "urlCancelDownload": "Annulla download",
+ "addToQueue": "Aggiungi alla coda",
+ "queueProgress": "{{completed}}/{{total}} completati",
+ "cancelAll": "Annulla tutto",
+ "clearQueue": "Cancella",
+ "pasteUrls": "Incolla URL (uno per riga)",
+ "speakerDetection": "Rilevamento parlanti",
+ "speakerDetectionDescription": "Identifica i diversi parlanti nell'audio",
+ "numSpeakersPlaceholder": "Rilevamento automatico",
+ "downloadingModels": "Download modelli in corso...",
+ "openaiDiarizeNote": "Sostituisce il tuo modello di trascrizione con gpt-4o-transcribe-diarize, l’unico modello OpenAI con rilevamento dei parlanti. I costi potrebbero differire dal modello selezionato.",
+ "mistralDiarizeNote": "Rilevamento dei parlanti incluso senza costi aggiuntivi con Voxtral.",
+ "groqDiarizeNote": "Il rilevamento dei parlanti non è disponibile con Groq. Verrà usata la diarizzazione locale.",
+ "batchCancelled": "Annullato",
+ "batchTranscriptionFailed": "Trascrizione non riuscita",
+ "batchSaveFailed": "Salvataggio nota non riuscito",
+ "batchUnknownError": "Errore sconosciuto",
+ "removeFromQueue": "Rimuovi dalla coda",
+ "diarizationRunsLocally": "Il rilevamento parlanti viene eseguito localmente sul tuo dispositivo.",
+ "urlSubmit": "Aggiungi link",
+ "urlsSkipped": "Alcuni link non sono stati aggiunti ({{n}})",
+ "queueFailed": "{{n}} non riusciti",
+ "urlFileTooLarge": "Il file è troppo grande per essere scaricato. La dimensione massima è 500 MB.",
+ "urlYoutubeBlocked": "YouTube sta bloccando temporaneamente i download dalla tua rete. Riprova tra poco."
},
"meeting": {
"title": "Note delle riunioni",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index ff74048dc..806def69c 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -2156,7 +2156,40 @@
"switchToCloudForLargeFiles": "このファイルを文字起こしするには OpenWhispr Cloud に切り替えてください。",
"createAccount": "アカウント作成",
"upgrade": "アップグレード",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "または",
+ "urlPlaceholder": "YouTubeまたは音声URLを貼り付け",
+ "urlDownloading": "音声をダウンロード中...",
+ "urlResolving": "URLを解析中...",
+ "urlInvalid": "無効なURLです。YouTubeリンクまたは音声ファイルの直接URLを貼り付けてください。",
+ "urlVideoUnavailable": "この動画は利用できません。非公開、削除済み、または地域制限されている可能性があります。",
+ "urlPlaylistNotSupported": "プレイリストには対応していません。個別の動画URLを貼り付けてください。",
+ "urlContentTypeInvalid": "このURLは音声または動画ファイルを指していません。",
+ "urlDownloadFailed": "ダウンロードに失敗しました。URLを確認してもう一度お試しください。",
+ "urlCancelDownload": "ダウンロードをキャンセル",
+ "addToQueue": "キューに追加",
+ "queueProgress": "{{completed}}/{{total}} 完了",
+ "cancelAll": "すべてキャンセル",
+ "clearQueue": "クリア",
+ "pasteUrls": "URLを貼り付け(1行に1つ)",
+ "speakerDetection": "話者検出",
+ "speakerDetectionDescription": "音声内の異なる話者を識別",
+ "numSpeakersPlaceholder": "自動検出",
+ "downloadingModels": "モデルをダウンロード中...",
+ "openaiDiarizeNote": "話者検出をサポートする唯一のOpenAIモデルであるgpt-4o-transcribe-diarizeに切り替わります。選択したモデルとコストが異なる場合があります。",
+ "mistralDiarizeNote": "Voxtralでの話者検出は追加料金なしで利用できます。",
+ "groqDiarizeNote": "Groqでは話者検出を利用できません。代わりにローカルダイアライゼーションが使用されます。",
+ "batchCancelled": "キャンセル済み",
+ "batchTranscriptionFailed": "文字起こしに失敗しました",
+ "batchSaveFailed": "ノートの保存に失敗しました",
+ "batchUnknownError": "不明なエラー",
+ "removeFromQueue": "キューから削除",
+ "diarizationRunsLocally": "話者検出はお使いのデバイス上でローカルに実行されます。",
+ "urlSubmit": "リンクを追加",
+ "urlsSkipped": "追加できなかったリンクがあります({{n}}件)",
+ "queueFailed": "{{n}}件失敗",
+ "urlFileTooLarge": "ファイルが大きすぎてダウンロードできません。最大サイズは500 MBです。",
+ "urlYoutubeBlocked": "YouTubeがお使いのネットワークからのダウンロードを一時的にブロックしています。しばらくしてからもう一度お試しください。"
},
"meeting": {
"title": "議事録",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index ba0e3bc58..7c8b4cf66 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -2172,7 +2172,40 @@
"switchToCloudForLargeFiles": "Mude para o OpenWhispr Cloud para transcrever este arquivo.",
"createAccount": "Criar conta",
"upgrade": "Fazer upgrade",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "ou",
+ "urlPlaceholder": "Cole uma URL do YouTube ou de áudio",
+ "urlDownloading": "Baixando áudio...",
+ "urlResolving": "Resolvendo URL...",
+ "urlInvalid": "URL inválida. Cole um link do YouTube ou uma URL direta de arquivo de áudio.",
+ "urlVideoUnavailable": "Este vídeo não está disponível. Pode ser privado, removido ou bloqueado geograficamente.",
+ "urlPlaylistNotSupported": "Playlists não são suportadas. Cole a URL de um único vídeo.",
+ "urlContentTypeInvalid": "Esta URL não aponta para um arquivo de áudio ou vídeo.",
+ "urlDownloadFailed": "Falha no download. Verifique a URL e tente novamente.",
+ "urlCancelDownload": "Cancelar download",
+ "addToQueue": "Adicionar à fila",
+ "queueProgress": "{{completed}}/{{total}} concluídos",
+ "cancelAll": "Cancelar tudo",
+ "clearQueue": "Limpar",
+ "pasteUrls": "Colar URLs (uma por linha)",
+ "speakerDetection": "Detecção de locutores",
+ "speakerDetectionDescription": "Identificar diferentes locutores no áudio",
+ "numSpeakersPlaceholder": "Detecção automática",
+ "downloadingModels": "Baixando modelos...",
+ "openaiDiarizeNote": "Substitui seu modelo de transcrição por gpt-4o-transcribe-diarize, o único modelo OpenAI com detecção de falantes. Os custos podem diferir do modelo selecionado.",
+ "mistralDiarizeNote": "Detecção de falantes incluída sem custo adicional com Voxtral.",
+ "groqDiarizeNote": "A detecção de falantes não está disponível com Groq. A diarização local será usada.",
+ "batchCancelled": "Cancelado",
+ "batchTranscriptionFailed": "Falha na transcrição",
+ "batchSaveFailed": "Falha ao salvar a nota",
+ "batchUnknownError": "Erro desconhecido",
+ "removeFromQueue": "Remover da fila",
+ "diarizationRunsLocally": "A detecção de falantes é executada localmente no seu dispositivo.",
+ "urlSubmit": "Adicionar link",
+ "urlsSkipped": "Alguns links não puderam ser adicionados ({{n}})",
+ "queueFailed": "{{n}} com falha",
+ "urlFileTooLarge": "O arquivo é grande demais para baixar. O tamanho máximo é 500 MB.",
+ "urlYoutubeBlocked": "O YouTube está bloqueando temporariamente downloads da sua rede. Tente novamente em instantes."
},
"meeting": {
"title": "Notas de reunião",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index b3b08dcf0..d43fe38f9 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -2172,7 +2172,40 @@
"switchToCloudForLargeFiles": "Переключитесь на OpenWhispr Cloud, чтобы транскрибировать этот файл.",
"createAccount": "Создать аккаунт",
"upgrade": "Обновить",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "или",
+ "urlPlaceholder": "Вставьте URL YouTube или аудиофайла",
+ "urlDownloading": "Загрузка аудио...",
+ "urlResolving": "Определение URL...",
+ "urlInvalid": "Недопустимый URL. Вставьте ссылку на YouTube или прямой URL аудиофайла.",
+ "urlVideoUnavailable": "Это видео недоступно. Возможно, оно приватное, удалено или заблокировано в вашем регионе.",
+ "urlPlaylistNotSupported": "Плейлисты не поддерживаются. Вставьте URL одного видео.",
+ "urlContentTypeInvalid": "Этот URL не указывает на аудио- или видеофайл.",
+ "urlDownloadFailed": "Ошибка загрузки. Проверьте URL и попробуйте снова.",
+ "urlCancelDownload": "Отменить загрузку",
+ "addToQueue": "Добавить в очередь",
+ "queueProgress": "{{completed}}/{{total}} завершено",
+ "cancelAll": "Отменить все",
+ "clearQueue": "Очистить",
+ "pasteUrls": "Вставьте URL (по одному на строку)",
+ "speakerDetection": "Определение говорящих",
+ "speakerDetectionDescription": "Определить разных говорящих в аудио",
+ "numSpeakersPlaceholder": "Автоопределение",
+ "downloadingModels": "Загрузка моделей...",
+ "openaiDiarizeNote": "Заменяет вашу модель транскрипции на gpt-4o-transcribe-diarize — единственную модель OpenAI с определением говорящих. Стоимость может отличаться от выбранной модели.",
+ "mistralDiarizeNote": "Определение говорящих включено без дополнительной оплаты с Voxtral.",
+ "groqDiarizeNote": "Определение говорящих недоступно с Groq. Вместо этого будет использована локальная диаризация.",
+ "batchCancelled": "Отменено",
+ "batchTranscriptionFailed": "Ошибка транскрипции",
+ "batchSaveFailed": "Не удалось сохранить заметку",
+ "batchUnknownError": "Неизвестная ошибка",
+ "removeFromQueue": "Удалить из очереди",
+ "diarizationRunsLocally": "Распознавание говорящих выполняется локально на вашем устройстве.",
+ "urlSubmit": "Добавить ссылку",
+ "urlsSkipped": "Некоторые ссылки не удалось добавить ({{n}})",
+ "queueFailed": "{{n}} с ошибкой",
+ "urlFileTooLarge": "Файл слишком большой для загрузки. Максимальный размер — 500 МБ.",
+ "urlYoutubeBlocked": "YouTube временно блокирует загрузки из вашей сети. Попробуйте снова чуть позже."
},
"meeting": {
"title": "Заметки со встреч",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 7dac49003..fc7d63b96 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -2167,7 +2167,40 @@
"switchToCloudForLargeFiles": "切换到 OpenWhispr Cloud 来转录此文件。",
"createAccount": "创建账户",
"upgrade": "升级",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "或",
+ "urlPlaceholder": "粘贴 YouTube 或音频 URL",
+ "urlDownloading": "正在下载音频...",
+ "urlResolving": "正在解析 URL...",
+ "urlInvalid": "无效的 URL。请粘贴 YouTube 链接或直接音频文件 URL。",
+ "urlVideoUnavailable": "此视频不可用。可能是私密、已删除或受地区限制。",
+ "urlPlaylistNotSupported": "不支持播放列表。请粘贴单个视频的 URL。",
+ "urlContentTypeInvalid": "此 URL 不指向音频或视频文件。",
+ "urlDownloadFailed": "下载失败。请检查 URL 后重试。",
+ "urlCancelDownload": "取消下载",
+ "addToQueue": "添加到队列",
+ "queueProgress": "{{completed}}/{{total}} 已完成",
+ "cancelAll": "取消全部",
+ "clearQueue": "清除",
+ "pasteUrls": "粘贴 URL(每行一个)",
+ "speakerDetection": "说话人检测",
+ "speakerDetectionDescription": "识别音频中的不同说话人",
+ "numSpeakersPlaceholder": "自动检测",
+ "downloadingModels": "正在下载模型...",
+ "openaiDiarizeNote": "将替换您的转录模型为 gpt-4o-transcribe-diarize,这是唯一支持说话人检测的 OpenAI 模型。费用可能与您选择的模型不同。",
+ "mistralDiarizeNote": "使用 Voxtral 时说话人检测无需额外费用。",
+ "groqDiarizeNote": "Groq 不支持说话人检测。将改用本地分离。",
+ "batchCancelled": "已取消",
+ "batchTranscriptionFailed": "转录失败",
+ "batchSaveFailed": "保存笔记失败",
+ "batchUnknownError": "未知错误",
+ "removeFromQueue": "从队列中移除",
+ "diarizationRunsLocally": "说话人检测在您的设备上本地运行。",
+ "urlSubmit": "添加链接",
+ "urlsSkipped": "部分链接无法添加({{n}} 个)",
+ "queueFailed": "{{n}} 个失败",
+ "urlFileTooLarge": "文件过大,无法下载。最大大小为 500 MB。",
+ "urlYoutubeBlocked": "YouTube 暂时阻止了来自您网络的下载。请稍后重试。"
},
"meeting": {
"title": "会议笔记",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index a98dff946..06a865126 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -2167,7 +2167,40 @@
"switchToCloudForLargeFiles": "切換到 OpenWhispr Cloud 來轉錄此檔案。",
"createAccount": "建立帳戶",
"upgrade": "升級",
- "switchToCloud": "OpenWhispr Cloud"
+ "switchToCloud": "OpenWhispr Cloud",
+ "orDivider": "或",
+ "urlPlaceholder": "貼上 YouTube 或音訊 URL",
+ "urlDownloading": "正在下載音訊...",
+ "urlResolving": "正在解析 URL...",
+ "urlInvalid": "無效的 URL。請貼上 YouTube 連結或直接音訊檔案 URL。",
+ "urlVideoUnavailable": "此影片無法使用。可能是私人、已移除或受地區限制。",
+ "urlPlaylistNotSupported": "不支援播放清單。請貼上單一影片的 URL。",
+ "urlContentTypeInvalid": "此 URL 並未指向音訊或影片檔案。",
+ "urlDownloadFailed": "下載失敗。請檢查 URL 後重試。",
+ "urlCancelDownload": "取消下載",
+ "addToQueue": "加入佇列",
+ "queueProgress": "{{completed}}/{{total}} 已完成",
+ "cancelAll": "取消全部",
+ "clearQueue": "清除",
+ "pasteUrls": "貼上 URL(每行一個)",
+ "speakerDetection": "說話者偵測",
+ "speakerDetectionDescription": "辨識音訊中的不同說話者",
+ "numSpeakersPlaceholder": "自動偵測",
+ "downloadingModels": "正在下載模型...",
+ "openaiDiarizeNote": "將替換您的轉錄模型為 gpt-4o-transcribe-diarize,這是唯一支援說話人偵測的 OpenAI 模型。費用可能與您選擇的模型不同。",
+ "mistralDiarizeNote": "使用 Voxtral 時說話人偵測無需額外費用。",
+ "groqDiarizeNote": "Groq 不支援說話人偵測。將改用本地分離。",
+ "batchCancelled": "已取消",
+ "batchTranscriptionFailed": "轉錄失敗",
+ "batchSaveFailed": "儲存筆記失敗",
+ "batchUnknownError": "未知錯誤",
+ "removeFromQueue": "從佇列中移除",
+ "diarizationRunsLocally": "說話人偵測在您的裝置上本機執行。",
+ "urlSubmit": "新增連結",
+ "urlsSkipped": "部分連結無法新增({{n}} 個)",
+ "queueFailed": "{{n}} 個失敗",
+ "urlFileTooLarge": "檔案過大,無法下載。大小上限為 500 MB。",
+ "urlYoutubeBlocked": "YouTube 暫時封鎖了來自您網路的下載。請稍後再試。"
},
"meeting": {
"title": "會議筆記",
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 62867cb57..8c4a9f85d 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -450,14 +450,24 @@ class SyncService {
continue;
}
- // A default folder created on another platform arrives with an
- // unknown client_folder_id; inserting it would violate the local
- // unique folder name. Match it by name and adopt its identity.
- if (!local && cloudFolder.is_default) {
+ // A folder created elsewhere arrives with an unknown client_folder_id;
+ // inserting it would violate the local unique folder name. Converge by
+ // adopting the cloud identity onto the same-named local folder — e.g. a
+ // pre-existing user-created "Videos" in the cloud meeting the locally
+ // seeded default, in either combination. Only unlinked folders are
+ // adoptable (never re-point one already bound to another cloud folder),
+ // and the case-insensitive fallback stays reserved for fixed-name
+ // defaults so distinct user folders like "work"/"Work" never merge.
+ if (!local) {
const allFolders = (await window.electronAPI.getFolderIdMap?.()) ?? [];
- const nameMatch = allFolders.find(
- (f) => f.is_default && f.name.toLowerCase() === cloudFolder.name.toLowerCase()
- );
+ const adoptable = allFolders.filter((f) => !f.cloud_id || f.cloud_id === cloudFolder.id);
+ const nameMatch =
+ adoptable.find((f) => f.name === cloudFolder.name) ??
+ adoptable.find(
+ (f) =>
+ (f.is_default || cloudFolder.is_default) &&
+ f.name.toLowerCase() === cloudFolder.name.toLowerCase()
+ );
if (nameMatch) {
await window.electronAPI.adoptFolderIdentity?.(
nameMatch.id,
diff --git a/src/services/fileTranscription.ts b/src/services/fileTranscription.ts
new file mode 100644
index 000000000..860382425
--- /dev/null
+++ b/src/services/fileTranscription.ts
@@ -0,0 +1,135 @@
+import { withSessionRefresh } from "../lib/auth";
+
+export interface FileTranscriptionResult {
+ success: boolean;
+ text?: string;
+ error?: string;
+ code?: string;
+ diarized?: boolean;
+ warning?: string;
+}
+
+export interface DiarizationSettings {
+ enabled: boolean;
+ // Local sherpa-onnx models present; BYOK-native diarization doesn't need them.
+ localModelsReady: boolean;
+ numSpeakers: number | null;
+}
+
+export interface FileTranscriptionConfig {
+ useLocalWhisper: boolean;
+ localTranscriptionProvider: string;
+ whisperModel: string;
+ parakeetModel: string;
+ isOpenWhisprCloud: boolean;
+ getApiKey: () => string;
+ cloudTranscriptionProvider: string;
+ cloudTranscriptionBaseUrl: string;
+ cloudTranscriptionModel: string;
+ language: string;
+ cortiEnvironment?: string;
+ cortiTenant?: string;
+ transcriptionMode?: string;
+ remoteTranscriptionUrl?: string;
+ remoteTranscriptionModel?: string;
+}
+
+// Single provider dispatch shared by the single-file flow and the batch queue,
+// so BYOK providers receive identical options in both.
+export async function transcribeFile(
+ filePath: string,
+ cfg: FileTranscriptionConfig,
+ diarize: boolean
+): Promise<FileTranscriptionResult> {
+ if (cfg.isOpenWhisprCloud) {
+ return withSessionRefresh(async () => {
+ const r = await window.electronAPI.transcribeAudioFileCloud!(filePath);
+ if (!r.success && r.code) {
+ throw Object.assign(new Error(r.error || "Cloud transcription failed"), {
+ code: r.code,
+ });
+ }
+ return r;
+ });
+ }
+
+ if (cfg.useLocalWhisper) {
+ return window.electronAPI.transcribeAudioFile(filePath, {
+ provider: cfg.localTranscriptionProvider as "whisper" | "nvidia",
+ model: cfg.localTranscriptionProvider === "nvidia" ? cfg.parakeetModel : cfg.whisperModel,
+ });
+ }
+
+ // Self-hosted fields make the handler route to the configured server
+ // (fail-closed on misconfiguration) instead of stale BYOK settings.
+ return window.electronAPI.transcribeAudioFileByok!({
+ filePath,
+ apiKey: cfg.getApiKey(),
+ baseUrl: cfg.cloudTranscriptionBaseUrl || "",
+ model: cfg.cloudTranscriptionModel,
+ diarize: diarize || undefined,
+ provider: cfg.cloudTranscriptionProvider,
+ language: cfg.language,
+ environment: cfg.cortiEnvironment,
+ tenant: cfg.cortiTenant,
+ transcriptionMode: cfg.transcriptionMode,
+ remoteTranscriptionUrl: cfg.remoteTranscriptionUrl,
+ remoteTranscriptionModel: cfg.remoteTranscriptionModel,
+ });
+}
+
+// OpenAI/Mistral BYOK handle diarization inside the transcription call itself.
+// Self-hosted mode routes to the user's own server, which doesn't — those users
+// get local diarization like everyone else.
+export function shouldUseByokDiarize(
+ cfg: FileTranscriptionConfig,
+ diarizationEnabled: boolean
+): boolean {
+ return (
+ diarizationEnabled &&
+ !cfg.useLocalWhisper &&
+ !cfg.isOpenWhisprCloud &&
+ cfg.transcriptionMode !== "self-hosted" &&
+ (cfg.cloudTranscriptionProvider === "openai" || cfg.cloudTranscriptionProvider === "mistral")
+ );
+}
+
+// Transcribe and diarize in parallel, then merge speaker labels into the text.
+// Shared by the single-file flow and the batch queue. `durationSeconds` (when the
+// source knows it, e.g. URL downloads) beats inferring duration from segments.
+export async function transcribeFileWithSpeakers(
+ filePath: string,
+ cfg: FileTranscriptionConfig,
+ diarization: DiarizationSettings,
+ durationSeconds?: number | null
+): Promise<FileTranscriptionResult> {
+ const byokDiarize = shouldUseByokDiarize(cfg, diarization.enabled);
+ const diarizePromise =
+ diarization.enabled && diarization.localModelsReady && !byokDiarize
+ ? (window.electronAPI
+ .diarizeAudioFile?.(filePath, {
+ numSpeakers: diarization.numSpeakers ?? undefined,
+ })
+ .catch(() => null) ?? Promise.resolve(null))
+ : Promise.resolve(null);
+
+ const [result, diar] = await Promise.all([
+ transcribeFile(filePath, cfg, byokDiarize),
+ diarizePromise,
+ ]);
+
+ if (!result.success || !result.text || result.diarized) return result;
+ if (!diar?.success || !diar.segments?.length) return result;
+
+ try {
+ const merged = await window.electronAPI.mergeSpeakerText?.(
+ diar.segments,
+ result.text,
+ durationSeconds || 0
+ );
+ if (merged?.success && merged.text) return { ...result, text: merged.text };
+ } catch {
+ // Merge failure falls back to the plain transcript.
+ }
+ return result;
+}
diff --git a/src/stores/batchQueueStore.ts b/src/stores/batchQueueStore.ts
new file mode 100644
index 000000000..93020e3db
--- /dev/null
+++ b/src/stores/batchQueueStore.ts
@@ -0,0 +1,285 @@
+import { create } from "zustand";
+import { transcribeFileWithSpeakers } from "../services/fileTranscription";
+import type { FileTranscriptionConfig, DiarizationSettings } from "../services/fileTranscription";
+import { DOWNLOAD_ERROR_KEYS } from "../components/notes/shared";
+
+export type QueueItemStatus = "queued" | "downloading" | "transcribing" | "done" | "error";
+
+export interface QueueItem {
+ id: string;
+ source: "file" | "url";
+ name: string;
+ path: string;
+ url?: string;
+ sizeBytes: number;
+ status: QueueItemStatus;
+ progress: number;
+ error?: string;
+ // Transcription completed but parts of the audio failed (e.g. failed chunks).
+ warning?: boolean;
+ noteId?: number;
+ tempPath?: string;
+}
+
+export interface TranscribeOptions {
+ transcription: FileTranscriptionConfig;
+ folderId: number | null;
+ // Returns an i18n key under notes.upload.* when the file exceeds the
+ // mode-aware size limit, null when acceptable.
+ validateSize?: (sizeBytes: number) => string | null;
+ generateTitle?: (text: string) => Promise<string | null>;
+}
+
+interface BatchQueueStoreState {
+ queue: QueueItem[];
+ isProcessing: boolean;
+}
+
+export const useBatchQueueStore = create<BatchQueueStoreState>()(() => ({
+ queue: [],
+ 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.
+let runId = 0;
+
+function updateQueue(updater: (prev: QueueItem[]) => QueueItem[]) {
+ useBatchQueueStore.setState((s) => ({ queue: updater(s.queue) }));
+}
+
+export function addFiles(files: Array<{ name: string; path: string; sizeBytes: number }>) {
+ const items: QueueItem[] = files.map((f) => ({
+ id: crypto.randomUUID(),
+ source: "file" as const,
+ name: f.name,
+ path: f.path,
+ sizeBytes: f.sizeBytes,
+ status: "queued" as const,
+ progress: 0,
+ }));
+ updateQueue((prev) => [...prev, ...items]);
+ return items;
+}
+
+export function addUrls(urls: string[]) {
+ const items: QueueItem[] = urls.map((url) => ({
+ id: crypto.randomUUID(),
+ source: "url" as const,
+ name: url,
+ path: "",
+ url,
+ sizeBytes: 0,
+ status: "queued" as const,
+ progress: 0,
+ }));
+ updateQueue((prev) => [...prev, ...items]);
+ return items;
+}
+
+export function removeQueueItem(id: string) {
+ updateQueue((prev) => prev.filter((item) => item.id !== id));
+}
+
+export function cancelBatch() {
+ runId++;
+ window.electronAPI.cancelUrlDownload();
+ useBatchQueueStore.setState((s) => ({
+ isProcessing: false,
+ queue: s.queue.map((item) =>
+ item.status === "done" || item.status === "error"
+ ? item
+ : { ...item, status: "error" as const, error: "batchCancelled" }
+ ),
+ }));
+}
+
+export function clearBatchQueue() {
+ runId++;
+ useBatchQueueStore.setState({ queue: [], isProcessing: false });
+}
+
+/**
+ * Drain the queue in the background. Runs detached from React — survives
+ * component unmounts and navigation so the user can browse notes mid-batch.
+ */
+export function processBatchQueue(
+ transcribeOpts: TranscribeOptions,
+ diarization: DiarizationSettings
+): void {
+ if (useBatchQueueStore.getState().isProcessing) return;
+ const run = ++runId;
+ useBatchQueueStore.setState({ isProcessing: true });
+
+ const snapshotApiKey = transcribeOpts.transcription.getApiKey();
+ const transcription: FileTranscriptionConfig = {
+ ...transcribeOpts.transcription,
+ getApiKey: () => snapshotApiKey,
+ };
+
+ // Run-scoped writer: a cancelled run's late IPC results must not touch items.
+ const updateItem = (id: string, updates: Partial<QueueItem>) => {
+ if (run !== runId) return;
+ updateQueue((prev) => prev.map((item) => (item.id === id ? { ...item, ...updates } : item)));
+ };
+
+ const processItem = async (item: QueueItem) => {
+ let filePath = item.path;
+ let tempPath: string | undefined;
+ let noteName = item.name;
+ let sizeBytes = item.sizeBytes;
+ let durationSeconds: number | null = null;
+
+ try {
+ if (item.source === "url" && item.url) {
+ updateItem(item.id, { status: "downloading", progress: 0 });
+
+ const cleanupProgress = window.electronAPI.onUrlDownloadProgress?.((data) => {
+ if (data.downloadId && data.downloadId !== item.id) return;
+ updateItem(item.id, {
+ progress: data.percent,
+ name: data.title || item.name,
+ });
+ });
+
+ try {
+ const res = await window.electronAPI.downloadUrlAudio(item.url, item.id);
+ if (!res.success) {
+ const fail = res as { success: false; error: string; code?: string };
+ const key =
+ fail.code === "DOWNLOAD_CANCELLED"
+ ? "batchCancelled"
+ : DOWNLOAD_ERROR_KEYS[fail.code || ""];
+ updateItem(item.id, { status: "error", error: key || fail.error });
+ return;
+ }
+ filePath = res.tempPath;
+ tempPath = res.tempPath;
+ noteName = res.title || item.name;
+ sizeBytes = res.sizeBytes;
+ durationSeconds = res.durationSeconds;
+ updateItem(item.id, {
+ path: res.tempPath,
+ tempPath: res.tempPath,
+ name: noteName,
+ sizeBytes: res.sizeBytes,
+ });
+ } finally {
+ cleanupProgress?.();
+ }
+ }
+
+ if (run !== runId) return;
+
+ const sizeError = transcribeOpts.validateSize?.(sizeBytes) ?? null;
+ if (sizeError) {
+ updateItem(item.id, { status: "error", error: sizeError });
+ return;
+ }
+
+ updateItem(item.id, { status: "transcribing", progress: 0 });
+
+ const transcriptionResult = await transcribeFileWithSpeakers(
+ filePath,
+ transcription,
+ diarization,
+ durationSeconds
+ );
+
+ if (run !== runId) return;
+
+ if (!transcriptionResult.success || !transcriptionResult.text) {
+ updateItem(item.id, {
+ status: "error",
+ error:
+ transcriptionResult.code === "NO_SPEECH_DETECTED"
+ ? "noSpeechDetected"
+ : transcriptionResult.error || "batchTranscriptionFailed",
+ });
+ return;
+ }
+
+ const finalText = transcriptionResult.text;
+
+ // URL notes keep the video title; file notes get the same generated
+ // titles as the single-file flow.
+ let noteTitle = noteName;
+ if (item.source === "file") {
+ const words = finalText.trim().split(/\s+/);
+ const fallback =
+ words.slice(0, 6).join(" ") + (words.length > 6 ? "..." : "") ||
+ noteName.replace(/\.[^.]+$/, "");
+ noteTitle = (await transcribeOpts.generateTitle?.(finalText)) || fallback;
+ if (run !== runId) return;
+ }
+
+ const noteRes = await window.electronAPI.saveNote(
+ noteTitle,
+ finalText,
+ "upload",
+ noteName,
+ null,
+ transcribeOpts.folderId
+ );
+
+ if (noteRes.success && noteRes.note) {
+ updateItem(item.id, {
+ status: "done",
+ progress: 100,
+ warning: !!transcriptionResult.warning,
+ noteId: noteRes.note.id,
+ });
+ } else {
+ updateItem(item.id, { status: "error", error: "batchSaveFailed" });
+ }
+ } catch (err) {
+ updateItem(item.id, {
+ status: "error",
+ error: err instanceof Error ? err.message : "batchUnknownError",
+ });
+ } finally {
+ // Nothing else owns the temp file, so delete it even for a stale run.
+ if (tempPath) {
+ window.electronAPI.deleteTempFile(tempPath);
+ }
+ }
+ };
+
+ (async () => {
+ const processed = new Set<string>();
+ let next: QueueItem | undefined;
+ while (
+ run === runId &&
+ (next = useBatchQueueStore
+ .getState()
+ .queue.find((i) => i.status === "queued" && !processed.has(i.id)))
+ ) {
+ processed.add(next.id);
+ await processItem(next);
+ }
+ if (run === runId) {
+ useBatchQueueStore.setState({ isProcessing: false });
+ }
+ })();
+}
+
+// Same composed shape the queue UI consumed when this lived in a hook.
+export function useBatchQueue() {
+ const { queue, isProcessing } = useBatchQueueStore();
+
+ return {
+ queue,
+ isProcessing,
+ hasQueue: queue.length > 0,
+ completedCount: queue.filter((i) => i.status === "done").length,
+ failedCount: queue.filter((i) => i.status === "error").length,
+ totalCount: queue.length,
+ addFiles,
+ addUrls,
+ removeItem: removeQueueItem,
+ cancelAll: cancelBatch,
+ clearQueue: clearBatchQueue,
+ processQueue: processBatchQueue,
+ };
+}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 0a9b6eef1..8d63098ef 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -697,7 +697,11 @@ declare global {
onActionDeleted?: (callback: (payload: { id: number }) => void) => () => void;
// Audio file operations
- selectAudioFile: () => Promise<{ canceled: boolean; filePath?: string }>;
+ selectAudioFile: (options?: { multiple?: boolean }) => Promise<{
+ canceled: boolean;
+ filePath?: string;
+ filePaths?: string[];
+ }>;
getFileSize?: (filePath: string) => Promise<number>;
transcribeAudioFile: (
filePath: string,
@@ -710,6 +714,31 @@ declare global {
) => Promise<{ success: boolean; text?: string; error?: string }>;
getPathForFile: (file: File) => string;
+ // URL audio download
+ downloadUrlAudio: (
+ url: string,
+ downloadId?: string
+ ) => Promise<
+ | {
+ success: true;
+ tempPath: string;
+ title: string;
+ durationSeconds: number | null;
+ sizeBytes: number;
+ }
+ | { success: false; error: string; code?: string }
+ >;
+ cancelUrlDownload: (downloadId?: string) => Promise<{ success: boolean }>;
+ deleteTempFile: (filePath: string) => Promise<{ success: boolean; error?: string }>;
+ onUrlDownloadProgress?: (
+ callback: (data: {
+ stage: "resolving" | "downloading" | "ready";
+ percent: number;
+ title?: string;
+ downloadId?: string;
+ }) => void
+ ) => () => void;
+
// Note event listeners
onNoteAdded?: (callback: (note: NoteItem) => void) => () => void;
onNoteUpdated?: (callback: (note: NoteItem) => void) => () => void;
@@ -1316,6 +1345,7 @@ declare global {
apiKey: string;
baseUrl: string;
model: string;
+ diarize?: boolean;
provider?: string;
language?: string;
environment?: string;
@@ -1327,6 +1357,7 @@ declare global {
success: boolean;
text?: string;
error?: string;
+ diarized?: boolean;
}>;
// Usage limit events
@@ -1735,6 +1766,19 @@ declare global {
message?: string;
error?: string;
}>;
+ mergeSpeakerText?: (
+ segments: Array<{ start: number; end: number; speaker: string }>,
+ text: string,
+ duration: number
+ ) => Promise<{ success: boolean; text?: string; error?: string }>;
+ diarizeAudioFile?: (
+ filePath: string,
+ options?: { numSpeakers?: number; threshold?: number }
+ ) => Promise<{
+ success: boolean;
+ segments?: Array<{ start: number; end: number; speaker: string }>;
+ error?: string;
+ }>;
onDiarizationDownloadProgress?: (callback: (data: any) => void) => () => void;
onMeetingDiarizationComplete?: (
callback: (data: {
diff --git a/test/helpers/speakerMerge.test.js b/test/helpers/speakerMerge.test.js
new file mode 100644
index 000000000..04ee4ad67
--- /dev/null
+++ b/test/helpers/speakerMerge.test.js
@@ -0,0 +1,173 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { mergeSpeakersWithText, formatSpeakerTranscript } = require("../../src/helpers/speakerMerge");
+
+test("mergeSpeakersWithText assigns sentences to speakers by time proportion", () => {
+ const segments = [
+ { start: 0, end: 10, speaker: "speaker_0" },
+ { start: 10, end: 20, speaker: "speaker_1" },
+ ];
+ const text = "Hello this is the first part. And this is the second part.";
+ const duration = 20;
+
+ const result = mergeSpeakersWithText(segments, text, duration);
+ assert.equal(result.length, 2);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.ok(result[0].text.includes("first part"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 10);
+ assert.equal(result[1].speaker, "speaker_1");
+ assert.ok(result[1].text.includes("second part"));
+ assert.equal(result[1].start, 10);
+ assert.equal(result[1].end, 20);
+});
+
+test("mergeSpeakersWithText handles single speaker", () => {
+ const segments = [{ start: 0, end: 30, speaker: "speaker_0" }];
+ const text = "All of this text belongs to one speaker.";
+ const duration = 30;
+
+ const result = mergeSpeakersWithText(segments, text, duration);
+ assert.equal(result.length, 1);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.ok(result[0].text.includes("All of this text"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 30);
+});
+
+test("mergeSpeakersWithText returns text as-is when no segments", () => {
+ const result = mergeSpeakersWithText([], "Some text here.", 10);
+ assert.equal(result.length, 1);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.equal(result[0].text, "Some text here.");
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 10);
+});
+
+test("mergeSpeakersWithText consolidates adjacent same-speaker segments", () => {
+ const segments = [
+ { start: 0, end: 5, speaker: "speaker_0" },
+ { start: 5, end: 10, speaker: "speaker_0" },
+ { start: 10, end: 20, speaker: "speaker_1" },
+ ];
+ const text = "First sentence. Second sentence. Third sentence here.";
+ const duration = 20;
+
+ const result = mergeSpeakersWithText(segments, text, duration);
+ assert.equal(result.length, 2);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.ok(result[0].text.includes("First sentence"));
+ assert.ok(result[0].text.includes("Second sentence"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 10);
+ assert.equal(result[1].speaker, "speaker_1");
+ assert.ok(result[1].text.includes("Third sentence here"));
+ assert.equal(result[1].start, 10);
+ assert.equal(result[1].end, 20);
+});
+
+test("formatSpeakerTranscript formats with labels and timestamps", () => {
+ const merged = [
+ { speaker: "speaker_0", text: "Hello there.", start: 0, end: 10 },
+ { speaker: "speaker_1", text: "Hi back.", start: 10, end: 20 },
+ ];
+
+ const output = formatSpeakerTranscript(merged);
+ assert.equal(output, "[Speaker 1] 0:00 - 0:10\nHello there.\n\n[Speaker 2] 0:10 - 0:20\nHi back.");
+});
+
+test("mergeSpeakersWithText handles duration=0 with segments", () => {
+ const segments = [{ start: 0, end: 5, speaker: "speaker_0" }];
+ const text = "Short clip text.";
+ const result = mergeSpeakersWithText(segments, text, 0);
+ assert.equal(result.length, 1);
+ assert.ok(result[0].text.includes("Short clip text"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 5);
+});
+
+test("mergeSpeakersWithText handles zero-duration segment", () => {
+ const segments = [{ start: 0, end: 0, speaker: "speaker_0" }];
+ const text = "Some text.";
+ const result = mergeSpeakersWithText(segments, text, 10);
+ assert.equal(result.length, 1);
+ assert.ok(result[0].text.includes("Some text"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 0);
+});
+
+test("formatSpeakerTranscript returns empty string for empty input", () => {
+ assert.equal(formatSpeakerTranscript([]), "");
+});
+
+test("formatSpeakerTranscript formats minutes and seconds correctly", () => {
+ const merged = [{ speaker: "speaker_0", text: "Long segment.", start: 0, end: 125 }];
+
+ const output = formatSpeakerTranscript(merged);
+ assert.equal(output, "[Speaker 1] 0:00 - 2:05\nLong segment.");
+});
+
+// Regression: the totalDuration fallback used to take segments[segments.length - 1].end,
+// which assumes sorted input. Unsorted segments produced a wrong duration and collapsed
+// every sentence onto one speaker.
+test("mergeSpeakersWithText assigns correct speakers with unsorted segments and no duration", () => {
+ const segments = [
+ { start: 10, end: 20, speaker: "speaker_1" },
+ { start: 0, end: 10, speaker: "speaker_0" },
+ ];
+ const text = "Alpha comes first. Beta comes second.";
+
+ const result = mergeSpeakersWithText(segments, text);
+ assert.equal(result.length, 2);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.ok(result[0].text.includes("Alpha comes first"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 10);
+ assert.equal(result[1].speaker, "speaker_1");
+ assert.ok(result[1].text.includes("Beta comes second"));
+ assert.equal(result[1].start, 10);
+ assert.equal(result[1].end, 20);
+});
+
+test("mergeSpeakersWithText fallback duration matches sorted-input behavior when segments are already ordered", () => {
+ const segments = [
+ { start: 0, end: 10, speaker: "speaker_0" },
+ { start: 10, end: 20, speaker: "speaker_1" },
+ ];
+ const text = "Alpha comes first. Beta comes second.";
+
+ const result = mergeSpeakersWithText(segments, text);
+ assert.equal(result.length, 2);
+ assert.equal(result[0].speaker, "speaker_0");
+ assert.ok(result[0].text.includes("Alpha comes first"));
+ assert.equal(result[0].start, 0);
+ assert.equal(result[0].end, 10);
+ assert.equal(result[1].speaker, "speaker_1");
+ assert.ok(result[1].text.includes("Beta comes second"));
+ assert.equal(result[1].start, 10);
+ assert.equal(result[1].end, 20);
+});
+
+test("empty-sentence fallback uses the max segment end, not the last segment's", () => {
+ const segments = [
+ { speaker: "spk_0", start: 0, end: 30 },
+ { speaker: "spk_1", start: 10, end: 15 },
+ ];
+ const merged = mergeSpeakersWithText(segments, " ", 0);
+ assert.equal(merged.length, 1);
+ assert.equal(merged[0].end, 30);
+});
+
+test("zero duration with unsorted segments still maps proportionally against the max end", () => {
+ // Overlap segment emitted last with an earlier end; a last-segment duration
+ // would compress the timeline to 15s and misassign the tail sentences.
+ const segments = [
+ { speaker: "spk_0", start: 0, end: 30 },
+ { speaker: "spk_1", start: 25, end: 40 },
+ { speaker: "spk_0", start: 10, end: 15 },
+ ];
+ const text = "First sentence here. Second sentence here. Third sentence here. Fourth sentence here.";
+ const merged = mergeSpeakersWithText(segments, text, 0);
+ const last = merged[merged.length - 1];
+ assert.equal(last.speaker, "spk_1", "tail sentences must map to the late segment");
+});
diff --git a/test/helpers/urlAudioDownloader.test.js b/test/helpers/urlAudioDownloader.test.js
new file mode 100644
index 000000000..d977422c8
--- /dev/null
+++ b/test/helpers/urlAudioDownloader.test.js
@@ -0,0 +1,1113 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const dns = require("dns");
+const https = require("https");
+const childProcess = require("child_process");
+const { EventEmitter } = require("events");
+const { Readable } = require("stream");
+const fs = require("fs");
+const os = require("os");
+const path = require("path");
+// Isolate the yt-dlp self-update cache in a temp dir so tests never touch the
+// real ~/.cache/openwhispr. Must be set before the module is required.
+const YT_DLP_TEST_CACHE_DIR = path.join(os.tmpdir(), `ow-ytdlp-test-${process.pid}`);
+process.env.OPENWHISPR_YTDLP_CACHE_DIR = YT_DLP_TEST_CACHE_DIR;
+const downloader = require("../../src/helpers/urlAudioDownloader");
+const {
+ detectUrlType,
+ extractYouTubeVideoId,
+ isPlaylistUrl,
+ isPrivateIp,
+ isAcceptableAudioContentType,
+ ssrfSafeLookup,
+ maybeUpdateYtDlp,
+} = downloader;
+
+test("detectUrlType returns youtube for standard watch URL", () => {
+ assert.equal(detectUrlType("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "youtube");
+});
+
+test("detectUrlType returns youtube for youtu.be short URL", () => {
+ assert.equal(detectUrlType("https://youtu.be/dQw4w9WgXcQ"), "youtube");
+});
+
+test("detectUrlType returns youtube for Shorts URL", () => {
+ assert.equal(detectUrlType("https://www.youtube.com/shorts/dQw4w9WgXcQ"), "youtube");
+});
+
+test("detectUrlType returns youtube for Music URL", () => {
+ assert.equal(detectUrlType("https://music.youtube.com/watch?v=dQw4w9WgXcQ"), "youtube");
+});
+
+test("detectUrlType returns youtube for URL with extra params", () => {
+ assert.equal(
+ detectUrlType("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=120&list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf"),
+ "youtube"
+ );
+});
+
+test("detectUrlType returns youtube for embed URL", () => {
+ assert.equal(detectUrlType("https://www.youtube.com/embed/dQw4w9WgXcQ"), "youtube");
+});
+
+test("detectUrlType returns direct for a podcast mp3 URL", () => {
+ assert.equal(detectUrlType("https://example.com/episodes/ep42.mp3"), "direct");
+});
+
+test("detectUrlType returns direct for any non-YouTube https URL", () => {
+ assert.equal(detectUrlType("https://cdn.radio.com/stream.ogg"), "direct");
+});
+
+test("detectUrlType throws INVALID_URL for non-http scheme", () => {
+ assert.throws(() => detectUrlType("ftp://files.example.com/audio.mp3"));
+ try {
+ detectUrlType("ftp://files.example.com/audio.mp3");
+ } catch (err) {
+ assert.equal(err.code, "INVALID_URL");
+ }
+});
+
+test("detectUrlType throws INVALID_URL for empty string", () => {
+ assert.throws(() => detectUrlType(""));
+ try {
+ detectUrlType("");
+ } catch (err) {
+ assert.equal(err.code, "INVALID_URL");
+ }
+});
+
+test("detectUrlType throws INVALID_URL for garbage input", () => {
+ assert.throws(() => detectUrlType("not a url at all"));
+ try {
+ detectUrlType("not a url at all");
+ } catch (err) {
+ assert.equal(err.code, "INVALID_URL");
+ }
+});
+
+test("extractYouTubeVideoId extracts from standard watch URL", () => {
+ assert.equal(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+});
+
+test("extractYouTubeVideoId extracts from short URL", () => {
+ assert.equal(extractYouTubeVideoId("https://youtu.be/dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+});
+
+test("extractYouTubeVideoId extracts from Shorts URL", () => {
+ assert.equal(extractYouTubeVideoId("https://www.youtube.com/shorts/dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+});
+
+test("extractYouTubeVideoId extracts from embed URL", () => {
+ assert.equal(extractYouTubeVideoId("https://www.youtube.com/embed/dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+});
+
+test("extractYouTubeVideoId extracts from Music URL", () => {
+ assert.equal(extractYouTubeVideoId("https://music.youtube.com/watch?v=dQw4w9WgXcQ"), "dQw4w9WgXcQ");
+});
+
+test("extractYouTubeVideoId returns null for playlist-only URL", () => {
+ assert.equal(extractYouTubeVideoId("https://www.youtube.com/playlist?list=PLrAXtmErZgOe"), null);
+});
+
+test("isPlaylistUrl returns true for playlist-only URL", () => {
+ assert.equal(isPlaylistUrl("https://www.youtube.com/playlist?list=PLrAXtmErZgOe"), true);
+});
+
+test("isPlaylistUrl returns false for watch URL with playlist param", () => {
+ assert.equal(isPlaylistUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLrAXtmErZgOe"), false);
+});
+
+test("isPlaylistUrl returns false for non-YouTube URL", () => {
+ assert.equal(isPlaylistUrl("https://example.com/playlist"), false);
+});
+
+test("isPrivateIp blocks loopback 127.x.x.x", () => {
+ assert.equal(isPrivateIp("127.0.0.1"), true);
+ assert.equal(isPrivateIp("127.255.255.255"), true);
+});
+
+test("isPrivateIp blocks 10.x.x.x", () => {
+ assert.equal(isPrivateIp("10.0.0.1"), true);
+ assert.equal(isPrivateIp("10.255.255.255"), true);
+});
+
+test("isPrivateIp blocks 172.16-31.x.x", () => {
+ assert.equal(isPrivateIp("172.16.0.1"), true);
+ assert.equal(isPrivateIp("172.31.255.255"), true);
+ assert.equal(isPrivateIp("172.15.0.1"), false);
+ assert.equal(isPrivateIp("172.32.0.1"), false);
+});
+
+test("isPrivateIp blocks 192.168.x.x", () => {
+ assert.equal(isPrivateIp("192.168.0.1"), true);
+ assert.equal(isPrivateIp("192.168.255.255"), true);
+});
+
+test("isPrivateIp blocks link-local 169.254.x.x", () => {
+ assert.equal(isPrivateIp("169.254.169.254"), true);
+});
+
+test("isPrivateIp blocks 0.0.0.0/8 (this network)", () => {
+ assert.equal(isPrivateIp("0.0.0.0"), true);
+ assert.equal(isPrivateIp("0.1.2.3"), true);
+});
+
+test("isPrivateIp blocks CGNAT 100.64-127.x.x", () => {
+ assert.equal(isPrivateIp("100.64.0.1"), true);
+ assert.equal(isPrivateIp("100.127.255.255"), true);
+ assert.equal(isPrivateIp("100.63.0.1"), false);
+ assert.equal(isPrivateIp("100.128.0.1"), false);
+});
+
+test("isPrivateIp blocks multicast and reserved (224+)", () => {
+ assert.equal(isPrivateIp("224.0.0.1"), true);
+ assert.equal(isPrivateIp("240.0.0.1"), true);
+ assert.equal(isPrivateIp("255.255.255.255"), true);
+});
+
+test("isPrivateIp allows public IPs", () => {
+ assert.equal(isPrivateIp("8.8.8.8"), false);
+ assert.equal(isPrivateIp("1.1.1.1"), false);
+ assert.equal(isPrivateIp("203.0.113.1"), false);
+});
+
+test("isPrivateIp blocks IPv6 loopback and unspecified", () => {
+ assert.equal(isPrivateIp("::1"), true);
+ assert.equal(isPrivateIp("::"), true);
+});
+
+test("isPrivateIp blocks IPv6 unique local (fc/fd)", () => {
+ assert.equal(isPrivateIp("fc00::1"), true);
+ assert.equal(isPrivateIp("fd12:3456::1"), true);
+});
+
+test("isPrivateIp blocks IPv6 link-local (fe80)", () => {
+ assert.equal(isPrivateIp("fe80::1"), true);
+});
+
+test("isPrivateIp blocks IPv6 multicast (ff)", () => {
+ assert.equal(isPrivateIp("ff02::1"), true);
+});
+
+test("isPrivateIp blocks IPv4-mapped IPv6", () => {
+ assert.equal(isPrivateIp("::ffff:127.0.0.1"), true);
+ assert.equal(isPrivateIp("::ffff:10.0.0.1"), true);
+ assert.equal(isPrivateIp("::ffff:169.254.169.254"), true);
+ assert.equal(isPrivateIp("::ffff:8.8.8.8"), false);
+});
+
+test("isPrivateIp blocks IPv4-compatible IPv6", () => {
+ assert.equal(isPrivateIp("::127.0.0.1"), true);
+ assert.equal(isPrivateIp("::10.0.0.1"), true);
+ assert.equal(isPrivateIp("::8.8.8.8"), false);
+});
+
+test("isPrivateIp blocks NAT64 (64:ff9b::/96) with private embedded IPv4", () => {
+ // hex-embedded forms
+ assert.equal(isPrivateIp("64:ff9b::a00:1"), true); // 10.0.0.1
+ assert.equal(isPrivateIp("64:ff9b::c0a8:101"), true); // 192.168.1.1
+ // dotted-embedded form
+ assert.equal(isPrivateIp("64:ff9b::10.0.0.1"), true);
+ assert.equal(isPrivateIp("64:ff9b::192.168.1.1"), true);
+});
+
+test("isPrivateIp allows NAT64 (64:ff9b::/96) with public embedded IPv4", () => {
+ assert.equal(isPrivateIp("64:ff9b::8.8.8.8"), false);
+ assert.equal(isPrivateIp("64:ff9b::808:808"), false); // 8.8.8.8 in hex
+});
+
+test("isPrivateIp blocks zero-padded NAT64 prefix (0064:ff9b)", () => {
+ assert.equal(isPrivateIp("0064:ff9b::a00:1"), true); // 10.0.0.1
+ assert.equal(isPrivateIp("0064:ff9b::c0a8:101"), true); // 192.168.1.1
+ assert.equal(isPrivateIp("0064:ff9b::10.0.0.1"), true);
+});
+
+test("isPrivateIp allows zero-padded NAT64 prefix with public embedded IPv4", () => {
+ assert.equal(isPrivateIp("0064:ff9b::808:808"), false); // 8.8.8.8
+});
+
+test("isPrivateIp blocks fully-expanded IPv4-mapped loopback/private", () => {
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:7f00:1"), true); // 127.0.0.1
+ assert.equal(isPrivateIp("0000:0000:0000:0000:0000:ffff:7f00:0001"), true); // 127.0.0.1
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:a00:1"), true); // 10.0.0.1
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:a9fe:a9fe"), true); // 169.254.169.254
+});
+
+test("isPrivateIp allows fully-expanded IPv4-mapped public address", () => {
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:808:808"), false); // 8.8.8.8
+});
+
+test("isPrivateIp blocks fully-expanded IPv4-mapped with dotted tail", () => {
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:127.0.0.1"), true);
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:169.254.169.254"), true);
+ assert.equal(isPrivateIp("0:0:0:0:0:ffff:8.8.8.8"), false);
+});
+
+test("isAcceptableAudioContentType accepts audio and video, rejects octet-stream and html", () => {
+ assert.equal(isAcceptableAudioContentType("audio/mpeg"), true);
+ assert.equal(isAcceptableAudioContentType("video/mp4"), true);
+ assert.equal(isAcceptableAudioContentType("AUDIO/MPEG"), true);
+ assert.equal(isAcceptableAudioContentType("application/octet-stream"), false);
+ assert.equal(isAcceptableAudioContentType("text/html"), false);
+ assert.equal(isAcceptableAudioContentType(""), false);
+ assert.equal(isAcceptableAudioContentType(undefined), false);
+});
+
+test("ssrfSafeLookup rejects private IPs via callback", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ dns.lookup = (_hostname, _opts, cb) => cb(null, "127.0.0.1", 4);
+ ssrfSafeLookup("evil.com", {}, (err) => {
+ dns.lookup = original;
+ try {
+ assert.ok(err);
+ assert.equal(err.code, "SSRF_BLOCKED");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ });
+});
+
+test("ssrfSafeLookup allows public IPs via callback", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ dns.lookup = (_hostname, _opts, cb) => cb(null, "93.184.216.34", 4);
+ ssrfSafeLookup("example.com", {}, (err, address) => {
+ dns.lookup = original;
+ try {
+ assert.equal(err, null);
+ assert.equal(address, "93.184.216.34");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ });
+});
+
+// Regression: Happy Eyeballs / autoSelectFamily calls lookup with { all: true },
+// so dns.lookup returns an ARRAY. The old single-value check let private IPs through.
+test("ssrfSafeLookup blocks a private IP in the all:true array form", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ dns.lookup = (_hostname, _opts, cb) =>
+ cb(null, [{ address: "169.254.169.254", family: 4 }]);
+ try {
+ ssrfSafeLookup("metadata.evil.com", { all: true }, (err) => {
+ dns.lookup = original;
+ try {
+ assert.ok(err);
+ assert.equal(err.code, "SSRF_BLOCKED");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ } catch (e) {
+ dns.lookup = original;
+ reject(e);
+ }
+ });
+});
+
+test("ssrfSafeLookup forwards an all-public array unchanged", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ const arr = [
+ { address: "93.184.216.34", family: 4 },
+ { address: "2606:2800:220:1:248:1893:25c8:1946", family: 6 },
+ ];
+ dns.lookup = (_hostname, _opts, cb) => cb(null, arr);
+ try {
+ ssrfSafeLookup("example.com", { all: true }, (err, address) => {
+ dns.lookup = original;
+ try {
+ assert.equal(err, null);
+ assert.deepEqual(address, arr);
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ } catch (e) {
+ dns.lookup = original;
+ reject(e);
+ }
+ });
+});
+
+test("ssrfSafeLookup blocks one private entry mixed into a public array", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ dns.lookup = (_hostname, _opts, cb) =>
+ cb(null, [
+ { address: "8.8.8.8", family: 4 },
+ { address: "10.0.0.5", family: 4 },
+ ]);
+ try {
+ ssrfSafeLookup("rebind.evil.com", { all: true }, (err) => {
+ dns.lookup = original;
+ try {
+ assert.ok(err);
+ assert.equal(err.code, "SSRF_BLOCKED");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ } catch (e) {
+ dns.lookup = original;
+ reject(e);
+ }
+ });
+});
+
+test("ssrfSafeLookup still blocks the legacy single-string private form", () => {
+ return new Promise((resolve, reject) => {
+ const original = dns.lookup;
+ dns.lookup = (_hostname, _opts, cb) => cb(null, "127.0.0.1", 4);
+ try {
+ ssrfSafeLookup("evil.com", {}, (err) => {
+ dns.lookup = original;
+ try {
+ assert.ok(err);
+ assert.equal(err.code, "SSRF_BLOCKED");
+ resolve();
+ } catch (e) {
+ reject(e);
+ }
+ });
+ } catch (e) {
+ dns.lookup = original;
+ reject(e);
+ }
+ });
+});
+
+test("extractYouTubeVideoId rejects youtu.be with non-standard ID", () => {
+ assert.equal(extractYouTubeVideoId("https://youtu.be/x%25(home)s"), null);
+ assert.equal(extractYouTubeVideoId("https://youtu.be/short"), null);
+ assert.equal(extractYouTubeVideoId("https://youtu.be/toolongvideoiddd"), null);
+});
+
+// --- maybeUpdateYtDlp self-update: hang/leak regression ---
+
+// A fake child that never emits close/exit, with a kill() that records the call.
+function makeFakeChild() {
+ const child = new EventEmitter();
+ child.killCalled = false;
+ child.kill = () => { child.killCalled = true; return true; };
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ return child;
+}
+
+// Reject if the promise hasn't settled within ms, so a real hang fails loudly
+// instead of relying on the test runner's global timeout.
+async function resolvesWithin(promise, ms) {
+ let timer;
+ const guard = new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`did not resolve within ${ms}ms`)), ms);
+ });
+ try {
+ await Promise.race([promise, guard]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+// Ensure the writable cache binary exists so maybeUpdateYtDlp reaches the spawn
+// path (it short-circuits when the cache copy is missing). Operates in the
+// isolated test cache dir; the cleanup fn removes that whole dir.
+function ensureCacheBinary() {
+ const cacheDir = YT_DLP_TEST_CACHE_DIR;
+ const name = `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+ const binPath = path.join(cacheDir, name);
+ fs.mkdirSync(cacheDir, { recursive: true });
+ fs.writeFileSync(binPath, "#!/bin/sh\n");
+ try { fs.chmodSync(binPath, 0o755); } catch {}
+ // The update path refuses unverified cache copies, so record the checksum.
+ downloader._recordCacheChecksum();
+ return () => {
+ try { fs.rmSync(cacheDir, { recursive: true, force: true }); } catch {}
+ };
+}
+
+test("maybeUpdateYtDlp resolves on -U timeout, kills the child, and clears the in-flight flag", async () => {
+ const cleanup = ensureCacheBinary();
+ const origSpawn = childProcess.spawn;
+ let spawnCount = 0;
+ let lastChild = null;
+ childProcess.spawn = () => {
+ spawnCount += 1;
+ lastChild = makeFakeChild();
+ return lastChild;
+ };
+ try {
+ await resolvesWithin(maybeUpdateYtDlp({ force: true, timeoutMs: 20 }), 2000);
+ assert.ok(lastChild.killCalled, "timeout should have killed the stuck child");
+ assert.equal(downloader._isYtDlpUpdateInFlight(), false, "in-flight flag must be cleared");
+ assert.equal(spawnCount, 1);
+
+ // A stuck flag would make this second call short-circuit without spawning.
+ await resolvesWithin(maybeUpdateYtDlp({ force: true, timeoutMs: 20 }), 2000);
+ assert.equal(spawnCount, 2, "second call must spawn again, proving no stuck single-flight flag");
+ assert.equal(downloader._isYtDlpUpdateInFlight(), false);
+ } finally {
+ childProcess.spawn = origSpawn;
+ cleanup();
+ }
+});
+
+test("maybeUpdateYtDlp with an already-aborted signal resolves promptly and kills the child", async () => {
+ const cleanup = ensureCacheBinary();
+ const origSpawn = childProcess.spawn;
+ let lastChild = null;
+ childProcess.spawn = () => {
+ lastChild = makeFakeChild();
+ return lastChild;
+ };
+ const ac = new AbortController();
+ ac.abort();
+ try {
+ await resolvesWithin(
+ maybeUpdateYtDlp({ force: true, abortSignal: ac.signal, timeoutMs: 60000 }),
+ 2000
+ );
+ assert.ok(lastChild.killCalled, "abort should have killed the child");
+ assert.equal(downloader._isYtDlpUpdateInFlight(), false, "in-flight flag must be cleared");
+ } finally {
+ childProcess.spawn = origSpawn;
+ cleanup();
+ }
+});
+
+// --- downloadViaProxy: redirect handling regression ---
+//
+// Electron requires request.followRedirect()/request.abort() to be invoked
+// synchronously from inside the "redirect" event. downloadViaProxy instead
+// aborts and rejects with a REDIRECT_RESTART sentinel, then recurses on the
+// redirect URL (re-running assertPublicHost). These fakes emit their events
+// from inside request.end(), which runs after all request.on() listeners are
+// attached in the source, matching real net.request() ordering.
+
+function makeFakeProxyRequest() {
+ const req = new EventEmitter();
+ req.abortCalled = false;
+ req.followRedirectCalled = false;
+ req.abort = () => { req.abortCalled = true; };
+ req.followRedirect = () => { req.followRedirectCalled = true; };
+ req.setHeader = () => {};
+ req.end = () => {};
+ return req;
+}
+
+function makeAudioResponse(body) {
+ const response = Readable.from([Buffer.from(body)]);
+ response.statusCode = 200;
+ response.headers = { "content-type": "audio/mpeg", "content-length": String(body.length) };
+ return response;
+}
+
+test("downloadViaProxy restarts on redirect via abort, never calls followRedirect, and ignores a late error", async () => {
+ const requests = [];
+ const fakeNet = {
+ request(options) {
+ const req = makeFakeProxyRequest();
+ req.url = options.url;
+ requests.push(req);
+ req.end = () => {
+ if (requests.length === 1) {
+ req.emit("redirect", 302, "GET", "https://93.184.216.34/real.mp3");
+ // Late error after the abort must be a no-op: the promise already settled.
+ req.emit("error", new Error("stale socket error"));
+ } else {
+ req.emit("response", makeAudioResponse("audiodata"));
+ }
+ };
+ return req;
+ },
+ };
+
+ downloader._setElectronNetForTests(fakeNet);
+ let tempPath;
+ try {
+ const result = await downloader.downloadViaProxy("https://93.184.216.34/file.mp3", null, null);
+ tempPath = result.tempPath;
+ assert.equal(fs.readFileSync(tempPath, "utf8"), "audiodata");
+ assert.equal(requests.length, 2, "must restart with a fresh request, not follow in place");
+ assert.equal(requests[0].url, "https://93.184.216.34/file.mp3");
+ assert.equal(requests[1].url, "https://93.184.216.34/real.mp3", "restart must target the redirect URL");
+ assert.equal(requests[0].abortCalled, true);
+ assert.equal(requests[0].followRedirectCalled, false);
+ assert.equal(requests[1].followRedirectCalled, false);
+ } finally {
+ downloader._setElectronNetForTests(null);
+ if (tempPath) { try { fs.unlinkSync(tempPath); } catch {} }
+ }
+});
+
+test("downloadViaProxy rejects a redirect to a private IP with SSRF_BLOCKED", async () => {
+ const requests = [];
+ const fakeNet = {
+ request(options) {
+ const req = makeFakeProxyRequest();
+ req.url = options.url;
+ requests.push(req);
+ req.end = () => {
+ req.emit("redirect", 302, "GET", "https://127.0.0.1/x.mp3");
+ };
+ return req;
+ },
+ };
+
+ downloader._setElectronNetForTests(fakeNet);
+ try {
+ await assert.rejects(
+ downloader.downloadViaProxy("https://93.184.216.34/file.mp3", null, null),
+ { code: "SSRF_BLOCKED" }
+ );
+ assert.equal(requests.length, 1, "must not re-request a redirect target rejected by assertPublicHost");
+ } finally {
+ downloader._setElectronNetForTests(null);
+ }
+});
+
+test("downloadViaProxy rejects a non-https redirect with INVALID_URL", async () => {
+ const requests = [];
+ const fakeNet = {
+ request(options) {
+ const req = makeFakeProxyRequest();
+ req.url = options.url;
+ requests.push(req);
+ req.end = () => {
+ req.emit("redirect", 302, "GET", "http://93.184.216.34/x.mp3");
+ };
+ return req;
+ },
+ };
+
+ downloader._setElectronNetForTests(fakeNet);
+ try {
+ await assert.rejects(
+ downloader.downloadViaProxy("https://93.184.216.34/file.mp3", null, null),
+ { code: "INVALID_URL" }
+ );
+ assert.equal(requests.length, 1);
+ } finally {
+ downloader._setElectronNetForTests(null);
+ }
+});
+
+test("downloadViaProxy fails with DOWNLOAD_FAILED after exceeding MAX_REDIRECTS", async () => {
+ const requests = [];
+ const fakeNet = {
+ request(options) {
+ const req = makeFakeProxyRequest();
+ req.url = options.url;
+ requests.push(req);
+ req.end = () => {
+ req.emit("redirect", 302, "GET", "https://93.184.216.34/next.mp3");
+ };
+ return req;
+ },
+ };
+
+ downloader._setElectronNetForTests(fakeNet);
+ try {
+ await assert.rejects(
+ downloader.downloadViaProxy("https://93.184.216.34/file.mp3", null, null),
+ (err) => {
+ assert.equal(err.code, "DOWNLOAD_FAILED");
+ assert.match(err.message, /Too many redirects/);
+ return true;
+ }
+ );
+ // MAX_REDIRECTS is 3 in urlAudioDownloader.js; the 4th redirect trips the limit.
+ assert.equal(requests.length, 4);
+ } finally {
+ downloader._setElectronNetForTests(null);
+ }
+});
+
+test("downloadViaProxy rejects with DOWNLOAD_CANCELLED on mid-flight abort", async () => {
+ const requests = [];
+ const fakeNet = {
+ // A request that emits nothing: no redirect, no response, no error. abort()
+ // only records the call, matching ClientRequest.abort() (never emits 'error').
+ request(options) {
+ const req = makeFakeProxyRequest();
+ req.url = options.url;
+ requests.push(req);
+ return req;
+ },
+ };
+
+ downloader._setElectronNetForTests(fakeNet);
+ const ac = new AbortController();
+ try {
+ const promise = downloader.downloadViaProxy("https://93.184.216.34/file.mp3", null, ac.signal);
+ // Abort after the synchronous setup (assertPublicHost + request.end()) has run.
+ setImmediate(() => ac.abort());
+ await assert.rejects(promise, { code: "DOWNLOAD_CANCELLED" });
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].abortCalled, true, "abort() must be called on the in-flight request");
+ } finally {
+ downloader._setElectronNetForTests(null);
+ }
+});
+
+// --- downloadDirect: node-https path (HEAD/GET redirects, validation, caps) ---
+//
+// download() routes non-YouTube URLs here; the fakes patch https.request (the
+// module calls it through its captured `https` reference, which is this same
+// object). Literal-IP hosts skip DNS, so ssrfSafeLookup is never exercised —
+// these tests cover the per-hop checks in the HEAD/GET redirect handling.
+
+function makeDirectResponse({ statusCode = 200, headers = {}, body = null }) {
+ const res = body != null ? Readable.from([Buffer.from(body)]) : new EventEmitter();
+ res.statusCode = statusCode;
+ res.headers = headers;
+ if (!res.resume) res.resume = () => {};
+ if (!res.destroy) res.destroy = () => {};
+ if (!res.pipe) res.pipe = () => {};
+ return res;
+}
+
+// Patch https.request for the duration of fn. handler(parsed, options) returns
+// the fake response; onResponse (optional) runs after the caller received it.
+async function withFakeHttps(handler, fn) {
+ const orig = https.request;
+ const calls = [];
+ https.request = (parsed, options, callback) => {
+ calls.push({ method: options.method, url: parsed.href });
+ const req = new EventEmitter();
+ req.destroy = () => {};
+ req.end = () => {
+ setImmediate(() => {
+ const { response, after } = handler(parsed, options);
+ callback(response);
+ if (after) setImmediate(() => after(response));
+ });
+ };
+ return req;
+ };
+ try {
+ return await fn(calls);
+ } finally {
+ https.request = orig;
+ }
+}
+
+function listOwUrlTempFiles() {
+ const { getSafeTempDir } = require("../../src/helpers/safeTempDir");
+ return new Set(fs.readdirSync(getSafeTempDir()).filter((f) => f.startsWith("ow-url-")));
+}
+
+test("downloadDirect streams a validated GET to a temp file", async () => {
+ const body = "audiodata";
+ let tempPath;
+ try {
+ await withFakeHttps(
+ (parsed, options) => ({
+ response:
+ options.method === "HEAD"
+ ? makeDirectResponse({
+ headers: { "content-type": "audio/mpeg", "content-length": String(body.length) },
+ })
+ : makeDirectResponse({
+ headers: { "content-type": "audio/mpeg", "content-length": String(body.length) },
+ body,
+ }),
+ }),
+ async (calls) => {
+ const result = await downloader.download("https://93.184.216.34/interview.mp3", null, null);
+ tempPath = result.tempPath;
+ assert.equal(fs.readFileSync(tempPath, "utf8"), body);
+ assert.equal(result.title, "interview");
+ assert.equal(result.sizeBytes, body.length);
+ assert.deepEqual(calls.map((c) => c.method), ["HEAD", "GET"]);
+ }
+ );
+ } finally {
+ if (tempPath) { try { fs.unlinkSync(tempPath); } catch {} }
+ }
+});
+
+test("downloadDirect rejects a HEAD redirect to http:// with INVALID_URL", async () => {
+ await withFakeHttps(
+ () => ({
+ response: makeDirectResponse({
+ statusCode: 302,
+ headers: { location: "http://93.184.216.34/x.mp3" },
+ }),
+ }),
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, null), {
+ code: "INVALID_URL",
+ });
+ }
+ );
+});
+
+test("downloadDirect rejects a HEAD redirect to a private IP with SSRF_BLOCKED", async () => {
+ await withFakeHttps(
+ () => ({
+ response: makeDirectResponse({
+ statusCode: 302,
+ headers: { location: "https://127.0.0.1/x.mp3" },
+ }),
+ }),
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, null), {
+ code: "SSRF_BLOCKED",
+ });
+ }
+ );
+});
+
+test("downloadDirect fails with DOWNLOAD_FAILED after exceeding MAX_REDIRECTS on HEAD", async () => {
+ await withFakeHttps(
+ () => ({
+ response: makeDirectResponse({
+ statusCode: 302,
+ headers: { location: "https://93.184.216.34/next.mp3" },
+ }),
+ }),
+ async (calls) => {
+ await assert.rejects(
+ downloader.download("https://93.184.216.34/file.mp3", null, null),
+ (err) => {
+ assert.equal(err.code, "DOWNLOAD_FAILED");
+ assert.match(err.message, /Too many redirects/);
+ return true;
+ }
+ );
+ // MAX_REDIRECTS is 3; the 4th redirect hop trips the limit.
+ assert.equal(calls.length, 4);
+ }
+ );
+});
+
+test("downloadDirect rejects a GET redirect to a private IP with SSRF_BLOCKED", async () => {
+ await withFakeHttps(
+ (parsed, options) =>
+ options.method === "HEAD"
+ ? { response: makeDirectResponse({ statusCode: 405 }) }
+ : {
+ response: makeDirectResponse({
+ statusCode: 302,
+ headers: { location: "https://10.0.0.1/x.mp3" },
+ }),
+ },
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, null), {
+ code: "SSRF_BLOCKED",
+ });
+ }
+ );
+});
+
+test("downloadDirect re-validates content-type on GET when HEAD is refused", async () => {
+ await withFakeHttps(
+ (parsed, options) =>
+ options.method === "HEAD"
+ ? { response: makeDirectResponse({ statusCode: 405 }) }
+ : {
+ response: makeDirectResponse({
+ headers: { "content-type": "text/html" },
+ body: "<html></html>",
+ }),
+ },
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, null), {
+ code: "CONTENT_TYPE_INVALID",
+ });
+ }
+ );
+});
+
+test("downloadDirect enforces MAX_DOWNLOAD_BYTES on unknown-size streams and cleans up", async () => {
+ const before = listOwUrlTempFiles();
+ await withFakeHttps(
+ (parsed, options) =>
+ options.method === "HEAD"
+ ? { response: makeDirectResponse({ statusCode: 405 }) }
+ : {
+ response: makeDirectResponse({ headers: { "content-type": "audio/mpeg" } }),
+ // Lying length stands in for 501 MB without allocating it.
+ after: (response) => response.emit("data", { length: 501 * 1024 * 1024 }),
+ },
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, null), {
+ code: "FILE_TOO_LARGE",
+ });
+ }
+ );
+ assert.deepEqual(listOwUrlTempFiles(), before, "oversized download must remove its temp file");
+});
+
+test("downloadDirect rejects with DOWNLOAD_CANCELLED on mid-stream abort and cleans up", async () => {
+ const before = listOwUrlTempFiles();
+ const ac = new AbortController();
+ await withFakeHttps(
+ (parsed, options) =>
+ options.method === "HEAD"
+ ? { response: makeDirectResponse({ statusCode: 405 }) }
+ : {
+ response: makeDirectResponse({ headers: { "content-type": "audio/mpeg" } }),
+ after: (response) => {
+ response.emit("data", { length: 1024 });
+ ac.abort();
+ },
+ },
+ async () => {
+ await assert.rejects(downloader.download("https://93.184.216.34/file.mp3", null, ac.signal), {
+ code: "DOWNLOAD_CANCELLED",
+ });
+ }
+ );
+ assert.deepEqual(listOwUrlTempFiles(), before, "cancelled download must remove its temp file");
+});
+
+// --- selectYtDlpOutput: finished-file selection + transient cleanup ---
+
+function mkSelectDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "ow-ytdlp-select-"));
+}
+
+// Create a prefix-matched file with a fixed mtime (seconds) to make ordering deterministic.
+function writeAt(dir, name, mtimeSeconds) {
+ const p = path.join(dir, name);
+ fs.writeFileSync(p, "x");
+ fs.utimesSync(p, mtimeSeconds, mtimeSeconds);
+ return p;
+}
+
+test("selectYtDlpOutput picks the finished file over a longer-named .part leftover", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-1-abc";
+ try {
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ writeAt(dir, `${prefix}.m4a.part`, 1700000500);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.m4a`));
+ assert.equal(fs.existsSync(selected), true);
+ assert.equal(fs.existsSync(path.join(dir, `${prefix}.m4a.part`)), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput prefers the finished file over a newer .fNNN intermediate (tier beats mtime)", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-2-abc";
+ try {
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ writeAt(dir, `${prefix}.f140.m4a`, 1700000500);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.m4a`));
+ assert.equal(fs.existsSync(path.join(dir, `${prefix}.f140.m4a`)), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput picks the newest of two equal-tier audio files", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-3-abc";
+ try {
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ writeAt(dir, `${prefix}.opus`, 1700000500);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.opus`));
+ assert.equal(fs.existsSync(path.join(dir, `${prefix}.m4a`)), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput throws DOWNLOAD_FAILED when only transients remain", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-4-abc";
+ try {
+ writeAt(dir, `${prefix}.m4a.part`, 1700000000);
+ writeAt(dir, `${prefix}.ytdl`, 1700000500);
+ assert.throws(
+ () => downloader._selectYtDlpOutput(dir, prefix),
+ (err) => {
+ assert.equal(err.code, "DOWNLOAD_FAILED");
+ assert.equal(err.message, "Download produced no output");
+ return true;
+ }
+ );
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput keeps only the selected file and deletes every other prefix match", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-5-abc";
+ try {
+ const others = [
+ `${prefix}.m4a.part`,
+ `${prefix}.temp.m4a`,
+ `${prefix}.f140.m4a.part`,
+ `${prefix}.m4a.ytdl`,
+ `${prefix}.f251.webm`,
+ ];
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ for (const name of others) writeAt(dir, name, 1700000500);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.m4a`));
+ assert.equal(fs.existsSync(selected), true);
+ for (const name of others) {
+ assert.equal(fs.existsSync(path.join(dir, name)), false, `${name} should have been deleted`);
+ }
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput excludes a .temp. infix file even when it is newer", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-6-abc";
+ try {
+ writeAt(dir, `${prefix}.temp.m4a`, 1700000500);
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.m4a`));
+ assert.equal(fs.existsSync(path.join(dir, `${prefix}.temp.m4a`)), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("selectYtDlpOutput excludes -Frag fragment files", () => {
+ const dir = mkSelectDir();
+ const prefix = "ow-url-7-abc";
+ try {
+ writeAt(dir, `${prefix}.m4a.part-Frag3`, 1700000500);
+ writeAt(dir, `${prefix}.m4a`, 1700000000);
+ const selected = downloader._selectYtDlpOutput(dir, prefix);
+ assert.equal(selected, path.join(dir, `${prefix}.m4a`));
+ assert.equal(fs.existsSync(path.join(dir, `${prefix}.m4a.part-Frag3`)), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+// --- fe80::/10 link-local range ---
+
+test("isPrivateIp covers the whole fe80::/10 link-local range", () => {
+ assert.equal(isPrivateIp("fe80::1"), true);
+ assert.equal(isPrivateIp("fe81::1"), true);
+ assert.equal(isPrivateIp("febf::1"), true);
+ assert.equal(isPrivateIp("fec0::1"), false);
+ assert.equal(isPrivateIp("fe00::1"), false);
+});
+
+// --- cache binary checksum verification ---
+
+test("resolveYtDlpBinary discards a cache copy whose checksum does not match", () => {
+ const cleanup = ensureCacheBinary();
+ const name = `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+ const cachePath = path.join(YT_DLP_TEST_CACHE_DIR, name);
+ try {
+ assert.equal(downloader._resolveYtDlpBinary(), cachePath, "verified cache copy must win");
+
+ fs.writeFileSync(cachePath, "#!/bin/sh\necho tampered\n");
+ const resolved = downloader._resolveYtDlpBinary();
+ assert.notEqual(resolved, cachePath, "tampered cache copy must not be executed");
+ assert.equal(fs.existsSync(cachePath), false, "tampered copy must be discarded");
+ assert.equal(fs.existsSync(`${cachePath}.sha256`), false, "stale checksum must be discarded");
+ } finally {
+ cleanup();
+ }
+});
+
+test("resolveYtDlpBinary ignores a cache copy that has no recorded checksum", () => {
+ const cleanup = ensureCacheBinary();
+ const name = `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+ const cachePath = path.join(YT_DLP_TEST_CACHE_DIR, name);
+ try {
+ fs.unlinkSync(`${cachePath}.sha256`);
+ const resolved = downloader._resolveYtDlpBinary();
+ assert.notEqual(resolved, cachePath);
+ assert.equal(fs.existsSync(cachePath), false, "unverifiable copy must be discarded");
+ } finally {
+ cleanup();
+ }
+});
+
+test("maybeUpdateYtDlp never executes a tampered cache copy and a failed update keeps the old checksum", async () => {
+ const cleanup = ensureCacheBinary();
+ const name = `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+ const cachePath = path.join(YT_DLP_TEST_CACHE_DIR, name);
+ fs.writeFileSync(cachePath, "#!/bin/sh\necho tampered\n");
+ const origSpawn = childProcess.spawn;
+ const spawnedContents = [];
+ childProcess.spawn = (bin) => {
+ spawnedContents.push(fs.readFileSync(bin));
+ const child = makeFakeChild();
+ setImmediate(() => child.emit("close", 1));
+ return child;
+ };
+ try {
+ await resolvesWithin(maybeUpdateYtDlp({ force: true }), 2000);
+ for (const content of spawnedContents) {
+ assert.ok(!content.includes("tampered"), "tampered binary must never be spawned");
+ }
+ // Whatever remains on disk must be either absent or checksum-consistent —
+ // a failed update (exit 1) must not have blessed anything new.
+ if (fs.existsSync(cachePath)) {
+ assert.equal(downloader._resolveYtDlpBinary(), cachePath, "remaining copy must verify");
+ }
+ } finally {
+ childProcess.spawn = origSpawn;
+ cleanup();
+ }
+});
+
+test("maybeUpdateYtDlp updates on the nightly channel and re-records the checksum", async () => {
+ const cleanup = ensureCacheBinary();
+ const name = `yt-dlp-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`;
+ const cachePath = path.join(YT_DLP_TEST_CACHE_DIR, name);
+ const origSpawn = childProcess.spawn;
+ let spawnArgs = null;
+ let child = null;
+ childProcess.spawn = (_bin, args) => {
+ spawnArgs = args;
+ child = makeFakeChild();
+ setImmediate(() => {
+ // Simulate the updater replacing the binary before exiting.
+ fs.writeFileSync(cachePath, "#!/bin/sh\necho updated\n");
+ child.emit("close", 0);
+ });
+ return child;
+ };
+ try {
+ await resolvesWithin(maybeUpdateYtDlp({ force: true }), 2000);
+ assert.deepEqual(spawnArgs, ["--update-to", "nightly"]);
+ assert.equal(downloader._resolveYtDlpBinary(), cachePath, "updated copy must pass verification");
+ } finally {
+ childProcess.spawn = origSpawn;
+ cleanup();
+ }
+});
+
+// --- YouTube network-block heuristic ---
+
+test("looksLikeYouTubeBlock matches bot checks, 403s, and login walls but not ordinary errors", () => {
+ const block = downloader._looksLikeYouTubeBlock;
+ assert.equal(block("ERROR: Sign in to confirm you're not a bot"), true);
+ assert.equal(block("HTTP Error 403: Forbidden"), true);
+ assert.equal(block("The following content is not available on this app (LOGIN_REQUIRED)"), true);
+ assert.equal(block("YouTube is forcing SABR streaming for this client"), true);
+ assert.equal(block("Video unavailable"), false);
+ assert.equal(block("This video is private"), false);
+ assert.equal(block(""), false);
+});