Skip to content

The agent that grows with you

refactor(desktop): align reasoning tags with think_scrubber, trim #113302 tests

kshitijk4poora12ab2280a4f
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
index 79c2af9a7b2..2d2fa6dfcd2 100644
--- a/apps/desktop/src/components/assistant-ui/streaming-text-fidelity.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/streaming-text-fidelity.test.tsx
@@ -1,114 +1,38 @@
import { act, cleanup, render } from '@testing-library/react'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, 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.
- */
+// The real surface re-renders preprocessMarkdown → Streamdown on the accumulated
+// text every flush, so a settled message never shows this bug: only frames do.
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="" />)
+const REASONED = '<thinking>let me think about the render pipeline in detail</thinking>Resposta final com acentuação.'
- try {
- for (let end = chunk; end < text.length; end += chunk) {
- const frame = text.slice(0, end)
+it('never paints the chain of thought, and never un-paints an answer, in any 3-char frame', async () => {
+ const { container, rerender } = render(<MarkdownTextContent isRunning text="" />)
+ let previous = ''
- await act(async () => {
- rerender(<MarkdownTextContent isRunning text={frame} />)
- await Promise.resolve()
- })
-
- onFrame(container.textContent ?? '')
- }
+ for (let end = 3; end <= REASONED.length + 2; end += 3) {
+ const frame = REASONED.slice(0, end)
await act(async () => {
- rerender(<MarkdownTextContent isRunning text={text} />)
+ rerender(<MarkdownTextContent isRunning text={frame} />)
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)
+ const visible = container.textContent ?? ''
+ expect(visible).not.toContain('let me think')
+ expect(visible).not.toMatch(/<\/?thinking/)
- 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')
+ // A half-arrived tag (`<thin`) is not a tag yet, so those frames sit outside the curve.
+ if (!/<[a-z]*$/i.test(frame)) {
+ expect(norm(visible).startsWith(previous)).toBe(true)
+ previous = norm(visible)
}
+ }
- expect(frames.at(-1)).toBe('Resposta final com acentuação.')
- })
+ expect(container.textContent).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 023c6dd079d..dcfd0f1a38a 100644
--- a/apps/desktop/src/lib/markdown-preprocess.ts
+++ b/apps/desktop/src/lib/markdown-preprocess.ts
@@ -7,16 +7,15 @@ import { previewMarkdownHref } from '@/lib/preview-targets'
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
+// Same tag set as agent/think_scrubber.py THINK_TAG_NAMES, plus the desktop-only
+// `scratchpad`/`analysis` that were already stripped here before the two lists met.
+const REASONING_TAGS = 'think|thinking|reasoning|thought|reasoning_scratchpad|scratchpad|analysis'
+const REASONING_BLOCK_RE = new RegExp(`<(${REASONING_TAGS})>[\\s\\S]*?<\\/\\1>\\s*`, 'gi')
+// An open tag that starts its own block with no close tag yet. The block-boundary
+// requirement is what lets a real reasoning preamble (always its own block) vanish
+// while prose that merely mentions `<thinking>` mid-sentence survives — the same
+// line agent/think_scrubber.py draws.
+const OPEN_REASONING_BLOCK_RE = new RegExp(`(^|\\n)[ \\t]*<(${REASONING_TAGS})>[\\s\\S]*$`, 'i')
const PREVIEW_MARKER_RE = /\[Preview:[^\]]+\]\(#preview[:/][^)]+\)/gi
const FENCE_LINE_RE = /^([ \t]*)(`{3,}|~{3,})([^\n]*)$/
@@ -168,25 +167,11 @@ 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.
- */
+// Runs on the ACCUMULATED text every streaming flush, so an unterminated block
+// must already be hidden here: otherwise the chain of thought paints as prose
+// until the close tag lands and then the whole span vanishes in one frame
+// (#62774). Removing a closed block between two words keeps one space so `no` +
+// `Hermes` does not fuse into `noHermes`.
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)
diff --git a/apps/desktop/src/lib/markdown-reasoning-stream.test.ts b/apps/desktop/src/lib/markdown-reasoning-stream.test.ts
index deb4dbd134f..dfe17caaa9c 100644
--- a/apps/desktop/src/lib/markdown-reasoning-stream.test.ts
+++ b/apps/desktop/src/lib/markdown-reasoning-stream.test.ts
@@ -2,90 +2,20 @@ 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'
-
+// preprocessMarkdown runs on the accumulated text every streaming flush, so the
+// reasoning strip has to behave on a text whose close tag has not arrived yet.
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')
+ expect(preprocessMarkdown('<thought>x</thought>\n\nResposta final.')).toBe('Resposta final.')
})
- it('hides an unterminated reasoning block instead of rendering it', () => {
+ it('hides an unterminated block at a block boundary but keeps a mid-sentence mention', () => {
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')
- })
+ expect(preprocessMarkdown('Resposta final.\n<reasoning_scratchpad>checking')).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.')
- })
})