Skip to content

The agent that grows with you

fix(desktop): reasoning blocks stop eating streamed prose

finn763956abb9d250d
diff --git a/apps/desktop/src/components/assistant-ui/streaming-text-fidelity.test.tsx b/apps/desktop/src/components/assistant-ui/streaming-text-fidelity.test.tsx
new file mode 100644
index 00000000000..79c2af9a7b2
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/streaming-text-fidelity.test.tsx
@@ -0,0 +1,114 @@
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { MarkdownTextContent } from './markdown-text'
+
+/**
+ * What the reader actually sees while an answer streams, frame by frame.
+ *
+ * The desktop renders `preprocessMarkdown → tailBoundedRemend → Streamdown` on
+ * the accumulated text every flush, so a defect in any of those steps shows up
+ * here as characters missing from the DOM on some frame — and only here: a
+ * settled message is preprocessed once, so "streaming is broken, static text is
+ * fine" is the shape of every bug in this file.
+ */
+const norm = (value: string) => value.replace(/\s+/g, ' ').trim()
+
+afterEach(cleanup)
+
+/** Stream `text` into the real surface in `chunk`-character deltas, calling
+ * `onFrame` with the DOM text after each flush. */
+async function streamFrames(text: string, chunk: number, onFrame: (visible: string) => void) {
+ const { container, rerender } = render(<MarkdownTextContent isRunning text="" />)
+
+ try {
+ for (let end = chunk; end < text.length; end += chunk) {
+ const frame = text.slice(0, end)
+
+ await act(async () => {
+ rerender(<MarkdownTextContent isRunning text={frame} />)
+ await Promise.resolve()
+ })
+
+ onFrame(container.textContent ?? '')
+ }
+
+ await act(async () => {
+ rerender(<MarkdownTextContent isRunning text={text} />)
+ await Promise.resolve()
+ })
+
+ onFrame(container.textContent ?? '')
+ } finally {
+ cleanup()
+ }
+}
+
+// Accents (BMP) plus an astral-plane emoji: a surrogate pair the pipeline must
+// never split.
+const ACCENTED = 'Açúcar, coração, órgão: a renderização no Hermes Desktop está correta 🎉 sem perder nada.'
+// Plain long prose — the protection case: no markdown, no reasoning, no escapes.
+const PLAIN =
+ 'Vou investigar o pipeline de renderização de texto porque o usuário relatou que palavras inteiras ' +
+ 'somem durante o streaming e que palavras adjacentes ficam coladas na mesma frase inteira do parágrafo.'
+const REASONED = '<thinking>let me think about the render pipeline in detail</thinking>Resposta final com acentuação.'
+
+describe('streamed markdown keeps every visible character', () => {
+ it.each([1, 3])('renders accents and emoji intact when streamed in %i-character deltas', async chunk => {
+ const frames: string[] = []
+
+ await streamFrames(ACCENTED, chunk, visible => frames.push(visible))
+
+ expect(frames.length).toBeGreaterThan(10)
+
+ for (const visible of frames) {
+ // No frame may show anything that has not arrived yet (raw, spaces and
+ // all), and none may lose a word.
+ expect(ACCENTED.startsWith(visible)).toBe(true)
+ expect(norm(ACCENTED).includes(norm(visible))).toBe(true)
+ }
+
+ // Character-for-character, spaces included.
+ expect(frames.at(-1)).toBe(ACCENTED)
+ })
+
+ it.each([1, 3])('loses nothing from plain prose streamed in %i-character deltas', async chunk => {
+ const frames: string[] = []
+
+ await streamFrames(PLAIN, chunk, visible => frames.push(visible))
+
+ expect(frames.length).toBeGreaterThan(10)
+
+ let previous = ''
+
+ for (const visible of frames) {
+ const current = norm(visible)
+
+ // Every frame is a prefix of the finished text...
+ expect(norm(PLAIN).startsWith(current)).toBe(true)
+ // ...and nothing already on screen ever disappears.
+ expect(current.startsWith(previous)).toBe(true)
+
+ previous = current
+ }
+
+ expect(norm(frames.at(-1) ?? '')).toBe(norm(PLAIN))
+ })
+
+ it('never paints the chain of thought, in any frame', async () => {
+ const frames: string[] = []
+
+ await streamFrames(REASONED, 3, visible => frames.push(visible))
+
+ expect(frames.length).toBeGreaterThan(10)
+
+ for (const visible of frames) {
+ expect(visible).not.toContain('let me think')
+ expect(visible).not.toContain('render pipeline')
+ expect(visible).not.toContain('<thinking')
+ expect(visible).not.toContain('</thinking')
+ }
+
+ expect(frames.at(-1)).toBe('Resposta final com acentuação.')
+ })
+})
diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.ts
index ec95338e63b..023c6dd079d 100644
--- a/apps/desktop/src/lib/markdown-preprocess.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.ts
@@ -8,6 +8,15 @@ import { stripPreviewTargets } from '@/lib/preview-targets'
import { linkifySessionRefs } from '@/lib/session-refs'
const REASONING_BLOCK_RE = /<(think|thinking|reasoning|scratchpad|analysis)>[\s\S]*?<\/\1>\s*/gi
+// An unterminated reasoning block: an open tag that starts its own block (start
+// of text, or a fresh line) with no close tag in the text yet. Reasoning models
+// inline their chain of thought in the answer channel and stream the open tag
+// long before the close one, so between those two flushes the regex above — which
+// needs a close tag — matches nothing and the reasoning renders as chat prose.
+// `agent/think_scrubber.py` draws the same block-boundary line for the same
+// reason: a real reasoning preamble is always its own block, while prose that
+// merely *mentions* `<thinking>` mid-sentence must survive.
+const OPEN_REASONING_BLOCK_RE = /(^|\n)[ \t]*<(think|thinking|reasoning|scratchpad|analysis)>[\s\S]*$/i
const PREVIEW_MARKER_RE = /\[Preview:[^\]]+\]\(#preview[:/][^)]+\)/gi
const FENCE_LINE_RE = /^([ \t]*)(`{3,}|~{3,})([^\n]*)$/
@@ -159,6 +168,36 @@ function scrubBacktickNoise(text: string): string {
return out
}
+/**
+ * Strip reasoning blocks out of assistant text.
+ *
+ * Applied to the whole accumulated text on every streaming flush, which is what
+ * makes the two defects around the plain `.replace(REASONING_BLOCK_RE, '')` show
+ * up in chat but never on a settled message:
+ *
+ * 1. The regex consumes the whitespace on its seam, so a block sitting BETWEEN
+ * two words fused them — `no` + `Hermes` rendered as `noHermes` (the report's
+ * `noHermes` / `backendveal`). When both sides of the removed span are still
+ * prose, keep one space instead of deleting the seam.
+ * 2. An unterminated block was not stripped at all, so the model's chain of
+ * thought painted as answer prose for as long as the close tag took to arrive,
+ * and when it arrived the whole span vanished in one frame — the text the
+ * reader had already read, gone. Stripping the unterminated block is what the
+ * backend scrubber already does at end-of-stream ("leaking partial reasoning
+ * is worse than a truncated answer"); doing it here keeps the surface stable
+ * instead of showing reasoning then deleting it.
+ */
+function stripReasoningBlocks(text: string): string {
+ const closed = text.replace(REASONING_BLOCK_RE, (match: string, _tag: string, offset: number, whole: string) => {
+ const before = whole.slice(0, offset)
+ const after = whole.slice(offset + match.length)
+
+ return /\S$/.test(before) && /^\S/.test(after) ? ' ' : ''
+ })
+
+ return closed.replace(OPEN_REASONING_BLOCK_RE, '$1')
+}
+
function stripEmptyFenceBlocks(text: string): string {
return text.replace(EMPTY_FENCE_BLOCK_RE, '$1')
}
@@ -649,7 +688,7 @@ function normalizeFenceBlocks(text: string): string {
}
export function preprocessMarkdown(text: string): string {
- const cleaned = text.replace(REASONING_BLOCK_RE, '').replace(PREVIEW_MARKER_RE, '')
+ const cleaned = stripReasoningBlocks(text).replace(PREVIEW_MARKER_RE, '')
const scrubbed = scrubBacktickNoise(cleaned)
const normalizedFences = normalizeFenceBlocks(scrubbed)
const strippedEmptyFences = stripEmptyFenceBlocks(normalizedFences)
diff --git a/apps/desktop/src/lib/markdown-reasoning-stream.test.ts b/apps/desktop/src/lib/markdown-reasoning-stream.test.ts
new file mode 100644
index 00000000000..deb4dbd134f
--- /dev/null
+++ b/apps/desktop/src/lib/markdown-reasoning-stream.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from 'vitest'
+
+import { preprocessMarkdown } from './markdown-preprocess'
+
+/**
+ * Reasoning blocks on the STREAMING surface.
+ *
+ * Models that inline their chain of thought in the answer channel (`<thinking>…`
+ * — DeepSeek/R1-style, and anything relaying a reasoning model onto a chat wire)
+ * stream the open tag first and the close tag much later, if at all. Two things
+ * follow from `preprocessMarkdown` running on the accumulated text on every
+ * flush, and both were visible in the chat:
+ *
+ * 1. The chain of thought rendered as user-visible prose until the close tag
+ * landed, and when it did the whole span was deleted in one frame — taking
+ * text the reader had already read with it (the reported mid-reply
+ * "truncation" on long answers).
+ * 2. The strip ate the whitespace on its seam, so a block sitting BETWEEN two
+ * words fused them: `no` + `Hermes` rendered as `noHermes`.
+ */
+const normalize = (value: string) => value.replace(/\s+/g, ' ').trim()
+
+const REASONING = 'let me think about the render pipeline in detail'
+
+describe('reasoning blocks in streamed markdown', () => {
+ it('does not fuse the words a stripped block separated', () => {
+ expect(preprocessMarkdown('no<thinking>hmm</thinking> Hermes Desktop')).toBe('no Hermes Desktop')
+ expect(preprocessMarkdown('componentes<analysis>e</analysis>-chave aqui')).toBe('componentes -chave aqui')
+ expect(preprocessMarkdown('backend e o <thinking>x</thinking>useSmoothReveal')).toBe('backend e o useSmoothReveal')
+ })
+
+ it('hides an unterminated reasoning block instead of rendering it', () => {
+ expect(preprocessMarkdown('<thinking>let me think about the render pipeline')).toBe('')
+ expect(preprocessMarkdown('<thinking>')).toBe('')
+ expect(preprocessMarkdown('Resposta final.\n<thinking>checking the render pipeline')).toBe('Resposta final.\n')
+ expect(preprocessMarkdown('Resposta final.\n<thinking>')).toBe('Resposta final.\n')
+ })
+
+ it('leaves prose that merely mentions a tag alone', () => {
+ const inline = 'The model writes <thinking> tags inline in its output, and closes them too.'
+ const quoted = 'O texto acima explica o formato do bloco <thinking> sem nunca fechá-lo'
+
+ expect(preprocessMarkdown(inline)).toBe(inline)
+ expect(preprocessMarkdown(quoted)).toBe(quoted)
+ })
+
+ it('drops the block for a closed pair, however it is split', () => {
+ expect(preprocessMarkdown(`<thinking>${REASONING}</thinking>\n\nResposta final com acentuação.`)).toBe(
+ 'Resposta final com acentuação.'
+ )
+ expect(preprocessMarkdown(`Resposta: <analysis>${REASONING}</analysis>e o resto.`)).toBe('Resposta: e o resto.')
+ })
+
+ it('never shows the chain of thought at any delta boundary', () => {
+ const stream = `<thinking>${REASONING}</thinking>Resposta final com acentuação, referência e ação.`
+ const answers: string[] = []
+ let accumulated = ''
+
+ for (let index = 0; index < stream.length; index += 3) {
+ accumulated = stream.slice(0, index + 3)
+ const visible = preprocessMarkdown(accumulated)
+
+ // The reasoning text and the completed tag must never reach the surface,
+ // at any flush — not only once the block has closed. (A half-arrived tag
+ // is not a tag yet; it renders as nothing, and is covered in the DOM test.)
+ expect(visible).not.toContain('let me think')
+ expect(visible).not.toContain('render pipeline')
+ expect(visible).not.toMatch(/<(\/?)(think|thinking|reasoning|scratchpad|analysis)>/i)
+
+ // And nothing that WAS visible may disappear as the stream grows: every
+ // visible fragment is a prefix of what the next frame shows. A half-arrived
+ // tag (`<thin`, no `>` yet) is not a tag this pass can see — the DOM renders
+ // those 1-4 characters as nothing the moment the tag completes, which the
+ // surface test pins end-to-end — so those frames are not part of the curve.
+ if (/<[a-z]*$/i.test(accumulated)) {
+ continue
+ }
+
+ const next = normalize(visible)
+ const previous = answers.at(-1)
+
+ if (previous !== undefined) {
+ expect(next.startsWith(previous)).toBe(true)
+ }
+
+ answers.push(next)
+ }
+
+ expect(normalize(preprocessMarkdown(accumulated))).toBe('Resposta final com acentuação, referência e ação.')
+ })
+})