Skip to content

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

fix(reasoning): strip nested think blocks without leftover tags (#1619)

Henry Su78b77dde7adc
diff --git a/src/helpers/stripThinking.js b/src/helpers/stripThinking.js
index d108cc580..39d682b10 100644
--- a/src/helpers/stripThinking.js
+++ b/src/helpers/stripThinking.js
@@ -1,9 +1,14 @@
// Strip <think>...</think> blocks (including unterminated ones) emitted by
-// reasoning models. Mirrors the regex in localReasoningBridge.js.
+// reasoning models. Innermost closed pairs are removed first so nested blocks
+// cannot leave a stray </think>, then a trailing unterminated <think> is removed.
export function stripThinkingTags(text) {
if (typeof text !== "string") return text;
- return text
- .replace(/<think>[\s\S]*?<\/think>/g, "")
- .replace(/<think>[\s\S]*$/, "")
- .trim();
+ const innermostClosed = /<think>(?:(?!<think>)[\s\S])*?<\/think>/;
+ let out = text;
+ let next = out.replace(innermostClosed, "");
+ while (next !== out) {
+ out = next;
+ next = out.replace(innermostClosed, "");
+ }
+ return next.replace(/<think>[\s\S]*$/, "").trim();
}
diff --git a/src/services/localReasoningBridge.js b/src/services/localReasoningBridge.js
index cf9d7ec9f..8b751b43a 100644
--- a/src/services/localReasoningBridge.js
+++ b/src/services/localReasoningBridge.js
@@ -49,10 +49,7 @@ class LocalReasoningService {
const result = await modelManager.runInference(modelId, text, inferenceConfig);
const stripThinking = config.disableThinking !== false;
const cleanResult = stripThinking
- ? result
- .replace(/<think>[\s\S]*?<\/think>/g, "")
- .replace(/<think>[\s\S]*$/, "")
- .trim()
+ ? (await import("../helpers/stripThinking.js")).stripThinkingTags(result)
: result.trim();
const processingTime = Date.now() - startTime;
diff --git a/test/helpers/stripThinking.test.js b/test/helpers/stripThinking.test.js
index fdc3055b1..1432b6341 100644
--- a/test/helpers/stripThinking.test.js
+++ b/test/helpers/stripThinking.test.js
@@ -35,3 +35,21 @@ test("non-string input is returned as-is", async () => {
const { stripThinkingTags } = await load();
assert.equal(stripThinkingTags(undefined), undefined);
});
+
+test("peels nested think blocks instead of leaving a stray close tag", async () => {
+ const { stripThinkingTags } = await load();
+ assert.equal(stripThinkingTags("<think>a<think>b</think>c</think>Answer"), "Answer");
+});
+
+test("peels doubly nested think blocks", async () => {
+ const { stripThinkingTags } = await load();
+ assert.equal(
+ stripThinkingTags("<think>outer<think>mid<think>inner</think>x</think>y</think>Done"),
+ "Done"
+ );
+});
+
+test("still keeps sequential (non-nested) think blocks from leaking", async () => {
+ const { stripThinkingTags } = await load();
+ assert.equal(stripThinkingTags("<think>one</think>Keep<think>two</think>This"), "KeepThis");
+});