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.

feat(ui): play audio and video chat attachments inline (#2198)

Call White6b45ef47a542
diff --git a/Dockerfile b/Dockerfile
index aac14d93f..575f815f8 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -14,6 +14,7 @@ RUN npm ci --ignore-scripts
# expects, or ``npm run build`` fails to resolve it.
COPY vibe/message_types.json /app/vibe/message_types.json
COPY vibe/data/api_key_vendors.json /app/vibe/data/api_key_vendors.json
+COPY vibe/data/media_types.json /app/vibe/data/media_types.json
COPY ui/ .
RUN npm run build
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index 09b6a1a95..b2c00b061 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -20,6 +20,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO, Callable
+from core.media_types import is_inline_safe_type
+
logger = logging.getLogger(__name__)
MAX_FILE_BYTES = 25 * 1024 * 1024
@@ -30,6 +32,7 @@ DELETE_UNDO_ENTRY_SIZE_CAP_BYTES = 512 * 1024 * 1024
DELETE_UNDO_TOTAL_SIZE_CAP_BYTES = 2 * 1024 * 1024 * 1024
COPY_TOTAL_SIZE_CAP_BYTES = 2 * 1024 * 1024 * 1024
+# Every audio/* and video/* type is inline-safe too (``core.media_types.is_inline_safe_type``).
INLINE_SAFE_CONTENT_TYPES = {
"image/png",
"image/jpeg",
@@ -45,20 +48,36 @@ INLINE_SAFE_CONTENT_TYPES = {
"text/markdown",
"text/csv",
"application/json",
- "audio/mpeg",
- "audio/mp4",
- "audio/aac",
- "audio/ogg",
- "audio/wav",
- "audio/webm",
- "audio/flac",
- "audio/x-m4a",
- "video/mp4",
- "video/webm",
- "video/ogg",
- "video/quicktime",
}
+# ``Range: bytes=<first>-<last>`` with bounded digits: a longer number is treated as malformed (full
+# 200 body) rather than handed to int(). A comma never matches, so multi-range requests also fall back.
+_BYTE_RANGE_RE = re.compile(r"^\s*bytes\s*=\s*(\d{0,20})\s*-\s*(\d{0,20})\s*$", re.IGNORECASE)
+
+
+def parse_byte_range(header: str | None, size: int) -> tuple[int, int] | None:
+ """Resolve a single ``Range: bytes=`` spec against ``size`` bytes into an inclusive span.
+
+ Returns ``None`` to serve the whole body (no header, multi-range, or malformed spec — RFC 9110
+ lets a server ignore those) and raises ``RangeNotSatisfiableError`` for a parsable range that
+ starts at or beyond the end of the file."""
+ match = _BYTE_RANGE_RE.match(header or "")
+ if not match or not (match.group(1) or match.group(2)):
+ return None
+ first, last = match.group(1), match.group(2)
+ if not first:
+ suffix = int(last)
+ if suffix == 0 or size == 0:
+ raise RangeNotSatisfiableError(size)
+ return max(size - suffix, 0), size - 1
+ start = int(first)
+ if last and int(last) < start:
+ return None
+ if start >= size:
+ raise RangeNotSatisfiableError(size)
+ return start, min(int(last), size - 1) if last else size - 1
+
+
_AT_FDCWD = -100
_RENAME_NOREPLACE = 1
_RENAME_NOREPLACE_FALLBACK_WARNED = False
@@ -93,6 +112,12 @@ class FileBrowserError(Exception):
self.status_code = status_code
+class RangeNotSatisfiableError(FileBrowserError):
+ def __init__(self, size: int) -> None:
+ super().__init__("range_not_satisfiable", "Requested range not satisfiable", 416)
+ self.size = size
+
+
class NotFoundError(FileBrowserError):
def __init__(self, message: str = "Path not found") -> None:
super().__init__("not_found", message, 404)
@@ -109,6 +134,9 @@ class FileContent:
mime: str
disposition: str
data: bytes
+ size: int = 0
+ # Inclusive (start, end) when ``data`` is a byte-range slice of the ``size``-byte file.
+ byte_range: tuple[int, int] | None = None
@dataclass(frozen=True)
@@ -635,14 +663,13 @@ def metadata(raw_path: str) -> dict[str, Any]:
}
-def file_content(raw_path: str, *, download: bool = False) -> FileContent:
+def file_content(raw_path: str, *, download: bool = False, range_header: str | None = None) -> FileContent:
path = _require_regular_file(raw_path)
stat_result = _stat_existing(path)
if stat_result.st_size > MAX_FILE_BYTES:
raise FileBrowserError("too_large", "File is too large", 413)
mime = _guess_mime(path)
- base_mime = mime.split(";", 1)[0].strip().lower()
- disposition = "attachment" if download or base_mime not in INLINE_SAFE_CONTENT_TYPES else "inline"
+ disposition = "attachment" if download or not is_inline_safe_type(mime, INLINE_SAFE_CONTENT_TYPES) else "inline"
try:
flags = os.O_RDONLY
if hasattr(os, "O_NOFOLLOW"):
@@ -654,8 +681,15 @@ def file_content(raw_path: str, *, download: bool = False) -> FileContent:
raise FileBrowserError("not_file", "Path is not a regular file", 400)
if stat_result.st_size > MAX_FILE_BYTES:
raise FileBrowserError("too_large", "File is too large", 413)
+ size = stat_result.st_size
+ # A media seek reads only the requested span from the already-validated fd.
+ byte_range = parse_byte_range(range_header, size)
with os.fdopen(fd, "rb", closefd=False) as handle:
- data = handle.read(MAX_FILE_BYTES + 1)
+ if byte_range is None:
+ data = handle.read(MAX_FILE_BYTES + 1)
+ else:
+ handle.seek(byte_range[0])
+ data = handle.read(byte_range[1] - byte_range[0] + 1)
finally:
os.close(fd)
except FileNotFoundError as exc:
@@ -666,7 +700,12 @@ def file_content(raw_path: str, *, download: bool = False) -> FileContent:
raise FileBrowserError("fs_error", str(exc), 400) from exc
if len(data) > MAX_FILE_BYTES:
raise FileBrowserError("too_large", "File is too large", 413)
- return FileContent(path=path, mime=mime, disposition=disposition, data=data)
+ if byte_range is not None:
+ # The file may have shrunk after fstat; report the span actually read.
+ byte_range = (byte_range[0], byte_range[0] + len(data) - 1) if data else None
+ if byte_range is None:
+ raise RangeNotSatisfiableError(size)
+ return FileContent(path=path, mime=mime, disposition=disposition, data=data, size=size, byte_range=byte_range)
def _audit_mutation(op: str, path: Path, **extra: Any) -> None:
diff --git a/core/media_types.py b/core/media_types.py
new file mode 100644
index 000000000..61dbcd4ff
--- /dev/null
+++ b/core/media_types.py
@@ -0,0 +1,54 @@
+"""Server-side audio/video content types shared by every file-serving route.
+
+``vibe/data/media_types.json`` is the one catalog of extensions the Web UI plays natively; the UI
+classifier (``ui/src/lib/filePreview.ts``) imports the same file, so the two cannot drift. Python's
+built-in ``mimetypes`` table omits several of them (``.flac``, ``.m4a``, ``.ogg``, ``.weba``, ``.m4v``,
+``.ogv`` …) unless the host ships a ``mime.types`` file, so a clean Linux install would serve them as
+``application/octet-stream`` attachments. Registering the catalog at import keeps the guessed type
+identical across hosts.
+"""
+
+from __future__ import annotations
+
+import json
+import mimetypes
+from importlib import resources
+
+MEDIA_TYPES_BY_EXT: dict[str, str] = json.loads(
+ resources.files("vibe").joinpath("data", "media_types.json").read_text(encoding="utf-8")
+)
+
+for _ext, _mime in MEDIA_TYPES_BY_EXT.items():
+ mimetypes.add_type(_mime, f".{_ext}")
+
+INLINE_SAFE_MEDIA_MAJOR_TYPES = {"audio", "video"}
+
+
+def is_inline_safe_type(mime: str | None, allowlist: set[str]) -> bool:
+ """Whether a response of ``mime`` may be served ``inline`` (always together with ``nosniff``).
+
+ Audio and video are inline by major type: sent with ``nosniff`` the browser can only treat
+ them as media, never as active content, so every format the Web UI player accepts streams
+ inline without a hand-kept alias list. Everything else (notably ``image/svg+xml`` and
+ ``text/html``) must be listed explicitly in ``allowlist``."""
+ base = (mime or "").split(";", 1)[0].strip().lower()
+ return base.split("/", 1)[0] in INLINE_SAFE_MEDIA_MAJOR_TYPES or base in allowlist
+
+
+_GENERIC_TYPES = {"", "application/octet-stream", "binary/octet-stream"}
+
+
+def resolve_media_row_type(stored: str | None, file_name: str) -> str:
+ """The content type to serve for a stored media row.
+
+ A row may carry a generic type: the browser declared none for an upload, or the row predates the
+ catalog registration above on a host whose ``mimetypes`` table lacked the extension. For those rows
+ the catalog extension decides, so a known audio/video file still plays inline. Only a catalog
+ (audio/video) guess replaces a generic type; any other stored value is served unchanged."""
+ base = (stored or "").split(";", 1)[0].strip().lower()
+ if base not in _GENERIC_TYPES:
+ return stored # type: ignore[return-value]
+ guessed = mimetypes.guess_type(file_name)[0]
+ if guessed and guessed.split("/", 1)[0] in INLINE_SAFE_MEDIA_MAJOR_TYPES:
+ return guessed
+ return stored or guessed or "application/octet-stream"
diff --git a/storage/media_service.py b/storage/media_service.py
index cb6890233..f4b686a64 100644
--- a/storage/media_service.py
+++ b/storage/media_service.py
@@ -20,6 +20,7 @@ from sqlalchemy import select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
+import core.media_types # noqa: F401 — registers audio/video types before guess_type
from storage.models import media_object_references, media_objects
logger = logging.getLogger(__name__)
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index e40c69e64..4190b40d3 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -2178,6 +2178,41 @@ def test_symlink_mutations_operate_on_link_not_target(tmp_path):
assert target.read_text(encoding="utf-8") == "target"
+ ("range_header", "status", "body", "content_range"),
+ [
+ (None, 200, bytes(range(256)), None),
+ ("bytes=16-31", 206, bytes(range(16, 32)), "bytes 16-31/256"),
+ ("bytes=250-", 206, bytes(range(250, 256)), "bytes 250-255/256"),
+ ("bytes=-4", 206, bytes(range(252, 256)), "bytes 252-255/256"),
+ ("bytes=240-999", 206, bytes(range(240, 256)), "bytes 240-255/256"),
+ ("bytes=256-", 416, b"", "bytes */256"),
+ ("bytes=0-1,4-5", 200, bytes(range(256)), None),
+ ("bytes=31-16", 200, bytes(range(256)), None),
+ ("bytes=" + "9" * 5000 + "-", 200, bytes(range(256)), None),
+ ("items=0-15", 200, bytes(range(256)), None),
+ ],
+)
+def test_file_content_serves_media_inline_with_byte_ranges(tmp_path, range_header, status, body, content_range):
+ """The Files preview's native <audio>/<video> loads and seeks through byte-range requests
+ (Safari refuses media without them), and a ``mimetypes`` alias like audio/x-wav stays inline."""
+ file_path = tmp_path / "voice.wav"
+ file_path.write_bytes(bytes(range(256)))
+ client = app.test_client()
+
+ response = client.get(
+ f"/api/files/content?path={file_path}", headers={"Range": range_header} if range_header else {}
+ )
+
+ assert response.status_code == status
+ assert response.content == body
+ assert response.headers.get("Content-Range") == content_range
+ assert response.headers["Accept-Ranges"] == "bytes"
+ if status != 416:
+ assert response.headers["Content-Type"].startswith("audio/")
+ assert response.headers["Content-Disposition"].startswith("inline;")
+
+
def test_http_routes_return_contract_and_headers(tmp_path):
file_path = tmp_path / "note.txt"
file_path.write_text("hello", encoding="utf-8")
diff --git a/tests/test_media_types.py b/tests/test_media_types.py
new file mode 100644
index 000000000..404453a7a
--- /dev/null
+++ b/tests/test_media_types.py
@@ -0,0 +1,31 @@
+"""Every extension the Web UI plays natively must be guessed as media, and served inline, by the server.
+
+The UI classifier and the server's type inference drifted twice (files the card offered to play were
+served as ``application/octet-stream`` attachments); both now read ``vibe/data/media_types.json``, and
+this holds the server side of that catalog to the inline contract on any host.
+"""
+
+from __future__ import annotations
+
+import mimetypes
+
+import pytest
+
+from core.file_browser_service import INLINE_SAFE_CONTENT_TYPES
+from core.media_types import MEDIA_TYPES_BY_EXT, is_inline_safe_type
+from vibe.ui_server import _INLINE_SAFE_MEDIA_TYPES
+
+
[email protected]("ext", sorted(MEDIA_TYPES_BY_EXT))
+def test_ui_playable_extension_is_guessed_as_media_and_served_inline(ext):
+ mime = mimetypes.guess_type(f"clip.{ext}")[0]
+
+ assert mime and mime.split("/", 1)[0] in {"audio", "video"}, (ext, mime)
+ assert is_inline_safe_type(mime, INLINE_SAFE_CONTENT_TYPES)
+ assert is_inline_safe_type(mime, _INLINE_SAFE_MEDIA_TYPES)
+
+
[email protected]("mime", ["image/svg+xml", "text/html", "application/xhtml+xml", "application/octet-stream", None])
+def test_active_or_unknown_types_are_not_inline_by_major_type(mime):
+ assert not is_inline_safe_type(mime, INLINE_SAFE_CONTENT_TYPES)
+ assert not is_inline_safe_type(mime, _INLINE_SAFE_MEDIA_TYPES)
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
index 219cf7a61..b149b1b54 100644
--- a/tests/test_workbench_media.py
+++ b/tests/test_workbench_media.py
@@ -191,6 +191,87 @@ def test_agent_download_and_metadata_preserve_real_filename(
engine.dispose()
+ ("filename", "content_type"),
+ [
+ ("voice.wav", None),
+ ("voice.m4a", None),
+ ("voice.aac", None),
+ ("voice.flac", None),
+ ("voice.opus", None),
+ ("upload.wav", "audio/vnd.wave"),
+ ("upload.mp3", "audio/mp3"),
+ ("upload.m4v", "video/x-m4v"),
+ ("legacy.flac", "application/octet-stream"),
+ ],
+)
+def test_media_serves_inline_with_range_for_the_web_player(
+ tmp_path, monkeypatch, filename, content_type, sqlite_schema_db_factory,
+):
+ """Media the Web UI offers a player for must stream inline (not force-download) so the native
+ <audio>/<video> element can load and seek it — whatever alias ``mimetypes`` guessed for an agent
+ file or the browser reported for an upload."""
+ from tests.ui_server_test_helpers import _save_config
+ from vibe import ui_server
+
+ _save_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ sqlite_schema_db_factory(db)
+ engine = create_sqlite_engine(db)
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: engine)
+ audio = tmp_path / filename
+ audio.write_bytes(bytes(range(256)))
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ if content_type:
+ token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="file", source="user_upload",
+ local_path=str(audio.resolve()), file_name=filename, content_type=content_type,
+ )
+ else:
+ rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=f"[memo]({audio.as_uri()})")
+ token = conn.execute(select(media_objects.c.token)).scalar_one()
+
+ client = ui_server.app.test_client()
+ response = client.get(f"/api/media/{token}")
+ assert response.status_code == 200
+ assert response.headers["Content-Type"].split("/", 1)[0] in {"audio", "video"}
+ disposition = Message()
+ disposition["Content-Disposition"] = response.headers["Content-Disposition"]
+ assert disposition.get_content_disposition() == "inline"
+ assert client.get(f"/api/media/{token}/meta").get_json()["content_type"] == response.headers["Content-Type"]
+ ranged = client.get(f"/api/media/{token}", headers={"Range": "bytes=16-31"})
+ assert ranged.status_code == 206
+ assert ranged.content == bytes(range(16, 32))
+ engine.dispose()
+
+
+def test_generic_media_row_is_reinferred_only_to_audio_or_video(tmp_path, monkeypatch, sqlite_schema_db_factory):
+ """A generic stored type falls back to the extension catalog, which only ever yields audio/video:
+ a generic-typed ``.html`` upload must still download, never render on this origin."""
+ from tests.ui_server_test_helpers import _save_config
+ from vibe import ui_server
+
+ _save_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ sqlite_schema_db_factory(db)
+ engine = create_sqlite_engine(db)
+ monkeypatch.setattr(ui_server, "_projects_engine", lambda: engine)
+ page = tmp_path / "page.html"
+ page.write_text("<script>alert(1)</script>", encoding="utf-8")
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ token = media_service.register(
+ conn, scope_id=scope_id, session_id="sess_x", kind="file", source="user_upload",
+ local_path=str(page.resolve()), file_name="page.html", content_type="application/octet-stream",
+ )
+
+ response = ui_server.app.test_client().get(f"/api/media/{token}")
+ assert response.headers["Content-Type"] == "application/octet-stream"
+ assert response.headers["Content-Disposition"].startswith("attachment;")
+ engine.dispose()
+
+
def test_uploaded_download_keeps_original_name_instead_of_storage_basename(tmp_path, monkeypatch, sqlite_schema_db_factory):
from tests.ui_server_test_helpers import _save_config
from vibe import ui_server
diff --git a/ui/src/components/ui/file-card.test.tsx b/ui/src/components/ui/file-card.test.tsx
new file mode 100644
index 000000000..8b2a18fa6
--- /dev/null
+++ b/ui/src/components/ui/file-card.test.tsx
@@ -0,0 +1,71 @@
+/* @vitest-environment jsdom */
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { FileCard } from './file-card';
+
+const mock = vi.hoisted(() => ({ apiFetch: vi.fn() }));
+vi.mock('@/lib/apiFetch', async (importOriginal) => ({ ...await importOriginal<typeof import('@/lib/apiFetch')>(), apiFetch: mock.apiFetch }));
+
+function serveMeta(meta: Record<string, unknown>) {
+ mock.apiFetch.mockResolvedValue(new Response(JSON.stringify(meta), { status: 200, headers: { 'Content-Type': 'application/json' } }));
+}
+
+afterEach(() => {
+ cleanup();
+ mock.apiFetch.mockReset();
+});
+
+describe('FileCard media', () => {
+ it('plays an audio attachment inline instead of offering the preview overlay', async () => {
+ serveMeta({ name: 'take-2.wav', ext: 'wav', content_type: 'audio/x-wav', size: 2048 });
+ const { container } = render(<FileCard href="/api/media/tok">Voice memo</FileCard>);
+
+ await waitFor(() => expect(screen.getByText(/WAV/)).toBeTruthy());
+ const audio = container.querySelector('audio');
+ expect(audio?.getAttribute('src')).toBe('/api/media/tok');
+ expect(audio?.hasAttribute('controls')).toBe(true);
+ expect(screen.queryByLabelText('chat.media.preview')).toBeNull();
+ expect(screen.getByLabelText('chat.media.download')).toBeTruthy();
+ });
+
+ it('never mounts a player on the label alone — only once /meta confirms audio', async () => {
+ let resolve!: (r: Response) => void;
+ mock.apiFetch.mockReturnValue(new Promise<Response>((r) => { resolve = r; }));
+ const { container } = render(<FileCard href="/api/media/tok">report.mp3</FileCard>);
+
+ expect(container.querySelector('audio')).toBeNull();
+ resolve(new Response(JSON.stringify({ name: 'report.pdf', ext: 'pdf', content_type: 'application/pdf', size: 1024 }), { status: 200 }));
+ await waitFor(() => expect(screen.getByText(/PDF/)).toBeTruthy());
+ expect(container.querySelector('audio')).toBeNull();
+ expect(screen.getByLabelText('chat.media.preview')).toBeTruthy();
+ });
+
+ it('drops the previous attachment\'s audio kind when a reused card switches to a new URL', async () => {
+ serveMeta({ name: 'take-2.wav', ext: 'wav', content_type: 'audio/x-wav', size: 2048 });
+ const { container, rerender } = render(<FileCard href="/api/media/one">Attachment</FileCard>);
+ await waitFor(() => expect(container.querySelector('audio')).toBeTruthy());
+
+ mock.apiFetch.mockReturnValue(new Promise<Response>(() => {}));
+ rerender(<FileCard href="/api/media/two">Attachment</FileCard>);
+
+ expect(container.querySelector('audio')).toBeNull();
+ });
+
+ it('keeps video behind the preview control rather than autoloading it in the card', async () => {
+ serveMeta({ name: 'demo.mp4', ext: 'mp4', content_type: 'video/mp4', size: 4096 });
+ const { container } = render(<FileCard href="/api/media/tok">Demo</FileCard>);
+
+ await waitFor(() => expect(screen.getByLabelText('chat.media.preview')).toBeTruthy());
+ expect(container.querySelector('audio, video')).toBeNull();
+ });
+
+ it('never mounts a player for a non-proxy URL', () => {
+ const { container } = render(<FileCard href="https://example.com/a.mp3">a.mp3</FileCard>);
+
+ expect(mock.apiFetch).not.toHaveBeenCalled();
+ expect(container.querySelector('audio')).toBeNull();
+ expect(screen.getByLabelText('chat.media.preview')).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsx
index 58c25e793..8d95ff447 100644
--- a/ui/src/components/ui/file-card.tsx
+++ b/ui/src/components/ui/file-card.tsx
@@ -1,6 +1,6 @@
import * as React from 'react';
import { useTranslation } from 'react-i18next';
-import { Download, Eye, File, FileArchive, FileText, Image as ImageIcon } from 'lucide-react';
+import { Download, Eye, File, FileArchive, FileAudio, FileText, FileVideo, Image as ImageIcon } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -8,7 +8,7 @@ import { apiFetch } from '@/lib/apiFetch';
import { isProxyMediaUrl } from '@/lib/mediaProxy';
import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';
import { useFileViewer } from '@/components/ui/file-viewer-context';
-import { previewRenderKind, formatBytes } from '@/lib/filePreview';
+import { mediaKind, previewRenderKind, formatBytes } from '@/lib/filePreview';
import { cn } from '@/lib/utils';
// Download card for an agent-reply file that was rewritten to the same-origin
@@ -25,6 +25,9 @@ const DOC_EXT = new Set(['doc', 'docx', 'txt', 'md', 'rtf', 'csv', 'json', 'log'
// Literal class strings (Tailwind can't see interpolated names) so the tint
// utilities are actually generated.
function kindOf(ext: string): { Icon: LucideIcon; tile: string } {
+ const media = mediaKind('', null, ext);
+ if (media === 'audio') return { Icon: FileAudio, tile: 'bg-violet/15 text-violet-ink' };
+ if (media === 'video') return { Icon: FileVideo, tile: 'bg-cyan/15 text-cyan-ink' };
if (IMAGE_EXT.has(ext)) return { Icon: ImageIcon, tile: 'bg-cyan/15 text-cyan-ink' };
if (ARCHIVE_EXT.has(ext)) return { Icon: FileArchive, tile: 'bg-gold/15 text-gold-ink' };
if (ext === 'pdf') return { Icon: FileText, tile: 'bg-cyan/15 text-cyan-ink' };
@@ -46,7 +49,10 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =
const { t } = useTranslation();
const viewer = useFileViewer();
const label = nodeText(children).trim();
- const [meta, setMeta] = React.useState<Meta | null>(null);
+ // Metadata is keyed by the URL it describes: a reused card whose ``href`` changes must not render the
+ // previous attachment's kind (e.g. mount a player on an unrelated token) before its own /meta lands.
+ const [resolved, setResolved] = React.useState<{ href: string; meta: Meta } | null>(null);
+ const meta = resolved?.href === href ? resolved.meta : null;
React.useEffect(() => {
// Only fetch metadata for our own media proxy — never auto-call an arbitrary
@@ -56,7 +62,7 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =
apiFetch(`${href}/meta`)
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
- if (alive && data) setMeta(data);
+ if (alive && data) setResolved({ href, meta: data });
})
.catch(() => {});
return () => {
@@ -76,46 +82,56 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =
const proxy = isProxyMediaUrl(href);
// Gate the preview eye with the shared render classifier (not just the text-only previewKind) so the
// chat offers in-app preview for every kind the kernel can render — PDF / Office / image included.
- const previewable = previewRenderKind(meta?.name || label, meta?.content_type, meta?.ext) !== null;
+ const renderKind = previewRenderKind(meta?.name || label, meta?.content_type, meta?.ext);
+ // Audio plays right in the card (a compact native player under the title row) — opening an overlay
+ // just to press play adds a step. It needs the proxy URL (same-origin, cookie-authenticated, Range
+ // capable) and the resolved /meta: a label alone is caller-controlled Markdown text, so a player is
+ // never mounted (and never starts fetching) on the label's say-so. The eye stays for every other
+ // previewable kind, including video.
+ const inlineAudio = proxy && meta !== null && renderKind === 'audio';
+ const previewable = renderKind !== null && !inlineAudio;
return (
- <span className="my-1 inline-flex min-w-[240px] max-w-full items-center gap-3 rounded-[10px] border border-border bg-surface-2 px-3 py-2.5 align-middle no-underline">
- <span className={cn('grid size-10 shrink-0 place-items-center rounded-lg', tile)}>
- <Icon className="size-5" />
- </span>
- <span className="flex min-w-0 flex-col">
- <span className="truncate text-[13px] font-semibold text-foreground">{title}</span>
- {metaLine && <span className="font-mono text-[10px] text-muted">{metaLine}</span>}
- </span>
- <span className="ml-auto flex shrink-0 items-center gap-1.5">
- {previewable &&
- (proxy && viewer ? (
- <Button
- variant="ghost"
- size="icon"
- className="size-8"
- aria-label={t('chat.media.preview')}
- onClick={() => viewer.open({ url: href, name: meta?.name || label })}
- >
- <Eye className="size-4" />
- </Button>
- ) : (
- <Button asChild variant="ghost" size="icon" className="size-8" aria-label={t('chat.media.preview')}>
- <a href={href} target="_blank" rel="noopener noreferrer">
+ <span className="my-1 inline-flex min-w-[240px] max-w-full flex-col gap-2 rounded-[10px] border border-border bg-surface-2 px-3 py-2.5 align-middle no-underline">
+ <span className="flex min-w-0 items-center gap-3">
+ <span className={cn('grid size-10 shrink-0 place-items-center rounded-lg', tile)}>
+ <Icon className="size-5" />
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate text-[13px] font-semibold text-foreground">{title}</span>
+ {metaLine && <span className="font-mono text-[10px] text-muted">{metaLine}</span>}
+ </span>
+ <span className="ml-auto flex shrink-0 items-center gap-1.5">
+ {previewable &&
+ (proxy && viewer ? (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8"
+ aria-label={t('chat.media.preview')}
+ onClick={() => viewer.open({ url: href, name: meta?.name || label })}
+ >
<Eye className="size-4" />
- </a>
- </Button>
- ))}
- <Button asChild variant="ghost" size="icon" className="size-8 text-mint-ink" aria-label={t('chat.media.download')}>
- <a
- href={mediaDownloadHref(href)}
- download
- onClick={(e) => handleMediaDownloadClick(e, href, meta?.name || label)}
- >
- <Download className="size-4" />
- </a>
- </Button>
+ </Button>
+ ) : (
+ <Button asChild variant="ghost" size="icon" className="size-8" aria-label={t('chat.media.preview')}>
+ <a href={href} target="_blank" rel="noopener noreferrer">
+ <Eye className="size-4" />
+ </a>
+ </Button>
+ ))}
+ <Button asChild variant="ghost" size="icon" className="size-8 text-mint-ink" aria-label={t('chat.media.download')}>
+ <a
+ href={mediaDownloadHref(href)}
+ download
+ onClick={(e) => handleMediaDownloadClick(e, href, meta?.name || label)}
+ >
+ <Download className="size-4" />
+ </a>
+ </Button>
+ </span>
</span>
+ {inlineAudio && <audio controls preload="metadata" src={href} aria-label={title} className="h-9 w-full min-w-0" />}
</span>
);
};
diff --git a/ui/src/components/ui/file-preview.test.tsx b/ui/src/components/ui/file-preview.test.tsx
index ae6c374a0..fe14ffeb4 100644
--- a/ui/src/components/ui/file-preview.test.tsx
+++ b/ui/src/components/ui/file-preview.test.tsx
@@ -17,6 +17,27 @@ afterEach(() => {
resetEditorFontSize();
});
+describe('FilePreview media', () => {
+ it.each([
+ ['voice.wav', 'audio'],
+ ['clip.mp4', 'video'],
+ ])('plays %s with a native <%s> pointed at the content URL', (name, tag) => {
+ const { container } = render(<FilePreview source={{ name, url: '/api/media/tok' }} />);
+ const el = container.querySelector<HTMLMediaElement>(tag);
+ expect(el?.getAttribute('src')).toBe('/api/media/tok');
+ expect(el?.hasAttribute('controls')).toBe(true);
+ });
+
+ it('falls back to the failure message when the browser cannot load the media', () => {
+ const { container } = render(<FilePreview source={{ name: 'voice.wav', url: '/api/media/tok' }} />);
+ act(() => {
+ container.querySelector('audio')?.dispatchEvent(new Event('error'));
+ });
+ expect(container.querySelector('audio')).toBeNull();
+ expect(container.textContent).toContain('preview.failed');
+ });
+});
+
describe('FilePreview font size', () => {
it('tracks the Editor font-size preference for Markdown previews', () => {
const { container } = render(
diff --git a/ui/src/components/ui/file-preview.tsx b/ui/src/components/ui/file-preview.tsx
index f0a059ada..462cfb911 100644
--- a/ui/src/components/ui/file-preview.tsx
+++ b/ui/src/components/ui/file-preview.tsx
@@ -40,7 +40,7 @@ export type PreviewSource = {
/** Server-supplied extension (e.g. chat /meta `ext`) — used to classify when the name is just a
* descriptive label whose suffix doesn't match the real file type. */
ext?: string | null;
- /** Same-origin, apiFetch-able content URL. Required for image / pdf / office; default fetch for text. */
+ /** Same-origin, apiFetch-able content URL. Required for image / media / pdf / office; default fetch for text. */
url?: string;
/** In-memory text (the editor's live buffer). Used for text-derived kinds instead of fetching `url`. */
text?: string;
@@ -68,6 +68,8 @@ export const FilePreview: React.FC<{ source: PreviewSource; className?: string;
if (!kind) return <Centered className={className}>{t('preview.unsupported')}</Centered>;
if (kind === 'image')
return source.url ? <ImageBody src={source.url} name={source.name} className={className} onDownload={onDownload} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
+ if (kind === 'audio' || kind === 'video')
+ return source.url ? <MediaView key={source.url} kind={kind} src={source.url} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
if (kind === 'pdf')
return source.url ? <PdfView url={source.url} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;
if (kind === 'docx' || kind === 'xlsx' || kind === 'pptx') {
@@ -311,6 +313,28 @@ const PdfView: React.FC<{ url: string; className?: string }> = ({ url, className
return <iframe title={t('preview.title')} src={url} className={clsx('h-full w-full border-0 bg-white', className)} />;
};
+// ── Audio / Video ────────────────────────────────────────────────────────────
+// Native players pointed straight at the same-origin content URL (like <img> and the PDF iframe), so
+// the session cookie authenticates and the browser streams with Range requests instead of buffering
+// the whole file into a blob. A decode/load failure falls back to the shared failure message (keyed by
+// `src` at the call site, so a new file starts unfailed).
+const MediaView: React.FC<{ kind: 'audio' | 'video'; src: string; className?: string }> = ({ kind, src, className }) => {
+ const { t } = useTranslation();
+ const [failed, setFailed] = React.useState(false);
+ if (failed) return <Centered className={className}>{t('preview.failed')}</Centered>;
+ if (kind === 'audio')
+ return (
+ <Centered className={className}>
+ <audio controls preload="metadata" src={src} onError={() => setFailed(true)} className="w-full max-w-md" />
+ </Centered>
+ );
+ return (
+ <div className={clsx('grid h-full min-h-0 place-items-center bg-black', className)}>
+ <video controls playsInline preload="metadata" src={src} onError={() => setFailed(true)} className="max-h-full max-w-full" />
+ </div>
+ );
+};
+
// ── HTML ──────────────────────────────────────────────────────────────────────
// Render the markup in a fully sandboxed iframe: `sandbox=""` disables scripts, same-origin access,
// forms, and popups. But sandbox does NOT stop subresource fetches — a `<img src="https://…">` or CSS
diff --git a/ui/src/lib/filePreview.test.ts b/ui/src/lib/filePreview.test.ts
index 85b8e112c..e06eb944e 100644
--- a/ui/src/lib/filePreview.test.ts
+++ b/ui/src/lib/filePreview.test.ts
@@ -1,12 +1,14 @@
import { describe, expect, it } from 'vitest';
-import { isEditableFile, isEditableMeta, PREVIEW_MAX_BYTES, previewOverlayKind, previewWindowKind } from './filePreview';
+import { isEditableFile, isEditableMeta, PREVIEW_MAX_BYTES, previewOverlayKind, previewRenderKind, previewWindowKind } from './filePreview';
const entry = (name: string, size = 100) => ({ kind: 'file', name, size });
describe('File Browser open classification', () => {
it.each([
['photo.png', 'image'],
+ ['voice.wav', 'audio'],
+ ['clip.mp4', 'video'],
['document.pdf', 'pdf'],
['document.docx', 'docx'],
['notes.md', 'markdown'],
@@ -37,3 +39,46 @@ describe('File Browser open classification', () => {
expect(previewWindowKind(entry('large.csv', PREVIEW_MAX_BYTES + 1))).toBeNull();
});
});
+
+describe('audio / video preview classification', () => {
+ it.each([
+ ...['wav', 'mp3', 'm4a', 'aac', 'ogg', 'oga', 'opus', 'flac', 'weba'].map((ext) => [`clip.${ext}`, 'audio'] as const),
+ ...['mp4', 'm4v', 'webm', 'mov', 'ogv'].map((ext) => [`clip.${ext}`, 'video'] as const),
+ ])('renders %s as %s', (name, kind) => {
+ expect(previewRenderKind(name)).toBe(kind);
+ });
+
+ it.each(['clip.aiff', 'clip.aif', 'voice.silk', 'voice.amr'])('does not offer a player for undecodable %s', (name) => {
+ expect(previewRenderKind(name)).toBeNull();
+ });
+
+ it.each([
+ ['audio/x-wav', 'audio'],
+ ['audio/mp4a-latm', 'audio'],
+ ['audio/mpeg; charset=binary', 'audio'],
+ ['video/quicktime', 'video'],
+ ['audio/x-aiff', null],
+ ['audio/silk', null],
+ ])('classifies a label-only chat link by content type %s', (mime, kind) => {
+ expect(previewRenderKind('Listen here', mime)).toBe(kind);
+ });
+
+ it.each([
+ ['clip.ogg', null, 'audio'],
+ ['clip.ogg', 'video/ogg', 'video'],
+ ['clip.webm', null, 'video'],
+ ['clip.webm', 'audio/webm', 'audio'],
+ ])('lets an explicit content type pick the track kind of container %s (%s)', (name, mime, kind) => {
+ expect(previewRenderKind(name, mime)).toBe(kind);
+ });
+
+ it('routes media within the content cap to read-only preview and oversized media to download', () => {
+ expect(previewOverlayKind(entry('voice.wav'))).toBe('audio');
+ expect(previewOverlayKind(entry('clip.mov', 25 * 1024 * 1024 + 1))).toBeNull();
+ });
+
+ it('trusts the server ext over a misleading label suffix', () => {
+ expect(previewRenderKind('notes.txt', 'audio/x-wav', 'wav')).toBe('audio');
+ expect(previewRenderKind('song.mp3', 'application/pdf', 'pdf')).toBe('pdf');
+ });
+});
diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.ts
index e93bce9ae..767a52541 100644
--- a/ui/src/lib/filePreview.ts
+++ b/ui/src/lib/filePreview.ts
@@ -3,6 +3,8 @@
// language in the FileViewer. Keep the language ids here in sync with the
// grammar loaders in ``highlighter.ts``.
+import mediaCatalog from '../../../vibe/data/media_types.json';
+
export type PreviewKind = 'markdown' | 'text' | 'json' | 'csv' | 'code' | 'source';
// Refuse to preview files larger than this (fetch the bytes into the page) —
@@ -167,15 +169,46 @@ export function docPreviewKind(name: string, mime?: string | null, serverExt?: s
return OFFICE_MIME[m] ?? null;
}
+// Audio / video a native <audio> / <video> element can play. Deliberately an allowlist rather than
+// `audio/*`: formats browsers can't decode (AIFF, WeChat SILK, AMR) must fall back to download instead
+// of opening a broken player. An unambiguous media ext decides; Ogg and WebM containers hold either
+// audio or video, so for those an explicit content type wins and the ext only supplies the default.
+// Otherwise the content type (including the aliases Python's ``mimetypes`` emits, e.g. ``audio/x-wav``)
+// classifies a label-only chat link. The playable extensions come from ``vibe/data/media_types.json``,
+// the same catalog ``core/media_types.py`` registers server-side, so every ext offered here is guessed as
+// audio/* or video/* and served inline there (Vite inlines the JSON at build time).
+export type MediaKind = 'audio' | 'video';
+const CONTAINER_EXTS = new Set(['ogg', 'webm']);
+const MEDIA_EXT: Record<string, MediaKind> = Object.fromEntries(
+ Object.entries(mediaCatalog as Record<string, string>).map(([ext, mime]) => [ext, mime.startsWith('video/') ? 'video' : 'audio']),
+);
+const AUDIO_MIME = new Set([
+ 'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/x-wav', 'audio/wave', 'audio/vnd.wave',
+ 'audio/mp4', 'audio/x-m4a', 'audio/mp4a-latm', 'audio/aac', 'audio/x-aac',
+ 'audio/ogg', 'audio/opus', 'audio/flac', 'audio/x-flac', 'audio/webm',
+]);
+const VIDEO_MIME = new Set(['video/mp4', 'video/webm', 'video/quicktime', 'video/ogg', 'video/x-m4v']);
+
+export function mediaKind(name: string, mime?: string | null, serverExt?: string | null): MediaKind | null {
+ const ext = effectiveExt(name, serverExt);
+ if (MEDIA_EXT[ext] && !CONTAINER_EXTS.has(ext)) return MEDIA_EXT[ext];
+ const m = (mime || '').split(';')[0].trim().toLowerCase();
+ if (AUDIO_MIME.has(m)) return 'audio';
+ if (VIDEO_MIME.has(m)) return 'video';
+ return CONTAINER_EXTS.has(ext) ? (MEDIA_EXT[ext] ?? null) : null;
+}
+
// ── Unified preview dispatch ────────────────────────────────────────────────
// HOW a file renders in the shared <FilePreview> kernel (one classifier for the File Browser, the
-// editor preview, and the chat viewer). Combines imageKind (raster/svg) + html + docPreviewKind
+// editor preview, and the chat viewer). Combines imageKind (raster/svg) + mediaKind (audio/video) + html + docPreviewKind
// (office/pdf) + previewKind (text). 'code' is the catch-all for highlightable text — including
// non-HTML markup (xml/vue/svelte) and plain text (highlights to nothing). Order matters: images and
// HTML are decided before the text classifier so an .svg renders as an image, not edited source.
export type PreviewRenderKind =
| 'image'
| 'svg'
+ | 'audio'
+ | 'video'
| 'html'
| 'pdf'
| 'docx'
@@ -192,6 +225,8 @@ export function previewRenderKind(name: string, mime?: string | null, serverExt?
const img = imageKind(name, mime, serverExt);
if (img === 'raster') return 'image';
if (img === 'svg') return 'svg';
+ const media = mediaKind(name, mime, serverExt);
+ if (media) return media;
const ext = effectiveExt(name, serverExt);
const m = (mime || '').split(';')[0].trim().toLowerCase();
if (HTML_EXT.has(ext) || m === 'text/html') return 'html';
@@ -216,14 +251,15 @@ export function editorPreviewKind(name: string): EditorPreviewKind | null {
return null;
}
-// Non-editable rich files that use a read-only preview tab inside Editor. Keep editable formats out
-// of this set so "Open in Editor" always lands on a source tab.
-export type PreviewOverlayKind = 'image' | 'pdf' | 'docx' | 'xlsx' | 'pptx';
+// Non-editable rich files that use a read-only preview tab inside Editor (and open in the Files
+// Preview / chat local-file viewer). Keep editable formats out of this set so "Open in Editor" always
+// lands on a source tab. Media shares the 25 MB cap: `/api/files/content` refuses larger files.
+export type PreviewOverlayKind = 'image' | 'audio' | 'video' | 'pdf' | 'docx' | 'xlsx' | 'pptx';
export function previewOverlayKind(entry: { kind: string; name: string; size: number | null }): PreviewOverlayKind | null {
if (entry.kind !== 'file') return null;
if (entry.size != null && entry.size > DOC_PREVIEW_MAX_BYTES) return null;
const rk = previewRenderKind(entry.name);
- return rk === 'image' || rk === 'pdf' || rk === 'docx' || rk === 'xlsx' || rk === 'pptx' ? rk : null;
+ return rk === 'image' || rk === 'audio' || rk === 'video' || rk === 'pdf' || rk === 'docx' || rk === 'xlsx' || rk === 'pptx' ? rk : null;
}
// What the Files app opens in Preview: a standalone window on desktop and its in-page overlay on
diff --git a/ui/vite.config.ts b/ui/vite.config.ts
index f54b9f2e3..ddf9773e1 100644
--- a/ui/vite.config.ts
+++ b/ui/vite.config.ts
@@ -53,7 +53,7 @@ export default defineConfig({
// one tracked file each rather than from a copy per reader:
// ``src/lib/messageTypes.ts`` imports ``vibe/message_types.json``, and
// ``src/components/settings/models/apiKeyVendors.ts`` imports
- // ``vibe/data/api_key_vendors.json``.
+ // ``vibe/data/api_key_vendors.json``, and ``vibe/data/media_types.json``.
// ``ui/package-lock.json`` makes Vite infer ``ui/`` as the workspace root, which
// would put both files outside the dev server's default allow list; production
// builds inline the JSON and are unaffected. Allow the UI root plus those exact
@@ -63,6 +63,7 @@ export default defineConfig({
fileURLToPath(new URL('.', import.meta.url)),
fileURLToPath(new URL('../vibe/message_types.json', import.meta.url)),
fileURLToPath(new URL('../vibe/data/api_key_vendors.json', import.meta.url)),
+ fileURLToPath(new URL('../vibe/data/media_types.json', import.meta.url)),
],
},
proxy: {
diff --git a/vibe/data/media_types.json b/vibe/data/media_types.json
new file mode 100644
index 000000000..45342a290
--- /dev/null
+++ b/vibe/data/media_types.json
@@ -0,0 +1,16 @@
+{
+ "wav": "audio/wav",
+ "mp3": "audio/mpeg",
+ "m4a": "audio/mp4",
+ "aac": "audio/aac",
+ "oga": "audio/ogg",
+ "ogg": "audio/ogg",
+ "opus": "audio/ogg",
+ "flac": "audio/flac",
+ "weba": "audio/webm",
+ "mp4": "video/mp4",
+ "m4v": "video/mp4",
+ "mov": "video/quicktime",
+ "webm": "video/webm",
+ "ogv": "video/ogg"
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bce71d834..f799a5d47 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -10418,24 +10418,29 @@ async def files_content(starlette_request: FastAPIRequest):
async def handler():
from core import file_browser_service
+ headers = {
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ "Cache-Control": "private, no-store",
+ "Accept-Ranges": "bytes",
+ }
try:
content = await asyncio.to_thread(
file_browser_service.file_content,
request.args.get("path") or "",
download=request.args.get("download") == "1",
+ range_header=starlette_request.headers.get("range"),
)
+ except file_browser_service.RangeNotSatisfiableError as exc:
+ return FastAPIResponse(status_code=416, headers={**headers, "Content-Range": f"bytes */{exc.size}"})
except Exception as exc:
return _file_browser_error_response(exc)
- return FastAPIResponse(
- content=content.data,
- media_type=content.mime,
- headers={
- "X-Content-Type-Options": "nosniff",
- "Referrer-Policy": "no-referrer",
- "Cache-Control": "private, no-store",
- "Content-Disposition": f"{content.disposition}; filename*=UTF-8''{quote(content.path.name)}",
- },
- )
+ headers["Content-Disposition"] = f"{content.disposition}; filename*=UTF-8''{quote(content.path.name)}"
+ if content.byte_range is None:
+ return FastAPIResponse(content=content.data, media_type=content.mime, headers=headers)
+ start, end = content.byte_range
+ headers["Content-Range"] = f"bytes {start}-{end}/{content.size}"
+ return FastAPIResponse(content=content.data, status_code=206, media_type=content.mime, headers=headers)
return await _dispatch_native_ui_request(starlette_request, handler)
@@ -10791,7 +10796,8 @@ async def files_search_undo(starlette_request: FastAPIRequest):
return await _dispatch_native_ui_request(starlette_request, handler)
-# Content types the media proxy is willing to serve ``inline``. Anything else —
+# Content types the media proxy is willing to serve ``inline``, plus every audio/* and
+# video/* type (``core.media_types.is_inline_safe_type``). Anything else —
# text/html, image/svg+xml, xml, application/octet-stream, unknown — is forced to
# ``attachment`` so a preview-open of agent-produced ACTIVE content can't execute
# script on the UI origin (``nosniff`` doesn't help when the type IS active).
@@ -10808,18 +10814,6 @@ _INLINE_SAFE_MEDIA_TYPES = {
"image/heif",
"application/pdf",
"text/plain",
- "audio/mpeg",
- "audio/mp4",
- "audio/aac",
- "audio/ogg",
- "audio/wav",
- "audio/webm",
- "audio/flac",
- "audio/x-m4a",
- "video/mp4",
- "video/webm",
- "video/ogg",
- "video/quicktime",
}
@@ -10954,7 +10948,9 @@ def _registered_media_response(
# file, refuse (closes the mint→click TOCTOU window).
if str(candidate) != stored or not candidate.is_file():
return jsonify({"error": "not_found"}), 404
- mime_type = row.get("content_type") or mimetypes.guess_type(str(candidate))[0] or "application/octet-stream"
+ from core.media_types import is_inline_safe_type, resolve_media_row_type
+
+ mime_type = resolve_media_row_type(row.get("content_type"), str(candidate))
response = send_file(candidate, mimetype=mime_type)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["Referrer-Policy"] = "no-referrer"
@@ -10965,8 +10961,9 @@ def _registered_media_response(
filename = row.get("file_name") or candidate.name
# Force download for non-allowlisted (active) types even without ?download=1,
# so previewing an agent-produced HTML/SVG can't run script on this origin.
- base_ct = mime_type.split(";", 1)[0].strip().lower()
- force_download = request.args.get("download") == "1" or base_ct not in _INLINE_SAFE_MEDIA_TYPES
+ # The same ``mime_type`` is sent as Content-Type (with nosniff), so an inline response is always
+ # rendered as exactly the type it was judged by — even when an upload's declared type is wrong.
+ force_download = request.args.get("download") == "1" or not is_inline_safe_type(mime_type, _INLINE_SAFE_MEDIA_TYPES)
disposition = "attachment" if force_download else "inline"
response.headers["Content-Disposition"] = f"{disposition}; filename*=UTF-8''{quote(filename)}"
return response
@@ -10977,6 +10974,7 @@ def media_meta(token: str):
"""Lightweight metadata for a media token so the UI file card can show the
name / type / size without downloading the file. Same token gate as the
file route."""
+ from core.media_types import resolve_media_row_type
from storage import media_service
engine = _projects_engine()
@@ -10990,7 +10988,7 @@ def media_meta(token: str):
{
"kind": row.get("kind"),
"name": row.get("file_name"),
- "content_type": row.get("content_type"),
+ "content_type": resolve_media_row_type(row.get("content_type"), row.get("file_name") or ""),
"ext": row.get("file_ext"),
"size": row.get("size_bytes"),
"width": row.get("width_px"),