Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: 正确渲染 Markdown 图片与 Obsidian 嵌入语法

shisonghongba745c6aa471
diff --git a/src/components/editor/file-preview.tsx b/src/components/editor/file-preview.tsx
index 4b7778f4..02939eb9 100644
--- a/src/components/editor/file-preview.tsx
+++ b/src/components/editor/file-preview.tsx
@@ -20,8 +20,9 @@ import {
isExtractedTextPreviewFile,
} from "@/lib/file-types"
import type { FileCategory } from "@/lib/file-types"
-import { getFileName } from "@/lib/path-utils"
+import { getFileName, normalizePath } from "@/lib/path-utils"
import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"
+import { transformImageEmbeds } from "@/lib/wikilink-transform"
import { detectLanguage } from "@/lib/detect-language"
import { getHtmlLang, getTextDirection } from "@/lib/language-metadata"
import { parseFrontmatter } from "@/lib/frontmatter"
@@ -153,6 +154,18 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
const scrollRootRef = useRef<HTMLDivElement | null>(null)
const { frontmatter, body } = useMemo(() => parseFrontmatter(content), [content])
+ // Rewrite Obsidian image embeds (`![[…]]`) into standard markdown
+ // so raw-source previews (e.g. skill-exported docs) actually show
+ // their images instead of dumping the embed syntax as text.
+ const renderBody = useMemo(() => transformImageEmbeds(body), [body])
+ // Directory of this file (project-absolute) so relative image
+ // references (`../assets/x.png`) resolve against the file's own
+ // location, Obsidian-style.
+ const currentFileDir = useMemo(() => {
+ const norm = normalizePath(filePath)
+ const dir = norm.slice(0, norm.lastIndexOf("/"))
+ return dir || null
+ }, [filePath])
const renderLanguage = useMemo(() => detectLanguage(body), [body])
const direction = getTextDirection(renderLanguage)
const htmlLang = getHtmlLang(renderLanguage)
@@ -240,7 +253,7 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
// URL (which differs per platform).
img: ({ src, alt, ...props }) => (
<img
- src={typeof src === "string" ? resolveMarkdownImageSrc(src, projectPath) : undefined}
+ src={typeof src === "string" ? resolveMarkdownImageSrc(src, projectPath, currentFileDir) : undefined}
data-mdsrc={typeof src === "string" ? src : undefined}
alt={alt ?? ""}
className="max-w-full rounded border border-border/40 transition-all"
@@ -275,7 +288,7 @@ function TextPreview({ filePath, content, label }: { filePath: string; content:
},
}}
>
- {body}
+ {renderBody}
</ReactMarkdown>
</div>
</div>
diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsx
index a083bae3..d05c40b5 100644
--- a/src/components/editor/wiki-editor.tsx
+++ b/src/components/editor/wiki-editor.tsx
@@ -59,6 +59,9 @@ function WikiEditorInner({ content, onSave, onMarkdownChange }: WikiEditorInnerP
interface WikiEditorProps {
content: string
onSave: (markdown: string, options?: { immediate?: boolean }) => void
+ /** Absolute path of the file, threaded to WikiReader so relative
+ * image references resolve against the file's own directory. */
+ filePath?: string
}
function wrapBareMathBlocks(text: string): string {
@@ -68,7 +71,7 @@ function wrapBareMathBlocks(text: string): string {
)
}
-export function WikiEditor({ content, onSave }: WikiEditorProps) {
+export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {
// Default to read mode (ReactMarkdown render). Edit mode swaps
// in Milkdown WYSIWYG. We default to read because:
// 1. Milkdown's commonmark/gfm preset has no wikilink schema,
@@ -137,7 +140,7 @@ export function WikiEditor({ content, onSave }: WikiEditorProps) {
{mode === "read" ? (
<div className="px-6 py-6">
{frontmatter && <FrontmatterPanel data={frontmatter} />}
- <WikiReader body={body} />
+ <WikiReader body={body} filePath={filePath} />
</div>
) : (
<MilkdownProvider>
diff --git a/src/components/editor/wiki-reader.tsx b/src/components/editor/wiki-reader.tsx
index f4ea67ef..3bc04610 100644
--- a/src/components/editor/wiki-reader.tsx
+++ b/src/components/editor/wiki-reader.tsx
@@ -4,7 +4,7 @@ import remarkGfm from "remark-gfm"
import remarkMath from "remark-math"
import rehypeKatex from "rehype-katex"
import "katex/dist/katex.min.css"
-import { transformWikilinks } from "@/lib/wikilink-transform"
+import { transformImageEmbeds, transformWikilinks } from "@/lib/wikilink-transform"
import { resolveRelatedSlug } from "@/lib/wiki-page-resolver"
import { resolveMarkdownImageSrc } from "@/lib/markdown-image-resolver"
import { normalizePath } from "@/lib/path-utils"
@@ -15,6 +15,14 @@ import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"
interface WikiReaderProps {
body: string
+ /**
+ * Absolute path of the markdown file being rendered. Used to
+ * resolve relative image references against the file's own
+ * directory (Obsidian-style), so e.g. `../assets/x.png` works.
+ * Optional — when omitted, image paths fall back to wiki-root
+ * resolution.
+ */
+ filePath?: string
}
/**
@@ -29,17 +37,31 @@ interface WikiReaderProps {
* against the project's wiki tree and routed to setSelectedFile,
* giving the user single-click navigation between pages.
*/
-export function WikiReader({ body }: WikiReaderProps) {
+export function WikiReader({ body, filePath }: WikiReaderProps) {
const project = useWikiStore((s) => s.project)
const fileTree = useWikiStore((s) => s.fileTree)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
- const transformed = useMemo(() => transformWikilinks(body), [body])
+ // Image embeds (`![[…]]`) must be rewritten BEFORE the generic
+ // wikilink pass, otherwise the embed target gets mangled into a
+ // `#fragment` link.
+ const transformed = useMemo(
+ () => transformWikilinks(transformImageEmbeds(body)),
+ [body],
+ )
const renderLanguage = detectLanguage(body)
const direction = getTextDirection(renderLanguage)
const htmlLang = getHtmlLang(renderLanguage)
const projectPath = project ? normalizePath(project.path) : null
const wikiRoot = projectPath ? `${projectPath}/wiki` : null
+ // Directory of the file being rendered (project-absolute), so
+ // relative image srcs resolve against it like Obsidian does.
+ const currentFileDir = useMemo(() => {
+ if (!filePath) return null
+ const norm = normalizePath(filePath)
+ const dir = norm.slice(0, norm.lastIndexOf("/"))
+ return dir || null
+ }, [filePath])
function handleAnchorClick(e: React.MouseEvent<HTMLAnchorElement>, href: string) {
if (!href.startsWith("#")) return
@@ -113,7 +135,7 @@ export function WikiReader({ body }: WikiReaderProps) {
<img
src={
typeof src === "string"
- ? resolveMarkdownImageSrc(src, projectPath)
+ ? resolveMarkdownImageSrc(src, projectPath, currentFileDir)
: undefined
}
data-mdsrc={typeof src === "string" ? src : undefined}
diff --git a/src/components/layout/preview-panel.tsx b/src/components/layout/preview-panel.tsx
index 1dd88581..68f4e1df 100644
--- a/src/components/layout/preview-panel.tsx
+++ b/src/components/layout/preview-panel.tsx
@@ -125,6 +125,7 @@ export function PreviewPanel() {
key={selectedFile}
content={fileContent}
onSave={handleSave}
+ filePath={selectedFile}
/>
) : (
<FilePreview
diff --git a/src/lib/markdown-image-resolver.test.ts b/src/lib/markdown-image-resolver.test.ts
index 5fb09d40..0bd2ba51 100644
--- a/src/lib/markdown-image-resolver.test.ts
+++ b/src/lib/markdown-image-resolver.test.ts
@@ -105,4 +105,154 @@ describe("resolveMarkdownImageSrc", () => {
it("returns empty string verbatim for empty src", () => {
expect(resolveMarkdownImageSrc("", PROJECT)).toBe("")
})
+
+ describe("file-relative resolution (currentFileDir)", () => {
+ it("resolves ../assets against the file's own directory (Obsidian-style)", () => {
+ // A skill-exported raw source lives in raw/sources and refers
+ // to ../assets/<md5>.png — must land on raw/assets, NOT
+ // wiki/../assets.
+ expect(
+ resolveMarkdownImageSrc(
+ "../assets/abc123.png",
+ PROJECT,
+ `${PROJECT}/raw/sources`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/raw/assets/abc123.png")
+ })
+
+ it("resolves ../assets/boards (whiteboard screenshots) correctly", () => {
+ expect(
+ resolveMarkdownImageSrc(
+ "../assets/boards/WB1.jpg",
+ PROJECT,
+ `${PROJECT}/raw/sources`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/raw/assets/boards/WB1.jpg")
+ })
+
+ it("resolves a same-directory relative path against the file dir", () => {
+ expect(
+ resolveMarkdownImageSrc(
+ "diagram.png",
+ PROJECT,
+ `${PROJECT}/wiki/concepts`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/concepts/diagram.png")
+ })
+
+ it("strips a leading ./ before joining to the file dir", () => {
+ expect(
+ resolveMarkdownImageSrc(
+ "./img.png",
+ PROJECT,
+ `${PROJECT}/raw/sources`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/raw/sources/img.png")
+ })
+
+ it("accepts a project-relative currentFileDir and anchors it under the project", () => {
+ expect(
+ resolveMarkdownImageSrc("../assets/x.png", PROJECT, "raw/sources"),
+ ).toBe("tauri-asset:/Users/me/MyWiki/raw/assets/x.png")
+ })
+
+ it("normalizes backslashes in currentFileDir", () => {
+ expect(
+ resolveMarkdownImageSrc(
+ "../assets/x.png",
+ "C:\\Users\\me\\MyWiki",
+ "C:\\Users\\me\\MyWiki\\raw\\sources",
+ ),
+ ).toBe("tauri-asset:C:/Users/me/MyWiki/raw/assets/x.png")
+ })
+
+ it("collapses `..` segments against the file dir", () => {
+ // From /Users/me/MyWiki/raw/sources, four `..` pop
+ // sources, raw, MyWiki, me — landing in /Users.
+ expect(
+ resolveMarkdownImageSrc("../../../../etc/x.png", PROJECT, `${PROJECT}/raw/sources`),
+ ).toBe("tauri-asset:/Users/etc/x.png")
+ })
+
+ it("clamps `..` at the filesystem root rather than producing ../ garbage", () => {
+ // More `..` than there are segments → clamped at root.
+ expect(
+ resolveMarkdownImageSrc("../../x.png", PROJECT, "/a"),
+ ).toBe("tauri-asset:/x.png")
+ })
+
+ it("still uses wiki-root fallback when no currentFileDir is given", () => {
+ // The canonical generated-wiki case is unchanged.
+ expect(resolveMarkdownImageSrc("media/slug/img-1.png", PROJECT)).toBe(
+ "tauri-asset:/Users/me/MyWiki/wiki/media/slug/img-1.png",
+ )
+ })
+
+ it("keeps `media/` refs wiki-root-relative even WITH a currentFileDir set", () => {
+ // Regression: a generated `wiki/sources/<slug>.md` page embeds
+ // ingest images as `media/<slug>/img.jpg` — wiki-ROOT-relative,
+ // NOT relative to wiki/sources. Passing currentFileDir must not
+ // re-anchor it to wiki/sources/media/… (one level too deep,
+ // which 404s and shows the alt text instead of the image).
+ expect(
+ resolveMarkdownImageSrc(
+ "media/易配置平台2.0培训-1/001-abc.jpg",
+ PROJECT,
+ `${PROJECT}/wiki/sources`,
+ ),
+ ).toBe(
+ "tauri-asset:/Users/me/MyWiki/wiki/media/易配置平台2.0培训-1/001-abc.jpg",
+ )
+ })
+
+ it("decodes percent-encoded CJK paths so the disk path is literal UTF-8", () => {
+ // Regression: ReactMarkdown/remark percent-encodes non-ASCII
+ // image URLs. The src arrives already-encoded; if we don't
+ // decode it, convertFileSrc double-encodes (%E6 → %25E6) and
+ // the asset server 404s. Decode must restore the real filename.
+ const encoded =
+ "media/%E6%98%93%E9%85%8D%E7%BD%AE%E5%B9%B3%E5%8F%B02.0%E5%9F%B9%E8%AE%AD-1/001-GTuhw460rheJYBb4dnccLxYDngd.jpg"
+ expect(
+ resolveMarkdownImageSrc(encoded, PROJECT, `${PROJECT}/wiki/sources`),
+ ).toBe(
+ "tauri-asset:/Users/me/MyWiki/wiki/media/易配置平台2.0培训-1/001-GTuhw460rheJYBb4dnccLxYDngd.jpg",
+ )
+ })
+
+ it("decodes percent-encoded file-relative CJK paths too", () => {
+ // Same fix must apply on the file-relative branch (raw/sources
+ // with a CJK asset name, e.g. an exported Feishu image).
+ expect(
+ resolveMarkdownImageSrc(
+ "../assets/%E5%9B%BE%E7%89%87.png",
+ PROJECT,
+ `${PROJECT}/raw/sources`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/raw/assets/图片.png")
+ })
+
+ it("keeps a malformed percent sequence as-is rather than throwing", () => {
+ // A bare `%` that isn't a valid escape must not crash the
+ // renderer — fall back to the raw value.
+ expect(
+ resolveMarkdownImageSrc("media/100%-done.png", PROJECT),
+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/media/100%-done.png")
+ })
+
+ it("honors `./media/` (leading ./) as a wiki-root ref too, with a file dir", () => {
+ expect(
+ resolveMarkdownImageSrc(
+ "./media/slug/img-2.png",
+ PROJECT,
+ `${PROJECT}/wiki/concepts`,
+ ),
+ ).toBe("tauri-asset:/Users/me/MyWiki/wiki/media/slug/img-2.png")
+ })
+
+ it("passes absolute srcs through convertFileSrc even with a file dir set", () => {
+ expect(
+ resolveMarkdownImageSrc("/var/data/x.png", PROJECT, `${PROJECT}/raw/sources`),
+ ).toBe("tauri-asset:/var/data/x.png")
+ })
+ })
})
diff --git a/src/lib/markdown-image-resolver.ts b/src/lib/markdown-image-resolver.ts
index 3e0429cf..9bcad7b6 100644
--- a/src/lib/markdown-image-resolver.ts
+++ b/src/lib/markdown-image-resolver.ts
@@ -17,9 +17,18 @@
* - Any src starting with `/` (absolute) is wrapped with
* `convertFileSrc` directly — the path is the filesystem
* absolute path.
- * - **Anything else is treated as relative to the project's
- * `wiki/` root.** Generated content uses this form
- * (`media/foo/img-1.png`); user-written content can use it too.
+ * - **A relative src is resolved against the rendering markdown
+ * file's own directory** when that directory is known
+ * (`currentFileDir`). This is how Obsidian — and every other
+ * markdown tool — resolves images, and it's what lets
+ * skill-exported sources work: a `raw/sources/foo.md` that
+ * references `../assets/img.png` correctly lands on
+ * `raw/assets/img.png`.
+ * - When the file's directory is NOT known, a relative src is
+ * treated as relative to the project's `wiki/` root. Generated
+ * wiki content uses this form (`media/foo/img-1.png`) and the
+ * fallback keeps it working for callers that can't supply a
+ * file context (e.g. chat replies).
*
* The resolver returns a string that React's <img src=...> can load:
* the appropriate `convertFileSrc(...)` URL or the original src
@@ -30,14 +39,43 @@ import { normalizePath } from "@/lib/path-utils"
const PASSTHROUGH_RE = /^(https?:|data:|blob:|file:|tauri:)/i
+/**
+ * Collapse `.` and `..` segments in a forward-slashed path without
+ * touching the filesystem. A leading `..` that would escape the
+ * root is dropped (clamped at root) rather than throwing — image
+ * references should degrade gracefully, not crash the renderer.
+ */
+function collapsePath(p: string): string {
+ const isAbsolute = p.startsWith("/")
+ const out: string[] = []
+ for (const seg of p.split("/")) {
+ if (seg === "" || seg === ".") continue
+ if (seg === "..") {
+ if (out.length > 0 && out[out.length - 1] !== "..") out.pop()
+ else if (!isAbsolute) out.push("..")
+ // absolute path: `..` above root is simply ignored
+ } else {
+ out.push(seg)
+ }
+ }
+ return (isAbsolute ? "/" : "") + out.join("/")
+}
+
/**
* `projectPath` is the wiki project's root directory. When null
* (no project loaded), the resolver passes srcs through unchanged
* so it remains safe to call before a project is open.
+ *
+ * `currentFileDir` is the directory of the markdown file being
+ * rendered (absolute, or relative-to-project). When provided,
+ * relative image srcs resolve against it — matching how Obsidian
+ * and other markdown tools behave. When omitted, relative srcs
+ * fall back to being resolved against `<project>/wiki/`.
*/
export function resolveMarkdownImageSrc(
rawSrc: string,
projectPath: string | null,
+ currentFileDir?: string | null,
): string {
if (!rawSrc) return rawSrc
if (PASSTHROUGH_RE.test(rawSrc)) return rawSrc
@@ -54,12 +92,59 @@ export function resolveMarkdownImageSrc(
// Strip a leading `./` for cleanliness; treat `media/foo.png` and
// `./media/foo.png` identically.
- const cleaned = rawSrc.replace(/^\.\//, "")
+ const stripped = rawSrc.replace(/^\.\//, "")
+
+ // Decode percent-encoding BEFORE assembling the filesystem path.
+ // ReactMarkdown / remark normalize image URLs and percent-encode
+ // non-ASCII characters, so a CJK path like
+ // media/易配置平台2.0培训-1/001-x.jpg
+ // arrives here as
+ // media/%E6%98%93%E9%85%8D.../001-x.jpg
+ // We must turn that back into the literal UTF-8 path that exists on
+ // disk — otherwise convertFileSrc() encodes the `%` again (→ %25E6),
+ // the asset server looks for a file whose name literally contains
+ // "%E6", finds nothing, and the image 404s (showing the alt text).
+ // Decoding is wrapped because a malformed `%` sequence throws; in
+ // that case we keep the raw value rather than crash the renderer.
+ let cleaned: string
+ try {
+ cleaned = decodeURIComponent(stripped)
+ } catch {
+ cleaned = stripped
+ }
+
+ // Generated-wiki convention takes precedence: ingest always emits
+ // embedded images as `media/<source-slug>/img-N.png` — a path
+ // relative to the project's `wiki/` ROOT, regardless of which
+ // wiki subdirectory the page lives in (`wiki/sources/foo.md`,
+ // `wiki/concepts/bar.md`, …). If we let `currentFileDir` win for
+ // these, a page in `wiki/sources/` would resolve `media/…` to
+ // `wiki/sources/media/…` — one level too deep — and the image
+ // 404s. So a `media/`-prefixed src is ALWAYS wiki-root-relative,
+ // never file-relative. File-relative refs use `../assets/…` /
+ // `./x.png` / bare names and never start with `media/`, so this
+ // doesn't steal any of those cases.
+ const isGeneratedMediaRef = cleaned.startsWith("media/")
+
+ // Preferred path: resolve relative to the markdown file's own
+ // directory, exactly like Obsidian. This is what makes
+ // `../assets/img.png` from a file in `raw/sources/` land on the
+ // right place. We normalize the dir to be project-absolute first
+ // (it may arrive as absolute or as a project-relative path), then
+ // collapse `..`/`.` segments.
+ if (currentFileDir && !isGeneratedMediaRef) {
+ const dir = normalizePath(currentFileDir)
+ const dirIsAbsolute =
+ dir.startsWith("/") || /^[a-zA-Z]:/.test(dir) || dir.startsWith("\\\\")
+ const baseDir = dirIsAbsolute ? dir : `${pp}/${dir}`
+ const absolute = collapsePath(`${baseDir.replace(/\/+$/, "")}/${cleaned}`)
+ return convertFileSrc(absolute)
+ }
- // Resolve as wiki-root-relative. The markdown lives somewhere
- // under wiki/ but we ignore its location — image references in
- // generated content always use this convention so the path is
- // stable regardless of page depth.
- const absolute = `${pp}/wiki/${cleaned}`
+ // Fallback: resolve as wiki-root-relative. Image references in
+ // generated wiki content use this convention (`media/<slug>/…`)
+ // so the path is stable regardless of page depth, and callers
+ // without a file context (chat replies) rely on it too.
+ const absolute = collapsePath(`${pp}/wiki/${cleaned}`)
return convertFileSrc(absolute)
}
diff --git a/src/lib/wikilink-transform.test.ts b/src/lib/wikilink-transform.test.ts
index 078a5ebd..dfe6181e 100644
--- a/src/lib/wikilink-transform.test.ts
+++ b/src/lib/wikilink-transform.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest"
-import { transformWikilinks } from "./wikilink-transform"
+import { transformImageEmbeds, transformWikilinks } from "./wikilink-transform"
describe("transformWikilinks", () => {
it("returns input unchanged when there are no wikilinks", () => {
@@ -85,3 +85,82 @@ describe("transformWikilinks", () => {
expect(transformWikilinks("broken]]")).toBe("broken]]")
})
})
+
+describe("transformImageEmbeds", () => {
+ it("returns input unchanged when there are no embeds", () => {
+ expect(transformImageEmbeds("plain text")).toBe("plain text")
+ expect(transformImageEmbeds("a [[link]] but no embed")).toBe(
+ "a [[link]] but no embed",
+ )
+ })
+
+ it("converts an Obsidian image embed to standard markdown", () => {
+ expect(transformImageEmbeds("![[../assets/abc123.png]]")).toBe(
+ "![](<../assets/abc123.png>)",
+ )
+ })
+
+ it("converts a whiteboard-screenshot embed (jpg under boards/)", () => {
+ expect(
+ transformImageEmbeds("![[../assets/boards/WB1.jpg]]"),
+ ).toBe("![](<../assets/boards/WB1.jpg>)")
+ })
+
+ it("uses the alias as alt text for ![[target|alias]]", () => {
+ expect(transformImageEmbeds("![[img.png|A diagram]]")).toBe(
+ "![A diagram](<img.png>)",
+ )
+ })
+
+ it("wraps the target in <…> so spaces/non-ASCII survive the parser", () => {
+ expect(transformImageEmbeds("![[../assets/变与不变 图.png]]")).toBe(
+ "![](<../assets/变与不变 图.png>)",
+ )
+ })
+
+ it("converts multiple embeds and keeps surrounding text", () => {
+ expect(
+ transformImageEmbeds("before ![[a.png]] middle ![[b.png|B]] after"),
+ ).toBe("before ![](<a.png>) middle ![B](<b.png>) after")
+ })
+
+ it("does not touch embeds inside fenced code blocks", () => {
+ const input = "![[a.png]]\n```\n![[b.png]]\n```\n![[c.png]]"
+ expect(transformImageEmbeds(input)).toBe(
+ "![](<a.png>)\n```\n![[b.png]]\n```\n![](<c.png>)",
+ )
+ })
+
+ it("does not touch embeds inside inline code spans", () => {
+ expect(transformImageEmbeds("`![[skip.png]]` and ![[keep.png]]")).toBe(
+ "`![[skip.png]]` and ![](<keep.png>)",
+ )
+ })
+
+ it("leaves an embed whose alias contains `]` untouched (safe degradation)", () => {
+ // A `]` inside an alias is not valid Obsidian embed syntax; the
+ // regex declines to match rather than producing a malformed
+ // image. The literal text is preserved.
+ expect(transformImageEmbeds("![[x.png|a ] b]]")).toBe("![[x.png|a ] b]]")
+ })
+})
+
+describe("composition: embeds then wikilinks", () => {
+ it("an image embed survives the wikilink pass unmangled", () => {
+ // This is the real pipeline order used by the renderers.
+ const input = "See ![[../assets/x.png]] and the [[concept]] page."
+ const out = transformWikilinks(transformImageEmbeds(input))
+ expect(out).toBe("See ![](<../assets/x.png>) and the [concept](#concept) page.")
+ })
+
+ it("REGRESSION: wikilinks-only would have mangled an image embed", () => {
+ // Documents the bug this fix addresses: running the generic
+ // wikilink transform alone turns `![[x.png]]` into a broken
+ // image whose src is a `#fragment`. The embed pass must run first.
+ const mangled = transformWikilinks("![[x.png]]")
+ expect(mangled).toBe("![x.png](#x.png)")
+ // …whereas the correct pipeline yields a real image reference:
+ const correct = transformWikilinks(transformImageEmbeds("![[x.png]]"))
+ expect(correct).toBe("![](<x.png>)")
+ })
+})
diff --git a/src/lib/wikilink-transform.ts b/src/lib/wikilink-transform.ts
index a220660f..d263d97b 100644
--- a/src/lib/wikilink-transform.ts
+++ b/src/lib/wikilink-transform.ts
@@ -14,6 +14,68 @@
* code spans (`…`) so wikilinks shown as code examples in
* documentation don't get mangled.
*/
+/**
+ * Convert Obsidian-style image/file embeds `![[target]]` (and
+ * `![[target|alias]]`) into standard CommonMark image syntax
+ * `![alt](target)` so a commonmark renderer actually displays them.
+ *
+ * Obsidian's embed syntax is a superset of CommonMark that react-
+ * markdown does NOT understand — left untouched, `![[../assets/x.png]]`
+ * renders as literal text. The feishu-to-md export skill emits this
+ * form by default ("Obsidian mode"), so without this rewrite every
+ * exported image is invisible in the app.
+ *
+ * The `target` is preserved verbatim as the image URL (NOT URL-
+ * encoded) — `resolveMarkdownImageSrc` expects raw filesystem-style
+ * relative paths like `../assets/x.png` or `media/slug/img.png`.
+ * The alias (after `|`), if present, becomes the alt text.
+ *
+ * Must run BEFORE `transformWikilinks`, otherwise the generic
+ * `[[…]]` → `[label](#frag)` rule would mangle the embed target
+ * into a fragment link.
+ *
+ * Skips fenced code blocks and inline code spans so documentation
+ * showing the syntax literally isn't rewritten.
+ */
+export function transformImageEmbeds(body: string): string {
+ if (!body.includes("![[")) return body
+
+ const parts = body.split(/(```[\s\S]*?```)/g)
+ return parts
+ .map((part, idx) =>
+ idx % 2 === 1 ? part : transformImageEmbedsOutsideCode(part),
+ )
+ .join("")
+}
+
+const IMAGE_EMBED_RE = /!\[\[([^\]|\n]+)(?:\|([^\]\n]*))?\]\]/g
+
+function transformImageEmbedsOutsideCode(text: string): string {
+ if (!text.includes("![[")) return text
+ const parts = text.split(/(`[^`\n]+`)/g)
+ return parts
+ .map((part, idx) => (idx % 2 === 1 ? part : replaceImageEmbeds(part)))
+ .join("")
+}
+
+function replaceImageEmbeds(text: string): string {
+ return text.replace(
+ IMAGE_EMBED_RE,
+ (_match, rawTarget: string, rawAlias?: string) => {
+ const target = rawTarget.trim()
+ const alias = rawAlias?.trim() ?? ""
+ // Sanitize alt text so `]` doesn't terminate the markdown image
+ // alt bracket early.
+ const alt = alias.replace(/]/g, ")")
+ // Wrap the URL in <…> so spaces / parens / non-ASCII in the
+ // path don't break the CommonMark image parser. The resolver
+ // strips no angle brackets — react-markdown removes them while
+ // parsing, so `src` arrives clean.
+ return `![${alt}](<${target}>)`
+ },
+ )
+}
+
export function transformWikilinks(body: string): string {
if (!body.includes("[[")) return body