Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 无语言标注的代码块不再套行内 code 底色 (#1127)

Dash89b285caebbe
diff --git a/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts b/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
index 51b2c9afda..3716408a52 100644
--- a/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownDiffBlock.test.ts
@@ -22,7 +22,7 @@
* F3 MarkdownRenderer's `pre` renderer detects language-diff and routes
* to <MarkdownDiffBlock raw=.../>, leaving non-diff blocks on the
* default <pre><code> path.
- * F4 inline code path (no className) is unchanged.
+ * F4 inline code path is gated by structure (not fenced) AND no className.
* F5 parseDiffText: '+' / '-' produce add / del; '+++' / '---' / '@@'
* hunk headers stay as ctx (no color bleed onto file headers).
*/
@@ -177,11 +177,17 @@ describe('F3 — MarkdownRenderer routes ```diff to MarkdownDiffBlock', () => {
});
});
-describe('F4 — inline code path unchanged', () => {
- it('inline = !className still gates the inline branch', () => {
- expect(rendererSrc).toMatch(/const\s+isInline\s*=\s*!className/);
+describe('F4 — inline code 分派判据', () => {
+ // 判据从「有没有 className」改成「结构标记 + 没有 className」:className 只在
+ // 带语言标注时由 rehype-highlight 下发,```(无语言)围栏与缩进代码块会漏判成
+ // 行内 code。这里锚定两个合取项都在,防止任一半被删回退。
+ // 行为级断言见 markdownFencedCodeInline.test.ts。
+ it('inline 分支同时要求「非 fenced 结构」与「无 className」', () => {
+ expect(rendererSrc).toMatch(
+ /const\s+isFencedCode\s*=\s*node\?\.properties\?\.\[FENCED_CODE_PROP\]\s*!==\s*undefined/,
+ );
+ expect(rendererSrc).toMatch(/const\s+isInline\s*=\s*!isFencedCode\s*&&\s*!className/);
});
-
});
describe('F5 — parseDiffText classification', () => {
diff --git a/apps/desktop/src/renderer/__tests__/markdownFencedCodeInline.test.ts b/apps/desktop/src/renderer/__tests__/markdownFencedCodeInline.test.ts
new file mode 100644
index 0000000000..bf4e9a46db
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/markdownFencedCodeInline.test.ts
@@ -0,0 +1,182 @@
+/**
+ * markdownFencedCodeInline.test.ts
+ * ---------------------------------------------------------------------------
+ * 回归:代码块里的文字不得套行内 code 的底色。
+ *
+ * 起因(2026-07):MarkdownRenderer 的 code 渲染器用 `!className` 近似判断行内
+ * code,而 className 只在**带语言标注**时由 rehype-highlight 下发。于是
+ * ```(无语言)围栏与 4 空格缩进代码块的 `<code>` 落进行内分支,被套上
+ * `bg-[var(--msg-md-inline-code-bg)]` + 内距——inline 元素多行折断时逐行画底,
+ * 整块代码变成一行一个灰条;内容还会被送进文件路径检测(可能误变可点 chip)。
+ *
+ * 修法与 GitHub 一致:按祖先结构判定(`pre code` 一律复位),不看语言标注。
+ * rehypeFencedCodeMarker 给 `pre > code` 打 data-fenced-code,渲染器据此分派。
+ *
+ * 这里跑真实 unified 管线(真 rehype-highlight + 真 marker 插件),用镜像 code
+ * 渲染器复刻源码的判定式,并从源码里提取真实的 INLINE_CODE_CLASS 参与断言,
+ * 避免底色 token 改名后测试变成空壳。判定式本身的 source-contract 锚在
+ * markdownDiffBlock.test.ts 的 F4。
+ */
+
+import { describe, it, expect } from 'vitest';
+import { createElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ReactMarkdown from 'react-markdown';
+import rehypeHighlight from 'rehype-highlight';
+import {
+ FENCED_CODE_ATTR,
+ FENCED_CODE_PROP,
+ rehypeFencedCodeMarker,
+} from '../components/chat/rehypeFencedCodeMarker';
+
+const rendererPath = resolve(__dirname, '..', 'components', 'chat', 'MarkdownRenderer.tsx');
+const rendererSrc = readFileSync(rendererPath, 'utf8');
+
+/** 从源码提取真实的行内 code class 串,让底色 token 改名时测试跟着走。 */
+function readInlineCodeClass(): string {
+ const match = rendererSrc.match(/const INLINE_CODE_CLASS = '([^']+)'/);
+ expect(match, 'INLINE_CODE_CLASS 常量未找到').toBeTruthy();
+ return match![1];
+}
+
+const INLINE_CODE_CLASS = readInlineCodeClass();
+
+/**
+ * 镜像 MarkdownRenderer 的 code 分派:结构标记优先,className 次之。
+ * 行内分支套真实 INLINE_CODE_CLASS;代码块分支保持 highlight 的 className。
+ */
+function render(markdown: string): string {
+ return renderToStaticMarkup(
+ createElement(ReactMarkdown, {
+ rehypePlugins: [rehypeHighlight, rehypeFencedCodeMarker],
+ components: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ code: ({ className, children, node, ...props }: any) => {
+ const isFencedCode = node?.properties?.[FENCED_CODE_PROP] !== undefined;
+ const isInline = !isFencedCode && !className;
+ return createElement(
+ 'code',
+ isInline
+ ? { className: INLINE_CODE_CLASS }
+ : { className: className ?? 'fenced-without-language', ...props },
+ children,
+ );
+ },
+ },
+ children: markdown,
+ }),
+ );
+}
+
+/** 行内底色的判据:整个 class 串里的底色片段。 */
+const INLINE_BG_CLASS = 'bg-[var(--msg-md-inline-code-bg)]';
+
+/** 观测管线实际下发给每个 `<code>` 的两项判据,用于锚定 bug 的前提。 */
+function probeCodeNodes(markdown: string): Array<{ className?: string; fenced: boolean }> {
+ const seen: Array<{ className?: string; fenced: boolean }> = [];
+ renderToStaticMarkup(
+ createElement(ReactMarkdown, {
+ rehypePlugins: [rehypeHighlight, rehypeFencedCodeMarker],
+ components: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ code: ({ className, children, node }: any) => {
+ seen.push({
+ className,
+ fenced: node?.properties?.[FENCED_CODE_PROP] !== undefined,
+ });
+ return createElement('code', null, children);
+ },
+ },
+ children: markdown,
+ }),
+ );
+ return seen;
+}
+
+describe('代码块内不套行内 code 底色', () => {
+ it('INLINE_CODE_CLASS 确实带行内底色(否则下面的断言是空壳)', () => {
+ expect(INLINE_CODE_CLASS).toContain(INLINE_BG_CLASS);
+ });
+
+ it('无语言标注的围栏(截图里的树形图形态)不套行内底色', () => {
+ const html = render('```\n任务(Session)\n└─ 对话(Chat)\n └─ 消息(Message)\n```');
+ expect(html).toContain('<pre>');
+ expect(html).not.toContain(INLINE_BG_CLASS);
+ expect(html).toContain(FENCED_CODE_ATTR);
+ });
+
+ it('带语言标注的围栏同样不套行内底色(既有行为不回退)', () => {
+ const html = render('```ts\nconst a = 1;\n```');
+ expect(html).not.toContain(INLINE_BG_CLASS);
+ expect(html).toContain('language-ts');
+ expect(html).toContain(FENCED_CODE_ATTR);
+ });
+
+ it('4 空格缩进代码块也按代码块处理(它同样没有 className)', () => {
+ const html = render('正文\n\n 任务(Session)\n 对话(Chat)\n');
+ expect(html).toContain('<pre>');
+ expect(html).not.toContain(INLINE_BG_CLASS);
+ expect(html).toContain(FENCED_CODE_ATTR);
+ });
+
+ it('行内 code 仍然保留底色,且不被打上代码块标记', () => {
+ const html = render('一句话里的 `path/to/file.ts` 标识');
+ expect(html).toContain(INLINE_BG_CLASS);
+ expect(html).not.toContain('<pre>');
+ expect(html).not.toContain(FENCED_CODE_ATTR);
+ });
+
+ it('同一段里行内 code 与围栏共存时各走各的分支', () => {
+ const html = render('先看 `a.ts`:\n\n```\nplain block\n```\n');
+ expect(html).toContain(INLINE_BG_CLASS);
+ expect(html).toContain(FENCED_CODE_ATTR);
+ // 行内那个不带标记,代码块那个不带底色 —— 两者都只出现一次。
+ expect(html.match(new RegExp(FENCED_CODE_ATTR, 'g'))?.length).toBe(1);
+ expect(html.match(/bg-\[var\(--msg-md-inline-code-bg\)\]/g)?.length).toBe(1);
+ });
+});
+
+describe('bug 前提锚定 —— className 不是可靠判据', () => {
+ it('无语言围栏的 code 没有 className,只有结构标记能认出它是代码块', () => {
+ const [probe, ...rest] = probeCodeNodes('```\nplain block\n```');
+ expect(rest).toHaveLength(0);
+ // 这两条就是旧判定 `!className` 误判的完整原因:className 缺席、结构在场。
+ expect(probe.className).toBeUndefined();
+ expect(probe.fenced).toBe(true);
+ });
+
+ it('带语言标注时 className 才出现(rehype-highlight 只在这时下发)', () => {
+ const [probe] = probeCodeNodes('```ts\nconst a = 1;\n```');
+ expect(probe.className).toContain('language-ts');
+ expect(probe.fenced).toBe(true);
+ });
+
+ it('行内 code 两项判据都缺席 —— 这才是真的行内', () => {
+ const [probe] = probeCodeNodes('一句话里的 `a.ts` 标识');
+ expect(probe.className).toBeUndefined();
+ expect(probe.fenced).toBe(false);
+ });
+});
+
+describe('marker 插件只标记 pre 的直接 code 子节点', () => {
+ it('未闭合围栏(流式中途)同样被标记 —— 底色不该在流式时闪现', () => {
+ const html = render('```\n流式中途还没闭合\n');
+ expect(html).toContain('<pre>');
+ expect(html).toContain(FENCED_CODE_ATTR);
+ expect(html).not.toContain(INLINE_BG_CLASS);
+ });
+});
+
+describe('source contract — 插件注册位置', () => {
+ it('rehypeFencedCodeMarker 注册在 rehype 链里,且排在 rehypeHighlight 之后', () => {
+ const match = rendererSrc.match(/const REHYPE_PLUGINS: PluggableList = \[([\s\S]*?)\];/);
+ expect(match, 'REHYPE_PLUGINS 未找到').toBeTruthy();
+ const chain = match![1];
+ const highlightAt = chain.indexOf('rehypeHighlight');
+ const markerAt = chain.indexOf('rehypeFencedCodeMarker');
+ expect(highlightAt).toBeGreaterThanOrEqual(0);
+ expect(markerAt).toBeGreaterThan(highlightAt);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index a3e970c362..004a2e1f84 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -29,6 +29,7 @@ import remarkPreserveLocalImagePaths, {
} from './remarkPreserveLocalImagePaths';
import remarkSessionLinks from './remarkSessionLinks';
import { rehypeMathBlockMarker } from './rehypeMathBlockMarker';
+import { FENCED_CODE_PROP, rehypeFencedCodeMarker } from './rehypeFencedCodeMarker';
import { CopyAsImageBlock, mathBlockToLatex, tableToTsv } from './CopyAsImageBlock';
import type { Components, UrlTransform } from 'react-markdown';
import type { PluggableList } from 'unified';
@@ -201,11 +202,15 @@ const REMARK_PLUGINS_PRIVILEGED: PluggableList = [
// rehypeMathBlockMarker 紧随 rehypeKatex:把裸 `<span class="katex-display">`
// 包进 `<div data-math-block>`,让下方 div 渲染器能挂「复制为图片」工具栏
// (components 映射只认 tagName,认不了 class)。
+// rehypeFencedCodeMarker 必须排在最后:katex 已消费掉 `$$…$$` 的 `<pre><code>`、
+// highlight 已注入 hljs span,此时剩下的 `pre > code` 就是真正的代码块,给它们
+// 打 data-fenced-code 供下方 code 渲染器按结构(而非语言标注)分派。
const REHYPE_PLUGINS: PluggableList = [
rehypeSlug,
[rehypeKatex, { strict: 'ignore', errorColor: 'var(--error-fg)' }],
rehypeMathBlockMarker,
rehypeHighlight,
+ rehypeFencedCodeMarker,
];
const MARKDOWN_LINK_CLASS = 'text-[var(--msg-link)] underline underline-offset-2 cursor-pointer [overflow-wrap:anywhere]';
/**
@@ -1577,10 +1582,17 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
);
},
// text-lightbox-trigger-extension v2: inline `<code>` whose content
- // looks like a file path becomes a clickable preview entry. Fenced
- // code blocks (className=language-*) bypass the path check.
- code: ({ className, children, ...props }) => {
- const isInline = !className;
+ // looks like a file path becomes a clickable preview entry. 代码块
+ // (`pre > code`)一律绕开路径检测与行内底色。
+ //
+ // 判据是 rehypeFencedCodeMarker 打的结构标记,不是「有没有 className」:
+ // className 由 rehype-highlight 按语言标注下发,```(无语言)围栏和 4 空格
+ // 缩进代码块都没有,曾因此被整块套上行内底色 + 内距(inline 元素逐行画底,
+ // 一行一个灰条),内容还被拿去做路径检测。这与 GitHub 用 `pre code` 祖先
+ // 选择器复位底色是同一条判据。
+ code: ({ className, children, node, ...props }) => {
+ const isFencedCode = node?.properties?.[FENCED_CODE_PROP] !== undefined;
+ const isInline = !isFencedCode && !className;
if (!isInline) {
return (
<code className={cn(className, 'font-mono text-[length:var(--app-code-font-size)]')} {...props}>
diff --git a/apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts b/apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts
new file mode 100644
index 0000000000..5b5a527d36
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts
@@ -0,0 +1,47 @@
+/**
+ * rehypeFencedCodeMarker — 给代码块内的 `<code>` 打上结构标记。
+ *
+ * 「这个 `<code>` 是行内 code 还是代码块的一部分」在 hast 里只能由父节点回答:
+ * mdast 的 `inlineCode` / `code` 两类节点转成 hast 后都是 `<code>`,区别只剩
+ * 「外面是否包着 `<pre>`」。react-markdown 的 components 映射按 tagName 分派、
+ * 拿不到父节点,于是历史实现退而用「有没有 className」近似判断——而 className
+ * 来自 rehype-highlight,它只给**带语言标注**的围栏加 `hljs language-xxx`。
+ * 结果 ```(无语言)围栏与 4 空格缩进代码块的 `<code>` 没有 className,被误判成
+ * 行内 code:套上行内底色 + 内距(inline 元素逐行画底,整块代码变成一行一个灰
+ * 条),内容还会被送进文件路径检测。
+ *
+ * 本插件排在 rehype 链最后(rehype-katex 已把 `$$…$$` 的 `<pre><code>` 消费掉,
+ * rehype-highlight 也已注入 hljs span),遍历 `<pre>` 给其 `<code>` 子节点加
+ * `data-fenced-code`,让 MarkdownRenderer 按结构而不是按语言标注分派。
+ * 这与 GitHub 的 `pre code { background: transparent; padding: 0 }` 是同一条
+ * 判据(祖先关系),也与移动端 WebView 面的 `pre code` 复位规则一致。
+ *
+ * 标记刻意用 data 属性而不是往 className 里塞值:className 是 highlight.js 的
+ * 地盘,且 `isDiffCodeChild` / `isMermaidCodeChild` 用正则匹配它来分流
+ * ```diff / ```mermaid,混入结构信息会互相干扰。属性留在 DOM 上,devtools 与
+ * 回归测试都能直接看到这个分派依据。
+ */
+
+import type { Plugin } from 'unified';
+import type { Element, Root } from 'hast';
+import { visit } from 'unist-util-visit';
+
+/** hast property 名(camelCase);序列化到 DOM 即 `data-fenced-code`。 */
+export const FENCED_CODE_PROP = 'dataFencedCode';
+
+/** DOM / JSX 上的属性名,供渲染层与测试断言复用。 */
+export const FENCED_CODE_ATTR = 'data-fenced-code';
+
+export const rehypeFencedCodeMarker: Plugin<[], Root> = () => {
+ return (tree) => {
+ visit(tree, 'element', (node: Element) => {
+ if (node.tagName !== 'pre') return;
+ for (const child of node.children) {
+ // 只认 `<pre>` 的直接 `<code>` 子节点——这正是 mdast `code` 节点转出来的
+ // 形状。更深层的 `<code>`(如 pre 里手写的嵌套 HTML)不在此语义内。
+ if (child.type !== 'element' || child.tagName !== 'code') continue;
+ child.properties = { ...child.properties, [FENCED_CODE_PROP]: '' };
+ }
+ });
+ };
+};
diff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.ts
index bbc0afb55d..3f64f26821 100644
--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts
+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts
@@ -73,6 +73,30 @@ describe('messageMarkdown', () => {
]);
});
+ // 无语言标注的围栏:桌面端曾因「按 className 判定行内 code」把这种块整段套上
+ // 行内底色(rehype-highlight 只给带语言的围栏下发 className)。移动端解析器在
+ // 块级就分出 code 块、与行内 code 是两个类型,天然不会误判——这条测试把该性质
+ // 钉住,防止将来有人把「无语言就当普通文本/行内」塞进解析器。
+ // 桌面端同一形态的回归见 apps/desktop 的 markdownFencedCodeInline.test.ts。
+ it('无语言标注的围栏仍是 code 块(language 缺席),不降级成 inline code', () => {
+ const blocks = parseMobileMarkdown([
+ '```',
+ '任务(Session)',
+ '└─ 对话(Chat)',
+ '```',
+ ].join('\n'));
+ expect(blocks).toEqual([
+ {
+ type: 'code',
+ key: 'code:0:0',
+ language: undefined,
+ text: '任务(Session)\n└─ 对话(Chat)',
+ },
+ ]);
+ // 关键:整块内容没有任何一段变成行内 code inline。
+ expect(JSON.stringify(blocks)).not.toContain('"inlines"');
+ });
+
it('keeps unclosed fenced code as a code block', () => {
expect(parseMobileMarkdown('```bash\npnpm test')).toEqual([
{
diff --git a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
index b5085d0726..c3adb12a32 100644
--- a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
+++ b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts
@@ -85,3 +85,39 @@ describe('buildSelectableMarkdownHtml 代码块语法着色', () => {
expect(html).toContain('&lt;b&gt;');
});
});
+
+/**
+ * 代码块里的 `<code>` 不带行内 code 的装饰 —— 三端同一条判据:**看祖先结构,
+ * 不看语言标注**。
+ *
+ * - 这里(WebView 面):`pre code` 祖先选择器复位,与 GitHub 的
+ * `pre code { background: transparent; padding: 0 }` 同形。
+ * - 原生聊天流:解析阶段就分出 code 块 / 行内 code 两个类型(见
+ * messageMarkdown.test.ts 的无语言围栏用例)。
+ * - 桌面端:rehypeFencedCodeMarker 给 `pre > code` 打结构标记(见 apps/desktop 的
+ * markdownFencedCodeInline.test.ts)。桌面端曾按「有没有 className」近似判断,
+ * ```(无语言)围栏因此被整块套上行内底色,一行一个灰条。
+ *
+ * 这条 CSS 规则是纯样式、没有行为面,靠代码 review 容易被当冗余删掉,所以在这里
+ * 钉住。
+ */
+describe('buildSelectableMarkdownHtml 代码块内不套行内 code 装饰', () => {
+ const css = (): string => buildSelectableMarkdownHtml('# 标题');
+
+ it('存在 pre code 复位规则,且把底色清成 transparent', () => {
+ const rule = css().match(/pre code \{([^}]*)\}/);
+ expect(rule, '找不到 pre code 复位规则').toBeTruthy();
+ expect(rule![1]).toMatch(/background:\s*transparent/);
+ });
+
+ it('行内 code 自己的规则仍在(复位只针对代码块内,不是全局取消)', () => {
+ // `code { ... }` 独立规则:行内 code 的压暗色与等宽字体。
+ expect(css()).toMatch(/\n\s*code \{[^}]*font-family/);
+ });
+
+ it('无语言标注的围栏同样进 pre(复位规则因此对它生效)', () => {
+ const html = buildSelectableMarkdownHtml(['```', '任务(Session)', '```'].join('\n'));
+ expect(html).toContain('<pre>');
+ expect(html).toContain('<code>');
+ });
+});
diff --git a/apps/mobile/src/session/selectableMarkdownHtml.ts b/apps/mobile/src/session/selectableMarkdownHtml.ts
index 9f269e40a2..f3e0788504 100644
--- a/apps/mobile/src/session/selectableMarkdownHtml.ts
+++ b/apps/mobile/src/session/selectableMarkdownHtml.ts
@@ -301,7 +301,12 @@ function buildSelectableMarkdownCss(options: SelectableMarkdownHtmlOptions): str
font-size: ${codeFontSize}px;
}
/* 代码块内不压暗:pre 已有底色与描边把它划成独立区块,里面还要承载语法着色,
- 正文片段必须留在正文色上。不写这条 color 就会继承上面 code 的压暗。 */
+ 正文片段必须留在正文色上。不写这条 color 就会继承上面 code 的压暗。
+ background 同理复位(与 GitHub 的 pre code 规则同形):判据是**祖先结构**,
+ 不是语言标注 —— 无语言围栏一样在 pre 里,一样要复位。桌面端因为按
+ className(只有带语言标注才有)近似判断,曾把无语言围栏整块套上行内底色,
+ 修法是给 pre 的 code 打结构标记(见 desktop 的 rehypeFencedCodeMarker)。
+ 别当这条规则冗余删掉,回归测试见 selectableMarkdownHtml.test.ts。 */
pre code {
background: transparent;
color: ${textColor};