Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix: support hash characters in file paths and Markdown references (#4927)

Jiajie - He/him/his985bd1d7c768
diff --git a/bot/tests/test_compile.py b/bot/tests/test_compile.py
index 0e94ef01f..9c571662a 100644
--- a/bot/tests/test_compile.py
+++ b/bot/tests/test_compile.py
@@ -59,6 +59,10 @@ from vikingbot.utils.session_paths import portable_path_component
from openviking.core.skill_loader import SkillLoader
from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
+from openviking.session.memory.utils.resource_refs import (
+ content_references_resource,
+ unlink_resource_references_from_memory,
+)
from openviking_cli.exceptions import OpenVikingError
@@ -379,6 +383,32 @@ def test_renderer_creates_okf_pages_links_and_source_fallbacks():
assert "- [source](viking://resources/source)" in first["content"]
[email protected]("name", ["a#one.md", "a%23one.md"])
[email protected]("inline", [True, False])
[email protected]("scope", ["resources", "user/alice/memories"])
+def test_renderer_encodes_literal_source_filenames(name, inline, scope):
+ source = f"viking://resources/source#1/{name}"
+ bundle = WikiBundleDraft.model_validate(
+ {"pages": [_page(1, "Overview", body_markdown=f"Source: {source}" if inline else "Body")]}
+ )
+ rendered = WikiRenderer().render(
+ bundle=bundle,
+ target_uri=f"viking://{scope}/wiki",
+ source_roots={"src_1": source},
+ catalog_uris=set(),
+ existing_raw={},
+ )
+ encoded = source.replace("%", "%25").replace("#", "%23")
+ assert rendered.operations[0]["content"].count(f"]({encoded})") == 1
+ if scope != "resources":
+ mf = MemoryFileUtils.read(rendered.operations[0]["content"])
+ assert mf.extra_fields["resource_refs"][0]["resource_uri"] == source
+ assert content_references_resource(mf.content, source)
+ assert unlink_resource_references_from_memory(mf, source)
+ assert "resource_refs" not in mf.extra_fields
+ assert not content_references_resource(mf.content, source)
+
+
def test_renderer_preserves_existing_link_without_adding_another_mention_or_backlink():
bundle = WikiBundleDraft.model_validate(
{
@@ -4499,7 +4529,8 @@ async def test_salvage_copies_workspace_and_repairs_links(tmp_path: Path):
"caseonly.md": b"case mismatch",
"Foo.md": b"first",
"foo.md": b"duplicate",
- "bad#name.txt": b"unsafe URI",
+ "hash#name.txt": b"literal hash",
+ "bad?name.txt": b"unsafe URI",
"__compile_staging__/work/notes.txt": b"notes",
"__compile_staging__/tmp/check.txt": b"check",
READLIST_PATH: b"compile_resources/src_1/a.md\n",
@@ -4570,7 +4601,8 @@ async def test_salvage_copies_workspace_and_repairs_links(tmp_path: Path):
assert "sandboxes/cmp-srt-settings.json" not in payloads
assert "sandboxes/cmp-srt-settings.json" not in {path for path, _limit in sandbox.reads}
assert sum(path.casefold() == "foo.md" for path in payloads) == 1
- assert "bad#name.txt" not in payloads
+ assert payloads["hash#name.txt"] == b"literal hash"
+ assert "bad?name.txt" not in payloads
topic = payloads["guide/topic.md"].decode()
assert "[Home](../home.md#top)" in topic
assert "[Meta](../meta/readme.md)" in topic
diff --git a/bot/vikingbot/compile/renderer.py b/bot/vikingbot/compile/renderer.py
index a8387a91a..d655fc432 100644
--- a/bot/vikingbot/compile/renderer.py
+++ b/bot/vikingbot/compile/renderer.py
@@ -3,10 +3,10 @@
from __future__ import annotations
import base64
+import posixpath
import re
from dataclasses import dataclass, field
from typing import Any, Mapping
-from urllib.parse import unquote
import yaml
@@ -190,9 +190,10 @@ def _linkify_source_uris(body: str, source_roots: Mapping[str, str]) -> str:
continue
if not _citation_target_allowed(target, source_roots):
continue
- label = unquote(target.rstrip("/").rsplit("/", 1)[-1]).removesuffix(".md")
+ label = target.rstrip("/").rsplit("/", 1)[-1].removesuffix(".md")
label = label.replace("[", r"\[").replace("]", r"\]") or "Source"
- replacements.append((start, end, f"[{label}]({target})"))
+ encoded_target = LinkRenderer.encode_markdown_target(target)
+ replacements.append((start, end, f"[{label}]({encoded_target})"))
rendered = list(body)
for start, end, replacement in reversed(replacements):
@@ -201,7 +202,7 @@ def _linkify_source_uris(body: str, source_roots: Mapping[str, str]) -> str:
def _wiki_page_basename(uri: str) -> str:
- name = unquote(uri.rstrip("/").rsplit("/", 1)[-1])
+ name = uri.rstrip("/").rsplit("/", 1)[-1]
return name[:-3] if name.casefold().endswith(".md") else name
@@ -218,10 +219,9 @@ def _wiki_mention_targets(uris: set[str]) -> dict[str, str]:
def _has_link_to(body: str, source_uri: str, target_uri: str) -> bool:
relative = LinkRenderer.relative_path(source_uri, target_uri)
- expected = {
- LinkRenderer.normalize_markdown_target(target_uri),
- LinkRenderer.normalize_markdown_target(relative if relative is not None else target_uri),
- }
+ expected = {target_uri.rstrip("/")}
+ if relative is not None:
+ expected.add(posixpath.normpath(relative))
return any(
link.start == 0 or body[link.start - 1] != "!"
for link in LinkRenderer.iter_markdown_links(body)
@@ -355,8 +355,8 @@ def _render_source_fallback(
for linked in linked_targets
):
continue
- label = unquote(target.rstrip("/").rsplit("/", 1)[-1]) or f"Source {source_id}"
- missing.append((label, target))
+ label = target.rstrip("/").rsplit("/", 1)[-1] or f"Source {source_id}"
+ missing.append((label, LinkRenderer.encode_markdown_target(target)))
if not missing:
return body.rstrip()
heading = "来源" if wiki_language == "zh-CN" else "Sources"
diff --git a/bot/vikingbot/compile/service.py b/bot/vikingbot/compile/service.py
index 4fbe55126..61914fc8e 100644
--- a/bot/vikingbot/compile/service.py
+++ b/bot/vikingbot/compile/service.py
@@ -1591,7 +1591,7 @@ class BotCompileService:
return link.text
if "/" not in corrected and not corrected.startswith("."):
corrected = f"./{corrected}"
- corrected = corrected.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+ corrected = LinkRenderer.encode_markdown_target(corrected)
image_marker = "!" if image else ""
return f"{image_marker}[{link.text}]({corrected}{suffix})"
diff --git a/openviking/service/reindex_executor.py b/openviking/service/reindex_executor.py
index 542889063..4bd6933b2 100644
--- a/openviking/service/reindex_executor.py
+++ b/openviking/service/reindex_executor.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import asyncio
+import re
import time
from dataclasses import dataclass, field
from typing import Any, Iterable, Optional
@@ -846,9 +847,26 @@ class ReindexExecutor:
)
return True
+ if self._is_hidden_meta_file(uri):
+ return False
+ exists = await self._prune_source_exists(uri, ctx=owner_ctx)
+ if exists.error:
+ self._record_prune_source_error(
+ counters=counters,
+ uri=uri,
+ source_uri=uri,
+ error=exists.error,
+ )
+ return False
+ # A real filename can have the same spelling as a virtual chunk URI.
+ if exists.exists:
+ return False
+
if "#" in uri:
- if context_type == ContextType.MEMORY.value and "#chunk_" in uri:
- base_uri = uri.split("#chunk_", 1)[0]
+ # Generated chunks append a zero-padded index to the full base URI.
+ chunk_match = re.fullmatch(r"(.+)#chunk_[0-9]{4,}", uri)
+ if context_type == ContextType.MEMORY.value and chunk_match:
+ base_uri = chunk_match.group(1)
base = await self._read_prune_source(base_uri, ctx=owner_ctx)
if base.error:
self._record_prune_source_error(
@@ -866,18 +884,7 @@ class ReindexExecutor:
return uri not in expected
return False
- if self._is_hidden_meta_file(uri):
- return False
- exists = await self._prune_source_exists(uri, ctx=owner_ctx)
- if exists.error:
- self._record_prune_source_error(
- counters=counters,
- uri=uri,
- source_uri=uri,
- error=exists.error,
- )
- return False
- return not exists.exists
+ return True
async def _read_prune_source(self, uri: str, *, ctx: RequestContext) -> _PruneSourceRead:
viking_fs = get_viking_fs()
diff --git a/openviking/session/memory/utils/link_renderer.py b/openviking/session/memory/utils/link_renderer.py
index a193fdbd1..bb2699da6 100644
--- a/openviking/session/memory/utils/link_renderer.py
+++ b/openviking/session/memory/utils/link_renderer.py
@@ -2,7 +2,7 @@ import posixpath
import re
from dataclasses import dataclass
from typing import Callable, Dict, Iterator, List, Optional
-from urllib.parse import unquote
+from urllib.parse import quote, unquote
from openviking.core.namespace import uri_parts
@@ -181,14 +181,19 @@ class LinkRenderer:
return start, end
return None
+ @staticmethod
+ def encode_markdown_target(path: str) -> str:
+ """Encode a literal file path for Markdown; append any fragment afterward."""
+ return re.sub(r"[%# ()]", lambda match: quote(match.group(), safe=""), path)
+
@staticmethod
def normalize_markdown_target(target: str) -> str:
- """Decode and normalize a parsed Markdown link destination."""
- target = unquote(target.strip())
+ """Decode a Markdown destination once, after removing its fragment."""
+ target = target.strip()
if target.startswith("<") and target.endswith(">"):
target = target[1:-1]
target = LinkRenderer._BACKSLASH_ESCAPE_RE.sub(r"\1", target)
- target = target.split("#", 1)[0]
+ target = unquote(target.split("#", 1)[0])
return target.rstrip("/") if "://" in target else posixpath.normpath(target)
@staticmethod
@@ -207,12 +212,9 @@ class LinkRenderer:
link_spans = {(link.start, link.end) for link in markdown_links}
non_link_protected = [span for span in protected_spans if span not in link_spans]
relative_target = LinkRenderer.relative_path(source_uri, target_uri)
- expected_targets = {
- LinkRenderer.normalize_markdown_target(target_uri),
- LinkRenderer.normalize_markdown_target(
- relative_target if relative_target is not None else target_uri
- ),
- }
+ expected_targets = {target_uri.rstrip("/")}
+ if relative_target is not None:
+ expected_targets.add(posixpath.normpath(relative_target))
for link in markdown_links:
if link.start > 0 and content[link.start - 1] == "!":
@@ -273,12 +275,7 @@ class LinkRenderer:
if any(not (end <= rs or start >= re_) for rs, re_, _ in replacements):
continue
- # Percent-encode spaces in the rendered target so the link is portable
- # across markdown renderers (e.g. `[Frank](entities/frank ocean.md)`
- # would otherwise be ambiguous). We accept the literal-space form when
- # matching existing links, but always emit the encoded form when
- # generating new ones.
- encoded_target = link_target.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+ encoded_target = LinkRenderer.encode_markdown_target(link_target)
rendered = f"[{content[start:end]}]({encoded_target})"
replacements.append((start, end, rendered))
diff --git a/openviking/session/memory/utils/resource_refs.py b/openviking/session/memory/utils/resource_refs.py
index 02f441d2e..f4b594941 100644
--- a/openviking/session/memory/utils/resource_refs.py
+++ b/openviking/session/memory/utils/resource_refs.py
@@ -9,6 +9,7 @@ from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Sequence
from openviking.session.memory.dataclass import MemoryFile
+from openviking.session.memory.utils.link_renderer import LinkRenderer
RESOURCE_REF_SOURCE_CONTENT_WRITE = "content.write"
RESOURCE_REF_SOURCE_SESSION_COMMIT = "session.commit"
@@ -89,13 +90,12 @@ def content_references_resource(
def extract_resource_uris(content: str) -> List[str]:
- """Extract visible resource URIs from markdown links or bare URI text."""
- uris: List[str] = []
- for match in _MARKDOWN_RESOURCE_LINK_RE.finditer(content or ""):
- uri = _trim_resource_uri(match.group(2).strip())
- if uri:
- uris.append(uri)
+ """Extract literal storage URIs, decoding Markdown destinations only."""
+ refs, markdown_spans = _extract_markdown_resource_refs(content, ())
+ uris = [ref["resource_uri"] for ref in refs]
for match in _RESOURCE_URI_RE.finditer(content or ""):
+ if _overlaps_spans(match.start(), match.end(), markdown_spans):
+ continue
uri = _trim_resource_uri(match.group(0))
if uri:
uris.append(uri)
@@ -174,7 +174,9 @@ def _extract_markdown_resource_refs(
if _overlaps_spans(match.start(), match.end(), protected_spans):
continue
label = match.group(1).strip()
- resource_uri = _trim_resource_uri(match.group(2).strip())
+ resource_uri = LinkRenderer.normalize_markdown_target(
+ _trim_resource_uri(match.group(2).strip())
+ )
link_spans.append((match.start(), match.end()))
refs.append(
{
@@ -193,7 +195,7 @@ def _unlink_matching_markdown_resource_links(
) -> str:
def replacement(match: re.Match[str]) -> str:
label = match.group(1).strip()
- linked_uri = match.group(2)
+ linked_uri = LinkRenderer.normalize_markdown_target(match.group(2))
if resource_ref_matches(linked_uri, resource_uri, recursive=recursive):
return label
return match.group(0)
@@ -208,7 +210,13 @@ def _remove_matching_bare_resource_uris(
recursive: bool,
) -> str:
text = content or ""
+ # Surviving Markdown destinations are encoded URLs, not bare storage URIs.
+ markdown_spans = [
+ (match.start(), match.end()) for match in _MARKDOWN_RESOURCE_LINK_RE.finditer(text)
+ ]
for match in reversed(list(_RESOURCE_URI_RE.finditer(text))):
+ if _overlaps_spans(match.start(), match.end(), markdown_spans):
+ continue
matched_uri = _trim_resource_uri(match.group(0))
if not resource_ref_matches(matched_uri, resource_uri, recursive=recursive):
continue
@@ -249,7 +257,7 @@ def _linkify_bare_resource_uris(
if contains_resource_uri(anchor) or "](" in anchor:
continue
refs[-1]["match_text"] = anchor
- replacement = f"[{anchor}]({resource_uri})"
+ replacement = f"[{anchor}]({LinkRenderer.encode_markdown_target(resource_uri)})"
updated = updated[:anchor_start] + replacement + updated[end:]
covered_start = anchor_start
diff --git a/openviking/utils/path_safety.py b/openviking/utils/path_safety.py
index 45700cffe..bcb1733c4 100644
--- a/openviking/utils/path_safety.py
+++ b/openviking/utils/path_safety.py
@@ -43,9 +43,9 @@ def sanitize_relative_viking_path(rel_path: str) -> str:
def validate_safe_viking_uri_path(uri: str) -> str:
- """Reject ambiguous or traversal-bearing path syntax in a Viking URI."""
+ """Validate a literal storage path, where ``#`` is part of the filename."""
normalized = VikingURI(uri.strip()).uri.rstrip("/")
- if "?" in normalized or "#" in normalized:
+ if "?" in normalized:
raise ValueError(f"Unsafe Viking URI path rejected: {uri}")
path = normalized[len(f"{VikingURI.SCHEME}://") :]
if not path:
diff --git a/tests/server/test_admin_rebuild_api.py b/tests/server/test_admin_rebuild_api.py
index 829e3da77..a703d595c 100644
--- a/tests/server/test_admin_rebuild_api.py
+++ b/tests/server/test_admin_rebuild_api.py
@@ -922,10 +922,11 @@ async def test_prune_orphans_dry_run_preserves_resource_l1_fallback_and_skips_un
@pytest.mark.asyncio
-async def test_prune_orphans_deletes_stale_memory_chunk_with_uri_owner_ctx(monkeypatch):
[email protected]("filename", ["theme.md", "report#chunk_notes.md", "report#chunk_0000"])
+async def test_prune_orphans_deletes_stale_memory_chunk_with_uri_owner_ctx(monkeypatch, filename):
from openviking.service.reindex_executor import ReindexExecutor, _ReindexCounters
- base_uri = "viking://user/bob/memories/preferences/theme.md"
+ base_uri = f"viking://user/bob/memories/preferences/{filename}"
deleted = {}
class FakeVikingFS:
diff --git a/tests/server/test_content_write_service.py b/tests/server/test_content_write_service.py
index 1f5b98783..136570bc2 100644
--- a/tests/server/test_content_write_service.py
+++ b/tests/server/test_content_write_service.py
@@ -793,9 +793,10 @@ async def test_write_direct_reuses_outer_lease_for_viking_fs(monkeypatch):
@pytest.mark.asyncio
-async def test_resource_write_updates_target_and_queues_refresh_before_return(monkeypatch):
- file_uri = "viking://resources/demo/doc.md"
- root_uri = "viking://resources/demo"
[email protected]("path", ["demo/doc.md", "demo#1/a#one.md"])
+async def test_resource_write_updates_target_and_queues_refresh_before_return(monkeypatch, path):
+ file_uri = f"viking://resources/{path}"
+ root_uri = file_uri.rsplit("/", 1)[0]
ctx = RequestContext(user=UserIdentifier.the_default_user(), role=Role.USER)
viking_fs = _FakeVikingFS(file_uri=file_uri, root_uri=root_uri)
coordinator = ContentWriteCoordinator(viking_fs=viking_fs)
diff --git a/tests/session/memory/test_resource_refs.py b/tests/session/memory/test_resource_refs.py
index 541b1cc73..620eec28f 100644
--- a/tests/session/memory/test_resource_refs.py
+++ b/tests/session/memory/test_resource_refs.py
@@ -1,15 +1,44 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import pytest
+
from openviking.session.memory.dataclass import MemoryFile
from openviking.session.memory.utils.resource_refs import (
contains_resource_uri,
+ content_references_resource,
extract_resource_uris,
sync_memory_resource_refs,
unlink_resource_references_from_memory,
)
+ ("name", "encoded"),
+ [("a#one.md", "a%23one.md"), ("a%23one.md", "a%2523one.md")],
+)
[email protected]("bare", [False, True])
+def test_resource_refs_preserve_literal_filenames(name, encoded, bare):
+ root = "viking://resources/source/"
+ uri = root + name
+ content = f"Source {uri}" if bare else f"[Source]({root}{encoded}#intro)"
+ mf = MemoryFile(content=content, extra_fields={})
+
+ assert extract_resource_uris(content) == [uri]
+ assert sync_memory_resource_refs(mf, source="compile")
+ assert mf.extra_fields["resource_refs"][0]["resource_uri"] == uri
+ assert f"]({root}{encoded}" in mf.content
+ assert not sync_memory_resource_refs(mf, source="compile")
+ assert extract_resource_uris(mf.content) == [uri]
+ assert content_references_resource(mf.content, uri)
+ for other in {"a#one.md", "a%23one.md", "a#two.md", "a"} - {name}:
+ assert not content_references_resource(mf.content, root + other)
+ assert not unlink_resource_references_from_memory(mf, root + other)
+ assert unlink_resource_references_from_memory(mf, uri)
+ assert mf.content == "Source"
+ assert "resource_refs" not in mf.extra_fields
+
+
def test_extract_resource_uris_stops_at_common_sentence_delimiters():
cases = [
(
diff --git a/tests/test_link_renderer.py b/tests/test_link_renderer.py
index e6afc54df..95ea78547 100644
--- a/tests/test_link_renderer.py
+++ b/tests/test_link_renderer.py
@@ -1,8 +1,30 @@
+import pytest
+
from openviking.session.memory.dataclass import MemoryFile
from openviking.session.memory.utils.link_renderer import LinkRenderer
from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
+ ("name", "encoded"),
+ [("a#one.md", "a%23one.md"), ("a%23one.md", "a%2523one.md")],
+)
+def test_hash_filename_links_round_trip_without_aliasing(name, encoded):
+ source = "viking://resources/wiki/index.md"
+ target = f"viking://resources/wiki/{name}"
+ assert (
+ LinkRenderer.render_links("Details", source, [{"match_text": "Details", "to_uri": target}])
+ == f"[Details](./{encoded})"
+ )
+ for prefix in ("./", "viking://resources/wiki/"):
+ content = f"[Details]({prefix}{encoded}#intro)"
+ assert LinkRenderer.can_render_link(content, "Details", source, target)
+ for other in {"a#one.md", "a#two.md", "a%23one.md", "a"} - {name}:
+ assert not LinkRenderer.can_render_link(
+ content, "Details", source, f"viking://resources/wiki/{other}"
+ )
+
+
class TestRelativePath:
def test_same_directory(self):
result = LinkRenderer.relative_path(
diff --git a/web-studio/src/routes/resources/-components/file-preview.test.tsx b/web-studio/src/routes/resources/-components/file-preview.test.tsx
index 34a2b7a76..07f225fef 100644
--- a/web-studio/src/routes/resources/-components/file-preview.test.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.test.tsx
@@ -113,6 +113,11 @@ function renderPreview(
}
describe('FilePreview Markdown links', () => {
+ beforeEach(() => cleanup())
+ afterEach(() => {
+ previewState.override = null
+ })
+
it('opens internal Markdown links in the resource preview', () => {
const onNavigate = vi.fn()
renderPreview(file, onNavigate)
@@ -174,6 +179,26 @@ describe('FilePreview Markdown links', () => {
expect(onNavigate).toHaveBeenCalledWith('viking://resources/资料/目标.md')
})
+ it.each([file, directory])('opens encoded filenames from $name', (entry) => {
+ const onNavigate = vi.fn()
+ const prefix = entry.isDir ? 'viking://resources/wiki/' : './'
+ const content = `[One](${prefix}a%23one.md#intro)\n\n[Percent](${prefix}a%2523one.md#intro)`
+ previewState.override = entry.isDir
+ ? null
+ : { content, fileType: 'markdown' }
+ renderPreview(entry, onNavigate, content)
+ fireEvent.click(screen.getByRole('link', { name: 'One' }))
+ fireEvent.click(screen.getByRole('link', { name: 'Percent' }))
+ expect(onNavigate).toHaveBeenNthCalledWith(
+ 1,
+ 'viking://resources/wiki/a#one.md',
+ )
+ expect(onNavigate).toHaveBeenNthCalledWith(
+ 2,
+ 'viking://resources/wiki/a%23one.md',
+ )
+ })
+
it('preserves non-viking links in a directory overview', () => {
const onNavigate = vi.fn()
renderPreview(
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index 2e5276b49..b16780fca 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -294,6 +294,7 @@ function dirnameVikingUri(fileUri: string): string {
return `${trimmed.slice(0, idx + 1)}`
}
+/** Resolve a decoded file path without interpreting literal # or percent signs. */
function resolveRelativeVikingUri(
baseFileUri: string,
rawPath: string,
@@ -301,11 +302,8 @@ function resolveRelativeVikingUri(
const baseDir = dirnameVikingUri(baseFileUri)
const baseBody = baseDir.slice(vikingPrefix.length, -1)
- const pathPart = rawPath.split('#')[0]?.split('?')[0] || ''
- const suffix = rawPath.slice(pathPart.length)
-
const baseSegments = baseBody ? baseBody.split('/').filter(Boolean) : []
- const relativeSegments = pathPart.split('/').filter(Boolean)
+ const relativeSegments = rawPath.split('/').filter(Boolean)
const merged = [...baseSegments]
for (const segment of relativeSegments) {
@@ -320,7 +318,7 @@ function resolveRelativeVikingUri(
}
const resolved = `${vikingPrefix}${merged.join('/')}`
- return `${resolved}${suffix}`
+ return resolved
}
type MarkdownAssetTarget =
@@ -349,11 +347,8 @@ function resolveMarkdownAssetTarget(
return { kind: 'external', value: trimmed }
}
- // react-markdown percent-encodes the URL it passes via `src`/`href`
- // (e.g. Chinese characters become %E4%BA%92). Decode it back to the literal
- // form so the API client's query serializer encodes it exactly once and we
- // avoid a double-encoded URI that the backend rejects with HTTP 400.
- const decoded = safeDecodeUri(trimmed)
+ // Split URL components before decoding; %23 is literal filename data.
+ const decoded = safeDecodeUri(trimmed.split(/[?#]/, 1)[0])
const vikingUri = decoded.startsWith(vikingPrefix)
? decoded
@@ -361,8 +356,7 @@ function resolveMarkdownAssetTarget(
return { kind: 'viking', value: vikingUri }
}
-function resolveMarkdownAssetUrl(assetPath: string, fileUri: string): string {
- const target = resolveMarkdownAssetTarget(assetPath, fileUri)
+function resolveMarkdownAssetUrl(target: MarkdownAssetTarget): string {
if (target.kind === 'viking') {
return toDownloadUrl(target.value)
}
@@ -389,7 +383,7 @@ function MarkdownLink({
const resolvedHref = target
? isInternal
? target.value
- : resolveMarkdownAssetUrl(target.value, fileUri)
+ : resolveMarkdownAssetUrl(target)
: ''
const isExternal = /^(https?:|mailto:|tel:)/i.test(resolvedHref)
@@ -427,7 +421,7 @@ function DirectoryMarkdownLink({
}
return (
- <MarkdownLink href={decodedHref} fileUri={fileUri} onNavigate={onNavigate}>
+ <MarkdownLink href={href} fileUri={fileUri} onNavigate={onNavigate}>
{children}
</MarkdownLink>
)