Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(reply): parse angle-wrapped file links (#1363)

Call Whiteb69fcd4aacb3
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 9e97c64f9..011a07e1c 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -25,9 +25,13 @@ from typing import List, Tuple
from urllib.parse import unquote, urlparse
from markdown_it import MarkdownIt
+from markdown_it.common.normalize_url import validateLink as _validate_markdown_link
+from markdown_it.common.utils import isStrSpace, unescapeAll
from markdown_it.common.html_re import HTML_TAG_RE
from markdown_it.rules_inline.autolink import AUTOLINK_RE, EMAIL_RE
from markdown_it.rules_inline.backticks import backtick as _commonmark_backtick
+from markdown_it.rules_inline.image import image as _commonmark_image
+from markdown_it.rules_inline.link import link as _commonmark_link
from markdown_it.rules_inline.state_inline import StateInline
logger = logging.getLogger(__name__)
@@ -36,6 +40,7 @@ _INLINE_MARKDOWN = MarkdownIt("commonmark")
_INLINE_CODE_RANGES_KEY = "avibe_inline_code_ranges"
_INLINE_ANGLE_RANGES_KEY = "avibe_inline_angle_ranges"
_INLINE_SILENT_RANGES_KEY = "avibe_inline_silent_ranges"
+_FILE_LINK_CAPTURES_KEY = "avibe_file_link_captures"
def _track_inline_code(state: StateInline, silent: bool) -> bool:
@@ -76,6 +81,76 @@ def _skip_silent_control(state: StateInline, silent: bool) -> bool:
return True
+def _validate_file_link_locally(url: str) -> bool:
+ """Allow file links only in the reply parser's isolated MarkdownIt."""
+ return url.strip().casefold().startswith("file:") or _validate_markdown_link(url)
+
+
+def _capture_file_link_rule(rule, *, is_image: bool):
+ """Wrap a CommonMark rule and record its accepted source ownership."""
+
+ def capture(state: StateInline, silent: bool) -> bool:
+ start = state.pos
+ token_start = len(state.tokens)
+ matched = rule(state, silent)
+ if not matched or silent:
+ return matched
+
+ href = None
+ for token in state.tokens[token_start:]:
+ if is_image and token.type == "image":
+ href = token.attrGet("src")
+ break
+ if not is_image and token.type == "link_open":
+ href = token.attrGet("href")
+ break
+ if not isinstance(href, str) or not href.casefold().startswith("file:"):
+ return matched
+
+ bracket_start = start + (1 if is_image else 0)
+ label_start = bracket_start + 1
+ label_end = state.md.helpers.parseLinkLabel(
+ state,
+ bracket_start,
+ not is_image,
+ )
+ pos = label_end + 1
+ if label_end < 0 or pos >= state.posMax or state.src[pos] != "(":
+ return matched
+ pos += 1
+ while pos < state.posMax:
+ char = state.src[pos]
+ if not isStrSpace(char) and char != "\n":
+ break
+ pos += 1
+ destination_start = pos
+ destination = state.md.helpers.parseLinkDestination(
+ state.src,
+ destination_start,
+ state.posMax,
+ )
+ if not destination.ok:
+ return matched
+ destination_end = destination.pos
+ if state.src[destination_start : destination_start + 1] == "<":
+ destination_start += 1
+ destination_end -= 1
+ state.env.setdefault(_FILE_LINK_CAPTURES_KEY, []).append(
+ (
+ start,
+ state.pos,
+ is_image,
+ label_start,
+ label_end,
+ destination_start,
+ destination_end,
+ )
+ )
+ return matched
+
+ return capture
+
+
_INLINE_MARKDOWN.inline.ruler.disable(["autolink", "html_inline"])
_INLINE_MARKDOWN.inline.ruler.before(
"backticks",
@@ -89,6 +164,17 @@ _INLINE_MARKDOWN.inline.ruler.before(
)
_INLINE_MARKDOWN.inline.ruler.at("backticks", _track_inline_code)
+_FILE_LINK_MARKDOWN = MarkdownIt("commonmark")
+_FILE_LINK_MARKDOWN.validateLink = _validate_file_link_locally
+_FILE_LINK_MARKDOWN.inline.ruler.at(
+ "link",
+ _capture_file_link_rule(_commonmark_link, is_image=False),
+)
+_FILE_LINK_MARKDOWN.inline.ruler.at(
+ "image",
+ _capture_file_link_rule(_commonmark_image, is_image=True),
+)
+
# ---------------------------------------------------------------------------
# Data classes
# ---------------------------------------------------------------------------
@@ -134,15 +220,58 @@ class EnhancedReply:
secret_requests: List[SecretRequest] = field(default_factory=list)
+@dataclass(frozen=True)
+class _FileLinkMatch:
+ """Small match-compatible value shared by the regex and angle scanner."""
+
+ source: str
+ start_offset: int
+ end_offset: int
+ bang: str
+ label: str
+ url: str
+ label_start_offset: int
+ label_end_offset: int
+ url_start_offset: int
+ url_end_offset: int
+
+ def start(self, group: int | None = None) -> int:
+ if group in (None, 0):
+ return self.start_offset
+ if group == 1:
+ return self.start_offset
+ if group == 2:
+ return self.label_start_offset
+ if group == 3:
+ return self.url_start_offset
+ raise IndexError(group)
+
+ def end(self, group: int | None = None) -> int:
+ if group in (None, 0):
+ return self.end_offset
+ if group == 1:
+ return self.start_offset + len(self.bang)
+ if group == 2:
+ return self.label_end_offset
+ if group == 3:
+ return self.url_end_offset
+ raise IndexError(group)
+
+ def group(self, *groups: int) -> str | tuple[str, ...]:
+ values = (self.source, self.bang, self.label, self.url)
+ if not groups:
+ return self.source
+ selected = tuple(values[group] for group in groups)
+ return selected[0] if len(selected) == 1 else selected
+
+ def groups(self) -> tuple[str, str, str]:
+ return self.bang, self.label, self.url
+
+
# ---------------------------------------------------------------------------
# Regex patterns
# ---------------------------------------------------------------------------
-# Matches markdown links with file:// URLs, including image links:
-# [label](file:///path)
-# ![alt](file:///path)
-_FILE_LINK_RE = re.compile(r"(!?)\[([^\]]*)\]\((file://(?:[^()]+|\([^)]*\))+)\)")
-
# Matches the quick-reply button block at the end of the text.
# A horizontal rule (``---``) on its own line, followed by bracket buttons.
# Accept link-formatted variants defensively because agents routinely wrap a
@@ -287,8 +416,8 @@ def _extract_file_links(
results: List[FileLink] = []
for match in _file_link_matches(text, markdown_mask):
bang, label, url = match.groups()
- parsed = urlparse(url)
- if parsed.scheme != "file":
+ parsed = _parse_file_uri(url)
+ if parsed.scheme.casefold() != "file":
continue
path = _file_uri_to_local_path(parsed)
if not os.path.isabs(path):
@@ -300,6 +429,8 @@ def _extract_file_links(
def _file_uri_to_local_path(parsed) -> str:
"""Convert a parsed file URI into a local path for the current OS."""
+ # CommonMark pointy destinations permit backslash-escaped angle brackets;
+ # those escapes are Markdown syntax, not part of the local filename.
path = unquote(parsed.path)
if os.name != "nt":
return path
@@ -311,6 +442,194 @@ def _file_uri_to_local_path(parsed) -> str:
return ntpath.normpath(path)
+def _parse_file_uri(value: str):
+ """Parse a CommonMark-normalized file destination."""
+ return urlparse(value)
+
+
+def _protect_file_uri_delimiters(value: str) -> str:
+ """Keep escaped URI delimiters in the path before CommonMark unescaping."""
+ chars: List[str] = []
+ cursor = 0
+ while cursor < len(value):
+ if value[cursor] != "\\":
+ chars.append(value[cursor])
+ cursor += 1
+ continue
+ slash_start = cursor
+ while cursor < len(value) and value[cursor] == "\\":
+ cursor += 1
+ slash_count = cursor - slash_start
+ if cursor < len(value) and value[cursor] in "?#":
+ chars.append("\\" * (slash_count - slash_count % 2))
+ chars.append(
+ f"%{ord(value[cursor]):02X}"
+ if slash_count % 2
+ else value[cursor]
+ )
+ cursor += 1
+ continue
+ chars.append("\\" * slash_count)
+ return "".join(chars)
+
+
+def _normalize_file_destination(value: str) -> str:
+ """Apply markdown-it's strict entity and backslash normalization once."""
+ return unescapeAll(_protect_file_uri_delimiters(value))
+
+
+def _mask_legacy_bare_file_link_spaces(source: str) -> str:
+ """Make only legacy bare ``file://`` path spaces parseable by CommonMark.
+
+ The returned source is the same length as the input. MarkdownIt still owns
+ link/image syntax and nesting; replacing the spaces only lets it evaluate
+ the one historical extension that CommonMark rejects lexically.
+ """
+ marker = "](file://"
+ if marker not in source or " " not in source:
+ return source
+
+ masked: List[str] | None = None
+ search_start = 0
+ while True:
+ marker_start = source.find(marker, search_start)
+ if marker_start < 0:
+ break
+ destination_start = marker_start + 2
+ cursor = destination_start + len("file://")
+ depth = 0
+ slash_count = 0
+ space_offsets: List[int] = []
+ destination_end = -1
+ later_marker_start = -1
+ while cursor < len(source):
+ if source.startswith(marker, cursor):
+ later_marker_start = cursor
+ break
+ char = source[cursor]
+ if char in "\t\r\n":
+ break
+ if char == "\\":
+ slash_count += 1
+ cursor += 1
+ continue
+
+ escaped = slash_count % 2 == 1
+ slash_count = 0
+ if char == " " and depth >= 0:
+ space_offsets.append(cursor)
+ elif char == "(" and not escaped:
+ depth += 1
+ elif char == ")" and not escaped:
+ if depth == 0:
+ destination_end = cursor
+ break
+ depth -= 1
+ cursor += 1
+
+ if later_marker_start >= 0:
+ search_start = later_marker_start
+ continue
+ if destination_end >= 0 and space_offsets:
+ title_separator = _legacy_bare_title_separator(
+ source,
+ destination_start,
+ destination_end,
+ )
+ if title_separator is not None:
+ space_offsets = [
+ offset for offset in space_offsets if offset < title_separator
+ ]
+ if not space_offsets:
+ search_start = destination_end + 1
+ continue
+ if masked is None:
+ masked = list(source)
+ for offset in space_offsets:
+ masked[offset] = "_"
+ search_start = destination_end + 1
+ elif cursor >= len(source):
+ break
+ else:
+ search_start = cursor + 1
+
+ return "".join(masked) if masked is not None else source
+
+
+def _legacy_bare_title_separator(
+ source: str,
+ destination_start: int,
+ destination_end: int,
+) -> int | None:
+ """Return the ASCII-space separator before a standard trailing title."""
+ if destination_end <= destination_start + 2:
+ return None
+ closer = source[destination_end - 1]
+ opener = "(" if closer == ")" else closer
+ if opener not in "\"'(":
+ return None
+
+ cursor = destination_end - 2
+ title_start = -1
+ while cursor >= destination_start:
+ if source[cursor] != opener:
+ cursor -= 1
+ continue
+ slash_start = cursor
+ while slash_start > destination_start and source[slash_start - 1] == "\\":
+ slash_start -= 1
+ if (cursor - slash_start) % 2 == 0:
+ title_start = cursor
+ break
+ cursor = slash_start - 1
+ if title_start <= destination_start or source[title_start - 1] != " ":
+ return None
+
+ title = _FILE_LINK_MARKDOWN.helpers.parseLinkTitle(
+ source,
+ title_start,
+ destination_end,
+ )
+ if not title.ok or title.pos != destination_end:
+ return None
+ separator = title_start - 1
+ while separator > destination_start and source[separator - 1] == " ":
+ separator -= 1
+ return separator
+
+
+def _inline_file_link_captures(
+ content: str,
+) -> list[tuple[int, int, bool, int, int, int, int]]:
+ """Capture CommonMark links plus the bounded legacy bare-space extension."""
+ env: dict = {_FILE_LINK_CAPTURES_KEY: []}
+ _FILE_LINK_MARKDOWN.inline.parse(content, _FILE_LINK_MARKDOWN, env, [])
+ captures = list(env[_FILE_LINK_CAPTURES_KEY])
+
+ compatibility_source = _mask_legacy_bare_file_link_spaces(content)
+ if compatibility_source == content:
+ return captures
+
+ compatibility_env: dict = {_FILE_LINK_CAPTURES_KEY: []}
+ _FILE_LINK_MARKDOWN.inline.parse(
+ compatibility_source,
+ _FILE_LINK_MARKDOWN,
+ compatibility_env,
+ [],
+ )
+ claimed_spans = {(capture[0], capture[1]) for capture in captures}
+ for capture in compatibility_env[_FILE_LINK_CAPTURES_KEY]:
+ destination = content[capture[5] : capture[6]]
+ if (
+ (capture[0], capture[1]) not in claimed_spans
+ and content[capture[5] - 1 : capture[5]] != "<"
+ and destination.startswith("file://")
+ and " " in destination
+ ):
+ captures.append(capture)
+ return captures
+
+
def _strip_file_links(text: str) -> str:
"""Replace file links outside Markdown code with their labels."""
return _strip_file_links_with_mask(text, _mask_markdown_code(text))[0]
@@ -336,21 +655,167 @@ def _strip_file_links_with_mask(text: str, markdown_mask: str) -> Tuple[str, str
return "".join(text_parts), "".join(mask_parts)
+def _replace_file_links(text: str, replacement) -> str:
+ """Replace eligible file-link destinations while preserving Markdown syntax."""
+ matches = _file_link_matches(text)
+ if not matches:
+ return text
+ parts: List[str] = []
+ cursor = 0
+ for match in matches:
+ parts.append(text[cursor : match.start(3)])
+ parts.append(replacement(match))
+ cursor = match.end(3)
+ parts.append(text[cursor:])
+ return "".join(parts)
+
+
+def _inline_source_offsets(
+ text: str,
+ start: int,
+ end: int,
+ content: str,
+) -> dict[int, int]:
+ """Map container-stripped inline content offsets to source offsets."""
+ source_lines: List[Tuple[int, str]] = []
+ line_start = start
+ for match in re.finditer(r"\r\n|\r|\n", text[start:end]):
+ line_end = start + match.start()
+ source_lines.append((line_start, text[line_start:line_end]))
+ line_start = start + match.end()
+ source_lines.append((line_start, text[line_start:end]))
+
+ offsets: dict[int, int] = {}
+ source_index = 0
+ content_offset = 0
+ for content_line in content.split("\n"):
+ for candidate_index in range(source_index, len(source_lines)):
+ absolute_start, source_line = source_lines[candidate_index]
+ normalized_source_line = source_line.replace("\x00", "\ufffd")
+ relative_start = normalized_source_line.find(content_line)
+ if relative_start < 0:
+ continue
+ for relative_offset in range(len(content_line) + 1):
+ offsets[content_offset + relative_offset] = (
+ absolute_start + relative_start + relative_offset
+ )
+ source_index = candidate_index + 1
+ break
+ content_offset += len(content_line) + 1
+ return offsets
+
+
+def _map_file_link_capture(
+ capture: tuple[int, int, bool, int, int, int, int],
+ offsets: dict[int, int],
+) -> tuple[int, int, bool, int, int, int, int] | None:
+ """Translate one inline-token capture back to the original source."""
+ start, end, is_image, label_start, label_end, url_start, url_end = capture
+ boundaries = (start, end - 1, label_start, label_end, url_start, url_end)
+ if any(boundary not in offsets for boundary in boundaries):
+ return None
+ return (
+ offsets[start],
+ offsets[end - 1] + 1,
+ is_image,
+ offsets[label_start],
+ offsets[label_end],
+ offsets[url_start],
+ offsets[url_end],
+ )
+
+
def _file_link_matches(
text: str,
markdown_mask: str | None = None,
-) -> List[re.Match]:
- """Find eligible link ranges using a mask, then recover original groups."""
- matches: List[re.Match] = []
- mask = markdown_mask if markdown_mask is not None else _mask_markdown_code(text)
- for masked_match in _FILE_LINK_RE.finditer(mask):
- original_match = _FILE_LINK_RE.fullmatch(
+) -> List[_FileLinkMatch]:
+ """Return file links accepted by CommonMark and the local-path policy."""
+ code_ranges, inline_ranges, _ = _markdown_block_ranges(text)
+ captures: list[tuple[int, int, bool, int, int, int, int]] = []
+ for source_start, source_end, content in inline_ranges:
+ inline_captures = _inline_file_link_captures(content)
+ if not inline_captures:
+ continue
+ offsets = _inline_source_offsets(
text,
- masked_match.start(),
- masked_match.end(),
+ source_start,
+ source_end,
+ content,
)
- if original_match is not None:
- matches.append(original_match)
+ for capture in inline_captures:
+ mapped = _map_file_link_capture(capture, offsets)
+ if mapped is not None:
+ captures.append(mapped)
+
+ if markdown_mask is not None:
+ for source_start, source_end in code_ranges:
+ if "[" not in markdown_mask[source_start:source_end]:
+ continue
+ for capture in _inline_file_link_captures(
+ text[source_start:source_end]
+ ):
+ captures.append(
+ (
+ source_start + capture[0],
+ source_start + capture[1],
+ capture[2],
+ source_start + capture[3],
+ source_start + capture[4],
+ source_start + capture[5],
+ source_start + capture[6],
+ )
+ )
+
+ candidates: List[_FileLinkMatch] = []
+ captures = sorted(
+ captures,
+ key=lambda capture: (capture[0], -capture[1]),
+ )
+ for capture in captures:
+ (
+ start,
+ end,
+ is_image,
+ label_start,
+ label_end,
+ url_start,
+ url_end,
+ ) = capture
+ opener_end = start + (2 if is_image else 1)
+ if (
+ markdown_mask is not None
+ and markdown_mask[start:opener_end] != text[start:opener_end]
+ ):
+ continue
+ normalized_url = _normalize_file_destination(text[url_start:url_end])
+ try:
+ parsed = _parse_file_uri(normalized_url)
+ except ValueError:
+ continue
+ path = _file_uri_to_local_path(parsed)
+ if parsed.scheme.casefold() != "file" or not os.path.isabs(path):
+ continue
+ candidates.append(
+ _FileLinkMatch(
+ source=text[start:end],
+ start_offset=start,
+ end_offset=end,
+ bang="!" if is_image else "",
+ label=text[label_start:label_end],
+ url=normalized_url,
+ label_start_offset=label_start,
+ label_end_offset=label_end,
+ url_start_offset=url_start,
+ url_end_offset=url_end,
+ )
+ )
+ matches: List[_FileLinkMatch] = []
+ covered_until = 0
+ for candidate in candidates:
+ if candidate.start() < covered_until:
+ continue
+ matches.append(candidate)
+ covered_until = candidate.end()
return matches
diff --git a/core/workbench_media.py b/core/workbench_media.py
index 30f0e58ba..540240d4c 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -28,12 +28,11 @@ from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO
-from urllib.parse import urlparse
from sqlalchemy.engine import Connection
from config import paths
-from core.reply_enhancer import _FILE_LINK_RE, _file_uri_to_local_path
+from core.reply_enhancer import _file_uri_to_local_path, _parse_file_uri, _replace_file_links
from storage import media_service
logger = logging.getLogger(__name__)
@@ -372,23 +371,24 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: s
and non-absolute paths are left untouched. Best-effort: a registration
failure leaves that one link as written rather than dropping the reply.
"""
- if not text or "file://" not in text:
+ if not text:
return text
def _replace(match) -> str:
bang, label, url = match.group(1), match.group(2), match.group(3)
- parsed = urlparse(url)
- if parsed.scheme != "file":
- return match.group(0)
+ source_url = text[match.start(3) : match.end(3)]
+ parsed = _parse_file_uri(url)
+ if parsed.scheme.casefold() != "file":
+ return source_url
path = _file_uri_to_local_path(parsed)
if not os.path.isabs(path):
logger.warning("workbench_media: skipping non-absolute file link: %s", url)
- return match.group(0)
+ return source_url
try:
safe_path = str(Path(path).resolve())
except Exception:
logger.warning("workbench_media: could not resolve file link: %s", url)
- return match.group(0)
+ return source_url
try:
token = register_agent_reply_media(
conn,
@@ -400,7 +400,7 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: s
)
except Exception:
logger.exception("workbench_media: failed to register media for %s", safe_path)
- return match.group(0)
+ return source_url
url = f"/api/media/{token}"
# For an image, carry its pixel dimensions on the URL (``?w=&h=``) so the
# browser reserves the box before it loads — the transcript never shifts on
@@ -413,9 +413,9 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: s
url = f"{url}?w={w}&h={h}"
except Exception:
logger.debug("workbench_media: no dimensions for %s", safe_path, exc_info=True)
- return f"{bang}[{label}]({url})"
+ return url
- return _FILE_LINK_RE.sub(_replace, text)
+ return _replace_file_links(text, _replace)
def resolve_attachment_specs(conn: Connection, *, session_id: str, attachments) -> list[dict]:
diff --git a/tests/test_message_dispatcher_file_uploads.py b/tests/test_message_dispatcher_file_uploads.py
index 07c593d14..8eda46d3a 100644
--- a/tests/test_message_dispatcher_file_uploads.py
+++ b/tests/test_message_dispatcher_file_uploads.py
@@ -7,7 +7,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
-from core.reply_enhancer import FileLink
+from core.reply_enhancer import FileLink, process_reply
from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -65,6 +65,107 @@ class _SuccessfulWechatIMClient(_FailingWechatIMClient):
class MessageDispatcherFileUploadTests(unittest.IsolatedAsyncioTestCase):
+ async def test_angle_wrapped_file_link_is_extracted_and_uploaded(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController())
+ im_client = _StubIMClient()
+ context = MessageContext(user_id="U1", channel_id="C1")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "报告 (最终).md"
+ file_path.write_text("report", encoding="utf-8")
+ enhanced = process_reply(f"[下载报告](<file://{file_path}>)")
+
+ self.assertEqual(enhanced.text, "下载报告")
+ await dispatcher._upload_file_links(im_client, context, enhanced.files)
+
+ self.assertEqual(
+ im_client.file_uploads,
+ [("C1", str(file_path.resolve()), "下载报告.md")],
+ )
+ self.assertEqual(im_client.image_uploads, [])
+
+ async def test_angle_image_link_with_title_is_uploaded_as_image(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController())
+ im_client = _StubIMClient()
+ context = MessageContext(user_id="U1", channel_id="C1")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "preview & (final).png"
+ file_path.write_bytes(b"png")
+ escaped_path = (
+ str(file_path)
+ .replace("&", "&amp;")
+ .replace("(", r"\(")
+ .replace(")", r"\)")
+ )
+ enhanced = process_reply(
+ f'![preview](<f&#105;le://{escaped_path}> "download") '
+ "and [draft](<file:relative.png>)"
+ )
+
+ self.assertEqual(enhanced.text, "preview and [draft](<file:relative.png>)")
+ self.assertEqual(len(enhanced.files), 1)
+ await dispatcher._upload_file_links(im_client, context, enhanced.files)
+
+ self.assertEqual(
+ im_client.image_uploads,
+ [("C1", str(file_path.resolve()), "preview.png")],
+ )
+
+ async def test_legacy_bare_space_image_ignores_malformed_authority(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController())
+ im_client = _StubIMClient()
+ context = MessageContext(user_id="U1", channel_id="C1")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "preview image.png"
+ file_path.write_bytes(b"png")
+ malformed = "[bad](<file://[bad/path>)"
+ enhanced = process_reply(
+ f"![preview](file://{file_path}) and {malformed}"
+ )
+
+ self.assertEqual(enhanced.text, f"preview and {malformed}")
+ self.assertEqual(len(enhanced.files), 1)
+ await dispatcher._upload_file_links(
+ im_client,
+ context,
+ enhanced.files,
+ )
+
+ self.assertEqual(
+ im_client.image_uploads,
+ [("C1", str(file_path.resolve()), "preview.png")],
+ )
+ self.assertEqual(im_client.file_uploads, [])
+
+ async def test_legacy_bare_space_image_after_malformed_prefix_is_uploaded(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController())
+ im_client = _StubIMClient()
+ context = MessageContext(user_id="U1", channel_id="C1")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "preview image.png"
+ file_path.write_bytes(b"png")
+ prefix = "[bad](file:///tmp/My Report "
+ enhanced = process_reply(
+ f"{prefix}![preview](file://{file_path})"
+ )
+
+ self.assertEqual(enhanced.text, f"{prefix}preview")
+ self.assertEqual(len(enhanced.files), 1)
+ await dispatcher._upload_file_links(
+ im_client,
+ context,
+ enhanced.files,
+ )
+
+ self.assertEqual(
+ im_client.image_uploads,
+ [("C1", str(file_path.resolve()), "preview.png")],
+ )
+ self.assertEqual(im_client.file_uploads, [])
+
async def test_upload_file_link_allows_path_outside_cwd(self):
dispatcher = ConsolidatedMessageDispatcher(_StubController())
im_client = _StubIMClient()
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 4d90c4c10..403da5f6b 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1,5 +1,6 @@
import os
import sys
+import time
import unittest
from pathlib import Path
from types import SimpleNamespace
@@ -1976,6 +1977,327 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
"/Users/test/SaveTwitter.Net_GABV3XNWYAARAZz(gif).mp4",
)
+ def test_angle_wrapped_file_links_accept_commonmark_destinations(self):
+ enhanced = process_reply(
+ "[下载报告](<file:///tmp/My Report (最终).md>) and "
+ "![图片](<file:///tmp/图片 文件.png>)"
+ )
+
+ self.assertEqual(enhanced.text, "下载报告 and 图片")
+ self.assertEqual(
+ [(file.label, file.path, file.is_image) for file in enhanced.files],
+ [
+ ("下载报告", "/tmp/My Report (最终).md", False),
+ ("图片", "/tmp/图片 文件.png", True),
+ ],
+ )
+
+ def test_legacy_bare_file_links_accept_ascii_spaces(self):
+ enhanced = process_reply(
+ "[download](file:///tmp/My Report.md) and "
+ '![image](file:///tmp/图片 文件.png "preview")'
+ )
+
+ self.assertEqual(enhanced.text, "download and image")
+ self.assertEqual(
+ [(file.path, file.is_image) for file in enhanced.files],
+ [
+ ("/tmp/My Report.md", False),
+ ("/tmp/图片 文件.png", True),
+ ],
+ )
+
+ def test_legacy_bare_file_link_extension_rejects_near_neighbors(self):
+ specimens = [
+ "[newline](file:///tmp/My\nReport.md)",
+ "[tab](file:///tmp/My\tReport.md)",
+ "[unclosed](file:///tmp/My Report.md",
+ "[upper](FILE:///tmp/My Report.md)",
+ "`[code](file:///tmp/My Report.md)`",
+ '<span title="[html](file:///tmp/My Report.md)">visible</span>',
+ '[outer](https://example.com "[inner](file:///tmp/My Report.md)")',
+ r"\[escaped](file:///tmp/My Report.md)",
+ ]
+
+ for text in specimens:
+ with self.subTest(text=text):
+ enhanced = process_reply(text)
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_legacy_bare_file_link_recovers_after_malformed_prefix(self):
+ text = (
+ "[bad](file:///tmp/My Report "
+ "[ok](file:///tmp/Good Report.md)"
+ )
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, "[bad](file:///tmp/My Report ok")
+ self.assertEqual(
+ [(file.label, file.path) for file in enhanced.files],
+ [("ok", "/tmp/Good Report.md")],
+ )
+
+ def test_legacy_bare_file_link_recovers_after_multiple_malformed_prefixes(self):
+ text = (
+ "[bad1](file:///tmp/One Report "
+ "[bad2](file:///tmp/Two Report "
+ "[ok](file:///tmp/Good Report.md)"
+ )
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(
+ enhanced.text,
+ "[bad1](file:///tmp/One Report [bad2](file:///tmp/Two Report ok",
+ )
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/Good Report.md"])
+
+ def test_legacy_bare_file_link_keeps_malformed_source_without_valid_tail(self):
+ text = "[bad](file:///tmp/My Report"
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_angle_wrapped_file_links_unescape_angle_brackets_in_paths(self):
+ enhanced = process_reply(r"[report](<file:///tmp/a\>b.md>)")
+
+ self.assertEqual(enhanced.text, "report")
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/a>b.md"])
+
+ def test_angle_wrapped_file_links_allow_unbalanced_parentheses(self):
+ enhanced = process_reply(r"[draft](<file:///tmp/draft (v1.txt>)")
+
+ self.assertEqual(enhanced.text, "draft")
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/draft (v1.txt"])
+
+ def test_angle_wrapped_file_links_unescape_before_percent_decoding(self):
+ enhanced = process_reply(r"[literal](<file:///tmp/a%5C%3Eb.txt>)")
+
+ self.assertEqual(enhanced.text, "literal")
+ self.assertEqual([file.path for file in enhanced.files], [r"/tmp/a\>b.txt"])
+
+ def test_angle_wrapped_file_links_unescape_all_commonmark_punctuation(self):
+ enhanced = process_reply(r"[report](<file:///tmp/a\(b\)\[c\]\#d.md> 'download')")
+
+ self.assertEqual(enhanced.text, "report")
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/a(b)[c]#d.md"])
+
+ def test_angle_wrapped_file_links_commonmark_source_matrix(self):
+ cases = {
+ r"[a\]b](<file:///tmp/report.md>)": "/tmp/report.md",
+ r"[double](<file:///tmp/a\\(b.txt>)": r"/tmp/a\(b.txt",
+ "[refs](<file:///tmp/a&amp;b.txt>)": "/tmp/a&b.txt",
+ "[upper](<FILE:///tmp/upper.txt>)": "/tmp/upper.txt",
+ }
+ for text, expected_path in cases.items():
+ with self.subTest(text=text):
+ enhanced = process_reply(text)
+ self.assertEqual(len(enhanced.files), 1)
+ self.assertEqual(enhanced.files[0].path, expected_path)
+
+ def test_file_link_parser_uses_commonmark_link_ownership(self):
+ nested = process_reply("[outer [inner](<file:///tmp/inner.txt>)]")
+ titled = process_reply(
+ '[outer](<file:///tmp/outer.txt> "fake [inner](<file:///tmp/inner.txt>)")'
+ )
+ image_label = process_reply(
+ "[outer ![inner](<file:///tmp/inner.png>)](<file:///tmp/outer.txt>)"
+ )
+
+ self.assertEqual(nested.text, "[outer inner]")
+ self.assertEqual([file.path for file in nested.files], ["/tmp/inner.txt"])
+ self.assertEqual(titled.text, "outer")
+ self.assertEqual([file.path for file in titled.files], ["/tmp/outer.txt"])
+ self.assertEqual(
+ image_label.text,
+ "outer ![inner](<file:///tmp/inner.png>)",
+ )
+ self.assertEqual(
+ [file.path for file in image_label.files],
+ ["/tmp/outer.txt"],
+ )
+
+ def test_file_link_parser_respects_commonmark_html_block_ownership(self):
+ html_block = "<script>\n[hidden](<file:///tmp/hidden.txt>)\n</script>"
+ escaped_tag = r"\<span>[visible](<file:///tmp/visible.txt>)</span>"
+
+ blocked = process_reply(html_block)
+ visible = process_reply(escaped_tag)
+
+ self.assertEqual(blocked.text, html_block)
+ self.assertEqual(blocked.files, [])
+ self.assertEqual(visible.text, r"\<span>visible</span>")
+ self.assertEqual([file.path for file in visible.files], ["/tmp/visible.txt"])
+
+ def test_file_link_parser_normalizes_strict_entities_before_acceptance(self):
+ valid = process_reply("[report](<f&#105;le:///tmp/a&amp;b.txt>)")
+ semicolonless = process_reply("[literal](<file:///tmp/a&amp.txt>)")
+
+ self.assertEqual([file.path for file in valid.files], ["/tmp/a&b.txt"])
+ self.assertEqual(
+ [file.path for file in semicolonless.files],
+ ["/tmp/a&amp.txt"],
+ )
+
+ def test_file_link_parser_keeps_rejected_relative_links_verbatim(self):
+ text = "[draft](<file:relative/report.md>)"
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_file_link_parser_keeps_malformed_authority_verbatim(self):
+ text = "[bad](<file://[bad/path>)"
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_file_link_parser_skips_offset_maps_without_captures(self):
+ with patch.object(
+ reply_enhancer,
+ "_inline_source_offsets",
+ wraps=reply_enhancer._inline_source_offsets,
+ ) as source_offsets:
+ enhanced = process_reply("ordinary reply " + "x" * 100000)
+
+ self.assertEqual(enhanced.files, [])
+ source_offsets.assert_not_called()
+
+ def test_file_link_parser_maps_captured_inline_source(self):
+ with patch.object(
+ reply_enhancer,
+ "_inline_source_offsets",
+ wraps=reply_enhancer._inline_source_offsets,
+ ) as source_offsets:
+ enhanced = process_reply("> [report](<file:///tmp/report.md>)")
+
+ self.assertEqual(enhanced.text, "> report")
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/report.md"])
+ self.assertGreaterEqual(source_offsets.call_count, 1)
+
+ def test_angle_wrapped_file_links_require_whitespace_before_title(self):
+ text = '[report](<file:///tmp/report.md>"download")'
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_angle_wrapped_file_links_support_titles_and_reject_bad_titles(self):
+ valid = [
+ '[double](<file:///tmp/report.md> "download")',
+ r"[single](<file:///tmp/report.md> 'download')",
+ r"[paren](<file:///tmp/report.md> (download))",
+ '[line](<file:///tmp/report.md>\n "download")',
+ ]
+ for text in valid:
+ with self.subTest(text=text):
+ self.assertEqual(len(process_reply(text).files), 1)
+
+ invalid = [
+ '[unclosed](<file:///tmp/report.md> "download)',
+ r"[nested](<file:///tmp/report.md> (download (copy)))",
+ '[marker](<file:///tmp/report.md> `download`)',
+ '[no-space](<file:///tmp/report.md>"download")',
+ '[blank](<file:///tmp/report.md>\n\n"download")',
+ ]
+ for text in invalid:
+ with self.subTest(text=text):
+ enhanced = process_reply(text)
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_angle_wrapped_file_links_ignore_escaped_openers(self):
+ escaped = process_reply(r"\[example](<file:///tmp/report.txt>)")
+ even_escaped = process_reply(r"\\[example](<file:///tmp/report.txt>)")
+
+ self.assertEqual(escaped.text, r"\[example](<file:///tmp/report.txt>)")
+ self.assertEqual(escaped.files, [])
+ self.assertEqual(even_escaped.text, r"\\example")
+ self.assertEqual([file.path for file in even_escaped.files], ["/tmp/report.txt"])
+
+ escaped_image = process_reply(r"\![preview](<file:///tmp/preview.png>)")
+ even_escaped_image = process_reply(r"\\![preview](<file:///tmp/preview.png>)")
+ self.assertEqual(escaped_image.text, r"\!preview")
+ self.assertEqual([file.is_image for file in escaped_image.files], [False])
+ self.assertEqual(even_escaped_image.text, r"\\preview")
+ self.assertEqual([file.is_image for file in even_escaped_image.files], [True])
+
+ def test_angle_wrapped_file_links_ignore_raw_html_attributes(self):
+ text = '<span title="[hidden](<file:///tmp/hidden.txt>)">visible</span>'
+
+ enhanced = process_reply(text)
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_angle_wrapped_file_links_reject_malformed_markdown_and_code(self):
+ specimens = [
+ "[missing close](<file:///tmp/report.md)",
+ "[extra angle](<file:///tmp/report>copy.md>)",
+ "[extra open](<<file:///tmp/report.md>>)",
+ "[missing label close(<file:///tmp/report.md>)",
+ "[missing close](<file://" + "a" * 100000,
+ "`[inline](<file:///tmp/report.md>)`",
+ "```markdown\n[fenced](<file:///tmp/report.md>)\n```",
+ ]
+
+ for text in specimens:
+ with self.subTest(text=text):
+ enhanced = process_reply(text)
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+
+ def test_file_link_parser_handles_many_openers_in_bounded_time(self):
+ text = "[" * 100000 + "[report](<file:///tmp/report.md>)"
+
+ started = time.perf_counter()
+ enhanced = process_reply(text)
+ elapsed = time.perf_counter() - started
+
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/report.md"])
+ self.assertLess(elapsed, 10.0)
+
+ def test_legacy_bare_file_link_scans_malformed_destination_in_bounded_time(self):
+ text = "[missing](file:///tmp/" + "a " * 50000 + "tail"
+
+ started = time.perf_counter()
+ enhanced = process_reply(text)
+ elapsed = time.perf_counter() - started
+
+ self.assertEqual(enhanced.text, text)
+ self.assertEqual(enhanced.files, [])
+ self.assertLess(elapsed, 10.0)
+
+ def test_legacy_bare_file_link_scans_many_malformed_candidates_linearly(self):
+ text = (
+ "[bad](file:///tmp/My Report " * 4000
+ + "[ok](file:///tmp/Good Report.md)"
+ )
+
+ started = time.perf_counter()
+ enhanced = process_reply(text)
+ elapsed = time.perf_counter() - started
+
+ self.assertEqual([file.path for file in enhanced.files], ["/tmp/Good Report.md"])
+ self.assertLess(elapsed, 10.0)
+
+ def test_unwrapped_file_link_parser_keeps_existing_destination_behavior(self):
+ enhanced = process_reply("[report](file:///tmp/report>draft.md)")
+
+ self.assertEqual(enhanced.text, "report")
+ self.assertEqual(
+ [file.path for file in enhanced.files],
+ ["/tmp/report>draft.md"],
+ )
+
def test_windows_file_uri_is_normalized_before_absolute_check(self):
with patch("core.reply_enhancer.os.name", "nt"), patch("core.reply_enhancer.os.path.isabs") as isabs:
isabs.side_effect = lambda value: value == r"C:\Users\test\generated image.png"
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index 5627724dd..cb6350c40 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import struct
import zlib
from datetime import datetime, timezone
+from unittest.mock import patch
from sqlalchemy import select
@@ -139,6 +140,99 @@ def test_rewrite_in_place_image_file_and_external(tmp_path):
assert all(r["source"] == "agent_reply" for r in rows)
+def test_rewrite_angle_wrapped_file_links(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ image = tmp_path / "图片 文件.png"
+ image.write_bytes(b"image")
+ report = tmp_path / "My Report (最终).md"
+ report.write_text("report", encoding="utf-8")
+ text = f"![图片](<file://{image}>) and [下载报告](<file://{report}>)"
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+
+ assert "file://" not in out
+ assert out.startswith("![图片](</api/media/")
+ assert "and [下载报告](</api/media/" in out
+ with engine.connect() as conn:
+ rows = conn.execute(select(media_objects)).mappings().all()
+ assert {row["local_path"] for row in rows} == {
+ str(image.resolve()),
+ str(report.resolve()),
+ }
+ assert sorted(row["kind"] for row in rows) == ["file", "image"]
+
+
+def test_rewrite_legacy_bare_space_link_and_reject_malformed_authority(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ report = tmp_path / "My Report.md"
+ report.write_text("report", encoding="utf-8")
+ malformed = "[bad](<file://[bad/path>)"
+ text = f'[report](file://{report} "download") and {malformed}'
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(
+ conn,
+ scope_id=scope_id,
+ session_id="sess_x",
+ text=text,
+ )
+
+ assert out.startswith("[report](/api/media/")
+ assert out.endswith(f' "download") and {malformed}')
+ with engine.connect() as conn:
+ rows = conn.execute(select(media_objects)).mappings().all()
+ assert [row["local_path"] for row in rows] == [str(report.resolve())]
+
+
+def test_rewrite_legacy_bare_space_link_after_malformed_prefix(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ report = tmp_path / "Good Report.md"
+ report.write_text("report", encoding="utf-8")
+ prefix = "[bad](file:///tmp/My Report "
+ text = f"{prefix}[report](file://{report})"
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(
+ conn,
+ scope_id=scope_id,
+ session_id="sess_x",
+ text=text,
+ )
+
+ assert out.startswith(f"{prefix}[report](/api/media/")
+ with engine.connect() as conn:
+ rows = conn.execute(select(media_objects)).mappings().all()
+ assert [row["local_path"] for row in rows] == [str(report.resolve())]
+
+
+def test_rewrite_does_not_materialize_file_links_inside_code(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ image = tmp_path / "code.png"
+ image.write_bytes(b"image")
+ text = f"Example `![code](<file://{image}>)` and:\n\n```md\n![fenced](<file://{image}>)\n```"
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+
+ assert out == text
+ with engine.connect() as conn:
+ assert conn.execute(select(media_objects)).first() is None
+
+
def test_resolve_attachment_specs(tmp_path):
db = tmp_path / "vibe.sqlite"
run_migrations(db)
@@ -353,3 +447,70 @@ def test_rewrite_appends_image_dimensions(tmp_path):
# …and a non-image link gets no dimension query.
assert "/api/media/" in out.split(" and ")[1]
assert "?w=" not in out.split(" and ")[1]
+
+
+def test_rewrite_angle_file_link_unescapes_path_and_ignores_title(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ report = tmp_path / "report (final).md"
+ report.write_text("report", encoding="utf-8")
+ escaped_report = str(report).replace("(", "\\(").replace(")", "\\)")
+ text = f'[report](<FILE://{escaped_report}> "download")'
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+
+ assert out.startswith("[report](</api/media/")
+ assert out.endswith('> "download")')
+
+
+def test_rewrite_commonmark_owned_destination_preserves_source_syntax(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ report = tmp_path / "report & (final).md"
+ report.write_text("report", encoding="utf-8")
+ escaped_report = (
+ str(report)
+ .replace("&", "&amp;")
+ .replace("(", r"\(")
+ .replace(")", r"\)")
+ )
+ text = (
+ f'[outer [report](<f&#105;le://{escaped_report}>\n "download")]'
+ " and [draft](<file:relative.md>)"
+ )
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+
+ assert out.startswith("[outer [report](</api/media/")
+ assert out.endswith('>\n "download")] and [draft](<file:relative.md>)')
+ with engine.connect() as conn:
+ rows = conn.execute(select(media_objects)).mappings().all()
+ assert [row["local_path"] for row in rows] == [str(report.resolve())]
+
+
+def test_rewrite_failure_preserves_original_destination_source(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ text = '[report](<f&#105;le:///tmp/a&amp;b.md> "download")'
+
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ with patch(
+ "core.workbench_media.register_agent_reply_media",
+ side_effect=RuntimeError("registration failed"),
+ ):
+ out = rewrite_agent_media(
+ conn,
+ scope_id=scope_id,
+ session_id="sess_x",
+ text=text,
+ )
+
+ assert out == text