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): 保住 Windows 反斜杠本地路径的 markdown 链接不再退化纯文本 (#1752)

DavidShenXD9270ecef5a08
diff --git a/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts b/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
index cd03d1560f..c9a5da0890 100644
--- a/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownImagePathEncoding.test.ts
@@ -11,9 +11,9 @@ import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
import { describe, expect, it } from 'vitest';
import { normalizeMarkdownImageSrc } from '@/lib/localPathResolver';
-import remarkPreserveLocalImagePaths, {
+import remarkPreserveRawLocalDestinations, {
RAW_LOCAL_IMAGE_SRC_PROP,
-} from '../components/chat/remarkPreserveLocalImagePaths';
+} from '../components/chat/remarkPreserveRawLocalDestinations';
function normalizedImageSrc(markdown: string, workingDir = '/repo'): string | undefined {
let normalized: string | undefined;
@@ -30,7 +30,7 @@ function normalizedImageSrc(markdown: string, workingDir = '/repo'): string | un
return null;
},
},
- remarkPlugins: [remarkPreserveLocalImagePaths],
+ remarkPlugins: [remarkPreserveRawLocalDestinations],
urlTransform: defaultUrlTransform,
children: markdown,
}),
diff --git a/apps/desktop/src/renderer/__tests__/markdownLinkPathEncoding.test.ts b/apps/desktop/src/renderer/__tests__/markdownLinkPathEncoding.test.ts
new file mode 100644
index 0000000000..b4e7b2a71f
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/markdownLinkPathEncoding.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Regression coverage for local Markdown *links* whose destinations survive
+ * mdast-to-hast URL serialization only through the raw-preservation channel
+ * (issue #1629).
+ *
+ * `normalizeUri` percent-encodes Windows backslashes (`\` → `%5C`), so a
+ * model-written `[label](C:\Users\...\a.png)` reaches urlTransform as
+ * `C:%5CUsers%5C...` — it no longer matches the Windows-absolute whitelist,
+ * falls into react-markdown's protocol whitelist (`c:` = unknown scheme), and
+ * the href is stripped to "". Without the raw property the link degrades to
+ * dead plain text while the identical path renders fine as an image.
+ */
+
+import { createElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';
+import { describe, expect, it } from 'vitest';
+
+import { classifyMarkdownLinkTarget } from '@/lib/markdownTarget';
+import remarkLocalPathLinks from '../components/chat/remarkLocalPathLinks';
+import remarkPreserveRawLocalDestinations, {
+ RAW_LOCAL_LINK_HREF_PROP,
+} from '../components/chat/remarkPreserveRawLocalDestinations';
+
+interface CapturedLink {
+ raw?: string;
+ href?: string;
+}
+
+function renderLink(markdown: string): CapturedLink {
+ const captured: CapturedLink = {};
+ renderToStaticMarkup(
+ createElement(ReactMarkdown, {
+ components: {
+ a: ({ href, node }) => {
+ const raw = node?.properties?.[RAW_LOCAL_LINK_HREF_PROP];
+ captured.raw = typeof raw === 'string' ? raw : undefined;
+ captured.href = href;
+ return null;
+ },
+ },
+ // 与 MarkdownRenderer 的约束一致:preserve 插件必须排在
+ // remarkLocalPathLinks 之后,正文裸路径切出的 link 才拿得到原始值。
+ remarkPlugins: [remarkLocalPathLinks, remarkPreserveRawLocalDestinations],
+ urlTransform: defaultUrlTransform,
+ children: markdown,
+ }),
+ );
+ return captured;
+}
+
+describe('Markdown local link path encoding', () => {
+ it('preserves a Windows backslash absolute link that urlTransform strips to ""', () => {
+ const path = 'C:\\Users\\test\\AppData\\Roaming\\Cindy\\dialogues\\random_coordinates.png';
+ const { raw, href } = renderLink(`[查看图片 random_coordinates.png](${path})`);
+
+ // 前提锁死:没有 raw 通道时这条链接必死(href 被清空)。这一断言失败说明
+ // 上游序列化/transform 行为变了,需要重新评估本修复是否仍必要。
+ expect(href).toBe('');
+ expect(raw).toBe(path);
+
+ // 原始值走既有分类链路 → 本地图片 candidate(后续 resolve → 可点)。
+ const target = classifyMarkdownLinkTarget(raw);
+ expect(target.kind).toBe('local-candidate');
+ expect(target.kind === 'local-candidate' && target.localKind).toBe('image');
+ });
+
+ it('preserves a Windows absolute link with spaces via <> wrapping', () => {
+ const path = 'C:\\Users\\test\\My Pictures\\random coordinates.png';
+ const { raw } = renderLink(`[查看图片](<${path}>)`);
+ expect(raw).toBe(path);
+ });
+
+ it('preserves a POSIX absolute link with a real space next to a literal %20', () => {
+ const path = '/tmp/report %20final.csv';
+ const { raw } = renderLink(`[下载数据](<${path}>)`);
+ expect(raw).toBe(path);
+ });
+
+ it('preserves a workingDir-relative link destination', () => {
+ const { raw } = renderLink('[脚本](./scripts/generate_random_coordinates.py)');
+ expect(raw).toBe('./scripts/generate_random_coordinates.py');
+ });
+
+ it('stashes bare prose Windows paths cut out by remarkLocalPathLinks', () => {
+ // remarkLocalPathLinks 从正文纯文本切出的 link 节点同样经过 hast 序列化,
+ // 同样需要 raw 通道 —— preserve 插件排它之后才能覆盖到。
+ const { raw } = renderLink('改的是 C:\\proj\\src\\app.ts 这个文件');
+ expect(raw).toBe('C:\\proj\\src\\app.ts');
+ });
+
+ it('does not stash scheme-bearing destinations', () => {
+ for (const md of [
+ '[外链](https://example.com/a.png)',
+ '[邮件](mailto:[email protected])',
+ '[深链](cindy://session/00000000-0000-0000-0000-000000000000)',
+ ]) {
+ expect(renderLink(md).raw).toBeUndefined();
+ }
+ });
+
+ it('still stashes file:// destinations, matching the image channel', () => {
+ const url = 'file:///C:/Users/test/My%20Pictures/image.png';
+ expect(renderLink(`[图](${url})`).raw).toBe(url);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
index 9bb24c1ea1..0684dd5d33 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTargetRendererContract.test.ts
@@ -104,8 +104,23 @@ describe('Markdown target rendering contract', () => {
expect(markdownRenderer).toContain('WINDOWS_ABSOLUTE_HREF_RE.test(url)');
});
+ it('restores raw local link hrefs mangled by hast URL serialization (#1629)', () => {
+ // mdast→hast 会把反斜杠 percent-encode 成 %5C,`C:\...` 链接因此漏出
+ // trustedUrlTransform 白名单、href 被清空退化纯文本。a 渲染器必须优先消费
+ // remarkPreserveRawLocalDestinations 存的原始值(与 img 同构),且仅限受信任内容。
+ expect(markdownRenderer).toContain('RAW_LOCAL_LINK_HREF_PROP');
+ expect(markdownRenderer).toContain(
+ "allowPrivilegedLinks && typeof rawLocalHref === 'string' ? rawLocalHref : href",
+ );
+ // preserve 插件必须排在两份插件链的**链尾**(remarkLocalPathLinks 之后),
+ // 正文裸路径切出的 link 节点才拿得到原始值。
+ expect(
+ markdownRenderer.match(/remarkLocalPathLinks,\n remarkPreserveRawLocalDestinations,\n\]/g),
+ ).toHaveLength(2);
+ });
+
it('passes already-rewritten remote media image URLs through normalization', () => {
- expect(markdownRenderer).toContain('remarkPreserveLocalImagePaths');
+ expect(markdownRenderer).toContain('remarkPreserveRawLocalDestinations');
expect(markdownRenderer).toContain('normalizeMarkdownImageSrc(');
const normalizeBlock = localPathResolver.match(
/export function normalizeMarkdownImageSrc[\s\S]*?return toLocalFileUrl/,
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index c3b9856877..712c939691 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -25,9 +25,10 @@ import remarkStrictInlineMath from './remarkStrictInlineMath';
import { normalizeMathDelimiters } from '@cindy/maker-shared/math-markdown';
import remarkLocalPathLinks, { BARE_PATH_ATTR } from './remarkLocalPathLinks';
import remarkHtmlImages from './remarkHtmlImages';
-import remarkPreserveLocalImagePaths, {
+import remarkPreserveRawLocalDestinations, {
RAW_LOCAL_IMAGE_SRC_PROP,
-} from './remarkPreserveLocalImagePaths';
+ RAW_LOCAL_LINK_HREF_PROP,
+} from './remarkPreserveRawLocalDestinations';
import remarkSessionLinks from './remarkSessionLinks';
import { rehypeMathBlockMarker } from './rehypeMathBlockMarker';
import { FENCED_CODE_PROP, rehypeFencedCodeMarker } from './rehypeFencedCodeMarker';
@@ -186,6 +187,11 @@ function isMermaidCodeChild(child: ReactNode): boolean {
// 全中招);mobile 自研 parser 用正则配对本就能渲染这些写法,此处对齐。只放宽
// emphasis/strong 的定界判定,不碰 `~~` 删除线(gfm strikethrough 有独立定界
// 逻辑,行为不变),也不影响带空格的 `2 ** 3 ** 4` 这类本应保持字面量的写法。
+// remarkPreserveRawLocalDestinations 必须排在**链尾**:它给 image / link 节点存原始
+// 本地目的地(见该文件头部说明),必须在所有会新建这两类节点的插件之后运行——
+// remarkHtmlImages(<img> HTML → mdast image)与 remarkLocalPathLinks(正文裸路径
+// → link)。remarkSessionLinks 产出的 cindy:// 深链带 scheme,被它的判据跳过,
+// 顺序无关。
const REMARK_PLUGINS: PluggableList = [
[remarkGfm, { singleTilde: false }],
remarkCjkFriendly,
@@ -193,8 +199,8 @@ const REMARK_PLUGINS: PluggableList = [
remarkStrictInlineMath,
remarkTruncateCjkUrls,
remarkHtmlImages,
- remarkPreserveLocalImagePaths,
remarkLocalPathLinks,
+ remarkPreserveRawLocalDestinations,
];
const REMARK_PLUGINS_PRIVILEGED: PluggableList = [
[remarkGfm, { singleTilde: false }],
@@ -203,9 +209,9 @@ const REMARK_PLUGINS_PRIVILEGED: PluggableList = [
remarkStrictInlineMath,
remarkTruncateCjkUrls,
remarkHtmlImages,
- remarkPreserveLocalImagePaths,
remarkSessionLinks,
remarkLocalPathLinks,
+ remarkPreserveRawLocalDestinations,
];
// rehypeSlug: assigns a slug-style `id` to every heading. Without it
// in-document anchor links (`[Section](#section-name)`) hit dead targets.
@@ -1738,8 +1744,17 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
// remarkLocalPathLinks 打的标记:这条 link 来自正文裸写的路径,不是作者手写的
// `[label](path)`。读完即从 DOM props 里剥掉(它只是内部信道,不该落到 <a> 上)。
const fromBarePath = BARE_PATH_ATTR in rawProps;
+ // remarkPreserveRawLocalDestinations 存的原始本地 href。mdast→hast 序列化会把
+ // 反斜杠 percent-encode 成 %5C,`C:\Users\...` 变成 `C:%5CUsers...` 后既过不了
+ // trustedUrlTransform 的 Windows 绝对路径白名单(href 被清成 "" → 链接退化
+ // 纯文本,#1629),字面 `%20` 与真实空格也不可区分。与 img 渲染器同构:
+ // 分类/解析优先用原始值;仅受信任内容启用(untrusted 保持既有降级)。
+ const rawLocalHref = rawProps[RAW_LOCAL_LINK_HREF_PROP];
const safeProps = omitMarkdownInternalProps(rawProps);
delete safeProps[BARE_PATH_ATTR];
+ delete safeProps[RAW_LOCAL_LINK_HREF_PROP];
+ const targetHref =
+ allowPrivilegedLinks && typeof rawLocalHref === 'string' ? rawLocalHref : href;
if (allowPrivilegedLinks && href != null && hasDeepLinkPathPrefix(href, 'session-card/')) {
const parsed = parseSessionCardHref(href);
if (parsed) {
@@ -1776,7 +1791,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
}
return (
<MarkdownTargetLink
- href={href}
+ href={targetHref}
workingDir={workingDir}
isStreaming={isStreaming}
localFileRefs={localFileRefs}
diff --git a/apps/desktop/src/renderer/components/chat/remarkPreserveLocalImagePaths.ts b/apps/desktop/src/renderer/components/chat/remarkPreserveLocalImagePaths.ts
deleted file mode 100644
index 8eba3143fc..0000000000
--- a/apps/desktop/src/renderer/components/chat/remarkPreserveLocalImagePaths.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Preserve the exact local image destination before mdast-to-hast URL
- * serialization makes literal percent escapes ambiguous.
- *
- * Both a real space and the literal filename segment `%20` reach a custom
- * react-markdown image renderer as `%20`. Store the mdast value in a neutral
- * data property so the renderer can route the original filesystem path.
- */
-
-import type { Image, Root } from 'mdast';
-import type { Plugin } from 'unified';
-import { visit } from 'unist-util-visit';
-
-export const RAW_LOCAL_IMAGE_SRC_PROP = 'data-cindy-raw-local-image-src';
-
-const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
-const WINDOWS_ABSOLUTE_PATH_RE = /^[A-Za-z]:[\\/]/;
-
-function isLocalImageDestination(url: string): boolean {
- return (
- WINDOWS_ABSOLUTE_PATH_RE.test(url) ||
- url.startsWith('file://') ||
- !URL_SCHEME_RE.test(url)
- );
-}
-
-const remarkPreserveLocalImagePaths: Plugin<[], Root> = () => {
- return (tree) => {
- visit(tree, 'image', (node: Image) => {
- if (!isLocalImageDestination(node.url)) return;
-
- node.data = {
- ...node.data,
- hProperties: {
- ...(node.data?.hProperties ?? {}),
- [RAW_LOCAL_IMAGE_SRC_PROP]: node.url,
- },
- };
- });
- };
-};
-
-export default remarkPreserveLocalImagePaths;
diff --git a/apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts b/apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts
new file mode 100644
index 0000000000..c69876213f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts
@@ -0,0 +1,64 @@
+/**
+ * Preserve the exact local image / link destination before mdast-to-hast URL
+ * serialization mangles it.
+ *
+ * Two distinct failure modes, one mechanism:
+ * - Percent ambiguity: both a real space and the literal filename segment
+ * `%20` reach a custom react-markdown renderer as `%20`.
+ * - Windows backslashes: `normalizeUri` percent-encodes `\` into `%5C`, so a
+ * model-written `[label](C:\Users\...\a.png)` arrives as `C:%5CUsers%5C...`.
+ * That no longer matches the renderer's Windows-absolute whitelist in
+ * `trustedUrlTransform`, falls into react-markdown's default protocol
+ * whitelist (`c:` = unknown scheme), and the href is stripped to `""` —
+ * the link degrades to dead plain text while the same path renders fine
+ * as an image (issue #1629; images were already covered, links were not).
+ *
+ * Store the mdast value in a neutral data property so the img / a renderers
+ * can route the original filesystem path. Links and images use separate
+ * property names so neither renderer can accidentally consume the other's
+ * channel.
+ *
+ * Ordering: must run AFTER every plugin that creates image / link nodes with
+ * local destinations — remarkHtmlImages (single <img> HTML → mdast image) and
+ * remarkLocalPathLinks (bare prose paths → link). Keep it last in the remark
+ * plugin lists. remarkSessionLinks emits cindy:// deep links, which the
+ * scheme check below skips regardless of order.
+ */
+
+import type { Image, Link, Root } from 'mdast';
+import type { Plugin } from 'unified';
+import { visit } from 'unist-util-visit';
+
+export const RAW_LOCAL_IMAGE_SRC_PROP = 'data-cindy-raw-local-image-src';
+export const RAW_LOCAL_LINK_HREF_PROP = 'data-cindy-raw-local-link-href';
+
+const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
+const WINDOWS_ABSOLUTE_PATH_RE = /^[A-Za-z]:[\\/]/;
+
+function isLocalDestination(url: string): boolean {
+ return (
+ WINDOWS_ABSOLUTE_PATH_RE.test(url) ||
+ url.startsWith('file://') ||
+ !URL_SCHEME_RE.test(url)
+ );
+}
+
+const remarkPreserveRawLocalDestinations: Plugin<[], Root> = () => {
+ return (tree) => {
+ visit(tree, ['image', 'link'], (node) => {
+ const typed = node as Image | Link;
+ if (!isLocalDestination(typed.url)) return;
+
+ const prop = node.type === 'image' ? RAW_LOCAL_IMAGE_SRC_PROP : RAW_LOCAL_LINK_HREF_PROP;
+ typed.data = {
+ ...typed.data,
+ hProperties: {
+ ...(typed.data?.hProperties ?? {}),
+ [prop]: typed.url,
+ },
+ };
+ });
+ };
+};
+
+export default remarkPreserveRawLocalDestinations;