Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(chat): render provider-neutral image video and audio outputs

rubenluetke10-beepa9537c06316f
diff --git a/jarvis/agent_chat/media.py b/jarvis/agent_chat/media.py
new file mode 100644
index 0000000000..c3c2ae3557
--- /dev/null
+++ b/jarvis/agent_chat/media.py
@@ -0,0 +1,466 @@
+"""Provider-neutral media receipts using the existing Markdown event contract.
+
+Only explicitly returned files inside the chat workspace are archived. Remote
+URLs stay remote: this code never fetches an arbitrary tool-supplied address.
+Binary tool content is removed from the persisted debug output after archiving.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import hashlib
+import json
+import os
+import re
+import tempfile
+from pathlib import Path
+from typing import Any
+from urllib.parse import quote, unquote, urlsplit
+
+from jarvis.missions.standalone_run import write_marker
+
+MEDIA_TYPES = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".avif": "image/avif",
+ ".svg": "image/svg+xml",
+ ".bmp": "image/bmp",
+ ".ico": "image/x-icon",
+ ".tif": "image/tiff",
+ ".tiff": "image/tiff",
+ ".heic": "image/heic",
+ ".heif": "image/heif",
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".mov": "video/quicktime",
+ ".m4v": "video/mp4",
+ ".ogv": "video/ogg",
+ ".avi": "video/x-msvideo",
+ ".mkv": "video/x-matroska",
+ ".mpeg": "video/mpeg",
+ ".mpg": "video/mpeg",
+ ".wmv": "video/x-ms-wmv",
+ ".mp3": "audio/mpeg",
+ ".wav": "audio/wav",
+ ".ogg": "audio/ogg",
+ ".m4a": "audio/mp4",
+ ".flac": "audio/flac",
+ ".aac": "audio/aac",
+}
+MAX_FILE_BYTES = 512 * 1024 * 1024
+MAX_INLINE_BYTES = 24 * 1024 * 1024
+MAX_REFERENCES = 128
+_EXT = "|".join(re.escape(ext[1:]) for ext in MEDIA_TYPES)
+_LINK = re.compile(r"(!?\[[^\]\n]*\]\()(<[^>\n]+>|[^)\n]+)(\))")
+_RAW = re.compile(
+ rf"(?<![^\s\"'`(=])(?:https?://|file:///|[A-Za-z]:[/\\]|\./|/)[^\s<>\"'`]+?\.(?:{_EXT})(?:\?[^\s<>\"'`)]+)?(?=$|[\s<>\"'`)])",
+ re.I,
+)
+_BARE = re.compile(rf"(?<![\w:/\\])(?:[\w.-]+[/\\])*[\w.-]+\.(?:{_EXT})(?=$|[\s\"'`),])", re.I)
+_QUOTED = re.compile(rf"[\"'`]([^\"'`\r\n]+\.(?:{_EXT}))[\"'`]", re.I)
+_MIME_SUFFIX = {mime: ext for ext, mime in reversed(list(MEDIA_TYPES.items()))}
+_REF_KEYS = {
+ "url",
+ "src",
+ "uri",
+ "path",
+ "file",
+ "file_path",
+ "savedpath",
+ "saved_path",
+ "image_url",
+ "video_url",
+ "audio_url",
+ "output_file",
+ "output_path",
+ "image_path",
+ "video_path",
+}
+
+
+def media_type(reference: str, hint: str = "") -> str | None:
+ if hint in _MIME_SUFFIX:
+ return hint
+ if reference.startswith("data:"):
+ mime = reference[5:].split(";", 1)[0]
+ return mime if mime in _MIME_SUFFIX else None
+ try:
+ normalized = reference.replace("\\", "/")
+ path = (
+ unquote(urlsplit(normalized).path)
+ if normalized.lower().startswith(("http:", "https:", "file:"))
+ or normalized.startswith("/api/")
+ else normalized
+ )
+ except ValueError:
+ return None
+ path = re.sub(r"/(download|raw|view)$", "", path)
+ return MEDIA_TYPES.get(Path(path).suffix.lower())
+
+
+def display_url(url: str, mime: str) -> str:
+ if media_type(url):
+ return url
+ return url + ("&" if "#" in url else "#") + "jarvis-media=" + quote(mime, safe="")
+
+
+def media_markdown(url: str, mime: str) -> str:
+ kind = mime.split("/", 1)[0]
+ return ("!" if kind == "image" else "") + f"[{kind}](<{display_url(url, mime)}>)"
+
+
+def content_markdown(blocks: list[Any], receipts: dict[str, str]) -> str:
+ parts: list[str] = []
+ for block in blocks:
+ if isinstance(block, dict) and block.get("type") == "text":
+ parts.append(str(block.get("text", "")))
+ continue
+ urls: list[str] = []
+
+ def visit(value: Any, urls: list[str] = urls) -> None:
+ if isinstance(value, str) and value in receipts and value not in urls:
+ urls.append(value)
+ elif isinstance(value, dict):
+ for child in value.values():
+ visit(child)
+ elif isinstance(value, list):
+ for child in value:
+ visit(child)
+
+ visit(block)
+ parts.extend(media_markdown(url, receipts[url]) for url in urls)
+ return "\n\n".join(part for part in parts if part)
+
+
+class MediaNormalizer:
+ def __init__(self, cwd: Path, outputs_root: Path, scope: str) -> None:
+ self.cwd = cwd.expanduser().resolve()
+ self.outputs_root = outputs_root.resolve()
+ self.scope = scope
+ self.receipts: dict[str, str] = {}
+ self.errors: list[str] = []
+ self._resolved: dict[str, str] = {}
+
+ def _remember(self, url: str, mime: str) -> str:
+ if len(self.receipts) >= MAX_REFERENCES and url not in self.receipts:
+ raise ValueError("Too many media files in one tool result")
+ self.receipts[url] = mime
+ return url
+
+ def _archive(self, handle: Any, suffix: str, expected: os.stat_result | None = None) -> str:
+ self.outputs_root.mkdir(parents=True, exist_ok=True)
+ # Staging is outside the deliverable subtree, so the gallery cannot
+ # expose a half-written video while it is being copied.
+ with tempfile.TemporaryDirectory(prefix=".chat-media-", dir=self.outputs_root) as temp:
+ staged = Path(temp) / ("media" + suffix)
+ digest = hashlib.sha256(self.scope.encode())
+ total = 0
+ with staged.open("wb") as target:
+ while chunk := handle.read(1024 * 1024):
+ total += len(chunk)
+ if total > MAX_FILE_BYTES:
+ raise ValueError("Media file exceeds the 512 MiB import limit")
+ digest.update(chunk)
+ target.write(chunk)
+ if total == 0:
+ raise ValueError("Media file is empty")
+ if expected is not None:
+ actual = os.fstat(handle.fileno())
+ if (expected.st_size, expected.st_mtime_ns, expected.st_ino) != (
+ actual.st_size,
+ actual.st_mtime_ns,
+ actual.st_ino,
+ ):
+ raise ValueError("Media file changed while being imported")
+ key = digest.hexdigest()[:24]
+ run = self.outputs_root / f"chat-media-{key}"
+ files = run / "tasks" / "chat" / "artifacts" / "files"
+ if run.resolve() != run or not files.resolve().is_relative_to(run):
+ raise ValueError("Media archive path leaves its own directory")
+ files.mkdir(parents=True, exist_ok=True)
+ name = "media" + suffix
+ os.replace(staged, files / name)
+ write_marker(run, kind="chat_media", title="Chat media")
+ return (
+ f"/api/outputs/{run.name}/files/tasks/chat/artifacts/files/{name}"
+ "/download?disposition=inline"
+ )
+
+ def reference(self, raw: str, hint: str = "") -> str:
+ ref = raw.strip().removeprefix("<").removesuffix(">")
+ if ref in self._resolved:
+ return self._resolved[ref]
+ mime = media_type(ref, hint)
+ if not mime:
+ return raw
+ try:
+ if ref.startswith("data:"):
+ header, encoded = ref.split(",", 1)
+ if header != f"data:{mime};base64" or len(encoded) > (
+ MAX_INLINE_BYTES * 4 // 3 + 4
+ ):
+ raise ValueError("Unsupported or oversized inline media")
+ import io
+
+ data = base64.b64decode(encoded, validate=True)
+ if len(data) > MAX_INLINE_BYTES:
+ raise ValueError("Inline media exceeds the import limit")
+ url = self._archive(io.BytesIO(data), _MIME_SUFFIX[mime])
+ elif ref.lower().startswith(("https://", "http://")):
+ parsed = urlsplit(ref)
+ if (
+ not parsed.hostname
+ or parsed.username
+ or parsed.password
+ or re.search(r"[\x00-\x20<>]", ref)
+ ):
+ raise ValueError("Invalid media URL")
+ url = ref
+ elif ref.startswith("/api/"):
+ url = ref
+ else:
+ if ref.startswith("file:"):
+ parsed = urlsplit(ref)
+ if parsed.netloc:
+ raise ValueError("Network file locations are not chat artifacts")
+ ref = unquote(parsed.path)
+ if re.match(r"^/[A-Za-z]:/", ref):
+ ref = ref[1:]
+ if ref.startswith(("\\\\", "//")):
+ raise ValueError("Network file locations are not chat artifacts")
+ file = Path(ref)
+ file = (file if file.is_absolute() else self.cwd / file).resolve()
+ if not file.is_relative_to(self.cwd):
+ raise ValueError("Media file is outside this chat workspace")
+ if "%" in ref and not file.exists():
+ decoded = Path(unquote(ref))
+ file = (decoded if decoded.is_absolute() else self.cwd / decoded).resolve()
+ if not file.is_relative_to(self.cwd):
+ raise ValueError("Media file is outside this chat workspace")
+ before = file.stat()
+ with file.open("rb") as source:
+ url = self._archive(source, file.suffix.lower(), before)
+ self._resolved[raw] = self._remember(url, mime)
+ return url
+ except (OSError, ValueError, binascii.Error) as exc:
+ # The original receipt remains inspectable, alongside a visible
+ # delivery error. Never replace missing pixels with a success claim.
+ self.errors.append(str(exc))
+ return raw
+
+ def text(self, text: str) -> str:
+ if text.strip().startswith("data:") and media_type(text.strip()):
+ return self.reference(text.strip())
+ # Code examples are not output receipts. Do not expose a file merely
+ # because an instruction block happens to mention its name.
+ parts = re.split(r"(```[\s\S]*?```)", text)
+ for i in range(0, len(parts), 2):
+ part = parts[i]
+
+ def link(match: re.Match[str]) -> str:
+ raw = match[2].strip()
+ url = self.reference(raw)
+ return match[0] if url == raw else match[1] + "<" + url + ">" + match[3]
+
+ part = _LINK.sub(link, part)
+ # Scan other explicit URL/path receipts, without changing prose.
+ without_links = _LINK.sub("", part)
+ for match in _QUOTED.finditer(without_links):
+ ref = match[1]
+ candidate = (self.cwd / ref).resolve()
+ if ref.startswith(("http://", "https://", "file:///")) or (
+ candidate.is_relative_to(self.cwd) and candidate.is_file()
+ ):
+ self.reference(ref)
+ for match in _RAW.finditer(without_links):
+ self.reference(match[0])
+ for match in _BARE.finditer(without_links):
+ candidate = (self.cwd / match[0]).resolve()
+ if candidate.is_relative_to(self.cwd) and candidate.is_file():
+ self.reference(match[0])
+ parts[i] = part
+ return "".join(parts)
+
+ def structured(self, value: Any, depth: int = 0, inherited_hint: str = "") -> Any:
+ if depth > 12:
+ return value
+ if isinstance(value, list):
+ return [self.structured(item, depth + 1, inherited_hint) for item in value]
+ if isinstance(value, dict):
+ result = dict(value)
+ hint = str(
+ value.get("mimeType")
+ or value.get("mime_type")
+ or value.get("media_type")
+ or value.get("content_type")
+ or inherited_hint
+ )
+ if not hint:
+ hint = {
+ "image": "image/png",
+ "image_url": "image/png",
+ "input_image": "image/png",
+ "image_generation_call": "image/png",
+ "video": "video/mp4",
+ "video_url": "video/mp4",
+ "audio": "audio/mpeg",
+ }.get(str(value.get("type")), "")
+ hint = hint.split(";", 1)[0].strip().lower()
+ binary_keys = ["data", "blob"]
+ if value.get("type") == "image_generation_call":
+ binary_keys.append("result")
+ for binary_key in binary_keys:
+ if hint in _MIME_SUFFIX and isinstance(value.get(binary_key), str):
+ uri = self.reference(f"data:{hint};base64,{value[binary_key]}", hint)
+ result.pop(binary_key, None)
+ if not uri.startswith("data:"):
+ result["url"] = uri
+ else:
+ result["media_error"] = "Media import failed"
+ if isinstance(value.get("b64_json"), str):
+ uri = self.reference("data:image/png;base64," + value["b64_json"], "image/png")
+ if not uri.startswith("data:"):
+ result.pop("b64_json", None)
+ result["url"] = uri
+ for key, child in list(result.items()):
+ if (
+ key in {"image_url", "video_url", "audio_url"}
+ and isinstance(child, dict)
+ and isinstance(child.get("url"), str)
+ ):
+ mime = {
+ "image_url": "image/png",
+ "video_url": "video/mp4",
+ "audio_url": "audio/mpeg",
+ }[key]
+ result[key] = {**child, "url": self.reference(child["url"], mime)}
+ elif key.lower() in _REF_KEYS and isinstance(child, str):
+ key_hint = {
+ "image_url": "image/png",
+ "video_url": "video/mp4",
+ "audio_url": "audio/mpeg",
+ }.get(key, hint)
+ result[key] = self.reference(child, key_hint)
+ elif key not in {"b64_json"}:
+ child_hint = {
+ "images": "image/png",
+ "image": "image/png",
+ "videos": "video/mp4",
+ "video": "video/mp4",
+ "audio": "audio/mpeg",
+ }.get(key, hint if key in {"source", "resource", "result"} else "")
+ if key != "data" or not isinstance(child, str):
+ result[key] = self.structured(child, depth + 1, child_hint)
+ return result
+ if isinstance(value, str):
+ return self.reference(value, inherited_hint) if inherited_hint else self.text(value)
+ return value
+
+
+def normalize_media_event(
+ event: dict[str, Any], *, cwd: Path, outputs_root: Path, scope: str
+) -> list[dict[str, Any]]:
+ kind = event.get("kind")
+ payload = event.get("payload") or {}
+ if kind not in {"assistant_text", "tool_result", "user_message"} or payload.get("is_error"):
+ return [event]
+ normalizer = MediaNormalizer(cwd, outputs_root, scope)
+ if kind == "user_message":
+ from jarvis.agentic_ide.drops import dereference
+
+ attachments = []
+ for row in payload.get("attachments") or []:
+ if not isinstance(row, dict):
+ continue
+ receipt = {key: value for key, value in row.items() if key != "reference"}
+ ref = dereference(str(row.get("reference") or ""))
+ if ref and media_type(ref):
+ url = normalizer.reference(ref)
+ if url != ref:
+ receipt["url"] = url
+ attachments.append(receipt)
+ result = (
+ [{**event, "payload": {**payload, "attachments": attachments}}]
+ if "attachments" in payload
+ else [event]
+ )
+ if normalizer.errors:
+ result.append(
+ {
+ **event,
+ "kind": "error",
+ "payload": {
+ "message": "Attached media could not be displayed: "
+ + "; ".join(dict.fromkeys(normalizer.errors))
+ },
+ }
+ )
+ return result
+ field = "text" if kind == "assistant_text" else "output"
+ value = payload.get(field, "")
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value) if value.lstrip().startswith(("{", "[")) else None
+ except ValueError:
+ parsed = None
+ processed = normalizer.structured(parsed) if parsed is not None else None
+ rewritten = (
+ json.dumps(processed, ensure_ascii=False)
+ if parsed is not None
+ else normalizer.text(value)
+ )
+ content = processed.get("content") if isinstance(processed, dict) else processed
+ if (
+ kind == "assistant_text"
+ and isinstance(content, list)
+ and all(isinstance(block, dict) and "type" in block for block in content)
+ and (normalizer.receipts or normalizer.errors)
+ ):
+ rewritten = content_markdown(content, normalizer.receipts)
+ else:
+ rewritten = json.dumps(normalizer.structured(value), ensure_ascii=False)
+ result = [{**event, "payload": {**payload, field: rewritten}}]
+ # Explicit Markdown in assistant prose is already rendered in place.
+ inline = (
+ set(re.findall(r"\]\(<?([^)>]+)>?\)", rewritten)) if kind == "assistant_text" else set()
+ )
+ if kind == "assistant_text":
+ prose = re.sub(r"`[^`]*`", "", rewritten)
+ inline.update(
+ match[0]
+ for match in _RAW.finditer(prose)
+ if match[0].startswith(("http://", "https://"))
+ )
+ for url, mime in normalizer.receipts.items():
+ if url in inline or display_url(url, mime) in inline:
+ continue
+ key = hashlib.sha256((str(payload.get("turn_id")) + url).encode()).hexdigest()[:24]
+ markdown = media_markdown(url, mime)
+ result.append(
+ {
+ **event,
+ "kind": "assistant_text",
+ "payload": {
+ "turn_id": payload.get("turn_id"),
+ "message_id": f"media-{key}",
+ "text": markdown,
+ },
+ }
+ )
+ if normalizer.errors:
+ result.append(
+ {
+ **event,
+ "kind": "error",
+ "payload": {
+ "turn_id": payload.get("turn_id"),
+ "message": "Media could not be displayed: "
+ + "; ".join(dict.fromkeys(normalizer.errors)),
+ },
+ }
+ )
+ return result
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 1707467b19..0dc30169f9 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -1134,6 +1134,14 @@ def _content_text(content: Any) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
+ if any(
+ isinstance(block, dict)
+ and block.get("type")
+ in {"image", "image_url", "input_image", "video", "audio", "resource", "resource_link"}
+ for block in content
+ ):
+ # Preserve structured media for the common chat delivery layer.
+ return json.dumps(content, ensure_ascii=False)
parts: list[str] = []
for block in content:
if isinstance(block, dict):
@@ -1144,6 +1152,8 @@ def _content_text(content: Any) -> str:
elif isinstance(block, str):
parts.append(block)
return "\n".join(p for p in parts if p)
+ if isinstance(content, dict):
+ return json.dumps(content, ensure_ascii=False)
return "" if content is None else str(content)
@@ -1246,6 +1256,32 @@ def translate_claude_line(obj: dict[str, Any], st: _ClaudeState) -> list[dict[st
content = [{"type": "text", "text": str(content)}]
text_blocks = [b for b in content if isinstance(b, dict) and b.get("type") == "text"]
snapshot = len(content) > 1
+ visual_blocks = [
+ block
+ for block in content
+ if isinstance(block, dict)
+ and block.get("type")
+ in {"image", "image_url", "input_image", "video", "audio", "resource", "resource_link"}
+ ]
+ if visual_blocks:
+ st.emitted_text = True
+ visual_content = [
+ block
+ for block in content
+ if block in visual_blocks
+ or (isinstance(block, dict) and block.get("type") == "text")
+ ]
+ out.append(
+ make_event(
+ "assistant_text",
+ {
+ "turn_id": st.turn_id,
+ "message_id": mid,
+ "text": json.dumps({"content": visual_content}, ensure_ascii=False),
+ },
+ )
+ )
+ text_blocks = []
for block in content:
if not isinstance(block, dict):
continue
@@ -1681,7 +1717,7 @@ def translate_agy_line(obj: dict[str, Any], st: _AgyState) -> list[dict[str, Any
err_text = (
str(err.get("message") or err) if isinstance(err, dict) else str(err or "")
)
- output = str(info.get("output") or "") if isinstance(info, dict) else ""
+ output = _content_text(info.get("output")) if isinstance(info, dict) else ""
is_error = state != "DONE" or bool(err_text)
if is_error and err_text:
output = (output.rstrip() + ("\n" if output else "") + err_text).strip()
@@ -1852,7 +1888,7 @@ def translate_opencode_line(obj: dict[str, Any], st: _OpenCodeState) -> list[dic
status = str(state.get("status") or "")
if status in {"completed", "error"}:
is_error = status == "error"
- output = str(state.get("output") or "")
+ output = _content_text(state.get("output"))
err = state.get("error")
if is_error and err:
output = (output.rstrip() + ("\n" if output else "") + str(err)).strip()
@@ -1952,7 +1988,8 @@ def translate_kimi_line(obj: dict[str, Any], st: _KimiState) -> list[dict[str, A
if role == "assistant":
st.messages += 1
mid = f"kimi-{st.messages}"
- content = obj.get("content")
+ raw_content = obj.get("content")
+ content = _content_text(raw_content) if isinstance(raw_content, list) else raw_content
if isinstance(content, str) and content.strip():
st.emitted_text = True
st.result_text = content
@@ -2082,12 +2119,12 @@ def _cursor_tool_output(payload: dict[str, Any]) -> tuple[str, bool]:
val = success.get(key)
if isinstance(val, str) and val.strip():
return val, False
- return json.dumps(success, ensure_ascii=False)[:4000], False
+ return json.dumps(success, ensure_ascii=False), False
return str(success or "done"), False
if "error" in result or "failure" in result:
err = result.get("error") or result.get("failure")
return str(err or "failed"), True
- return json.dumps(result, ensure_ascii=False)[:4000], False
+ return json.dumps(result, ensure_ascii=False), False
def translate_cursor_line(obj: dict[str, Any], st: _CursorState) -> list[dict[str, Any]]:
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index cf2f8d0e14..0fddc527ae 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -286,6 +286,41 @@ class AgentChatService:
await self._emit(session_id, make_event("notice", dict(payload)))
async def _emit(self, session_id: str, event: dict[str, Any]) -> None:
+ # One delivery path for every runner. Normalize only finished receipts;
+ # token deltas and voice-critical streaming never perform file I/O.
+ if event.get("kind") in {"assistant_text", "tool_result", "user_message"}:
+ from jarvis.agent_chat.media import normalize_media_event
+ from jarvis.core.paths import repo_root
+ from jarvis.missions.isolation.worktree import resolve_outputs_root
+
+ session = self.store.get_session(session_id)
+ if session is not None:
+ try:
+ expanded = await asyncio.to_thread(
+ normalize_media_event,
+ event,
+ cwd=Path(session.cwd),
+ outputs_root=resolve_outputs_root(repo_root()),
+ scope=session_id,
+ )
+ except (OSError, ValueError):
+ log.warning("agent chat: media normalization failed", exc_info=True)
+ expanded = [
+ event,
+ make_event(
+ "error",
+ {
+ "turn_id": (event.get("payload") or {}).get("turn_id"),
+ "message": "Media could not be added to the chat.",
+ },
+ ),
+ ]
+ for item in expanded:
+ self._publish_event(session_id, item)
+ return
+ self._publish_event(session_id, event)
+
+ def _publish_event(self, session_id: str, event: dict[str, Any]) -> None:
stored = self.store.append_event(session_id, event)
for q in list(self._subscribers.get(session_id, ())):
try:
@@ -413,6 +448,7 @@ class AgentChatService:
"attachments": [
{
"name": item.name,
+ "reference": item.reference,
"kind": item.kind,
"described_by": item.described_by,
"note": item.note,
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
index 321052937e..f6264cc644 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx
@@ -1,6 +1,5 @@
import { memo } from "react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
+import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";
import { CircleAlert, FileText, ImageIcon } from "lucide-react";
import { InternalMessageBubble, type InternalParticipant } from "./InternalMessageBubble";
import { MessageWithChips } from "./ToolChoiceChips";
@@ -65,7 +64,9 @@ export function AgentTimeline({
// icon (maintainer, 2026-08-27). A file with no url —
// a document, or the front page's chat, whose drops
// are read and not stored — keeps the chip.
- file.kind === "image" && file.url ? (
+ file.url && (mediaKind(file.url) === "video" || mediaKind(file.url) === "audio") ? (
+ <MediaPreview key={file.name} src={file.url} label={file.name} kind={mediaKind(file.url)!} />
+ ) : (file.kind === "image" || (file.url && mediaKind(file.url) === "image")) && file.url ? (
<img
key={file.name}
src={file.url}
@@ -145,7 +146,7 @@ export function AgentTimeline({
className="mx-auto flex max-w-[85%] flex-col gap-0.5 rounded-lg bg-card px-4 py-3 text-body"
>
{headline ? <span className="font-medium text-foreground">{headline}</span> : null}
- {item.text ? <span className="whitespace-pre-wrap text-muted-foreground">{item.text}</span> : null}
+ {item.text ? <ChatMarkdown text={item.text} className="text-muted-foreground" /> : null}
</div>
);
}
@@ -195,7 +196,7 @@ function Prose({ block }: { block: TextBlock }) {
"prose-thead:text-foreground-strong prose-th:text-foreground-strong prose-td:text-foreground",
)}
>
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{block.text}</ReactMarkdown>
+ <ChatMarkdown text={block.text} />
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
new file mode 100644
index 0000000000..837975e521
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
@@ -0,0 +1,97 @@
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { ChatMarkdown, mediaKind, normalizeMediaMarkup, safeMediaUrl } from "./ChatMarkdown";
+
+afterEach(cleanup);
+
+describe("shared chat media", () => {
+ it("renders every image and video in a mixed response", () => {
+ const { container } = render(<ChatMarkdown text={'![First](https://example.test/a.png)\n\n![Second](https://example.test/b.webp)\n\n[Clip](https://example.test/video.mp4)\n\n[Audio](https://example.test/audio.mp3)'} />);
+ expect(screen.getAllByRole("img")).toHaveLength(2);
+ const video = container.querySelector("video")!;
+ expect(video.getAttribute("src")).toBe("https://example.test/video.mp4");
+ expect(video.hasAttribute("controls")).toBe(true);
+ expect(video.hasAttribute("autoplay")).toBe(false);
+ expect(video.getAttribute("preload")).toBe("metadata");
+ expect(container.querySelector("audio")?.hasAttribute("controls")).toBe(true);
+ });
+
+ it.each(["mp4", "webm", "mov", "ogv"])("renders archived %s receipts with video controls", extension => {
+ const url = `/api/outputs/run/files/tasks/chat/artifacts/files/clip.${extension}/download?disposition=inline`;
+ render(<ChatMarkdown text={`[Clip](<${url}>)`} />);
+ expect(screen.getByLabelText("Clip").tagName).toBe("VIDEO");
+ expect(screen.getByLabelText("Clip").getAttribute("src")).toBe(url);
+ });
+
+ it("honors an extensionless video URL without altering its signed query", () => {
+ const url = "https://example.test/object?signature=a%2Bb#jarvis-media=video%2Fmp4";
+ render(<ChatMarkdown text={`[Video](<${url}>)`} />);
+ expect(screen.getByLabelText("Video").getAttribute("src")).toBe(url);
+ });
+
+ it("renders a video even when a provider used Markdown image syntax", () => {
+ const { container } = render(<ChatMarkdown text="![Movie](https://example.test/movie.webm)" />);
+ expect(container.querySelector("video")).toBeTruthy();
+ expect(container.querySelector("img")).toBeNull();
+ });
+
+ it("keeps a download link without duplicating an image preview", () => {
+ const base = "/api/outputs/run/files/tasks/chat/artifacts/files/photo.png/download";
+ render(<ChatMarkdown text={`![Photo](${base}?disposition=inline)\n\n[Download](${base})`} />);
+ expect(screen.getAllByRole("img")).toHaveLength(1);
+ expect(screen.getByRole("link", {name:"Download"})).toBeTruthy();
+ });
+
+ it("opens images in an accessible viewer", () => {
+ render(<ChatMarkdown text="![Photo](https://example.test/photo.png)" />);
+ fireEvent.click(screen.getByRole("button", {name:"Enlarge Photo"}));
+ expect(within(screen.getByRole("dialog")).getByRole("img").getAttribute("src")).toBe("https://example.test/photo.png");
+ });
+
+ it("shows an explicit error and retains access to a failed video", () => {
+ render(<ChatMarkdown text="[Clip](https://example.test/clip.mp4)" />);
+ fireEvent.error(screen.getByLabelText("Clip"));
+ expect(screen.getByRole("status").textContent).toContain("cannot be loaded or played");
+ expect(screen.getByRole("link", {name:/Open file/}).getAttribute("href")).toBe("https://example.test/clip.mp4");
+ });
+
+ it("retries a changed source without retaining the previous error", () => {
+ const {rerender} = render(<ChatMarkdown text="![Photo](https://example.test/old.png)" />);
+ fireEvent.error(screen.getByRole("img"));
+ rerender(<ChatMarkdown text="![Photo](https://example.test/new.png)" />);
+ expect(screen.getByRole("img").getAttribute("src")).toBe("https://example.test/new.png");
+ });
+
+ it("preserves playback when streamed text and another image arrive", () => {
+ const text = "[Clip](https://example.test/clip.mp4)";
+ const {rerender} = render(<ChatMarkdown text={text} />);
+ (screen.getByLabelText("Clip") as HTMLVideoElement).currentTime = 1.25;
+ rerender(<ChatMarkdown text={text + "\n\nMore text.\n\n![Photo](https://example.test/photo.png)"} />);
+ expect((screen.getByLabelText("Clip") as HTMLVideoElement).currentTime).toBe(1.25);
+ });
+
+ it("retries without changing a signed media URL", () => {
+ const url = "https://example.test/clip.mp4?signature=abc";
+ render(<ChatMarkdown text={`[Clip](${url})`} />);
+ fireEvent.error(screen.getByLabelText("Clip"));
+ fireEvent.click(screen.getByRole("button", {name:"Retry"}));
+ expect(screen.getByLabelText("Clip").getAttribute("src")).toBe(url);
+ });
+
+ it("recognizes safe HTML media tags without running their handlers", () => {
+ const {container} = render(<ChatMarkdown text={'<video controls><source src="https://example.test/clip.mp4" type="video/mp4"></video>\n\n<img src="https://example.test/photo.png" onerror="alert(1)" alt="Photo">'} />);
+ expect(container.querySelector("video")).toBeTruthy();
+ expect(screen.getByRole("img").hasAttribute("onerror")).toBe(false);
+ expect(container.querySelector("script")).toBeNull();
+ });
+
+ it("does not turn HTML code examples into media tags", () => {
+ const text = '```text\n<video src="https://example.test/clip.mp4"></video>\n```';
+ expect(normalizeMediaMarkup(text)).toBe(text);
+ });
+
+ it.each(["javascript:alert(1)", "file:///private/image.png", "C:\\private\\image.png", "data:text/html;base64,PHNjcmlwdD4=", "https://user:[email protected]/image.png"])("rejects unsafe or unarchived media URL %s", url => {
+ expect(safeMediaUrl(url)).toBeNull();
+ expect(mediaKind(url)).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
new file mode 100644
index 0000000000..28319d0732
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
@@ -0,0 +1,158 @@
+import { Children, createContext, isValidElement, lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
+import ReactMarkdown, { defaultUrlTransform, type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { AlertCircle, Download, Maximize2, X } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { openExternalUrl } from "@/lib/openExternal";
+import * as Dialog from "@radix-ui/react-dialog";
+
+const RenderedFence = lazy(() => import("@/components/outputs/RenderedFence").then(module => ({ default: module.RenderedFence })));
+
+export type MediaKind = "image" | "video" | "audio";
+const EXTENSIONS: Record<string, MediaKind> = {
+ png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", avif: "image", svg: "image", bmp: "image",
+ ico: "image", tif: "image", tiff: "image", heic: "image", heif: "image",
+ mp4: "video", webm: "video", mov: "video", m4v: "video", ogv: "video",
+ avi: "video", mkv: "video", mpeg: "video", mpg: "video", wmv: "video",
+ mp3: "audio", wav: "audio", ogg: "audio", m4a: "audio", flac: "audio", aac: "audio",
+};
+
+export function safeMediaUrl(raw: string): string | null {
+ if (/^data:image\/(?:png|jpeg|gif|webp|avif);base64,[a-zA-Z0-9+/=]+$/.test(raw) && raw.length <= 32 * 1024 * 1024) return raw;
+ try {
+ const url = new URL(raw, "http://chat.local");
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return null;
+ // Unarchived native paths must never turn into accidental app requests.
+ if (!raw.startsWith("/") && !/^https?:\/\//i.test(raw)) return null;
+ return raw;
+ } catch { return null; }
+}
+
+export function mediaKind(raw: string): MediaKind | null {
+ if (!safeMediaUrl(raw)) return null;
+ if (raw.startsWith("data:image/")) return "image";
+ const url = new URL(raw, "http://chat.local");
+ const hint = new URLSearchParams(url.hash.slice(1)).get("jarvis-media")?.split("/")[0];
+ if (hint === "image" || hint === "video" || hint === "audio") return hint;
+ let path: string;
+ try { path = decodeURIComponent(url.pathname); } catch { return null; }
+ path = path.replace(/\/(download|raw|view)$/, "");
+ return EXTENSIONS[path.split(".").pop()?.toLowerCase() ?? ""] ?? null;
+}
+
+function assetKey(raw: string): string {
+ try {
+ const url = new URL(raw, "http://chat.local");
+ url.hash = "";
+ if (url.pathname.startsWith("/api/outputs/")) url.searchParams.delete("disposition");
+ return url.href;
+ } catch { return raw; }
+}
+
+/** Recognize media tags without executing arbitrary model-authored HTML. */
+export function normalizeMediaMarkup(text: string): string {
+ const attr = (markup: string, name: string) => markup.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, "i"))?.[1];
+ const parts = text.split(/(```[\s\S]*?```)/);
+ return parts.map((part, i) => i % 2 ? part : part
+ .replace(/<(video|audio)\b([^>]*)>([\s\S]*?)<\/\1>/gi, (original, kind: string, head: string, body: string) => {
+ const source = attr(head, "src") ?? attr(body.match(/<source\b[^>]*>/i)?.[0] ?? "", "src");
+ if (!source || !safeMediaUrl(source)) return original;
+ const marker = source.includes("#") ? "&" : "#";
+ return `\n\n[${kind}](<${source}${marker}jarvis-media=${kind}%2F${kind === "video" ? "mp4" : "mpeg"}>)\n\n`;
+ })
+ .replace(/<img\b[^>]*>/gi, original => {
+ const src = attr(original, "src");
+ if (!src || !safeMediaUrl(src)) return original;
+ const alt = (attr(original, "alt") ?? "image").replace(/[\[\]\r\n]/g, " ");
+ return `![${alt}](<${src}>)`;
+ })).join("");
+}
+
+export function MediaPreview({ src, label, kind }: { src: string; label: string; kind: MediaKind }) {
+ const t = useT();
+ const [failedSource, setFailedSource] = useState<string | null>(null);
+ const [expanded, setExpanded] = useState(false);
+ const [revision, setRevision] = useState(0);
+ const safe = safeMediaUrl(src);
+ const failed = !safe || failedSource === src;
+ const unavailable = t("chat_media.unavailable");
+ const playerRef = useRef<HTMLMediaElement | null>(null);
+ useEffect(() => {
+ const player = playerRef.current;
+ return () => {
+ if (!player) return;
+ if (!player.paused) player.pause();
+ if (player.networkState !== player.NETWORK_EMPTY) {
+ player.removeAttribute("src");
+ player.load();
+ }
+ };
+ }, [safe, kind, failed, revision]);
+ return <Dialog.Root open={expanded} onOpenChange={setExpanded}><span className="my-3 block min-w-0 max-w-full" data-testid="chat-media" data-kind={kind}>
+ {failed ? <span role="status" className="flex items-center gap-2 py-3 text-sm text-muted-foreground">
+ <AlertCircle aria-hidden className="h-4 w-4 shrink-0" />{unavailable}
+ {safe ? <button type="button" onClick={() => { setFailedSource(null); setRevision(value => value + 1); }} className="shrink-0 rounded px-2 py-1 text-foreground underline focus-visible:ring-2 focus-visible:ring-ring">{t("chat_media.retry")}</button> : null}
+ </span> : kind === "image" ? <Dialog.Trigger asChild><button type="button"
+ aria-label={t("chat_media.expand").replace("{file}", label)}
+ className="group relative block max-w-full rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <img key={revision} src={safe!} alt={label} loading="lazy" decoding="async" onError={() => { setFailedSource(src); setExpanded(false); }}
+ className="m-0 max-h-[520px] max-w-full rounded-lg object-contain" />
+ <Maximize2 aria-hidden className="absolute bottom-2 right-2 h-6 w-6 rounded bg-background/90 p-1 text-foreground opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100" />
+ </button></Dialog.Trigger> : kind === "video" ? <video ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls playsInline preload="metadata"
+ onError={() => { setFailedSource(src); setExpanded(false); }} className="max-h-[520px] w-full rounded-lg bg-muted" />
+ : <audio ref={node => { playerRef.current = node; }} key={`${revision}:${safe}`} src={safe!} aria-label={label} controls preload="metadata" onError={() => { setFailedSource(src); setExpanded(false); }} className="w-full" />}
+ {safe ? <a href={safe} download={safe.startsWith("/api/outputs/") ? true : undefined}
+ onClick={event => {
+ if (!safe.startsWith("/api/outputs/")) {
+ event.preventDefault();
+ void openExternalUrl(new URL(safe, window.location.href).href);
+ }
+ }} className="mt-1 inline-flex items-center gap-1.5 text-xs text-muted-foreground underline underline-offset-2">
+ <Download aria-hidden className="h-3 w-3" />{t(safe.startsWith("/api/outputs/") ? "chat_media.download" : "chat_media.open_file")} · {label}
+ </a> : <span className="text-xs text-muted-foreground">{label}</span>}
+ {kind === "image" && safe ? <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-50 bg-background/90" />
+ <Dialog.Content aria-describedby={undefined} className="fixed left-1/2 top-1/2 z-50 grid max-h-[95vh] w-max max-w-[95vw] -translate-x-1/2 -translate-y-1/2 gap-3 overflow-auto rounded-lg border border-border bg-background p-4 text-foreground shadow-xl">
+ <Dialog.Title className="pr-8 text-sm">{label}</Dialog.Title>
+ <Dialog.Close aria-label={t("common.close")} className="absolute right-3 top-3 rounded p-1 focus-visible:ring-2 focus-visible:ring-ring"><X aria-hidden className="h-4 w-4" /></Dialog.Close>
+ <img src={safe} alt={label} className="mx-auto max-h-[80vh] max-w-full object-contain" />
+ </Dialog.Content>
+ </Dialog.Portal> : null}
+ </span></Dialog.Root>;
+}
+
+const ImageKeysContext = createContext<ReadonlySet<string>>(new Set());
+
+// Stable component identities are essential: changing these on each streamed
+// token would unmount videos, reset playback and discard image error state.
+const MARKDOWN_COMPONENTS: Components = {
+ img: ({ src = "", alt = "image" }) => <MediaPreview src={src} label={alt || "image"} kind={mediaKind(src) ?? "image"} />,
+ a: function MediaLink({ href = "", children }) {
+ const imageKeys = useContext(ImageKeysContext);
+ const kind = mediaKind(href);
+ const label = Children.toArray(children).filter(child => typeof child === "string").join("") || kind || "media";
+ if (kind && !imageKeys.has(assetKey(href))) return <MediaPreview src={href} label={label} kind={kind} />;
+ return <a href={href} onClick={event => {
+ if (/^https?:\/\//i.test(href)) { event.preventDefault(); void openExternalUrl(href); }
+ }}>{children}</a>;
+ },
+ pre: ({ children, node: _node, ...props }) => {
+ const child = Children.toArray(children)[0];
+ if (isValidElement<{ className?: string; children?: unknown }>(child)) {
+ const language = child.props.className?.match(/language-(html|svg)\b/)?.[1];
+ if (language === "html" || language === "svg") return <Suspense fallback={<pre>{children}</pre>}><RenderedFence language={language} code={String(child.props.children ?? "").replace(/\n$/, "")} /></Suspense>;
+ }
+ return <pre {...props}>{children}</pre>;
+ },
+};
+
+export function ChatMarkdown({ text, className }: { text: string; className?: string }) {
+ const body = useMemo(() => normalizeMediaMarkup(text), [text]);
+ const imageKeys = useMemo(() => new Set(Array.from(body.matchAll(/!\[[^\]]*\]\(<?([^)>]+)>?\)/g), match => assetKey(match[1]))), [body]);
+ return <div className={cn("min-w-0 [overflow-wrap:anywhere]", className)}>
+ <ImageKeysContext.Provider value={imageKeys}>
+ <ReactMarkdown remarkPlugins={[remarkGfm]} urlTransform={url => url.startsWith("data:") ? safeMediaUrl(url) ?? "" : defaultUrlTransform(url)} components={MARKDOWN_COMPONENTS}>{body}</ReactMarkdown>
+ </ImageKeysContext.Provider>
+ </div>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
index 2a62f7f910..bea14c714d 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
@@ -1,5 +1,6 @@
import { useOpenPairConversation } from "./PairConversation";
import { useState } from "react";
+import { ChatMarkdown } from "./ChatMarkdown";
import { ArrowRight, ChevronDown, MessagesSquare } from "lucide-react";
import { AgentSwatch } from "@/components/society/AgentSwatch";
@@ -174,7 +175,7 @@ export function InternalMessageBubble({
<div className="px-3 pb-2.5 pl-[30px]" onClick={canOpenPair ? () => openPair?.({ id: item.message.sender_id, name: senderName }) : undefined} style={canOpenPair ? { cursor: "pointer" } : undefined}>
{shown ? (
<div data-testid="agent-message-internal-full" className="whitespace-pre-wrap text-sm leading-relaxed text-foreground [overflow-wrap:anywhere]">
- {text}
+ <ChatMarkdown text={text} />
</div>
) : (
<p
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/PairConversation.tsx b/jarvis/ui/web/frontend/src/components/agentchat/PairConversation.tsx
index e2be5f975d..3e0cb8e0c1 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/PairConversation.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/PairConversation.tsx
@@ -1,7 +1,6 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { ArrowLeftRight, Lock, X } from "lucide-react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
+import { ChatMarkdown } from "./ChatMarkdown";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import type { SocietyEnvelope } from "@/lib/societyApi";
@@ -115,7 +114,7 @@ export function PairConversation({ pair, onClose }: { pair: Pair; onClose: () =>
</div>
<div className="rounded-2xl border border-border bg-card px-3.5 py-2.5 text-foreground">
<div className="prose prose-sm prose-neutral max-w-none dark:prose-invert prose-p:my-1 prose-pre:overflow-x-auto [overflow-wrap:anywhere]">
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{String(message.payload.text)}</ReactMarkdown>
+ <ChatMarkdown text={String(message.payload.text)} />
</div>
</div>
</article>)}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
index 6be3493008..14cba745b4 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
@@ -7,6 +7,7 @@ import { cn } from "@/lib/utils";
import { describeToolStep } from "@/lib/toolStepLabel";
import type { ApprovalDecision } from "@/lib/agentChatApi";
import type { ReasoningBlock, ToolBlock, TurnBlock, TurnItem, TurnStatus } from "./reduce";
+import { ChatMarkdown } from "./ChatMarkdown";
import { toolDiff } from "./toolDiff";
import { formatTokens, outputTokens } from "./toolView";
@@ -207,7 +208,7 @@ export function WorkTrace({ blocks, status, startedMs, durationMs, error, onDeci
</Disclosure>;
if (first.kind === "tool") return <TraceTool key={group.id} block={first} status={status} onDecide={onDecide} />;
if (first.kind === "reasoning") return <ReasoningTrace key={group.id} block={first} turnLive={live} />;
- return first.text.trim() ? <div key={group.id} className="min-w-0 py-2">{renderText ? renderText(first.text, first.id) : <div className="prose prose-sm max-w-none text-foreground dark:prose-invert [overflow-wrap:anywhere]"><ReactMarkdown remarkPlugins={[remarkGfm]}>{first.text}</ReactMarkdown></div>}</div> : null;
+ return first.text.trim() ? <div key={group.id} className="min-w-0 py-2">{renderText ? renderText(first.text, first.id) : <div className="prose prose-sm max-w-none text-foreground dark:prose-invert [overflow-wrap:anywhere]"><ChatMarkdown text={first.text} /></div>}</div> : null;
})}
{error ? <p role="alert" className="py-2 text-sm text-destructive [overflow-wrap:anywhere]">{error}</p> : null}
<div role="status" aria-live="polite" className={cn("flex flex-wrap items-center gap-2 border-t border-border pt-3 text-xs text-muted-foreground", status === "error" && "text-destructive")}>
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
index e576777353..a5820f3565 100644
--- a/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
@@ -1,3 +1,4 @@
+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";
import { useLayoutEffect, useMemo } from "react";
import { AudioLines, Mic } from "lucide-react";
@@ -148,7 +149,7 @@ function SpokenTurn({ message }: { message: ChatMessage }) {
</div>
)}
{!isUser && trace && <ThoughtTraceDisclosure trace={trace} />}
- <div className={cn("whitespace-pre-wrap", !isUser && "mt-1.5")}>{message.content}</div>
+ {isUser ? <div className="whitespace-pre-wrap">{message.content}</div> : <ChatMarkdown text={message.content} className="prose prose-sm mt-1.5 max-w-none dark:prose-invert" />}
</div>
</div>
);
diff --git a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx
index 7e7a5364ea..a0b9c94652 100644
--- a/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/local-models/AssistantPanel.tsx
@@ -57,7 +57,7 @@ import {
type Proposal,
type ProposalStep,
} from "./assistantProposal";
-import { renderInline } from "./assistantText";
+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";
import { useLocalModelsAssistantStore } from "./assistantStore";
import { BrainSwitchCard, SetupProposalCard } from "./SetupProposalCard";
@@ -506,11 +506,7 @@ export function AssistantPanel({
className="flex flex-col gap-3 text-title text-foreground"
data-testid="assistant-answer"
>
- {answer.split(/\n{2,}/).map((para, k) => (
- <p key={k} className="whitespace-pre-wrap">
- {renderInline(para)}
- </p>
- ))}
+ <ChatMarkdown text={answer} className="prose prose-sm max-w-none dark:prose-invert" />
</div>
)}
{item.status === "error" && item.error && (
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index 4e427e9364..9b976f57d7 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -22,8 +22,7 @@ import { InternalMessageBubble } from "@/components/agentchat/InternalMessageBub
*/
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";
-import ReactMarkdown from "react-markdown";
-import remarkGfm from "remark-gfm";
+import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";
import { AgentChatStoreProvider, useAgentChat } from "@/components/agentchat/AgentChatStoreContext";
import { ChatAttachmentStrip } from "@/components/agentchat/ChatAttachmentStrip";
@@ -724,7 +723,7 @@ function NoticeLine({ item }: { item: NoticeItem }) {
return (
<div className="flex max-w-[85%] flex-col gap-0.5 self-start rounded-2xl rounded-bl-md border border-border bg-card px-3.5 py-2 text-xs">
{headline ? <p className="font-medium text-foreground">{headline}</p> : null}
- {item.text ? <p className="whitespace-pre-wrap leading-relaxed text-muted-foreground">{item.text}</p> : null}
+ {item.text ? <ChatMarkdown text={item.text} className="leading-relaxed text-muted-foreground" /> : null}
</div>
);
}
@@ -908,7 +907,7 @@ export function UserBubble({ item }: { item: UserItem }) {
{item.attachments.length > 0 ? (
<div className="flex flex-wrap justify-end gap-1">
{item.attachments.map((a) => (
- <span key={a.name} className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
+ a.url && (a.kind === "image" || mediaKind(a.url)) ? <MediaPreview key={a.name} src={a.url} label={a.name} kind={mediaKind(a.url) ?? "image"} /> : <span key={a.name} className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
{a.name}
</span>
))}
@@ -953,7 +952,7 @@ function Prose({ text, muted }: { text: string; muted?: boolean }) {
"prose-hr:my-3 prose-blockquote:border-l-2 prose-blockquote:pl-3 prose-blockquote:not-italic",
)}
>
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{text}</ReactMarkdown>
+ <ChatMarkdown text={text} />
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index cd4c1c3e81..0173c387be 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5537,5 +5537,12 @@
"command": "Befehl ausführen",
"edit": "Datei bearbeiten",
"write": "Datei schreiben"
+},
+ "chat_media": {
+ "unavailable": "Dieses Medium kann nicht geladen oder abgespielt werden. Du kannst die Datei weiterhin öffnen.",
+ "expand": "{file} vergrößern",
+ "open_file": "Datei öffnen",
+ "download": "Herunterladen",
+ "retry": "Erneut versuchen"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 36f38fd5e0..f2b1873373 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5570,5 +5570,12 @@
"command": "Run command",
"edit": "Edit file",
"write": "Write file"
+},
+ "chat_media": {
+ "unavailable": "This media cannot be loaded or played. You can still open the file.",
+ "expand": "Enlarge {file}",
+ "open_file": "Open file",
+ "download": "Download",
+ "retry": "Retry"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index facbe3924b..9879d6cdb6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5537,5 +5537,12 @@
"command": "Ejecutar comando",
"edit": "Editar archivo",
"write": "Escribir archivo"
+},
+ "chat_media": {
+ "unavailable": "No se puede cargar o reproducir este archivo. Puedes abrirlo directamente.",
+ "expand": "Ampliar {file}",
+ "open_file": "Abrir archivo",
+ "download": "Descargar",
+ "retry": "Reintentar"
}
}
diff --git a/tests/unit/agent_chat/test_media.py b/tests/unit/agent_chat/test_media.py
new file mode 100644
index 0000000000..c81bbb5a18
--- /dev/null
+++ b/tests/unit/agent_chat/test_media.py
@@ -0,0 +1,288 @@
+"""Every runner shares the same media delivery and workspace boundary."""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+
+import pytest
+
+from jarvis.agent_chat import media
+from jarvis.agent_chat.runner_cli import _content_text
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+
+PNG = b"\x89PNG\r\n\x1a\nexample image bytes"
+
+
+def event(output, kind="tool_result", **extra):
+ field = "text" if kind == "assistant_text" else "output"
+ return {"kind": kind, "ts_ms": 1000, "payload": {"turn_id": "turn", field: output, **extra}}
+
+
+def normalize(tmp_path, output, kind="tool_result", **extra):
+ cwd = tmp_path / "work"
+ cwd.mkdir(exist_ok=True)
+ return media.normalize_media_event(
+ event(output, kind, **extra), cwd=cwd, outputs_root=tmp_path / "archive", scope="session"
+ )
+
+
+def test_mixed_images_videos_and_audio_are_all_delivered(tmp_path):
+ outputs = [
+ {"url": "https://example.test/a.png"},
+ {"url": "https://example.test/b.mp4"},
+ {"url": "https://example.test/c.wav"},
+ ]
+ result = normalize(tmp_path, json.dumps({"results": outputs}))
+ assert len(result) == 4
+ assert "![image]" in result[1]["payload"]["text"]
+ assert "[video]" in result[2]["payload"]["text"]
+ assert "[audio]" in result[3]["payload"]["text"]
+ assert not (tmp_path / "archive").exists() # No arbitrary server-side URL fetch.
+
+
+ "shape",
+ [
+ lambda b: {"content": [{"type": "image", "mimeType": "image/png", "data": b}]},
+ lambda b: {"data": [{"b64_json": b}]},
+ lambda b: {"inlineData": {"mimeType": "image/png", "data": b}},
+ lambda b: {"resource": {"mimeType": "image/png", "blob": b}},
+ lambda b: {"type": "image_generation_call", "result": b},
+ ],
+)
+def test_binary_receipt_shapes_become_small_durable_links(tmp_path, shape):
+ encoded = base64.b64encode(PNG).decode()
+ result = normalize(tmp_path, json.dumps(shape(encoded)))
+ assert len(result) == 2
+ assert encoded not in json.dumps(result)
+ files = list((tmp_path / "archive").rglob("*.png"))
+ assert len(files) == 1 and files[0].read_bytes() == PNG
+ assert "/api/outputs/" in result[1]["payload"]["text"]
+
+
+ "shape",
+ [
+ {"image_url": {"url": "https://example.test/signed?id=1"}},
+ {"video": {"url": "https://example.test/signed?id=1"}},
+ {
+ "type": "resource_link",
+ "mimeType": "video/mp4",
+ "uri": "https://example.test/signed?id=1",
+ },
+ {"image_url": "https://example.test/signed?id=1"},
+ ],
+)
+def test_extensionless_urls_keep_their_media_hint(tmp_path, shape):
+ result = normalize(tmp_path, shape)
+ assert len(result) == 2
+ assert "#jarvis-media=" in result[1]["payload"]["text"]
+ assert "?id=1" in result[1]["payload"]["text"]
+
+
+ "name", ["movie.mp4", "photo with spaces.webp", "sound.mp3", "diagram.svg"]
+)
+def test_local_cli_files_are_retained_after_the_source_is_removed(tmp_path, name):
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ source = cwd / name
+ source.write_bytes(b"tool-created media")
+ result = normalize(tmp_path, {"file_path": str(source)})
+ source.unlink()
+ assert len(result) == 2
+ assert [p.read_bytes() for p in (tmp_path / "archive").rglob("media.*")] == [
+ b"tool-created media"
+ ]
+ assert str(cwd) not in result[1]["payload"]["text"]
+
+
+def test_markdown_local_media_stays_in_place_without_a_duplicate(tmp_path):
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ (cwd / "plot.png").write_bytes(PNG)
+ result = normalize(tmp_path, "Before.\n\n![Plot](plot.png)\n\nAfter.", "assistant_text")
+ assert len(result) == 1
+ text = result[0]["payload"]["text"]
+ assert "![Plot](</api/outputs/" in text
+ assert text.startswith("Before.") and text.endswith("After.")
+
+
+def test_preserves_normal_links_and_does_not_scan_code_examples(tmp_path):
+ text = '[Documentation](https://example.test/docs "Title")\n```sh\nread /secret/photo.png\n```'
+ result = normalize(tmp_path, text, "assistant_text")
+ assert result == [event(text, "assistant_text")]
+
+
+def test_quoted_cli_media_paths_with_spaces(tmp_path):
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ (cwd / "final movie.mp4").write_bytes(b"video")
+ result = normalize(tmp_path, 'Saved "final movie.mp4"')
+ assert len(result) == 2
+ assert "[video]" in result[1]["payload"]["text"]
+
+
+ "name,reference", [("frame#1.png", "frame#1.png"), ("my photo.png", "my%20photo.png")]
+)
+def test_local_media_filenames_are_not_mistaken_for_url_fragments(tmp_path, name, reference):
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ (cwd / name).write_bytes(PNG)
+ result = normalize(tmp_path, {"path": reference})
+ assert len(result) == 2
+ assert "![image]" in result[1]["payload"]["text"]
+
+
+def test_plain_remote_url_is_rendered_in_place_without_duplicate(tmp_path):
+ result = normalize(tmp_path, "Watch https://example.test/clip.mp4", "assistant_text")
+ assert len(result) == 1
+
+
+def test_mixed_assistant_content_keeps_text_and_each_visual_in_order(tmp_path):
+ blocks = [
+ {"type": "text", "text": "First image:"},
+ {"type": "image_url", "image_url": {"url": "https://example.test/first.png"}},
+ {"type": "text", "text": "Then the video:"},
+ {"type": "video", "url": "https://example.test/second.mp4"},
+ ]
+ result = normalize(tmp_path, json.dumps({"content": blocks}), "assistant_text")
+ assert len(result) == 1
+ text = result[0]["payload"]["text"]
+ assert (
+ text.index("First image:")
+ < text.index("![image]")
+ < text.index("Then the video:")
+ < text.index("[video]")
+ )
+ assert "image_url" not in text
+
+
+def test_uploaded_media_uses_the_existing_attachment_url_contract(tmp_path):
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ (cwd / "upload.mp4").write_bytes(b"video attachment")
+ original = {
+ "kind": "user_message",
+ "payload": {
+ "text": "Watch this",
+ "attachments": [{"name": "upload.mp4", "kind": "other", "reference": '"upload.mp4"'}],
+ },
+ }
+ result = media.normalize_media_event(
+ original, cwd=cwd, outputs_root=tmp_path / "archive", scope="session"
+ )
+ assert len(result) == 1
+ attachment = result[0]["payload"]["attachments"][0]
+ assert attachment["url"].startswith("/api/outputs/")
+ assert "reference" not in attachment
+ assert result[0]["payload"]["text"] == "Watch this"
+
+
+def test_backend_and_renderer_recognize_the_same_media_extensions():
+ import re
+ from pathlib import Path
+
+ source = (
+ Path(__file__).resolve().parents[3]
+ / "jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx"
+ ).read_text(encoding="utf-8")
+ block = source.split("const EXTENSIONS:", 1)[1].split("};", 1)[0]
+ frontend = dict(re.findall(r'(\w+): "(image|video|audio)"', block))
+ assert frontend == {ext[1:]: mime.split("/", 1)[0] for ext, mime in media.MEDIA_TYPES.items()}
+
+
+def test_archived_video_supports_byte_ranges_for_seeking(tmp_path):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.outputs_routes import router
+
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ data = b"video byte range fixture"
+ (cwd / "clip.mp4").write_bytes(data)
+ result = normalize(tmp_path, {"path": "clip.mp4"})
+ url = result[1]["payload"]["text"].split("(<", 1)[1].split(">)", 1)[0]
+ app = FastAPI()
+ app.state.outputs_root = tmp_path / "archive"
+ app.include_router(router)
+ with TestClient(app) as client:
+ response = client.get(url, headers={"Range": "bytes=0-3"})
+ assert response.status_code == 206
+ assert response.content == data[:4]
+ assert response.headers["content-type"] == "video/mp4"
+
+
+def test_changing_media_is_not_published_as_a_complete_artifact(tmp_path):
+ file = tmp_path / "clip.mp4"
+ file.write_bytes(b"initial")
+ expected = file.stat()
+ file.write_bytes(b"still being written")
+ archive = tmp_path / "archive"
+ normalizer = media.MediaNormalizer(tmp_path, archive, "session")
+ with file.open("rb") as source, pytest.raises(ValueError, match="changed"):
+ normalizer._archive(source, ".mp4", expected)
+ assert not list(archive.rglob(".standalone-run.json"))
+
+
+def test_media_in_failed_tool_output_is_not_claimed_as_a_result(tmp_path):
+ result = normalize(tmp_path, "https://example.test/photo.png", is_error=True)
+ assert len(result) == 1
+
+
+ "reference",
+ [
+ "../secret.png",
+ "file:///etc/private.png",
+ "https://user:[email protected]/a.png",
+ "javascript:alert(1).png",
+ ],
+)
+def test_invalid_or_outside_workspace_media_is_not_imported(tmp_path, reference):
+ (tmp_path / "secret.png").write_bytes(PNG)
+ result = normalize(tmp_path, {"path": reference})
+ assert not list((tmp_path / "archive").glob("*"))
+ assert all("![image]" not in str(item) for item in result)
+ assert result[-1]["kind"] == "error"
+
+
+def test_import_limit_reports_an_error_instead_of_silently_hiding_media(tmp_path, monkeypatch):
+ monkeypatch.setattr(media, "MAX_FILE_BYTES", 2)
+ cwd = tmp_path / "work"
+ cwd.mkdir()
+ (cwd / "large.mp4").write_bytes(b"large video")
+ result = normalize(tmp_path, {"path": "large.mp4"})
+ assert result[-1]["kind"] == "error"
+ assert not list((tmp_path / "archive").rglob("media.mp4"))
+
+
+def test_claude_shaped_content_does_not_discard_non_text_media():
+ blocks = [
+ {"type": "text", "text": "Here is the video"},
+ {"type": "resource_link", "mimeType": "video/mp4", "uri": "https://example.test/video.mp4"},
+ ]
+ assert json.loads(_content_text(blocks)) == blocks
+
+
[email protected]("provider", ["openai", "google", "openai-codex", "arbitrary-cli"])
+def test_service_persists_and_streams_media_for_any_provider(tmp_path, monkeypatch, provider):
+ monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(tmp_path / "archive"))
+ store = AgentChatStore(tmp_path / "chat.db")
+ session = store.create_session(provider=provider, model="", effort="", cwd=str(tmp_path))
+ service = AgentChatService(store)
+ queue = service.subscribe(session.session_id)
+ asyncio.run(
+ service._emit(session.session_id, event('{"url":"https://example.test/result.webm"}'))
+ )
+ persisted = store.list_events(session.session_id)
+ assert [item["kind"] for item in persisted] == ["tool_result", "assistant_text"]
+ assert queue.get_nowait() == persisted[0]
+ assert queue.get_nowait() == persisted[1]
+ assert "[video]" in persisted[1]["payload"]["text"]
+ store.close()