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): der Prompt-Transport verliert den Gedanken nicht mehr

purple608342efa2c4
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 6432fcc0..5737c789 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -10,7 +10,7 @@ import {
} from '../lib/approval-queue'
import { v4 as uuid } from 'uuid'
import { streamProviderTurn } from '../lib/provider-stream'
-import { createHermesDisplayFilter, createThinkStreamSplitter } from '../lib/hermes-stream'
+import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'
import { beginAgentRun, endAgentRun, setActiveAgentModel, renderWorkspaceSection, takeChatArtifacts, type AgentRunContext } from '../api/agent-context'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
import { isOllamaLocal } from '../api/backend'
@@ -1158,9 +1158,21 @@ export function useAgentChat() {
// end-of-turn parse on the full raw text stays authoritative.
const splitter = createThinkStreamSplitter({ startInThink: keepThinking })
let shown = ''
+ // Two live reasoning sources on this transport, merged by the one
+ // shared sink so neither can overwrite the other: the <think> spans
+ // the splitter pulls out of the text stream, and the native
+ // reasoning channel the backend may fill instead. Paint only; the
+ // end-of-turn parse on the full raw text stays authoritative.
+ const thinkSink = createTurnThinkingSink()
+ const paintThink = () => {
+ if (!keepThinking) return
+ thinkingRef.current = thinkSink.live()
+ scheduleUIUpdate()
+ }
const feedUI = (chunk: { prose: string; thinking: string }) => {
if (chunk.thinking && keepThinking) {
- thinkingRef.current += chunk.thinking.replace(/<think>/g, '')
+ thinkSink.inline(chunk.thinking)
+ paintThink()
}
if (chunk.prose) shown += chunk.prose
contentRef.current = shown
@@ -1177,9 +1189,21 @@ export function useAgentChat() {
sendMessages,
{ ...chatOptions, thinking: undefined as unknown as boolean },
(_full, delta) => feedUI(splitter.feed(display.feed(delta))),
+ // A prompt-transport backend can still answer on the NATIVE
+ // reasoning channel: the built-in engine extracts <think> into
+ // reasoning_content itself and the provider yields it as
+ // `thinking`. This branch passed no thinking callback and never
+ // read hermesTurn.thinking either, so that reasoning fell on the
+ // floor and the block stayed empty with the Think button on.
+ (full) => { thinkSink.native(full); paintThink() },
)
feedUI(splitter.feed(display.flush()))
feedUI(splitter.flush())
+ if (hermesTurn.thinking) {
+ turnThinking = turnThinking
+ ? `${turnThinking}\n\n${hermesTurn.thinking}`
+ : hermesTurn.thinking
+ }
const rawContent = hermesTurn.content
if (hasToolCallTags(rawContent)) {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index d69b30cb..8e446c37 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -16,7 +16,7 @@ import { useAgentLoopStore } from '../stores/agentLoopStore'
import { CODEX_CONFIRM_TOOLS } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, buildHermesToolCall, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
-import { createHermesDisplayFilter } from '../lib/hermes-stream'
+import { createHermesDisplayFilter, createThinkStreamSplitter, createTurnThinkingSink } from '../lib/hermes-stream'
import { beginAgentRun, endAgentRun, setActiveAgentModel, type AgentRunContext } from '../api/agent-context'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
import { codexModeKnobs, CODEX_MODE_LABELS, type CodexMode } from '../lib/codex-mode'
@@ -959,6 +959,13 @@ export function useCodex() {
thinking: thinkOptCx as unknown as boolean,
signal: abort.signal,
}
+ // Hoisted to the top of the step (2.6.7 Denk-Audit): the prompt
+ // transport declared its own copy AFTER the stream, so the branch that
+ // needed it while streaming could not see it at all. One gate per step,
+ // read by every transport and by the end-of-turn routing.
+ const keepThinking =
+ codexThinkMode(activeModel) === 'always' ||
+ (settings.thinkingEnabled === true && codexCanThink(activeModel))
// ── Request build (2.6.6, plan A1/A2/A3) ─────────────────────────
// Age decay, then the send budget, then compaction, in that order.
@@ -1175,10 +1182,6 @@ export function useCodex() {
lastUserMsg: lastUserMsg.slice(0, 120),
})
- const keepThinking =
- codexThinkMode(activeModel) === 'always' ||
- (settings.thinkingEnabled === true && codexCanThink(activeModel))
-
if (providerId === 'ollama') {
// ── Streaming path for Ollama ──────────────────────────────
// Shows live content/thinking tokens so the user isn't staring
@@ -1386,18 +1389,61 @@ export function useCodex() {
// which spoke Ollama's /api/chat and quietly mis-routed hermes
// turns on every other provider.
const display = createHermesDisplayFilter()
+ // G35 parity with the Agent path (David 2026-08-07): the thought
+ // streams inside the SAME bounded ThinkingBlock window, never
+ // full-height into the answer. Without the splitter this branch fed
+ // the raw reasoning straight into the answer bubble for the whole
+ // turn, and only the end-of-turn parse pulled it back out again.
+ // The Qwen3 templates pre-open the thought in the PROMPT, so the
+ // stream begins mid-thought and only ever sends the closer, which
+ // is what startInThink covers.
+ const splitter = createThinkStreamSplitter({ startInThink: keepThinking })
let shown = ''
+ // Live only, through the SAME shared sink the Agent path uses, so
+ // the inline <think> spans and the native reasoning channel cannot
+ // overwrite each other. Nothing is committed into thinkingContent
+ // here: the authoritative end-of-turn parse runs on the FULL raw
+ // text and owns what counts, exactly like the tool-call extraction.
+ const thinkSink = createTurnThinkingSink()
+ const paintThink = () => {
+ if (!keepThinking) return
+ const live = thinkSink.live()
+ if (!live) return
+ useChatStore.getState().updateMessageThinking(
+ convId!, assistantMsg.id, thinkingContent ? thinkingContent + '\n\n' + live : live,
+ )
+ }
+ const feedUI = (part: { prose: string; thinking: string }) => {
+ if (part.thinking) {
+ thinkSink.inline(part.thinking)
+ paintThink()
+ }
+ if (part.prose) {
+ shown += part.prose
+ liveContent(shown)
+ }
+ }
const hermesTurn = await streamProviderTurn(
provider,
modelToUse,
sendMessages.map(m => ({ role: m.role, content: m.content })),
{ ...chatOptions, thinking: undefined as unknown as boolean, contextWindow: numCtx },
- (_full, delta) => {
- shown += display.feed(delta)
- liveContent(shown)
- },
+ (_full, delta) => feedUI(splitter.feed(display.feed(delta))),
+ // A prompt-transport backend can still answer on the NATIVE
+ // reasoning channel: llama-server extracts <think> into
+ // reasoning_content by itself and the provider yields it as
+ // `thinking`. This branch used to pass streamProviderTurn no
+ // thinking callback at all and then never read hermesTurn.thinking
+ // either, so that reasoning fell on the floor and the block stayed
+ // empty with the Think button switched on.
+ (full) => { thinkSink.native(full); paintThink() },
)
- shown += display.flush()
+ feedUI(splitter.feed(display.flush()))
+ feedUI(splitter.flush())
+ if (keepThinking && hermesTurn.thinking) {
+ thinkingContent += (thinkingContent ? '\n\n' : '') + hermesTurn.thinking
+ useChatStore.getState().updateMessageThinking(convId!, assistantMsg.id, thinkingContent)
+ }
// Final paint DIRECT + settle the coalesced frame, so a queued
// stale frame can never fire after the writes below (audit D1).
settleLivePaint()
@@ -1418,9 +1464,6 @@ export function useCodex() {
// (Gemma channel tags, <thought>, <reasoning>, etc.) are always
// stripped — they are never user-facing content.
{
- const keepThinking =
- codexThinkMode(activeModel) === 'always' ||
- (settings.thinkingEnabled === true && codexCanThink(activeModel))
turnContent = turnContent.replace(/<think>([\s\S]*?)<\/think>/g, (_m, inner) => {
if (keepThinking) {
thinkingContent += (thinkingContent ? '\n\n' : '') + inner
diff --git a/src/lib/__tests__/turn-thinking-sink.test.ts b/src/lib/__tests__/turn-thinking-sink.test.ts
new file mode 100644
index 00000000..c0e74e94
--- /dev/null
+++ b/src/lib/__tests__/turn-thinking-sink.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Loch 2 und 3 des Denk-Audits (2.6.7, 2026-08-29).
+ *
+ * The prompt transport (tools as text, the route every strict template and
+ * every tool-less local model takes) had two ways to lose the thought:
+ *
+ * 2. Both agent loops called streamProviderTurn WITHOUT a thinking
+ * callback and then never read `turn.thinking` either. A backend that
+ * parses <think> into the native reasoning channel by itself, which is
+ * what the built-in engine does, had its whole thought dropped on the
+ * floor: Think button on, answer fine, thinking block empty.
+ * 3. The Coding path had no ThinkStreamSplitter at all, so the reasoning
+ * ran full-height into the answer bubble for the length of the turn and
+ * only the end-of-turn parse pulled it back out.
+ *
+ * Both hooks now feed the SAME sink, which is what this file tests: one place
+ * that merges the inline <think> deltas with the cumulative native channel.
+ * The wiring itself is pinned by the drift test at the bottom, in the house
+ * style of useCodex-streaming.test.ts, because the branch is not reachable
+ * without a whole hook harness.
+ *
+ * Run: npx vitest run src/lib/__tests__/turn-thinking-sink.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'fs'
+import { fileURLToPath } from 'url'
+import { dirname, join } from 'path'
+import { createTurnThinkingSink, createThinkStreamSplitter } from '../hermes-stream'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const src = (rel: string) => readFileSync(join(here, '..', '..', rel), 'utf8')
+
+describe('the sink keeps both reasoning sources', () => {
+ it('inline deltas accumulate', () => {
+ const s = createTurnThinkingSink()
+ s.inline('first ')
+ s.inline('second')
+ expect(s.live()).toBe('first second')
+ })
+
+ it('the native channel is cumulative, not appended', () => {
+ const s = createTurnThinkingSink()
+ s.native('let me')
+ s.native('let me think')
+ expect(s.live()).toBe('let me think')
+ })
+
+ it('a native answer does NOT wipe the inline one, which is what the Agent path did', () => {
+ const s = createTurnThinkingSink()
+ s.inline('from the text stream')
+ s.native('from reasoning_content')
+ expect(s.live()).toBe('from reasoning_content\n\nfrom the text stream')
+ })
+
+ it('and the inline one does not wipe the native one either', () => {
+ const s = createTurnThinkingSink()
+ s.native('from reasoning_content')
+ s.inline('from the text stream')
+ expect(s.live()).toBe('from reasoning_content\n\nfrom the text stream')
+ })
+
+ it('a repeated literal opener is a marker, not reasoning to read', () => {
+ const s = createTurnThinkingSink()
+ s.inline('<think>the thought')
+ expect(s.live()).toBe('the thought')
+ })
+
+ it('negative control: nothing fed means nothing shown, so no empty block opens', () => {
+ const s = createTurnThinkingSink()
+ s.inline('')
+ s.native('')
+ expect(s.live()).toBe('')
+ })
+})
+
+describe('the Qwen3 pre-opened thought reaches the sink and not the answer', () => {
+ it('reasoning before the closer goes to the block, the answer stays clean', () => {
+ // Exactly the shape the Qwen3 chat templates produce: the opener sits in
+ // the PROMPT, so the reply starts mid-thought and only sends the closer.
+ const splitter = createThinkStreamSplitter({ startInThink: true })
+ const sink = createTurnThinkingSink()
+ let prose = ''
+ for (const delta of ['Let me ', 'check that.', '</think>', 'The answer is 42.']) {
+ const part = splitter.feed(delta)
+ sink.inline(part.thinking)
+ prose += part.prose
+ }
+ const rest = splitter.flush()
+ sink.inline(rest.thinking)
+ prose += rest.prose
+ expect(sink.live()).toBe('Let me check that.')
+ expect(prose).toBe('The answer is 42.')
+ })
+
+ it('negative control: without startInThink the whole thought reads as answer', () => {
+ // This is what the Coding path did before the fix, and why the raw
+ // reasoning stood in the answer bubble for the length of the turn.
+ const splitter = createThinkStreamSplitter()
+ const sink = createTurnThinkingSink()
+ let prose = ''
+ for (const delta of ['Let me ', 'check that.', '</think>', 'The answer is 42.']) {
+ const part = splitter.feed(delta)
+ sink.inline(part.thinking)
+ prose += part.prose
+ }
+ expect(sink.live()).toBe('')
+ expect(prose).toContain('Let me check that.')
+ })
+})
+
+describe('both agent loops are wired to it, on the prompt transport too', () => {
+ const agent = src('hooks/useAgentChat.ts')
+ const codex = src('hooks/useCodex.ts')
+
+ it('the Coding path splits the thought out of the live stream', () => {
+ expect(codex).toContain('createThinkStreamSplitter({ startInThink: keepThinking })')
+ })
+
+ it('both loops merge through the shared sink', () => {
+ expect(agent).toContain('createTurnThinkingSink()')
+ expect(codex).toContain('createTurnThinkingSink()')
+ })
+
+ it('both loops hand streamProviderTurn a thinking callback that feeds it', () => {
+ expect(agent).toContain('thinkSink.native(full); paintThink()')
+ expect(codex).toContain('thinkSink.native(full); paintThink()')
+ })
+
+ it('and both read the native reasoning of the finished prompt-transport turn', () => {
+ expect(agent).toContain('if (hermesTurn.thinking)')
+ expect(codex).toContain('if (keepThinking && hermesTurn.thinking)')
+ })
+})
diff --git a/src/lib/hermes-stream.ts b/src/lib/hermes-stream.ts
index 6a46e8b1..ec542865 100644
--- a/src/lib/hermes-stream.ts
+++ b/src/lib/hermes-stream.ts
@@ -167,3 +167,54 @@ export function createThinkStreamSplitter(opts?: { startInThink?: boolean }): Th
},
}
}
+
+/**
+ * The two live reasoning sources of ONE turn, merged in one place.
+ *
+ * A prompt-transport turn can be handed its reasoning two different ways at
+ * the same time, and 2.6.7 lost one of them on both agent paths:
+ *
+ * - inline, as `<think>` spans inside the visible text, which is what
+ * `createThinkStreamSplitter` pulls out; and
+ * - natively, as the provider's `thinking` chunks, which is what
+ * llama-server produces once it parses `<think>` into `reasoning_content`
+ * for us, and what every cloud reasoner sends.
+ *
+ * They differ in shape: the splitter emits DELTAS, the provider callback hands
+ * over the CUMULATIVE text. Merging them by hand in each hook is how the
+ * Coding path ended up with no live thinking at all and the Agent path with a
+ * native answer that overwrote the inline one. This holds both, keeps them
+ * apart, and answers the only question the UI has: what should the thinking
+ * block show right now.
+ *
+ * Live display only. The end-of-turn parse on the full raw text stays
+ * authoritative for what is finally stored on the message.
+ */
+export interface TurnThinkingSink {
+ /** One `<think>` delta out of the visible stream. */
+ inline(delta: string): void
+ /** The provider's reasoning channel, cumulative. */
+ native(full: string): void
+ /** What the thinking block should show right now, '' when there is nothing. */
+ live(): string
+}
+
+export function createTurnThinkingSink(): TurnThinkingSink {
+ let inlineText = ''
+ let nativeText = ''
+ return {
+ inline(delta: string) {
+ if (!delta) return
+ // A pre-opened thought (Qwen3 templates put the opener in the PROMPT)
+ // can still carry a literal opener when the model repeats it. It is a
+ // marker, never reasoning the user wants to read.
+ inlineText += delta.replace(/<think>/g, '')
+ },
+ native(full: string) {
+ nativeText = full ?? ''
+ },
+ live() {
+ return [nativeText, inlineText].filter(Boolean).join('\n\n')
+ },
+ }
+}