Skip to content

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

fix(parse/media): honor source_name/resource_name for media internal filenames (#2382) (#2492)

Evo5bc465a5f639
diff --git a/openviking/parse/parsers/media/audio.py b/openviking/parse/parsers/media/audio.py
index 09edcb7a4..7ab549db7 100644
--- a/openviking/parse/parsers/media/audio.py
+++ b/openviking/parse/parsers/media/audio.py
@@ -36,6 +36,7 @@ import openai
from openviking.parse.base import NodeType, ParseResult, ResourceNode
from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.media.constants import AUDIO_EXTENSIONS
+from openviking.parse.parsers.media.naming import resolve_media_names
from openviking_cli.utils.config.parser_config import AudioConfig
from openviking_cli.utils.logger import get_logger
@@ -93,10 +94,11 @@ class AudioParser(BaseParser):
from openviking_cli.utils.uri import VikingURI
- # Sanitize original filename (replace spaces with underscores)
- original_filename = file_path.name.replace(" ", "_")
+ # Resolve the resource name from the caller's resource_name / source_name
+ # (falling back to the temp file name) so the filename, URI and title
+ # reflect the real upload, not the internal temp id — see resolve_media_names.
+ display_stem, stem, original_filename = resolve_media_names(file_path, ext, **kwargs)
# Root directory name: filename stem + _ + extension (without dot)
- stem = file_path.stem.replace(" ", "_")
ext_no_dot = ext[1:] if ext else ""
root_dir_name = VikingURI.sanitize_segment(f"{stem}_{ext_no_dot}")
root_dir_uri = f"{temp_uri}/{root_dir_name}"
@@ -140,7 +142,7 @@ class AudioParser(BaseParser):
# Create ResourceNode - metadata only, no content understanding yet
root_node = ResourceNode(
type=NodeType.ROOT,
- title=file_path.stem,
+ title=display_stem,
level=0,
detail_file=None,
content_path=None,
@@ -151,8 +153,8 @@ class AudioParser(BaseParser):
"channels": channels,
"format": format_str.lower(),
"content_type": "audio",
- "source_title": file_path.stem,
- "semantic_name": file_path.stem,
+ "source_title": display_stem,
+ "semantic_name": display_stem,
"original_filename": original_filename,
},
)
diff --git a/openviking/parse/parsers/media/image.py b/openviking/parse/parsers/media/image.py
index 854e5cb39..e6338d87f 100644
--- a/openviking/parse/parsers/media/image.py
+++ b/openviking/parse/parsers/media/image.py
@@ -20,6 +20,7 @@ from PIL import Image
from openviking.parse.base import NodeType, ParseResult, ResourceNode
from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.media.constants import IMAGE_EXTENSIONS
+from openviking.parse.parsers.media.naming import resolve_media_names
from openviking.prompts import render_prompt
from openviking.storage.viking_fs import get_viking_fs
from openviking_cli.utils.config import get_openviking_config
@@ -101,10 +102,11 @@ class ImageParser(BaseParser):
image_bytes = file_path.read_bytes()
ext = file_path.suffix
- # Sanitize original filename (replace spaces with underscores)
- original_filename = file_path.name.replace(" ", "_")
+ # Resolve the resource name from the caller's resource_name / source_name
+ # (falling back to the temp file name) so the filename, URI and title
+ # reflect the real upload, not the internal temp id — see resolve_media_names.
+ display_stem, stem, original_filename = resolve_media_names(file_path, ext, **kwargs)
# Root directory name: filename stem + _ + extension (without dot)
- stem = file_path.stem.replace(" ", "_")
ext_no_dot = ext[1:] if ext else ""
root_dir_name = VikingURI.sanitize_segment(f"{stem}_{ext_no_dot}")
root_dir_uri = f"{temp_uri}/{root_dir_name}"
@@ -127,7 +129,7 @@ class ImageParser(BaseParser):
# Create ResourceNode - metadata only, no content understanding yet
root_node = ResourceNode(
type=NodeType.ROOT,
- title=file_path.stem,
+ title=display_stem,
level=0,
detail_file=None,
content_path=None,
@@ -137,8 +139,8 @@ class ImageParser(BaseParser):
"height": height,
"format": format_str.lower(),
"content_type": "image",
- "source_title": file_path.stem,
- "semantic_name": file_path.stem,
+ "source_title": display_stem,
+ "semantic_name": display_stem,
"original_filename": original_filename,
},
)
diff --git a/openviking/parse/parsers/media/naming.py b/openviking/parse/parsers/media/naming.py
new file mode 100644
index 000000000..cdc9978ba
--- /dev/null
+++ b/openviking/parse/parsers/media/naming.py
@@ -0,0 +1,56 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Shared resource-name resolution for the media parsers (image / audio / video).
+
+A staged upload reaches a parser as a temp file named ``upload_<uuid>.<ext>``.
+The caller's real name arrives via the ``resource_name`` / ``source_name``
+kwargs (the markdown parser already honors these, and ``media_processor`` passes
+``resource_name`` through). Centralizing the resolution keeps the three media
+parsers in lockstep so the resource's filename, URI and title reflect the real
+upload instead of the internal temp id.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Tuple
+
+from openviking.parse.parsers.media.constants import MEDIA_EXTENSIONS
+
+
+def resolve_media_names(file_path: Path, ext: str, **kwargs: Any) -> Tuple[str, str, str]:
+ """Resolve ``(display_stem, path_stem, original_filename)`` for a media resource.
+
+ Honors a caller-supplied ``resource_name`` / ``source_name``, reducing it to
+ its stem only when the trailing suffix is a known media extension (so a
+ filename-like value such as ``"photo.png"`` does not double its extension,
+ while a name that merely contains a dot like ``"meeting.v1"`` is preserved).
+ When neither is supplied, falls back to the temp file name with behavior
+ byte-identical to the historical inline logic.
+
+ Args:
+ file_path: the temp (or source) file path the parser is reading.
+ ext: the resource extension to use (the parser passes ``file_path.suffix``).
+ **kwargs: parser kwargs; ``resource_name`` / ``source_name`` are consulted.
+
+ Returns:
+ display_stem: human-readable name for the title / metadata fields.
+ path_stem: ``display_stem`` with spaces -> underscores, for URI segments.
+ original_filename: the resource's internal filename.
+ """
+ explicit_name = kwargs.get("resource_name") or kwargs.get("source_name")
+ if explicit_name:
+ # Strip a trailing extension only when it is a known media extension, so
+ # a filename-like value ("photo.png") does not double its extension,
+ # while a name that merely contains a dot ("meeting.v1") is preserved.
+ candidate = Path(explicit_name)
+ display_stem = candidate.stem if candidate.suffix.lower() in MEDIA_EXTENSIONS else explicit_name
+ path_stem = display_stem.replace(" ", "_")
+ original_filename = f"{path_stem}{ext}"
+ else:
+ display_stem = file_path.stem
+ path_stem = file_path.stem.replace(" ", "_")
+ # Preserve the historical fallback exactly: replace spaces anywhere in
+ # the basename (including inside the extension), not just in the stem.
+ original_filename = file_path.name.replace(" ", "_")
+ return display_stem, path_stem, original_filename
diff --git a/openviking/parse/parsers/media/video.py b/openviking/parse/parsers/media/video.py
index 87f700bd0..3d9d8b429 100644
--- a/openviking/parse/parsers/media/video.py
+++ b/openviking/parse/parsers/media/video.py
@@ -30,6 +30,7 @@ from typing import List, Optional, Union
from openviking.parse.base import NodeType, ParseResult, ResourceNode
from openviking.parse.parsers.base_parser import BaseParser
from openviking.parse.parsers.media.constants import VIDEO_EXTENSIONS
+from openviking.parse.parsers.media.naming import resolve_media_names
from openviking_cli.utils.config.parser_config import VideoConfig
@@ -84,10 +85,11 @@ class VideoParser(BaseParser):
from openviking_cli.utils.uri import VikingURI
- # Sanitize original filename (replace spaces with underscores)
- original_filename = file_path.name.replace(" ", "_")
+ # Resolve the resource name from the caller's resource_name / source_name
+ # (falling back to the temp file name) so the filename, URI and title
+ # reflect the real upload, not the internal temp id — see resolve_media_names.
+ display_stem, stem, original_filename = resolve_media_names(file_path, ext, **kwargs)
# Root directory name: filename stem + _ + extension (without dot)
- stem = file_path.stem.replace(" ", "_")
ext_no_dot = ext[1:] if ext else ""
root_dir_name = VikingURI.sanitize_segment(f"{stem}_{ext_no_dot}")
root_dir_uri = f"{temp_uri}/{root_dir_name}"
@@ -132,7 +134,7 @@ class VideoParser(BaseParser):
# Create ResourceNode - metadata only, no content understanding yet
root_node = ResourceNode(
type=NodeType.ROOT,
- title=file_path.stem,
+ title=display_stem,
level=0,
detail_file=None,
content_path=None,
@@ -144,8 +146,8 @@ class VideoParser(BaseParser):
"fps": fps,
"format": format_str.lower(),
"content_type": "video",
- "source_title": file_path.stem,
- "semantic_name": file_path.stem,
+ "source_title": display_stem,
+ "semantic_name": display_stem,
"original_filename": original_filename,
},
)
diff --git a/tests/parse/test_media_resource_name.py b/tests/parse/test_media_resource_name.py
new file mode 100644
index 000000000..1e9be92a3
--- /dev/null
+++ b/tests/parse/test_media_resource_name.py
@@ -0,0 +1,125 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Media parsers must honor a caller-supplied resource_name / source_name for
+the resource's internal filename, URI and title, instead of leaking the temp
+upload id (upload_<uuid>) — matching the markdown parser. Regression test for
+#2382.
+
+The name-resolution logic is shared by the image / audio / video parsers via
+``resolve_media_names``; it is unit-tested directly here (covering all three),
+plus one image-parser integration test wiring it end-to-end.
+"""
+
+import io
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from PIL import Image
+
+from openviking.parse.parsers.media.image import ImageParser
+from openviking.parse.parsers.media.naming import resolve_media_names
+from openviking_cli.utils.config.parser_config import ImageConfig
+
+
+def _png_bytes(width: int = 10, height: int = 10) -> bytes:
+ img = Image.new("RGB", (width, height), color="white")
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _fake_viking_fs() -> MagicMock:
+ fs = MagicMock()
+ fs.create_temp_uri = MagicMock(return_value="viking://temp/abc123")
+ fs.mkdir = AsyncMock()
+ fs.write_file_bytes = AsyncMock()
+ return fs
+
+
+# --- resolve_media_names (shared by image / audio / video parsers) -----------
+
+
+def test_resolve_uses_resource_name():
+ fp = Path("upload_0123456789abcdef.png")
+ assert resolve_media_names(fp, ".png", resource_name="vacation") == ("vacation", "vacation", "vacation.png")
+
+
+def test_resolve_resource_name_filename_is_not_double_extended():
+ # A filename-like resource_name is reduced to its stem ("My Holiday.png" ->
+ # "My_Holiday.png", not "My_Holiday.png.png").
+ fp = Path("upload_x.png")
+ assert resolve_media_names(fp, ".png", resource_name="My Holiday.png") == ("My Holiday", "My_Holiday", "My_Holiday.png")
+
+
+def test_resolve_source_name_stem_when_no_resource_name():
+ fp = Path("upload_x.png")
+ assert resolve_media_names(fp, ".png", source_name="My Holiday.png") == ("My Holiday", "My_Holiday", "My_Holiday.png")
+
+
+def test_resolve_preserves_non_media_dotted_name():
+ # A name that merely contains a dot (not a media extension) is kept intact —
+ # only a real media extension is stripped, so "meeting.v1" is not truncated.
+ fp = Path("upload_x.png")
+ assert resolve_media_names(fp, ".png", resource_name="meeting.v1") == ("meeting.v1", "meeting.v1", "meeting.v1.png")
+
+
+def test_resolve_empty_resource_name_falls_through_to_source_name():
+ fp = Path("upload_x.png")
+ assert resolve_media_names(fp, ".png", resource_name="", source_name="clip.png") == ("clip", "clip", "clip.png")
+
+
+def test_resolve_falls_back_to_temp_name_when_no_caller_name():
+ fp = Path("upload_0123456789abcdef.png")
+ assert resolve_media_names(fp, ".png") == (
+ "upload_0123456789abcdef",
+ "upload_0123456789abcdef",
+ "upload_0123456789abcdef.png",
+ )
+
+
+def test_resolve_fallback_is_byte_identical_to_legacy_for_spaces():
+ # Legacy behavior replaced spaces anywhere in the basename via
+ # name.replace(" ", "_") — including a space inside the extension. The
+ # no-kwargs fallback must reproduce that exactly.
+ fp = Path("my clip. mp4")
+ display, stem, original = resolve_media_names(fp, fp.suffix)
+ assert original == "my_clip._mp4"
+ assert original == fp.name.replace(" ", "_") # exact legacy expression
+ assert (display, stem) == ("my clip", "my_clip")
+
+
+# --- image parser integration (wires resolve_media_names end-to-end) ---------
+
+
+async def test_image_parser_honors_resource_name(tmp_path):
+ upload = tmp_path / "upload_0123456789abcdef.png"
+ upload.write_bytes(_png_bytes())
+
+ parser = ImageParser(config=ImageConfig())
+ fake_fs = _fake_viking_fs()
+ with patch("openviking.parse.parsers.media.image.get_viking_fs", return_value=fake_fs):
+ result = await parser.parse(str(upload), resource_name="vacation")
+
+ assert result.root.meta["original_filename"] == "vacation.png"
+ assert result.root.meta["semantic_name"] == "vacation"
+ assert result.root.meta["source_title"] == "vacation"
+ assert result.root.title == "vacation"
+
+ written = [call.args[0] for call in fake_fs.write_file_bytes.await_args_list]
+ assert any(p.endswith("/vacation.png") for p in written)
+ assert not any("upload_0123456789abcdef" in p for p in written)
+
+
+async def test_image_parser_falls_back_to_temp_name(tmp_path):
+ upload = tmp_path / "upload_0123456789abcdef.png"
+ upload.write_bytes(_png_bytes())
+
+ parser = ImageParser(config=ImageConfig())
+ fake_fs = _fake_viking_fs()
+ with patch("openviking.parse.parsers.media.image.get_viking_fs", return_value=fake_fs):
+ result = await parser.parse(str(upload))
+
+ assert result.root.meta["original_filename"] == "upload_0123456789abcdef.png"