Skip to content

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

feat: audio retention, raw transcript viewing, and hover actions

Gabriel Stein1a1b05450fc9
diff --git a/preload.js b/preload.js
index 975d5629d..797e43066 100644
--- a/preload.js
+++ b/preload.js
@@ -31,10 +31,22 @@ contextBridge.exposeInMainWorld("electronAPI", {
onStopDictation: registerListener("stop-dictation", (callback) => () => callback()),
// Database functions
- saveTranscription: (text) => ipcRenderer.invoke("db-save-transcription", text),
+ saveTranscription: (text, rawText) => ipcRenderer.invoke("db-save-transcription", text, rawText),
getTranscriptions: (limit) => ipcRenderer.invoke("db-get-transcriptions", limit),
clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),
deleteTranscription: (id) => ipcRenderer.invoke("db-delete-transcription", id),
+
+ // Audio storage functions
+ saveTranscriptionAudio: (id, audioBuffer, metadata) =>
+ ipcRenderer.invoke("save-transcription-audio", id, audioBuffer, metadata),
+ getAudioPath: (id) => ipcRenderer.invoke("get-audio-path", id),
+ getAudioBuffer: (id) => ipcRenderer.invoke("get-audio-buffer", id),
+ deleteTranscriptionAudio: (id) => ipcRenderer.invoke("delete-transcription-audio", id),
+ getAudioStorageUsage: () => ipcRenderer.invoke("get-audio-storage-usage"),
+ deleteAllAudio: () => ipcRenderer.invoke("delete-all-audio"),
+ retryTranscription: (id) => ipcRenderer.invoke("retry-transcription", id),
+ getTranscriptionById: (id) => ipcRenderer.invoke("get-transcription-by-id", id),
+
// Dictionary functions
getDictionary: () => ipcRenderer.invoke("db-get-dictionary"),
setDictionary: (words) => ipcRenderer.invoke("db-set-dictionary", words),
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 348337b8e..089951ecc 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -15,6 +15,7 @@ import {
useTranscriptions,
initializeTranscriptions,
removeTranscription as removeFromStore,
+ updateTranscription as updateInStore,
} from "../stores/transcriptionStore";
import ControlPanelSidebar, { type ControlPanelView } from "./ControlPanelSidebar";
import WindowControls from "./WindowControls";
@@ -243,6 +244,59 @@ export default function ControlPanel() {
[showConfirmDialog, showAlertDialog, t]
);
+ const downloadAudio = useCallback(
+ async (id: number) => {
+ try {
+ const buffer = await window.electronAPI.getAudioBuffer(id);
+ if (!buffer) {
+ toast({
+ title: t("controlPanel.history.audioNotFound"),
+ variant: "destructive",
+ });
+ return;
+ }
+ const blob = new Blob([buffer], { type: "audio/webm" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `openwhispr-${id}.webm`;
+ a.click();
+ URL.revokeObjectURL(url);
+ toast({ title: t("controlPanel.history.audioSaved") });
+ } catch {
+ toast({
+ title: t("controlPanel.history.audioNotFound"),
+ variant: "destructive",
+ });
+ }
+ },
+ [toast, t]
+ );
+
+ const retryTranscription = useCallback(
+ async (id: number) => {
+ try {
+ const result = await window.electronAPI.retryTranscription(id);
+ if (result.success && result.transcription) {
+ updateInStore(result.transcription);
+ toast({ title: t("controlPanel.history.retrySuccess") });
+ } else {
+ toast({
+ title: t("controlPanel.history.retryError"),
+ description: result.error,
+ variant: "destructive",
+ });
+ }
+ } catch {
+ toast({
+ title: t("controlPanel.history.retryError"),
+ variant: "destructive",
+ });
+ }
+ },
+ [toast, t]
+ );
+
const handleUpdateClick = async () => {
if (updateStatus.updateDownloaded) {
showConfirmDialog({
@@ -495,6 +549,8 @@ export default function ControlPanel() {
useReasoningModel={useReasoningModel}
copyToClipboard={copyToClipboard}
deleteTranscription={deleteTranscription}
+ onDownloadAudio={downloadAudio}
+ onRetryTranscription={retryTranscription}
onOpenSettings={(section) => {
setSettingsSection(section);
setShowSettings(true);
diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsx
index 504c8e240..2442d38a7 100644
--- a/src/components/HistoryView.tsx
+++ b/src/components/HistoryView.tsx
@@ -19,6 +19,8 @@ interface HistoryViewProps {
copyToClipboard: (text: string) => void;
deleteTranscription: (id: number) => void;
onOpenSettings: (section?: string) => void;
+ onDownloadAudio: (id: number) => void;
+ onRetryTranscription: (id: number) => Promise<void>;
}
export default function HistoryView({
@@ -33,6 +35,8 @@ export default function HistoryView({
copyToClipboard,
deleteTranscription,
onOpenSettings,
+ onDownloadAudio,
+ onRetryTranscription,
}: HistoryViewProps) {
const { t } = useTranslation();
@@ -257,6 +261,8 @@ export default function HistoryView({
item={item}
onCopy={copyToClipboard}
onDelete={deleteTranscription}
+ onDownloadAudio={onDownloadAudio}
+ onRetryTranscription={onRetryTranscription}
/>
))}
</div>
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 49e265165..8084c2e9a 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -62,6 +62,7 @@ import logger from "../utils/logger";
import { SettingsRow } from "./ui/SettingsSection";
import { useUsage } from "../hooks/useUsage";
import { cn } from "./lib/utils";
+import { formatBytes } from "../utils/formatBytes";
export type SettingsSectionType =
| "account"
@@ -681,6 +682,8 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
setCloudBackupEnabled,
telemetryEnabled,
setTelemetryEnabled,
+ audioRetentionDays,
+ setAudioRetentionDays,
customDictionary,
setCustomDictionary,
} = useSettings();
@@ -718,6 +721,31 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
const { agentName, setAgentName } = useAgentName();
const [agentNameInput, setAgentNameInput] = useState(agentName);
const [newDictionaryWord, setNewDictionaryWord] = useState("");
+ const [audioStorageUsage, setAudioStorageUsage] = useState<{
+ fileCount: number;
+ totalBytes: number;
+ }>({ fileCount: 0, totalBytes: 0 });
+
+ useEffect(() => {
+ if (activeSection !== "privacyData") return;
+ window.electronAPI
+ ?.getAudioStorageUsage?.()
+ .then((usage: { fileCount: number; totalBytes: number }) => {
+ if (usage) setAudioStorageUsage(usage);
+ })
+ .catch(() => {});
+ }, [activeSection]);
+
+ const handleClearAllAudio = async () => {
+ if (!window.electronAPI?.deleteAllAudio) return;
+ try {
+ await window.electronAPI.deleteAllAudio();
+ setAudioStorageUsage({ fileCount: 0, totalBytes: 0 });
+ toast({ title: t("settingsPage.privacy.clearAllAudio"), variant: "default" });
+ } catch {
+ // silent fail
+ }
+ };
const handleAddDictionaryWord = useCallback(() => {
const existingWords = new Set(customDictionary.map((w) => w.toLowerCase()));
@@ -2367,6 +2395,69 @@ export default function SettingsPage({ activeSection = "general" }: SettingsPage
</SettingsPanel>
</div>
+ {/* Audio Retention */}
+ <div className="border-t border-border/40 pt-6">
+ <SectionHeader
+ title={t("settingsPage.privacy.audioRetention")}
+ description={t("settingsPage.privacy.audioRetentionDescription")}
+ />
+
+ <SettingsPanel>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.audioRetention")}
+ description={t("settingsPage.privacy.audioRetentionDescription")}
+ >
+ <select
+ value={audioRetentionDays}
+ onChange={(e) => setAudioRetentionDays(parseInt(e.target.value, 10))}
+ className="h-7 rounded border border-border/70 bg-surface-1/80 px-2.5 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm hover:border-border-hover hover:bg-surface-2/70 focus:outline-none focus:ring-2 focus:ring-ring/30 focus:ring-offset-1 transition-colors duration-200"
+ >
+ <option value={0}>{t("settingsPage.privacy.audioRetentionDisabled")}</option>
+ <option value={7}>
+ {t("settingsPage.privacy.audioRetentionDays", { count: 7 })}
+ </option>
+ <option value={14}>
+ {t("settingsPage.privacy.audioRetentionDays", { count: 14 })}
+ </option>
+ <option value={30}>
+ {t("settingsPage.privacy.audioRetentionDays", { count: 30 })}
+ </option>
+ <option value={60}>
+ {t("settingsPage.privacy.audioRetentionDays", { count: 60 })}
+ </option>
+ <option value={90}>
+ {t("settingsPage.privacy.audioRetentionDays", { count: 90 })}
+ </option>
+ </select>
+ </SettingsRow>
+ </SettingsPanelRow>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.audioStorageUsage")}
+ description={
+ audioStorageUsage.fileCount > 0
+ ? t("settingsPage.privacy.audioStorageFiles", {
+ count: audioStorageUsage.fileCount,
+ size: formatBytes(audioStorageUsage.totalBytes),
+ })
+ : t("settingsPage.privacy.audioStorageEmpty")
+ }
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 text-xs"
+ disabled={audioStorageUsage.fileCount === 0}
+ onClick={handleClearAllAudio}
+ >
+ {t("settingsPage.privacy.clearAllAudio")}
+ </Button>
+ </SettingsRow>
+ </SettingsPanelRow>
+ </SettingsPanel>
+ </div>
+
{/* Permissions */}
<div className="border-t border-border/40 pt-6">
<SectionHeader
diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsx
index adf2d8305..60edb53d1 100644
--- a/src/components/ui/TranscriptionItem.tsx
+++ b/src/components/ui/TranscriptionItem.tsx
@@ -1,7 +1,8 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "./button";
-import { Copy, Trash2 } from "lucide-react";
+import { Tooltip } from "./tooltip";
+import { Copy, Trash2, FileText, Download, RotateCcw, Loader2 } from "lucide-react";
import type { TranscriptionItem as TranscriptionItemType } from "../../types/electron";
import { cn } from "../lib/utils";
@@ -9,11 +10,21 @@ interface TranscriptionItemProps {
item: TranscriptionItemType;
onCopy: (text: string) => void;
onDelete: (id: number) => void;
+ onDownloadAudio?: (id: number) => void;
+ onRetryTranscription?: (id: number) => Promise<void>;
}
-export default function TranscriptionItem({ item, onCopy, onDelete }: TranscriptionItemProps) {
- const { i18n } = useTranslation();
+export default function TranscriptionItem({
+ item,
+ onCopy,
+ onDelete,
+ onDownloadAudio,
+ onRetryTranscription,
+}: TranscriptionItemProps) {
+ const { t, i18n } = useTranslation();
const [isHovered, setIsHovered] = useState(false);
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [isRetrying, setIsRetrying] = useState(false);
const timestampSource = item.timestamp.endsWith("Z") ? item.timestamp : `${item.timestamp}Z`;
const timestampDate = new Date(timestampSource);
@@ -24,6 +35,20 @@ export default function TranscriptionItem({ item, onCopy, onDelete }: Transcript
minute: "2-digit",
});
+ const handleRetry = async () => {
+ if (isRetrying || !onRetryTranscription) return;
+ setIsRetrying(true);
+ try {
+ await onRetryTranscription(item.id);
+ } finally {
+ setIsRetrying(false);
+ }
+ };
+
+ const hasRawText = item.raw_text !== null;
+ const hasAudio = item.has_audio === 1;
+ const showUtilityGroup = hasRawText || hasAudio;
+
return (
<div
className="group rounded-md border border-border/40 dark:border-border-subtle/60 bg-card/50 dark:bg-surface-2/60 px-3 py-2.5 transition-colors duration-150 hover:bg-muted/30 dark:hover:bg-surface-2/80"
@@ -47,22 +72,90 @@ export default function TranscriptionItem({ item, onCopy, onDelete }: Transcript
isHovered ? "opacity-100" : "opacity-0"
)}
>
- <Button
- size="icon"
- variant="ghost"
- onClick={() => onCopy(item.text)}
- className="h-6 w-6 rounded-sm text-muted-foreground hover:text-foreground hover:bg-foreground/10"
- >
- <Copy size={12} />
- </Button>
- <Button
- size="icon"
- variant="ghost"
- onClick={() => onDelete(item.id)}
- className="h-6 w-6 rounded-sm text-muted-foreground hover:text-destructive hover:bg-destructive/10"
- >
- <Trash2 size={12} />
- </Button>
+ {hasRawText && (
+ <Tooltip content={t("controlPanel.history.viewRawTranscript")}>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={() => setIsExpanded(!isExpanded)}
+ className={cn(
+ "h-6 w-6 rounded-sm text-muted-foreground hover:text-primary hover:bg-primary/10",
+ isExpanded && "text-primary"
+ )}
+ >
+ <FileText size={12} />
+ </Button>
+ </Tooltip>
+ )}
+ {hasAudio && (
+ <Tooltip content={t("controlPanel.history.downloadAudio")}>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={() => onDownloadAudio?.(item.id)}
+ className="h-6 w-6 rounded-sm text-muted-foreground hover:text-primary hover:bg-primary/10"
+ >
+ <Download size={12} />
+ </Button>
+ </Tooltip>
+ )}
+ {hasAudio && (
+ <Tooltip content={t("controlPanel.history.retryTranscription")}>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handleRetry}
+ disabled={isRetrying}
+ className="h-6 w-6 rounded-sm text-muted-foreground hover:text-primary hover:bg-primary/10"
+ >
+ {isRetrying ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ <RotateCcw size={12} />
+ )}
+ </Button>
+ </Tooltip>
+ )}
+ {showUtilityGroup && <div className="w-px h-3 bg-border/30" />}
+ <Tooltip content={t("controlPanel.history.copyText")}>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={() => onCopy(item.text)}
+ className="h-6 w-6 rounded-sm text-muted-foreground hover:text-foreground hover:bg-foreground/10"
+ >
+ <Copy size={12} />
+ </Button>
+ </Tooltip>
+ <Tooltip content={t("controlPanel.history.deleteItem")}>
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={() => onDelete(item.id)}
+ className="h-6 w-6 rounded-sm text-muted-foreground hover:text-destructive hover:bg-destructive/10"
+ >
+ <Trash2 size={12} />
+ </Button>
+ </Tooltip>
+ </div>
+ </div>
+
+ <div
+ className={cn(
+ "overflow-hidden transition-all duration-200",
+ isExpanded ? "max-h-96" : "max-h-0"
+ )}
+ >
+ <div className="border-t border-border/20 mt-2 pt-2">
+ <span className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">
+ {t("controlPanel.history.rawTranscript")}
+ </span>
+ <p className="text-xs text-muted-foreground/80 leading-relaxed mt-1">{item.raw_text}</p>
+ {item.raw_text === item.text && (
+ <p className="text-[10px] text-muted-foreground/50 italic mt-1">
+ {t("controlPanel.history.noAiProcessing")}
+ </p>
+ )}
</div>
</div>
</div>
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index fcc5376e4..6e6831a86 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -98,6 +98,8 @@ class AudioManager {
this.skipReasoning = false;
this.context = "dictation";
this.sttConfig = null;
+ this.lastAudioBlob = null;
+ this.lastAudioMetadata = null;
}
getWorkletBlobUrl() {
@@ -323,6 +325,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.onStateChange?.({ isRecording: false, isProcessing: true });
const audioBlob = new Blob(this.audioChunks, { type: this.recordingMimeType });
+ this.lastAudioBlob = audioBlob; // preserve for audio retention
logger.info(
"Recording stopped",
@@ -477,6 +480,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
return;
}
+ this.lastAudioMetadata = {
+ durationMs: metadata?.durationSeconds
+ ? Math.round(metadata.durationSeconds * 1000)
+ : Math.round(performance.now() - pipelineStart),
+ provider: result?.source || (useLocalWhisper ? localProvider : "cloud"),
+ model: activeModel || null,
+ };
+
this.onTranscriptionComplete?.(result);
if (result?.source === "openwhispr") {
@@ -1810,9 +1821,27 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
}
- async saveTranscription(text) {
+ async saveTranscription(text, rawText = null) {
try {
- await window.electronAPI.saveTranscription(text);
+ const result = await window.electronAPI.saveTranscription(text, rawText);
+
+ // Save audio if we have a captured blob and the transcription was saved successfully
+ if (result?.id && this.lastAudioBlob) {
+ try {
+ const arrayBuffer = await this.lastAudioBlob.arrayBuffer();
+ await window.electronAPI.saveTranscriptionAudio(
+ result.id,
+ arrayBuffer,
+ this.lastAudioMetadata
+ );
+ } catch (audioErr) {
+ // Non-blocking: transcription is saved even if audio save fails
+ logger.warn("Failed to save transcription audio", { error: audioErr.message }, "audio");
+ }
+ this.lastAudioBlob = null;
+ this.lastAudioMetadata = null;
+ }
+
return true;
} catch (error) {
return false;
@@ -2217,6 +2246,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.streamingFallbackRecorder.stop();
});
}
+ if (fallbackBlob) {
+ this.lastAudioBlob = fallbackBlob; // preserve for audio retention
+ }
this.streamingFallbackRecorder = null;
this.streamingFallbackChunks = [];
@@ -2380,6 +2412,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
if (finalText) {
const tBeforePaste = performance.now();
const clientTotalMs = Math.round(tBeforePaste - t0);
+ this.lastAudioMetadata = {
+ durationMs: durationSeconds
+ ? Math.round(durationSeconds * 1000)
+ : Math.round(tBeforePaste - t0),
+ provider: `${this.sttConfig?.streamingProvider || "deepgram"}-streaming`,
+ model: streamingSttModel || null,
+ };
this.onTranscriptionComplete?.({
success: true,
text: finalText,
@@ -2501,6 +2540,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
}
cleanup() {
+ this.lastAudioBlob = null;
+ this.lastAudioMetadata = null;
if (this.isStreaming) {
this.cleanupStreaming();
}
diff --git a/src/helpers/audioStorage.js b/src/helpers/audioStorage.js
new file mode 100644
index 000000000..84638ba1a
--- /dev/null
+++ b/src/helpers/audioStorage.js
@@ -0,0 +1,167 @@
+const fs = require("fs");
+const path = require("path");
+const { app } = require("electron");
+const debugLogger = require("./debugLogger");
+
+class AudioStorageManager {
+ constructor() {
+ this.audioDir = path.join(app.getPath("userData"), "audio");
+ this.ensureAudioDir();
+ }
+
+ ensureAudioDir() {
+ try {
+ fs.mkdirSync(this.audioDir, { recursive: true });
+ } catch (error) {
+ debugLogger.error(
+ "Failed to create audio directory",
+ { error: error.message },
+ "audio-storage"
+ );
+ }
+ }
+
+ saveAudio(transcriptionId, audioBuffer) {
+ try {
+ const filePath = path.join(this.audioDir, `${transcriptionId}.webm`);
+ fs.writeFileSync(filePath, audioBuffer);
+ debugLogger.debug(
+ "Audio saved",
+ { transcriptionId, size: audioBuffer.length },
+ "audio-storage"
+ );
+ return { success: true, path: filePath };
+ } catch (error) {
+ debugLogger.error(
+ "Failed to save audio",
+ { transcriptionId, error: error.message },
+ "audio-storage"
+ );
+ return { success: false };
+ }
+ }
+
+ getAudioPath(transcriptionId) {
+ const filePath = path.join(this.audioDir, `${transcriptionId}.webm`);
+ return fs.existsSync(filePath) ? filePath : null;
+ }
+
+ getAudioBuffer(transcriptionId) {
+ const filePath = this.getAudioPath(transcriptionId);
+ if (!filePath) return null;
+ try {
+ return fs.readFileSync(filePath);
+ } catch (error) {
+ debugLogger.error(
+ "Failed to read audio",
+ { transcriptionId, error: error.message },
+ "audio-storage"
+ );
+ return null;
+ }
+ }
+
+ deleteAudio(transcriptionId) {
+ try {
+ const filePath = path.join(this.audioDir, `${transcriptionId}.webm`);
+ if (fs.existsSync(filePath)) {
+ fs.unlinkSync(filePath);
+ debugLogger.debug("Audio deleted", { transcriptionId }, "audio-storage");
+ }
+ return { success: true };
+ } catch (error) {
+ debugLogger.error(
+ "Failed to delete audio",
+ { transcriptionId, error: error.message },
+ "audio-storage"
+ );
+ return { success: false };
+ }
+ }
+
+ cleanupExpiredAudio(retentionDays, databaseManager) {
+ try {
+ const cutoffMs = Date.now() - retentionDays * 86400000;
+ const files = fs.readdirSync(this.audioDir).filter((f) => f.endsWith(".webm"));
+ const expiredIds = [];
+ let kept = 0;
+
+ for (const file of files) {
+ const filePath = path.join(this.audioDir, file);
+ try {
+ const stats = fs.statSync(filePath);
+ if (stats.mtimeMs < cutoffMs) {
+ fs.unlinkSync(filePath);
+ const id = path.basename(file, ".webm");
+ expiredIds.push(id);
+ } else {
+ kept++;
+ }
+ } catch (error) {
+ debugLogger.error(
+ "Failed to process audio file during cleanup",
+ { file, error: error.message },
+ "audio-storage"
+ );
+ }
+ }
+
+ if (expiredIds.length > 0 && databaseManager) {
+ databaseManager.clearAudioFlags(expiredIds);
+ }
+
+ debugLogger.info(
+ "Audio cleanup complete",
+ { deleted: expiredIds.length, kept, retentionDays },
+ "audio-storage"
+ );
+ return { deleted: expiredIds.length, kept };
+ } catch (error) {
+ debugLogger.error("Audio cleanup failed", { error: error.message }, "audio-storage");
+ return { deleted: 0, kept: 0 };
+ }
+ }
+
+ deleteAllAudio() {
+ try {
+ const files = fs.readdirSync(this.audioDir).filter((f) => f.endsWith(".webm"));
+ for (const file of files) {
+ try {
+ fs.unlinkSync(path.join(this.audioDir, file));
+ } catch (error) {
+ debugLogger.error(
+ "Failed to delete audio file",
+ { file, error: error.message },
+ "audio-storage"
+ );
+ }
+ }
+ debugLogger.info("All audio deleted", { count: files.length }, "audio-storage");
+ return { deleted: files.length };
+ } catch (error) {
+ debugLogger.error("Failed to delete all audio", { error: error.message }, "audio-storage");
+ return { deleted: 0 };
+ }
+ }
+
+ getStorageUsage() {
+ try {
+ const files = fs.readdirSync(this.audioDir).filter((f) => f.endsWith(".webm"));
+ let totalBytes = 0;
+ for (const file of files) {
+ try {
+ const stats = fs.statSync(path.join(this.audioDir, file));
+ totalBytes += stats.size;
+ } catch {
+ // Skip files that can't be stat'd
+ }
+ }
+ return { fileCount: files.length, totalBytes };
+ } catch (error) {
+ debugLogger.error("Failed to get storage usage", { error: error.message }, "audio-storage");
+ return { fileCount: 0, totalBytes: 0 };
+ }
+ }
+}
+
+module.exports = AudioStorageManager;
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 423c8faa7..069436c61 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -29,6 +29,33 @@ class DatabaseManager {
)
`);
+ // Audio retention columns
+ try {
+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN raw_text TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN has_audio INTEGER NOT NULL DEFAULT 0");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN audio_duration_ms INTEGER");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN provider TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+ try {
+ this.db.exec("ALTER TABLE transcriptions ADD COLUMN model TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
this.db.exec(`
CREATE TABLE IF NOT EXISTS custom_dictionary (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -148,13 +175,13 @@ class DatabaseManager {
}
}
- saveTranscription(text) {
+ saveTranscription(text, rawText = null) {
try {
if (!this.db) {
throw new Error("Database not initialized");
}
- const stmt = this.db.prepare("INSERT INTO transcriptions (text) VALUES (?)");
- const result = stmt.run(text);
+ const stmt = this.db.prepare("INSERT INTO transcriptions (text, raw_text) VALUES (?, ?)");
+ const result = stmt.run(text, rawText);
const fetchStmt = this.db.prepare("SELECT * FROM transcriptions WHERE id = ?");
const transcription = fetchStmt.get(result.lastInsertRowid);
@@ -208,6 +235,61 @@ class DatabaseManager {
}
}
+ updateTranscriptionAudio(id, { hasAudio, audioDurationMs, provider, model }) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare(
+ "UPDATE transcriptions SET has_audio = ?, audio_duration_ms = ?, provider = ?, model = ? WHERE id = ?"
+ );
+ stmt.run(hasAudio, audioDurationMs, provider, model, id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error updating transcription audio", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ updateTranscriptionText(id, text, rawText) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare("UPDATE transcriptions SET text = ?, raw_text = ? WHERE id = ?");
+ stmt.run(text, rawText, id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error updating transcription text", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ getTranscriptionById(id) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ const stmt = this.db.prepare("SELECT * FROM transcriptions WHERE id = ?");
+ return stmt.get(id) || null;
+ } catch (error) {
+ debugLogger.error("Error getting transcription by id", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
+ clearAudioFlags(ids) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ if (!ids || ids.length === 0) return { success: true };
+ const transaction = this.db.transaction((idList) => {
+ const stmt = this.db.prepare("UPDATE transcriptions SET has_audio = 0 WHERE id = ?");
+ for (const id of idList) {
+ stmt.run(id);
+ }
+ });
+ transaction(ids);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error clearing audio flags", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
getDictionary() {
try {
if (!this.db) {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index d6f4eac20..67f37be62 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -9,6 +9,7 @@ const GnomeShortcutManager = require("./gnomeShortcut");
const AssemblyAiStreaming = require("./assemblyAiStreaming");
const { i18nMain, changeLanguage } = require("./i18nMain");
const DeepgramStreaming = require("./deepgramStreaming");
+const AudioStorageManager = require("./audioStorage");
const MISTRAL_TRANSCRIPTION_URL = "https://api.mistral.ai/v1/audio/transcriptions";
@@ -106,7 +107,10 @@ class IPCHandlers {
this._autoLearnDebounceTimer = null;
this._autoLearnLatestData = null;
this._textEditHandler = null;
+ this.audioStorageManager = new AudioStorageManager();
+ this._audioCleanupInterval = null;
this._setupTextEditMonitor();
+ this._setupAudioCleanup();
this.setupHandlers();
if (this.whisperManager?.serverManager) {
@@ -136,6 +140,38 @@ class IPCHandlers {
}
}
+ _setupAudioCleanup() {
+ const DEFAULT_RETENTION_DAYS = 30;
+ const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
+
+ // Run initial cleanup with default retention
+ try {
+ this.audioStorageManager.cleanupExpiredAudio(DEFAULT_RETENTION_DAYS, this.databaseManager);
+ } catch (error) {
+ debugLogger.error("Initial audio cleanup failed", { error: error.message }, "audio-storage");
+ }
+
+ // Set up periodic cleanup every 6 hours
+ this._audioCleanupInterval = setInterval(() => {
+ try {
+ this.audioStorageManager.cleanupExpiredAudio(DEFAULT_RETENTION_DAYS, this.databaseManager);
+ } catch (error) {
+ debugLogger.error(
+ "Periodic audio cleanup failed",
+ { error: error.message },
+ "audio-storage"
+ );
+ }
+ }, SIX_HOURS_MS);
+ }
+
+ _cleanupAudioInterval() {
+ if (this._audioCleanupInterval) {
+ clearInterval(this._audioCleanupInterval);
+ this._audioCleanupInterval = null;
+ }
+ }
+
_setupTextEditMonitor() {
if (!this.textEditMonitor) return;
@@ -310,8 +346,8 @@ class IPCHandlers {
return this.environmentManager.createProductionEnvFile(apiKey);
});
- ipcMain.handle("db-save-transcription", async (event, text) => {
- const result = this.databaseManager.saveTranscription(text);
+ ipcMain.handle("db-save-transcription", async (event, text, rawText) => {
+ const result = this.databaseManager.saveTranscription(text, rawText);
if (result?.success && result?.transcription) {
setImmediate(() => {
this.broadcastToWindows("transcription-added", result.transcription);
@@ -325,6 +361,7 @@ class IPCHandlers {
});
ipcMain.handle("db-clear-transcriptions", async (event) => {
+ this.audioStorageManager.deleteAllAudio();
const result = this.databaseManager.clearTranscriptions();
if (result?.success) {
setImmediate(() => {
@@ -337,6 +374,7 @@ class IPCHandlers {
});
ipcMain.handle("db-delete-transcription", async (event, id) => {
+ this.audioStorageManager.deleteAudio(id);
const result = this.databaseManager.deleteTranscription(id);
if (result?.success) {
setImmediate(() => {
@@ -346,6 +384,105 @@ class IPCHandlers {
return result;
});
+ // Audio storage handlers
+ ipcMain.handle("save-transcription-audio", async (event, id, audioBuffer, metadata) => {
+ const result = this.audioStorageManager.saveAudio(id, Buffer.from(audioBuffer));
+ if (result.success) {
+ this.databaseManager.updateTranscriptionAudio(id, {
+ hasAudio: 1,
+ audioDurationMs: metadata?.durationMs || null,
+ provider: metadata?.provider || null,
+ model: metadata?.model || null,
+ });
+ }
+ return result;
+ });
+
+ ipcMain.handle("get-audio-path", async (event, id) => {
+ return this.audioStorageManager.getAudioPath(id);
+ });
+
+ ipcMain.handle("get-audio-buffer", async (event, id) => {
+ const buffer = this.audioStorageManager.getAudioBuffer(id);
+ return buffer ? buffer.buffer : null;
+ });
+
+ ipcMain.handle("delete-transcription-audio", async (event, id) => {
+ const result = this.audioStorageManager.deleteAudio(id);
+ if (result.success) {
+ this.databaseManager.updateTranscriptionAudio(id, {
+ hasAudio: 0,
+ audioDurationMs: null,
+ provider: null,
+ model: null,
+ });
+ }
+ return result;
+ });
+
+ ipcMain.handle("get-audio-storage-usage", async () => {
+ return this.audioStorageManager.getStorageUsage();
+ });
+
+ ipcMain.handle("delete-all-audio", async () => {
+ const result = this.audioStorageManager.deleteAllAudio();
+ try {
+ const rows = this.databaseManager.db
+ .prepare("SELECT id FROM transcriptions WHERE has_audio = 1")
+ .all();
+ if (rows.length > 0) {
+ this.databaseManager.clearAudioFlags(rows.map((r) => r.id));
+ }
+ } catch (error) {
+ debugLogger.error(
+ "Failed to clear audio flags after delete-all",
+ { error: error.message },
+ "audio-storage"
+ );
+ }
+ return result;
+ });
+
+ ipcMain.handle("retry-transcription", async (event, id) => {
+ const buffer = this.audioStorageManager.getAudioBuffer(id);
+ if (!buffer) return { success: false, error: "Audio file not found" };
+ try {
+ let result;
+ if (this.parakeetManager?.isReady?.()) {
+ result = await this.parakeetManager.transcribeLocalParakeet(buffer, {});
+ } else if (this.whisperManager?.serverManager?.isReady?.()) {
+ result = await this.whisperManager.transcribeLocalWhisper(buffer, {});
+ } else {
+ return { success: false, error: "No transcription engine available" };
+ }
+ if (result?.text) {
+ this.databaseManager.updateTranscriptionText(id, result.text, result.text);
+ const provider = result.source || "local";
+ const model = result.model || null;
+ this.databaseManager.updateTranscriptionAudio(id, {
+ hasAudio: 1,
+ audioDurationMs: null,
+ provider,
+ model,
+ });
+ const updated = this.databaseManager.getTranscriptionById(id);
+ return { success: true, transcription: updated };
+ }
+ return { success: false, error: "Transcription returned empty" };
+ } catch (error) {
+ debugLogger.error(
+ "Retry transcription failed",
+ { id, error: error.message },
+ "audio-storage"
+ );
+ return { success: false, error: error.message };
+ }
+ });
+
+ ipcMain.handle("get-transcription-by-id", async (event, id) => {
+ return this.databaseManager.getTranscriptionById(id);
+ });
+
// Dictionary handlers
ipcMain.on("auto-learn-changed", (_event, enabled) => {
this._autoLearnEnabled = !!enabled;
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 017ba6bc0..96645614f 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -117,7 +117,7 @@ export const useAudioRecording = (toast, options = {}) => {
"streaming"
);
- audioManagerRef.current.saveTranscription(result.text);
+ audioManagerRef.current.saveTranscription(result.text, result.text);
if (result.source === "openai" && getSettings().useLocalWhisper) {
toast({
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index 230576d8f..9cbb958c8 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -53,6 +53,7 @@ export interface ApiKeySettings {
export interface PrivacySettings {
cloudBackupEnabled: boolean;
telemetryEnabled: boolean;
+ audioRetentionDays: number;
}
export interface ThemeSettings {
@@ -225,6 +226,8 @@ function useSettingsInternal() {
setCloudBackupEnabled: store.setCloudBackupEnabled,
telemetryEnabled: store.telemetryEnabled,
setTelemetryEnabled: store.setTelemetryEnabled,
+ audioRetentionDays: store.audioRetentionDays,
+ setAudioRetentionDays: store.setAudioRetentionDays,
updateTranscriptionSettings: store.updateTranscriptionSettings,
updateReasoningSettings: store.updateReasoningSettings,
updateApiKeys: store.updateApiKeys,
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 96321112c..4bc7d1a04 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -222,7 +222,19 @@
"dateGroups": {
"today": "Today",
"yesterday": "Yesterday"
- }
+ },
+ "copyText": "Copy text",
+ "deleteItem": "Delete",
+ "viewRawTranscript": "View raw transcript",
+ "downloadAudio": "Download audio",
+ "retryTranscription": "Re-transcribe",
+ "retrying": "Re-transcribing...",
+ "retrySuccess": "Transcription updated",
+ "retryError": "Failed to re-transcribe",
+ "audioSaved": "Audio saved",
+ "audioNotFound": "Audio file not found or expired",
+ "noAiProcessing": "No AI processing was applied to this transcription",
+ "rawTranscript": "Raw Transcript"
},
"cloudMigration": {
"title": "Welcome to OpenWhispr Pro",
@@ -1162,7 +1174,17 @@
"description": "Control what data leaves your device. Everything is off by default.",
"title": "Privacy",
"usageAnalytics": "Usage analytics",
- "usageAnalyticsDescription": "Help us improve OpenWhispr by sharing anonymous performance metrics. We never send transcription content — only timing and error data."
+ "usageAnalyticsDescription": "Help us improve OpenWhispr by sharing anonymous performance metrics. We never send transcription content — only timing and error data.",
+ "audioRetention": "Audio Retention",
+ "audioRetentionDescription": "Store audio recordings locally for re-transcription and download. Files are automatically deleted after the retention period.",
+ "audioRetentionDisabled": "Disabled",
+ "audioRetentionDays": "{{count}} days",
+ "audioStorageUsage": "Storage Usage",
+ "audioStorageUsageDescription": "Audio files stored on this device",
+ "audioStorageFiles": "{{count}} files, {{size}}",
+ "audioStorageEmpty": "No audio files stored",
+ "clearAllAudio": "Clear All Audio",
+ "clearAllAudioConfirm": "Delete all stored audio files? This cannot be undone."
},
"prompts": {
"description": "View, customize, and test the unified system prompt that powers text cleanup and instruction detection",
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index 583487d2f..2a09e2827 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -60,6 +60,8 @@ const BOOLEAN_SETTINGS = new Set([
const ARRAY_SETTINGS = new Set(["customDictionary"]);
+const NUMERIC_SETTINGS = new Set(["audioRetentionDays"]);
+
const LANGUAGE_MIGRATIONS: Record<string, string> = { zh: "zh-CN" };
function migratePreferredLanguage() {
@@ -123,6 +125,7 @@ export interface SettingsState
setTheme: (value: "light" | "dark" | "auto") => void;
setCloudBackupEnabled: (value: boolean) => void;
setTelemetryEnabled: (value: boolean) => void;
+ setAudioRetentionDays: (days: number) => void;
setAudioCuesEnabled: (value: boolean) => void;
setFloatingIconAutoHide: (enabled: boolean) => void;
setIsSignedIn: (value: boolean) => void;
@@ -234,6 +237,13 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
})(),
cloudBackupEnabled: readBoolean("cloudBackupEnabled", false),
telemetryEnabled: readBoolean("telemetryEnabled", false),
+ audioRetentionDays: (() => {
+ if (!isBrowser) return 30;
+ const stored = localStorage.getItem("audioRetentionDays");
+ if (stored === null) return 30;
+ const parsed = parseInt(stored, 10);
+ return isNaN(parsed) ? 30 : parsed;
+ })(),
audioCuesEnabled: readBoolean("audioCuesEnabled", true),
floatingIconAutoHide: readBoolean("floatingIconAutoHide", false),
isSignedIn: readBoolean("isSignedIn", false),
@@ -358,6 +368,10 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({
setCloudBackupEnabled: createBooleanSetter("cloudBackupEnabled"),
setTelemetryEnabled: createBooleanSetter("telemetryEnabled"),
+ setAudioRetentionDays: (days: number) => {
+ if (isBrowser) localStorage.setItem("audioRetentionDays", String(days));
+ set({ audioRetentionDays: days });
+ },
setAudioCuesEnabled: createBooleanSetter("audioCuesEnabled"),
setFloatingIconAutoHide: (enabled: boolean) => {
@@ -601,6 +615,9 @@ export async function initializeSettings(): Promise<void> {
} catch {
value = [];
}
+ } else if (NUMERIC_SETTINGS.has(key)) {
+ const parsed = parseInt(newValue, 10);
+ value = isNaN(parsed) ? 30 : parsed;
} else {
value = newValue;
}
diff --git a/src/stores/transcriptionStore.ts b/src/stores/transcriptionStore.ts
index 5412afb33..11e401b6f 100644
--- a/src/stores/transcriptionStore.ts
+++ b/src/stores/transcriptionStore.ts
@@ -81,6 +81,13 @@ export function removeTranscription(id: number) {
useTranscriptionStore.setState({ transcriptions: next });
}
+export function updateTranscription(item: TranscriptionItem) {
+ if (!item) return;
+ const { transcriptions } = useTranscriptionStore.getState();
+ const next = transcriptions.map((existing) => (existing.id === item.id ? item : existing));
+ useTranscriptionStore.setState({ transcriptions: next });
+}
+
export function clearTranscriptions() {
if (useTranscriptionStore.getState().transcriptions.length === 0) return;
useTranscriptionStore.setState({ transcriptions: [] });
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 51dcba4df..ef666f735 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -3,8 +3,13 @@ export type LocalTranscriptionProvider = "whisper" | "nvidia";
export interface TranscriptionItem {
id: number;
text: string;
+ raw_text: string | null;
timestamp: string;
created_at: string;
+ has_audio: number;
+ audio_duration_ms: number | null;
+ provider: string | null;
+ model: string | null;
}
export interface NoteItem {
@@ -279,10 +284,29 @@ declare global {
} | null>;
// Database operations
- saveTranscription: (text: string) => Promise<{ id: number; success: boolean }>;
+ saveTranscription: (
+ text: string,
+ rawText?: string | null
+ ) => Promise<{ id: number; success: boolean; transcription?: TranscriptionItem }>;
getTranscriptions: (limit?: number) => Promise<TranscriptionItem[]>;
clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;
deleteTranscription: (id: number) => Promise<{ success: boolean }>;
+ getTranscriptionById: (id: number) => Promise<TranscriptionItem | null>;
+
+ // Audio retention operations
+ saveTranscriptionAudio: (
+ id: number,
+ audioBuffer: ArrayBuffer,
+ metadata?: { durationMs?: number; provider?: string; model?: string }
+ ) => Promise<{ success: boolean; path?: string }>;
+ getAudioPath: (id: number) => Promise<string | null>;
+ getAudioBuffer: (id: number) => Promise<ArrayBuffer | null>;
+ deleteTranscriptionAudio: (id: number) => Promise<{ success: boolean }>;
+ getAudioStorageUsage: () => Promise<{ fileCount: number; totalBytes: number }>;
+ deleteAllAudio: () => Promise<{ deleted: number }>;
+ retryTranscription: (
+ id: number
+ ) => Promise<{ success: boolean; transcription?: TranscriptionItem; error?: string }>;
// Dictionary operations
getDictionary: () => Promise<string[]>;