Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(history): preserve discarded dictations in transcription history (#964)
Alcahestafff1c7256b9
diff --git a/preload.js b/preload.jsindex efd2b9b33..e75e14ad0 100644--- a/preload.js+++ b/preload.js@@ -34,7 +34,8 @@ contextBridge.exposeInMainWorld("electronAPI", {// Database functionssaveTranscription: (text, rawText, options) =>ipcRenderer.invoke("db-save-transcription", text, rawText, options),- getTranscriptions: (limit) => ipcRenderer.invoke("db-get-transcriptions", limit),+ getTranscriptions: (limit, options) =>+ ipcRenderer.invoke("db-get-transcriptions", limit, options),clearTranscriptions: () => ipcRenderer.invoke("db-clear-transcriptions"),deleteTranscription: (id) => ipcRenderer.invoke("db-delete-transcription", id),diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex f06d028f3..cd81bff88 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -14,6 +14,7 @@ import { useAuth } from "../hooks/useAuth";import { useUsage } from "../hooks/useUsage";import {useTranscriptions,+ useShowDiscarded,initializeTranscriptions,removeTranscription as removeFromStore,updateTranscription as updateInStore,@@ -75,6 +76,7 @@ export default function ControlPanel() {const [showReferrals, setShowReferrals] = useState(false);const [invitationToken, setInvitationToken] = useState<string | null>(null);const [showSearch, setShowSearch] = useState(false);+ const showDiscarded = useShowDiscarded();const [showCloudMigrationBanner, setShowCloudMigrationBanner] = useState(false);const [activeView, setActiveView] = useState<ControlPanelView>("home");const isMeetingMode = useIsMeetingMode();@@ -130,11 +132,11 @@ export default function ControlPanel() {hideAlertDialog,} = useDialogs();- useEffect(() => {- (async () => {+ const loadTranscriptions = useCallback(+ async (includeDiscarded?: boolean) => {try {setIsLoading(true);- await initializeTranscriptions();+ await initializeTranscriptions(undefined, includeDiscarded);} catch {showAlertDialog({title: t("controlPanel.history.couldNotLoadTitle"),@@ -143,8 +145,13 @@ export default function ControlPanel() {} finally {setIsLoading(false);}- })();- }, [showAlertDialog, t]);+ },+ [showAlertDialog, t]+ );++ useEffect(() => {+ loadTranscriptions();+ }, [loadTranscriptions]);useEffect(() => {const { noteFilesEnabled, noteFilesPath } = useSettingsStore.getState();@@ -480,7 +487,7 @@ export default function ControlPanel() {);const retryTranscription = useCallback(- async (id: number) => {+ async (id: number, options?: { isRecover?: boolean }) => {try {const s = useSettingsStore.getState();const result = await window.electronAPI.retryTranscription(id, {@@ -535,7 +542,13 @@ export default function ControlPanel() {}updateInStore(finalTranscription);- toast({ title: t("controlPanel.history.retrySuccess") });+ toast({+ title: t(+ options?.isRecover+ ? "controlPanel.history.discarded.recovered"+ : "controlPanel.history.retrySuccess"+ ),+ });} else {toast({title: t("controlPanel.history.retryError"),@@ -553,6 +566,10 @@ export default function ControlPanel() {[toast, t, useCleanupModel]);+ const toggleShowDiscarded = useCallback(() => {+ loadTranscriptions(!showDiscarded);+ }, [loadTranscriptions, showDiscarded]);+const handleUpdateClick = async () => {if (updateStatus.updateDownloaded) {showConfirmDialog({@@ -875,6 +892,8 @@ export default function ControlPanel() {clearAllTranscriptions={clearAllTranscriptions}onShowAudioInFolder={showAudioInFolder}onRetryTranscription={retryTranscription}+ showDiscarded={showDiscarded}+ onToggleDiscarded={toggleShowDiscarded}onOpenSettings={(section) => {setSettingsSection(section);setShowSettings(true);diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsxindex a1b2f222f..d44d4591d 100644--- a/src/components/HistoryView.tsx+++ b/src/components/HistoryView.tsx@@ -1,7 +1,7 @@import { useMemo } from "react";import { useTranslation } from "react-i18next";import { Button } from "./ui/button";-import { Loader2, Sparkles, Cloud, X, Mic, Trash2 } from "lucide-react";+import { Loader2, Sparkles, Cloud, X, Mic, Trash2, Archive } from "lucide-react";import TranscriptionItem from "./ui/TranscriptionItem";import type { TranscriptionItem as TranscriptionItemType } from "../types/electron";import { formatHotkeyLabel } from "../utils/hotkeys";@@ -25,7 +25,9 @@ interface HistoryViewProps {clearAllTranscriptions: () => void;onOpenSettings: (section?: string) => void;onShowAudioInFolder: (id: number) => void;- onRetryTranscription: (id: number) => Promise<void>;+ onRetryTranscription: (id: number, options?: { isRecover?: boolean }) => Promise<void>;+ showDiscarded: boolean;+ onToggleDiscarded: () => void;}export default function HistoryView({@@ -43,6 +45,8 @@ export default function HistoryView({onOpenSettings,onShowAudioInFolder,onRetryTranscription,+ showDiscarded,+ onToggleDiscarded,}: HistoryViewProps) {const { t } = useTranslation();const dataRetentionEnabled = useSettingsStore((s) => s.dataRetentionEnabled);@@ -71,6 +75,19 @@ export default function HistoryView({return (<div className="px-4 pt-4 pb-6"><div className={cn("mx-auto", isConnected ? "max-w-5xl" : "max-w-3xl")}>+ <div className="mb-2 flex justify-end">+ <button+ onClick={onToggleDiscarded}+ className="flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground hover:text-foreground transition-colors"+ >+ <Archive size={12} />+ <span>+ {showDiscarded+ ? t("controlPanel.history.discarded.hide")+ : t("controlPanel.history.discarded.show")}+ </span>+ </button>+ </div>{showCloudMigrationBanner && (<div className="mb-3 relative rounded-lg border border-primary/20 bg-primary/5 dark:bg-primary/10 p-3"><buttondiff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex ff0504ae5..36c84d9af 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -751,6 +751,8 @@ export default function SettingsPage({setAudioRetentionDays,dataRetentionEnabled,setDataRetentionEnabled,+ saveDiscardedTranscriptions,+ setSaveDiscardedTranscriptions,customDictionary,setCustomDictionary,noteFilesEnabled,@@ -3532,6 +3534,18 @@ EOF`,<Toggle checked={dataRetentionEnabled} onChange={setDataRetentionEnabled} /></SettingsRow></SettingsPanelRow>+ <SettingsPanelRow>+ <SettingsRow+ label={t("settingsPage.privacy.saveDiscarded")}+ description={t("settingsPage.privacy.saveDiscardedDescription")}+ >+ <Toggle+ checked={saveDiscardedTranscriptions}+ disabled={!dataRetentionEnabled || audioRetentionDays === 0}+ onChange={setSaveDiscardedTranscriptions}+ />+ </SettingsRow>+ </SettingsPanelRow></SettingsPanel></div>diff --git a/src/components/notes/DictationWidget.tsx b/src/components/notes/DictationWidget.tsxindex 36fa43f66..2181a8d4f 100644--- a/src/components/notes/DictationWidget.tsx+++ b/src/components/notes/DictationWidget.tsx@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { Mic, Square, Loader2 } from "lucide-react";import { cn } from "../lib/utils";+import { formatMmSs } from "../../utils/formatDuration";interface DictationWidgetProps {isRecording: boolean;@@ -35,8 +36,7 @@ export default function DictationWidget({return () => clearInterval(id);}, [isRecording]);- const minutes = String(Math.floor(elapsed / 60)).padStart(2, "0");- const seconds = String(elapsed % 60).padStart(2, "0");+ const elapsedLabel = formatMmSs(elapsed);return (<div className="absolute bottom-5 left-0 right-0 z-10 flex justify-center pointer-events-none">@@ -78,7 +78,7 @@ export default function DictationWidget({animation: "fade-in-content 0.3s ease-out 0.25s both",}}>- {minutes}:{seconds}+ {elapsedLabel}</span><buttondiff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsxindex 62df0d1a0..ffddaebda 100644--- a/src/components/notes/NoteBottomBar.tsx+++ b/src/components/notes/NoteBottomBar.tsx@@ -2,6 +2,7 @@ import { useState, useRef, useCallback, useEffect } from "react";import { useTranslation } from "react-i18next";import { Mic, ArrowUp, Square, Loader2 } from "lucide-react";import { cn } from "../lib/utils";+import { formatMmSs } from "../../utils/formatDuration";const BAR_COUNT = 5;@@ -47,8 +48,7 @@ export default function NoteBottomBar({return () => clearInterval(id);}, [isRecording]);- const minutes = String(Math.floor(elapsed / 60)).padStart(2, "0");- const seconds = String(elapsed % 60).padStart(2, "0");+ const elapsedLabel = formatMmSs(elapsed);const hasText = inputText.trim().length > 0;@@ -129,7 +129,7 @@ export default function NoteBottomBar({))}</div><span className="text-[11px] font-medium tabular-nums text-primary/60 dark:text-primary/70">- {minutes}:{seconds}+ {elapsedLabel}</span><Square size={9} fill="currentColor" className="text-primary/50" /></button>diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsxindex bfaf78b8d..df8da9b24 100644--- a/src/components/ui/TranscriptionItem.tsx+++ b/src/components/ui/TranscriptionItem.tsx@@ -2,13 +2,23 @@ import { useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "./button";import { Tooltip } from "./tooltip";-import { Copy, Trash2, FileText, FolderOpen, RotateCcw, Loader2, AlertCircle } from "lucide-react";+import {+ Copy,+ Trash2,+ FileText,+ FolderOpen,+ RotateCcw,+ Loader2,+ AlertCircle,+ ArchiveRestore,+} from "lucide-react";import type {TranscriptionItem as TranscriptionItemType,TranscriptionErrorCode,} from "../../types/electron";import { cn } from "../lib/utils";import { getCachedPlatform } from "../../utils/platform";+import { formatMmSs } from "../../utils/formatDuration";const platform = getCachedPlatform();@@ -23,7 +33,7 @@ interface TranscriptionItemProps {onCopy: (text: string) => void;onDelete: (id: number) => void;onShowAudioInFolder?: (id: number) => void;- onRetryTranscription?: (id: number) => Promise<void>;+ onRetryTranscription?: (id: number, options?: { isRecover?: boolean }) => Promise<void>;onOpenSettings?: () => void;}@@ -53,13 +63,18 @@ export default function TranscriptionItem({if (isRetrying || !onRetryTranscription) return;setIsRetrying(true);try {- await onRetryTranscription(item.id);+ await onRetryTranscription(item.id, { isRecover: item.status === "discarded" });} finally {setIsRetrying(false);}};const isFailed = item.status === "failed";+ const isDiscarded = item.status === "discarded";+ const discardedDuration =+ item.audio_duration_ms && item.audio_duration_ms > 0+ ? formatMmSs(Math.round(item.audio_duration_ms / 1000))+ : null;const hasRawText = item.raw_text !== null;const hasAudio = item.has_audio === 1;const showUtilityGroup = hasRawText || hasAudio;@@ -78,7 +93,9 @@ export default function TranscriptionItem({"group rounded-md border px-3 py-2.5 transition-colors duration-150",isFailed? "border-destructive/30 bg-destructive/5 hover:bg-destructive/10"- : "border-border/40 dark:border-border-subtle/60 bg-card/50 dark:bg-surface-2/60 hover:bg-muted/30 dark:hover:bg-surface-2/80"+ : isDiscarded+ ? "border-border/30 bg-muted/20 hover:bg-muted/30 opacity-80"+ : "border-border/40 dark:border-border-subtle/60 bg-card/50 dark:bg-surface-2/60 hover:bg-muted/30 dark:hover:bg-surface-2/80")}onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}@@ -136,6 +153,19 @@ export default function TranscriptionItem({)}</div></div>+ ) : isDiscarded ? (+ <div className="flex-1 min-w-0 flex items-center gap-2">+ <span className="shrink-0 rounded-sm bg-muted px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ {t("controlPanel.history.discarded.badge")}+ </span>+ <span className="text-sm text-muted-foreground truncate">+ {discardedDuration+ ? t("controlPanel.history.discarded.recordingWithDuration", {+ duration: discardedDuration,+ })+ : t("controlPanel.history.discarded.recording")}+ </span>+ </div>) : (<p className="flex-1 min-w-0 text-foreground text-sm leading-[1.5] break-words">{item.text}@@ -145,9 +175,26 @@ export default function TranscriptionItem({<divclassName={cn("flex items-center gap-0.5 shrink-0 transition-opacity duration-150",- isFailed ? "opacity-100" : isHovered ? "opacity-100" : "opacity-0"+ isFailed || isDiscarded ? "opacity-100" : isHovered ? "opacity-100" : "opacity-0")}>+ {isDiscarded && hasAudio && (+ <Tooltip content={t("controlPanel.history.discarded.recover")}>+ <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" />+ ) : (+ <ArchiveRestore size={12} />+ )}+ </Button>+ </Tooltip>+ )}{isFailed && hasAudio && (<Tooltip content={t("controlPanel.history.retryTranscription")}><Button@@ -165,7 +212,7 @@ export default function TranscriptionItem({</Button></Tooltip>)}- {!isFailed && hasRawText && (+ {!isFailed && !isDiscarded && hasRawText && (<Tooltip content={t("controlPanel.history.viewRawTranscript")}><Buttonsize="icon"@@ -192,7 +239,7 @@ export default function TranscriptionItem({</Button></Tooltip>)}- {!isFailed && hasAudio && (+ {!isFailed && !isDiscarded && hasAudio && (<Tooltip content={t("controlPanel.history.retryTranscription")}><Buttonsize="icon"@@ -210,7 +257,7 @@ export default function TranscriptionItem({</Tooltip>)}{showUtilityGroup && <div className="w-px h-3 bg-border/30" />}- {!isFailed && (+ {!isFailed && !isDiscarded && (<Tooltip content={t("controlPanel.history.copyText")}><Buttonsize="icon"@@ -235,7 +282,7 @@ export default function TranscriptionItem({</div></div>- {!isFailed && (+ {!isFailed && !isDiscarded && (<divclassName={cn("overflow-hidden transition-all duration-200",diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 48977d5ec..03d1c0c07 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -11,6 +11,7 @@ import {recordLocalSpeechWindow,} from "./localSpeechGate";import { reacquireIfDead } from "./micTrackHealth";+import { shouldSaveDiscardedRecording } from "./discardedRecording";import { getSettings, getEffectiveCleanupModel, isCloudCleanupMode } from "../stores/settingsStore";import { shouldSkipTranscriptionApiKey } from "./transcriptionAuth";import { detectAgentName } from "../config/agentDetection";@@ -543,12 +544,28 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);cancelRecording() {if (this.mediaRecorder && this.mediaRecorder.state === "recording") {this.mediaRecorder.onstop = () => {+ const durationSeconds = this.recordingStartTime+ ? (Date.now() - this.recordingStartTime) / 1000+ : null;+ const shouldSave =+ shouldSaveDiscardedRecording(getSettings(), durationSeconds) &&+ this.audioChunks.length > 0;+ const blob = shouldSave+ ? new Blob(this.audioChunks, { type: this.recordingMimeType })+ : null;+this.cleanupPreview({ dismiss: true });this.isRecording = false;this.isProcessing = false;this.audioChunks = [];this.recordingStartTime = null;this.onStateChange?.({ isRecording: false, isProcessing: false });++ if (blob) {+ this.saveDiscardedTranscription(blob, durationSeconds).catch((err) => {+ logger.warn("Failed to save discarded transcription", { error: err.message }, "audio");+ });+ }};this.mediaRecorder.stop();@@ -2211,6 +2228,48 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}}+ async saveDiscardedTranscription(blob, durationSeconds) {+ let savedId = null;+ try {+ const result = await window.electronAPI.saveTranscription("", null, {+ status: "discarded",+ });+ if (!result?.id) return;+ savedId = result.id;++ if (blob) {+ const durationMs = durationSeconds ? Math.round(durationSeconds * 1000) : null;+ const arrayBuffer = await blob.arrayBuffer();+ await window.electronAPI.saveTranscriptionAudio(savedId, arrayBuffer, {+ durationMs,+ provider: null,+ model: null,+ });+ }++ syncService.debouncedPush("transcription", savedId);+ } catch (error) {+ logger.error(+ "Failed to save discarded transcription record",+ { error: error.message },+ "audio"+ );+ // A discarded row is only recoverable through its audio; if the audio save+ // failed, drop the dead row instead of leaving an empty unrecoverable entry. See #907.+ if (savedId != null) {+ try {+ await window.electronAPI.deleteTranscription(savedId);+ } catch (cleanupError) {+ logger.warn(+ "Failed to clean up discarded row after audio save failure",+ { error: cleanupError.message },+ "audio"+ );+ }+ }+ }+ }+getState() {return {isRecording: this.isRecording,diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 90c8c76bc..1b2f05eab 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -640,13 +640,14 @@ class DatabaseManager {}}- getTranscriptions(limit = 50) {+ getTranscriptions(limit = 50, { includeDiscarded = false } = {}) {try {if (!this.db) {throw new Error("Database not initialized");}+ const statusFilter = includeDiscarded ? "" : " AND status != 'discarded'";const stmt = this.db.prepare(- "SELECT * FROM transcriptions WHERE deleted_at IS NULL ORDER BY timestamp DESC LIMIT ?"+ `SELECT * FROM transcriptions WHERE deleted_at IS NULL${statusFilter} ORDER BY timestamp DESC LIMIT ?`);const transcriptions = stmt.all(limit);return transcriptions;diff --git a/src/helpers/discardedRecording.js b/src/helpers/discardedRecording.jsnew file mode 100644index 000000000..0d83c76a8--- /dev/null+++ b/src/helpers/discardedRecording.js@@ -0,0 +1,12 @@+// Minimum recording length (seconds) worth preserving as a discarded record.+// Avoids saving accidental sub-second Escape taps. See #907.+export const MIN_DISCARDED_DURATION_SECONDS = 1;++export function shouldSaveDiscardedRecording(settings, durationSeconds) {+ if (!settings) return false;+ if (!settings.saveDiscardedTranscriptions) return false;+ if (!settings.dataRetentionEnabled) return false;+ if (!(settings.audioRetentionDays > 0)) return false;+ if (!(durationSeconds >= MIN_DISCARDED_DURATION_SECONDS)) return false;+ return true;+}diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 97cb23397..392d9dc54 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -804,8 +804,8 @@ class IPCHandlers {return result;});- ipcMain.handle("db-get-transcriptions", async (event, limit = 50) => {- return this.databaseManager.getTranscriptions(limit);+ ipcMain.handle("db-get-transcriptions", async (event, limit = 50, options = {}) => {+ return this.databaseManager.getTranscriptions(limit, options);});ipcMain.handle("db-clear-transcriptions", async (event) => {@@ -3891,9 +3891,10 @@ class IPCHandlers {this.databaseManager.updateTranscriptionStatus(id, "completed");const providerName = result.source || "local";const modelName = result.model || null;+ const existingRow = this.databaseManager.getTranscriptionById(id);this.databaseManager.updateTranscriptionAudio(id, {hasAudio: 1,- audioDurationMs: null,+ audioDurationMs: existingRow?.audio_duration_ms ?? null,provider: providerName,model: modelName,});diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.tsindex 07f091300..93ddee5de 100644--- a/src/hooks/useSettings.ts+++ b/src/hooks/useSettings.ts@@ -71,6 +71,7 @@ export interface PrivacySettings {telemetryEnabled: boolean;audioRetentionDays: number;dataRetentionEnabled: boolean;+ saveDiscardedTranscriptions: boolean;}export interface ThemeSettings {@@ -332,6 +333,8 @@ function useSettingsInternal() {setAudioRetentionDays: store.setAudioRetentionDays,dataRetentionEnabled: store.dataRetentionEnabled,setDataRetentionEnabled: store.setDataRetentionEnabled,+ saveDiscardedTranscriptions: store.saveDiscardedTranscriptions,+ setSaveDiscardedTranscriptions: store.setSaveDiscardedTranscriptions,updateTranscriptionSettings: store.updateTranscriptionSettings,updateCleanupSettings: store.updateCleanupSettings,updateApiKeys: store.updateApiKeys,diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex d7df3192d..55a65136d 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -320,7 +320,16 @@"retryError": "Erneute Transkription fehlgeschlagen","audioNotFound": "Audiodatei nicht gefunden oder abgelaufen","noAiProcessing": "Auf diese Transkription wurde keine KI-Verarbeitung angewendet",- "rawTranscript": "Rohtranskript"+ "rawTranscript": "Rohtranskript",+ "discarded": {+ "show": "Verworfene anzeigen",+ "hide": "Verworfene ausblenden",+ "badge": "Verworfen",+ "recording": "Verworfene Aufnahme",+ "recordingWithDuration": "Verworfene Aufnahme · {{duration}}",+ "recover": "Wiederherstellen",+ "recovered": "Wiederhergestellt"+ }},"cloudMigration": {"title": "Willkommen bei OpenWhispr Cloud",@@ -1524,7 +1533,9 @@"audioStorageFiles": "{{count}} Dateien, {{size}}","audioStorageEmpty": "Keine Audiodateien gespeichert","clearAllAudio": "Alle Audiodateien löschen",- "clearAllAudioConfirm": "Alle gespeicherten Audiodateien löschen? Dies kann nicht rückgängig gemacht werden."+ "clearAllAudioConfirm": "Alle gespeicherten Audiodateien löschen? Dies kann nicht rückgängig gemacht werden.",+ "saveDiscarded": "Verworfene Diktate speichern",+ "saveDiscardedDescription": "Wenn Sie ein Diktat mit Escape abbrechen, bleibt das Audio im Verlauf, damit Sie es wiederherstellen können. Erfordert aktive Daten- und Audio-Aufbewahrung."},"prompts": {"description": "Den einheitlichen System-Prompt anzeigen, anpassen und testen, der Textbereinigung und Anweisungserkennung steuert",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 2a3cbd8d1..06f20ae19 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -320,7 +320,16 @@"clearAllDescription": "All transcriptions and audio files will be permanently removed.","clearAllSuccess": "History cleared","clearAllErrorTitle": "Couldn't clear history",- "clearAllErrorDescription": "Something went wrong. Please try again."+ "clearAllErrorDescription": "Something went wrong. Please try again.",+ "discarded": {+ "show": "Show discarded",+ "hide": "Hide discarded",+ "badge": "Discarded",+ "recording": "Discarded recording",+ "recordingWithDuration": "Discarded recording · {{duration}}",+ "recover": "Recover",+ "recovered": "Recovered"+ }},"cloudMigration": {"title": "Welcome to OpenWhispr Cloud",@@ -1708,7 +1717,9 @@"hoursAgo": "{{count}}h ago","justNow": "just now","lastSynced": "Last synced {{time}}",- "minutesAgo": "{{count}}m ago"+ "minutesAgo": "{{count}}m ago",+ "saveDiscarded": "Save discarded dictations",+ "saveDiscardedDescription": "When you cancel a dictation with Escape, keep its audio in history so you can recover it. Requires data and audio retention to be on."},"prompts": {"description": "View, customize, and test the unified system prompt that powers text cleanup and instruction detection",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 962862392..43859a61a 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -279,6 +279,15 @@"history": {"couldNotLoadTitle": "No se pudo cargar tu historial","couldNotLoadDescription": "Ocurrió un problema al cargar tus transcripciones. Cierra y abre la app de nuevo.",+ "discarded": {+ "show": "Mostrar descartadas",+ "hide": "Ocultar descartadas",+ "badge": "Descartada",+ "recording": "Grabación descartada",+ "recordingWithDuration": "Grabación descartada · {{duration}}",+ "recover": "Recuperar",+ "recovered": "Recuperada"+ },"copiedTitle": "¡Copiado!","copiedDescription": "Texto copiado al portapapeles","couldNotCopyTitle": "No se pudo copiar",@@ -1565,6 +1574,8 @@"minutesAgo": "hace {{count}}m","audioRetention": "Retención de audio","audioRetentionDescription": "Almacena grabaciones de audio localmente para volver a transcribir y descargar. Los archivos se eliminan automáticamente tras el periodo de retención.",+ "saveDiscarded": "Guardar dictados descartados",+ "saveDiscardedDescription": "Cuando cancelas un dictado con Escape, conserva su audio en el historial para poder recuperarlo. Requiere tener activadas la retención de datos y de audio.","audioRetentionDisabled": "Desactivado","audioRetentionDays": "{{count}} días","audioStorageUsage": "Uso de almacenamiento",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex eab4f300e..f3bbbd7bf 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -320,7 +320,16 @@"retryError": "Échec de la retranscription","audioNotFound": "Fichier audio introuvable ou expiré","noAiProcessing": "Aucun traitement IA n'a été appliqué à cette transcription",- "rawTranscript": "Transcription brute"+ "rawTranscript": "Transcription brute",+ "discarded": {+ "show": "Afficher les abandonnées",+ "hide": "Masquer les abandonnées",+ "badge": "Abandonnée",+ "recording": "Enregistrement abandonné",+ "recordingWithDuration": "Enregistrement abandonné · {{duration}}",+ "recover": "Récupérer",+ "recovered": "Récupérée"+ }},"cloudMigration": {"title": "Bienvenue sur OpenWhispr Cloud",@@ -1572,7 +1581,9 @@"audioStorageFiles": "{{count}} fichiers, {{size}}","audioStorageEmpty": "Aucun fichier audio stocké","clearAllAudio": "Supprimer tous les fichiers audio",- "clearAllAudioConfirm": "Supprimer tous les fichiers audio stockés ? Cette action est irréversible."+ "clearAllAudioConfirm": "Supprimer tous les fichiers audio stockés ? Cette action est irréversible.",+ "saveDiscarded": "Enregistrer les dictées abandonnées",+ "saveDiscardedDescription": "Quand vous annulez une dictée avec Échap, conserve son audio dans l'historique pour pouvoir la récupérer. Nécessite la conservation des données et de l'audio."},"prompts": {"description": "Affichez, personnalisez et testez le prompt système unifié qui gère la correction du texte et la détection des instructions",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex f5910b03b..1a3eb8db5 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -320,7 +320,16 @@"retryError": "Ritrascrizione non riuscita","audioNotFound": "File audio non trovato o scaduto","noAiProcessing": "Nessuna elaborazione IA applicata a questa trascrizione",- "rawTranscript": "Trascrizione grezza"+ "rawTranscript": "Trascrizione grezza",+ "discarded": {+ "show": "Mostra scartate",+ "hide": "Nascondi scartate",+ "badge": "Scartata",+ "recording": "Registrazione scartata",+ "recordingWithDuration": "Registrazione scartata · {{duration}}",+ "recover": "Recupera",+ "recovered": "Recuperata"+ }},"cloudMigration": {"title": "Benvenuto in OpenWhispr Cloud",@@ -1524,7 +1533,9 @@"audioStorageFiles": "{{count}} file, {{size}}","audioStorageEmpty": "Nessun file audio salvato","clearAllAudio": "Elimina tutti i file audio",- "clearAllAudioConfirm": "Eliminare tutti i file audio salvati? Questa azione è irreversibile."+ "clearAllAudioConfirm": "Eliminare tutti i file audio salvati? Questa azione è irreversibile.",+ "saveDiscarded": "Salva le dettature scartate",+ "saveDiscardedDescription": "Quando annulli una dettatura con Escape, conserva l'audio nella cronologia per poterla recuperare. Richiede la conservazione di dati e audio attiva."},"prompts": {"description": "Visualizza, personalizza e testa il prompt di sistema unificato che gestisce la correzione del testo e il rilevamento delle istruzioni",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 31ee5ad4f..7fbfb98b6 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -320,7 +320,16 @@"retryError": "再文字起こしに失敗しました","audioNotFound": "音声ファイルが見つからないか有効期限切れです","noAiProcessing": "この文字起こしにはAI処理が適用されていません",- "rawTranscript": "生の文字起こし"+ "rawTranscript": "生の文字起こし",+ "discarded": {+ "show": "破棄したものを表示",+ "hide": "破棄したものを非表示",+ "badge": "破棄済み",+ "recording": "破棄した録音",+ "recordingWithDuration": "破棄した録音 · {{duration}}",+ "recover": "復元",+ "recovered": "復元しました"+ }},"cloudMigration": {"title": "OpenWhispr Cloud へようこそ",@@ -1524,7 +1533,9 @@"audioStorageFiles": "{{count}}ファイル、{{size}}","audioStorageEmpty": "保存された音声ファイルはありません","clearAllAudio": "すべての音声を削除",- "clearAllAudioConfirm": "保存されたすべての音声ファイルを削除しますか?この操作は元に戻せません。"+ "clearAllAudioConfirm": "保存されたすべての音声ファイルを削除しますか?この操作は元に戻せません。",+ "saveDiscarded": "破棄したディクテーションを保存",+ "saveDiscardedDescription": "Escape でディクテーションをキャンセルしたとき、音声を履歴に残して後で復元できるようにします。データと音声の保持を有効にする必要があります。"},"prompts": {"description": "テキスト補正と指示検出を行う統合システムプロンプトの表示、カスタマイズ、テスト",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 80de33a49..c66c9eac1 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -292,7 +292,16 @@"retryError": "Falha ao retranscrever","audioNotFound": "Arquivo de áudio não encontrado ou expirado","noAiProcessing": "Nenhum processamento de IA foi aplicado a esta transcrição",- "rawTranscript": "Transcrição bruta"+ "rawTranscript": "Transcrição bruta",+ "discarded": {+ "show": "Mostrar descartadas",+ "hide": "Ocultar descartadas",+ "badge": "Descartada",+ "recording": "Gravação descartada",+ "recordingWithDuration": "Gravação descartada · {{duration}}",+ "recover": "Recuperar",+ "recovered": "Recuperada"+ }},"cloudMigration": {"title": "Boas-vindas ao OpenWhispr Cloud",@@ -1496,7 +1505,9 @@"audioStorageFiles": "{{count}} arquivos, {{size}}","audioStorageEmpty": "Nenhum arquivo de áudio armazenado","clearAllAudio": "Excluir todos os áudios",- "clearAllAudioConfirm": "Excluir todos os arquivos de áudio armazenados? Esta ação não pode ser desfeita."+ "clearAllAudioConfirm": "Excluir todos os arquivos de áudio armazenados? Esta ação não pode ser desfeita.",+ "saveDiscarded": "Salvar ditados descartados",+ "saveDiscardedDescription": "Quando você cancela um ditado com Escape, mantém o áudio no histórico para poder recuperá-lo. Requer a retenção de dados e áudio ativada."},"prompts": {"description": "Visualize, personalize e teste o prompt de sistema unificado que alimenta a limpeza de texto e a detecção de instruções",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 75ab7e23e..624e1e913 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -320,7 +320,16 @@"retryError": "Не удалось повторить расшифровку","audioNotFound": "Аудиофайл не найден или истёк срок хранения","noAiProcessing": "К этой расшифровке не применялась обработка ИИ",- "rawTranscript": "Исходная расшифровка"+ "rawTranscript": "Исходная расшифровка",+ "discarded": {+ "show": "Показать отменённые",+ "hide": "Скрыть отменённые",+ "badge": "Отменено",+ "recording": "Отменённая запись",+ "recordingWithDuration": "Отменённая запись · {{duration}}",+ "recover": "Восстановить",+ "recovered": "Восстановлено"+ }},"cloudMigration": {"title": "Добро пожаловать в OpenWhispr Cloud",@@ -1524,7 +1533,9 @@"audioStorageFiles": "{{count}} файлов, {{size}}","audioStorageEmpty": "Аудиофайлы отсутствуют","clearAllAudio": "Удалить все аудиофайлы",- "clearAllAudioConfirm": "Удалить все сохранённые аудиофайлы? Это действие нельзя отменить."+ "clearAllAudioConfirm": "Удалить все сохранённые аудиофайлы? Это действие нельзя отменить.",+ "saveDiscarded": "Сохранять отменённые диктовки",+ "saveDiscardedDescription": "При отмене диктовки клавишей Escape сохраняйте её аудио в истории, чтобы можно было восстановить. Требует включённого хранения данных и аудио."},"prompts": {"description": "Просматривайте, настраивайте и тестируйте единый системный промпт, который управляет очисткой текста и обнаружением инструкций",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 8b73fdc32..ecf8a431f 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -320,7 +320,16 @@"retryError": "重新转录失败","audioNotFound": "音频文件未找到或已过期","noAiProcessing": "此转录未应用 AI 处理",- "rawTranscript": "原始转录"+ "rawTranscript": "原始转录",+ "discarded": {+ "show": "显示已放弃",+ "hide": "隐藏已放弃",+ "badge": "已放弃",+ "recording": "已放弃的录音",+ "recordingWithDuration": "已放弃的录音 · {{duration}}",+ "recover": "恢复",+ "recovered": "已恢复"+ }},"cloudMigration": {"title": "欢迎使用 OpenWhispr 云端",@@ -1519,7 +1528,9 @@"audioStorageFiles": "{{count}} 个文件,{{size}}","audioStorageEmpty": "没有存储的音频文件","clearAllAudio": "清除所有音频",- "clearAllAudioConfirm": "删除所有已存储的音频文件?此操作无法撤销。"+ "clearAllAudioConfirm": "删除所有已存储的音频文件?此操作无法撤销。",+ "saveDiscarded": "保存已放弃的听写",+ "saveDiscardedDescription": "用 Escape 取消听写时,将其音频保留在历史记录中以便恢复。需开启数据和音频保留。"},"prompts": {"description": "查看、自定义和测试用于文本整理和指令识别的统一系统提示词",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex ecd4886bf..9925ad97e 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -320,7 +320,16 @@"retryError": "重新轉錄失敗","audioNotFound": "找不到音訊檔案或檔案已過期","noAiProcessing": "此轉錄未套用 AI 處理",- "rawTranscript": "原始轉錄"+ "rawTranscript": "原始轉錄",+ "discarded": {+ "show": "顯示已捨棄",+ "hide": "隱藏已捨棄",+ "badge": "已捨棄",+ "recording": "已捨棄的錄音",+ "recordingWithDuration": "已捨棄的錄音 · {{duration}}",+ "recover": "復原",+ "recovered": "已復原"+ }},"cloudMigration": {"title": "歡迎使用 OpenWhispr Cloud",@@ -1519,7 +1528,9 @@"audioStorageFiles": "{{count}} 個檔案,{{size}}","audioStorageEmpty": "沒有已儲存的音訊檔案","clearAllAudio": "清除所有音訊",- "clearAllAudioConfirm": "刪除所有已儲存的音訊檔案?此操作無法復原。"+ "clearAllAudioConfirm": "刪除所有已儲存的音訊檔案?此操作無法復原。",+ "saveDiscarded": "儲存已捨棄的聽寫",+ "saveDiscardedDescription": "當你以 Escape 取消聽寫時,將其音訊保留在歷史記錄中以便復原。需要開啟資料與音訊保留。"},"prompts": {"description": "檢視、自訂和測試用於文字整理和指令偵測的統一系統提示詞",diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 1ad6289ac..7cafe787e 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -127,6 +127,7 @@ const BOOLEAN_SETTINGS = new Set(["autoPasteEnabled","keepTranscriptionInClipboard","dataRetentionEnabled",+ "saveDiscardedTranscriptions","noteFilesEnabled","showTranscriptionPreview","cleanupDisableThinking",@@ -552,6 +553,7 @@ export interface SettingsStatesetTelemetryEnabled: (value: boolean) => void;setAudioRetentionDays: (days: number) => void;setDataRetentionEnabled: (value: boolean) => void;+ setSaveDiscardedTranscriptions: (value: boolean) => void;setAudioCuesEnabled: (value: boolean) => void;setPauseMediaOnDictation: (value: boolean) => void;setFloatingIconAutoHide: (enabled: boolean) => void;@@ -854,6 +856,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({return isNaN(parsed) ? 30 : parsed;})(),dataRetentionEnabled: readBoolean("dataRetentionEnabled", true),+ saveDiscardedTranscriptions: readBoolean("saveDiscardedTranscriptions", false),audioCuesEnabled: readBoolean("audioCuesEnabled", true),pauseMediaOnDictation: readBoolean("pauseMediaOnDictation", false),floatingIconAutoHide: readBoolean("floatingIconAutoHide", false),@@ -1337,6 +1340,7 @@ export const useSettingsStore = create<SettingsState>()((set, get) => ({"settings");},+ setSaveDiscardedTranscriptions: createBooleanSetter("saveDiscardedTranscriptions"),setAudioCuesEnabled: createBooleanSetter("audioCuesEnabled"),setPauseMediaOnDictation: createBooleanSetter("pauseMediaOnDictation"),diff --git a/src/stores/transcriptionStore.ts b/src/stores/transcriptionStore.tsindex 258eb4132..c5d12a61d 100644--- a/src/stores/transcriptionStore.ts+++ b/src/stores/transcriptionStore.ts@@ -3,10 +3,12 @@ import type { TranscriptionItem } from "../types/electron";interface TranscriptionState {transcriptions: TranscriptionItem[];+ includeDiscarded: boolean;}const useTranscriptionStore = create<TranscriptionState>()(() => ({transcriptions: [],+ includeDiscarded: false,}));let hasBoundIpcListeners = false;@@ -67,16 +69,20 @@ function ensureIpcListeners() {});}-export async function initializeTranscriptions(limit = DEFAULT_LIMIT) {+export async function initializeTranscriptions(+ limit = currentLimit,+ includeDiscarded = useTranscriptionStore.getState().includeDiscarded+) {currentLimit = limit;ensureIpcListeners();- const items = await window.electronAPI.getTranscriptions(limit);- useTranscriptionStore.setState({ transcriptions: items });+ const items = await window.electronAPI.getTranscriptions(limit, { includeDiscarded });+ useTranscriptionStore.setState({ transcriptions: items, includeDiscarded });return items;}export function addTranscription(item: TranscriptionItem) {if (!item) return;+ if (item.status === "discarded" && !useTranscriptionStore.getState().includeDiscarded) return;const { transcriptions } = useTranscriptionStore.getState();const withoutDuplicate = transcriptions.filter((existing) => existing.id !== item.id);useTranscriptionStore.setState({@@ -107,3 +113,7 @@ export function clearTranscriptions() {export function useTranscriptions() {return useTranscriptionStore((state) => state.transcriptions);}++export function useShowDiscarded() {+ return useTranscriptionStore((state) => state.includeDiscarded);+}diff --git a/src/types/electron.ts b/src/types/electron.tsindex f75452fdb..c950835c3 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -4,7 +4,7 @@ export type InferenceMode = "openwhispr" | "providers" | "local" | "self-hosted"export type SelfHostedType = "openai-compatible" | "lan";-export type TranscriptionStatus = "completed" | "failed" | "pending";+export type TranscriptionStatus = "completed" | "failed" | "pending" | "discarded";export type TranscriptionErrorCode =| "TIMEOUT"@@ -518,7 +518,10 @@ declare global {clientTranscriptionId?: string;}) => Promise<{ id: number; success: boolean; transcription?: TranscriptionItem }>;- getTranscriptions: (limit?: number) => Promise<TranscriptionItem[]>;+ getTranscriptions: (+ limit?: number,+ options?: { includeDiscarded?: boolean }+ ) => Promise<TranscriptionItem[]>;clearTranscriptions: () => Promise<{ cleared: number; success: boolean }>;deleteTranscription: (id: number) => Promise<{ success: boolean }>;getTranscriptionById: (id: number) => Promise<TranscriptionItem | null>;diff --git a/src/utils/formatDuration.ts b/src/utils/formatDuration.tsnew file mode 100644index 000000000..0611b66ba--- /dev/null+++ b/src/utils/formatDuration.ts@@ -0,0 +1,6 @@+export function formatMmSs(totalSeconds: number): string {+ const whole = Math.floor(totalSeconds);+ const minutes = Math.floor(whole / 60);+ const seconds = whole % 60;+ return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;+}diff --git a/test/helpers/discardedRecording.test.js b/test/helpers/discardedRecording.test.jsnew file mode 100644index 000000000..3815c71e9--- /dev/null+++ b/test/helpers/discardedRecording.test.js@@ -0,0 +1,40 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const load = () => import("../../src/helpers/discardedRecording.js");++const base = {+ saveDiscardedTranscriptions: true,+ dataRetentionEnabled: true,+ audioRetentionDays: 30,+};++test("saves when all gates pass and duration >= threshold", async () => {+ const { shouldSaveDiscardedRecording, MIN_DISCARDED_DURATION_SECONDS } = await load();+ assert.equal(shouldSaveDiscardedRecording(base, 3), true);+ assert.equal(shouldSaveDiscardedRecording(base, MIN_DISCARDED_DURATION_SECONDS), true);+});++test("does not save below the minimum duration", async () => {+ const { shouldSaveDiscardedRecording } = await load();+ assert.equal(shouldSaveDiscardedRecording(base, 0.5), false);+ assert.equal(shouldSaveDiscardedRecording(base, 0), false);+ assert.equal(shouldSaveDiscardedRecording(base, null), false);+ assert.equal(shouldSaveDiscardedRecording(base, NaN), false);+});++test("respects each gate", async () => {+ const { shouldSaveDiscardedRecording } = await load();+ assert.equal(+ shouldSaveDiscardedRecording({ ...base, saveDiscardedTranscriptions: false }, 3),+ false+ );+ assert.equal(shouldSaveDiscardedRecording({ ...base, dataRetentionEnabled: false }, 3), false);+ assert.equal(shouldSaveDiscardedRecording({ ...base, audioRetentionDays: 0 }, 3), false);+});++test("handles missing settings", async () => {+ const { shouldSaveDiscardedRecording } = await load();+ assert.equal(shouldSaveDiscardedRecording(null, 3), false);+ assert.equal(shouldSaveDiscardedRecording(undefined, 3), false);+});