Skip to content

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

fix(cleanup): fail truncated cleanup replies instead of pasting them (#2130)

void1a0eafa61b9d
diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsx
index 6435f9792..74ca937af 100644
--- a/src/components/ControlPanel.tsx
+++ b/src/components/ControlPanel.tsx
@@ -648,12 +648,22 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
settings.translationSourceLanguage,
settings.translationTargetLanguage
),
- onCleanupError: (cleanupError: Error) =>
+ onCleanupError: (cleanupError: Error & { messageKey?: string }) => {
logger.warn(
"Cleanup step failed in translation chain, translating raw transcript",
{ error: cleanupError.message },
"transcription"
- ),
+ );
+ // The chain still translates the raw transcript, so say why cleanup
+ // was dropped rather than reporting a clean success (#2091).
+ toast({
+ title: t("app.toasts.cleanupFailed.title"),
+ description: cleanupError.messageKey
+ ? t(cleanupError.messageKey)
+ : cleanupError.message,
+ variant: "destructive",
+ });
+ },
onEmptyTranslate: () =>
logger.warn(
"Translation step returned empty text, keeping previous text",
@@ -703,6 +713,7 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
const agentName = getAgentName();
const reasonedText = await ReasoningService.processText(rawText, model, agentName, {
disableThinking: getSettings().cleanupDisableThinking,
+ requireCompleteOutput: true,
});
if (hasTextContent(reasonedText) && reasonedText !== rawText) {
const updated = await window.electronAPI.updateTranscriptionText(
@@ -715,8 +726,15 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelPro
}
}
}
- } catch {
- // Reasoning failed — keep the raw STT result
+ } catch (cleanupError) {
+ // The row keeps its raw transcript, so the retry must not look like it
+ // cleaned anything — report why, the way dictation does (#2091).
+ const failure = cleanupError as Error & { messageKey?: string };
+ toast({
+ title: t("app.toasts.cleanupFailed.title"),
+ description: failure.messageKey ? t(failure.messageKey) : failure.message,
+ variant: "destructive",
+ });
}
}
diff --git a/src/config/constants.ts b/src/config/constants.ts
index 6b1d035da..e2898e604 100644
--- a/src/config/constants.ts
+++ b/src/config/constants.ts
@@ -147,8 +147,6 @@ export const TOKEN_LIMITS = {
MAX_TOKENS: 2048,
MIN_TOKENS_ANTHROPIC: 100,
MAX_TOKENS_ANTHROPIC: 4096,
- MIN_TOKENS_GEMINI: 100,
- MAX_TOKENS_GEMINI: 8192,
TOKEN_MULTIPLIER: 2, // text.length * multiplier
REASONING_CONTEXT_SIZE: 4096,
} as const;
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index e263e9380..c5de5adc5 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -246,18 +246,24 @@ function resolveReasoningRoute(
"transcription"
);
}
+ // Shared by the cleanup route and the translation chain's cleanup step. Cleanup is a
+ // deterministic transform: pass temperature 0 explicitly, because the IPC-bridged
+ // providers (local bridge, Anthropic, enterprise) otherwise apply their own default.
+ // A truncated reply must fail rather than replace the dictation with its first part:
+ // the cleanup route pastes the raw transcript and the chain translates it, and both
+ // raise the cleanup-failed toast (#2091).
+ const cleanupConfig = {
+ inferenceScope: /** @type {const} */ ("dictationCleanup"),
+ disableThinking: settings.cleanupDisableThinking,
+ temperature: 0,
+ requireCompleteOutput: true,
+ };
if (kind === "translation") {
return {
kind: "translation",
model: translation.model,
cleanupReachable,
- cleanupConfig: {
- inferenceScope: /** @type {const} */ ("dictationCleanup"),
- disableThinking: settings.cleanupDisableThinking,
- // The chain's cleanup step is the same deterministic transform — see
- // the cleanup route below for why the value has to be explicit.
- temperature: 0,
- },
+ cleanupConfig,
config: {
...translation.config,
systemPrompt: resolvePrompt("translate", {
@@ -315,16 +321,7 @@ function resolveReasoningRoute(
};
}
if (kind === "cleanup") {
- return {
- kind: "cleanup",
- config: {
- inferenceScope: /** @type {const} */ ("dictationCleanup"),
- disableThinking: settings.cleanupDisableThinking,
- // Cleanup is a deterministic transform: pass 0 explicitly, because the IPC-bridged
- // providers (local bridge, Anthropic, enterprise) otherwise apply their own default.
- temperature: 0,
- },
- };
+ return { kind: "cleanup", config: cleanupConfig };
}
return { kind: "skip" };
}
@@ -2968,6 +2965,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ ...(extra || {}), error: cleanupError.message },
channel
);
+ // The chain translates the raw transcript, so the dropped cleanup has to
+ // surface the same toast the cleanup route raises (#2091).
+ this.pendingCleanupFailure = cleanupFailureFromError(cleanupError);
},
onEmptyTranslate: () => {
const { channel } = cleanup.log || {};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index a02e82d53..1ba2cf314 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -593,6 +593,11 @@ async function chunkedCloudTranscribe({
}
}
+// Cleanup toast wording for replies the main-process providers reject; mirror
+// TRUNCATED_/EMPTY_OUTPUT_MESSAGE_KEY in services/ai/chatRequestBody.ts (#2091).
+const CLEANUP_TRUNCATED_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupTruncated";
+const CLEANUP_EMPTY_REPLY_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupEmptyReply";
+
class IPCHandlers {
constructor(managers) {
this.environmentManager = managers.environmentManager;
@@ -4887,7 +4892,9 @@ class IPCHandlers {
config?.requireCompleteOutput &&
["length", "max-tokens", "max_tokens"].includes(finishReason)
) {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw Object.assign(new Error("Model output was truncated"), {
+ messageKey: CLEANUP_TRUNCATED_MESSAGE_KEY,
+ });
}
return { success: true, text: (generated || "").trim() };
@@ -4907,7 +4914,9 @@ class IPCHandlers {
return {
success: false,
error: mapped.message,
- messageKey: mapped.messageKey,
+ // mapEnterpriseError matches provider failures, so a truncation falls through
+ // to its generic mapping — keep the key the throw site set.
+ messageKey: err.messageKey || mapped.messageKey,
messageParams: mapped.messageParams,
action: mapped.action,
actionKey: mapped.actionKey,
@@ -5282,16 +5291,20 @@ class IPCHandlers {
const data = await response.json();
if (config?.requireCompleteOutput && data.stop_reason === "max_tokens") {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw Object.assign(new Error("Model output was truncated"), {
+ messageKey: CLEANUP_TRUNCATED_MESSAGE_KEY,
+ });
}
const outputText = extractAnthropicText(data);
if (outputText === null) {
- throw new Error(describeMissingAnthropicText(data));
+ throw Object.assign(new Error(describeMissingAnthropicText(data)), {
+ messageKey: CLEANUP_EMPTY_REPLY_MESSAGE_KEY,
+ });
}
return { success: true, text: outputText };
} catch (error) {
debugLogger.error("Anthropic reasoning error:", error);
- return { success: false, error: error.message };
+ return { success: false, error: error.message, messageKey: error.messageKey };
}
}
);
diff --git a/src/helpers/llamaServer.js b/src/helpers/llamaServer.js
index 83fc519a5..786b9a1b3 100644
--- a/src/helpers/llamaServer.js
+++ b/src/helpers/llamaServer.js
@@ -765,7 +765,10 @@ class LlamaServerManager {
options.requireCompleteOutput &&
["length", "max_tokens"].includes(response.choices?.[0]?.finish_reason)
) {
- reject(new Error("Model output was truncated before the selection edit completed"));
+ // The renderer maps the code to the cleanup toast's wording (#2091).
+ const error = new Error("Model output was truncated");
+ error.code = "OUTPUT_TRUNCATED";
+ reject(error);
return;
}
const message = response.choices?.[0]?.message;
diff --git a/src/helpers/modelManagerBridge.js b/src/helpers/modelManagerBridge.js
index d80d4ebab..1dba615f4 100644
--- a/src/helpers/modelManagerBridge.js
+++ b/src/helpers/modelManagerBridge.js
@@ -854,6 +854,9 @@ class ModelManager {
maxContextTokens: error.maxContextTokens ?? null,
});
}
+ if (error.code === "OUTPUT_TRUNCATED") {
+ throw new ModelError(error.message, "OUTPUT_TRUNCATED", { modelId });
+ }
throw new ModelError(`Inference failed: ${error.message}`, "INFERENCE_FAILED", {
error: error.message,
});
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index 53aff1fe6..a94aca908 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -46,7 +46,9 @@
"managedRouteInvalid": "تعذر بدء التفريغ المُدار بسبب عدم تطابق في الإعدادات. أعد المحاولة أو اتصل بالمسؤول.",
"managedAuthRejected": "رُفضت بيانات اعتماد التفريغ المُدار الخاصة بمؤسستك. اتصل بالمسؤول.",
"streamingOnlyProvider": "هذا المزود يدعم التفريغ المباشر فقط. اختر مزودًا آخر لرفع الملفات وإعادة المحاولة.",
- "providerKeyMissing": "لم يتم تعيين مفتاح API لمزود التفريغ الخاص بك. أضفه في الإعدادات ← تحويل الكلام إلى نص (Speech to Text)."
+ "providerKeyMissing": "لم يتم تعيين مفتاح API لمزود التفريغ الخاص بك. أضفه في الإعدادات ← تحويل الكلام إلى نص (Speech to Text).",
+ "cleanupTruncated": "نفدت مساحة الإخراج لدى نموذج الذكاء الاصطناعي قبل أن يُكمل تنقيح إملائك.",
+ "cleanupEmptyReply": "أرجع نموذج الذكاء الاصطناعي ردًا فارغًا بدلًا من الإملاء المنقَّح."
},
"translationFallback": {
"unreachableTitle": "الترجمة غير متاحة",
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 636a7a36a..7fce22374 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "Die verwaltete Transkription konnte aufgrund einer Konfigurationsabweichung nicht gestartet werden. Versuchen Sie es erneut oder wenden Sie sich an Ihren Administrator.",
"managedAuthRejected": "Die verwalteten Transkriptions-Anmeldedaten Ihrer Organisation wurden abgelehnt. Wenden Sie sich an Ihren Administrator.",
"streamingOnlyProvider": "Dieser Anbieter unterstützt nur Live-Transkription. Wähle für Datei-Uploads und Wiederholungen einen anderen Anbieter.",
- "providerKeyMissing": "Für Ihren Transkriptionsanbieter ist kein API-Schlüssel hinterlegt. Fügen Sie ihn unter Einstellungen → Sprache zu Text hinzu."
+ "providerKeyMissing": "Für Ihren Transkriptionsanbieter ist kein API-Schlüssel hinterlegt. Fügen Sie ihn unter Einstellungen → Sprache zu Text hinzu.",
+ "cleanupTruncated": "Dem KI-Modell ging der Platz aus, bevor es dein Diktat fertig bereinigt hatte.",
+ "cleanupEmptyReply": "Das KI-Modell lieferte eine leere Antwort statt des bereinigten Diktats."
},
"translationFallback": {
"unreachableTitle": "Übersetzung nicht verfügbar",
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 54515e938..bb275fbf9 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "Managed transcription couldn't start due to a configuration mismatch. Try again or contact your administrator.",
"managedAuthRejected": "Your organization's managed transcription credentials were rejected. Contact your administrator.",
"streamingOnlyProvider": "This provider only supports live transcription. Choose another provider for file uploads and retries.",
- "providerKeyMissing": "No API key is set for your transcription provider. Add it in Settings → Speech to Text."
+ "providerKeyMissing": "No API key is set for your transcription provider. Add it in Settings → Speech to Text.",
+ "cleanupTruncated": "The AI model ran out of room before it finished cleaning up your dictation.",
+ "cleanupEmptyReply": "The AI model returned an empty reply instead of the cleaned-up dictation."
},
"translationFallback": {
"unreachableTitle": "Translation unavailable",
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index e673441e5..921e3288d 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "La transcripción gestionada no pudo iniciarse debido a una discrepancia de configuración. Inténtalo de nuevo o contacta a tu administrador.",
"managedAuthRejected": "Las credenciales de transcripción gestionada de tu organización fueron rechazadas. Contacta a tu administrador.",
"streamingOnlyProvider": "Este proveedor solo admite transcripción en directo. Elige otro proveedor para subir archivos y reintentos.",
- "providerKeyMissing": "No hay ninguna clave de API configurada para tu proveedor de transcripción. Añádela en Ajustes → Voz a texto."
+ "providerKeyMissing": "No hay ninguna clave de API configurada para tu proveedor de transcripción. Añádela en Ajustes → Voz a texto.",
+ "cleanupTruncated": "El modelo de IA se quedó sin espacio antes de terminar de limpiar tu dictado.",
+ "cleanupEmptyReply": "El modelo de IA devolvió una respuesta vacía en lugar del dictado limpio."
},
"translationFallback": {
"unreachableTitle": "Traducción no disponible",
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index dd48dbe3d..d2564cf6a 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "La transcription gérée n'a pas pu démarrer en raison d'une incohérence de configuration. Réessayez ou contactez votre administrateur.",
"managedAuthRejected": "Les identifiants de transcription gérée de votre organisation ont été refusés. Contactez votre administrateur.",
"streamingOnlyProvider": "Ce fournisseur ne prend en charge que la transcription en direct. Choisissez un autre fournisseur pour les imports de fichiers et les nouvelles tentatives.",
- "providerKeyMissing": "Aucune clé API n'est définie pour votre fournisseur de transcription. Ajoutez-la dans Réglages → Parole en texte."
+ "providerKeyMissing": "Aucune clé API n'est définie pour votre fournisseur de transcription. Ajoutez-la dans Réglages → Parole en texte.",
+ "cleanupTruncated": "Le modèle d'IA a manqué de place avant de terminer le nettoyage de votre dictée.",
+ "cleanupEmptyReply": "Le modèle d'IA a renvoyé une réponse vide au lieu de la dictée nettoyée."
},
"translationFallback": {
"unreachableTitle": "Traduction indisponible",
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 8760d10ae..18eb91c2e 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "La trascrizione gestita non è potuta partire per un'incoerenza di configurazione. Riprova o contatta l'amministratore.",
"managedAuthRejected": "Le credenziali di trascrizione gestita della tua organizzazione sono state rifiutate. Contatta l'amministratore.",
"streamingOnlyProvider": "Questo provider supporta solo la trascrizione dal vivo. Scegli un altro provider per i caricamenti di file e i nuovi tentativi.",
- "providerKeyMissing": "Nessuna chiave API impostata per il tuo provider di trascrizione. Aggiungila in Impostazioni → Da voce a testo."
+ "providerKeyMissing": "Nessuna chiave API impostata per il tuo provider di trascrizione. Aggiungila in Impostazioni → Da voce a testo.",
+ "cleanupTruncated": "Il modello IA ha esaurito lo spazio prima di finire la pulizia della dettatura.",
+ "cleanupEmptyReply": "Il modello IA ha restituito una risposta vuota invece della dettatura pulita."
},
"translationFallback": {
"unreachableTitle": "Traduzione non disponibile",
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index f39e90fa8..f42fd095b 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "設定の不一致により、マネージド文字起こしを開始できませんでした。もう一度お試しいただくか、管理者にお問い合わせください。",
"managedAuthRejected": "組織のマネージド文字起こしの認証情報が拒否されました。管理者にお問い合わせください。",
"streamingOnlyProvider": "このプロバイダーはライブ文字起こしのみに対応しています。ファイルのアップロードや再実行には別のプロバイダーを選択してください。",
- "providerKeyMissing": "文字起こしプロバイダーのAPIキーが設定されていません。設定 → 音声テキスト変換 から追加してください。"
+ "providerKeyMissing": "文字起こしプロバイダーのAPIキーが設定されていません。設定 → 音声テキスト変換 から追加してください。",
+ "cleanupTruncated": "AI モデルの出力が上限に達し、ディクテーションのクリーンアップが完了しませんでした。",
+ "cleanupEmptyReply": "AI モデルが空の応答を返したため、クリーンアップされたテキストがありません。"
},
"translationFallback": {
"unreachableTitle": "翻訳を利用できません",
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 109551e39..7de3582c6 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -891,7 +891,9 @@
"managedRouteInvalid": "A transcrição gerenciada não pôde ser iniciada devido a uma incompatibilidade de configuração. Tente novamente ou entre em contato com o administrador.",
"managedAuthRejected": "As credenciais de transcrição gerenciada da sua organização foram rejeitadas. Entre em contato com o administrador.",
"streamingOnlyProvider": "Este provedor só suporta transcrição ao vivo. Escolha outro provedor para uploads de arquivos e novas tentativas.",
- "providerKeyMissing": "Nenhuma chave de API definida para seu provedor de transcrição. Adicione-a em Configurações → Fala para texto."
+ "providerKeyMissing": "Nenhuma chave de API definida para seu provedor de transcrição. Adicione-a em Configurações → Fala para texto.",
+ "cleanupTruncated": "O modelo de IA ficou sem espaço antes de terminar a limpeza do seu ditado.",
+ "cleanupEmptyReply": "O modelo de IA devolveu uma resposta vazia em vez do ditado limpo."
},
"translationFallback": {
"unreachableTitle": "Tradução indisponível",
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 9e50ca88c..4cf5b95f8 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "Не удалось запустить управляемую транскрипцию из-за несоответствия конфигурации. Повторите попытку или обратитесь к администратору.",
"managedAuthRejected": "Учётные данные управляемой транскрипции вашей организации отклонены. Обратитесь к администратору.",
"streamingOnlyProvider": "Этот провайдер поддерживает только транскрипцию в реальном времени. Для загрузки файлов и повторных попыток выберите другого провайдера.",
- "providerKeyMissing": "Для вашего провайдера транскрипции не задан API-ключ. Добавьте его в Настройках → Речь в текст."
+ "providerKeyMissing": "Для вашего провайдера транскрипции не задан API-ключ. Добавьте его в Настройках → Речь в текст.",
+ "cleanupTruncated": "У ИИ-модели закончилось место, и она не завершила очистку диктовки.",
+ "cleanupEmptyReply": "ИИ-модель вернула пустой ответ вместо очищенной диктовки."
},
"translationFallback": {
"unreachableTitle": "Перевод недоступен",
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 26ad074a6..683e7b6ff 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "由于配置不匹配,托管转录无法启动。请重试或联系管理员。",
"managedAuthRejected": "您组织的托管转录凭证被拒绝。请联系管理员。",
"streamingOnlyProvider": "该服务商仅支持实时转录。请为文件上传和重试选择其他服务商。",
- "providerKeyMissing": "尚未为您的转录服务商设置 API 密钥。请在“设置 → 语音转文字”中添加。"
+ "providerKeyMissing": "尚未为您的转录服务商设置 API 密钥。请在“设置 → 语音转文字”中添加。",
+ "cleanupTruncated": "AI 模型的输出长度达到上限,未能完成听写清理。",
+ "cleanupEmptyReply": "AI 模型返回了空响应,没有生成清理后的文本。"
},
"translationFallback": {
"unreachableTitle": "翻译不可用",
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index d111fe4c2..6a7eacf71 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -912,7 +912,9 @@
"managedRouteInvalid": "由於設定不符,託管轉錄無法啟動。請重試或聯絡管理員。",
"managedAuthRejected": "您組織的託管轉錄憑證遭拒。請聯絡管理員。",
"streamingOnlyProvider": "此服務商僅支援即時轉錄。請為檔案上傳與重試選擇其他服務商。",
- "providerKeyMissing": "尚未為您的轉錄服務商設定 API 金鑰。請在「設定 → 語音轉文字」中新增。"
+ "providerKeyMissing": "尚未為您的轉錄服務商設定 API 金鑰。請在「設定 → 語音轉文字」中新增。",
+ "cleanupTruncated": "AI 模型的輸出長度達到上限,未能完成聽寫清理。",
+ "cleanupEmptyReply": "AI 模型傳回空白回應,沒有產生清理後的文字。"
},
"translationFallback": {
"unreachableTitle": "翻譯無法使用",
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 13b4bfcc3..96362e592 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -31,6 +31,7 @@ import {
emptyResponseError,
fetchWithParamFallback,
isTruncatedFinishReason,
+ truncatedOutputError,
} from "./ai/chatRequestBody";
import { getModelFamilyConstraints } from "./ai/modelFamilyConstraints";
import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
@@ -416,7 +417,7 @@ class ReasoningService extends BaseReasoningService {
const choice = response.choices[0];
if (config.requireCompleteOutput && isTruncatedFinishReason(choice?.finish_reason)) {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw truncatedOutputError();
}
// Reasoning models leak <think> blocks into non-streamed output; strip them
// unless the user explicitly enabled thinking (same default as streaming).
diff --git a/src/services/ai/chatRequestBody.ts b/src/services/ai/chatRequestBody.ts
index 2599ba055..8dd2b80cf 100644
--- a/src/services/ai/chatRequestBody.ts
+++ b/src/services/ai/chatRequestBody.ts
@@ -70,6 +70,29 @@ export function isTruncatedFinishReason(reason: unknown): boolean {
return reason === "length" || reason === "max_tokens";
}
+/**
+ * Dictation cleanup renders these errors as the toast title, so they carry the key
+ * the renderer translates. Anthropic and enterprise attach the same key on the
+ * main-process side; local llama reports a code that localInferenceError.ts maps.
+ */
+export const TRUNCATED_OUTPUT_MESSAGE_KEY =
+ "hooks.audioRecording.errorDescriptions.cleanupTruncated";
+const EMPTY_OUTPUT_MESSAGE_KEY = "hooks.audioRecording.errorDescriptions.cleanupEmptyReply";
+
+/** Output cut off at the token cap; providers may pass their own wording for the logs. */
+export function truncatedOutputError(
+ message = "Model output was truncated"
+): Error & { messageKey: string } {
+ return Object.assign(new Error(message), { messageKey: TRUNCATED_OUTPUT_MESSAGE_KEY });
+}
+
+/** A reply with no text at all; providers pass their own wording for the logs. */
+export function emptyOutputError(
+ message = "Model returned an empty response"
+): Error & { messageKey: string } {
+ return Object.assign(new Error(message), { messageKey: EMPTY_OUTPUT_MESSAGE_KEY });
+}
+
/**
* Error for a completion that produced no text, or null when the caller may
* echo its input instead. Only the default cleanup transform (no systemPrompt)
@@ -80,10 +103,10 @@ export function emptyResponseError(
config: ReasoningConfig,
responseIncomplete: boolean
): Error | null {
- if (config.requireCompleteOutput) return new Error("Model returned an empty selection edit");
if (responseIncomplete) {
- return new Error("Model ran out of output tokens before producing a response");
+ return truncatedOutputError("Model ran out of output tokens before producing a response");
}
+ if (config.requireCompleteOutput) return emptyOutputError();
if (config.systemPrompt) return new Error(`${providerName} returned empty response`);
return null;
}
diff --git a/src/services/ai/inferenceProviders/anthropic.ts b/src/services/ai/inferenceProviders/anthropic.ts
index 029ce4937..0cd540ed8 100644
--- a/src/services/ai/inferenceProviders/anthropic.ts
+++ b/src/services/ai/inferenceProviders/anthropic.ts
@@ -36,7 +36,8 @@ export const anthropicProvider: InferenceProvider = {
if (!result.success) {
logger.logReasoning("ANTHROPIC_ERROR", { model, processingTimeMs, error: result.error });
- throw new Error(result.error);
+ // Carry the main process's i18n key (a truncated cleanup) so the toast can translate it.
+ throw Object.assign(new Error(result.error), { messageKey: result.messageKey });
}
logger.logReasoning("ANTHROPIC_SUCCESS", {
diff --git a/src/services/ai/inferenceProviders/gemini.ts b/src/services/ai/inferenceProviders/gemini.ts
index 4ea83b6a1..41bf689dd 100644
--- a/src/services/ai/inferenceProviders/gemini.ts
+++ b/src/services/ai/inferenceProviders/gemini.ts
@@ -1,11 +1,12 @@
import type { InferenceProvider } from "./types";
import { getCloudModel } from "../../../models/ModelRegistry";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
-import { API_ENDPOINTS, TOKEN_LIMITS } from "../../../config/constants";
+import { API_ENDPOINTS } from "../../../config/constants";
import { getLlmRequestTimeoutSeconds } from "../../../helpers/llmRequestTimeout.js";
import { extractGeminiText } from "../../../helpers/geminiResponse.js";
import { wrapCleanupTranscript } from "../../../config/prompts";
import { extractApiErrorMessage } from "../apiErrorMessage";
+import { emptyOutputError, truncatedOutputError } from "../chatRequestBody";
import logger from "../../../utils/logger";
interface GeminiResponse {
@@ -18,7 +19,6 @@ interface GeminiResponse {
interface GeminiGenerationConfig {
temperature: number;
- maxOutputTokens: number;
thinkingConfig?: {
thinkingLevel: "minimal" | "low" | "medium" | "high";
includeThoughts: boolean;
@@ -38,20 +38,10 @@ export const geminiProvider: InferenceProvider = {
const generationConfig: GeminiGenerationConfig = {
temperature: config.temperature ?? (config.systemPrompt ? 0.3 : 0),
- // A caller's budget raises this ceiling, never lowers it: note formatting
- // pins maxTokens so the local path can price it against the context
- // window, and letting that short-circuit Gemini's own allowance halved
- // long summaries on the provider with the most room to give (#2142).
- maxOutputTokens: Math.max(
- config.maxTokens || 0,
- 2000,
- ctx.calculateMaxTokens(
- text.length,
- TOKEN_LIMITS.MIN_TOKENS_GEMINI,
- TOKEN_LIMITS.MAX_TOKENS_GEMINI,
- TOKEN_LIMITS.TOKEN_MULTIPLIER
- )
- ),
+ // No maxOutputTokens. Gemini bills thinking against it, so any budget sized
+ // for the text starved thinking models (#2091), and a caller's pinned budget
+ // is priced for the local path, not for Gemini (#2142). The model's own
+ // limit and the request timeout bound the reply.
};
if (config.disableThinking === true && getCloudModel(model)?.supportsThinking) {
@@ -140,7 +130,7 @@ export const geminiProvider: InferenceProvider = {
const candidate = response.candidates?.[0];
if (config.requireCompleteOutput && candidate?.finishReason === "MAX_TOKENS") {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw truncatedOutputError();
}
const responseText = extractGeminiText(candidate);
if (!responseText) {
@@ -149,11 +139,12 @@ export const geminiProvider: InferenceProvider = {
finishReason: candidate?.finishReason,
});
if (candidate?.finishReason === "MAX_TOKENS") {
- throw new Error(
+ // Same cause as the truncation check above: the cap hit before any text arrived.
+ throw truncatedOutputError(
"Gemini reached token limit before generating response. Try a shorter input or increase max tokens."
);
}
- throw new Error("Gemini returned empty response");
+ throw emptyOutputError("Gemini returned empty response");
}
logger.logReasoning("GEMINI_RESPONSE", {
model,
diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.ts
index 57cbb63cb..618082c28 100644
--- a/src/services/ai/inferenceProviders/openai.ts
+++ b/src/services/ai/inferenceProviders/openai.ts
@@ -10,6 +10,7 @@ import {
emptyResponseError,
fetchWithParamFallback,
isTruncatedFinishReason,
+ truncatedOutputError,
} from "../chatRequestBody";
import { detectEndpointDialect } from "../thinkingSuppressionDialects";
import { getLlmRequestTimeoutSeconds } from "../../../helpers/llmRequestTimeout.js";
@@ -342,7 +343,7 @@ export const openaiProvider: InferenceProvider = {
!!response?.incomplete_details ||
response?.choices?.some((choice: any) => isTruncatedFinishReason(choice?.finish_reason));
if (config.requireCompleteOutput && responseIncomplete) {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw truncatedOutputError();
}
logger.logReasoning("OPENAI_RAW_RESPONSE", {
diff --git a/src/services/ai/inferenceProviders/tinfoil.ts b/src/services/ai/inferenceProviders/tinfoil.ts
index b5be6d267..e8d096aaf 100644
--- a/src/services/ai/inferenceProviders/tinfoil.ts
+++ b/src/services/ai/inferenceProviders/tinfoil.ts
@@ -6,6 +6,7 @@ import {
applyChatCompletionsParams,
emptyResponseError,
isTruncatedFinishReason,
+ truncatedOutputError,
} from "../chatRequestBody";
import { getTinfoilChatClient } from "../tinfoilClient";
import { getLlmRequestTimeoutSeconds } from "../../../helpers/llmRequestTimeout.js";
@@ -64,7 +65,7 @@ export const tinfoilProvider: InferenceProvider = {
isTruncatedFinishReason(choice?.finish_reason)
);
if (config.requireCompleteOutput && responseIncomplete) {
- throw new Error("Model output was truncated before the selection edit completed");
+ throw truncatedOutputError();
}
logger.logReasoning("TINFOIL_RESPONSE", {
diff --git a/src/types/electron.ts b/src/types/electron.ts
index ecfc237e9..88e8f0b96 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -1857,7 +1857,7 @@ declare global {
modelId: string,
agentName: string | null,
config: any
- ) => Promise<{ success: boolean; text?: string; error?: string }>;
+ ) => Promise<{ success: boolean; text?: string; error?: string; messageKey?: string }>;
// Enterprise reasoning (Bedrock, Azure, Vertex)
processEnterpriseReasoning: (
diff --git a/src/utils/localInferenceError.ts b/src/utils/localInferenceError.ts
index 05ff11437..d4cdaf59e 100644
--- a/src/utils/localInferenceError.ts
+++ b/src/utils/localInferenceError.ts
@@ -9,6 +9,8 @@
* Before #2142 the raw llama.cpp 400 body was shown to the user verbatim.
*/
+import { TRUNCATED_OUTPUT_MESSAGE_KEY } from "../services/ai/chatRequestBody";
+
export interface LocalInferenceFailure {
error?: string;
code?: string;
@@ -55,6 +57,9 @@ export function buildLocalInferenceError(result: LocalInferenceFailure): LocalIn
// name crosses, so there is nothing here that could reach the user raw.
error.messageKey = "models.errors.localServerUnavailable";
error.messageParams = { model: typeof details.modelName === "string" ? details.modelName : "" };
+ } else if (result.code === "OUTPUT_TRUNCATED") {
+ // Same toast the cloud providers raise when a cleanup reply hits the token cap (#2091).
+ error.messageKey = TRUNCATED_OUTPUT_MESSAGE_KEY;
}
return error;
diff --git a/test/helpers/audioManagerCleanupFallback.test.js b/test/helpers/audioManagerCleanupFallback.test.js
index a1e7db7d3..275c6200c 100644
--- a/test/helpers/audioManagerCleanupFallback.test.js
+++ b/test/helpers/audioManagerCleanupFallback.test.js
@@ -101,6 +101,88 @@ test("cleanup failure details ride the raw result instead of notifying before pa
assert.deepEqual(manager._takePendingResultExtras(), {});
});
+// The chain translates the raw transcript when cleanup fails, so the dropped cleanup
+// has to reach the same toast the plain cleanup route raises (#2091).
+test("a truncated cleanup inside the translation chain still reports the failure", async (t) => {
+ const { createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-audio-translation-cleanup-",
+ settingsKey: "__audioTranslationCleanupSettings",
+ settings: {
+ useCleanupModel: true,
+ cleanupProvider: "gemini",
+ cleanupMode: "providers",
+ cleanupDisableThinking: true,
+ useDictationAgent: false,
+ useDictationTranslation: true,
+ translationSourceLanguage: "en",
+ translationTargetLanguage: "es",
+ preferredLanguage: "en",
+ },
+ mockModules: {
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.__audioTranslationCleanupSettings;
+ export const getEffectiveCleanupModel = () => "gemini-3-flash-preview";
+ export const selectResolvedLLMConfig = () => ({
+ mode: "providers",
+ provider: "gemini",
+ model: "gemini-3-flash-preview"
+ });
+ export const isCloudCleanupMode = () => false;
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => false;
+ export const useSettingsStore = { subscribe: () => () => {} };
+ `,
+ "/dictationAgentInference": `
+ export const resolveDictationAgentInference = () => ({
+ reachable: false, model: "", displayProvider: "none", config: {}
+ });
+ export const resolveDictationAgentVisionInference = () => ({
+ active: false, model: "", config: {}
+ });
+ `,
+ "/dictationTranslationInference": `
+ export const resolveDictationTranslationInference = () => ({
+ reachable: true,
+ model: "gemini-3-flash-preview",
+ displayProvider: "gemini",
+ config: { provider: "gemini" }
+ });
+ `,
+ "/config/prompts": `
+ export const resolvePrompt = () => "translate prompt";
+ export const appendScreenContextSuffix = (prompt) => prompt;
+ export const wrapCleanupTranscript = (text) => text;
+ export const getCleanupSystemPrompt = () => "cleanup prompt";
+ `,
+ },
+ });
+
+ const truncated = Object.assign(new Error("Model output was truncated"), {
+ messageKey: "hooks.audioRecording.errorDescriptions.cleanupTruncated",
+ });
+ const manager = createManager({
+ voiceAgentRequested: false,
+ translationRequested: true,
+ pendingCleanupFailure: null,
+ pendingAssistantConversation: null,
+ pendingSelectionEdit: null,
+ isReasoningAvailable: async () => true,
+ notifyTranslationFallback: () => {},
+ // The cleanup step is the only call in the chain that requires complete output.
+ processWithReasoningModel: async (_text, _model, _agentName, config) => {
+ if (config?.requireCompleteOutput) throw truncated;
+ return "dictado traducido";
+ },
+ });
+
+ const text = await manager.processTranscriptionCore("original dictation", "local");
+
+ assert.equal(text, "dictado traducido");
+ assert.deepEqual(manager._takePendingResultExtras(), {
+ cleanupFailure: { message: truncated.message, messageKey: truncated.messageKey },
+ });
+});
+
test("safePaste returns false when the preload reports that no text was pasted", async (t) => {
const { createManager, window } = await loadAudioManager(t, {
cachePrefix: "openwhispr-audio-cleanup-paste-outcome-",
diff --git a/test/helpers/cleanupRouteTemperature.test.js b/test/helpers/cleanupRouteConfig.test.js
similarity index 79%
rename from test/helpers/cleanupRouteTemperature.test.js
rename to test/helpers/cleanupRouteConfig.test.js
index 34db5c535..abd7ff1e2 100644
--- a/test/helpers/cleanupRouteTemperature.test.js
+++ b/test/helpers/cleanupRouteConfig.test.js
@@ -6,14 +6,16 @@ const { loadAudioManager } = require("./harness/audioManager");
// IPC-bridged providers: local llama-server (`?? 0.7`), Anthropic and
// enterprise (`?? 0.3`) read `config.temperature` and otherwise keep their own
// default. Without this the "cleanup is deterministic" rule only held on the
-// chat-completions transports and Gemini.
+// chat-completions transports and Gemini. They also require complete output, so
+// a reply cut off at the token limit fails instead of replacing the dictation
+// with its first part (#2091).
async function loadRouteResolver(t) {
const { vite } = await loadAudioManager(t, {
- cachePrefix: "openwhispr-cleanup-temperature-test-",
- settingsKey: "__cleanupTemperatureSettings",
+ cachePrefix: "openwhispr-cleanup-route-config-test-",
+ settingsKey: "__cleanupRouteConfigSettings",
mockModules: {
"/stores/settingsStore": `
- export const getSettings = () => globalThis.__cleanupTemperatureSettings;
+ export const getSettings = () => globalThis.__cleanupRouteConfigSettings;
export const getEffectiveCleanupModel = () => "cleanup-model";
export const selectResolvedLLMConfig = () => ({ model: "cleanup-model" });
export const isCloudCleanupMode = () => false;
@@ -56,7 +58,7 @@ async function loadRouteResolver(t) {
resolveReasoningRoute(text, settings, "Jarvis", voiceAgentRequested, translationRequested);
}
-test("the cleanup route pins temperature 0", async (t) => {
+test("the cleanup route pins temperature 0 and requires complete output", async (t) => {
const resolveRoute = await loadRouteResolver(t);
const route = resolveRoute("so um clean this up");
@@ -64,9 +66,10 @@ test("the cleanup route pins temperature 0", async (t) => {
assert.equal(route.kind, "cleanup");
assert.equal(route.config.inferenceScope, "dictationCleanup");
assert.equal(route.config.temperature, 0);
+ assert.equal(route.config.requireCompleteOutput, true);
});
-test("the translation chain's cleanup step pins temperature 0 too", async (t) => {
+test("the translation chain's cleanup step pins the same config", async (t) => {
const resolveRoute = await loadRouteResolver(t);
const route = resolveRoute("so um translate this", { translationRequested: true });
@@ -74,13 +77,15 @@ test("the translation chain's cleanup step pins temperature 0 too", async (t) =>
assert.equal(route.kind, "translation");
assert.equal(route.cleanupConfig.inferenceScope, "dictationCleanup");
assert.equal(route.cleanupConfig.temperature, 0);
+ assert.equal(route.cleanupConfig.requireCompleteOutput, true);
});
-test("the agent route keeps its provider default temperature", async (t) => {
+test("the agent route keeps its provider defaults", async (t) => {
const resolveRoute = await loadRouteResolver(t);
const route = resolveRoute("Jarvis, what is on my calendar", { voiceAgentRequested: true });
assert.equal(route.kind, "agent");
assert.equal(route.config.temperature, undefined);
+ assert.equal(route.config.requireCompleteOutput, undefined);
});
diff --git a/test/helpers/modelManagerContextSizing.test.js b/test/helpers/modelManagerContextSizing.test.js
index 9289946cc..af0c1aaed 100644
--- a/test/helpers/modelManagerContextSizing.test.js
+++ b/test/helpers/modelManagerContextSizing.test.js
@@ -50,7 +50,10 @@ const SHORT_PROMPT = "Clean up this sentence.";
// ~20k estimated tokens, the size that fails on main today.
const LONG_PROMPT = "word ".repeat(12000);
-async function setup(t, { tokenCount = null, totalMemoryBytes = 48 * GIB } = {}) {
+async function setup(
+ t,
+ { tokenCount = null, totalMemoryBytes = 48 * GIB, finishReason = "stop" } = {}
+) {
const home = await fs.mkdtemp(path.join(os.tmpdir(), "openwhispr-ctx-sizing-"));
electronHome = home;
t.after(() => fs.rm(home, { recursive: true, force: true }));
@@ -82,7 +85,7 @@ async function setup(t, { tokenCount = null, totalMemoryBytes = 48 * GIB } = {})
} else {
calls.completions += 1;
completionBody = JSON.parse(raw);
- payload = { choices: [{ finish_reason: "stop", message: { content: "done" } }] };
+ payload = { choices: [{ finish_reason: finishReason, message: { content: "done" } }] };
}
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(payload));
@@ -477,3 +480,17 @@ test("only Apple Silicon is treated as memory the GPU already shares", async (t)
assert.equal(discrete.reason, "gpu-cap", "an Intel Mac's GPU memory is not system memory");
assert.ok(discrete.ceiling < unified.ceiling);
});
+
+test("a reply cut off at the token cap keeps its code through the bridge", async (t) => {
+ // The bridge rewraps failures; the renderer maps this code to the cleanup toast (#2091).
+ const { modelManager, modelId } = await setup(t, { tokenCount: 40, finishReason: "length" });
+
+ await assert.rejects(
+ () => modelManager.runInference(modelId, SHORT_PROMPT, { requireCompleteOutput: true }),
+ (error) => {
+ assert.equal(error.code, "OUTPUT_TRUNCATED");
+ assert.equal(error.details.modelId, modelId);
+ return true;
+ }
+ );
+});
diff --git a/test/services/geminiProviderResponse.test.js b/test/services/geminiProviderResponse.test.js
index c69f01a1f..4c4b43dc5 100644
--- a/test/services/geminiProviderResponse.test.js
+++ b/test/services/geminiProviderResponse.test.js
@@ -32,21 +32,29 @@ function createGeminiResponse(parts, finishReason = "STOP") {
};
}
-async function callGemini(t, response, config = {}) {
+// Pass `requests` to read what the provider actually sent, not what the config asked for.
+async function callGemini(
+ t,
+ response,
+ config = {},
+ { model = "gemini-2.5-flash", requests = [] } = {}
+) {
const originalFetch = globalThis.fetch;
t.after(() => {
globalThis.fetch = originalFetch;
});
- globalThis.fetch = async () =>
- new Response(JSON.stringify(response), {
+ globalThis.fetch = async (_input, init = {}) => {
+ requests.push(JSON.parse(init.body));
+ return new Response(JSON.stringify(response), {
status: 200,
headers: { "Content-Type": "application/json" },
});
+ };
const { geminiProvider } = await load();
return geminiProvider.call({
text: "raw transcript",
- model: "gemini-2.5-flash",
+ model,
agentName: null,
config: { systemPrompt: "Clean the transcript", ...config },
ctx: providerContext,
@@ -85,36 +93,37 @@ test("Gemini provider preserves complete-output truncation errors before extract
await assert.rejects(
callGemini(t, response, { requireCompleteOutput: true }),
- /Model output was truncated before the selection edit completed/
+ /Model output was truncated/
);
});
-test("a caller's output budget cannot shrink the one Gemini would have computed", async (t) => {
- // Note formatting pins maxTokens so the local path can price it against the
- // context window. On Gemini that short-circuited a computed allowance of up
- // to 8192 and halved long summaries — on the provider with the most room.
- const originalFetch = globalThis.fetch;
- t.after(() => {
- globalThis.fetch = originalFetch;
- });
+// Gemini bills thinking against maxOutputTokens, so a cap sized for the cleaned text
+// was spent on thinking and the reply arrived cut off or empty (#2091). The model's
+// own limit bounds the reply instead.
+test("Gemini requests carry no output cap, so thinking cannot starve the reply", async (t) => {
+ const requests = [];
+
+ await callGemini(
+ t,
+ createGeminiResponse([{ text: "Cleaned." }]),
+ {},
+ { model: "gemini-3-flash-preview", requests }
+ );
- let requestBody = null;
- globalThis.fetch = async (_url, init) => {
- requestBody = JSON.parse(init.body);
- return new Response(JSON.stringify(createGeminiResponse([{ text: "ok" }])), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- };
+ assert.equal(requests[0].generationConfig.maxOutputTokens, undefined);
+});
- const { geminiProvider } = await load();
- await geminiProvider.call({
- text: "a long meeting transcript",
- model: "gemini-2.5-flash",
- agentName: null,
- config: { systemPrompt: "Write meeting notes.", maxTokens: 4096 },
- ctx: { ...providerContext, calculateMaxTokens: () => 8192 },
- });
+test("a caller's pinned budget does not reintroduce a cap", async (t) => {
+ // Note formatting pins maxTokens for the local path; letting it cap Gemini halved
+ // long summaries (#2142).
+ const requests = [];
+
+ await callGemini(
+ t,
+ createGeminiResponse([{ text: "Cleaned." }]),
+ { maxTokens: 1000 },
+ { requests }
+ );
- assert.equal(requestBody.generationConfig.maxOutputTokens, 8192);
+ assert.equal(requests[0].generationConfig.maxOutputTokens, undefined);
});
diff --git a/test/services/openaiProviderResponse.test.js b/test/services/openaiProviderResponse.test.js
new file mode 100644
index 000000000..d131d84f2
--- /dev/null
+++ b/test/services/openaiProviderResponse.test.js
@@ -0,0 +1,130 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/ai/inferenceProviders/openai.ts");
+
+const providerContext = {
+ getApiKey: async () => "test-key",
+ getSystemPrompt: () => "Clean the transcript",
+ getCustomDictionary: () => [],
+ getPreferredLanguage: () => "en",
+ getUiLanguage: () => "en",
+ callChatCompletionsApi: async () => {
+ throw new Error("Unexpected chat completions delegation");
+ },
+ calculateMaxTokens: () => 4096,
+};
+
+// openai.ts remembers the endpoint it settled on per base URL at module scope, so each
+// test needs its own base to reach the endpoint it means to exercise. Callers can pass
+// `requested` to assert which endpoints the provider actually called.
+async function callOpenAI(t, { base, responses, chat, requested = [] }, config = {}) {
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ const json = (body, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+ globalThis.fetch = async (input, init = {}) => {
+ const url = String(input);
+ const method = init.method || "GET";
+ requested.push(`${method} ${url}`);
+ if (method === "GET") return json({}, 404); // model discovery
+ if (url.endsWith("/responses")) {
+ return responses ? json(responses) : json({ error: { message: "no responses api" } }, 404);
+ }
+ if (url.endsWith("/chat/completions")) return json(chat);
+ throw new Error(`Unexpected request: ${url}`);
+ };
+
+ const { openaiProvider } = await load();
+ return openaiProvider.call({
+ text: "raw transcript",
+ model: "cleanup-model",
+ agentName: null,
+ config: { provider: "custom", baseUrl: base, customApiKey: "test-key", ...config },
+ ctx: providerContext,
+ });
+}
+
+const incompleteResponses = {
+ status: "incomplete",
+ incomplete_details: { reason: "max_output_tokens" },
+ output: [{ type: "message", content: [{ type: "output_text", text: "Partial" }] }],
+};
+const lengthCappedChat = {
+ choices: [{ message: { content: "Partial" }, finish_reason: "length" }],
+};
+
+test("an incomplete Responses reply rejects with the localizable truncation error", async (t) => {
+ await assert.rejects(
+ callOpenAI(
+ t,
+ { base: "https://incomplete.example/v1", responses: incompleteResponses },
+ { requireCompleteOutput: true }
+ ),
+ (error) => {
+ assert.match(error.message, /Model output was truncated/);
+ // The cleanup toast renders this key rather than the English message.
+ assert.equal(error.messageKey, "hooks.audioRecording.errorDescriptions.cleanupTruncated");
+ return true;
+ }
+ );
+});
+
+test("a length-capped chat reply rejects when complete output is required", async (t) => {
+ const requested = [];
+
+ await assert.rejects(
+ callOpenAI(
+ t,
+ { base: "https://chat-capped.example/v1", chat: lengthCappedChat, requested },
+ { requireCompleteOutput: true }
+ ),
+ /Model output was truncated/
+ );
+
+ // Without the 404 above, the provider would have stopped at /responses and this case
+ // would never have reached the chat path it is named for.
+ assert.deepEqual(requested, [
+ "GET https://chat-capped.example/v1/models",
+ "POST https://chat-capped.example/v1/responses",
+ "POST https://chat-capped.example/v1/chat/completions",
+ ]);
+});
+
+test("a truncated reply still resolves when the caller did not require complete output", async (t) => {
+ const text = await callOpenAI(t, {
+ base: "https://truncated-allowed.example/v1",
+ responses: incompleteResponses,
+ });
+
+ assert.equal(text, "Partial");
+});
+
+test("an empty reply rejects with the localizable empty-reply error", async (t) => {
+ await assert.rejects(
+ callOpenAI(
+ t,
+ { base: "https://empty-required.example/v1", responses: { output: [] } },
+ { requireCompleteOutput: true }
+ ),
+ (error) => {
+ assert.match(error.message, /Model returned an empty response/);
+ assert.equal(error.messageKey, "hooks.audioRecording.errorDescriptions.cleanupEmptyReply");
+ return true;
+ }
+ );
+});
+
+test("an empty reply falls back to the input when complete output is not required", async (t) => {
+ const text = await callOpenAI(t, {
+ base: "https://empty-allowed.example/v1",
+ responses: { output: [] },
+ });
+
+ assert.equal(text, "raw transcript");
+});
diff --git a/test/utils/localInferenceError.test.js b/test/utils/localInferenceError.test.js
index 15376cd50..7836c6cfa 100644
--- a/test/utils/localInferenceError.test.js
+++ b/test/utils/localInferenceError.test.js
@@ -86,3 +86,15 @@ test("a server that will not start becomes a translatable message, not llama.cpp
assert.deepEqual(error.messageParams, { model: "Qwen3.5 9B" });
assert.ok(!error.message.includes("Process output"));
});
+
+test("a reply cut off at the token cap gets the cleanup truncation message", () => {
+ // llama-server reports the cut-off as a code so the key stays on the renderer side (#2091).
+ const error = errors.buildLocalInferenceError({
+ error: "Model output was truncated",
+ code: "OUTPUT_TRUNCATED",
+ });
+
+ assert.equal(error.code, "OUTPUT_TRUNCATED");
+ assert.equal(error.messageKey, "hooks.audioRecording.errorDescriptions.cleanupTruncated");
+ assert.equal(error.messageParams, undefined);
+});