Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Show a thinking block's preview as plain text (PRD-8098) (#5092)
Abrahamc157c6b2dc1e
diff --git a/.changeset/thinking-preview-plain-text.md b/.changeset/thinking-preview-plain-text.mdnew file mode 100644index 000000000..06e3325ab--- /dev/null+++ b/.changeset/thinking-preview-plain-text.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge-app": patch+---++A collapsed thinking block in an agent chat now previews its text without markdown formatting like `**`, even while a bold span is still streaming in.diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 14ce97218..52641e343 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -2349,6 +2349,66 @@ describe('ThreadView thought collapse', () => {expect(block.textContent).toContain('First thought line');expect(block.textContent).toContain('Last thought line');});++ test('the collapsed preview shows the markdown as plain text', () => {+ model = makeModel({+ turnActive: false,+ items: [{ ...thought, text: '**Planning the change**\n\nRead `ThreadView.tsx` first.' }],+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ const toggle = screen.getByTestId('agent-thread-thought-toggle');+ expect(toggle.textContent).toContain('Planning the change');+ expect(toggle.textContent).not.toContain('**');+ });++ test('a streaming preview hides the markers of a bold title still arriving', () => {+ model = makeModel({+ turnActive: true,+ items: [{ ...thought, text: 'Earlier line\n**Checking the te' }],+ });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ const toggle = screen.getByTestId('agent-thread-thought-toggle');+ expect(toggle.textContent).toContain('Checking the te');+ expect(toggle.textContent).not.toContain('**');+ });++ test.each([+ ['Earlier line\nNow checking the **config file', 'Now checking the config file'],+ ['Earlier line\n**Running the\ntest suite**', 'test suite'],+ ])('a streaming preview of %j hides its emphasis markers', (text, preview) => {+ model = makeModel({ turnActive: true, items: [{ ...thought, text }] });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ const toggle = screen.getByTestId('agent-thread-thought-toggle');+ expect(toggle.textContent).toContain(preview);+ expect(toggle.textContent).not.toContain('**');+ });++ test('the preview keeps the text of inline code that starts the line', () => {+ model = makeModel({+ turnActive: false,+ items: [{ ...thought, text: '`**kwargs` must be forwarded' }],+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ expect(screen.getByTestId('agent-thread-thought-toggle').textContent).toContain(+ '**kwargs must be forwarded',+ );+ });++ test('a streaming preview skips a line that renders no text', () => {+ model = makeModel({+ turnActive: true,+ items: [{ ...thought, text: 'Planning the edit\n\n```ts' }],+ });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ expect(screen.getByTestId('agent-thread-thought-toggle').textContent).toContain(+ 'Planning the edit',+ );+ });});describe('ThreadView config value hints', () => {diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 24e854ade..859649200 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -156,6 +156,7 @@ import { contextChoicesForModel, useModelCandidates } from '@/lib/acp/model-candimport { formatShellCommand, revealHiddenCharacters } from '@/lib/acp/shell-command-format';import { parseSignInOutput, shortenUrl } from '@/lib/acp/sign-in-output';import { renderTerminalText } from '@/lib/acp/terminal-text';+import { thoughtPreview } from '@/lib/acp/thought-preview';import { threadAttachmentPaths } from '@/lib/acp/thread-attachment-paths';import {getAgentThreadClient,@@ -2528,8 +2529,6 @@ function ThoughtBlock({}): ReactNode {const { t } = useLingui();const [open, setOpen] = useState(false);- const lines = item.text.split('\n').filter((line) => line.trim().length > 0);- const preview = (streaming ? lines[lines.length - 1] : lines[0]) ?? '';return (<div data-testid="agent-thread-thought"><Button@@ -2549,7 +2548,7 @@ function ThoughtBlock({{t`Thinking`}{open ? null : (<span className="min-w-0 flex-1 truncate text-left font-normal text-xs normal-case italic tracking-normal">- {preview}+ {thoughtPreview(item.text, streaming)}</span>)}</Button>diff --git a/packages/app/src/lib/acp/thought-preview.test.ts b/packages/app/src/lib/acp/thought-preview.test.tsnew file mode 100644index 000000000..a64de1704--- /dev/null+++ b/packages/app/src/lib/acp/thought-preview.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test, vi } from 'vitest';+import { thoughtPreview } from './thought-preview.ts';++describe('thoughtPreview', () => {+ test('a settled thought previews its first line as plain text', () => {+ expect(thoughtPreview('**Planning the change**\n\nThen the tests.', false)).toBe(+ 'Planning the change',+ );+ });++ test('a streaming thought previews its last line as plain text', () => {+ expect(thoughtPreview('**Planning the change**\n\nNow **checking the te', true)).toBe(+ 'Now checking the te',+ );+ });++ test('a streaming thought converts only its last paragraph', () => {+ const toPlainText = vi.fn((markdown: string) => markdown);+ const earlier = 'An earlier paragraph. '.repeat(500);++ expect(thoughtPreview(`${earlier}\n\nThe latest words`, true, toPlainText)).toBe(+ 'The latest words',+ );+ expect(toPlainText).toHaveBeenCalledTimes(1);+ expect(toPlainText).toHaveBeenCalledWith('The latest words');+ });++ test('a paragraph break that holds spaces still ends the earlier paragraph', () => {+ const toPlainText = vi.fn((markdown: string) => markdown);++ thoughtPreview('Earlier\n \nLatest', true, toPlainText);++ expect(toPlainText).toHaveBeenCalledWith('Latest');+ });++ test.each([+ ['Plan\n\n```py\nx = 1\n\n# retry the call', '# retry the call'],+ ['Plan\n\n```js\nconst a = 1\n\nconst b = a**2', 'const b = a**2'],+ ['Plan\n\n~~~\nfirst\n\n- not a list', '- not a list'],+ ])('a blank line inside a code fence still streaming in keeps %j literal', (text, preview) => {+ expect(thoughtPreview(text, true)).toBe(preview);+ });++ test('a code line still streaming in is shown as written, without converting anything', () => {+ const toPlainText = vi.fn((markdown: string) => markdown);++ expect(thoughtPreview('Plan\n\n```py\nx = 1', true, toPlainText)).toBe('x = 1');+ expect(toPlainText).not.toHaveBeenCalled();+ });++ test('a closed code fence with a blank line inside stays one block', () => {+ expect(thoughtPreview('Plan\n\n```\nx = 1\n\n# not a heading\n```', true)).toBe(+ '# not a heading',+ );+ });++ test('a paragraph after a closed code fence starts a new block', () => {+ const toPlainText = vi.fn((markdown: string) => markdown);++ thoughtPreview('```\ncode\n```\n\nAfter the fence', true, toPlainText);++ expect(toPlainText).toHaveBeenCalledWith('After the fence');+ });++ test('a streaming thought whose last paragraph has no text yet previews the line before it', () => {+ expect(thoughtPreview('Planning the edit\n\n```ts', true)).toBe('Planning the edit');+ });+});diff --git a/packages/app/src/lib/acp/thought-preview.ts b/packages/app/src/lib/acp/thought-preview.tsnew file mode 100644index 000000000..1791c8f75--- /dev/null+++ b/packages/app/src/lib/acp/thought-preview.ts@@ -0,0 +1,46 @@+import { createCodeFenceTracker, markdownToPlainText } from '@inkeep/open-knowledge-core';++function plainLines(markdown: string, toPlainText: (markdown: string) => string): string[] {+ return toPlainText(markdown)+ .split('\n')+ .filter((line) => line.trim().length > 0);+}++function lastCodeLine(lines: readonly string[]): string | undefined {+ for (let index = lines.length - 1; index >= 0; index -= 1) {+ const line = (lines[index] ?? '').replace(/\s+/g, ' ').trim();+ if (line !== '') return line;+ }+ return undefined;+}++function streamingPreview(text: string, toPlainText: (markdown: string) => string): string {+ const lines = text.trimEnd().split('\n');+ const isFenced = createCodeFenceTracker();+ let blockStart = 0;+ let fenceStart = -1;+ lines.forEach((line, index) => {+ const insideBefore = isFenced('');+ const fenced = isFenced(line);+ if (fenced && !insideBefore) fenceStart = index;+ if (!fenced && line.trim() === '') blockStart = index + 1;+ });+ if (isFenced('')) {+ const code = lastCodeLine(lines.slice(fenceStart + 1));+ if (code !== undefined) return code;+ const before = plainLines(lines.slice(0, fenceStart).join('\n'), toPlainText);+ return before[before.length - 1] ?? '';+ }+ const trailing = plainLines(lines.slice(blockStart).join('\n'), toPlainText);+ const all = trailing.length > 0 ? trailing : plainLines(text, toPlainText);+ return all[all.length - 1] ?? '';+}++export function thoughtPreview(+ text: string,+ streaming: boolean,+ toPlainText: (markdown: string) => string = markdownToPlainText,+): string {+ if (streaming) return streamingPreview(text, toPlainText);+ return plainLines(text, toPlainText)[0] ?? '';+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 9b394fe1d..4866a5c37 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -145,6 +145,7 @@"remark-parse": "^11.0.0","remark-rehype": "^11.1.2","remark-stringify": "^11.0.0",+ "remend": "1.3.0","unified": "^11.0.5","unified-lint-rule": "^3.0.0","unist-util-visit": "^5.1.0",diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex cf8c58cbb..5b2178484 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -1050,6 +1050,7 @@ export {skipInlineCode,} from './markdown/non-rendering-contexts.ts';export { isMutatingParserReservation } from './markdown/parser-reservations.ts';+export { markdownToPlainText } from './markdown/plain-text.ts';export { normalizeReferenceLabel } from './markdown/reference-label.ts';export { normalizeDocRelativeAssetUrl } from './markdown/resolve-image-url.ts';export {diff --git a/packages/core/src/markdown/plain-text.ts b/packages/core/src/markdown/plain-text.tsnew file mode 100644index 000000000..dae3fb363--- /dev/null+++ b/packages/core/src/markdown/plain-text.ts@@ -0,0 +1,40 @@+import type { Nodes } from 'mdast';+import remarkGfm from 'remark-gfm';+import remarkParse from 'remark-parse';+import remend from 'remend';+import { unified } from 'unified';++const parser = unified().use(remarkParse).use(remarkGfm);++const CHILD_SEPARATORS: Partial<Record<Nodes['type'], string>> = {+ paragraph: '',+ heading: '',+ tableCell: '',+ emphasis: '',+ strong: '',+ delete: '',+ link: '',+ linkReference: '',+ tableRow: ' | ',+};++function plainText(node: Nodes): string {+ if (node.type === 'break') return '\n';+ if (node.type === 'html') return '';+ if (node.type === 'image') return node.alt ?? '';+ if ('value' in node) return node.value;+ if (!('children' in node)) return '';+ return node.children.map(plainText).join(CHILD_SEPARATORS[node.type] ?? '\n');+}++export function markdownToPlainText(markdown: string): string {+ try {+ return plainText(parser.parse(remend(markdown, { katex: false })))+ .split('\n')+ .map((line) => line.replace(/\s+/g, ' ').trim())+ .join('\n');+ } catch (err: unknown) {+ console.warn('[markdown-plain-text] markdown parse failed, falling back to raw text', err);+ return markdown;+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5ab9b7686..82cdb1207 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1086,6 +1086,9 @@ importers:remark-stringify:specifier: ^11.0.0version: 11.0.0+ remend:+ specifier: 1.3.0+ version: 1.3.0unified:specifier: ^11.0.5version: 11.0.5