Skip to content

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

fix(notes): retry a notes run once when thinking uses up the output budget (#2670)

void257d47ea3d4b
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index cf290fd9e..229bb965a 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -23,7 +23,8 @@ export type { SettingsSectionType };
// The old AI Models sidebar had four items (transcription, meetings,
// intelligence, agentMode) — they now collapse into two: speechToText + llms.
// Legacy deep-links land on the matching sub-tab via LEGACY_SUB_TAB.
-// "dictationAgent" is a live deep-link (the Home GPU banner), not a legacy alias.
+// "dictationAgent" (the Home GPU banner) and "noteFormatting" (a note action's
+// error toast) are live deep-links, not legacy aliases.
const SECTION_ALIASES: Record<string, SettingsSectionType> = {
aiModels: "llms",
agentConfig: "llms",
@@ -31,6 +32,7 @@ const SECTION_ALIASES: Record<string, SettingsSectionType> = {
dictationAgent: "llms",
intelligence: "llms",
meetings: "llms",
+ noteFormatting: "llms",
prompts: "llms",
transcription: "speechToText",
uploadTranscription: "speechToText",
@@ -45,6 +47,7 @@ const LEGACY_SUB_TAB: Record<string, string> = {
uploadTranscription: "upload",
dictationAgent: "dictationAgent",
meetings: "noteFormatting",
+ noteFormatting: "noteFormatting",
intelligence: "dictationCleanup",
agentMode: "chatIntelligence",
agentConfig: "chatIntelligence",
diff --git a/src/components/settings/InferenceConfigEditor.tsx b/src/components/settings/InferenceConfigEditor.tsx
index 942f05a97..64a2d8ae0 100644
--- a/src/components/settings/InferenceConfigEditor.tsx
+++ b/src/components/settings/InferenceConfigEditor.tsx
@@ -25,9 +25,10 @@ import {
type InferenceScope,
type InferenceScopeDefinition,
} from "../../config/inferenceScopes";
-import { getCloudModel, getLocalModel, enterpriseProviderName } from "../../models/ModelRegistry";
+import { enterpriseProviderName } from "../../models/ModelRegistry";
import { AUTO_REASONING_EFFORT, isReasoningEffortSupported } from "../../models/reasoningEffort";
import { selectableReasoningEffort } from "../../services/ai/chatRequestBody";
+import { offersThinkingToggle } from "../../services/ai/thinkingSuppression";
import { useManagedScopeResolution } from "../../stores/enterpriseIdentityStore";
import { modeSwitchPatch } from "../../utils/llmModeSwitch";
import { requestSignIn } from "../../utils/requestSignIn";
@@ -171,13 +172,7 @@ export default function InferenceConfigEditor({
/>
);
- const showThinkingToggle =
- effectiveMode === "self-hosted" ||
- (effectiveMode === "providers" &&
- (config.provider === "custom" ||
- config.provider === "openrouter" ||
- !!getCloudModel(config.model)?.supportsThinking)) ||
- (effectiveMode === "local" && !!getLocalModel(config.model)?.supportsThinking);
+ const showThinkingToggle = offersThinkingToggle(effectiveMode, config.provider, config.model);
const effortCapability =
effectiveMode === "providers"
diff --git a/src/helpers/providerHttpErrors.js b/src/helpers/providerHttpErrors.js
index 9cd1e6b02..9b28db33f 100644
--- a/src/helpers/providerHttpErrors.js
+++ b/src/helpers/providerHttpErrors.js
@@ -22,7 +22,8 @@ export const PROVIDER_ERROR_CODES = Object.freeze({
const C = PROVIDER_ERROR_CODES;
-const PROVIDER_SETTINGS_TARGETS = Object.freeze(["speechToText", "llms"]);
+// "noteFormatting" opens Language Models on its Note Formatting tab.
+const PROVIDER_SETTINGS_TARGETS = Object.freeze(["speechToText", "llms", "noteFormatting"]);
export const isProviderSettingsTarget = (value) => PROVIDER_SETTINGS_TARGETS.includes(value);
diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.json
index 35f0d25a9..8d395990a 100644
--- a/src/locales/ar/translation.json
+++ b/src/locales/ar/translation.json
@@ -2450,6 +2450,9 @@
"actionFailed": "فشل الإجراء",
"noEndpoint": "لم يتم تعيين عنوان URL لخادم مستضاف ذاتيًا. قم بتكوين واحد في الإعدادات.",
"outputTruncated": "نفدت المساحة لدى نموذج الذكاء الاصطناعي قبل أن ينتهي، لذا بقيت الملاحظة كما هي.",
+ "outputSpentThinking": "استهلك نموذج الذكاء الاصطناعي كامل حد المخرجات في التفكير ولم يكتب أي ملاحظات، لذا بقيت الملاحظة كما هي. فعّل \"تعطيل مخرجات التفكير\" أو اختر نموذجًا يفكر أقل في الإعدادات ← النماذج اللغوية ← تنسيق الملاحظات، ثم حاول مرة أخرى.",
+ "outputSpentThinkingDisabled": "استهلك نموذج الذكاء الاصطناعي كامل حد المخرجات في التفكير ولم يكتب أي ملاحظات، رغم تفعيل \"تعطيل مخرجات التفكير\"، لذا بقيت الملاحظة كما هي. اختر نموذجًا آخر في الإعدادات ← النماذج اللغوية ← تنسيق الملاحظات.",
+ "outputSpentThinkingOtherModel": "استهلك نموذج الذكاء الاصطناعي كامل حد المخرجات في التفكير ولم يكتب أي ملاحظات، لذا بقيت الملاحظة كما هي. اختر نموذجًا يفكر أقل في الإعدادات ← النماذج اللغوية ← تنسيق الملاحظات.",
"nothingToSummarize": "لا يوجد في هذه الملاحظة ما يمكن تلخيصه بعد، لذا بقي الملخص بالذكاء الاصطناعي كما هو.",
"saveFailed": "تعذّر الحفظ. تأكد من أن لا شيء أطول من اللازم ثم حاول مرة أخرى."
},
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index e0895dbf0..4ef047f44 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -3676,6 +3676,9 @@
"actionFailed": "Aktion fehlgeschlagen",
"noEndpoint": "Keine URL für den selbst gehosteten Server festgelegt. Konfigurieren Sie eine in den Einstellungen.",
"outputTruncated": "Dem KI-Modell ging der Platz aus, bevor es fertig war. Die Notiz bleibt daher unverändert.",
+ "outputSpentThinking": "Das KI-Modell hat sein gesamtes Ausgabelimit mit Nachdenken verbraucht und keine Notizen geschrieben. Die Notiz bleibt daher unverändert. Aktivieren Sie unter Einstellungen → Sprachmodelle → Notizformatierung „Denkausgabe deaktivieren“ oder wählen Sie ein Modell, das weniger nachdenkt, und versuchen Sie es erneut.",
+ "outputSpentThinkingDisabled": "Das KI-Modell hat sein gesamtes Ausgabelimit mit Nachdenken verbraucht und keine Notizen geschrieben, obwohl „Denkausgabe deaktivieren“ aktiv ist. Die Notiz bleibt daher unverändert. Wählen Sie unter Einstellungen → Sprachmodelle → Notizformatierung ein anderes Modell.",
+ "outputSpentThinkingOtherModel": "Das KI-Modell hat sein gesamtes Ausgabelimit mit Nachdenken verbraucht und keine Notizen geschrieben. Die Notiz bleibt daher unverändert. Wählen Sie unter Einstellungen → Sprachmodelle → Notizformatierung ein Modell, das weniger nachdenkt.",
"nothingToSummarize": "Diese Notiz enthält noch nichts zum Zusammenfassen, daher bleibt die KI-Zusammenfassung unverändert.",
"saveFailed": "Speichern nicht möglich. Prüfen Sie, dass nichts zu lang ist, und versuchen Sie es erneut."
},
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 9c3b560dd..6fbfda319 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -3676,6 +3676,9 @@
"actionFailed": "Action failed",
"noEndpoint": "No self-hosted server URL set. Configure one in Settings.",
"outputTruncated": "The AI model ran out of room before it finished, so the note was left as it was.",
+ "outputSpentThinking": "The AI model spent its whole output limit thinking and wrote no notes, so the note was left as it was. Turn on \"Disable thinking output\" or choose a model that thinks less in Settings → Language Models → Note Formatting, then try again.",
+ "outputSpentThinkingDisabled": "The AI model spent its whole output limit thinking and wrote no notes, even with \"Disable thinking output\" on, so the note was left as it was. Choose another model in Settings → Language Models → Note Formatting.",
+ "outputSpentThinkingOtherModel": "The AI model spent its whole output limit thinking and wrote no notes, so the note was left as it was. Choose a model that thinks less in Settings → Language Models → Note Formatting.",
"nothingToSummarize": "There's nothing to summarize in this note yet, so the AI summary was left as it was.",
"saveFailed": "Couldn't save. Check that nothing is too long and try again."
},
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 9851f57ff..cc1a7550b 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -3361,6 +3361,9 @@
"actionFailed": "La acción falló",
"noEndpoint": "No hay URL del servidor autoalojado configurada. Configura una en Ajustes.",
"outputTruncated": "El modelo de IA se quedó sin espacio antes de terminar, así que la nota quedó como estaba.",
+ "outputSpentThinking": "El modelo de IA gastó todo su límite de salida pensando y no escribió notas, así que la nota quedó como estaba. Activa \"Desactivar salida de razonamiento\" o elige un modelo que razone menos en Ajustes → Modelos de lenguaje → Formato de notas y vuelve a intentarlo.",
+ "outputSpentThinkingDisabled": "El modelo de IA gastó todo su límite de salida pensando y no escribió notas, aunque \"Desactivar salida de razonamiento\" está activado, así que la nota quedó como estaba. Elige otro modelo en Ajustes → Modelos de lenguaje → Formato de notas.",
+ "outputSpentThinkingOtherModel": "El modelo de IA gastó todo su límite de salida pensando y no escribió notas, así que la nota quedó como estaba. Elige un modelo que razone menos en Ajustes → Modelos de lenguaje → Formato de notas.",
"nothingToSummarize": "Esta nota aún no tiene nada que resumir, así que el resumen con IA se quedó como estaba.",
"saveFailed": "No se pudo guardar. Comprueba que nada sea demasiado largo e inténtalo de nuevo."
},
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index c64f1ff86..cf24316ea 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -3676,6 +3676,9 @@
"actionFailed": "L'action a échoué",
"noEndpoint": "Aucune URL de serveur auto-hébergé définie. Configurez-en une dans les Paramètres.",
"outputTruncated": "Le modèle d'IA a manqué de place avant d'avoir fini, la note reste donc inchangée.",
+ "outputSpentThinking": "Le modèle d'IA a consacré toute sa limite de sortie à la réflexion sans écrire de notes, la note reste donc inchangée. Activez « Désactiver la sortie de raisonnement » ou choisissez un modèle qui réfléchit moins dans Réglages → Modèles de langage → Mise en forme des notes, puis réessayez.",
+ "outputSpentThinkingDisabled": "Le modèle d'IA a consacré toute sa limite de sortie à la réflexion sans écrire de notes, même avec « Désactiver la sortie de raisonnement » activé, la note reste donc inchangée. Choisissez un autre modèle dans Réglages → Modèles de langage → Mise en forme des notes.",
+ "outputSpentThinkingOtherModel": "Le modèle d'IA a consacré toute sa limite de sortie à la réflexion sans écrire de notes, la note reste donc inchangée. Choisissez un modèle qui réfléchit moins dans Réglages → Modèles de langage → Mise en forme des notes.",
"nothingToSummarize": "Cette note n'a encore rien à résumer, donc le résumé IA est resté tel quel.",
"saveFailed": "Enregistrement impossible. Vérifiez que rien n'est trop long, puis réessayez."
},
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index e4e77bf8f..dd1ea3ef6 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -3309,6 +3309,9 @@
"actionFailed": "Azione non riuscita",
"noEndpoint": "Nessun URL del server self-hosted impostato. Configurane uno nelle Impostazioni.",
"outputTruncated": "Il modello AI ha esaurito lo spazio prima di finire, quindi la nota è rimasta com'era.",
+ "outputSpentThinking": "Il modello AI ha usato tutto il suo limite di output per ragionare e non ha scritto note, quindi la nota è rimasta com'era. Attiva \"Disattiva output di ragionamento\" o scegli un modello che ragiona meno in Impostazioni → Modelli linguistici → Formattazione note e riprova.",
+ "outputSpentThinkingDisabled": "Il modello AI ha usato tutto il suo limite di output per ragionare e non ha scritto note, anche con \"Disattiva output di ragionamento\" attivo, quindi la nota è rimasta com'era. Scegli un altro modello in Impostazioni → Modelli linguistici → Formattazione note.",
+ "outputSpentThinkingOtherModel": "Il modello AI ha usato tutto il suo limite di output per ragionare e non ha scritto note, quindi la nota è rimasta com'era. Scegli un modello che ragiona meno in Impostazioni → Modelli linguistici → Formattazione note.",
"nothingToSummarize": "Questa nota non ha ancora nulla da riassumere, quindi il riepilogo AI è rimasto invariato.",
"saveFailed": "Impossibile salvare. Controlla che nulla sia troppo lungo e riprova."
},
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 0222143a9..4c2944356 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -3089,6 +3089,9 @@
"actionFailed": "アクションに失敗しました",
"noEndpoint": "セルフホストサーバーの URL が設定されていません。設定で構成してください。",
"outputTruncated": "AIモデルが出力の上限に達して最後まで書けなかったため、ノートは変更されていません。",
+ "outputSpentThinking": "AIモデルが出力の上限をすべて思考に使い、ノートを書きませんでした。ノートは変更されていません。設定 → 言語モデル → ノートのフォーマット で「思考出力を無効にする」をオンにするか、思考の少ないモデルを選んで、もう一度お試しください。",
+ "outputSpentThinkingDisabled": "「思考出力を無効にする」がオンでも、AIモデルが出力の上限をすべて思考に使い、ノートを書きませんでした。ノートは変更されていません。設定 → 言語モデル → ノートのフォーマット で別のモデルを選んでください。",
+ "outputSpentThinkingOtherModel": "AIモデルが出力の上限をすべて思考に使い、ノートを書きませんでした。ノートは変更されていません。設定 → 言語モデル → ノートのフォーマット で思考の少ないモデルを選んでください。",
"nothingToSummarize": "このノートにはまだ要約できる内容がないため、AI要約はそのままです。",
"saveFailed": "保存できませんでした。長すぎる項目がないか確認して、もう一度お試しください。"
},
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index a13827f01..65b3588e2 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -3309,6 +3309,9 @@
"actionFailed": "A ação falhou",
"noEndpoint": "Nenhum URL de servidor auto-hospedado definido. Configure um nas Configurações.",
"outputTruncated": "O modelo de IA ficou sem espaço antes de terminar, então a nota ficou como estava.",
+ "outputSpentThinking": "O modelo de IA gastou todo o limite de saída raciocinando e não escreveu notas, então a nota ficou como estava. Ative \"Desativar saída de raciocínio\" ou escolha um modelo que raciocine menos em Configurações → Modelos de linguagem → Formatação de notas e tente novamente.",
+ "outputSpentThinkingDisabled": "O modelo de IA gastou todo o limite de saída raciocinando e não escreveu notas, mesmo com \"Desativar saída de raciocínio\" ativado, então a nota ficou como estava. Escolha outro modelo em Configurações → Modelos de linguagem → Formatação de notas.",
+ "outputSpentThinkingOtherModel": "O modelo de IA gastou todo o limite de saída raciocinando e não escreveu notas, então a nota ficou como estava. Escolha um modelo que raciocine menos em Configurações → Modelos de linguagem → Formatação de notas.",
"nothingToSummarize": "Esta nota ainda não tem nada para resumir, então o resumo com IA ficou como estava.",
"saveFailed": "Não foi possível salvar. Verifique se nada está longo demais e tente novamente."
},
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index c757dd305..c8bc15bd6 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -3329,6 +3329,9 @@
"actionFailed": "Действие не выполнено",
"noEndpoint": "URL собственного сервера не задан. Настройте его в разделе Настройки.",
"outputTruncated": "Модели ИИ не хватило места, чтобы закончить, поэтому заметка осталась прежней.",
+ "outputSpentThinking": "Модель ИИ потратила весь лимит вывода на рассуждения и не написала заметки, поэтому заметка осталась прежней. Включите «Отключить вывод рассуждений» или выберите модель, которая меньше рассуждает, в Настройках → Языковые модели → Форматирование заметок и попробуйте снова.",
+ "outputSpentThinkingDisabled": "Модель ИИ потратила весь лимит вывода на рассуждения и не написала заметки, даже с включённым «Отключить вывод рассуждений», поэтому заметка осталась прежней. Выберите другую модель в Настройках → Языковые модели → Форматирование заметок.",
+ "outputSpentThinkingOtherModel": "Модель ИИ потратила весь лимит вывода на рассуждения и не написала заметки, поэтому заметка осталась прежней. Выберите модель, которая меньше рассуждает, в Настройках → Языковые модели → Форматирование заметок.",
"nothingToSummarize": "В этой заметке пока нечего обобщать, поэтому ИИ-сводка осталась без изменений.",
"saveFailed": "Не удалось сохранить. Проверьте, что ничего не слишком длинное, и попробуйте снова."
},
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index a9e94f511..d17c6e3bc 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -3309,6 +3309,9 @@
"actionFailed": "操作失败",
"noEndpoint": "未设置自托管服务器 URL。请在设置中配置。",
"outputTruncated": "AI 模型在完成之前就用完了输出空间,因此笔记保持不变。",
+ "outputSpentThinking": "AI 模型把全部输出额度都用在了思考上,没有写出笔记,因此笔记保持不变。请在“设置 → 语言模型 → 笔记格式化”中开启“禁用思考输出”,或选择思考较少的模型,然后重试。",
+ "outputSpentThinkingDisabled": "即使已开启“禁用思考输出”,AI 模型仍把全部输出额度用在了思考上,没有写出笔记,因此笔记保持不变。请在“设置 → 语言模型 → 笔记格式化”中选择其他模型。",
+ "outputSpentThinkingOtherModel": "AI 模型把全部输出额度都用在了思考上,没有写出笔记,因此笔记保持不变。请在“设置 → 语言模型 → 笔记格式化”中选择思考较少的模型。",
"nothingToSummarize": "这条笔记还没有可以总结的内容,因此 AI 摘要保持不变。",
"saveFailed": "无法保存。请检查是否有内容过长,然后重试。"
},
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index f754acbf1..de7e38c93 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -3309,6 +3309,9 @@
"actionFailed": "操作失敗",
"noEndpoint": "未設定自架伺服器 URL。請在設定中進行配置。",
"outputTruncated": "AI 模型在完成之前就用完了輸出空間,因此筆記維持不變。",
+ "outputSpentThinking": "AI 模型把全部輸出額度都用在了思考上,沒有寫出筆記,因此筆記維持不變。請在「設定 → 語言模型 → 筆記格式化」中開啟「停用思考輸出」,或選擇思考較少的模型,然後重試。",
+ "outputSpentThinkingDisabled": "即使已開啟「停用思考輸出」,AI 模型仍把全部輸出額度用在了思考上,沒有寫出筆記,因此筆記維持不變。請在「設定 → 語言模型 → 筆記格式化」中選擇其他模型。",
+ "outputSpentThinkingOtherModel": "AI 模型把全部輸出額度都用在了思考上,沒有寫出筆記,因此筆記維持不變。請在「設定 → 語言模型 → 筆記格式化」中選擇思考較少的模型。",
"nothingToSummarize": "這則筆記還沒有可以摘要的內容,因此 AI 摘要維持不變。",
"saveFailed": "無法儲存。請檢查是否有內容過長,然後再試一次。"
},
diff --git a/src/services/BaseReasoningService.ts b/src/services/BaseReasoningService.ts
index c2bb6df71..8a6028518 100644
--- a/src/services/BaseReasoningService.ts
+++ b/src/services/BaseReasoningService.ts
@@ -34,7 +34,10 @@ export interface ReasoningConfig {
* it still lets the allowance shrink to fit, where that flag alone refuses.
*/
refuseClippedByWindow?: boolean;
- /** Local models only: tags the request so `cancelLocalReasoning` can abort it. */
+ /**
+ * Tags the request so a cancel can abort it: `cancelLocalReasoning` for local
+ * models, `cancelRequest` (ai/requestCancellation) for the renderer's HTTP routes.
+ */
requestId?: string;
requiresAgent?: boolean;
inferenceScope?: InferenceScope;
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 6b262930a..3c5b3c20c 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -43,6 +43,7 @@ import {
} from "./ai/chatRequestBody";
import { getModelFamilyConstraints } from "./ai/modelFamilyConstraints";
import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
+import { abortOnCancel, isRequestCancelled, requestCancelledError } from "./ai/requestCancellation";
import { openCodeSessionHeaders } from "./ai/openCodeSession";
import { createStreamingThinkFilter } from "./ai/streamingThinkFilter";
import { extractApiErrorMessage } from "./ai/apiErrorMessage";
@@ -355,6 +356,7 @@ class ReasoningService extends BaseReasoningService {
this.activeRequestControllers.add(controller);
const timeoutSeconds = getLlmRequestTimeoutSeconds({ scope: config.inferenceScope });
const timeoutId = setTimeout(() => controller.abort(), timeoutSeconds * 1000);
+ const unlinkCancel = abortOnCancel(config.requestId, controller);
try {
const headers: Record<string, string> = {
"Content-Type": "application/json",
@@ -421,11 +423,13 @@ class ReasoningService extends BaseReasoningService {
if (requestGeneration !== this.requestCancellationGeneration) {
throw httpError("Request cancelled", 499);
}
+ if (isRequestCancelled(config.requestId)) throw requestCancelledError();
throw llmRequestTimeoutError(timeoutSeconds);
}
throw error;
} finally {
clearTimeout(timeoutId);
+ unlinkCancel();
this.activeRequestControllers.delete(controller);
}
}, createApiRetryStrategy()).catch((error) => {
diff --git a/src/services/ai/chatRequestBody.ts b/src/services/ai/chatRequestBody.ts
index d63546632..ecd7c4e6f 100644
--- a/src/services/ai/chatRequestBody.ts
+++ b/src/services/ai/chatRequestBody.ts
@@ -181,6 +181,17 @@ export function truncatedOutputError(
return Object.assign(new Error(message), { messageKey: TRUNCATED_OUTPUT_MESSAGE_KEY });
}
+/**
+ * Code on the truncated error for a reply cut off before any answer: a reasoning
+ * model spent the whole output cap thinking. Note formatting retries those (#2008).
+ */
+export const OUTPUT_LIMIT_BEFORE_ANSWER_CODE = "OUTPUT_LIMIT_BEFORE_ANSWER";
+
+// A reasoning model's hidden reasoning counts against the output cap; OpenAI
+// recommends reserving at least 25k tokens for reasoning plus output. A cap,
+// not a spend: an unused allowance costs nothing.
+export const REASONING_MODEL_MIN_OUTPUT_TOKENS = 25_000;
+
/** A reply with no text at all; providers pass their own wording for the logs. */
export function emptyOutputError(
message = "Model returned an empty response"
@@ -199,7 +210,10 @@ export function emptyResponseError(
responseIncomplete: boolean
): Error | null {
if (responseIncomplete) {
- return truncatedOutputError("Model ran out of output tokens before producing a response");
+ return Object.assign(
+ truncatedOutputError("Model ran out of output tokens before producing a response"),
+ { code: OUTPUT_LIMIT_BEFORE_ANSWER_CODE }
+ );
}
if (config.requireCompleteOutput) return emptyOutputError();
if (config.systemPrompt) return new Error(`${providerName} returned empty response`);
diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.ts
index 91e361b66..a0ec25717 100644
--- a/src/services/ai/inferenceProviders/openai.ts
+++ b/src/services/ai/inferenceProviders/openai.ts
@@ -7,13 +7,16 @@ import logger from "../../../utils/logger";
import { canBorrowCleanupCustomKey, resolveConfiguredOpenAIBase } from "../openaiBase";
import {
applyChatCompletionsParams,
+ emptyOutputError,
emptyResponseError,
fetchWithParamFallback,
isTruncatedFinishReason,
+ REASONING_MODEL_MIN_OUTPUT_TOKENS,
responsesReasoningEffort,
truncatedOutputError,
} from "../chatRequestBody";
import { detectEndpointDialect } from "../thinkingSuppressionDialects";
+import { abortOnCancel, isRequestCancelled, requestCancelledError } from "../requestCancellation";
import {
getLlmRequestTimeoutSeconds,
llmRequestTimeoutError,
@@ -29,10 +32,6 @@ import {
const OPENAI_ENDPOINT_PREF_STORAGE_KEY = "openAiEndpointPreference";
const PROBE_TIMEOUT_MS = 2_000;
-// OpenAI counts a reasoning model's hidden reasoning against the output cap and
-// recommends reserving at least 25k tokens for reasoning plus output. A cap,
-// not a spend: an unused allowance costs nothing.
-const REASONING_MODEL_MIN_OUTPUT_TOKENS = 25_000;
const endpointPreferenceCache = new Map<string, "responses" | "chat">();
const probedBases = new Set<string>();
@@ -236,6 +235,11 @@ export const openaiProvider: InferenceProvider = {
});
}
+ // Only registry-known OpenAI reasoning models on OpenAI's own host: an
+ // unknown id (fine-tune, proxy) may reject a cap above its output limit.
+ const hasReasoningRoom =
+ !isCustomEndpoint && getCloudModel(model)?.supportsTemperature === false;
+
const retryStrategy = createApiRetryStrategy();
const response = await withRetry(async () => {
let lastError: Error | null = null;
@@ -245,6 +249,7 @@ export const openaiProvider: InferenceProvider = {
const controller = new AbortController();
const timeoutSeconds = getLlmRequestTimeoutSeconds({ scope: config.inferenceScope });
const timeoutId = setTimeout(() => controller.abort(), timeoutSeconds * 1000);
+ const unlinkCancel = abortOnCancel(config.requestId, controller);
let readingBody = false;
try {
const requestedMaxTokens =
@@ -260,12 +265,9 @@ export const openaiProvider: InferenceProvider = {
);
// A known endpoint host knows its own request shape better than the model id does.
const apiConfig = dialect ?? getOpenAiApiConfig(model, resolvedProvider);
- // Only registry-known OpenAI reasoning models on OpenAI's own host: an
- // unknown id (fine-tune, proxy) may reject a cap above its output limit.
- const maxTokens =
- !isCustomEndpoint && getCloudModel(model)?.supportsTemperature === false
- ? Math.max(requestedMaxTokens, REASONING_MODEL_MIN_OUTPUT_TOKENS)
- : requestedMaxTokens;
+ const maxTokens = hasReasoningRoom
+ ? Math.max(requestedMaxTokens, REASONING_MODEL_MIN_OUTPUT_TOKENS)
+ : requestedMaxTokens;
const requestBody: Record<string, unknown> = { model };
@@ -344,6 +346,7 @@ export const openaiProvider: InferenceProvider = {
return await res.json();
} catch (error) {
if ((error as Error).name === "AbortError") {
+ if (isRequestCancelled(config.requestId)) throw requestCancelledError();
throw llmRequestTimeoutError(timeoutSeconds);
}
if (readingBody) throw error;
@@ -361,6 +364,7 @@ export const openaiProvider: InferenceProvider = {
throw lastRetryableError || error;
} finally {
clearTimeout(timeoutId);
+ unlinkCancel();
}
}
@@ -378,6 +382,9 @@ export const openaiProvider: InferenceProvider = {
response?.status === "incomplete" ||
!!response?.incomplete_details ||
response?.choices?.some((choice: any) => isTruncatedFinishReason(choice?.finish_reason));
+ const contentFiltered =
+ response?.incomplete_details?.reason === "content_filter" ||
+ response?.choices?.some((choice: any) => choice?.finish_reason === "content_filter");
if (config.requireCompleteOutput && responseIncomplete) {
throw truncatedOutputError();
}
@@ -459,8 +466,14 @@ export const openaiProvider: InferenceProvider = {
if (refusal) {
throw new Error(`Model declined the request: ${refusal}`);
}
+ // A content filter also marks a Responses reply "incomplete", but no output
+ // budget ran out: an empty reply, never retried and never echoed back.
+ if (contentFiltered) throw emptyOutputError("Model output was stopped by a content filter");
const error = emptyResponseError("OpenAI", config, !!responseIncomplete);
- if (error) throw error;
+ // No retry code: that request already had a retry's room.
+ if (error) {
+ throw responseIncomplete && hasReasoningRoom ? truncatedOutputError(error.message) : error;
+ }
logger.logReasoning("OPENAI_EMPTY_RESPONSE_FALLBACK", {
model,
originalTextLength: text.length,
diff --git a/src/services/ai/inferenceProviders/tinfoil.ts b/src/services/ai/inferenceProviders/tinfoil.ts
index dcffe755c..1b3bdc788 100644
--- a/src/services/ai/inferenceProviders/tinfoil.ts
+++ b/src/services/ai/inferenceProviders/tinfoil.ts
@@ -9,6 +9,7 @@ import {
truncatedOutputError,
} from "../chatRequestBody";
import { getTinfoilChatClient } from "../tinfoilClient";
+import { isRequestCancelled, requestCancelledError, requestSignal } from "../requestCancellation";
import {
getLlmRequestTimeoutSeconds,
llmRequestTimeoutError,
@@ -54,8 +55,11 @@ export const tinfoilProvider: InferenceProvider = {
return await client.chat.completions.create(requestBody as any, {
timeout: timeoutSeconds * 1000,
maxRetries: 0,
+ signal: requestSignal(config.requestId),
});
} catch (error) {
+ // The SDK's abort error has no status, which withRetry would re-send.
+ if (isRequestCancelled(config.requestId)) throw requestCancelledError();
// The SDK reports an expired deadline as a connection error, which
// withRetry would otherwise treat as a network drop and re-send.
if ((error as Error).name === "APIConnectionTimeoutError") {
diff --git a/src/services/ai/requestCancellation.ts b/src/services/ai/requestCancellation.ts
new file mode 100644
index 000000000..defdedf3b
--- /dev/null
+++ b/src/services/ai/requestCancellation.ts
@@ -0,0 +1,43 @@
+import { httpError } from "../../utils/retry";
+
+// Cancels the renderer's HTTP requests tagged with `ReasoningConfig.requestId`.
+// The config crosses IPC on some routes, where an AbortSignal can't be cloned,
+// so providers look the signal up here by the id instead.
+const controllers = new Map<string, AbortController>();
+
+/** Makes `requestId` cancellable; call the returned release once its requests settle. */
+export function trackRequest(requestId: string): () => void {
+ const controller = new AbortController();
+ controllers.set(requestId, controller);
+ return () => {
+ if (controllers.get(requestId) === controller) controllers.delete(requestId);
+ };
+}
+
+export function cancelRequest(requestId: string): void {
+ controllers.get(requestId)?.abort();
+}
+
+export function requestSignal(requestId: string | undefined): AbortSignal | undefined {
+ return requestId ? controllers.get(requestId)?.signal : undefined;
+}
+
+export function isRequestCancelled(requestId: string | undefined): boolean {
+ return requestSignal(requestId)?.aborted === true;
+}
+
+/** Aborts `controller` when the request is cancelled; returns the unlink. */
+export function abortOnCancel(
+ requestId: string | undefined,
+ controller: AbortController
+): () => void {
+ const signal = requestSignal(requestId);
+ if (!signal) return () => {};
+ const abort = () => controller.abort();
+ if (signal.aborted) abort();
+ else signal.addEventListener("abort", abort, { once: true });
+ return () => signal.removeEventListener("abort", abort);
+}
+
+/** Never retried: withRetry gives up on a 4xx other than 408 and 429. */
+export const requestCancelledError = (): Error => httpError("Request cancelled", 499);
diff --git a/src/services/ai/thinkingSuppression.ts b/src/services/ai/thinkingSuppression.ts
index 2236df0eb..8e7bbbb2f 100644
--- a/src/services/ai/thinkingSuppression.ts
+++ b/src/services/ai/thinkingSuppression.ts
@@ -1,7 +1,26 @@
import type { ReasoningConfig } from "../BaseReasoningService";
+import type { InferenceMode } from "../../types/electron";
import { getCloudModel, getLocalModel } from "../../models/ModelRegistry";
import { detectEndpointDialect, suppressThinking } from "./thinkingSuppressionDialects";
+/**
+ * Whether Settings offers "Disable thinking output" for this route: any
+ * endpoint that may honour it, but a known model only when it can think on request.
+ */
+export function offersThinkingToggle(
+ mode: InferenceMode,
+ provider: string,
+ model: string
+): boolean {
+ if (mode === "self-hosted") return true;
+ if (mode === "providers") {
+ return (
+ provider === "custom" || provider === "openrouter" || !!getCloudModel(model)?.supportsThinking
+ );
+ }
+ return mode === "local" && !!getLocalModel(model)?.supportsThinking;
+}
+
export function isThinkingSuppressed(model: string, config: ReasoningConfig): boolean {
const cloudModel = getCloudModel(model);
diff --git a/src/stores/actionProcessingStore.ts b/src/stores/actionProcessingStore.ts
index 6a4701cf4..34ef59243 100644
--- a/src/stores/actionProcessingStore.ts
+++ b/src/stores/actionProcessingStore.ts
@@ -3,10 +3,16 @@ import { NOTE_OUTPUT_MAX_TOKENS, NOTHING_TO_SUMMARIZE } from "../helpers/builtin
import { stripThinkingTags } from "../helpers/stripThinking";
import { compileSummaryActionPrompt, compileTemplatePrompt } from "../helpers/templatePrompts";
import reasoningService from "../services/ReasoningService";
-import { getSettings, selectResolvedNoteFormatting } from "./settingsStore";
+import {
+ getSettings,
+ selectResolvedNoteFormatting,
+ type ResolvedNoteFormatting,
+} from "./settingsStore";
import { appendDictionarySuffix } from "../config/prompts";
import { generateNoteTitle } from "../utils/generateTitle";
import { buildNoteFormattingOverrides } from "../helpers/noteFormattingOverrides";
+import { PROVIDER_ERROR_CODES } from "../helpers/providerHttpErrors.js";
+import { LLM_REQUEST_TIMEOUT_CODE } from "../helpers/llmRequestTimeout.js";
import { tagActionItemOwners, type MentionPerson } from "../utils/mentionMarkdown";
import type { ActionItem, NoteItem } from "../types/electron";
import { estimateNoteTokens, planNoteChunks, splitChunkInHalf } from "../helpers/noteChunking";
@@ -15,8 +21,12 @@ import type { TechnicalErrorDetailsData } from "../components/ui/useToast";
import type { ReasoningConfig } from "../services/BaseReasoningService";
import {
EMPTY_OUTPUT_MESSAGE_KEY,
+ OUTPUT_LIMIT_BEFORE_ANSWER_CODE,
+ REASONING_MODEL_MIN_OUTPUT_TOKENS,
TRUNCATED_OUTPUT_MESSAGE_KEY,
} from "../services/ai/chatRequestBody";
+import { cancelRequest, trackRequest } from "../services/ai/requestCancellation";
+import { offersThinkingToggle } from "../services/ai/thinkingSuppression";
// The providers' error keys describe dictation cleanup; a note run shows its own.
const NOTE_ERROR_KEYS: Record<string, string> = {
@@ -104,7 +114,7 @@ interface ActionProcessingStoreState {
// The run a note's in-flight action belongs to. A per-note flag would be reset
// by a new run on the same note and revive the run the user just cancelled.
-// The id also tags the run's local requests so a cancel can abort them.
+// The id also tags the run's requests so a cancel can abort them.
const activeRuns = new Map<number, string>();
const processingFlags = new Map<number, boolean>();
const successTimers = new Map<number, NodeJS.Timeout>();
@@ -195,6 +205,23 @@ interface LocalContextBudget {
const isContextTooLarge = (error: unknown): boolean =>
(error as { code?: string } | null)?.code === "CONTEXT_TOO_LARGE";
+const ranOutBeforeAnswer = (error: unknown): boolean =>
+ (error as { code?: string } | null)?.code === OUTPUT_LIMIT_BEFORE_ANSWER_CODE;
+
+/** Names "Disable thinking output" only where Settings shows it for this model. */
+function outputSpentThinkingKey(
+ noteFormatting: ResolvedNoteFormatting,
+ model: string,
+ disableThinking: boolean
+): string {
+ if (!offersThinkingToggle(noteFormatting.mode, noteFormatting.provider, model)) {
+ return "notes.actions.errors.outputSpentThinkingOtherModel";
+ }
+ return disableThinking
+ ? "notes.actions.errors.outputSpentThinkingDisabled"
+ : "notes.actions.errors.outputSpentThinking";
+}
+
const hasTranscript = (material: NoteMaterial | undefined): material is NoteMaterial =>
(material?.transcript.trim().length ?? 0) > 0;
@@ -260,6 +287,32 @@ async function runEnhancement(run: EnhancementRun): Promise<string> {
run.requestConfig
);
} catch (error) {
+ // A reasoning model spent the whole budget thinking before writing a word
+ // (#2008): one more try with room for its reasoning plus the notes, unless
+ // the request already had that room.
+ if (ranOutBeforeAnswer(error)) {
+ if (run.isCancelled()) throw new Error("cancelled");
+ return await reasoningService
+ .processText(run.noteContent, run.modelId, null, {
+ ...run.requestConfig,
+ maxTokens: REASONING_MODEL_MIN_OUTPUT_TOKENS,
+ })
+ .catch((retryError) => {
+ // A server that refuses the bigger cap, or a model still thinking at the
+ // deadline, keeps this failure, whose advice still applies, with the
+ // retry's details to copy; a key, quota or network problem shows as itself.
+ const { code, technicalDetails } = (retryError ?? {}) as {
+ code?: string;
+ technicalDetails?: TechnicalErrorDetailsData;
+ };
+ const keepsAdvice =
+ code === PROVIDER_ERROR_CODES.BAD_REQUEST ||
+ code === PROVIDER_ERROR_CODES.PAYLOAD_TOO_LARGE ||
+ code === PROVIDER_ERROR_CODES.TIMEOUT ||
+ code === LLM_REQUEST_TIMEOUT_CODE;
+ throw keepsAdvice ? Object.assign(error as Error, { technicalDetails }) : retryError;
+ });
+ }
if (!isContextTooLarge(error)) throw error;
refusal = error;
}
@@ -487,6 +540,7 @@ export function runBackgroundAction(
const runId = crypto.randomUUID();
activeRuns.set(noteId, runId);
+ const releaseRequests = trackRequest(runId);
const isCancelled = () => activeRuns.get(noteId) !== runId;
processingFlags.set(noteId, true);
setNoteState(noteId, { status: "processing", actionName: action.name, progress: null });
@@ -622,28 +676,37 @@ export function runBackgroundAction(
settingsTarget?: string;
technicalDetails?: TechnicalErrorDetailsData;
};
+ // A retry that still thought past its budget, or was refused or timed out:
+ // point at the setting that stops the thinking.
+ const thinkingSpentOutput = ranOutBeforeAnswer(err);
pushErrorEvent({
noteId,
message,
- messageKey: (messageKey && NOTE_ERROR_KEYS[messageKey]) || messageKey,
+ messageKey: thinkingSpentOutput
+ ? outputSpentThinkingKey(noteFormatting, modelId, settings.noteFormattingDisableThinking)
+ : (messageKey && NOTE_ERROR_KEYS[messageKey]) || messageKey,
messageParams,
notice,
- settingsTarget,
+ settingsTarget: thinkingSpentOutput ? "noteFormatting" : settingsTarget,
technicalDetails,
});
} finally {
+ releaseRequests();
if (activeRuns.get(noteId) === runId) activeRuns.delete(noteId);
}
})();
}
/**
- * Aborts the run's local request in flight, which would otherwise hold the one
- * local model slot for minutes. Other routes finish and are discarded.
+ * Aborts the run's request in flight: a local one would otherwise hold the one
+ * local model slot for minutes, and a cloud one bill a reply nobody reads.
*/
export function cancelAction(noteId: number): void {
const runId = activeRuns.get(noteId);
- if (runId) void window.electronAPI?.cancelLocalReasoning?.(runId);
+ if (runId) {
+ cancelRequest(runId);
+ void window.electronAPI?.cancelLocalReasoning?.(runId);
+ }
activeRuns.delete(noteId);
processingFlags.set(noteId, false);
const timer = successTimers.get(noteId);
diff --git a/src/utils/describeProviderError.ts b/src/utils/describeProviderError.ts
index c89466f9c..5803a681e 100644
--- a/src/utils/describeProviderError.ts
+++ b/src/utils/describeProviderError.ts
@@ -2,7 +2,7 @@ import type { TFunction } from "i18next";
import type { TechnicalErrorDetailsData, ToastActionConfig } from "../components/ui/useToast";
import { SELF_HOSTED_NAME, isProviderSettingsTarget } from "../helpers/providerHttpErrors.js";
-export type ProviderSettingsTarget = "speechToText" | "llms";
+export type ProviderSettingsTarget = "speechToText" | "llms" | "noteFormatting";
interface DescribableError {
message?: string;
diff --git a/test/helpers/providerHttpErrors.test.js b/test/helpers/providerHttpErrors.test.js
index 5fb8aef64..cb3e66e65 100644
--- a/test/helpers/providerHttpErrors.test.js
+++ b/test/helpers/providerHttpErrors.test.js
@@ -336,10 +336,11 @@ test("asProviderError leaves classified, cancelled and unrelated errors untouche
assert.equal(asProviderError(null, ctx), null);
});
-test("isProviderSettingsTarget whitelists only the two sections", async () => {
+test("isProviderSettingsTarget whitelists only the model settings targets", async () => {
const { isProviderSettingsTarget } = await load();
assert.equal(isProviderSettingsTarget("speechToText"), true);
assert.equal(isProviderSettingsTarget("llms"), true);
+ assert.equal(isProviderSettingsTarget("noteFormatting"), true);
assert.equal(isProviderSettingsTarget("account"), false);
assert.equal(isProviderSettingsTarget(undefined), false);
});
diff --git a/test/services/lanReasoningOutput.test.js b/test/services/lanReasoningOutput.test.js
new file mode 100644
index 000000000..608886149
--- /dev/null
+++ b/test/services/lanReasoningOutput.test.js
@@ -0,0 +1,90 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// A self-hosted reasoning model (Ollama, vLLM, llama.cpp) can spend the whole
+// output cap inside <think>, so nothing is left once the block is stripped.
+// That cut-off carries the code note formatting retries with more room (#2008).
+test("a self-hosted reply that only thought until the cap carries the cut-off code", async (t) => {
+ installBrowserGlobals(t, { window: { electronAPI: {} } });
+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-lan-reasoning-test-" });
+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });
+ t.after(() => reasoningService.destroy());
+
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ globalThis.fetch = async () =>
+ new Response(
+ JSON.stringify({
+ choices: [
+ { message: { content: "<think>Let me read the transcript" }, finish_reason: "length" },
+ ],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } }
+ );
+
+ await assert.rejects(
+ reasoningService.processText("## Meeting Transcript\nYou: ship on Friday.", "glm-5.3", null, {
+ lanUrl: "http://127.0.0.1:11434/v1",
+ systemPrompt: "Summarize",
+ maxTokens: 4096,
+ }),
+ { message: /ran out of output tokens/, code: "OUTPUT_LIMIT_BEFORE_ANSWER" }
+ );
+});
+
+test("a cancelled run aborts its self-hosted request and is not retried", async (t) => {
+ installBrowserGlobals(t, { window: { electronAPI: {} } });
+ const vite = await createRendererServer(t, { cachePrefix: "openwhispr-lan-reasoning-test-" });
+ const reasoningService = (await vite.ssrLoadModule("/services/ReasoningService.ts")).default;
+ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");
+ const { cancelRequest, trackRequest } = await vite.ssrLoadModule(
+ "/services/ai/requestCancellation.ts"
+ );
+ usePolicyStore.setState({ status: "unmanaged", appVersion: "1.10.0", policy: null });
+ t.after(() => reasoningService.destroy());
+ t.after(trackRequest("run-1"));
+
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ let requests = 0;
+ // A model still thinking: no reply until the request is aborted.
+ globalThis.fetch = (_input, init = {}) => {
+ requests += 1;
+ return new Promise((_resolve, reject) => {
+ const abort = () => reject(Object.assign(new Error("aborted"), { name: "AbortError" }));
+ if (init.signal.aborted) abort();
+ else init.signal.addEventListener("abort", abort);
+ });
+ };
+
+ const call = reasoningService.processText(
+ "## Meeting Transcript\nYou: ship on Friday.",
+ "glm-5.3",
+ null,
+ {
+ lanUrl: "http://127.0.0.1:11434/v1",
+ systemPrompt: "Summarize",
+ maxTokens: 25_000,
+ requestId: "run-1",
+ }
+ );
+ for (let attempt = 0; requests === 0 && attempt < 400; attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ cancelRequest("run-1");
+
+ // Promptly, not at the request deadline.
+ const deadline = new Promise((_resolve, reject) =>
+ setTimeout(() => reject(new Error("still waiting on the request")), 2_000).unref()
+ );
+ await assert.rejects(Promise.race([call, deadline]), { message: "Request cancelled" });
+ assert.equal(requests, 1, "an aborted request is never sent again");
+});
diff --git a/test/services/openaiReasoningOutput.test.js b/test/services/openaiReasoningOutput.test.js
index 09542389b..f691b4bb7 100644
--- a/test/services/openaiReasoningOutput.test.js
+++ b/test/services/openaiReasoningOutput.test.js
@@ -274,17 +274,142 @@ test("a Responses result that ran out of tokens before any text is an error, not
})
);
const { openaiProvider } = await load();
+ const { TRUNCATED_OUTPUT_MESSAGE_KEY } = await import("../../src/services/ai/chatRequestBody.ts");
- await assert.rejects(
- openaiProvider.call({
+ const error = await openaiProvider
+ .call({
text: TRANSCRIPT,
model: "gpt-5.6-terra",
agentName: null,
config: { provider: "openai", systemPrompt: "Summarize", maxTokens: 4096 },
ctx: makeCtx(),
+ })
+ .then(
+ () => null,
+ (rejection) => rejection
+ );
+
+ assert.match(error?.message ?? "", /ran out of output tokens/);
+ assert.equal(error.messageKey, TRUNCATED_OUTPUT_MESSAGE_KEY);
+ // The code is what note formatting retries with more room (#2008); this
+ // model's request already had it.
+ assert.equal(error.code, undefined, "note formatting must not send the same cap again");
+});
+
+test("a Custom endpoint's Responses result that only reasoned carries the retry code", async (t) => {
+ // Ollama answers the app's notes request on /v1/responses: GLM-5.3 at its
+ // default effort spends the whole 4,096 tokens reasoning (#2008).
+ installFetch(t, () =>
+ jsonResponse({
+ status: "incomplete",
+ incomplete_details: { reason: "max_output_tokens" },
+ output: [{ type: "reasoning", summary: [] }],
+ })
+ );
+ const { openaiProvider } = await load();
+
+ await assert.rejects(
+ openaiProvider.call({
+ text: TRANSCRIPT,
+ model: "glm-5.3",
+ agentName: null,
+ config: {
+ provider: "custom",
+ baseUrl: "https://ollama.example/v1",
+ customApiKey: "test-key",
+ systemPrompt: "Summarize",
+ maxTokens: 4096,
+ },
+ ctx: makeCtx(),
}),
- /ran out of output tokens/
+ { message: /ran out of output tokens/, code: "OUTPUT_LIMIT_BEFORE_ANSWER" }
+ );
+});
+
+test("a Responses result stopped by a content filter is not reported as running out of tokens", async (t) => {
+ installFetch(t, () =>
+ jsonResponse({
+ status: "incomplete",
+ incomplete_details: { reason: "content_filter" },
+ output: [],
+ })
+ );
+ const { openaiProvider } = await load();
+ const { EMPTY_OUTPUT_MESSAGE_KEY } = await import("../../src/services/ai/chatRequestBody.ts");
+
+ // Notes show it as their translated empty reply, and Prompt Studio's cleanup
+ // test (no system prompt) as an error rather than its own input echoed back.
+ for (const config of [
+ { provider: "openai", systemPrompt: "Summarize", maxTokens: 4096 },
+ { provider: "openai" },
+ ]) {
+ await assert.rejects(
+ openaiProvider.call({
+ text: TRANSCRIPT,
+ model: "gpt-5.6-terra",
+ agentName: null,
+ config,
+ ctx: makeCtx(),
+ }),
+ (error) =>
+ /content filter/.test(error.message) &&
+ error.messageKey === EMPTY_OUTPUT_MESSAGE_KEY &&
+ error.code === undefined
+ );
+ }
+});
+
+test("a cancelled run aborts its request in flight and is not retried", async (t) => {
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ let requests = 0;
+ globalThis.fetch = (_input, init = {}) => {
+ if ((init.method || "GET") === "GET") {
+ return Promise.resolve(jsonResponse({ error: { message: "unauthorized" } }, 401));
+ }
+ requests += 1;
+ // A model still thinking: no reply until the request is aborted.
+ return new Promise((_resolve, reject) => {
+ const abort = () => reject(Object.assign(new Error("aborted"), { name: "AbortError" }));
+ if (init.signal.aborted) abort();
+ else init.signal.addEventListener("abort", abort);
+ });
+ };
+ const { openaiProvider } = await load();
+ const { cancelRequest, trackRequest } =
+ await import("../../src/services/ai/requestCancellation.ts");
+ t.after(trackRequest("run-1"));
+
+ const call = openaiProvider.call({
+ text: TRANSCRIPT,
+ model: "glm-5.3",
+ agentName: null,
+ config: {
+ provider: "custom",
+ baseUrl: "https://ollama.example/v1",
+ customApiKey: "test-key",
+ systemPrompt: "Summarize",
+ maxTokens: 25_000,
+ requestId: "run-1",
+ },
+ ctx: makeCtx(),
+ });
+ for (let attempt = 0; requests === 0 && attempt < 400; attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ cancelRequest("run-1");
+
+ // Promptly, not at the request deadline.
+ const deadline = new Promise((_resolve, reject) =>
+ setTimeout(() => reject(new Error("still waiting on the request")), 2_000).unref()
);
+ await assert.rejects(Promise.race([call, deadline]), {
+ message: "Request cancelled",
+ status: 499,
+ });
+ assert.equal(requests, 1, "neither retried nor sent to another endpoint");
});
test("a Chat Completions result cut off before any text is an error, not the input echoed back", async (t) => {
@@ -307,10 +432,43 @@ test("a Chat Completions result cut off before any text is an error, not the inp
},
ctx: makeCtx(),
}),
- /ran out of output tokens/
+ { message: /ran out of output tokens/, code: "OUTPUT_LIMIT_BEFORE_ANSWER" }
);
});
+test("a cut-off on a task that needs complete output carries no retry code", async (t) => {
+ installFetch(t, () =>
+ jsonResponse({
+ status: "incomplete",
+ incomplete_details: { reason: "max_output_tokens" },
+ output: [{ type: "reasoning", summary: [] }],
+ })
+ );
+ const { openaiProvider } = await load();
+ const { TRUNCATED_OUTPUT_MESSAGE_KEY } = await import("../../src/services/ai/chatRequestBody.ts");
+
+ const error = await openaiProvider
+ .call({
+ text: TRANSCRIPT,
+ model: "gpt-4.1",
+ agentName: null,
+ config: {
+ provider: "openai",
+ systemPrompt: "Summarize",
+ maxTokens: 8192,
+ requireCompleteOutput: true,
+ },
+ ctx: makeCtx(),
+ })
+ .then(
+ () => null,
+ (rejection) => rejection
+ );
+
+ assert.equal(error?.messageKey, TRUNCATED_OUTPUT_MESSAGE_KEY);
+ assert.equal(error.code, undefined, "note formatting must not retry a summary rewrite");
+});
+
test("an empty but complete response on a task with its own prompt is an error, not the input echoed back", async (t) => {
installFetch(t, () => completeMessage(""));
const { openaiProvider } = await load();
diff --git a/test/services/tinfoilReasoningOutput.test.js b/test/services/tinfoilReasoningOutput.test.js
index b7bfc850a..7799ad1ba 100644
--- a/test/services/tinfoilReasoningOutput.test.js
+++ b/test/services/tinfoilReasoningOutput.test.js
@@ -13,18 +13,24 @@ async function loadProvider(t) {
mockModules: {
"/tinfoilClient": `
export const getTinfoilChatClient = async () => ({
- chat: { completions: { create: async () => globalThis.__tinfoilResponse } },
+ chat: {
+ completions: {
+ create: async (body, options) =>
+ globalThis.__tinfoilCreate?.(options) ?? globalThis.__tinfoilResponse,
+ },
+ },
});
`,
},
});
t.after(() => {
delete globalThis.__tinfoilResponse;
+ delete globalThis.__tinfoilCreate;
});
const { tinfoilProvider } = await vite.ssrLoadModule(
"/services/ai/inferenceProviders/tinfoil.ts"
);
- return tinfoilProvider;
+ return { tinfoilProvider, vite };
}
const ctx = {
@@ -34,7 +40,7 @@ const ctx = {
};
test("a Tinfoil result cut off before any text is an error, not the input echoed back", async (t) => {
- const tinfoilProvider = await loadProvider(t);
+ const { tinfoilProvider } = await loadProvider(t);
globalThis.__tinfoilResponse = {
choices: [{ message: { content: "" }, finish_reason: "length" }],
};
@@ -47,12 +53,12 @@ test("a Tinfoil result cut off before any text is an error, not the input echoed
config: { systemPrompt: "Summarize", maxTokens: 4096 },
ctx,
}),
- /ran out of output tokens/
+ { message: /ran out of output tokens/, code: "OUTPUT_LIMIT_BEFORE_ANSWER" }
);
});
test("an empty but complete Tinfoil response on a task with its own prompt is an error", async (t) => {
- const tinfoilProvider = await loadProvider(t);
+ const { tinfoilProvider } = await loadProvider(t);
globalThis.__tinfoilResponse = {
choices: [{ message: { content: "" }, finish_reason: "stop" }],
};
@@ -70,7 +76,7 @@ test("an empty but complete Tinfoil response on a task with its own prompt is an
});
test("an empty but complete Tinfoil response still falls back to the input for cleanup", async (t) => {
- const tinfoilProvider = await loadProvider(t);
+ const { tinfoilProvider } = await loadProvider(t);
globalThis.__tinfoilResponse = {
choices: [{ message: { content: "" }, finish_reason: "stop" }],
};
@@ -85,3 +91,44 @@ test("an empty but complete Tinfoil response still falls back to the input for c
assert.equal(result, "raw dictation");
});
+
+test("a cancelled run aborts its Tinfoil request and is not retried", async (t) => {
+ const { tinfoilProvider, vite } = await loadProvider(t);
+ const { cancelRequest, trackRequest } = await vite.ssrLoadModule(
+ "/services/ai/requestCancellation.ts"
+ );
+ t.after(trackRequest("run-1"));
+ let requests = 0;
+ // A model still thinking: no reply until the SDK's request is aborted.
+ globalThis.__tinfoilCreate = ({ signal }) => {
+ requests += 1;
+ return new Promise((_resolve, reject) => {
+ const abort = () =>
+ reject(Object.assign(new Error("Request was aborted."), { name: "APIUserAbortError" }));
+ if (signal.aborted) abort();
+ else signal.addEventListener("abort", abort);
+ });
+ };
+
+ const call = tinfoilProvider.call({
+ text: "## Meeting Transcript\nYou: ship on Friday.",
+ model: "gpt-oss-120b",
+ agentName: null,
+ config: { systemPrompt: "Summarize", maxTokens: 25_000, requestId: "run-1" },
+ ctx,
+ });
+ for (let attempt = 0; requests === 0 && attempt < 400; attempt += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ cancelRequest("run-1");
+
+ // Promptly, not at the request deadline.
+ const deadline = new Promise((_resolve, reject) =>
+ setTimeout(() => reject(new Error("still waiting on the request")), 2_000).unref()
+ );
+ await assert.rejects(Promise.race([call, deadline]), {
+ message: "Request cancelled",
+ status: 499,
+ });
+ assert.equal(requests, 1, "an aborted request is never sent again");
+});
diff --git a/test/stores/actionProcessingNoteOutput.test.js b/test/stores/actionProcessingNoteOutput.test.js
index 43802f915..fb77ece92 100644
--- a/test/stores/actionProcessingNoteOutput.test.js
+++ b/test/stores/actionProcessingNoteOutput.test.js
@@ -44,6 +44,8 @@ async function loadStore(t, storedNote = STORED_NOTE) {
export default {
processText: async (text, model, agentName, config) => {
globalThis.__processTextCalls.push({ text, model, config });
+ const queued = globalThis.__processTextErrors?.shift();
+ if (queued) throw queued;
if (globalThis.__processTextError) throw globalThis.__processTextError;
return globalThis.__processTextResult ?? "# Notes\\n- decided things";
},
@@ -63,13 +65,14 @@ async function loadStore(t, storedNote = STORED_NOTE) {
delete globalThis.__processTextCalls;
delete globalThis.__processTextResult;
delete globalThis.__processTextError;
+ delete globalThis.__processTextErrors;
delete globalThis.__generatedTitle;
delete globalThis.__titleRequests;
delete globalThis.__updateNoteFails;
});
const store = await vite.ssrLoadModule("/stores/actionProcessingStore.ts");
- return { store, calls, updates };
+ return { store, calls, updates, vite };
}
async function waitFor(predicate, label) {
@@ -301,6 +304,217 @@ test("a cut-off or empty rewrite reports a notes error, not the dictation one pr
assert.equal(updates.length, 0);
});
+// A reasoning model at its default effort can spend the whole notes budget
+// thinking before it writes a word: GLM-5.3 on Ollama Cloud returned no notes on
+// every real meeting at 4096 tokens, and wrote them with a bigger cap (#2008).
+const ranOutThinking = async () => {
+ const { emptyResponseError } = await import("../../src/services/ai/chatRequestBody.ts");
+ return emptyResponseError("OpenAI", { systemPrompt: "Summarize" }, true);
+};
+
+// The reporter's route: GLM-5.3 on Ollama Cloud through a Custom endpoint, where
+// Settings shows "Disable thinking output".
+const CUSTOM_ROUTE_RUN = { modelId: "glm-5.3", isCloudMode: false, isMeetingNote: true };
+async function useNoteFormattingRoute(vite, provider = "custom", model = "glm-5.3") {
+ const { setResolvedLLMConfig } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ setResolvedLLMConfig("noteFormatting", { mode: "providers", provider, model });
+}
+
+test("a notes reply cut off before any answer is retried once with room for reasoning", async (t) => {
+ const { store, calls, updates } = await loadStore(t);
+ const { REASONING_MODEL_MIN_OUTPUT_TOKENS } =
+ await import("../../src/services/ai/chatRequestBody.ts");
+ const transcript = "## Meeting Transcript\nAlice: we agreed to ship on Friday.";
+ globalThis.__processTextErrors = [await ranOutThinking()];
+
+ store.runBackgroundAction(
+ 21,
+ transcript,
+ "hash",
+ ACTION,
+ { modelId: "glm-5.3", isCloudMode: true, isMeetingNote: true },
+ LABELS
+ );
+ await waitFor(() => updates.length > 0, "the notes from the retry");
+
+ assert.equal(calls.length, 2);
+ assert.equal(calls[0].config.maxTokens, 4096);
+ assert.equal(calls[1].config.maxTokens, REASONING_MODEL_MIN_OUTPUT_TOKENS);
+ assert.equal(calls[1].text, transcript);
+ assert.equal(calls[1].config.systemPrompt, calls[0].config.systemPrompt);
+ assert.equal(updates[0].payload.enhanced_content, "# Notes\n- decided things");
+});
+
+test("a retry that still thinks past its budget points at Disable thinking output, or at another model when it is on or not offered", async (t) => {
+ const { store, calls, vite } = await loadStore(t);
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ globalThis.__processTextError = await ranOutThinking();
+
+ for (const [noteId, provider, model, disableThinking, messageKey] of [
+ [23, "custom", "glm-5.3", false, "notes.actions.errors.outputSpentThinking"],
+ [24, "custom", "glm-5.3", true, "notes.actions.errors.outputSpentThinkingDisabled"],
+ // Settings hides the toggle for Corti S1, which thinks but can't be told not
+ // to, so the toast must not name it whatever the shared setting says.
+ [32, "corti", "corti-s1", false, "notes.actions.errors.outputSpentThinkingOtherModel"],
+ [33, "corti", "corti-s1", true, "notes.actions.errors.outputSpentThinkingOtherModel"],
+ ]) {
+ await useNoteFormattingRoute(vite, provider, model);
+ useSettingsStore.getState().setNoteFormattingDisableThinking(disableThinking);
+ const before = calls.length;
+ store.runBackgroundAction(
+ noteId,
+ "## Meeting Transcript\nAlice: we agreed to ship on Friday.",
+ "hash",
+ ACTION,
+ { ...CUSTOM_ROUTE_RUN, modelId: model },
+ LABELS
+ );
+
+ let events = [];
+ await waitFor(() => (events = store.consumeErrorEvents()).length > 0, "the error");
+ assert.equal(calls.length - before, 2, "one retry, never a loop");
+ assert.equal(calls.at(-2).config.disableThinking, disableThinking);
+ assert.equal(events[0].messageKey, messageKey);
+ // Open Settings lands on Language Models → Note Formatting, which the toast names.
+ assert.equal(events[0].settingsTarget, "noteFormatting");
+ }
+});
+
+test("a reply cut off when its request already had room for reasoning is not sent again, and shows the cut-off error", async (t) => {
+ const { store, calls } = await loadStore(t);
+ const { truncatedOutputError } = await import("../../src/services/ai/chatRequestBody.ts");
+ // OpenAI's own reasoning models get that room on the first request, so their
+ // cut-off carries no retry code.
+ globalThis.__processTextError = truncatedOutputError(
+ "Model ran out of output tokens before producing a response"
+ );
+
+ store.runBackgroundAction(
+ 29,
+ "## Meeting Transcript\nAlice: we agreed to ship on Friday.",
+ "hash",
+ ACTION,
+ { modelId: "gpt-5.6-terra", isCloudMode: true, isMeetingNote: true },
+ LABELS
+ );
+
+ let events = [];
+ await waitFor(() => (events = store.consumeErrorEvents()).length > 0, "the error");
+ assert.equal(calls.length, 1, "no second request with the same cap");
+ // Settings hides Disable thinking output for these models; their request never sends it.
+ assert.equal(events[0].messageKey, "notes.actions.errors.outputTruncated");
+ assert.equal(events[0].settingsTarget, undefined);
+});
+
+test("a retry the server refuses or that times out keeps the first failure's advice; any other retry failure shows as itself", async (t) => {
+ const { store, calls, vite } = await loadStore(t);
+ await useNoteFormattingRoute(vite);
+ const { asProviderError, providerHttpError } =
+ await import("../../src/helpers/providerHttpErrors.js");
+ const { llmRequestTimeoutError } = await import("../../src/helpers/llmRequestTimeout.js");
+ const context = { provider: "Ollama", model: "glm-5.3", surface: "llm" };
+ const refusal = (status, body) => providerHttpError({ ...context, status, body });
+
+ for (const [noteId, retryError, messageKey] of [
+ // Say a self-hosted server with a 32k window: the bigger cap no longer fits.
+ [
+ 25,
+ refusal(400, "max_tokens exceeds the maximum context length"),
+ "notes.actions.errors.outputSpentThinkingDisabled",
+ ],
+ // Groq counts the cap against a free tier's tokens per minute and answers 413.
+ [
+ 30,
+ refusal(413, "Request too large for model on tokens per minute (TPM)"),
+ "notes.actions.errors.outputSpentThinkingDisabled",
+ ],
+ // Still thinking at the note deadline.
+ [
+ 28,
+ asProviderError(llmRequestTimeoutError(600), context),
+ "notes.actions.errors.outputSpentThinkingDisabled",
+ ],
+ // Tinfoil rejects with the deadline error as it is, unclassified.
+ [31, llmRequestTimeoutError(600), "notes.actions.errors.outputSpentThinkingDisabled"],
+ // Out of credit between the two requests: that is what the user can fix.
+ [27, refusal(402, "insufficient credits"), "providerErrors.quotaExhausted"],
+ ]) {
+ globalThis.__processTextErrors = [await ranOutThinking(), retryError];
+ const before = calls.length;
+ store.runBackgroundAction(
+ noteId,
+ "## Meeting Transcript\nAlice: we agreed to ship on Friday.",
+ "hash",
+ ACTION,
+ CUSTOM_ROUTE_RUN,
+ LABELS
+ );
+
+ let events = [];
+ await waitFor(() => (events = store.consumeErrorEvents()).length > 0, "the error");
+ assert.equal(calls.length - before, 2);
+ assert.equal(events[0].messageKey, messageKey);
+ // The refusal's own details stay copyable, e.g. the server's context limit.
+ assert.deepEqual(events[0].technicalDetails, retryError.technicalDetails);
+ }
+});
+
+test("a run cancelled during its retry aborts the retry's request", async (t) => {
+ const { store, calls, updates, vite } = await loadStore(t);
+ const { isRequestCancelled } = await vite.ssrLoadModule("/services/ai/requestCancellation.ts");
+ let finishRetry;
+ globalThis.__processTextErrors = [await ranOutThinking()];
+ globalThis.__processTextResult = new Promise((resolve) => {
+ finishRetry = resolve;
+ });
+
+ store.runBackgroundAction(
+ 34,
+ "## Meeting Transcript\nAlice: we agreed to ship on Friday.",
+ "hash",
+ ACTION,
+ CUSTOM_ROUTE_RUN,
+ LABELS
+ );
+ await waitFor(() => calls.length === 2, "the retry");
+ const { requestId } = calls[1].config;
+ assert.equal(isRequestCancelled(requestId), false);
+
+ store.cancelAction(34);
+ // The provider aborts its 25k request on this signal rather than paying for it.
+ assert.equal(isRequestCancelled(requestId), true);
+ finishRetry("# Notes\n- too late");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.deepEqual(updates, []);
+ assert.deepEqual(store.consumeErrorEvents(), []);
+});
+
+test("a run cancelled while its first reply comes back is not retried", async (t) => {
+ const { store, calls, updates } = await loadStore(t);
+ let fail;
+ globalThis.__processTextResult = new Promise((resolve, reject) => {
+ fail = reject;
+ });
+
+ store.runBackgroundAction(
+ 26,
+ "## Meeting Transcript\nAlice: we agreed to ship on Friday.",
+ "hash",
+ ACTION,
+ { modelId: "glm-5.3", isCloudMode: true, isMeetingNote: true },
+ LABELS
+ );
+ await waitFor(() => calls.length === 1, "provider start");
+ store.cancelAction(26);
+ fail(await ranOutThinking());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(calls.length, 1, "no paid 25k request for a cancelled run");
+ assert.deepEqual(updates, []);
+ assert.deepEqual(store.consumeErrorEvents(), []);
+});
+
test("a summary action on a note without a summary writes one from the transcript, and tracks it for staleness", async (t) => {
const { store, calls, updates } = await loadStore(t);
const action = {