Skip to content

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

feat(privacy): add 1-day retention and enforce the configured periods (#1368)

Gabriel Steinb975ad17daa0
diff --git a/preload.js b/preload.js
index ea4bb161d..0b7f6a560 100644
--- a/preload.js
+++ b/preload.js
@@ -71,6 +71,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
deleteTranscriptionAudio: (id) => ipcRenderer.invoke("delete-transcription-audio", id),
getAudioStorageUsage: () => ipcRenderer.invoke("get-audio-storage-usage"),
deleteAllAudio: () => ipcRenderer.invoke("delete-all-audio"),
+ syncRetentionSettings: (settings) => ipcRenderer.send("retention-settings-changed", settings),
retryTranscription: (id, settings) => ipcRenderer.invoke("retry-transcription", id, settings),
updateTranscriptionText: (id, text, rawText) =>
ipcRenderer.invoke("update-transcription-text", id, text, rawText),
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index 5fca6f0d1..46e7663a6 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -139,6 +139,11 @@ const UI_LANGUAGE_OPTIONS: import("./ui/LanguageSelector").LanguageOption[] = [
{ value: "zh-TW", label: "繁體中文", flag: "🇹🇼" },
];
+const RETENTION_DAY_OPTIONS = [1, 7, 14, 30, 60, 90];
+
+const RETENTION_SELECT_CLASS =
+ "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 disabled:cursor-not-allowed disabled:opacity-50 transition-colors duration-200";
+
const noop = () => {};
function SettingsPanel({
@@ -779,6 +784,8 @@ export default function SettingsPage({
setTelemetryEnabled,
audioRetentionDays,
setAudioRetentionDays,
+ transcriptRetentionDays,
+ setTranscriptRetentionDays,
dataRetentionEnabled,
setDataRetentionEnabled,
saveDiscardedTranscriptions,
@@ -3548,24 +3555,14 @@ EOF`,
<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"
+ className={RETENTION_SELECT_CLASS}
>
<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>
+ {RETENTION_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {t("settingsPage.privacy.retentionDays", { count: days })}
+ </option>
+ ))}
</select>
</SettingsRow>
</SettingsPanelRow>
@@ -3606,6 +3603,28 @@ EOF`,
<Toggle checked={dataRetentionEnabled} onChange={setDataRetentionEnabled} />
</SettingsRow>
</SettingsPanelRow>
+ <SettingsPanelRow>
+ <SettingsRow
+ label={t("settingsPage.privacy.transcriptRetention")}
+ description={t("settingsPage.privacy.transcriptRetentionDescription")}
+ >
+ <select
+ value={transcriptRetentionDays}
+ disabled={!dataRetentionEnabled}
+ onChange={(e) => setTranscriptRetentionDays(parseInt(e.target.value, 10))}
+ className={RETENTION_SELECT_CLASS}
+ >
+ <option value={0}>
+ {t("settingsPage.privacy.transcriptRetentionForever")}
+ </option>
+ {RETENTION_DAY_OPTIONS.map((days) => (
+ <option key={days} value={days}>
+ {t("settingsPage.privacy.retentionDays", { count: days })}
+ </option>
+ ))}
+ </select>
+ </SettingsRow>
+ </SettingsPanelRow>
<SettingsPanelRow>
<SettingsRow
label={t("settingsPage.privacy.saveDiscarded")}
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 38cf9e640..237ad42e4 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -747,6 +747,44 @@ class DatabaseManager {
}
}
+ /** Purges transcriptions older than the retention window. Returns the affected ids so
+ * callers can drop the matching audio files. */
+ deleteTranscriptionsExpiredBefore(retentionDays) {
+ try {
+ if (!this.db) {
+ throw new Error("Database not initialized");
+ }
+ // Resolve the cutoff once so the ids we report are exactly the rows we purge.
+ const cutoff = this.db
+ .prepare("SELECT datetime('now', ?) AS cutoff")
+ .get(`-${retentionDays} days`).cutoff;
+ const expired = this.db
+ .prepare("SELECT id FROM transcriptions WHERE deleted_at IS NULL AND created_at < ?")
+ .all(cutoff)
+ .map((row) => row.id);
+ if (expired.length === 0) return { ids: [] };
+
+ const tombstone = this.db.prepare(
+ "UPDATE transcriptions SET deleted_at = datetime('now'), sync_status = 'pending' WHERE cloud_id IS NOT NULL AND deleted_at IS NULL AND created_at < ?"
+ );
+ const hardDelete = this.db.prepare(
+ "DELETE FROM transcriptions WHERE cloud_id IS NULL AND created_at < ?"
+ );
+ this.db.transaction(() => {
+ tombstone.run(cutoff);
+ hardDelete.run(cutoff);
+ })();
+ return { ids: expired };
+ } catch (error) {
+ debugLogger.error(
+ "Error purging expired transcriptions",
+ { error: error.message },
+ "database"
+ );
+ throw error;
+ }
+ }
+
deleteTranscription(id) {
try {
if (!this.db) {
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index f985b5d15..83d310ef7 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -28,6 +28,7 @@ const MeetingEchoLeakDetector = require("./meetingEchoLeakDetector");
const { partitionPendingMicFinals, isWithinRetractWindow } = require("./meetingMicHoldback");
const { applySmartSpacing } = require("./smartSpacing");
const { applyAutoLearnSetting } = require("./autoLearnSetting");
+const { DEFAULT_RETENTION_SETTINGS, applyRetentionSettings } = require("./retentionSettings");
const {
transcriptsOverlap,
transcriptsLooselyOverlap,
@@ -511,7 +512,8 @@ class IPCHandlers {
this._textEditHandler = null;
this._activeRecordingPipeline = null;
this.audioStorageManager = new AudioStorageManager();
- this._audioCleanupInterval = null;
+ this._retentionCleanupInterval = null;
+ this._retentionSettings = { ...DEFAULT_RETENTION_SETTINGS }; // Synced from renderer
this._noteFilesEnabled = false;
this.speakerDiarizationEnabled = true;
this.activeMeetingSpeakerConfig = null;
@@ -523,7 +525,7 @@ class IPCHandlers {
};
liveSpeakerIdentifier.setDiarizationManager(this.diarizationManager);
this._setupTextEditMonitor();
- this._setupAudioCleanup();
+ this._setupRetentionCleanup();
this._logDetectedGpus();
this.setupHandlers();
@@ -781,29 +783,29 @@ class IPCHandlers {
}
}
- _setupAudioCleanup() {
- const DEFAULT_RETENTION_DAYS = 30;
+ _setupRetentionCleanup() {
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
+ this._runRetentionCleanup();
+ this._retentionCleanupInterval = setInterval(() => this._runRetentionCleanup(), SIX_HOURS_MS);
+ }
- // Run initial cleanup with default retention
+ _runRetentionCleanup() {
+ const { audioRetentionDays, transcriptRetentionDays } = this._retentionSettings;
try {
- this.audioStorageManager.cleanupExpiredAudio(DEFAULT_RETENTION_DAYS, this.databaseManager);
+ if (transcriptRetentionDays > 0) {
+ const { ids } =
+ this.databaseManager.deleteTranscriptionsExpiredBefore(transcriptRetentionDays);
+ for (const id of ids) {
+ this.audioStorageManager.deleteAudio(id);
+ this.broadcastToWindows("transcription-deleted", { id });
+ }
+ }
+ if (audioRetentionDays > 0) {
+ this.audioStorageManager.cleanupExpiredAudio(audioRetentionDays, this.databaseManager);
+ }
} catch (error) {
- debugLogger.error("Initial audio cleanup failed", { error: error.message }, "audio-storage");
+ debugLogger.error("Retention 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);
}
_setupTextEditMonitor() {
@@ -1106,6 +1108,13 @@ class IPCHandlers {
return this.audioStorageManager.getStorageUsage();
});
+ ipcMain.on("retention-settings-changed", (_event, incoming) => {
+ const { changed, settings } = applyRetentionSettings(this._retentionSettings, incoming);
+ if (!changed) return;
+ this._retentionSettings = settings;
+ this._runRetentionCleanup();
+ });
+
ipcMain.handle("delete-all-audio", async () => {
const result = this.audioStorageManager.deleteAllAudio();
try {
diff --git a/src/helpers/retentionSettings.js b/src/helpers/retentionSettings.js
new file mode 100644
index 000000000..e4f151160
--- /dev/null
+++ b/src/helpers/retentionSettings.js
@@ -0,0 +1,28 @@
+// Pure resolver for the "retention-settings-changed" IPC sync. Both renderer
+// windows re-sync on mount, so the handler needs to know whether the incoming
+// values actually differ before kicking off another cleanup sweep.
+const DEFAULT_RETENTION_SETTINGS = {
+ audioRetentionDays: 30,
+ transcriptRetentionDays: 0, // 0 = keep transcripts forever
+};
+
+function toDays(value, fallback) {
+ const days = Math.trunc(Number(value));
+ return Number.isFinite(days) && days >= 0 ? days : fallback;
+}
+
+function applyRetentionSettings(current, incoming) {
+ const settings = {
+ audioRetentionDays: toDays(incoming?.audioRetentionDays, current.audioRetentionDays),
+ transcriptRetentionDays: toDays(
+ incoming?.transcriptRetentionDays,
+ current.transcriptRetentionDays
+ ),
+ };
+ const changed =
+ settings.audioRetentionDays !== current.audioRetentionDays ||
+ settings.transcriptRetentionDays !== current.transcriptRetentionDays;
+ return { changed, settings };
+}
+
+module.exports = { DEFAULT_RETENTION_SETTINGS, applyRetentionSettings };
diff --git a/src/hooks/useSettings.ts b/src/hooks/useSettings.ts
index cc06cfca9..28146ff37 100644
--- a/src/hooks/useSettings.ts
+++ b/src/hooks/useSettings.ts
@@ -83,6 +83,7 @@ export interface PrivacySettings {
cloudBackupEnabled: boolean;
telemetryEnabled: boolean;
audioRetentionDays: number;
+ transcriptRetentionDays: number;
dataRetentionEnabled: boolean;
saveDiscardedTranscriptions: boolean;
}
@@ -168,6 +169,12 @@ function useSettingsInternal() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ // Retention periods are enforced by the main process cleanup sweep
+ const { audioRetentionDays, transcriptRetentionDays } = store;
+ useEffect(() => {
+ window.electronAPI?.syncRetentionSettings?.({ audioRetentionDays, transcriptRetentionDays });
+ }, [audioRetentionDays, transcriptRetentionDays]);
+
// Sync startup pre-warming preferences to main process
const {
useLocalWhisper,
@@ -370,6 +377,8 @@ function useSettingsInternal() {
setTelemetryEnabled: store.setTelemetryEnabled,
audioRetentionDays: store.audioRetentionDays,
setAudioRetentionDays: store.setAudioRetentionDays,
+ transcriptRetentionDays: store.transcriptRetentionDays,
+ setTranscriptRetentionDays: store.setTranscriptRetentionDays,
dataRetentionEnabled: store.dataRetentionEnabled,
setDataRetentionEnabled: store.setDataRetentionEnabled,
saveDiscardedTranscriptions: store.saveDiscardedTranscriptions,
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index fc7580bd1..ab7b15fc3 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1656,6 +1656,9 @@
"usageAnalyticsDescription": "Helfen Sie uns, OpenWhispr zu verbessern, indem Sie anonyme Leistungsdaten teilen. Wir senden niemals Transkriptionsinhalte – nur Timing- und Fehlerdaten.",
"dataRetention": "Datenaufbewahrung",
"dataRetentionDescription": "Transkriptionen und Audio lokal im Verlauf speichern. Wenn deaktiviert, werden Transkriptionen eingefügt, aber nicht gespeichert.",
+ "transcriptRetention": "Transkript-Aufbewahrung",
+ "transcriptRetentionDescription": "Gespeicherte Transkriptionen und deren Audio nach diesem Zeitraum automatisch löschen.",
+ "transcriptRetentionForever": "Unbegrenzt",
"hoursAgo": "vor {{count}} Std.",
"justNow": "gerade eben",
"lastSynced": "Zuletzt synchronisiert {{time}}",
@@ -1663,7 +1666,8 @@
"audioRetention": "Audio-Aufbewahrung",
"audioRetentionDescription": "Audioaufnahmen lokal für erneute Transkription und Download speichern. Dateien werden nach Ablauf der Aufbewahrungsfrist automatisch gelöscht.",
"audioRetentionDisabled": "Deaktiviert",
- "audioRetentionDays": "{{count}} Tage",
+ "retentionDays_one": "{{count}} Tag",
+ "retentionDays_other": "{{count}} Tage",
"audioStorageUsage": "Speicherverbrauch",
"audioStorageUsageDescription": "Auf diesem Gerät gespeicherte Audiodateien",
"audioStorageFiles": "{{count}} Dateien, {{size}}",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index fa474d46d..886fcb56e 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1830,7 +1830,8 @@
"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",
+ "retentionDays_one": "{{count}} day",
+ "retentionDays_other": "{{count}} days",
"audioStorageUsage": "Storage Usage",
"audioStorageUsageDescription": "Audio files stored on this device",
"audioStorageFiles": "{{count}} files, {{size}}",
@@ -1839,6 +1840,9 @@
"clearAllAudioConfirm": "Delete all stored audio files? This cannot be undone.",
"dataRetention": "Data Retention",
"dataRetentionDescription": "Store transcriptions and audio locally in your history. When disabled, transcriptions are pasted but not saved.",
+ "transcriptRetention": "Transcript Retention",
+ "transcriptRetentionDescription": "Automatically delete saved transcriptions and their audio after this period.",
+ "transcriptRetentionForever": "Forever",
"hoursAgo": "{{count}}h ago",
"justNow": "just now",
"lastSynced": "Last synced {{time}}",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 3e514ec56..3776e406e 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1704,6 +1704,9 @@
"usageAnalyticsDescription": "Ayúdanos a mejorar OpenWhispr compartiendo métricas de rendimiento anónimas. Nunca enviamos contenido de transcripciones, solo datos de tiempo y errores.",
"dataRetention": "Retención de datos",
"dataRetentionDescription": "Almacenar transcripciones y audio localmente en tu historial. Cuando está desactivado, las transcripciones se pegan pero no se guardan.",
+ "transcriptRetention": "Retención de transcripciones",
+ "transcriptRetentionDescription": "Eliminar automáticamente las transcripciones guardadas y su audio después de este período.",
+ "transcriptRetentionForever": "Para siempre",
"hoursAgo": "hace {{count}}h",
"justNow": "ahora mismo",
"lastSynced": "Última sincronización {{time}}",
@@ -1713,7 +1716,8 @@
"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",
+ "retentionDays_one": "{{count}} día",
+ "retentionDays_other": "{{count}} días",
"audioStorageUsage": "Uso de almacenamiento",
"audioStorageUsageDescription": "Archivos de audio almacenados en este dispositivo",
"audioStorageFiles": "{{count}} archivos, {{size}}",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index a7d39a672..bad8bced3 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1704,6 +1704,9 @@
"usageAnalyticsDescription": "Aidez-nous à améliorer OpenWhispr en partageant des métriques de performance anonymes. Nous n'envoyons jamais le contenu de vos transcriptions — uniquement des données de performance et d'erreurs.",
"dataRetention": "Conservation des données",
"dataRetentionDescription": "Stocker les transcriptions et l'audio localement dans votre historique. Lorsque désactivé, les transcriptions sont collées mais pas enregistrées.",
+ "transcriptRetention": "Conservation des transcriptions",
+ "transcriptRetentionDescription": "Supprimer automatiquement les transcriptions enregistrées et leur audio après cette période.",
+ "transcriptRetentionForever": "Toujours",
"hoursAgo": "il y a {{count}}h",
"justNow": "à l'instant",
"lastSynced": "Dernière synchronisation {{time}}",
@@ -1711,7 +1714,8 @@
"audioRetention": "Conservation de l'audio",
"audioRetentionDescription": "Stocke les enregistrements audio localement pour la retranscription et le téléchargement. Les fichiers sont automatiquement supprimés après la période de conservation.",
"audioRetentionDisabled": "Désactivé",
- "audioRetentionDays": "{{count}} jours",
+ "retentionDays_one": "{{count}} jour",
+ "retentionDays_other": "{{count}} jours",
"audioStorageUsage": "Espace utilisé",
"audioStorageUsageDescription": "Fichiers audio stockés sur cet appareil",
"audioStorageFiles": "{{count}} fichiers, {{size}}",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index a9fca197d..ffd1f4c28 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1656,6 +1656,9 @@
"usageAnalyticsDescription": "Aiutaci a migliorare OpenWhispr condividendo metriche di prestazione anonime. Non inviamo mai il contenuto delle trascrizioni, solo dati su tempi ed errori.",
"dataRetention": "Conservazione dei dati",
"dataRetentionDescription": "Salva trascrizioni e audio localmente nella cronologia. Se disattivato, le trascrizioni vengono incollate ma non salvate.",
+ "transcriptRetention": "Conservazione delle trascrizioni",
+ "transcriptRetentionDescription": "Elimina automaticamente le trascrizioni salvate e il relativo audio dopo questo periodo.",
+ "transcriptRetentionForever": "Per sempre",
"hoursAgo": "{{count}}h fa",
"justNow": "adesso",
"lastSynced": "Ultima sincronizzazione {{time}}",
@@ -1663,7 +1666,8 @@
"audioRetention": "Conservazione audio",
"audioRetentionDescription": "Salva le registrazioni audio localmente per la ritrascrizione e il download. I file vengono eliminati automaticamente al termine del periodo di conservazione.",
"audioRetentionDisabled": "Disattivato",
- "audioRetentionDays": "{{count}} giorni",
+ "retentionDays_one": "{{count}} giorno",
+ "retentionDays_other": "{{count}} giorni",
"audioStorageUsage": "Spazio utilizzato",
"audioStorageUsageDescription": "File audio salvati su questo dispositivo",
"audioStorageFiles": "{{count}} file, {{size}}",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 0dc23e239..94f3072c6 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1656,6 +1656,9 @@
"usageAnalyticsDescription": "匿名のパフォーマンスデータを共有して OpenWhispr の改善にご協力ください。文字起こしの内容は送信されません。タイミングとエラーデータのみです。",
"dataRetention": "データ保持",
"dataRetentionDescription": "文字起こしと音声を履歴にローカル保存します。無効にすると、文字起こしは貼り付けられますが保存されません。",
+ "transcriptRetention": "文字起こしの保持",
+ "transcriptRetentionDescription": "保存された文字起こしとその音声を、この期間の経過後に自動的に削除します。",
+ "transcriptRetentionForever": "無期限",
"hoursAgo": "{{count}}時間前",
"justNow": "たった今",
"lastSynced": "最終同期 {{time}}",
@@ -1663,7 +1666,8 @@
"audioRetention": "音声の保持",
"audioRetentionDescription": "再文字起こしやダウンロードのために音声録音をローカルに保存します。ファイルは保持期間が過ぎると自動的に削除されます。",
"audioRetentionDisabled": "無効",
- "audioRetentionDays": "{{count}}日",
+ "retentionDays_one": "{{count}}日",
+ "retentionDays_other": "{{count}}日",
"audioStorageUsage": "ストレージ使用量",
"audioStorageUsageDescription": "このデバイスに保存された音声ファイル",
"audioStorageFiles": "{{count}}ファイル、{{size}}",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 727331314..f7fc3521c 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1635,6 +1635,9 @@
"usageAnalyticsDescription": "Ajude-nos a melhorar o OpenWhispr compartilhando métricas anônimas de desempenho. Nunca enviamos conteúdo de transcrição — apenas dados de tempo e erros.",
"dataRetention": "Retenção de dados",
"dataRetentionDescription": "Armazenar transcrições e áudio localmente no seu histórico. Quando desativado, as transcrições são coladas mas não salvas.",
+ "transcriptRetention": "Retenção de transcrições",
+ "transcriptRetentionDescription": "Excluir automaticamente as transcrições salvas e o áudio delas após este período.",
+ "transcriptRetentionForever": "Para sempre",
"hoursAgo": "há {{count}}h",
"justNow": "agora mesmo",
"lastSynced": "Última sincronização {{time}}",
@@ -1642,7 +1645,8 @@
"audioRetention": "Retenção de áudio",
"audioRetentionDescription": "Armazena gravações de áudio localmente para retranscrição e download. Os arquivos são excluídos automaticamente após o período de retenção.",
"audioRetentionDisabled": "Desativado",
- "audioRetentionDays": "{{count}} dias",
+ "retentionDays_one": "{{count}} dia",
+ "retentionDays_other": "{{count}} dias",
"audioStorageUsage": "Uso de armazenamento",
"audioStorageUsageDescription": "Arquivos de áudio armazenados neste dispositivo",
"audioStorageFiles": "{{count}} arquivos, {{size}}",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 799c9b54c..9437c541e 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1656,6 +1656,9 @@
"usageAnalyticsDescription": "Помогите нам улучшить OpenWhispr, делясь анонимными метриками производительности. Мы никогда не отправляем содержимое транскрипций — только данные о времени и ошибках.",
"dataRetention": "Хранение данных",
"dataRetentionDescription": "Сохранять транскрипции и аудио локально в истории. При отключении транскрипции вставляются, но не сохраняются.",
+ "transcriptRetention": "Хранение транскрипций",
+ "transcriptRetentionDescription": "Автоматически удалять сохранённые транскрипции и их аудио по истечении этого срока.",
+ "transcriptRetentionForever": "Бессрочно",
"hoursAgo": "{{count}}ч назад",
"justNow": "только что",
"lastSynced": "Последняя синхронизация {{time}}",
@@ -1663,7 +1666,10 @@
"audioRetention": "Хранение аудио",
"audioRetentionDescription": "Сохранять аудиозаписи локально для повторной расшифровки и скачивания. Файлы автоматически удаляются по истечении срока хранения.",
"audioRetentionDisabled": "Отключено",
- "audioRetentionDays": "{{count}} дн.",
+ "retentionDays_one": "{{count}} день",
+ "retentionDays_few": "{{count}} дня",
+ "retentionDays_many": "{{count}} дней",
+ "retentionDays_other": "{{count}} дн.",
"audioStorageUsage": "Использование хранилища",
"audioStorageUsageDescription": "Аудиофайлы, сохранённые на этом устройстве",
"audioStorageFiles": "{{count}} файлов, {{size}}",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 83cbf23e8..f51f24ec4 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1651,6 +1651,9 @@
"usageAnalyticsDescription": "通过分享匿名性能数据帮助我们改进 OpenWhispr。我们绝不发送转录内容——仅发送计时和错误数据。",
"dataRetention": "数据保留",
"dataRetentionDescription": "将转录和音频本地保存到历史记录中。禁用后,转录内容会被粘贴但不会被保存。",
+ "transcriptRetention": "转录保留",
+ "transcriptRetentionDescription": "在此期限后自动删除已保存的转录及其音频。",
+ "transcriptRetentionForever": "永久",
"hoursAgo": "{{count}}小时前",
"justNow": "刚刚",
"lastSynced": "上次同步 {{time}}",
@@ -1658,7 +1661,8 @@
"audioRetention": "音频保留",
"audioRetentionDescription": "在本地存储音频录制文件以便重新转录和下载。文件会在保留期过后自动删除。",
"audioRetentionDisabled": "已禁用",
- "audioRetentionDays": "{{count}} 天",
+ "retentionDays_one": "{{count}} 天",
+ "retentionDays_other": "{{count}} 天",
"audioStorageUsage": "存储用量",
"audioStorageUsageDescription": "存储在此设备上的音频文件",
"audioStorageFiles": "{{count}} 个文件,{{size}}",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index a38c63c57..d084fa78b 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1651,6 +1651,9 @@
"usageAnalyticsDescription": "分享匿名的效能指標,協助我們改善 OpenWhispr。我們絕不會傳送轉錄內容——只有計時和錯誤資料。",
"dataRetention": "資料保留",
"dataRetentionDescription": "將轉錄和音訊本地儲存至歷史記錄。停用後,轉錄內容會被貼上但不會被儲存。",
+ "transcriptRetention": "轉錄保留",
+ "transcriptRetentionDescription": "在此期限後自動刪除已儲存的轉錄及其音訊。",
+ "transcriptRetentionForever": "永久",
"hoursAgo": "{{count}}小時前",
"justNow": "剛剛",
"lastSynced": "上次同步 {{time}}",
@@ -1658,7 +1661,8 @@
"audioRetention": "音訊保留",
"audioRetentionDescription": "將音訊錄製檔案儲存在本機以便重新轉錄和下載。檔案會在保留期限過後自動刪除。",
"audioRetentionDisabled": "已停用",
- "audioRetentionDays": "{{count}} 天",
+ "retentionDays_one": "{{count}} 天",
+ "retentionDays_other": "{{count}} 天",
"audioStorageUsage": "儲存空間用量",
"audioStorageUsageDescription": "儲存在此裝置上的音訊檔案",
"audioStorageFiles": "{{count}} 個檔案,{{size}}",
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index d1b7972a0..c12975096 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -51,6 +51,12 @@ function readBoolean(key: string, fallback: boolean): boolean {
return stored === "true";
}
+function readNumber(key: string, fallback: number): number {
+ if (!isBrowser) return fallback;
+ const parsed = parseInt(localStorage.getItem(key) ?? "", 10);
+ return isNaN(parsed) ? fallback : parsed;
+}
+
function readStringArray(key: string, fallback: string[]): string[] {
if (!isBrowser) return fallback;
const stored = localStorage.getItem(key);
@@ -162,6 +168,7 @@ const ARRAY_SETTINGS = new Set([
const NUMERIC_SETTINGS = new Set([
"audioRetentionDays",
+ "transcriptRetentionDays",
"whisperVadThreshold",
"whisperVadMinSpeechDurationMs",
"whisperVadMinSilenceDurationMs",
@@ -667,6 +674,7 @@ export interface SettingsState
setCloudBackupEnabled: (value: boolean) => void;
setTelemetryEnabled: (value: boolean) => void;
setAudioRetentionDays: (days: number) => void;
+ setTranscriptRetentionDays: (days: number) => void;
setDataRetentionEnabled: (value: boolean) => void;
setSaveDiscardedTranscriptions: (value: boolean) => void;
setAudioCuesEnabled: (value: boolean) => void;
@@ -734,6 +742,13 @@ function createBooleanSetter(key: string) {
};
}
+function createNumberSetter(key: string) {
+ return (value: number) => {
+ if (isBrowser) localStorage.setItem(key, String(value));
+ useSettingsStore.setState({ [key]: value });
+ };
+}
+
// Setter for hotkeys that must be registered with the main process before
// being persisted. Rolls back to the previous key if registration fails.
// Resolves to false on failure so optimistic UIs (HotkeyListInput) can revert.
@@ -1011,13 +1026,8 @@ 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;
- })(),
+ audioRetentionDays: readNumber("audioRetentionDays", 30),
+ transcriptRetentionDays: readNumber("transcriptRetentionDays", 0),
dataRetentionEnabled: readBoolean("dataRetentionEnabled", true),
saveDiscardedTranscriptions: readBoolean("saveDiscardedTranscriptions", false),
audioCuesEnabled: readBoolean("audioCuesEnabled", true),
@@ -1621,10 +1631,8 @@ 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 });
- },
+ setAudioRetentionDays: createNumberSetter("audioRetentionDays"),
+ setTranscriptRetentionDays: createNumberSetter("transcriptRetentionDays"),
setDataRetentionEnabled: (value: boolean) => {
if (isBrowser) localStorage.setItem("dataRetentionEnabled", String(value));
set({ dataRetentionEnabled: value });
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 51ab27c9f..a88b0b26e 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -615,6 +615,10 @@ declare global {
deleteTranscriptionAudio: (id: number) => Promise<{ success: boolean }>;
getAudioStorageUsage: () => Promise<{ fileCount: number; totalBytes: number }>;
deleteAllAudio: () => Promise<{ deleted: number }>;
+ syncRetentionSettings?: (settings: {
+ audioRetentionDays: number;
+ transcriptRetentionDays: number;
+ }) => void;
retryTranscription: (
id: number,
settings?: {
diff --git a/test/helpers/retentionSettings.test.js b/test/helpers/retentionSettings.test.js
new file mode 100644
index 000000000..0bb689c52
--- /dev/null
+++ b/test/helpers/retentionSettings.test.js
@@ -0,0 +1,42 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ DEFAULT_RETENTION_SETTINGS,
+ applyRetentionSettings,
+} = require("../../src/helpers/retentionSettings");
+
+test("reports a change when a retention period is shortened", () => {
+ assert.deepEqual(
+ applyRetentionSettings(DEFAULT_RETENTION_SETTINGS, {
+ audioRetentionDays: 1,
+ transcriptRetentionDays: 1,
+ }),
+ {
+ changed: true,
+ settings: { audioRetentionDays: 1, transcriptRetentionDays: 1 },
+ }
+ );
+});
+
+test("is idempotent when both values are unchanged — dual-window mount sync", () => {
+ const { changed } = applyRetentionSettings(DEFAULT_RETENTION_SETTINGS, {
+ audioRetentionDays: 30,
+ transcriptRetentionDays: 0,
+ });
+ assert.equal(changed, false);
+});
+
+test("keeps the current value when an incoming value is missing or unusable", () => {
+ const current = { audioRetentionDays: 7, transcriptRetentionDays: 1 };
+ for (const incoming of [
+ undefined,
+ {},
+ { audioRetentionDays: "abc", transcriptRetentionDays: -5 },
+ ]) {
+ assert.deepEqual(applyRetentionSettings(current, incoming), {
+ changed: false,
+ settings: current,
+ });
+ }
+});
diff --git a/test/helpers/transcriptRetention.test.js b/test/helpers/transcriptRetention.test.js
new file mode 100644
index 000000000..17cdce6a9
--- /dev/null
+++ b/test/helpers/transcriptRetention.test.js
@@ -0,0 +1,101 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const os = require("node:os");
+const path = require("node:path");
+const Module = require("node:module");
+
+let userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-retention-db-"));
+const originalLoad = Module._load;
+
+Module._load = function patchedLoad(request, parent, isMain) {
+ if (request === "electron") {
+ return {
+ app: {
+ getPath: () => userDataDir,
+ getAppPath: () => process.cwd(),
+ isReady: () => false,
+ },
+ };
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+process.env.NODE_ENV = "test";
+
+const DatabaseManager = require("../../src/helpers/database.js");
+
+function isNativeBindingUnavailable(error) {
+ const message = String(error?.message || error);
+ return (
+ message.includes("NODE_MODULE_VERSION") ||
+ message.includes("Could not locate the bindings file")
+ );
+}
+
+function createDb(t) {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-retention-db-"));
+ try {
+ return new DatabaseManager();
+ } catch (error) {
+ if (isNativeBindingUnavailable(error)) {
+ t.skip("better-sqlite3 native binding is not available for this Node runtime");
+ return null;
+ }
+ throw error;
+ }
+}
+
+function insert(db, text, ageDays, cloudId = null) {
+ const { lastInsertRowid } = db.db
+ .prepare(
+ "INSERT INTO transcriptions (text, created_at, cloud_id) VALUES (?, datetime('now', ?), ?)"
+ )
+ .run(text, `-${ageDays} days`, cloudId);
+ return lastInsertRowid;
+}
+
+test("purges local transcriptions past the retention window and keeps the rest", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const stale = insert(db, "two days old", 2);
+ const fresh = insert(db, "a few hours old", 0);
+
+ const { ids } = db.deleteTranscriptionsExpiredBefore(1);
+
+ assert.deepEqual(ids, [stale]);
+ const remaining = db.db
+ .prepare("SELECT id FROM transcriptions")
+ .all()
+ .map((r) => r.id);
+ assert.deepEqual(remaining, [fresh]);
+});
+
+test("tombstones synced transcriptions instead of deleting them so the cloud copy is removed too", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const synced = insert(db, "synced and stale", 10, "cloud-1");
+ db.deleteTranscriptionsExpiredBefore(7);
+
+ const row = db.db
+ .prepare("SELECT deleted_at, sync_status FROM transcriptions WHERE id = ?")
+ .get(synced);
+ assert.ok(row.deleted_at, "synced row should be tombstoned, not hard-deleted");
+ assert.equal(row.sync_status, "pending");
+});
+
+test("ignores rows that are already tombstoned", (t) => {
+ const db = createDb(t);
+ if (!db) return;
+
+ const synced = insert(db, "already gone", 10, "cloud-1");
+ db.deleteTranscriptionsExpiredBefore(7);
+
+ assert.deepEqual(db.deleteTranscriptionsExpiredBefore(7).ids, []);
+ assert.equal(
+ db.db.prepare("SELECT COUNT(*) c FROM transcriptions WHERE id = ?").get(synced).c,
+ 1
+ );
+});