merge #1043: fix(editor) resolve markdown preview images on the page base

# Conflicts:
#	src/client/markdown-images.ts
#	src/client/markdown-labels.tsx
#	src/client/markdown-navigation.ts
#	tests/markdown-images.spec.ts
This commit is contained in:
Menghuan1918 committed 2026-11-08 00:19:09 +08:00
commit 77cbf420ce
15 files changed
+649 -209

No files matched your search

+1 -1
View File
@@ -576,7 +576,7 @@ interface FileViewerProps {
> **head 字节从哪来**:第一次匹配(纯扩展名)没有 head。`fsRead` 策略读取后若文件为二进制,host 的 `fs.read` 响应会带 `head` 字段(base64,前 4KB,`src/index.ts` 的 `READ_HEAD_LIMIT`),编辑器会用它对 `detect` viewer **重匹配一次**——所以 detect 型 viewer 的实际触发场景是"扩展名匹配落空/二进制文件"。文本文件的 detect 嗅探不在内置流程内(用 `exts` 或 `custom` 策略替代)。
> **内置 viewer**(不可重复注册,全部 3 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体 src 重写走 `/sidebar/file`;≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存 + 未提交变更提示(行号着色 / 左侧细色条 / hover blame,一个 `editorGitGutter` 开关,[设计文档](plans/2026-10-05-editor-git-gutter.md)))。
> **内置 viewer**(不可重复注册,全部 3 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体走页面 base(markdown 语法的图片经 `pathImages` 解析:浏览器用页面 base 的 `/sidebar/file`,桌面壳用 `dsh-app://app/api/file`;内嵌 HTML 的 `<img src>` 直接重写为页面 base 的 `/sidebar/file`);≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md);桌面壳媒体基址的修复见 [2026-10-23 记录](plans/2026-10-23-desktop-markdown-media-base.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存 + 未提交变更提示(行号着色 / 左侧细色条 / hover blame,一个 `editorGitGutter` 开关,[设计文档](plans/2026-10-05-editor-git-gutter.md)))。
> code 是兜底 viewer:任何其他 viewer 未认领的文件都会落到 code(CodeMirror 文本编辑);二进制文件经 head 重匹配找不到 sniffer,落到编辑器的下载面板。外部 viewer 注册同扩展名 + 更高 priority 即可覆盖内置的那三个。
>
> ⚠️ **让给宿主的格式(重要,影响你的 viewer 能不能被调用)**:DSH 0.1.7 的 `ui-sidebar-documentpreview` 自带 code / excel(xlsx,xls,csv,tsv) / office(宿主侧转 PDF)/ pdf / image / html / markdown / text 预览,并带缩放与**按目录自动刷新**——本插件原有的 image / pdf / binary-download 三个 viewer 描述符因此删除。更重要的是**路由**:插件的 `editor` 类型在 `canOpen` 里对下列扩展名一律返回 false(`src/client/native/index.ts` 的 `HOST_OWNED_EXTS`),把地址让给内置 `text` 档,**根本不会进入本插件的 `matchFileViewer`**:
@@ -0,0 +1,96 @@
# 桌面壳下 Markdown 预览本地图片不渲染(媒体 URL 基址)
## 现象
DeepSeek Harness 桌面端(Electron 壳,DSH 0.2.1-rc.2,插件 0.28.0):打开一个引用本地图片的
`.md`(`![图](images/x.png)`),右侧「预览」里图片不出现,只显示图片的 **alt 文本**;把插件
禁用后,同一文件的宿主内置文档预览正常。浏览器(`dsh web`)下没有这个问题。
## 根因
1. **预览把媒体 URL 拼在 transport base 上。** `TextEditor` / `DiffPane` 用
`hostTransportBase()`(桌面壳里 = `__DSH_TRANSPORT__.streamBaseUrl`,即 Host 的
`http://127.0.0.1:<port>` origin)把本地图片改写成绝对 URL。
桌面壳的页面 origin 是 `dsh-app://app/`,所以这是**跨站子资源**
(`Sec-Fetch-Site: cross-site`)。
2. **宿主拒绝它。** `/sidebar/*` 的围栏(0.28.0 起为 `ctx.connection.requestRejection()`)里,
Host 的 `isTrustedApiRequest` 对 `cross-site` 直接拒绝;会话 cookie 是
`HttpOnly; SameSite=Strict`,跨站 `<img>` 不会携带。桌面壳只为两类请求补凭据/同源标记——
`dsh-app://app/*` 的转发(`forwardWebRequest` 加 cookie、删 `Origin`/`Sec-Fetch-Site`)和
`ws://127.0.0.1/*` 升级——普通 http 图片 GET 不在其中。实测同一 URL:不带 cookie
`403 forbidden`,带桌面会话的 `dsh-auth-*` cookie `200 image/png`。
3. **为什么不能只换基址。** `MarkdownText` 对 markdown 语法只接受绝对 http(s) 目标,其余交给
所属表面的图片词汇钩子(`pathImages`)并由渲染器**复检协议**:http(s)/blob/data,或
桌面应用文件路由 `dsh-app://app/api/file?`。所以:
- 换 `hostHttpBase()` 后直接拼 `/sidebar/file` → `dsh-app://app/sidebar/file?...` 会被
白名单拒绝,仍是 alt 文本;
- 桌面壳里能过白名单的本地文件形状只有 `dsh-app://app/api/file?path=...`(宿主
`SessionMediaReferences` 的认证文件路由,内置文档预览的 markdown 图片也用它)。
4. **宿主的文件路由只收绝对路径。** 从聊天地址打开的编辑 tab 可以携带**工作区相对**的
`path`(面包屑显示 `openwrt-proxy-primer/PRINCIPLES.md`)。插件的 `/sidebar/file` 路由
(v1 的 `/sidebar/file` 与浏览器的 `/sidebar/file` 分支)能靠 `cwd` 参数解析相对路径,
但 `/api/file?path=` 对相对路径直接回 **400 `absolute path required`** —— 最初只换路由
不换路径拼接时,桌面壳图片因此仍回退 alt 文本。
## 方案
沿用「渲染前把目标交给渲染器词汇」的既有架构,只修正词汇产出的 URL:
- `pathImages.resolve(destination)`:本地目标 → **页面 base** 上的可显示 URL;
- **浏览器**(页面 base 是 http(s)):插件的 `/sidebar/file` 媒体路由(与今天逐字相同,
保留反代前缀与会话/工作区围栏);
- **桌面壳**(页面 base 是 `dsh-app://app/`):宿主的认证 `api/file?path=` 路由
(`dsh-app://app/api/file?...`,壳转发时带 launch cookie)。
- 原始 HTML 的 `<img src="./x.png">` 是普通 DOM,不经渲染器白名单,继续由
`resolveLocalMediaDest` 直接重写为**页面 base** 的 `/sidebar/file`。
- markdown 图片目标保持作者原文(交给词汇钩子),因此删除 `rewriteLocalImageUrls`;
链接 pass 跳过**被图片引用的引用式定义**(否则定义被加 `?`,图片又退回 alt 文本),
只被普通链接引用的定义仍照旧钉住。
不新增界面元素:图片仍渲染为单个 `<img>`(max-width: 100%),尺寸与浏览器/内置预览一致,
不引入聊天里那种 640×360 缩略图 + 灯箱(那是 `MarkdownDelegate.fileImages` 的行为,
本次刻意不用)。
## 备选与取舍
| 方案 | 结论 |
| --- | --- |
| 只把 `hostTransportBase()` 换成 `hostHttpBase()` | 不够:`dsh-app://app/sidebar/file` 被渲染器白名单拒绝,仍是 alt 文本 |
| `MarkdownDelegate.fileImages` 委托 + 插件媒体路由 | 能修且保留插件路由,但宿主会按聊天惯例给委托图片加 640×360 缩略图上限与灯箱按钮,预览尺寸与内置预览/旧版不一致 |
| 预取字节 → blob:/data: URL | 异步、逐图缓存与失效成本高 |
| **`pathImages` + 桌面壳宿主文件路由(本方案)** | 浏览器 URL 与现状逐字相同;桌面壳用内置预览同款路由;单个 `<img>`,尺寸不变 |
## 改动
- `src/client/markdown-images.ts`:删除 `rewriteLocalImageUrls`;新增
`markdownImageTarget` / `markdownMediaUrl` / `desktopFileUrl` / `createMarkdownPathImages`,
`resolveLocalMediaDest` 共用同一路径解析(含一次百分号解码);桌面分支先用会话 cwd 把
相对目标补成绝对路径(无 cwd 时退回 alt 文本,而不是发一个必然 400 的 URL)。
- `src/client/markdown-labels.tsx`:`markdownTextProps` 透传可选 `pathImages`。
- `src/client/TextEditor.tsx`:`htmlMedia` 用页面 base + `pathImages`;预览不再重写图片目标。
- `src/client/MarkdownHtml.tsx`:markdown run 只跑链接 pass,`media.pathImages` 透传给
MarkdownText / mermaid chunk。
- `src/client/mermaid-blocks.ts` / `src/client/mermaid.tsx`:chunk props 透传 `pathImages`。
- `src/client/changes/DiffPane.tsx`:阅读模式同样传 `pathImages`(`filePath` 用绝对路径)。
- `src/client/markdown-navigation.ts`:链接 pass 跳过图片引用的定义。
## 验证
- `tests/markdown-images.spec.ts`:目标解析;浏览器/反代前缀/`dsh-app://app/` 三种 base
(桌面壳走 `dsh-app://app/api/file?path=`);**相对 tab 路径在桌面壳里必须补成绝对路径**
(无 cwd 时返回 undefined);一次百分号解码;raw HTML 分支。
- `tests/markdown-html-render.spec.tsx`:真实 `MarkdownText` + `pathImages`,断言
**`dsh-app://app/` 页面下 markdown 图片渲染为 `dsh-app://app/api/file?...`、raw HTML 图片
渲染为 `dsh-app://app/sidebar/file?...`**(修复前是 alt 文本);http 页面现有断言逐字不变。
- `tests/markdown-navigation.spec.ts` / `tests/markdown-crlf.spec.ts`:图片引用定义不被
链接 pass 改动,普通链接定义仍被钉住不可点;CRLF 与 LF 逐字一致。
- `pnpm typecheck` / `pnpm lint` / `pnpm build` / 全量 `pnpm test`。
## 已知边界
- 侧边对话转录、任务窗口等**其它** markdown 表面没有挂 `pathImages`,其中的本地图片行为不变
(修复前后都回退 alt 文本);本 PR 只覆盖编辑器预览与变更阅读窗。
- 桌面壳的 markdown 图片走宿主 `api/file` 路由(与内置文档预览一致);原始 HTML 图片走
插件自己的 `/sidebar/file` 路由(普通 DOM,不参与渲染器白名单)。
+21 -19
View File
@@ -11,16 +11,19 @@
* open-tag attributes) goes through DOMPurify with an explicit denylist on
* top of its defaults (no script/style/iframe/forms), anchors are forced to
* open in a new tab with noopener, and local media goes through the
* session-scoped `/sidebar/file` media route — markdown-syntax image
* destinations are rewritten via `markdown-images.ts` and `src` attributes
* through `resolveLocalMediaDest` (the same trust fence).
* session-scoped `/sidebar/file` media route — `src` attributes via
* `resolveLocalMediaDest` (the same trust fence). Markdown-syntax images are
* resolved by the owning surface's `pathImages` vocabulary
* (`markdown-images.ts`); that is what keeps them same-origin in the desktop
* shell.
*/
import { useLayoutEffect, useMemo, useRef } from 'react'
import { createElement, type ReactNode } from 'react'
import DOMPurify from 'dompurify'
import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'
import { markdownTextProps, type MarkdownCopyLabels } from './markdown-labels.tsx'
import { resolveLocalMediaDest, rewriteLocalImageUrls } from './markdown-images.ts'
import { resolveLocalMediaDest } from './markdown-images.ts'
import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts'
import {
analyzeHtmlSegment,
@@ -41,8 +44,10 @@ import { LazyMermaidMarkdown } from './mermaid-lazy.tsx'
export interface MarkdownHtmlMedia {
scope: SessionScope
path: string
/** The injected transport base, reverse-proxy prefix included. */
/** The PAGE base, reverse-proxy prefix included (`hostHttpBase()`). */
baseUrl: string
/** The owner's local-path image vocabulary for markdown runs. */
pathImages?: MarkdownPathImages | undefined
}
/** Tag-like text in a rendered text node — the inline pass gate. */
@@ -231,6 +236,7 @@ interface MarkdownSegmentProps {
* skips its own output, so mutation feedback settles after one extra pass.
*/
function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmentProps): ReactNode {
const pathImages = media.pathImages
const containerRef = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
const container = containerRef.current
@@ -279,8 +285,8 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen
return (
<div ref={containerRef}>
{hasMermaid
? <LazyMermaidMarkdown text={text} codeLabels={codeLabels} />
: <MarkdownText {...markdownTextProps(text, codeLabels)} />}
? <LazyMermaidMarkdown text={text} codeLabels={codeLabels} pathImages={pathImages} />
: <MarkdownText {...markdownTextProps(text, codeLabels, pathImages)} />}
</div>
)
}
@@ -324,18 +330,14 @@ export function MarkdownDocument({ info, media, codeLabels }: MarkdownDocumentPr
if (segment.kind === 'markdown') {
const defs = info.referenceDefinitions
const raw = defs === '' ? segment.text : `${segment.text}\n\n${defs}`
// MarkdownText drops non-http(s) image destinations (chat-security
// stance), so rewrite local ones into /sidebar/file media URLs first —
// the same trust fence the sanitized HTML leaves below go through.
// Idempotent: already-absolute media URLs pass through untouched.
// The link pass follows (it must see the media URLs already in place):
// it carries a heading fragment past the host parser and keeps every
// local destination the plugin does not claim inert.
const text = rewriteLocalMarkdownLinks(
rewriteLocalImageUrls(raw, media.scope, media.path, media.baseUrl),
media.path,
media.scope.cwd,
)
// Local image destinations stay as authored: the enclosing surface's
// `pathImages` vocabulary resolves them at render time (see
// markdown-images.ts — a rewritten URL could not be vouched for from the
// desktop shell's `dsh-app://` page). The link pass runs here so a
// heading fragment survives the host parser and every local link the
// plugin does not claim stays inert; image-referenced definitions are
// left alone by that pass so the renderer can still resolve them.
const text = rewriteLocalMarkdownLinks(raw, media.path, media.scope.cwd)
return {
kind: 'markdown',
text,
+25 -21
View File
@@ -29,9 +29,9 @@ import {
type GitGutterHost,
} from './editor-git-gutter.ts'
import { api, htmlUrl, SidebarApiError } from './api.ts'
import { hostTransportBase } from './desktop-env.ts'
import { hostHttpBase } from './desktop-env.ts'
import { markdownPreviewSource } from './markdown-frontmatter.ts'
import { rewriteLocalImageUrls } from './markdown-images.ts'
import { createMarkdownPathImages } from './markdown-images.ts'
import { rewriteLocalMarkdownLinks } from './markdown-navigation.ts'
import { languageForPath } from './lang.ts'
import { cmSurfaceTheme, CmThemeCompartment } from './cm-themes.ts'
@@ -924,17 +924,14 @@ export function TextEditor(props: FileViewerProps) {
requestAnimationFrame(() => { restoringRef.current = false })
}, [mode, previewMdText])
/** The preview source with local image destinations rewritten to absolute
* media URLs (see {@link rewriteLocalImageUrls}) and the local link
* destinations prepared for the host delegate (see
* {@link rewriteLocalMarkdownLinks}; the split renderer runs the same two
* passes per markdown run, and both are idempotent). */
/** The preview source with the local link destinations prepared for the
* host delegate (see {@link rewriteLocalMarkdownLinks}; the split renderer
* runs the same pass per markdown run, and it is idempotent). Local IMAGE
* destinations stay as authored: the owner's `pathImages` vocabulary
* resolves them at render time, which is the only shape that also works
* from the desktop shell's `dsh-app://` page (see markdown-images.ts). */
const previewText = markdown
? rewriteLocalMarkdownLinks(
rewriteLocalImageUrls(previewMdText, scope, path, hostTransportBase()),
path,
scope.cwd,
)
? rewriteLocalMarkdownLinks(previewMdText, path, scope.cwd)
: previewMdText
/** md/mermaid block split for the preview (mermaid fences lift out). Split
* only in preview mode: edit-mode keystrokes must not re-scan the source. */
@@ -944,9 +941,8 @@ export function TextEditor(props: FileViewerProps) {
)
/** Raw-HTML analysis (block runs lifted out + inline gate). Non-null for
* every markdown preview, so the render below always takes the split
* renderer — its markdown runs rewrite local image destinations internally
* (see MarkdownHtml.tsx). The legacy single-pass branches (fed the
* pre-rewritten `previewText`) are dead in the current wiring. */
* renderer. The legacy single-pass branches are dead in the current
* wiring. */
const htmlInfo = useMemo(
() => (markdown && mode === 'preview' ? analyzeMarkdownHtml(previewMdText) : null),
[markdown, mode, previewMdText],
@@ -959,11 +955,19 @@ export function TextEditor(props: FileViewerProps) {
[htmlInfo, mdBlocks],
)
/** The media context for the split renderer (local-src rewriting inside
* sanitized HTML). Memoized on primitives: MarkdownDocument sanitizes per
* `media` identity, so a fresh object per render would re-sanitize every
* keystroke. */
* sanitized HTML, plus the owner's `pathImages` vocabulary for markdown
* runs). The PAGE base is load-bearing: in the desktop shell the transport
* origin is a different site and its media request would be rejected by the
* Connection fence (see markdown-images.ts). Memoized on primitives:
* MarkdownDocument sanitizes per `media` identity, so a fresh object per
* render would re-sanitize every keystroke. */
const htmlMedia = useMemo<MarkdownHtmlMedia>(
() => ({ scope, path, baseUrl: hostTransportBase() }),
() => ({
scope,
path,
baseUrl: hostHttpBase(),
pathImages: createMarkdownPathImages(scope, path, hostHttpBase()),
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[scope.sessionId, scope.cwd, path],
)
@@ -1212,8 +1216,8 @@ export function TextEditor(props: FileViewerProps) {
{htmlInfo !== null
? <MarkdownDocument info={htmlInfo} media={htmlMedia} codeLabels={codeLabels} />
: hasMermaid
? <LazyMermaidMarkdown text={previewText} codeLabels={codeLabels} />
: <MarkdownText {...markdownTextProps(previewText, codeLabels)} />}
? <LazyMermaidMarkdown text={previewText} codeLabels={codeLabels} pathImages={htmlMedia.pathImages} />
: <MarkdownText {...markdownTextProps(previewText, codeLabels, htmlMedia.pathImages)} />}
</MarkdownDelegateProvider>
</div>
)}
+21 -18
View File
@@ -21,7 +21,7 @@ import { IconCloseOutlineRegular, IconRefreshOutlineRegular, IconRightUpOutlineR
import type { Context } from '../../context-types.ts'
import type { SessionScope } from '../api.ts'
import { api, htmlUrl } from '../api.ts'
import { hostTransportBase } from '../desktop-env.ts'
import { hostHttpBase } from '../desktop-env.ts'
import { t } from '../locales.ts'
import { baseName } from '../paths.ts'
import { resolveSidebarPath } from '../paths.ts'
@@ -36,7 +36,7 @@ import { buildDiffSegments, diffLines, diffStats, parseUnifiedDiff, unifiedSegme
import { useGitDiffTarget } from '../diff/use-git-diff.ts'
import { parseReadContent, parseReadLines, type FileOp } from './ops.ts'
import { redactText } from '../redact.ts'
import { rewriteLocalImageUrls } from '../markdown-images.ts'
import { createMarkdownPathImages } from '../markdown-images.ts'
import { markdownTextProps } from '../markdown-labels.tsx'
import { useMarkdownSurface } from '../use-markdown-surface.ts'
import { splitMermaidBlocks } from '../mermaid-blocks.ts'
@@ -163,16 +163,17 @@ export function PaneTabStrip(props: { tabs: readonly PaneTab[]; active: string;
}
/** The reading-mode body of one markdown op target: the shared MarkdownText
* pass (local image destinations already rewritten to the media route by
* the caller). Mermaid fences render through the same chunk-resident
* renderer the editor preview uses (one MarkdownText pass with the fences
* lifted out); the plain path stays byte-for-byte for documents without
* any.
* pass. Mermaid fences render through the same chunk-resident renderer the
* editor preview uses (one MarkdownText pass with the fences lifted out); the
* plain path stays byte-for-byte for documents without any.
*
* The body is also a markdown SURFACE: heading slugs, anchor jumps and `.md`
* link claiming, with relative targets resolved against the previewed file's
* own directory (see use-markdown-surface). */
function MdReadingView(props: { text: string; ctx: Context; scope: SessionScope; path: string }) {
* own directory (see use-markdown-surface). Local images resolve through the
* owner's `pathImages` vocabulary, based on the PAGE base — the same shape the
* editor preview uses (see markdown-images.ts): a transport-origin http URL
* would be cross-site and rejected from the desktop shell's page. */
function MdReadingView(props: { text: string; ctx: Context; scope: SessionScope; path: string; filePath: string }) {
const codeLabels = {
copyLabel: t('copy'),
copiedLabel: t('copied'),
@@ -186,8 +187,9 @@ function MdReadingView(props: { text: string; ctx: Context; scope: SessionScope;
cwd: props.scope.cwd,
path: props.path,
})
// The caller already rewrote local IMAGE destinations; this pass is the link
// half (and is idempotent, so the two can be composed in either order).
const pathImages = createMarkdownPathImages(props.scope, props.filePath, hostHttpBase())
// The caller's link pass (surface.rewrite) is idempotent and leaves image
// destinations to the vocabulary above.
const text = surface.rewrite(props.text)
const hasMermaid = splitMermaidBlocks(text).some((block) => block.kind === 'mermaid')
return (
@@ -195,8 +197,8 @@ function MdReadingView(props: { text: string; ctx: Context; scope: SessionScope;
<div className={css.mdBody}>
<MarkdownDelegateProvider openFile={surface.openFile}>
{hasMermaid
? <LazyMermaidMarkdown text={text} codeLabels={codeLabels} />
: <MarkdownText {...markdownTextProps(text, codeLabels)} />}
? <LazyMermaidMarkdown text={text} codeLabels={codeLabels} pathImages={pathImages} />
: <MarkdownText {...markdownTextProps(text, codeLabels, pathImages)} />}
</MarkdownDelegateProvider>
</div>
</div>
@@ -423,11 +425,12 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose,
() => (contentSrc === '' ? [] : contentSrc.split('\n').map((text, index) => ({ line: index + 1, text }))),
[contentSrc],
)
/** Reading mode receives the source as authored: local images resolve
* through the surface's `pathImages` vocabulary in `MdReadingView` (the
* source rewrite below cannot vouch for them from the desktop shell). */
const contentText = useMemo(
() => (mdOp && !contentRaw && contentSrc !== ''
? rewriteLocalImageUrls(contentSrc, scope, contentPath, hostTransportBase())
: ''),
[mdOp, contentRaw, contentSrc, scope, contentPath],
() => (mdOp && !contentRaw ? contentSrc : ''),
[mdOp, contentRaw, contentSrc],
)
const htmlRenderSrc = useMemo(
() => (htmlOp && contentAbs !== '' ? htmlUrl(scope, contentAbs) : ''),
@@ -543,7 +546,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose,
: contentView === 'html'
? <HtmlRenderPreview src={htmlRenderSrc} title={title} />
: contentView === 'md'
? <MdReadingView text={contentText} ctx={ctx} scope={scope} path={contentPath} />
? <MdReadingView text={contentText} ctx={ctx} scope={scope} path={contentPath} filePath={contentAbs !== '' ? contentAbs : contentPath} />
: gitWorktree !== null
? (gitContent.status === 'loading' || gitContent.status === 'idle'
? <div className={css.paneBody}><Notice kind="loading" tone="page">{t('loading')}</Notice></div>
+1 -1
View File
@@ -62,7 +62,7 @@ function fenceRun(line: string): { marker: string; length: number } | null {
* The tail may carry a CRLF terminator: `\r` is the line's ending, not
* content, and reading it as content left every fence in a CRLF document
* unclosed — the masked region then ran to the end of the file and the link /
* image passes skipped everything after the first fence. */
* rewrite passes skipped everything after the first fence. */
function closesFence(line: string, marker: string, length: number): boolean {
if (line.charAt(0) !== marker) return false
let run = 0
+177 -28
View File
@@ -1,19 +1,38 @@
/**
* Local-image resolution for rendered markdown: the shared `MarkdownText`
* (from @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s)
* image URLs — relative links are disabled for chat security — so a local
* image in a previewed `.md` (`![alt](./img.png)`, an absolute `/cwd/img.png`,
* or a reference definition) or in a Side Chat prose row would otherwise fall
* back to its alt text. This dependency-free helper rewrites those
* destinations into absolute `/sidebar/file` media URLs, resolved against the
* injected transport base so a reverse-proxy prefix survives; `MarkdownText`
* accepts them because they are absolute http(s), and the host media route
* then serves the bytes. Relative destinations resolve against the rendered
* file's directory for a document, and against the session workspace root for
* prose ({@link rewriteProseLocalImageUrls}).
* Local-image resolution for the plugin's markdown surfaces.
*
* The shared `MarkdownText` renders absolute http(s) image destinations as
* authored; a local destination (an image-relative `./img.png`, an absolute
* `/cwd/img.png`, or a reference definition) is handed to the owner's
* `pathImages` vocabulary, and only a miss falls back to the documented alt
* text. That is the DSH renderer's sanctioned rewrite hook: the owner maps an
* authored destination to a displayable absolute URL it vouches for.
*
* The base is what has to change for the desktop shell. Its page origin is
* `dsh-app://app/` while the Host listens on another origin
* (`__DSH_TRANSPORT__.streamBaseUrl`): an absolute http URL built from that
* transport base is a CROSS-SITE subresource, so the Host's Connection fence
* rejects it (403) and the image falls back to alt text. Two shapes survive:
*
* - **Browser** (page base is http(s)): the plugin's own `/sidebar/file`
* media route on the page base — same-origin as before, reverse-proxy
* prefix included.
* - **Desktop shell** (page base is `dsh-app://app/`): the Host's
* authenticated `api/file?path=` route on the page base. The shell forwards
* every non-static `dsh-app://app/*` request to the Host with the launch
* cookie, and `dsh-app://app/api/file?...` is the one local-file URL shape
* the renderer's image vocabulary accepts. The built-in document preview
* resolves its markdown images the same way.
*
* Raw HTML leaves (`<img src="./x.png">`) are different: they render as plain
* DOM elements, not through `MarkdownText`, so {@link resolveLocalMediaDest}
* hands them the plugin media route on the page base directly — a plain
* `<img>` has no protocol vocabulary to satisfy.
*/
import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionScope } from './api.ts'
import { hostHttpBase } from './desktop-env.ts'
import { hostRouteUrl } from './host-route-url.ts'
import { maskCodeRegions } from './markdown-code.ts'
import { isAbsolutePath } from './paths.ts'
@@ -21,7 +40,7 @@ import { isAbsolutePath } from './paths.ts'
/**
* True for a destination that is a remote URL — an absolute `scheme:` URL
* that is not a Windows drive path (`C:\...`). http/https/data/mailto etc.
* all match here and are handed back to `MarkdownText` untouched.
* all match here.
*/
function isRemoteUrl(dest: string): boolean {
return /^[a-z][a-z0-9+.-]*:/i.test(dest) && !/^[A-Za-z]:[\\/]/.test(dest)
@@ -31,7 +50,7 @@ function isRemoteUrl(dest: string): boolean {
* Collapse `.`/`..` segments of an absolute local path, preserving its root
* (POSIX `/`), its Windows drive (`C:\`), or its UNC `\\server\share`
* prefix. The host's `requireAbsolute` (`path.resolve`) normalizes anyway,
* but producing a canonical path here keeps the `/sidebar/file` URL clean.
* but producing a canonical path here keeps the media URLs clean.
* Shared with the markdown navigation resolver (`markdown-navigation.ts`),
* which canonicalizes a claimed link target the same way.
*/
@@ -51,13 +70,138 @@ export function normalizeLocalPath(path: string): string {
}
/**
* Resolve one media destination against the session's media route: local
* (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved
* through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them
* AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and
* empty destinations are returned untouched. Shared by the markdown image rewriter below and by the
* preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same
* allowlist when rendering `<img src="./x.png">` inside HTML blocks).
* The absolute spelling of one target for routes that require it (the desktop
* shell's host `api/file`): a relative target joins the session workspace
* root. Returns undefined when the target is relative and no root is known —
* the caller then falls back to alt text instead of an absolute-path 400.
* @param target - A target produced by {@link markdownImageTarget}.
* @param cwd - The session workspace root, when known.
* @returns The absolute target, or undefined.
*/
function absoluteTarget(target: string, cwd: string | undefined): string | undefined {
if (isAbsolutePath(target)) return target
if (cwd === undefined || cwd === '') return undefined
return normalizeLocalPath(`${cwd.replace(/[\\/]+$/, '')}/${target}`)
}
/**
* Percent-decode one authored destination exactly once (the renderer hands
* the rewrite hook the spelling the author wrote). A malformed escape is
* refused rather than thrown.
* @param value - The authored destination.
* @returns The decoded destination, or undefined for a malformed escape.
*/
function decodeDestination(value: string): string | undefined {
try {
return decodeURIComponent(value)
} catch {
return undefined
}
}
/**
* The absolute local target of one markdown destination, or undefined when
* the destination is not a local path this vocabulary serves. Relative
* destinations resolve against the opened file's own directory; remote URLs,
* `#`-anchors, empty destinations and queries are refused (the renderer keeps
* its alt-text fallback for those).
* The result may still be RELATIVE when the opened file's path is relative
* (an editor tab opened from a chat address can carry a workspace-relative
* path). The plugin media route accepts that together with `cwd`; the desktop
* shell's host file route does not — see {@link absoluteTarget}.
* @param destination - One decoded image destination.
* @param filePath - The path of the opened `.md` file.
* @returns The normalized target path, or undefined.
*/
export function markdownImageTarget(destination: string, filePath: string): string | undefined {
const dest = destination.trim()
if (dest === '' || dest.startsWith('#') || isRemoteUrl(dest)) return undefined
// The host's file-link grammar refuses queries and scheme-relative forms.
if (dest.includes('?') || /^[\\/]{2}/.test(dest)) return undefined
const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
const candidate = isAbsolutePath(dest) ? dest : directory + dest
return normalizeLocalPath(candidate)
}
/**
* Absolute URL of the plugin's session media route for one local image,
* resolved against the page base (browser deployments).
* @param target - Local image path (absolute, or relative to `scope.cwd` when
* the opened file itself carries a workspace-relative path).
* @param scope - The session scope (sessionId + cwd) for the media route.
* @param baseUrl - The page base (`hostHttpBase()`); injected for pure tests.
* @returns The absolute media URL.
*/
export function markdownMediaUrl(target: string, scope: SessionScope, baseUrl: string): string {
const params = new URLSearchParams({ sessionId: scope.sessionId, path: target })
if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href
}
/**
* Absolute URL of the Host's authenticated file route on the page base — the
* only local-file image shape the desktop shell page can display (see the
* module comment).
* @param target - Absolute local path of the image.
* @param baseUrl - The page base (`dsh-app://app/`); injected for pure tests.
* @returns The absolute file URL.
*/
export function desktopFileUrl(target: string, baseUrl: string): string {
const params = new URLSearchParams({ path: target })
return hostRouteUrl(`api/file?${params.toString()}`, baseUrl).href
}
/**
* Build the `pathImages` vocabulary for one markdown surface: `MarkdownText`
* asks it for an authored local image destination and gets back a displayable
* absolute URL on the page base, so the same code works in a browser and in
* the desktop shell.
* @param scope - The session scope (sessionId + cwd) for the plugin media route.
* @param filePath - The path of the opened `.md` file (may be workspace-relative).
* @param baseUrl - The page base; defaults to `hostHttpBase()`.
* @returns The owner's local-path image vocabulary.
*/
export function createMarkdownPathImages(
scope: SessionScope,
filePath: string,
baseUrl: string = hostHttpBase(),
): MarkdownPathImages {
let desktop = false
try {
desktop = new URL(baseUrl).protocol === 'dsh-app:'
} catch {
// Non-absolute/empty base (specs, non-DOM callers): the browser branch is
// the only one whose URL builder does not need a real scheme.
}
return {
resolve: (destination: string): string | undefined => {
const decoded = decodeDestination(destination)
if (decoded === undefined) return undefined
const target = markdownImageTarget(decoded, filePath)
if (target === undefined) return undefined
if (!desktop) return markdownMediaUrl(target, scope, baseUrl)
// The host file route requires an ABSOLUTE path (a relative one answers
// 400 "absolute path required"); a relative tab path is the common case
// for files opened from chat, so join the workspace root explicitly.
const absolute = absoluteTarget(target, scope.cwd)
return absolute === undefined ? undefined : desktopFileUrl(absolute, baseUrl)
},
}
}
/**
* Resolve one raw-HTML media destination to a displayable URL: local
* (relative or absolute) paths become absolute page-base `/sidebar/file` URLs,
* while remote URLs, `#`-anchors and empty destinations are returned
* untouched. Used by the preview's raw-HTML sanitizer (`MarkdownHtml.tsx`),
* whose `<img src>` renders as plain DOM; markdown-syntax images go through
* {@link createMarkdownPathImages} instead.
* @param dest - One `src`/`poster` value from the sanitized HTML.
* @param scope - The session scope (sessionId + cwd) for the media route.
* @param filePath - The path of the opened `.md` file (may be workspace-relative).
* @param baseUrl - The page base (`hostHttpBase()`); injected for pure tests.
* @returns The rewritten source (untouched for remote/anchor/empty values).
*/
export function resolveLocalMediaDest(
dest: string,
@@ -65,16 +209,21 @@ export function resolveLocalMediaDest(
filePath: string,
baseUrl: string,
): string {
const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
return resolveMediaDest(dest, scope, directory, baseUrl)
const trimmed = dest.trim()
if (trimmed === '' || trimmed.startsWith('#')) return dest
if (isRemoteUrl(trimmed)) return dest
const decoded = decodeDestination(trimmed)
if (decoded === undefined) return dest
const target = markdownImageTarget(decoded, filePath)
if (target === undefined) return dest
return markdownMediaUrl(target, scope, baseUrl)
}
/**
* One media destination against a base DIRECTORY (already path-separated):
* the shared body of the file and prose variants. `undefined` leaves relative
* destinations untouched — without a base there is nothing to resolve them
* against, and a bare relative URL would just fail the host allowlist.
* Legacy source rewriters, kept for the prose surface (SideChat) and for
* pre-existing callers/tests. Document surfaces use
* {@link createMarkdownPathImages}; these still build /sidebar/file URLs on the
* supplied base, so a desktop caller must not use them.
*/
function resolveMediaDest(
dest: string,
+6 -1
View File
@@ -89,9 +89,14 @@ function cachedLabels(labels: MarkdownCopyLabels): HostMarkdownLabels {
}
/** MarkdownText props carrying the nested chrome labels. */
export function markdownTextProps(text: string, labels: MarkdownCopyLabels): ComponentProps<typeof MarkdownText> {
export function markdownTextProps(
text: string,
labels: MarkdownCopyLabels,
pathImages?: ComponentProps<typeof MarkdownText>['pathImages'],
): ComponentProps<typeof MarkdownText> {
return {
text,
pathImages,
labels: cachedLabels(labels),
}
}
+29 -9
View File
@@ -10,9 +10,10 @@
* us, its `parseFileLink` accepts a fragment ONLY in the line grammar
* (`#L24` / `#L24-L30`); a heading fragment (`./other.md#标题`) makes the whole
* destination invalid, so the link would render as inert prose. That is why
* this module owns a SOURCE rewrite as well as a DOM pass — the same shape
* `markdown-images.ts` already has (images are rewritten into absolute
* `/sidebar/file` URLs because the renderer refuses relative ones):
* this module owns a SOURCE rewrite as well as a DOM pass. Markdown images
* take the vocabulary route instead (the owning surface's `pathImages`, see
* `markdown-images.ts`), which is why the source rewrite below skips a
* reference definition an image uses:
*
* - {@link rewriteLocalMarkdownLinks} (source, before rendering): a claimed
* link's non-line fragment is carried past the host parser as `%23` (an
@@ -362,8 +363,10 @@ function rewriteDestination(
* Code regions are masked first (see `maskCodeRegions` — fenced blocks opened
* by ``` ``` ``` OR `~~~`, and inline code spans), so documentation that
* demonstrates `[x](./a.md#标题)` is not mutated. Image destinations are left
* to `rewriteLocalImageUrls` (which must run FIRST: it rewrites the definitions
* an image uses into absolute media URLs, which this pass then ignores).
* to the renderer's local-image vocabulary (`pathImages`), so
* a reference definition an IMAGE uses is skipped here as well — neutering it
* would take the image away from that vocabulary. A definition used only by
* links is still pinned inert like any other unclaimed local destination.
* @param text - the markdown source about to be rendered.
* @param docPath - the rendered document's absolute path (relative-link base).
* @param cwd - the session workspace root, the base for prose surfaces.
@@ -376,6 +379,22 @@ export function rewriteLocalMarkdownLinks(
allLocalFiles = false,
): string {
const { masked, restore } = maskCodeRegions(text)
/** Reference labels image syntax resolves through, so those definitions are
* left for the renderer's `pathImages` vocabulary instead of being pinned
* inert. The label grammar image syntax uses: full `![alt][id]`,
* collapsed `![][id]` and the shortcut `![alt]` (which resolves to the
* label text itself). Code regions are already masked, so an example inside
* a fence is never harvested. */
const imageLabels = new Set<string>()
{
const labelRe = /!\[([^\]]*)\](?:\[((?:[^\][]|\[[^\]]*\])*)\])?/g
let match: RegExpExecArray | null
while ((match = labelRe.exec(masked)) !== null) {
const alt = match[1] ?? ''
const ref = match[2]
imageLabels.add((ref !== undefined && ref !== '' ? ref : alt).toLowerCase())
}
}
const links = masked
// Inline links. The negative lookbehind keeps IMAGE destinations out, and
@@ -396,12 +415,13 @@ export function rewriteLocalMarkdownLinks(
return `[${label}](${bracketed ? `<${rewritten}>` : rewritten}${title})`
},
)
// Reference definitions. Every local one is fair game: a definition an
// image uses was already turned into an absolute media URL by the image
// pass, and an absolute http(s) URL is never touched here.
// Reference definitions. An image-referenced definition stays verbatim so
// the renderer can resolve it through `pathImages`; every other local one
// is pinned inert like the inline links above (remote URLs untouched).
.replace(
/^(\s*\[([^\]]+)\]:\s*)(<[^>]+>|[^\s]+)/gm,
(_match, head: string, _label: string, destination: string) => {
(match, head: string, label: string, destination: string) => {
if (imageLabels.has(label.toLowerCase())) return match
// A `<…>` destination keeps its brackets: they are what lets the path
// carry a space, and dropping them would truncate the link.
const bracketed = destination.startsWith('<') && destination.endsWith('>')
+3
View File
@@ -10,6 +10,7 @@
*/
import type { MarkdownCopyLabels } from './markdown-labels.tsx'
import type { MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'
/** One fenced mermaid diagram lifted out of the markdown source. */
export interface MermaidBlock {
@@ -31,6 +32,8 @@ export interface MermaidMarkdownProps {
/** The full markdown source (rendered in a single MarkdownText pass). */
text: string
codeLabels: MarkdownCopyLabels
/** The owner's local-path image vocabulary for the same pass. */
pathImages?: MarkdownPathImages | undefined
}
/** CommonMark opening fence: 0-3 spaces indent + a run of 3+ backticks or tildes. */
+2 -2
View File
@@ -561,7 +561,7 @@ function isMermaidBlock(block: HTMLElement, bodies: ReadonlySet<string>): boolea
* Only mounted when the source contains at least one mermaid fence (see
* TextEditor.tsx).
*/
export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): React.ReactNode {
export function MermaidMarkdown({ text, codeLabels, pathImages }: MermaidMarkdownProps): React.ReactNode {
const containerRef = useRef<HTMLDivElement>(null)
const mountsRef = useRef(new Map<HTMLElement, MermaidMount>())
/** Visibility gate shared by every diagram of this document. */
@@ -677,7 +677,7 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea
return (
<div className={css.mermaidMarkdown} ref={containerRef}>
<MarkdownText {...markdownTextProps(text, codeLabels)} />
<MarkdownText {...markdownTextProps(text, codeLabels, pathImages)} />
</div>
)
}
+21 -9
View File
@@ -33,7 +33,6 @@ import {
import { splitMermaidBlocks, type MdBlock } from '../src/client/mermaid-blocks.ts'
import { maskCodeRegions } from '../src/client/markdown-code.ts'
import { rewriteLocalMarkdownLinks } from '../src/client/markdown-navigation.ts'
import { rewriteLocalImageUrls } from '../src/client/markdown-images.ts'
import type { SessionScope } from '../src/client/api.ts'
/** One document, both spellings — every case below compares the two. */
@@ -148,14 +147,27 @@ describe('the markdown pipeline reads CRLF and LF documents identically', () =>
expect(rewrittenCrlf).toContain('[demonstration](./demonstration.md#标题)')
})
it('rewriteLocalImageUrls + rewriteLocalMarkdownLinks: byte parity', () => {
const rewrite = (text: string): string =>
rewriteLocalMarkdownLinks(rewriteLocalImageUrls(text, SCOPE, DOC, ''), DOC, SCOPE.cwd)
expect(stripCr(rewrite(CRLF))).toEqual(rewrite(LF))
// The image pass ran in the CRLF spelling too (its destination became the
// session-scoped media URL).
expect(rewrite(CRLF)).toContain('pic.png')
expect(rewrite(CRLF)).not.toContain('](./pic.png)')
it('leaves image destinations (and image-referenced definitions) to the renderer, CRLF included', () => {
// Images are resolved by the owner's `pathImages` vocabulary at render
// time, so the source rewrite must hand them over verbatim — including the
// reference definition an image uses — while a definition only links use
// is still pinned inert.
const text = [
'![inline](./pic.png)',
'',
'![logo][logo]',
'',
'see [docs][d]',
'',
'[logo]: ./logo.png',
'',
'[d]: ./notes.txt',
].join('\n')
const rewrite = (source: string): string => rewriteLocalMarkdownLinks(source, DOC, SCOPE.cwd)
expect(stripCr(rewrite(text.replace(/\n/g, '\r\n')))).toEqual(rewrite(text))
expect(rewrite(text)).toContain('![inline](./pic.png)')
expect(rewrite(text)).toContain('[logo]: ./logo.png')
expect(rewrite(text)).toMatch(/\[d\]: \.\/notes\.txt\?/)
})
it('splitMermaidBlocks: a CRLF mermaid fence closes instead of swallowing the file', () => {
+63 -2
View File
@@ -13,6 +13,7 @@ import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { MarkdownDocument, type MarkdownHtmlMedia } from '../src/client/MarkdownHtml.tsx'
import { analyzeMarkdownHtml } from '../src/client/markdown-html.ts'
import { createMarkdownPathImages } from '../src/client/markdown-images.ts'
// The act() environment flag (React 18.2 reads it before flushing effects).
import { setupReactAct } from './test-utils.ts'
@@ -23,18 +24,38 @@ const media: MarkdownHtmlMedia = {
path: '/ws/docs/README.md',
baseUrl: 'http://gui.origin/proxy/3080/',
}
/** The desktop shell's page origin: the Host listens on a different site. */
const desktopMedia: MarkdownHtmlMedia = {
scope: { sessionId: 's1', cwd: '/ws' },
path: '/ws/docs/README.md',
baseUrl: 'dsh-app://app/',
}
const codeLabels = {
copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines',
}
async function renderDocument(text: string): Promise<{ container: HTMLElement; root: Root }> {
/**
* Render one document with the Markdown owner's `pathImages` vocabulary — the
* production wiring: local markdown images resolve through the page-base
* vocabulary, which is also the only branch that renders from the desktop
* shell's `dsh-app://` page (regression covered below).
*/
async function renderDocument(
text: string,
renderMedia: MarkdownHtmlMedia = media,
): Promise<{ container: HTMLElement; root: Root }> {
const container = document.createElement('div')
document.body.appendChild(container)
const root = createRoot(container)
const mediaWithImages: MarkdownHtmlMedia = {
...renderMedia,
pathImages: renderMedia.pathImages
?? createMarkdownPathImages(renderMedia.scope, renderMedia.path, renderMedia.baseUrl),
}
await act(async () => {
root.render(createElement(MarkdownDocument, {
info: analyzeMarkdownHtml(text),
media,
media: mediaWithImages,
codeLabels,
}))
// Let the MutationObserver's queued inline pass settle inside the act scope.
@@ -368,3 +389,43 @@ describe('MarkdownDocument (local markdown images)', () => {
await unmount(root)
})
})
describe('MarkdownDocument (desktop shell page origin)', () => {
// Regression: the desktop shell serves the GUI from `dsh-app://app/` and the
// Host listens on another origin (`__DSH_TRANSPORT__.streamBaseUrl`). A
// transport-origin http media URL is therefore a CROSS-SITE subresource, the
// Host's Connection fence rejects it (403) and MarkdownText falls back to the
// image's alt text — exactly the bug this suite pins. Markdown syntax is
// limited to the renderer's local-file vocabulary (`dsh-app://app/api/file`),
// whose request the shell forwards to the Host with the launch cookie.
it('renders markdown-syntax local images from the dsh-app page origin', async () => {
const { container, root } = await renderDocument([
'![icon](./assets/icon.svg)',
'',
'![logo][logo]',
'',
'[logo]: ./logo.png',
].join('\n'), desktopMedia)
const imgs = [...container.querySelectorAll('img')]
expect(imgs.length, 'both local images must render as <img>, not alt fallback').toBe(2)
// The host appends its own freshness counter to /api/file URLs; the path is
// the contract, the counter is render-time bookkeeping.
for (const [img, expected] of [
[imgs[0], 'dsh-app://app/api/file?path=%2Fws%2Fdocs%2Fassets%2Ficon.svg'],
[imgs[1], 'dsh-app://app/api/file?path=%2Fws%2Fdocs%2Flogo.png'],
] as const) {
expect(img?.getAttribute('src')).toMatch(new RegExp(`^${expected.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}&load=\\d+$`))
}
await unmount(root)
})
it('renders raw-HTML local images from the dsh-app page origin', async () => {
const { container, root } = await renderDocument(
'<picture><img src="./shot.png" alt="shot"/></picture>',
desktopMedia,
)
const img = container.querySelector('img')
expect(img?.getAttribute('src')).toBe('dsh-app://app/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
await unmount(root)
})
})
+159 -95
View File
@@ -1,131 +1,195 @@
/**
* Markdown-image vocabulary spec: the local destination → absolute target
* resolution, the page-base media URL (browser AND desktop shell), and the
* `pathImages` capability the preview surfaces hand the host renderer. The
* desktop-shell case is the regression: an absolute http URL on the transport
* origin is cross-site and the Connection fence answers 403, so only a
* page-base `dsh-app://app/api/file` URL renders there (see markdown-images.ts).
*/
import { describe, expect, it } from 'vitest'
import { rewriteLocalImageUrls, rewriteProseLocalImageUrls } from '../src/client/markdown-images.ts'
import {
createMarkdownPathImages,
desktopFileUrl,
markdownImageTarget,
markdownMediaUrl,
resolveLocalMediaDest,
rewriteLocalImageUrls,
rewriteProseLocalImageUrls,
} from '../src/client/markdown-images.ts'
import { rewriteLocalMarkdownLinks } from '../src/client/markdown-navigation.ts'
import type { SessionScope } from '../src/client/api.ts'
const ORIGIN = 'http://127.0.0.1:3080'
/** The desktop shell's page origin; the Host itself listens elsewhere. */
const APP = 'dsh-app://app/'
const scope: SessionScope = { sessionId: 'abc', cwd: '/repo' }
describe('rewriteLocalImageUrls', () => {
describe('markdownImageTarget', () => {
it('resolves relative destinations against the opened file directory', () => {
const md = '![a](./img.png)\n![b](images/b.jpg)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimg.png&cwd=%2Frepo)`)
expect(out).toContain(`![b](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimages%2Fb.jpg&cwd=%2Frepo)`)
expect(markdownImageTarget('./img.png', '/repo/docs/readme.md')).toBe('/repo/docs/img.png')
expect(markdownImageTarget('images/b.jpg', '/repo/docs/readme.md')).toBe('/repo/docs/images/b.jpg')
})
it('expects the rewritten destination to be an absolute http URL MarkdownText accepts', () => {
const out = rewriteLocalImageUrls('![a](./img.png)', scope, '/repo/readme.md', ORIGIN)
const url = out.match(/\]\((http[^)]+)\)/)?.[1]
expect(url).toBeDefined()
expect(new URL(url as string).protocol).toBe('http:')
it('normalizes `.`/`..` segments', () => {
expect(markdownImageTarget('./img.png', '/repo/docs/sub/readme.md')).toBe('/repo/docs/sub/img.png')
expect(markdownImageTarget('../assets/b.png', '/repo/docs/sub/readme.md')).toBe('/repo/docs/assets/b.png')
})
it('passes absolute local paths through unchanged', () => {
const md = '![a](/repo/assets/b.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fassets%2Fb.png&cwd=%2Frepo)`)
it('passes absolute local paths through', () => {
expect(markdownImageTarget('/repo/assets/b.png', '/repo/docs/readme.md')).toBe('/repo/assets/b.png')
expect(markdownImageTarget('~/pics/a.png', '/repo/docs/readme.md')).toBe('~/pics/a.png')
})
it('keeps remote http(s)/data/mailto destinations untouched', () => {
const md = '![a](https://example.com/x.jpg)\n![b](http://e.com/y.png)\n![c](data:image/png;base64,AAA)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('![a](https://example.com/x.jpg)')
expect(out).toContain('![b](http://e.com/y.png)')
expect(out).toContain('![c](data:image/png;base64,AAA)')
it('handles windows absolute and UNC paths as local', () => {
expect(markdownImageTarget('C:\\repo\\img.png', 'C:\\repo\\docs\\readme.md')).toBe('C:\\repo\\img.png')
expect(markdownImageTarget('//server/share/a.png', '/repo/docs/readme.md')).toBeUndefined()
})
it('leaves in-page anchors untouched', () => {
const md = '![a](#section)\n\n[link](#top)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('![a](#section)')
it('refuses everything the host renderer would not pass to the delegate', () => {
expect(markdownImageTarget('', '/repo/readme.md')).toBeUndefined()
expect(markdownImageTarget('#section', '/repo/readme.md')).toBeUndefined()
expect(markdownImageTarget('https://example.com/x.png', '/repo/readme.md')).toBeUndefined()
expect(markdownImageTarget('data:image/png;base64,AAA', '/repo/readme.md')).toBeUndefined()
expect(markdownImageTarget('./img.png?v=1', '/repo/readme.md')).toBeUndefined()
})
})
describe('markdownMediaUrl', () => {
it('builds a same-origin media URL on the page base (browser)', () => {
expect(markdownMediaUrl('/repo/docs/img.png', scope, ORIGIN)).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimg.png&cwd=%2Frepo',
)
})
it('rewrites reference-style image definitions', () => {
const md = '![logo][logo]\n\n[logo]: ./logo.svg'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain(`[logo]: ${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Flogo.svg&cwd=%2Frepo`)
// The inline reference itself is left for MarkdownText to combine.
expect(out).toContain('![logo][logo]')
it('keeps a reverse-proxy directory prefix', () => {
expect(markdownMediaUrl('/repo/img.png', scope, 'https://host.example.test/proxy/3080/')).toBe(
'https://host.example.test/proxy/3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fimg.png&cwd=%2Frepo',
)
})
it('normalizes `.`/`..` segments in relative destinations', () => {
const md = '![a](./img.png)\n![b](../assets/b.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/sub/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fsub%2Fimg.png&cwd=%2Frepo)`)
expect(out).toContain(`![b](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fassets%2Fb.png&cwd=%2Frepo)`)
expect(out).not.toContain('/.')
it('stays on the desktop shell page origin instead of the transport origin', () => {
// Regression: resolving against `__DSH_TRANSPORT__.streamBaseUrl`
// (`http://127.0.0.1:<port>`) produced a cross-site request from this page
// and the Connection fence answered 403, so every local image fell back to
// its alt text.
expect(markdownMediaUrl('/repo/docs/img.png', scope, APP)).toBe(
'dsh-app://app/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimg.png&cwd=%2Frepo',
)
})
it('drops the cwd param when the scope has no cwd', () => {
const out = rewriteLocalImageUrls('![a](./img.png)', { sessionId: 'abc' }, '/repo/readme.md', ORIGIN)
expect(out).toContain(`sessionId=abc&path=%2Frepo%2Fimg.png`)
expect(out).not.toContain('cwd=')
const url = markdownMediaUrl('/repo/img.png', { sessionId: 'abc' }, ORIGIN)
expect(url).toBe('http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fimg.png')
expect(url).not.toContain('cwd=')
})
})
describe('desktopFileUrl', () => {
it('builds the host file URL on the dsh-app page origin', () => {
expect(desktopFileUrl('/repo/a.png', APP)).toBe('dsh-app://app/api/file?path=%2Frepo%2Fa.png')
})
it('handles windows absolute paths as local (not remote)', () => {
const md = '![a](C:\\repo\\img.png)'
const out = rewriteLocalImageUrls(md, scope, 'C:\\repo\\docs\\readme.md', ORIGIN)
// A Windows drive path is absolute (not a remote scheme) → rewritten.
const url = out.match(/\]\(([^)]+)\)/)?.[1] as string
expect(url).toContain('/sidebar/file?')
expect(decodeURIComponent(url)).toContain('C:\\repo\\img.png')
it('keeps a reverse-proxy prefix under an http(s) page base', () => {
expect(desktopFileUrl('/repo/a.png', 'https://host.example.test/proxy/3080/')).toBe(
'https://host.example.test/proxy/3080/api/file?path=%2Frepo%2Fa.png',
)
})
})
describe('createMarkdownPathImages', () => {
it('maps local destinations to the plugin media route on the browser page base', () => {
const images = createMarkdownPathImages(scope, '/repo/docs/readme.md', ORIGIN)
expect(images.resolve('./img.png')).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimg.png&cwd=%2Frepo',
)
expect(images.resolve('../x.png')).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fx.png&cwd=%2Frepo',
)
})
it('does not rewrite image-looking text inside fenced code blocks', () => {
const md = '```\n![alt](./img.png)\n```\n![real](./real.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
// The fenced example must be preserved verbatim; only the real image is rewritten.
expect(out).toContain('```\n![alt](./img.png)\n```')
expect(out).toContain('/sidebar/file?')
it('maps local destinations to the authenticated host file route on the desktop page base', () => {
// The renderer's image vocabulary accepts exactly one local-file shape from
// the dsh-app:// page (`dsh-app://app/api/file?...`); the shell forwards it
// to the Host with the launch cookie.
const images = createMarkdownPathImages(scope, '/repo/docs/readme.md', APP)
expect(images.resolve('./img.png')).toBe(
'dsh-app://app/api/file?path=%2Frepo%2Fdocs%2Fimg.png',
)
expect(images.resolve('./img.png')).not.toContain('/sidebar/file')
})
it('does not rewrite image-looking text inside inline code spans', () => {
const md = 'Use `![alt](./img.png)` syntax.\n![real](./real.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('`![alt](./img.png)`')
expect(out).toContain('/sidebar/file?')
it('makes a relative tab path absolute for the desktop host file route', () => {
// An editor tab opened from a chat address can carry a workspace-RELATIVE
// path (`openwrt-proxy-primer/PRINCIPLES.md`). The plugin media route
// resolves that together with `cwd`, but the host `api/file` route answers
// 400 "absolute path required" — so the desktop branch joins the session
// workspace root first.
const images = createMarkdownPathImages(scope, 'docs/readme.md', APP)
expect(images.resolve('./img.png')).toBe(
'dsh-app://app/api/file?path=%2Frepo%2Fdocs%2Fimg.png',
)
expect(images.resolve('images/b.png')).toBe(
'dsh-app://app/api/file?path=%2Frepo%2Fdocs%2Fimages%2Fb.png',
)
})
it('leaves every code-region form alone, tilde fences included', () => {
// The image pass had the SAME `~~~` blind spot as the link pass, and it
// predates this feature: on the 58d7f71 baseline
// `rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~')` already produced a
// `/sidebar/file` URL. Both passes now share one fence mask
// (`markdown-code.ts`).
const forms = [
'```\n![i](./p.png)\n```',
'````\n```\n![i](./p.png)\n```\n````',
'~~~\n![i](./p.png)\n~~~',
'~~~\nuse `![i](./p.png)` here\n~~~',
]
for (const form of forms) {
const out = rewriteLocalImageUrls(form, scope, '/repo/readme.md', ORIGIN)
expect(out, form).toBe(form)
expect(out, form).not.toContain('/sidebar/file')
}
// A longer closing fence closes, and a real image after it is rewritten.
const after = rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~~\n\n![real](./real.png)', scope, '/repo/readme.md', ORIGIN)
expect(after).toContain('~~~\n![i](./p.png)\n~~~~')
expect(after).toMatch(/\[real\]\(.*\/sidebar\/file/)
// An unclosed fence runs to the end of the document.
expect(rewriteLocalImageUrls('~~~\n![i](./p.png)', scope, '/repo/readme.md', ORIGIN))
.toBe('~~~\n![i](./p.png)')
// A reference definition inside the fence is not harvested either.
const ref = rewriteLocalImageUrls('~~~\n![i][r]\n\n[r]: ./p.png\n~~~', scope, '/repo/readme.md', ORIGIN)
expect(ref).toBe('~~~\n![i][r]\n\n[r]: ./p.png\n~~~')
it('falls back without a workspace root when the tab path is relative (desktop)', () => {
const images = createMarkdownPathImages({ sessionId: 'abc' }, 'docs/readme.md', APP)
expect(images.resolve('./img.png')).toBeUndefined()
})
it('does not rewrite a reference definition used only by a plain link', () => {
// The `[manual][docs]` link references `[docs]: ./docs.md`, but that
// definition must NOT be redirected to /sidebar/file because it is not
// referenced by any image. Only image-referenced definitions are rewritten.
const md = '[manual][docs]\n\n![pic][pic-def]\n\n[docs]: ./docs.md\n[pic-def]: ./pic.png'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('[docs]: ./docs.md')
expect(out).not.toMatch(/\[docs\]:.*\/sidebar\/file/)
// The image-referenced definition IS rewritten.
expect(out).toMatch(/\[pic-def\]:.*\/sidebar\/file/)
it('keeps the relative spelling with a cwd on the browser page base', () => {
// The plugin media route resolves a relative target against `cwd`, so the
// browser branch does not have to normalize it (the desktop host route
// does — see the case above).
const images = createMarkdownPathImages(scope, 'docs/readme.md', ORIGIN)
expect(images.resolve('./img.png')).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=docs%2Fimg.png&cwd=%2Frepo',
)
})
it('decodes one authored percent-escape before resolving', () => {
const images = createMarkdownPathImages(scope, '/repo/docs/readme.md', ORIGIN)
expect(images.resolve('./my%20image.png')).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fmy+image.png&cwd=%2Frepo',
)
expect(images.resolve('./bad%E0%A4%A.png')).toBeUndefined()
})
it('answers undefined for destinations it cannot serve (alt-text fallback)', () => {
const images = createMarkdownPathImages(scope, '/repo/docs/readme.md', ORIGIN)
expect(images.resolve('https://example.com/x.png')).toBeUndefined()
expect(images.resolve('')).toBeUndefined()
expect(images.resolve('#anchor')).toBeUndefined()
})
})
describe('resolveLocalMediaDest (raw HTML leaves)', () => {
it('rewrites local sources on the page base', () => {
expect(resolveLocalMediaDest('./shot.png', scope, '/repo/docs/readme.md', ORIGIN)).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fshot.png&cwd=%2Frepo',
)
})
it('rewrites local sources on the desktop shell page origin', () => {
// Raw HTML <img> is plain DOM, so the same-origin plugin media route works
// (the markdown-syntax vocabulary above needs the host file route instead).
expect(resolveLocalMediaDest('./shot.png', scope, '/repo/docs/readme.md', APP)).toBe(
'dsh-app://app/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fshot.png&cwd=%2Frepo',
)
})
it('decodes one percent-escape from the authored src', () => {
expect(resolveLocalMediaDest('./my%20shot.png', scope, '/repo/docs/readme.md', ORIGIN)).toBe(
'http://127.0.0.1:3080/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fmy+shot.png&cwd=%2Frepo',
)
})
it('leaves remote, anchor and empty sources untouched', () => {
expect(resolveLocalMediaDest('https://example.com/x.png', scope, '/repo/readme.md', ORIGIN))
.toBe('https://example.com/x.png')
expect(resolveLocalMediaDest('#anchor', scope, '/repo/readme.md', ORIGIN)).toBe('#anchor')
expect(resolveLocalMediaDest('', scope, '/repo/readme.md', ORIGIN)).toBe('')
})
})
+24 -3
View File
@@ -253,7 +253,7 @@ describe('rewriteLocalMarkdownLinks', () => {
expect(rewriteLocalMarkdownLinks('[x](./a.md?raw=1)', DOC, CWD)).toBe('[x](./a.md?raw=1)')
})
it('leaves images to the image pass and code spans alone', () => {
it('leaves images to the renderer vocabulary and code spans alone', () => {
expect(rewriteLocalMarkdownLinks('![alt](./pic.png)', DOC, CWD)).toBe('![alt](./pic.png)')
expect(rewriteLocalMarkdownLinks('`[x](./other.md#标题)`', DOC, CWD)).toBe('`[x](./other.md#标题)`')
expect(rewriteLocalMarkdownLinks('```\n[x](./other.md#标题)\n```', DOC, CWD)).toBe('```\n[x](./other.md#标题)\n```')
@@ -333,12 +333,33 @@ describe('rewriteLocalMarkdownLinks', () => {
expect(rewriteLocalMarkdownLinks('[id]: ./other.md#标题', DOC, CWD)).toBe('[id]: ./other.md%23标题')
expect(rewriteLocalMarkdownLinks('[id]: <./a b.md#标题>', DOC, CWD)).toBe('[id]: <./a b.md%23标题>')
expect(rewriteLocalMarkdownLinks('[id]: ./notes.txt', DOC, CWD)).toBe('[id]: ./notes.txt?')
// An image-used definition was already turned into a media URL by the
// image pass (which runs first) — never touched here.
expect(rewriteLocalMarkdownLinks('[id]: http://gui/sidebar/file?path=%2Fx.png', DOC, CWD))
.toBe('[id]: http://gui/sidebar/file?path=%2Fx.png')
})
it('leaves image-referenced definitions for the renderer vocabulary', () => {
// The host renderer resolves a reference-style image through the owner's
// `pathImages` vocabulary; pinning the definition inert with a `?` would
// take that image away (it would render alt text).
const full = '![logo][logo]\n\n[logo]: ./logo.png'
expect(rewriteLocalMarkdownLinks(full, DOC, CWD)).toBe(full)
const collapsed = '![][id]\n\n[id]: ./pic.png'
expect(rewriteLocalMarkdownLinks(collapsed, DOC, CWD)).toBe(collapsed)
const shortcut = '![icon]\n\n[icon]: ./icon.svg'
expect(rewriteLocalMarkdownLinks(shortcut, DOC, CWD)).toBe(shortcut)
// Case-insensitive label matching, like CommonMark reference identifiers.
expect(rewriteLocalMarkdownLinks('![Logo][LOGO]\n\n[logo]: ./logo.png', DOC, CWD))
.toBe('![Logo][LOGO]\n\n[logo]: ./logo.png')
// A definition used only by a PLAIN LINK is still pinned inert (a non-md
// destination: a claimed `.md` one is left alone by the link pass).
expect(rewriteLocalMarkdownLinks('[docs][d]\n\n[d]: ./notes.txt', DOC, CWD))
.toBe('[docs][d]\n\n[d]: ./notes.txt?')
// The same definition used by BOTH an image and a plain link stays
// resolvable for the image; the link simply follows the same destination.
const both = '![pic][shared]\n\n[read][shared]\n\n[shared]: ./x.png'
expect(rewriteLocalMarkdownLinks(both, DOC, CWD)).toBe(both)
})
it('is idempotent: a second pass over its own output changes nothing', () => {
const once = rewriteLocalMarkdownLinks('[a](./other.md#标题) [b](./notes.txt) [c](#x) [d](./other.md#L3)', DOC, CWD)
expect(rewriteLocalMarkdownLinks(once, DOC, CWD)).toBe(once)