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
fix(history): keep the transcript when a post-transcription step fails (#2678)
Mitchell Etzel5de548584fa4
diff --git a/src/components/HistoryView.tsx b/src/components/HistoryView.tsxindex 4a3294f3a..0261e8ca1 100644--- a/src/components/HistoryView.tsx+++ b/src/components/HistoryView.tsx@@ -217,7 +217,7 @@ export default function HistoryView({onDelete={deleteTranscription}onShowAudioInFolder={onShowAudioInFolder}onRetryTranscription={onRetryTranscription}- onOpenSettings={() => onOpenSettings("transcription")}+ onOpenSettings={(section) => onOpenSettings(section ?? "transcription")}/>))}</div>diff --git a/src/components/ui/TranscriptionItem.tsx b/src/components/ui/TranscriptionItem.tsxindex 39e4a06bc..d7138fe9b 100644--- a/src/components/ui/TranscriptionItem.tsx+++ b/src/components/ui/TranscriptionItem.tsx@@ -32,6 +32,9 @@ const platform = getCachedPlatform();const ACTION_BUTTON_CLASS ="h-7 w-7 rounded-full text-muted-foreground/70 hover:text-foreground hover:bg-foreground/6 dark:hover:bg-white/6";+const TRANSCRIPT_TEXT_CLASS =+ "text-base leading-normal wrap-break-word whitespace-pre-wrap text-foreground";+function getShowInFolderKey(): string {if (platform === "win32") return "controlPanel.history.showInFolderWindows";if (platform === "linux") return "controlPanel.history.showInFolderLinux";@@ -52,7 +55,7 @@ interface TranscriptionItemProps {onDelete: (id: number) => void;onShowAudioInFolder?: (id: number) => void;onRetryTranscription?: (id: number, options?: { isRecover?: boolean }) => Promise<void>;- onOpenSettings?: () => void;+ onOpenSettings?: (section?: string) => void;}export default function TranscriptionItem({@@ -95,6 +98,8 @@ export default function TranscriptionItem({: null;const rawText = item.raw_text;const hasAudio = item.has_audio === 1;+ // A failed row keeps the transcript when only a later step failed.+ const hasKeptText = isFailed && item.text.trim() !== "";const errorCode = item.error_code as TranscriptionErrorCode;const isConfigError =@@ -174,12 +179,13 @@ export default function TranscriptionItem({"opacity-0 group-hover/row:opacity-100 has-[:focus-visible]:opacity-100 has-[[data-state=open]]:opacity-100")}>- {isTranscribed && (+ {(isTranscribed || hasKeptText) && (<Tooltip content={t("controlPanel.history.copyText")}><Buttonsize="icon"variant="ghost"onClick={() => onCopy(item.text)}+ aria-label={t("controlPanel.history.copyText")}className={ACTION_BUTTON_CLASS}><Copy size={13} />@@ -227,14 +233,28 @@ export default function TranscriptionItem({<AlertCircle size={14} className="mt-0.5 shrink-0 text-destructive" /><div className="min-w-0"><p className="text-sm font-medium text-destructive">- {t("controlPanel.history.transcriptionFailed")}+ {t(+ hasKeptText+ ? "controlPanel.history.editFailedTranscriptKept"+ : "controlPanel.history.transcriptionFailed"+ )}</p>{item.error_message && (<p className="mt-0.5 text-xs leading-relaxed wrap-break-word text-muted-foreground">{item.error_message}</p>)}- {isConfigError && (+ {isConfigError && hasKeptText && (+ <p className="mt-1 text-xs text-muted-foreground">+ <button+ onClick={() => onOpenSettings?.("dictationAgent")}+ className="cursor-pointer text-primary hover:underline"+ >+ {t("controlPanel.history.failedCtaAiSettings")}+ </button>+ </p>+ )}+ {isConfigError && !hasKeptText && (<p className="mt-1 text-xs text-muted-foreground">{hasAudio ? (<>@@ -282,10 +302,12 @@ export default function TranscriptionItem({</span></div>) : (- <p- dir="auto"- className="text-base leading-normal wrap-break-word whitespace-pre-wrap text-foreground"- >+ <p dir="auto" className={TRANSCRIPT_TEXT_CLASS}>+ {item.text}+ </p>+ )}+ {hasKeptText && (+ <p dir="auto" className={cn("mt-2", TRANSCRIPT_TEXT_CLASS)}>{item.text}</p>)}diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 2ba039ec3..230c3f477 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -182,6 +182,23 @@ const neverCancelled = () => false;const MIN_SPARSE_RECORDING_DURATION_SECONDS = 3;const MIN_UNIQUE_WORD_GAIN = 2;+// A selection edit that fails leaves its transcript behind; it rides out on the+// error so the failed history entry keeps it. Only those errors carry it: they+// are created per dictation, while others can be one cached rejection shared by+// every dictation. Non-enumerable, so a logged error never writes the text out.+const attachTranscript = (error, transcript, clientTranscriptionId) => {+ if (!error?.selectionEditFatal || error.transcript !== undefined) return;+ const text = typeof transcript === "string" ? transcript.trim() : "";+ if (!text) return;+ Object.defineProperty(error, "transcript", { value: text, configurable: true });+ if (clientTranscriptionId) {+ Object.defineProperty(error, "transcriptClientId", {+ value: clientTranscriptionId,+ configurable: true,+ });+ }+};+const cleanupFailureFromError = (error) => ({message: error?.message || String(error),...(error?.messageKey ? { messageKey: error.messageKey } : {}),@@ -2298,7 +2315,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);pipeline.resultHandled = this.saveFailedTranscription(error.message,error.code || null,- metadata+ metadata,+ { transcript: error.transcript, clientTranscriptionId: error.transcriptClientId });}} finally {@@ -3251,9 +3269,14 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}async processTranscription(text, source, wasCancelled = neverCancelled) {- const result = await this.processTranscriptionCore(text, source, wasCancelled);- if (wasCancelled()) return result;- return this.finalizeChineseScript(result);+ try {+ const result = await this.processTranscriptionCore(text, source, wasCancelled);+ if (wasCancelled()) return result;+ return this.finalizeChineseScript(result);+ } catch (error) {+ attachTranscript(error, text);+ throw error;+ }}async processTranscriptionCore(text, source, wasCancelled = neverCancelled) {@@ -3751,7 +3774,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);processedText = resolveTranslatedText(processedText, chainResult);}} catch (reasonError) {- if (reasonError.selectionEditFatal) throw reasonError;+ if (reasonError.selectionEditFatal) {+ // Cloud already recorded this transcription under its client id; the+ // failed entry reuses it so a later retry syncs onto the same row.+ attachTranscript(reasonError, rawText, result.clientTranscriptionId);+ throw reasonError;+ }if (!wasCancelled()) {logger.error("Cloud reasoning failed, using raw transcription",@@ -4472,7 +4500,12 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}}- async saveFailedTranscription(errorMessage, errorCode = null, metadata = {}) {+ async saveFailedTranscription(+ errorMessage,+ errorCode = null,+ metadata = {},+ { transcript = "", clientTranscriptionId } = {}+ ) {const { dataRetentionEnabled, audioRetentionDays } = getEffectiveRetentionPreferences();if (!dataRetentionEnabled) {logger.debug("Skipping failed transcription save — data retention disabled", {}, "audio");@@ -4482,16 +4515,23 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);}try {- const result = await window.electronAPI.saveTranscription("", null, {- status: "failed",- errorMessage,- errorCode,- routeKind: this.translationRequested ? "translation" : null,- ...(metadata?.analyticsOccurredAt- ? { analyticsOccurredAt: metadata.analyticsOccurredAt }- : {}),- });- if (result?.id) syncService.debouncedPush("transcription", result.id);+ // Empty when transcription itself failed; otherwise the transcript a later+ // step could not process, kept as both the entry's text and its raw text.+ const keptTranscript = typeof transcript === "string" ? transcript : "";+ const result = await window.electronAPI.saveTranscription(+ keptTranscript,+ keptTranscript || null,+ {+ status: "failed",+ errorMessage,+ errorCode,+ routeKind: this.translationRequested ? "translation" : null,+ ...(clientTranscriptionId ? { clientTranscriptionId } : {}),+ ...(metadata?.analyticsOccurredAt+ ? { analyticsOccurredAt: metadata.analyticsOccurredAt }+ : {}),+ }+ );if (result?.id && this.lastAudioBlob) {if (audioRetentionDays > 0) {@@ -5807,10 +5847,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const outcome = transcriptionFailureOutcome(error);failureReport = outcome.report;if (outcome.keepAudio) {- delivery.resultHandled = this.saveFailedTranscription(error.message, error.code || null, {- durationSeconds,- analyticsOccurredAt: analyticsOccurredAt.toISOString(),- });+ // error.transcript is Cloud's re-transcription, never Orukeet's text.+ delivery.resultHandled = this.saveFailedTranscription(+ error.message,+ error.code || null,+ { durationSeconds, analyticsOccurredAt: analyticsOccurredAt.toISOString() },+ { transcript: error.transcript, clientTranscriptionId: error.transcriptClientId }+ );}};try {@@ -6000,6 +6043,13 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);if (wasCancelled()) return true;if (reasonError.selectionEditFatal) {this.pendingSelectionEdit = null;+ attachTranscript(reasonError, rawStreamingText);+ delivery.resultHandled = this.saveFailedTranscription(+ reasonError.message,+ reasonError.code || null,+ { durationSeconds, analyticsOccurredAt: analyticsOccurredAt.toISOString() },+ { transcript: reasonError.transcript }+ );this.onError?.(transcriptionFailureOutcome(reasonError).report);this.isProcessing = false;this.onStateChange?.({ isRecording: false, isProcessing: false, isStreaming: false });@@ -6035,13 +6085,17 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);// reads as silence for a retry, as batch does.const failBatchFallback = (error) => {const outcome = transcriptionFailureOutcome(error);- if (!failoverReason && outcome.report) return;+ // A transcript the fallback produced before a later step failed is+ // reported and kept like the batch pipeline's.+ if (!failoverReason && outcome.report && !error.transcript) return;failureReport = outcome.report;if (outcome.keepAudio) {- delivery.resultHandled = this.saveFailedTranscription(error.message, error.code || null, {- durationSeconds,- analyticsOccurredAt: analyticsOccurredAt.toISOString(),- });+ delivery.resultHandled = this.saveFailedTranscription(+ error.message,+ error.code || null,+ { durationSeconds, analyticsOccurredAt: analyticsOccurredAt.toISOString() },+ { transcript: error.transcript, clientTranscriptionId: error.transcriptClientId }+ );}};if (diff --git a/src/helpers/transcriptionFailureOutcome.js b/src/helpers/transcriptionFailureOutcome.jsindex a16e39026..1b5b75142 100644--- a/src/helpers/transcriptionFailureOutcome.js+++ b/src/helpers/transcriptionFailureOutcome.js@@ -23,5 +23,7 @@ export const transcriptionFailureOutcome = (error) => {for (const key of IPC_ERROR_FIELDS) {if (error[key] !== undefined) report[key] = error[key];}+ // A transcript that outlived a later failure gets the pill's View Transcript.+ if (error.transcript) report.transcript = error.transcript;return { noAudio: false, keepAudio: true, report };};diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex d021248e2..91e0e5d63 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -581,6 +581,8 @@"failedCtaSettings": "قم بإعداد مزود التفريغ الخاص بك","failedCtaAndRetry": "ثم انقر فوق إعادة المحاولة","failedCtaSettingsOnly": "قم بإعداد مزود التفريغ الخاص بك في الإعدادات",+ "failedCtaAiSettings": "تحقق من نموذج المساعد الصوتي في الإعدادات",+ "editFailedTranscriptKept": "لم يُطبَّق التعديل · تم الاحتفاظ بالنص المفرَّغ","failedLimitReached": "تم الوصول إلى الحد اليومي","failedOffline": "أنت غير متصل بالإنترنت","rawTranscript": "النص المفرَّغ الخام",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 71522616e..9583a664e 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -689,6 +689,8 @@"failedCtaSettings": "Richten Sie Ihren Transkriptionsanbieter ein","failedCtaAndRetry": "und klicken Sie dann auf Wiederholen","failedCtaSettingsOnly": "Richten Sie Ihren Transkriptionsanbieter in den Einstellungen ein",+ "failedCtaAiSettings": "Prüfen Sie das Modell des Sprachassistenten in den Einstellungen",+ "editFailedTranscriptKept": "Bearbeitung nicht angewendet · Transkript behalten","failedLimitReached": "Tageslimit erreicht","failedOffline": "Offline","rawTranscript": "Rohtranskript",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 1d0b40e0b..5ebea019d 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -689,6 +689,8 @@"failedCtaSettings": "Set up your transcription provider","failedCtaAndRetry": "then click retry","failedCtaSettingsOnly": "Set up your transcription provider in Settings",+ "failedCtaAiSettings": "Check your Voice Assistant model in Settings",+ "editFailedTranscriptKept": "Edit not applied · transcript kept","failedLimitReached": "Daily limit reached","failedOffline": "You're offline","rawTranscript": "Raw Transcript",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex ebf690c7a..807f4bfa2 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -681,6 +681,8 @@"failedCtaSettings": "Configura tu proveedor de transcripción","failedCtaAndRetry": "y luego haz clic en reintentar","failedCtaSettingsOnly": "Configura tu proveedor de transcripción en Ajustes",+ "failedCtaAiSettings": "Revisa el modelo del Asistente de voz en Configuración",+ "editFailedTranscriptKept": "Edición no aplicada · transcripción guardada","failedLimitReached": "Límite diario alcanzado","failedOffline": "Sin conexión","clearAll": "Borrar todo",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 62cf115f5..d2f3b8adb 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -689,6 +689,8 @@"failedCtaSettings": "Configurez votre fournisseur de transcription","failedCtaAndRetry": "puis cliquez sur réessayer","failedCtaSettingsOnly": "Configurez votre fournisseur de transcription dans les Paramètres",+ "failedCtaAiSettings": "Vérifiez le modèle de l'Assistant vocal dans les Paramètres",+ "editFailedTranscriptKept": "Modification non appliquée · transcription conservée","failedLimitReached": "Limite quotidienne atteinte","failedOffline": "Hors ligne","rawTranscript": "Transcription brute",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 1de0fd830..6fa5a0cd1 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -672,6 +672,8 @@"failedCtaSettings": "Configura il tuo provider di trascrizione","failedCtaAndRetry": "poi clicca su riprova","failedCtaSettingsOnly": "Configura il tuo provider di trascrizione nelle Impostazioni",+ "failedCtaAiSettings": "Controlla il modello dell'Assistente vocale nelle Impostazioni",+ "editFailedTranscriptKept": "Modifica non applicata · trascrizione conservata","failedLimitReached": "Limite giornaliero raggiunto","failedOffline": "Offline","clearAll": "Cancella tutto",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex ba89b72c1..3ee93e73c 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -672,6 +672,8 @@"failedCtaSettings": "文字起こしプロバイダーを設定してください","failedCtaAndRetry": "その後、再試行をクリックしてください","failedCtaSettingsOnly": "設定で文字起こしプロバイダーを設定してください",+ "failedCtaAiSettings": "設定で音声アシスタントのモデルを確認してください",+ "editFailedTranscriptKept": "編集は適用されませんでした · 文字起こしは保存済み","failedLimitReached": "1日の上限に達しました","failedOffline": "オフラインです","clearAll": "すべて削除",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 94eb9282f..c9b829f69 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -651,6 +651,8 @@"failedCtaSettings": "Configure seu provedor de transcrição","failedCtaAndRetry": "e depois clique em tentar novamente","failedCtaSettingsOnly": "Configure seu provedor de transcrição nas Configurações",+ "failedCtaAiSettings": "Verifique o modelo do Assistente de voz nas Configurações",+ "editFailedTranscriptKept": "Edição não aplicada · transcrição mantida","failedLimitReached": "Limite diário atingido","failedOffline": "Sem conexão","clearAll": "Limpar tudo",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 5582d87d7..aa38733f9 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -672,6 +672,8 @@"failedCtaSettings": "Настройте провайдер транскрипции","failedCtaAndRetry": "затем нажмите повторить","failedCtaSettingsOnly": "Настройте провайдер транскрипции в Настройках",+ "failedCtaAiSettings": "Проверьте модель голосового помощника в настройках",+ "editFailedTranscriptKept": "Правка не применена · расшифровка сохранена","failedLimitReached": "Дневной лимит достигнут","failedOffline": "Нет подключения","clearAll": "Очистить все",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 5cf0e1c36..1fe403fb1 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -672,6 +672,8 @@"failedCtaSettings": "设置您的转录服务商","failedCtaAndRetry": "然后点击重试","failedCtaSettingsOnly": "在设置中配置您的转录服务商",+ "failedCtaAiSettings": "请在设置中检查语音助手模型",+ "editFailedTranscriptKept": "未应用编辑 · 已保留转录文本","failedLimitReached": "已达每日限额","failedOffline": "离线","clearAll": "全部清除",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 5cf419692..d805eeda3 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -672,6 +672,8 @@"failedCtaSettings": "設定您的轉錄服務供應商","failedCtaAndRetry": "然後點擊重試","failedCtaSettingsOnly": "在設定中配置您的轉錄服務供應商",+ "failedCtaAiSettings": "請在設定中檢查語音助理模型",+ "editFailedTranscriptKept": "未套用編輯 · 已保留轉錄文字","failedLimitReached": "已達每日限額","failedOffline": "離線","clearAll": "全部清除",diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex a1333dd26..c949bf85a 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -999,7 +999,8 @@ export class SyncService {private async pushTranscription(id: number): Promise<void> {const t = await window.electronAPI.getTranscriptionById?.(id);- if (!t || t.cloud_id) return;+ // A failed entry stays on this device until a retry completes it.+ if (!t || t.cloud_id || t.status === "failed") return;const cloud = await TranscriptionsService.create({client_transcription_id: t.client_transcription_id,@@ -2456,7 +2457,7 @@ export class SyncService {private async pushPendingTranscriptions(): Promise<void> {const pending = ((await window.electronAPI.getPendingTranscriptions?.()) ?? []).filter(- (t) => !!t.text?.trim()+ (t) => t.status !== "failed" && !!t.text?.trim());if (pending.length === 0) return;diff --git a/test/components/transcriptionItemKeptTranscript.test.js b/test/components/transcriptionItemKeptTranscript.test.jsnew file mode 100644index 000000000..acb6b6652--- /dev/null+++ b/test/components/transcriptionItemKeptTranscript.test.js@@ -0,0 +1,126 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const React = require("react");+const { renderToStaticMarkup } = require("react-dom/server");+const { createRoot } = require("react-dom/client");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");+const { installInteractiveDom, findElement } = require("../lib/interactiveDom");++// A failed history row keeps the transcript when only a step after+// transcription failed (#2676): it shows and copies the text, and its header+// and settings hint name the failed edit rather than transcription.+const TRANSCRIPT = "Nova, this is a long note about the quarterly plan.";++const row = (overrides = {}) => ({+ id: 1,+ timestamp: "2026-10-19T09:00:00.000Z",+ created_at: "2026-10-19T09:00:00.000Z",+ has_audio: 1,+ audio_duration_ms: 5000,+ provider: null,+ model: null,+ route_kind: null,+ client_transcription_id: "client-1",+ cloud_id: null,+ sync_status: "pending",+ deleted_at: null,+ status: "failed",+ text: "",+ raw_text: null,+ error_message: "Selection edit could not safely verify the selected text",+ error_code: "SELECTION_EDIT_CAPTURE_FAILED",+ ...overrides,+});++async function loadTranscriptionItem(t) {+ installBrowserGlobals(t);+ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-transcription-item-test-",+ noExternal: ["react-i18next"],+ mockModules: {+ "react-i18next": `+ const t = (key) => key;+ export function useTranslation() { return { t, i18n: { language: "en" } }; }+ export const initReactI18next = { type: "3rdParty", init() {} };+ `,+ },+ });+ const { default: TranscriptionItem } = await vite.ssrLoadModule(+ "/components/ui/TranscriptionItem.tsx"+ );+ return TranscriptionItem;+}++const render = (TranscriptionItem, item) =>+ renderToStaticMarkup(+ React.createElement(TranscriptionItem, { item, onCopy() {}, onDelete() {} })+ );++test("a failed row renders its kept transcript and names the failed edit", async (t) => {+ const TranscriptionItem = await loadTranscriptionItem(t);++ const kept = render(TranscriptionItem, row({ text: TRANSCRIPT, raw_text: TRANSCRIPT }));+ assert.match(kept, new RegExp(`<p dir="auto"[^>]*>${TRANSCRIPT}</p>`));+ assert.match(kept, /controlPanel\.history\.editFailedTranscriptKept/);+ assert.doesNotMatch(kept, /controlPanel\.history\.transcriptionFailed/);+ assert.match(kept, /aria-label="controlPanel\.history\.copyText"/);++ for (const text of ["", " \n "]) {+ const empty = render(TranscriptionItem, row({ text }));+ assert.match(empty, /controlPanel\.history\.transcriptionFailed/);+ assert.doesNotMatch(empty, /dir="auto"/);+ assert.doesNotMatch(empty, /controlPanel\.history\.copyText/);+ }+});++test("a kept-transcript row's key error points at the Voice Assistant settings", async (t) => {+ const TranscriptionItem = await loadTranscriptionItem(t);++ const kept = render(+ TranscriptionItem,+ row({ text: TRANSCRIPT, raw_text: TRANSCRIPT, error_code: "PROVIDER_AUTH_FAILED" })+ );+ assert.match(kept, /controlPanel\.history\.failedCtaAiSettings/);+ assert.doesNotMatch(kept, /controlPanel\.history\.failedCtaSettings"/);+ assert.doesNotMatch(kept, /failedCtaAndRetry/);+ // The hints stay above the transcript, which can run to thousands of words.+ assert.ok(kept.indexOf("failedCtaAiSettings") < kept.indexOf(TRANSCRIPT));++ const empty = render(TranscriptionItem, row({ error_code: "PROVIDER_AUTH_FAILED" }));+ assert.match(empty, /controlPanel\.history\.failedCtaSettings/);+ assert.doesNotMatch(empty, /failedCtaAiSettings/);+});++test("copy and the settings hint act on the kept transcript row", async (t) => {+ const TranscriptionItem = await loadTranscriptionItem(t);+ const container = installInteractiveDom(t);+ const root = createRoot(container);+ const copied = [];+ const opened = [];++ await React.act(async () =>+ root.render(+ React.createElement(TranscriptionItem, {+ item: row({ text: TRANSCRIPT, raw_text: TRANSCRIPT, error_code: "INVALID_KEY" }),+ onCopy: (text) => copied.push(text),+ onDelete() {},+ onOpenSettings: (section) => opened.push(section),+ })+ )+ );++ const click = (element) =>+ React.act(async () =>+ element.dispatchEvent({ type: "click", bubbles: true, button: 0, preventDefault() {} })+ );+ const button = (predicate) =>+ findElement(container, (element) => element.tagName === "BUTTON" && predicate(element));++ await click(button((el) => el.getAttribute("aria-label") === "controlPanel.history.copyText"));+ assert.deepEqual(copied, [TRANSCRIPT]);++ await click(button((el) => el.textContent === "controlPanel.history.failedCtaAiSettings"));+ assert.deepEqual(opened, ["dictationAgent"]);++ await React.act(async () => root.unmount());+});diff --git a/test/helpers/audioManagerFailedAgentRoute.test.js b/test/helpers/audioManagerFailedAgentRoute.test.jsnew file mode 100644index 000000000..f829371df--- /dev/null+++ b/test/helpers/audioManagerFailedAgentRoute.test.js@@ -0,0 +1,223 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const { loadAudioManager } = require("./harness/audioManager");++const TRANSCRIPT = "Nova, this is a long note about the quarterly plan.";++// The STT response (HTTP for BYOK, cloudTranscribe for Cloud) and the OS+// selection capture are stubbed, along with the harness's settings, service+// and endpoint seams. The real processAudio -> provider -> agent route ->+// processAgentCommand -> pipeline catch -> saveFailedTranscription chain runs.+async function runAgentDictation(+ t,+ { sttResponse, settings = {}, electronAPI = {}, onManager = () => {} }+) {+ const originalContext = globalThis.OfflineAudioContext;+ globalThis.OfflineAudioContext = class {+ decodeAudioData() {+ const samples = new Float32Array(8);+ return Promise.resolve({+ sampleRate: 16000,+ numberOfChannels: 1,+ getChannelData: () => samples,+ });+ }+ };+ t.after(() => {+ if (originalContext === undefined) delete globalThis.OfflineAudioContext;+ else globalThis.OfflineAudioContext = originalContext;+ });++ const { window, createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-failed-agent-route-test-",+ settingsKey: "__failedAgentRouteSettings",+ settings: {+ useLocalWhisper: false,+ cloudTranscriptionMode: "byok",+ cloudTranscriptionProvider: "custom",+ cloudTranscriptionBaseUrl: "https://stt.example.com/v1",+ cloudTranscriptionModel: "whisper-1",+ allowLocalFallback: false,+ dataRetentionEnabled: true,+ audioRetentionDays: 0,+ useDictationAgent: true,+ dictationAgentMode: "local",+ dictationAgentModel: "local-model",+ ...settings,+ },+ mockModules: {+ "/services/SyncService.js": "export const syncService = { debouncedPush() {} };",+ "/services/ReasoningService":+ "export default class ReasoningService { static cancelAllRequests() {} static async isAvailable() { return true; } }",+ "/config/prompts": "export const resolvePrompt = () => 'agent prompt';",+ },+ });+ window.localStorage.setItem("agentName", "Nova");++ const saved = [];+ const errors = [];+ window.electronAPI = {+ // The OS cannot verify the selection: neither "selected" nor caret/standalone.+ captureSelectedText: async () => ({ status: "error" }),+ saveTranscription: async (...args) => {+ saved.push(args);+ return { id: 1 };+ },+ ...electronAPI,+ };+ if (sttResponse) t.mock.method(globalThis, "fetch", async () => sttResponse());++ const audio = new Blob(["synthetic audio"], { type: "audio/webm" });+ const manager = createManager({+ isProcessing: true,+ lastAudioBlob: audio,+ _processingCancellationGeneration: 0,+ _streamingCancellationGeneration: 0,+ _streamingStopPromise: null,+ _activeTranscriptionAbortController: null,+ _localSpeechGateState: null,+ getEffectiveSttLanguage: () => "auto",+ getTranscriptionModel: () => "whisper-1",+ getAPIKey: async () => "test-key",+ getTranscriptionEndpoint: () => "https://stt.example.com/v1/audio/transcriptions",+ getWhisperPrompt: () => null,+ isDictionaryEcho: () => false,+ onStateChange() {},+ onError: (error) => errors.push(error),+ });+ onManager(manager);++ await manager.processAudio(audio);++ return { saved, errors };+}++const sttOk = () => new Response(JSON.stringify({ text: TRANSCRIPT }), { status: 200 });++test("a transcript that succeeded is not lost when the agent selection edit fails", async (t) => {+ const { saved, errors } = await runAgentDictation(t, { sttResponse: sttOk });++ assert.equal(errors[0]?.code, "SELECTION_EDIT_CAPTURE_FAILED", "the edit failure is reported");+ assert.equal(errors[0]?.transcript, TRANSCRIPT, "the failure pill offers the transcript");+ assert.equal(saved.length, 1, "one history entry is saved");+ const [text, rawText, options] = saved[0];+ assert.equal(text, TRANSCRIPT, "the transcribed text is kept in the saved entry");+ assert.equal(rawText, TRANSCRIPT, "the transcribed text is kept as the raw transcript");+ assert.equal(options.status, "failed");+ assert.equal(options.errorCode, "SELECTION_EDIT_CAPTURE_FAILED");+});++test("an OpenWhispr Cloud transcript is kept under Cloud's client id when the edit fails", async (t) => {+ const onLine = Object.getOwnPropertyDescriptor(globalThis.navigator, "onLine");+ Object.defineProperty(globalThis.navigator, "onLine", { value: true, configurable: true });+ t.after(() => {+ if (onLine) Object.defineProperty(globalThis.navigator, "onLine", onLine);+ else delete globalThis.navigator.onLine;+ });++ const { saved, errors } = await runAgentDictation(t, {+ settings: { cloudTranscriptionMode: "openwhispr", isSignedIn: true },+ electronAPI: {+ cloudTranscribe: async () => ({+ success: true,+ text: TRANSCRIPT,+ clientTranscriptionId: "cloud-client-id",+ }),+ },+ });++ assert.equal(errors[0]?.code, "SELECTION_EDIT_CAPTURE_FAILED");+ assert.equal(errors[0]?.transcript, TRANSCRIPT);+ assert.equal(saved.length, 1);+ const [text, rawText, options] = saved[0];+ assert.equal(text, TRANSCRIPT);+ assert.equal(rawText, TRANSCRIPT);+ assert.equal(options.status, "failed");+ // Cloud already holds this transcription's row; a later retry syncs onto it.+ assert.equal(options.clientTranscriptionId, "cloud-client-id");+});++test("the kept transcript never serializes with the error", async (t) => {+ let thrown;+ await runAgentDictation(t, {+ sttResponse: sttOk,+ onManager(manager) {+ const processTranscription = manager.processTranscription.bind(manager);+ manager.processTranscription = async (...args) => {+ try {+ return await processTranscription(...args);+ } catch (error) {+ thrown = error;+ throw error;+ }+ };+ },+ });++ assert.equal(thrown?.transcript, TRANSCRIPT);+ // The logger spreads a top-level error and JSON-encodes nested ones.+ assert.equal(Object.keys(thrown).includes("transcript"), false);+ assert.doesNotMatch(JSON.stringify({ ...thrown, nested: { error: thrown } }), /quarterly plan/);+});++test("a dictation cancelled during the selection edit saves nothing", async (t) => {+ let manager;+ const { saved, errors } = await runAgentDictation(t, {+ sttResponse: sttOk,+ onManager: (created) => {+ manager = created;+ },+ electronAPI: {+ captureSelectedText: async () => {+ manager._processingCancellationGeneration += 1;+ return { status: "error" };+ },+ },+ });++ assert.equal(saved.length, 0);+ assert.equal(errors.length, 0);+});++test("a failure before any transcript exists still saves empty text", async (t) => {+ const { saved, errors } = await runAgentDictation(t, {+ sttResponse: () =>+ new Response(JSON.stringify({ error: { message: "boom" } }), { status: 500 }),+ });++ assert.equal(errors[0]?.code, "PROVIDER_UNAVAILABLE", "the STT failure is what is reported");+ assert.equal(errors[0]?.transcript, undefined);+ assert.equal(saved.length, 1, "one history entry is saved");+ const [text, rawText, options] = saved[0];+ assert.equal(text, "");+ assert.equal(rawText, null);+ assert.equal(options.status, "failed");+ assert.equal("clientTranscriptionId" in options, false);+});++test("only a selection edit failure carries the transcript out", async (t) => {+ const { createManager } = await loadAudioManager(t, {+ cachePrefix: "openwhispr-failed-agent-route-test-",+ settingsKey: "__failedAgentRouteSettings",+ settings: {},+ mockModules: {+ "/services/SyncService.js": "export const syncService = { debouncedPush() {} };",+ },+ });+ const manager = createManager({});+ // A cached rejection (opencc-js failing to load) is one object shared by+ // every later dictation, so it must never pick up the first one's text.+ const shared = new Error("opencc-js failed to load");+ manager.processTranscriptionCore = async () => {+ throw shared;+ };+ await assert.rejects(manager.processTranscription(TRANSCRIPT, "openai"), shared);+ assert.equal(shared.transcript, undefined);++ const editFailure = Object.assign(new Error("edit failed"), { selectionEditFatal: true });+ manager.processTranscriptionCore = async () => {+ throw editFailure;+ };+ await assert.rejects(manager.processTranscription(` ${TRANSCRIPT} `, "openai"), editFailure);+ assert.equal(editFailure.transcript, TRANSCRIPT);+});diff --git a/test/helpers/audioManagerStreamingFinalization.test.js b/test/helpers/audioManagerStreamingFinalization.test.jsindex fff23ee3f..27d2569e6 100644--- a/test/helpers/audioManagerStreamingFinalization.test.js+++ b/test/helpers/audioManagerStreamingFinalization.test.js@@ -102,14 +102,23 @@ test("streamed selection failures keep local error parameters and recovery detaimanager.processAgentCommand = async () => {throw Object.assign(new Error("too long"), fields, { selectionEditFatal: true });};+ const saved = [];+ manager.saveFailedTranscription = async (...args) => {+ saved.push(args);+ };manager.onError = (error) => errors.push(error);manager.onTranscriptionComplete = (result) => published.push(result);assert.equal(await manager.stopStreamingRecording(), false);assert.equal(errors.length, 1);for (const [key, value] of Object.entries(fields)) assert.deepEqual(errors[0][key], value);assert.equal(errors[0].selectionEditFatal, true);+ assert.equal(errors[0].transcript, "replace this");assert.deepEqual(published, []);assert.equal(manager.pendingSelectionEdit, null);+ // The streamed transcript is kept in a failed history entry, as batch keeps it (#2676).+ assert.equal(saved.length, 1);+ assert.equal(saved[0][1], "CONTEXT_TOO_LARGE");+ assert.deepEqual(saved[0][3], { transcript: "replace this" });});test("streaming finalization is immediately processing and cannot start another session", async (t) => {@@ -680,6 +689,42 @@ test("a no-final stream whose Cloud upload finds no speech keeps the recording qassert.deepEqual(completions, [{ success: true, text: "" }]);});+test("a no-final stream whose upload transcribed but failed its selection edit keeps the text", async (t) => {+ const AudioManager = await loadManagerClass(t);+ globalThis.__streamingFinalizationSettings = {+ ...globalThis.__streamingFinalizationSettings,+ cloudTranscriptionMode: "openwhispr",+ isSignedIn: true,+ };+ const { manager } = createFinalizingManager(AudioManager);+ manager.recordingStartTime = Date.now() - 5000;+ manager.mergeRecordedSegments = async () => new Blob([new Uint8Array(100)]);+ const saved = [];+ const errors = [];+ manager.saveFailedTranscription = (...args) => saved.push(args);+ manager.onError = (error) => errors.push(error);+ manager.processWithOpenWhisprCloud = async () => {+ const error = Object.assign(new Error("Selection edit failed"), {+ selectionEditFatal: true,+ code: "SELECTION_EDIT_CAPTURE_FAILED",+ });+ Object.defineProperty(error, "transcript", { value: "Fallback text" });+ throw error;+ };++ await manager.stopStreamingRecording();++ // Unlike a real transcription failure here, it is reported and kept as batch's is.+ assert.deepEqual(+ errors.map(({ code, transcript }) => [code, transcript]),+ [["SELECTION_EDIT_CAPTURE_FAILED", "Fallback text"]]+ );+ assert.deepEqual(+ saved.map((args) => [args[1], args[3].transcript]),+ [["SELECTION_EDIT_CAPTURE_FAILED", "Fallback text"]]+ );+});+test("Orukeet uses the acknowledged final even if the transcript event is delayed", async (t) => {const AudioManager = await loadManagerClass(t);const { manager } = createFinalizingManager(AudioManager);@@ -1795,6 +1840,31 @@ test("an empty Orukeet final with a confident unsupported estimate still re-tranassert.equal(usage.length, 0);});+test("a language re-transcription whose selection edit fails keeps Cloud's transcript", async (t) => {+ const AudioManager = await loadManagerClass(t);+ const saved = [];+ const { published, errors } = await stopManagedDictation(AudioManager, {+ final: JA_FINAL,+ upload: async () => {+ const error = Object.assign(new Error("Selection edit failed"), {+ selectionEditFatal: true,+ code: "SELECTION_EDIT_REASONING_FAILED",+ });+ // What processWithOpenWhisprCloud attaches before rethrowing.+ Object.defineProperty(error, "transcript", { value: "明日の会議" });+ Object.defineProperty(error, "transcriptClientId", { value: "cloud-client-id" });+ throw error;+ },+ overrides: { saveFailedTranscription: (...args) => saved.push(args) },+ });+ assert.equal(errors[0].transcript, "明日の会議");+ assert.deepEqual(+ saved.map((args) => args[3]),+ [{ transcript: "明日の会議", clientTranscriptionId: "cloud-client-id" }]+ );+ assert.deepEqual(published, []);+});+test("a selection edit that fails during the language re-transcription surfaces its error", async (t) => {const AudioManager = await loadManagerClass(t);const selectionEditFailure = () =>diff --git a/test/helpers/syncServiceTranscriptions.test.js b/test/helpers/syncServiceTranscriptions.test.jsnew file mode 100644index 000000000..73e2ba523--- /dev/null+++ b/test/helpers/syncServiceTranscriptions.test.js@@ -0,0 +1,76 @@+// Transcription half of SyncService over a real DatabaseManager, with only the+// HTTP boundary faked. A failed entry can keep the transcript a later step+// could not process (#2676); it stays on this device until a retry completes+// it, so other devices and the server never hold a failed copy that a retry+// here would leave behind; the next sync pass pushes the completed row.++const test = require("node:test");+const assert = require("node:assert/strict");++const { createDb } = require("./harness/db.js");+const {+ installBrowserGlobals,+ resetBrowserGlobals,+ enableSync,+ establishValidatedAuth,+ stopSyncTimers,+ window: windowStub,+} = require("./harness/browserGlobals.js");+const { createElectronApi } = require("./harness/electronApiBridge.js");+const { createFakeCloud } = require("./harness/fakeCloud.js");+const { SyncService } = require("../../src/services/SyncService.ts");++async function setup(t) {+ const db = createDb(t);+ if (!db) return null;+ resetBrowserGlobals();+ installBrowserGlobals();+ enableSync();+ const cloud = createFakeCloud();+ windowStub.electronAPI = createElectronApi(db, { cloud });+ await establishValidatedAuth();+ const service = new SyncService();+ t.after(() => stopSyncTimers(service));+ return { db, cloud, service };+}++const pushedTexts = (cloud) => [+ ...cloud.logFor("/api/transcriptions/create").map((call) => [call.body.text, call.body.status]),+ ...cloud+ .logFor("/api/transcriptions/batch-create")+ .flatMap((call) => call.body.transcriptions.map((row) => [row.text, row.status])),+];++test("a failed entry with a kept transcript syncs only once a retry completes it", async (t) => {+ const ctx = await setup(t);+ if (!ctx) return;+ const { db, cloud, service } = ctx;++ const { id } = db.saveTranscription("kept text", "kept text", {+ status: "failed",+ errorMessage: "Selection edit failed",+ errorCode: "SELECTION_EDIT_CAPTURE_FAILED",+ clientTranscriptionId: "cloud-client-id",+ });+ db.saveTranscription("done", "done");++ await service.pushEntity("transcription", id);+ await service.syncAll(true);+ assert.deepEqual(pushedTexts(cloud), [["done", "completed"]]);+ assert.equal(db.getTranscriptionById(id).cloud_id, null);++ // Retry overwrites the text and completes the row; the next sync pushes it.+ db.updateTranscriptionText(id, "retried text", "retried text");+ db.updateTranscriptionStatus(id, "completed");+ await service.syncAll(true);++ const retried = cloud+ .logFor("/api/transcriptions/batch-create")+ .flatMap((call) => call.body.transcriptions)+ .filter((row) => row.client_transcription_id === "cloud-client-id");+ assert.deepEqual(+ retried.map(({ text, status }) => [text, status]),+ [["retried text", "completed"]]+ );+ assert.ok(db.getTranscriptionById(id).cloud_id);+});diff --git a/test/helpers/transcriptionFailureOutcome.test.js b/test/helpers/transcriptionFailureOutcome.test.jsindex 581b260d4..69bebe726 100644--- a/test/helpers/transcriptionFailureOutcome.test.js+++ b/test/helpers/transcriptionFailureOutcome.test.js@@ -28,3 +28,14 @@ test("an unclassified failure keeps today's description", async () => {assert.equal(report.description, "Transcription failed: boom");assert.equal(report.title, "Transcription Error");});++test("a transcript that outlived the failure reaches the pill", async () => {+ const { transcriptionFailureOutcome } = await load();+ const error = Object.assign(new Error("Selection edit failed"), {+ selectionEditFatal: true,+ code: "SELECTION_EDIT_CAPTURE_FAILED",+ });+ assert.equal("transcript" in transcriptionFailureOutcome(error).report, false);+ Object.defineProperty(error, "transcript", { value: "kept text" });+ assert.equal(transcriptionFailureOutcome(error).report.transcript, "kept text");+});