Skip to content

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

fix(ai): handle multipart responses and thinking parts in Gemini inference provider (#1968) (#1969)

Henry Su27d37898b113
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.yml
index ce8a35459..b29d5a684 100644
--- a/.github/workflows/build-and-notarize.yml
+++ b/.github/workflows/build-and-notarize.yml
@@ -30,9 +30,6 @@ jobs:
- name: Check translations
run: npm run i18n:check
- name: Audit dependencies
- # High and above only. onnxruntime-node depends on adm-zip, whose
- # symlink advisory (GHSA-vwc7-r8mq-g2x9, moderate) has no patched
- # release; failing on it would keep every PR red with nothing to fix.
run: npm audit --audit-level=high
- name: Build better-sqlite3 for the runner's node
# --ignore-scripts skips the native build; DB-backed tests silently
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8ef880bba..74f51737f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -45,9 +45,6 @@ jobs:
- name: Check translations
run: npm run i18n:check
- name: Audit dependencies
- # High and above only. onnxruntime-node depends on adm-zip, whose
- # symlink advisory (GHSA-vwc7-r8mq-g2x9, moderate) has no patched
- # release; failing on it would keep every PR red with nothing to fix.
run: npm audit --audit-level=high
- name: Build better-sqlite3 for the runner's node
# --ignore-scripts skips the native build, so DB-backed tests silently
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 7aaf8e8e9..14a3a1361 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -24,9 +24,6 @@ jobs:
- name: Check translations
run: npm run i18n:check
- name: Audit dependencies
- # High and above only. onnxruntime-node depends on adm-zip, whose
- # symlink advisory (GHSA-vwc7-r8mq-g2x9, moderate) has no patched
- # release; failing on it would keep every PR red with nothing to fix.
run: npm audit --audit-level=high
- name: Run tests
# The gates above fail on drift that has nothing to do with the suite —
diff --git a/src/helpers/geminiResponse.js b/src/helpers/geminiResponse.js
new file mode 100644
index 000000000..ce92d6c87
--- /dev/null
+++ b/src/helpers/geminiResponse.js
@@ -0,0 +1,21 @@
+// Text extraction for Gemini generateContent API responses. `content.parts`
+// is an array that may contain multiple text parts or lead with thought
+// blocks (Gemini thinking), so `parts[0].text` is not safe.
+
+/**
+ * Extract user-facing text from a Gemini generateContent response candidate.
+ * Concatenates all text parts while ignoring thought parts (from Gemini thinking).
+ * Returns trimmed text, or null if no valid text parts exist.
+ *
+ * @param {object} [candidate]
+ * @returns {string | null}
+ */
+export function extractGeminiText(candidate) {
+ const parts = candidate?.content?.parts;
+ if (!Array.isArray(parts)) return null;
+ const textParts = parts
+ .filter((part) => !part?.thought && typeof part?.text === "string" && part.text.length > 0)
+ .map((part) => part.text);
+ if (textParts.length === 0) return null;
+ return textParts.join("").trim();
+}
diff --git a/src/services/ai/inferenceProviders/gemini.ts b/src/services/ai/inferenceProviders/gemini.ts
index 35100695d..7bc4556b8 100644
--- a/src/services/ai/inferenceProviders/gemini.ts
+++ b/src/services/ai/inferenceProviders/gemini.ts
@@ -3,13 +3,14 @@ import { getCloudModel } from "../../../models/ModelRegistry";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
import { API_ENDPOINTS, TOKEN_LIMITS } 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 logger from "../../../utils/logger";
interface GeminiResponse {
candidates?: Array<{
- content?: { parts?: Array<{ text?: string }> };
+ content?: { parts?: Array<{ text?: string; thought?: boolean }> };
finishReason?: string;
}>;
usageMetadata?: { totalTokenCount?: number };
@@ -138,7 +139,8 @@ export const geminiProvider: InferenceProvider = {
if (config.requireCompleteOutput && candidate?.finishReason === "MAX_TOKENS") {
throw new Error("Model output was truncated before the selection edit completed");
}
- if (!candidate?.content?.parts?.[0]?.text) {
+ const responseText = extractGeminiText(candidate);
+ if (!responseText) {
logger.logReasoning("GEMINI_EMPTY_RESPONSE", {
model,
finishReason: candidate?.finishReason,
@@ -150,8 +152,6 @@ export const geminiProvider: InferenceProvider = {
}
throw new Error("Gemini returned empty response");
}
-
- const responseText = candidate.content.parts[0].text!.trim();
logger.logReasoning("GEMINI_RESPONSE", {
model,
responseLength: responseText.length,
diff --git a/test/helpers/geminiResponse.test.js b/test/helpers/geminiResponse.test.js
new file mode 100644
index 000000000..74e8a8da5
--- /dev/null
+++ b/test/helpers/geminiResponse.test.js
@@ -0,0 +1,73 @@
+const { test, describe } = require("node:test");
+const assert = require("node:assert");
+
+const load = () => import("../../src/helpers/geminiResponse.js");
+
+describe("extractGeminiText", () => {
+ test("returns trimmed text for a normal single text part", async () => {
+ const { extractGeminiText } = await load();
+ const candidate = {
+ content: {
+ parts: [{ text: " cleaned up transcript " }],
+ },
+ };
+ assert.strictEqual(extractGeminiText(candidate), "cleaned up transcript");
+ });
+
+ test("joins multiple text parts into a single string", async () => {
+ const { extractGeminiText } = await load();
+ const candidate = {
+ content: {
+ parts: [{ text: "First paragraph.\n\n" }, { text: "Second paragraph." }],
+ },
+ };
+ assert.strictEqual(extractGeminiText(candidate), "First paragraph.\n\nSecond paragraph.");
+ });
+
+ test("skips thought parts and returns subsequent text parts", async () => {
+ const { extractGeminiText } = await load();
+ const candidate = {
+ content: {
+ parts: [
+ { thought: true, text: "Let me think about this transcript..." },
+ { text: "Here is the cleaned result." },
+ ],
+ },
+ };
+ assert.strictEqual(extractGeminiText(candidate), "Here is the cleaned result.");
+ });
+
+ test("returns null when only thought parts are present", async () => {
+ const { extractGeminiText } = await load();
+ const candidate = {
+ content: {
+ parts: [{ thought: true, text: "Thinking only..." }],
+ },
+ };
+ assert.strictEqual(extractGeminiText(candidate), null);
+ });
+
+ test("returns null when parts array is empty", async () => {
+ const { extractGeminiText } = await load();
+ assert.strictEqual(extractGeminiText({ content: { parts: [] } }), null);
+ });
+
+ test("returns null for malformed or missing candidate", async () => {
+ const { extractGeminiText } = await load();
+ assert.strictEqual(extractGeminiText(null), null);
+ assert.strictEqual(extractGeminiText(undefined), null);
+ assert.strictEqual(extractGeminiText({}), null);
+ assert.strictEqual(extractGeminiText({ content: null }), null);
+ assert.strictEqual(extractGeminiText({ content: { parts: "invalid" } }), null);
+ });
+
+ test("skips parts without text or with empty text", async () => {
+ const { extractGeminiText } = await load();
+ const candidate = {
+ content: {
+ parts: [{ inlineData: {} }, { text: "" }, { text: "Valid text" }],
+ },
+ };
+ assert.strictEqual(extractGeminiText(candidate), "Valid text");
+ });
+});
diff --git a/test/services/geminiProviderResponse.test.js b/test/services/geminiProviderResponse.test.js
new file mode 100644
index 000000000..0c768f564
--- /dev/null
+++ b/test/services/geminiProviderResponse.test.js
@@ -0,0 +1,90 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/ai/inferenceProviders/gemini.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,
+};
+
+function createGeminiResponse(parts, finishReason = "STOP") {
+ return {
+ candidates: [
+ {
+ content: { role: "model", parts },
+ finishReason,
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 12,
+ candidatesTokenCount: 4,
+ totalTokenCount: 16,
+ },
+ };
+}
+
+async function callGemini(t, response, config = {}) {
+ const originalFetch = globalThis.fetch;
+ t.after(() => {
+ globalThis.fetch = originalFetch;
+ });
+ globalThis.fetch = async () =>
+ 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",
+ agentName: null,
+ config: { systemPrompt: "Clean the transcript", ...config },
+ ctx: providerContext,
+ });
+}
+
+test("Gemini provider returns all visible text without leaking thought or non-text parts", async (t) => {
+ const response = createGeminiResponse([
+ { thought: true, text: "Private reasoning" },
+ { functionCall: { name: "ignored", args: {} } },
+ { text: "First paragraph.\n\n" },
+ { inlineData: { mimeType: "image/png", data: "ignored" } },
+ { text: "Second paragraph." },
+ ]);
+
+ assert.equal(await callGemini(t, response), "First paragraph.\n\nSecond paragraph.");
+});
+
+test("Gemini provider accepts text after a leading non-text part", async (t) => {
+ const response = createGeminiResponse([
+ { functionCall: { name: "ignored", args: {} } },
+ { text: "Visible answer" },
+ ]);
+
+ assert.equal(await callGemini(t, response), "Visible answer");
+});
+
+test("Gemini provider rejects whitespace-only text as an empty response", async (t) => {
+ const response = createGeminiResponse([{ text: " \n " }]);
+
+ await assert.rejects(callGemini(t, response), /Gemini returned empty response/);
+});
+
+test("Gemini provider preserves complete-output truncation errors before extraction", async (t) => {
+ const response = createGeminiResponse([{ text: "Partial answer" }], "MAX_TOKENS");
+
+ await assert.rejects(
+ callGemini(t, response, { requireCompleteOutput: true }),
+ /Model output was truncated before the selection edit completed/
+ );
+});