Skip to content

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

fix: prevent silent dictation truncation during Gemini cleanup (#2092)

Idris Gadi450f50f98c69
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index c5de5adc5..698bbc032 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -204,6 +204,11 @@ function resolveReasoningRoute(
) {
const wakeWordLanguage = resolveWakeWordLanguage(settings, detectedLanguage, text);
const cleanup = selectResolvedLLMConfig(settings, "dictationCleanup");
+ // Pin cleanup to 0 where supported; bridges otherwise default to 0.7 (local)
+ // or 0.3 (Anthropic/enterprise). Zero does not guarantee determinism.
+ // Direct Gemini owns its defaults (3: 1.0, older: 0); check mode to ignore stale providers.
+ const cleanupTemperature =
+ cleanup.mode === "providers" && cleanup.provider === "gemini" ? undefined : 0;
const cleanupReachable =
!!settings.useCleanupModel && (!!cleanup.model?.trim() || isCloudCleanupMode());
const agent = resolveDictationAgentInference(settings, {
@@ -246,16 +251,14 @@ 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.
+ // Shared by ordinary cleanup and the translation chain's cleanup step.
// 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,
+ temperature: cleanupTemperature,
requireCompleteOutput: true,
};
if (kind === "translation") {
diff --git a/src/services/ai/inferenceProviders/gemini.ts b/src/services/ai/inferenceProviders/gemini.ts
index 41bf689dd..9db5c3d70 100644
--- a/src/services/ai/inferenceProviders/gemini.ts
+++ b/src/services/ai/inferenceProviders/gemini.ts
@@ -1,5 +1,4 @@
import type { InferenceProvider } from "./types";
-import { getCloudModel } from "../../../models/ModelRegistry";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
import { API_ENDPOINTS } from "../../../config/constants";
import { getLlmRequestTimeoutSeconds } from "../../../helpers/llmRequestTimeout.js";
@@ -14,17 +13,35 @@ interface GeminiResponse {
content?: { parts?: Array<{ text?: string; thought?: boolean }> };
finishReason?: string;
}>;
- usageMetadata?: { totalTokenCount?: number };
+ usageMetadata?: {
+ promptTokenCount?: number;
+ candidatesTokenCount?: number;
+ thoughtsTokenCount?: number;
+ totalTokenCount?: number;
+ };
}
interface GeminiGenerationConfig {
temperature: number;
thinkingConfig?: {
- thinkingLevel: "minimal" | "low" | "medium" | "high";
+ thinkingLevel?: "minimal" | "low";
+ thinkingBudget?: number;
includeThoughts: boolean;
};
}
+// Thinking controls differ by model: Pro cannot use minimal, and 2.5 uses budgets.
+const minimalThinking: Record<string, GeminiGenerationConfig["thinkingConfig"]> = {
+ "gemini-3.5-flash": { thinkingLevel: "minimal", includeThoughts: false },
+ "gemini-3.5-flash-lite": { thinkingLevel: "minimal", includeThoughts: false },
+ "gemini-3.1-flash-lite": { thinkingLevel: "minimal", includeThoughts: false },
+ "gemini-3-flash-preview": { thinkingLevel: "minimal", includeThoughts: false },
+ "gemini-3.1-pro-preview": { thinkingLevel: "low", includeThoughts: false },
+ "gemini-2.5-flash": { thinkingBudget: 0, includeThoughts: false },
+ "gemini-2.5-flash-lite": { thinkingBudget: 0, includeThoughts: false },
+ "gemini-2.5-pro": { thinkingBudget: 128, includeThoughts: false },
+};
+
export const geminiProvider: InferenceProvider = {
id: "gemini",
supportsImages: true,
@@ -36,20 +53,26 @@ export const geminiProvider: InferenceProvider = {
const systemPrompt = config.systemPrompt || ctx.getSystemPrompt(agentName);
const userContent = config.systemPrompt ? text : wrapCleanupTranscript(text);
+ const isGemini = model.startsWith("gemini-");
+ const isGemini3 = model.startsWith("gemini-3-") || model.startsWith("gemini-3.");
const generationConfig: GeminiGenerationConfig = {
- temperature: config.temperature ?? (config.systemPrompt ? 0.3 : 0),
+ // Google recommends 1.0 for Gemini 3 to avoid low-temperature looping.
+ // Cleanup defers here; explicit overrides still win.
+ // https://ai.google.dev/gemini-api/docs/gemini-3#temperature
+ temperature: config.temperature ?? (isGemini3 ? 1 : config.systemPrompt ? 0.3 : 0),
// 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) {
- generationConfig.thinkingConfig = { thinkingLevel: "minimal", includeThoughts: false };
+ if (config.disableThinking === true && minimalThinking[model]) {
+ generationConfig.thinkingConfig = minimalThinking[model];
}
const parts: Array<{ text: string } | { inlineData: { mimeType: string; data: string } }> = [
- { text: `${systemPrompt}\n\n${userContent}` },
+ // Keep the existing inline instructions for non-Gemini models (e.g. Gemma).
+ { text: isGemini ? userContent : `${systemPrompt}\n\n${userContent}` },
];
if (config.screenContext) {
parts.push({
@@ -60,22 +83,20 @@ export const geminiProvider: InferenceProvider = {
});
}
const requestBody = {
+ ...(isGemini ? { systemInstruction: { parts: [{ text: systemPrompt }] } } : {}),
contents: [{ parts }],
generationConfig,
};
const response = await withRetry(async () => {
+ // Metadata only: body previews can leak transcript text or base64 screenshots.
logger.logReasoning("GEMINI_REQUEST", {
endpoint: `${API_ENDPOINTS.GEMINI}/models/${model}:generateContent`,
model,
hasApiKey: !!apiKey,
hasScreenContext: !!config.screenContext,
- // A short prompt could let the 200-char preview reach into the base64
- // image part — preview the text part only, never the full body.
- requestBody: JSON.stringify({
- ...requestBody,
- contents: [{ parts: [parts[0]] }],
- }).substring(0, 200),
+ generationConfig,
+ textLength: text.length,
});
const controller = new AbortController();
@@ -116,6 +137,8 @@ export const geminiProvider: InferenceProvider = {
hasResponse: !!jsonResponse,
hasCandidates: !!jsonResponse?.candidates,
candidatesLength: jsonResponse?.candidates?.length || 0,
+ finishReason: jsonResponse?.candidates?.[0]?.finishReason,
+ usageMetadata: jsonResponse?.usageMetadata,
});
return jsonResponse;
} catch (error) {
@@ -129,23 +152,24 @@ export const geminiProvider: InferenceProvider = {
}, createApiRetryStrategy());
const candidate = response.candidates?.[0];
- if (config.requireCompleteOutput && candidate?.finishReason === "MAX_TOKENS") {
+ // Outside withRetry: don't repeat cutoffs/blocks; cleanup falls back to the original.
+ if (candidate?.finishReason === "MAX_TOKENS") {
throw truncatedOutputError();
}
+ if (candidate?.finishReason !== "STOP") {
+ throw new Error(
+ `Gemini returned incomplete output (${candidate?.finishReason || "missing finish reason"})`
+ );
+ }
const responseText = extractGeminiText(candidate);
if (!responseText) {
logger.logReasoning("GEMINI_EMPTY_RESPONSE", {
model,
finishReason: candidate?.finishReason,
});
- if (candidate?.finishReason === "MAX_TOKENS") {
- // 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 emptyOutputError("Gemini returned empty response");
}
+
logger.logReasoning("GEMINI_RESPONSE", {
model,
responseLength: responseText.length,
diff --git a/test/helpers/audioManagerCleanupFallback.test.js b/test/helpers/audioManagerCleanupFallback.test.js
index 275c6200c..df95f9781 100644
--- a/test/helpers/audioManagerCleanupFallback.test.js
+++ b/test/helpers/audioManagerCleanupFallback.test.js
@@ -208,3 +208,49 @@ test("safePaste returns true only when the preload reports a completed paste", a
assert.equal(await manager.safePaste("completed transcript"), true);
});
+
+test("translation cleanup failures survive successful and skipped translation for post-paste warnings", async (t) => {
+ const { createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-translation-cleanup-warning-",
+ settingsKey: "__translationCleanupWarningSettings",
+ });
+ const rawText = "Full first sentence. Full final sentence.";
+ const failure = new Error("Gemini returned incomplete output (MAX_TOKENS)");
+
+ for (const targetLanguage of ["en", "es"]) {
+ const manager = createManager({
+ pendingCleanupFailure: null,
+ processWithReasoningModel: async (text, model) => {
+ assert.equal(text, rawText);
+ if (model === "cleanup-model") throw failure;
+ assert.equal(model, "translation-model");
+ assert.equal(targetLanguage, "es");
+ return "Primera frase completa. Última frase completa.";
+ },
+ notifyTranslationFallback: () => assert.fail("translation did not fail"),
+ });
+
+ const result = await manager.runTranslationChain({
+ text: rawText,
+ settings: { translationSourceLanguage: "en", translationTargetLanguage: targetLanguage },
+ agentName: null,
+ route: {
+ model: "translation-model",
+ cleanupReachable: true,
+ cleanupConfig: {},
+ config: {},
+ },
+ cleanup: { mode: "model", model: "cleanup-model" },
+ });
+
+ assert.equal(
+ result.text,
+ targetLanguage === "en" ? rawText : "Primera frase completa. Última frase completa."
+ );
+ assert.equal(result.translated, targetLanguage === "es");
+ assert.deepEqual(manager._takePendingResultExtras(), {
+ cleanupFailure: { message: failure.message },
+ });
+ assert.deepEqual(manager._takePendingResultExtras(), {});
+ }
+});
diff --git a/test/helpers/cleanupRouteConfig.test.js b/test/helpers/cleanupRouteConfig.test.js
index abd7ff1e2..e0258e427 100644
--- a/test/helpers/cleanupRouteConfig.test.js
+++ b/test/helpers/cleanupRouteConfig.test.js
@@ -2,14 +2,9 @@ const test = require("node:test");
const assert = require("node:assert/strict");
const { loadAudioManager } = require("./harness/audioManager");
-// The cleanup configs are the only callers that can pin sampling for the
-// 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. 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) {
+// Pin both cleanup routes against bridge defaults (local: 0.7, Anthropic/enterprise: 0.3).
+// Only direct Gemini defers to model defaults; stale provider selections must not leak.
+async function loadRouteResolver(t, provider = "test", mode = "providers") {
const { vite } = await loadAudioManager(t, {
cachePrefix: "openwhispr-cleanup-route-config-test-",
settingsKey: "__cleanupRouteConfigSettings",
@@ -17,7 +12,7 @@ async function loadRouteResolver(t) {
"/stores/settingsStore": `
export const getSettings = () => globalThis.__cleanupRouteConfigSettings;
export const getEffectiveCleanupModel = () => "cleanup-model";
- export const selectResolvedLLMConfig = () => ({ model: "cleanup-model" });
+ export const selectResolvedLLMConfig = () => ({ model: "cleanup-model", provider: ${JSON.stringify(provider)}, mode: ${JSON.stringify(mode)} });
export const isCloudCleanupMode = () => false;
export const isCloudDictationAgentMode = () => false;
export const isCloudTranslationMode = () => false;
@@ -78,6 +73,25 @@ test("the translation chain's cleanup step pins the same config", async (t) => {
assert.equal(route.cleanupConfig.inferenceScope, "dictationCleanup");
assert.equal(route.cleanupConfig.temperature, 0);
assert.equal(route.cleanupConfig.requireCompleteOutput, true);
+ assert.equal(route.config.temperature, undefined);
+});
+
+test("both Gemini cleanup paths defer temperature to the provider", async (t) => {
+ const resolveRoute = await loadRouteResolver(t, "gemini");
+ assert.equal(resolveRoute("clean this").config.temperature, undefined);
+ assert.equal(
+ resolveRoute("translate this", { translationRequested: true }).cleanupConfig.temperature,
+ undefined
+ );
+});
+
+test("a stale Gemini selection does not change other cleanup modes", async (t) => {
+ const resolveRoute = await loadRouteResolver(t, "gemini", "local");
+ assert.equal(resolveRoute("clean this").config.temperature, 0);
+ assert.equal(
+ resolveRoute("translate this", { translationRequested: true }).cleanupConfig.temperature,
+ 0
+ );
});
test("the agent route keeps its provider defaults", async (t) => {
diff --git a/test/services/geminiInference.test.js b/test/services/geminiInference.test.js
new file mode 100644
index 000000000..d50b26fdc
--- /dev/null
+++ b/test/services/geminiInference.test.js
@@ -0,0 +1,152 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+async function setup(
+ t,
+ response = {
+ candidates: [{ finishReason: "STOP", content: { parts: [{ text: "Clean text." }] } }],
+ }
+) {
+ const { geminiProvider } = await import("../../src/services/ai/inferenceProviders/gemini.ts");
+ const { default: logger } = require("../../src/utils/logger.ts");
+ const requests = [];
+ const logs = [];
+ t.mock.method(logger, "logReasoning", (event, data) => logs.push({ event, data }));
+ t.mock.method(globalThis, "fetch", async (_url, init) => {
+ requests.push(JSON.parse(init.body));
+ return Response.json(response);
+ });
+ return {
+ requests,
+ logs,
+ call: (overrides = {}) =>
+ geminiProvider.call({
+ text: "private transcript",
+ model: "gemini-3-flash-preview",
+ agentName: null,
+ config: { disableThinking: true },
+ ctx: {
+ getApiKey: async () => "test-key",
+ getSystemPrompt: () => "Clean without omitting content.",
+ },
+ ...overrides,
+ }),
+ };
+}
+
+test("Gemini cleanup uses native instructions and metadata-only logs", async (t) => {
+ const usageMetadata = {
+ promptTokenCount: 100,
+ candidatesTokenCount: 20,
+ thoughtsTokenCount: 10,
+ totalTokenCount: 130,
+ };
+ const { call, requests, logs } = await setup(t, {
+ candidates: [{ finishReason: "STOP", content: { parts: [{ text: "Clean text." }] } }],
+ usageMetadata,
+ });
+ assert.equal(await call(), "Clean text.");
+ assert.deepEqual(requests[0].generationConfig, {
+ temperature: 1,
+ thinkingConfig: { thinkingLevel: "minimal", includeThoughts: false },
+ });
+ assert.deepEqual(requests[0].systemInstruction, {
+ parts: [{ text: "Clean without omitting content." }],
+ });
+ assert.equal(
+ requests[0].contents[0].parts[0].text,
+ "<transcript>\nprivate transcript\n</transcript>\n\nOutput only the cleaned transcript."
+ );
+ assert.equal(JSON.stringify(logs).includes("private transcript"), false);
+ assert.deepEqual(
+ logs.find(({ event }) => event === "GEMINI_RAW_RESPONSE").data.usageMetadata,
+ usageMetadata
+ );
+ assert.equal(logs.find(({ event }) => event === "GEMINI_RAW_RESPONSE").data.finishReason, "STOP");
+ assert.deepEqual(
+ logs.find(({ event }) => event === "GEMINI_REQUEST").data.generationConfig,
+ requests[0].generationConfig
+ );
+});
+
+test("thinking suppression uses controls supported by each registered Gemini model", async (t) => {
+ const { call, requests } = await setup(t);
+ for (const [model, control] of [
+ ["gemini-3.5-flash", { thinkingLevel: "minimal" }],
+ ["gemini-3.5-flash-lite", { thinkingLevel: "minimal" }],
+ ["gemini-3.1-flash-lite", { thinkingLevel: "minimal" }],
+ ["gemini-3.1-pro-preview", { thinkingLevel: "low" }],
+ ["gemini-2.5-flash", { thinkingBudget: 0 }],
+ ["gemini-2.5-flash-lite", { thinkingBudget: 0 }],
+ ["gemini-2.5-pro", { thinkingBudget: 128 }],
+ ]) {
+ await call({ model });
+ assert.equal(
+ requests.at(-1).generationConfig.temperature,
+ model.startsWith("gemini-3") ? 1 : 0
+ );
+ assert.deepEqual(
+ requests.at(-1).generationConfig.thinkingConfig,
+ { ...control, includeThoughts: false },
+ model
+ );
+ }
+ await call({ config: { disableThinking: false } });
+ assert.equal(requests.at(-1).generationConfig.thinkingConfig, undefined);
+});
+
+test("long inputs remain uncapped while explicit temperature and prompts are preserved", async (t) => {
+ const { call, requests } = await setup(t);
+ await call({ text: "x".repeat(10000) });
+ assert.equal(requests.at(-1).generationConfig.maxOutputTokens, undefined);
+ await call({ text: "x".repeat(100000) });
+ assert.equal(requests.at(-1).generationConfig.maxOutputTokens, undefined);
+ await call({ config: { temperature: 0, maxTokens: 1234, systemPrompt: "Custom prompt" } });
+ assert.equal(requests.at(-1).generationConfig.temperature, 0);
+ assert.equal(requests.at(-1).generationConfig.maxOutputTokens, undefined);
+ assert.equal(requests.at(-1).systemInstruction.parts[0].text, "Custom prompt");
+ assert.equal(requests.at(-1).contents[0].parts[0].text, "private transcript");
+});
+
+test("Gemma retains inline instructions and receives no unsupported thinking controls", async (t) => {
+ const { call, requests } = await setup(t);
+ await call({ model: "gemma-4-31b-it" });
+ assert.equal(requests[0].systemInstruction, undefined);
+ assert.ok(
+ requests[0].contents[0].parts[0].text.startsWith("Clean without omitting content.\n\n")
+ );
+ assert.equal(requests[0].generationConfig.thinkingConfig, undefined);
+ assert.equal(requests[0].generationConfig.temperature, 0);
+});
+
+test("cleanup rejects incomplete responses without retrying", async (t) => {
+ for (const [name, candidate] of [
+ ["partial cutoff", { finishReason: "MAX_TOKENS", content: { parts: [{ text: "Partial" }] } }],
+ ["empty cutoff", { finishReason: "MAX_TOKENS" }],
+ ["blocked partial", { finishReason: "SAFETY", content: { parts: [{ text: "Partial" }] } }],
+ ["missing finish reason", { content: { parts: [{ text: "Partial" }] } }],
+ ["missing candidate", undefined],
+ ]) {
+ await t.test(name, async (t) => {
+ const { call, requests } = await setup(t, { candidates: candidate ? [candidate] : [] });
+ await assert.rejects(call(), (error) => {
+ if (candidate?.finishReason === "MAX_TOKENS") {
+ assert.equal(error.messageKey, "hooks.audioRecording.errorDescriptions.cleanupTruncated");
+ } else {
+ assert.match(error.message, /Gemini returned incomplete output/);
+ }
+ return true;
+ });
+ assert.equal(requests.length, 1);
+ });
+ }
+});
+
+test("screenshots remain attached but are never included in request logs", async (t) => {
+ const { call, requests, logs } = await setup(t);
+ await call({ config: { screenContext: { mediaType: "image/jpeg", data: "private-base64" } } });
+ assert.deepEqual(requests[0].contents[0].parts[1], {
+ inlineData: { mimeType: "image/jpeg", data: "private-base64" },
+ });
+ assert.equal(JSON.stringify(logs).includes("private-base64"), false);
+});