Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(thinking): normaler Chat und Gruppenchat raeumen die Runde jetzt auch auf

purple758eccc63c5e
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 5737c789..f3af7cca 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -69,7 +69,7 @@ import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '.
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
-import { finalStripThinkingTags, splitOrphanCloser, splitUnclosedThink } from '../lib/thinking-stripper'
+import { settleThinking } from '../lib/thinking-stripper'
import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'
import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { planResumeAnchor } from '../lib/plan-resume'
@@ -1216,52 +1216,17 @@ export function useAgentChat() {
}
}
- // Parse <think>…</think> tags. Always strip them from the content
- // (otherwise raw tags land in the assistant bubble). Only ROUTE
- // them into the collapsible thinking block when the user actually
- // toggled Thinking on — thinking-only models (QwQ, DeepSeek-R1)
- // emit these tags unconditionally, and we must not surface them
- // when the user asked for thinking to be OFF.
- turnContent = turnContent.replace(/<think>([\s\S]*?)<\/think>/g, (_match, inner) => {
- if (keepThinking) {
- turnThinking = turnThinking
- ? `${turnThinking}\n\n${inner}`
- : inner
- }
- return ''
- })
- // The Qwen3 chat templates put the opening `<think>` in the PROMPT, so
- // the reply starts mid-thought and closes a tag it never opened. With
- // thinking ON the raw closer plus the whole thought stayed in the
- // bubble.
- const orphanClose = splitOrphanCloser(turnContent)
- if (orphanClose.thinking) {
- turnContent = orphanClose.content
- if (keepThinking) {
- turnThinking = turnThinking
- ? `${turnThinking}\n\n${orphanClose.thinking}`
- : orphanClose.thinking
- }
- }
- // A turn cut off mid-thought leaves the opener without its closer,
- // which the regex above cannot match. It belongs in the thinking
- // block, never in the assistant bubble.
- const orphanThink = splitUnclosedThink(turnContent)
- if (orphanThink.thinking) {
- turnContent = orphanThink.content
- if (keepThinking) {
- turnThinking = turnThinking
- ? `${turnThinking}\n\n${orphanThink.thinking}`
- : orphanThink.thinking
- }
+ // End-of-turn settlement, through the ONE shared routine every path
+ // uses now (lib/thinking-stripper settleThinking): balanced blocks,
+ // the pre-opened Qwen3 thought that only ever sends its closer, a
+ // turn cut off mid-thought, and the non-canonical markers. Routed
+ // into the collapsible block only when the user asked for thinking:
+ // reasoners emit the tags unconditionally and OFF has to mean off.
+ {
+ const settled = settleThinking(turnContent, turnThinking, keepThinking)
+ turnContent = settled.content
+ turnThinking = settled.thinking
}
- // Strip non-canonical thinking markers (Gemma channel tags,
- // `<thought>`, `<reasoning>`, etc.) that the canonical regex above
- // doesn't catch. These never belong in the assistant bubble.
- turnContent = finalStripThinkingTags(turnContent, keepThinking)
- // Also drop any orphan native-thinking that leaked through when the
- // toggle is OFF (e.g. provider returned `turn.thinking` anyway).
- if (!keepThinking) turnThinking = ''
// Update UI — but DON'T overwrite contentRef during intermediate
// turns. Previously every iteration did `contentRef.current =
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index 280d89bc..f5cbdfe9 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -27,7 +27,7 @@ import { getProviderForModel, getProviderIdFromModel } from "../api/providers"
import { modelOutOfMode } from "../lib/modeGate"
import { syncOllamaHealthFromError } from "../lib/sync-ollama-health"
import { isThinkingCompatible, isPlainTextPlanner } from "../lib/model-compatibility"
-import { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-stripper"
+import { stripNonCanonicalTags, finalStripThinkingTags, settleThinking } from "../lib/thinking-stripper"
import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from "../lib/ollama-errors"
import type { ImageAttachment, Message } from "../types/chat"
import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers } from "../lib/group-chat"
@@ -203,7 +203,15 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
}
if (chunk.done) {
if (chunk.finishReason) groupFinish = chunk.finishReason
- contentAcc = stripImpersonatedSpeakers(finalStripThinkingTags(contentAcc, keepThinking), others)
+ // Same settlement as every other path (2.6.7 Denk-Audit): the state
+ // machine above only fires on a literal `<think>`, and a Qwen3
+ // template pre-opens the thought in the prompt, so a group speaker
+ // used to put its whole reasoning plus a raw closer in the bubble.
+ {
+ const settled = settleThinking(contentAcc, thinkingAcc, keepThinking)
+ contentAcc = stripImpersonatedSpeakers(settled.content, others)
+ thinkingAcc = settled.thinking
+ }
useChatStore.getState().updateMessageContent(convId, assistantMessage.id, contentAcc)
if (keepThinking && thinkingAcc) {
useChatStore.getState().updateMessageThinking(convId, assistantMessage.id, thinkingAcc)
@@ -804,9 +812,17 @@ export function useChat() {
finishReason = chunk.finishReason
useChatStore.getState().updateMessageFinishReason(convId!, assistantMessage.id, chunk.finishReason)
}
- // Final safety pass — catches any orphan tags that leaked through
- // mid-stream (partial chunks, provider restarts, etc.).
- contentRef.current = finalStripThinkingTags(contentRef.current, keepThinking)
+ // Final settlement — the shared one, so plain chat catches the same
+ // orphan shapes the agent loops do. Before this the char-by-char
+ // machine above was the whole story here, and it only ever fires on
+ // a literal `<think>`: a Qwen3 template that pre-opens the thought
+ // in the prompt left the whole reasoning plus a raw closer standing
+ // in the answer with the Think button ON and the block empty.
+ {
+ const settled = settleThinking(contentRef.current, thinkingRef.current, keepThinking)
+ contentRef.current = settled.content
+ thinkingRef.current = settled.thinking
+ }
useChatStore
.getState()
.updateMessageContent(convId!, assistantMessage.id, contentRef.current)
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 8e446c37..d1a68d4c 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -46,7 +46,7 @@ import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
import { budgetFromSettings } from '../api/agents/budget'
-import { finalStripThinkingTags, splitOrphanCloser, splitUnclosedThink } from '../lib/thinking-stripper'
+import { settleThinking } from '../lib/thinking-stripper'
import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'
import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { planResumeAnchor } from '../lib/plan-resume'
@@ -1459,42 +1459,18 @@ export function useCodex() {
}
}
- // Inline <think>…</think> tags — route inner text into thinking
- // block when toggle is ON, else discard. Non-canonical markers
- // (Gemma channel tags, <thought>, <reasoning>, etc.) are always
- // stripped — they are never user-facing content.
+ // End-of-turn settlement, through the ONE shared routine every path
+ // uses now (lib/thinking-stripper settleThinking): balanced blocks,
+ // the pre-opened Qwen3 thought that only ever sends its closer, a
+ // turn cut off mid-thought, and the non-canonical markers. Routed
+ // into the thinking panel only when the toggle is ON.
{
- turnContent = turnContent.replace(/<think>([\s\S]*?)<\/think>/g, (_m, inner) => {
- if (keepThinking) {
- thinkingContent += (thinkingContent ? '\n\n' : '') + inner
- useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
- }
- return ''
- })
- // The Qwen3 chat templates put the opening `<think>` in the PROMPT,
- // so the reply starts mid-thought and closes a tag it never opened.
- // Nothing above matches that, and with thinking ON the raw closer
- // plus the whole thought stayed in the answer.
- const orphanClose = splitOrphanCloser(turnContent)
- if (orphanClose.thinking) {
- turnContent = orphanClose.content
- if (keepThinking) {
- thinkingContent += (thinkingContent ? '\n\n' : '') + orphanClose.thinking
- useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
- }
- }
- // A turn cut off mid-thought leaves the opener without its closer,
- // which the regex above cannot match. It belongs in the thinking
- // panel, never in the answer.
- const orphanThink = splitUnclosedThink(turnContent)
- if (orphanThink.thinking) {
- turnContent = orphanThink.content
- if (keepThinking) {
- thinkingContent += (thinkingContent ? '\n\n' : '') + orphanThink.thinking
- useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
- }
+ const settled = settleThinking(turnContent, thinkingContent, keepThinking)
+ turnContent = settled.content
+ if (settled.thinking !== thinkingContent) {
+ thinkingContent = settled.thinking
+ useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
}
- turnContent = finalStripThinkingTags(turnContent, keepThinking)
}
// Silent-retry on system-prompt echo — Gemma 4 sometimes
diff --git a/src/lib/__tests__/hermes-stream.test.ts b/src/lib/__tests__/hermes-stream.test.ts
index 8954f307..7f5ba4a5 100644
--- a/src/lib/__tests__/hermes-stream.test.ts
+++ b/src/lib/__tests__/hermes-stream.test.ts
@@ -165,7 +165,18 @@ describe('the agent hermes branch is wired through the splitter', () => {
})
it('NEGATIVE CONTROL: the authoritative end-of-turn parse still runs on the raw text', () => {
+ // The live splitter is UI only. What the turn KEEPS is decided on the
+ // full raw text, by the one shared settlement (2.6.7 Denk-Audit moved the
+ // hand-written copy of that sequence into lib/thinking-stripper).
expect(src).toContain('const rawContent = hermesTurn.content')
- expect(src).toMatch(/turnContent = turnContent\.replace\(\/<think>/)
+ expect(src).toContain('settleThinking(turnContent, turnThinking, keepThinking)')
+ })
+
+ it('and the same branch keeps the NATIVE reasoning channel too', () => {
+ // Loch 2: this branch used to pass streamProviderTurn no thinking
+ // callback and never read hermesTurn.thinking, so a backend that parses
+ // <think> into reasoning_content by itself lost the whole thought.
+ expect(src).toContain('thinkSink.native(full); paintThink()')
+ expect(src).toContain('if (hermesTurn.thinking)')
})
})
diff --git a/src/lib/__tests__/settle-thinking-plain-chat.test.ts b/src/lib/__tests__/settle-thinking-plain-chat.test.ts
new file mode 100644
index 00000000..95437400
--- /dev/null
+++ b/src/lib/__tests__/settle-thinking-plain-chat.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Loch 4 des Denk-Audits (2.6.7, 2026-08-29): plain chat and group chat never
+ * settled the turn.
+ *
+ * Both ran the char-by-char state machine and nothing else. That machine only
+ * ever switches on a literal `<think>`. The Qwen3 chat templates put the
+ * OPENER in the prompt, so the reply starts mid-thought and only ever sends
+ * the closer, the machine never switches, and with the Think button ON
+ * `finalStripThinkingTags` deliberately leaves canonical markers alone. Result
+ * on the two surfaces a user reaches first: the whole reasoning plus a raw
+ * `</think>` standing in the answer bubble, and an empty thinking block. A
+ * thinking model that visibly does not think.
+ *
+ * The agent and coding loops had been carrying their own copy of the fix since
+ * 2.6.6. Four hand-written copies, two of them incomplete, is the shape of bug
+ * this audit was sent to end: there is one `settleThinking` now and every path
+ * calls it.
+ *
+ * Run: npx vitest run src/lib/__tests__/settle-thinking-plain-chat.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+import { settleThinking, finalStripThinkingTags } from '../thinking-stripper'
+
+const read = (p: string) =>
+ readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), 'utf8')
+
+// Read off a real turn: reasoning, closer, answer, no opener anywhere.
+const PRE_OPENED = "Okay, the user wants the capital. That is Paris.</think>The capital of France is Paris."
+
+describe('the pre-opened Qwen3 thought', () => {
+ it('goes into the block and out of the answer with thinking ON', () => {
+ const r = settleThinking(PRE_OPENED, '', true)
+ expect(r.content).toBe('The capital of France is Paris.')
+ expect(r.thinking).toBe('Okay, the user wants the capital. That is Paris.')
+ })
+
+ it('is dropped, not shown, with thinking OFF', () => {
+ const r = settleThinking(PRE_OPENED, '', false)
+ expect(r.content).toBe('The capital of France is Paris.')
+ expect(r.thinking).toBe('')
+ })
+
+ it('NEGATIVE CONTROL: the old plain-chat treatment leaks the lot', () => {
+ // This is literally what useChat did at chunk.done before the fix, and
+ // why the answer bubble carried the reasoning and a raw closer.
+ const old = finalStripThinkingTags(PRE_OPENED, true)
+ expect(old).toContain('</think>')
+ expect(old).toContain('Okay, the user wants the capital')
+ })
+})
+
+describe('the other shapes the settlement has to cover on the same call', () => {
+ it('a balanced block still routes', () => {
+ const r = settleThinking('<think>weighing it up</think>Here you go.', '', true)
+ expect(r.content).toBe('Here you go.')
+ expect(r.thinking).toBe('weighing it up')
+ })
+
+ it('native reasoning already collected is kept and the inline one appended', () => {
+ const r = settleThinking('<think>and then this</think>Done.', 'from the native channel', true)
+ expect(r.thinking).toBe('from the native channel\n\nand then this')
+ })
+
+ it('a Gemma channel tag never reaches the answer, in either direction', () => {
+ expect(settleThinking('<|channel|>thought hmm</|channel|>Answer.', '', true).content).toBe('Answer.')
+ expect(settleThinking('<|channel|>thought hmm</|channel|>Answer.', '', false).content).toBe('Answer.')
+ })
+
+ it('NEGATIVE CONTROL: a turn with no reasoning at all is handed back untouched', () => {
+ const r = settleThinking('Just an answer.', '', true)
+ expect(r.content).toBe('Just an answer.')
+ expect(r.thinking).toBe('')
+ })
+})
+
+describe('plain chat and group chat are wired to it', () => {
+ const src = read('../../hooks/useChat.ts')
+
+ it('both turns in useChat settle', () => {
+ // One call in runGroupTurn, one in the plain send path.
+ expect(src.split('settleThinking(').length - 1).toBe(2)
+ })
+
+ it('the group turn settles before the impersonation strip writes the bubble', () => {
+ expect(src).toContain('settleThinking(contentAcc, thinkingAcc, keepThinking)')
+ })
+
+ it('the plain turn settles the refs the bubble is painted from', () => {
+ expect(src).toContain('settleThinking(contentRef.current, thinkingRef.current, keepThinking)')
+ })
+})
diff --git a/src/lib/__tests__/unclosed-think.test.ts b/src/lib/__tests__/unclosed-think.test.ts
index 91e460b1..0fc998d7 100644
--- a/src/lib/__tests__/unclosed-think.test.ts
+++ b/src/lib/__tests__/unclosed-think.test.ts
@@ -20,7 +20,7 @@ import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
-import { splitUnclosedThink, finalStripThinkingTags } from '../thinking-stripper'
+import { splitUnclosedThink, finalStripThinkingTags, settleThinking } from '../thinking-stripper'
const read = (p: string) =>
readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), 'utf8')
@@ -77,24 +77,39 @@ describe('the hole this closes', () => {
})
})
-describe('both agent loops call it', () => {
- it('the coding surface routes the orphan into the thinking panel', () => {
- const src = read('../../hooks/useCodex.ts')
- expect(src).toMatch(/splitUnclosedThink\(turnContent\)/)
- expect(src).toMatch(/updateMessageThinking\(convId!, assistantMsg\.id, thinkingContent\)/)
+// The 2.6.7 Denk-Audit moved the four hand-written copies of this sequence
+// into ONE routine, `settleThinking`, because two of the four were missing
+// steps. The order inside it is what these used to pin per call site, and
+// `settleThinking` is now the only place that can get it wrong.
+describe('the settlement runs the splits BEFORE the final strip', () => {
+ it('a turn cut off mid-thought lands in the panel, not in the answer', () => {
+ const r = settleThinking("answer so far<think> Okay, let's see", '', true)
+ expect(r.content).toBe('answer so far')
+ expect(r.thinking).toBe(" Okay, let's see")
})
- it('the agent surface does the same', () => {
- const src = read('../../hooks/useAgentChat.ts')
- expect(src).toMatch(/splitUnclosedThink\(turnContent\)/)
- expect(src).toMatch(/orphanThink\.thinking/)
+ it('NEGATIVE CONTROL: thinking OFF drops it instead of showing it', () => {
+ const r = settleThinking("answer so far<think> Okay, let's see", '', false)
+ expect(r.content).toBe('answer so far')
+ expect(r.thinking).toBe('')
})
+})
+
+describe('every path routes through it', () => {
+ for (const f of [
+ '../../hooks/useCodex.ts',
+ '../../hooks/useAgentChat.ts',
+ '../../hooks/useChat.ts',
+ ]) {
+ it(`${f} calls settleThinking`, () => {
+ expect(read(f)).toContain('settleThinking(')
+ })
+ }
- it('and both do it BEFORE the final strip, or the strip would hide it', () => {
- for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {
- const src = read(f)
- expect(src.indexOf('splitUnclosedThink(turnContent)'))
- .toBeLessThan(src.indexOf('finalStripThinkingTags(turnContent, keepThinking)'))
+ it('and none of them keeps a hand-written copy of the split sequence', () => {
+ for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts', '../../hooks/useChat.ts']) {
+ expect(read(f)).not.toContain('splitUnclosedThink(')
+ expect(read(f)).not.toContain('splitOrphanCloser(')
}
})
})
diff --git a/src/lib/thinking-stripper.ts b/src/lib/thinking-stripper.ts
index 81a2026e..73b66c08 100644
--- a/src/lib/thinking-stripper.ts
+++ b/src/lib/thinking-stripper.ts
@@ -166,3 +166,57 @@ export function finalStripThinkingTags(content: string, keepCanonicalThink = fal
}
return out.trim()
}
+
+/**
+ * The end-of-turn settlement, in ONE place for every path.
+ *
+ * Four call sites used to do this by hand and only two of them did it fully.
+ * The agent loop and the coding loop ran the balanced block, then
+ * splitOrphanCloser, then splitUnclosedThink, then the final strip. Plain chat
+ * and group chat ran the char-by-char state machine and nothing else, and that
+ * machine only ever triggers on a literal `<think>`. The Qwen3 chat templates
+ * put the opener in the PROMPT: the reply starts mid-thought and only ever
+ * sends the closer, the machine never switches, and with the Think button ON
+ * `finalStripThinkingTags` deliberately leaves canonical markers alone. So the
+ * whole thought plus a raw `</think>` stood in the answer bubble and the
+ * thinking block stayed empty. That is a thinking model that visibly does not
+ * think, on the two paths a user reaches first.
+ *
+ * `content` is what the turn produced, `thinking` whatever the native channel
+ * already delivered. Returns both, settled: reasoning out of the answer, and
+ * into the block when the toggle says so.
+ */
+export function settleThinking(
+ content: string,
+ thinking: string,
+ keepThinking: boolean,
+): { content: string; thinking: string } {
+ let out = content
+ let think = thinking
+ const add = (part: string) => {
+ if (!keepThinking || !part) return
+ think = think ? `${think}\n\n${part}` : part
+ }
+
+ // Balanced blocks first — the common, well-formed case.
+ out = out.replace(/<think>([\s\S]*?)<\/think>/gi, (_m, inner: string) => {
+ add(inner)
+ return ''
+ })
+ // Closer without opener: the pre-opened Qwen3 thought.
+ const closer = splitOrphanCloser(out)
+ if (closer.thinking) {
+ out = closer.content
+ add(closer.thinking)
+ }
+ // Opener without closer: a turn stopped or cut off mid-thought.
+ const opener = splitUnclosedThink(out)
+ if (opener.thinking) {
+ out = opener.content
+ add(opener.thinking)
+ }
+ // Non-canonical markers (Gemma channel tags, <thought>, <reasoning>, …).
+ out = finalStripThinkingTags(out, keepThinking)
+ if (!keepThinking) think = ''
+ return { content: out, thinking: think }
+}