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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): global media dedup + session-less proxy URL + open paths (#408)
Call White44ac19e22c3a
diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 99b5c561c..066d8f171 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -196,9 +196,8 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: sttry:from core.workbench_media import rewrite_agent_media- workdir = (spec.get("agent_session_target") or {}).get("workdir")text = rewrite_agent_media(- conn, scope_id=scope_id, session_id=row_session_id, text=text, workdir=workdir+ conn, scope_id=scope_id, session_id=row_session_id, text=text)except Exception:logger.exception("persist_agent_message: media rewrite failed")diff --git a/core/workbench_media.py b/core/workbench_media.pyindex d5bd3dc5b..5f9f4851a 100644--- a/core/workbench_media.py+++ b/core/workbench_media.py@@ -10,8 +10,8 @@ card) without ever touching ``file://`` or an attacker-chosen remote host.We reuse the reply-enhancer's file-link parser (one home for "what a file linklooks like") and, for each link, register the local file under an opaque token(:func:`storage.media_service.register`) then swap the URL for-``/api/sessions/<session_id>/media/<token>``. The ``!``/``[]`` Markdown shape is-preserved, so the frontend renders images vs files purely from element type.+``/api/media/<token>``. The ``!``/``[]`` Markdown shape is preserved, so the+frontend renders images vs files purely from element type."""from __future__ import annotations@@ -23,71 +23,30 @@ from urllib.parse import urlparsefrom sqlalchemy.engine import Connection-from config.paths import get_attachments_dirfrom core.reply_enhancer import _FILE_LINK_RE, _file_uri_to_local_pathfrom storage import media_servicelogger = logging.getLogger(__name__)-def _allowed_media_roots(workdir: str | None, session_id: str) -> list[Path]:- """Directories an agent reply may legitimately reference: the session's- working directory (where it produces files), THIS session's own upload dir,- and the Codex generated-images dir. The shared OS temp dir is deliberately- NOT included — ``/tmp`` is writable by unrelated tools and holds transient- secrets, so a prompt-injected ``[x](file:///tmp/secret)`` must not mint a- token. The uploads root is scoped to ``attachments/avibe/<session_id>`` (not- the whole attachments tree) so an agent reply can't mint a token for another- session's / IM channel's upload. Anything outside these roots- (``~/.vibe_remote/config.json``, ``~/.ssh``, another session, ...) is refused,- so untrusted output can't exfiltrate files through the media proxy. Agents- that want to show a produced file write it under their workdir."""- roots: list[Path] = []-- def _add(value) -> None:- try:- roots.append(Path(value).resolve())- except Exception:- pass-- _add(get_attachments_dir() / "avibe" / session_id)- _add(Path(os.environ.get("CODEX_HOME") or (Path.home() / ".codex")) / "generated_images")- if workdir:- _add(workdir)- return roots---def _safe_resolved_path(path: str, roots: list[Path]) -> str | None:- """Resolve *path* (following symlinks) and return it as a string only when it- sits at/inside one of *roots*; otherwise ``None``."""- try:- resolved = Path(path).resolve()- except Exception:- return None- for root in roots:- if resolved == root or root in resolved.parents:- return str(resolved)- return None---def rewrite_agent_media(- conn: Connection, *, scope_id: str, session_id: str, text: str, workdir: str | None = None-) -> str:+def rewrite_agent_media(conn: Connection, *, scope_id: str, session_id: str, text: str) -> str:"""Return *text* with ``file://`` links rewritten to media-proxy URLs.Registers each referenced file in ``media_objects`` (same transaction as the- caller's message insert). Only paths inside the session's safe roots- (workdir / temp / uploads / Codex images) are registered — untrusted agent- output can't mint a token for an arbitrary file such as ``~/.ssh/id_rsa`` or- ``~/.vibe_remote/config.json``. Non-``file://`` URLs, non-absolute paths, and- out-of-root paths are left untouched. Best-effort: a registration failure- leaves that one link as written rather than dropping the reply.+ caller's message insert) and swaps the ``file://`` URL for a same-origin+ ``/api/media/<token>``. Any absolute path the agent references is allowed:+ this is the user's own machine and the agent (Claude Code / Codex) already+ has full filesystem read access, so the proxy grants no capability it didn't+ already have — it just lets the user view what the agent points at. The path+ is resolved to its canonical (symlink-free) form before registering, and the+ serve endpoint re-resolves at fetch time and refuses if it changed, so a+ token can't be repointed at another file after minting. Non-``file://`` URLs+ and non-absolute paths are left untouched. Best-effort: a registration+ failure leaves that one link as written rather than dropping the reply."""if not text or "file://" not in text:return text- roots = _allowed_media_roots(workdir, session_id)-def _replace(match) -> str:bang, label, url = match.group(1), match.group(2), match.group(3)parsed = urlparse(url)@@ -97,9 +56,10 @@ def rewrite_agent_media(if not os.path.isabs(path):logger.warning("workbench_media: skipping non-absolute file link: %s", url)return match.group(0)- safe_path = _safe_resolved_path(path, roots)- if safe_path is None:- logger.warning("workbench_media: refusing media outside safe roots: %s", path)+ try:+ safe_path = str(Path(path).resolve())+ except Exception:+ logger.warning("workbench_media: could not resolve file link: %s", url)return match.group(0)try:token = media_service.register(@@ -114,7 +74,7 @@ def rewrite_agent_media(except Exception:logger.exception("workbench_media: failed to register media for %s", safe_path)return match.group(0)- return f"{bang}[{label}](/api/sessions/{session_id}/media/{token})"+ return f"{bang}[{label}](/api/media/{token})"return _FILE_LINK_RE.sub(_replace, text)diff --git a/storage/alembic/versions/20260603_0014_media_mtime.py b/storage/alembic/versions/20260603_0014_media_mtime.pynew file mode 100644index 000000000..2240aa236--- /dev/null+++ b/storage/alembic/versions/20260603_0014_media_mtime.py@@ -0,0 +1,44 @@+"""media_objects.mtime_ns for machine-global content-fingerprint dedup++``storage.media_service.register`` now reuses an existing token for the same+``(local_path, size_bytes, mtime_ns)`` instead of minting a new one per+reference, so a re-referenced file keeps one stable ``/api/media/<token>`` URL+and the browser can cache it. ``mtime_ns`` + ``size_bytes`` is the change+fingerprint (stat-only, no file read); a rewrite bumps mtime so changed content+gets a fresh token/URL. The dedup index backs the lookup.++Revision ID: 20260603_0014+Revises: 20260602_0013+Create Date: 2026-06-03+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260603_0014"+down_revision = "20260602_0013"+branch_labels = None+depends_on = None+++def _columns(table: str) -> set[str]:+ bind = op.get_bind()+ return {row[1] for row in bind.exec_driver_sql(f"PRAGMA table_info({table})")}+++def upgrade() -> None:+ if "mtime_ns" not in _columns("media_objects"):+ op.add_column("media_objects", sa.Column("mtime_ns", sa.Integer(), nullable=True))+ op.create_index(+ "ix_media_objects_dedup",+ "media_objects",+ ["local_path", "size_bytes", "mtime_ns"],+ if_not_exists=True,+ )+++def downgrade() -> None:+ op.drop_index("ix_media_objects_dedup", table_name="media_objects")+ op.drop_column("media_objects", "mtime_ns")diff --git a/storage/media_service.py b/storage/media_service.pyindex 515f16da3..9a48090ae 100644--- a/storage/media_service.py+++ b/storage/media_service.py@@ -1,7 +1,7 @@"""CRUD over the ``media_objects`` proxy-token table.-A single write path (:func:`register`) mints an opaque token for a local file-so the workbench can serve it over ``/api/sessions/<id>/media/<token>`` without+A single write path (:func:`register`) mints (or reuses) an opaque token for a+local file so the workbench can serve it over ``/api/media/<token>`` withoutever putting a filesystem path in the URL. Both agent-reply media (rewritten in``core/workbench_media``) and user uploads register here, so the proxy endpointand the UI file card have one shape to read.@@ -42,21 +42,47 @@ def register(content_type: Optional[str] = None,message_id: Optional[str] = None,) -> str:- """Register *local_path* under a fresh token and return the token.+ """Register *local_path* under a token and return it, reusing an existing+ token for the same file so its proxy URL is stable + cacheable.- ``content_type`` / ``file_ext`` / ``size_bytes`` are derived from the path- when not supplied so the proxy response and UI card don't re-compute them.+ Dedup is machine-global on the ``(local_path, size_bytes, mtime_ns)``+ fingerprint — scope/session are intentionally NOT part of the key, so the+ same file referenced from any message or session resolves to one URL the+ browser can cache. ``mtime_ns`` + ``size_bytes`` is a stat-only change+ detector: a rewritten file (new size/mtime) mints a fresh token, busting the+ cache. ``content_type`` / ``file_ext`` / ``size_bytes`` are derived from the+ path when not supplied so the proxy response and UI card don't re-compute+ them."""path = Path(local_path)name = file_name or path.nameext = (path.suffix.lower().lstrip(".") or None)ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"size: Optional[int] = None+ mtime_ns: Optional[int] = Nonetry:if path.is_file():- size = path.stat().st_size+ stat = path.stat()+ size = stat.st_size+ mtime_ns = stat.st_mtime_nsexcept OSError:size = None+ mtime_ns = None++ # Reuse an existing live token for the same fingerprint (stable, cacheable+ # URL). Only when both size + mtime are known — an unstattable file can't be+ # fingerprinted, so fall through to a fresh row.+ if size is not None and mtime_ns is not None:+ existing = conn.execute(+ select(media_objects.c.token).where(+ media_objects.c.local_path == str(local_path),+ media_objects.c.size_bytes == size,+ media_objects.c.mtime_ns == mtime_ns,+ media_objects.c.revoked_at.is_(None),+ )+ ).scalar()+ if existing:+ return existingtoken = _new_token()conn.execute(@@ -72,6 +98,7 @@ def register(content_type=ctype,file_ext=ext,size_bytes=size,+ mtime_ns=mtime_ns,created_at=_utc_now_iso(),expires_at=None,revoked_at=None,diff --git a/storage/models.py b/storage/models.pyindex 590eca3bf..d6afc5e24 100644--- a/storage/models.py+++ b/storage/models.py@@ -322,13 +322,16 @@ messages = Table(# Opaque-token proxy for chat media. The workbench browser can't load# ``file://`` and we deliberately neuter arbitrary remote images, so a local# file referenced by an agent reply (or uploaded by the user) is registered-# here and served back over ``/api/sessions/<session_id>/media/<token>``. The-# URL carries only the opaque ``token`` — never a filesystem path — so the-# proxy can't be coaxed into reading an arbitrary file: only rows we minted are-# reachable. ``content_type`` / ``file_ext`` are stored so the response and the-# UI file card don't have to re-derive them; ``kind`` (image|file) selects-# inline-image vs download-card rendering; ``source`` distinguishes agent-# output from user uploads so one table serves both.+# here and served back over ``/api/media/<token>``. The URL carries only the+# opaque ``token`` — never a filesystem path, never a session — so it is stable+# across messages/sessions and the browser can cache it. ``content_type`` /+# ``file_ext`` are stored so the response and the UI file card don't have to+# re-derive them; ``kind`` (image|file) selects inline-image vs download-card+# rendering; ``source`` distinguishes agent output from user uploads so one+# table serves both. ``size_bytes`` + ``mtime_ns`` are the content fingerprint:+# :func:`storage.media_service.register` reuses an existing token for the same+# (local_path, size_bytes, mtime_ns) so a re-referenced file keeps one cacheable+# URL, while a changed file mints a fresh token (busting the browser cache).media_objects = Table("media_objects",metadata,@@ -343,11 +346,14 @@ media_objects = Table(Column("content_type", String, nullable=True),Column("file_ext", String, nullable=True),Column("size_bytes", Integer, nullable=True),+ Column("mtime_ns", Integer, nullable=True),Column("created_at", String, nullable=False),Column("expires_at", String, nullable=True),Column("revoked_at", String, nullable=True),Index("ix_media_objects_session", "session_id"),Index("ix_media_objects_scope_created", "scope_id", "created_at"),+ # Backs register()'s dedup lookup (machine-global content fingerprint).+ Index("ix_media_objects_dedup", "local_path", "size_bytes", "mtime_ns"),)imported_state_tables = [diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 3ac0b8906..e1fa2e71e 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260602_0013"+HEAD_REVISION = "20260603_0014"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:@@ -41,6 +41,10 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert "show_pages" in tablesassert "show_session_events" in tablesassert "media_objects" in tables+ media_columns = {+ row[1] for row in conn.execute("pragma table_info(media_objects)")+ }+ assert "mtime_ns" in media_columns # 20260603_0014: dedup fingerprintbackground_columns = {row[1]for row in conn.execute(diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.pyindex bfde44c86..be9fcff8c 100644--- a/tests/test_workbench_media.py+++ b/tests/test_workbench_media.py@@ -79,6 +79,7 @@ def test_register_and_get_by_token(tmp_path):assert row["content_type"] == "image/png"assert row["file_ext"] == "png"assert row["size_bytes"] == 8+ assert row["mtime_ns"] is not Noneassert row["local_path"] == str(shot)assert row["session_id"] == "sess_x"@@ -100,14 +101,12 @@ def test_rewrite_in_place_image_file_and_external(tmp_path):with engine.begin() as conn:scope_id = _seed_scope_and_session(conn)- out = rewrite_agent_media(- conn, scope_id=scope_id, session_id="sess_x", text=text, workdir=str(tmp_path)- )+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)# Both file:// links are rewritten in place to same-origin proxy URLs.assert "file://" not in out- assert out.startswith("See - assert "the [report](/api/sessions/sess_x/media/" in out+ assert out.startswith("See + assert "the [report](/api/media/" in out# External URL is left untouched (no token, no rewrite).assert "[docs](https://example.com/x)" in out@@ -200,45 +199,59 @@ def test_process_reply_keep_file_links():assert len(kept.files) == 2-def test_rewrite_refuses_paths_outside_safe_roots(tmp_path):+def test_rewrite_allows_any_absolute_path(tmp_path):db = tmp_path / "vibe.sqlite"run_migrations(db)engine = create_sqlite_engine(db)from core.workbench_media import rewrite_agent_media- # A path outside temp / uploads / workdir / Codex roots (here /etc/hosts) must- # NOT mint a token, so untrusted agent output can't exfiltrate secrets.- text = "see [hosts](file:///etc/hosts)"+ # Any absolute path the agent references is proxied — it's the user's own+ # machine and the agent already has full FS read, so the proxy grants nothing+ # new. A file outside any "project" dir is rewritten + resolved canonically.+ outside = tmp_path / "outside.png"+ outside.write_bytes(b"x")+ text = f""with engine.begin() as conn:scope_id = _seed_scope_and_session(conn)- out = rewrite_agent_media(- conn, scope_id=scope_id, session_id="sess_x", text=text, workdir=str(tmp_path / "proj")- )- assert out == text # left untouched, no proxy URL+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)+ assert "/api/media/" in out+ assert "file://" not in outwith engine.connect() as conn:- assert conn.execute(select(media_objects)).first() is None+ rows = conn.execute(select(media_objects)).mappings().all()+ assert len(rows) == 1+ assert rows[0]["local_path"] == str(outside.resolve())-def test_rewrite_allows_paths_under_workdir(tmp_path):+def test_register_dedups_same_fingerprint(tmp_path):db = tmp_path / "vibe.sqlite"run_migrations(db)engine = create_sqlite_engine(db)- from core.workbench_media import rewrite_agent_media+ shot = tmp_path / "shot.png"+ shot.write_bytes(b"abc")- workdir = tmp_path / "proj"- workdir.mkdir()- img = workdir / "out.png"- img.write_bytes(b"x")- text = f""with engine.begin() as conn:scope_id = _seed_scope_and_session(conn)- out = rewrite_agent_media(- conn, scope_id=scope_id, session_id="sess_x", text=text, workdir=str(workdir)+ t1 = media_service.register(+ conn, scope_id=scope_id, session_id="sess_x", kind="image",+ source="agent_reply", local_path=str(shot),+ )+ # Same file (path + size + mtime), DIFFERENT session → same token: dedup is+ # machine-global, so the proxy URL stays stable + cacheable.+ t2 = media_service.register(+ conn, scope_id=scope_id, session_id="other", kind="image",+ source="agent_reply", local_path=str(shot),)- assert "/api/sessions/sess_x/media/" in out+ assert t2 == t1+ # Content change (new size + mtime) → fresh token, busting the cache.+ shot.write_bytes(b"abcdef-changed")+ t3 = media_service.register(+ conn, scope_id=scope_id, session_id="sess_x", kind="image",+ source="agent_reply", local_path=str(shot),+ )+ assert t3 != t1+with engine.connect() as conn:rows = conn.execute(select(media_objects)).mappings().all()- assert len(rows) == 1- assert rows[0]["local_path"] == str(img.resolve())+ assert len(rows) == 2 # original (reused once) + the changed filediff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsxindex 373cb327c..b116eae45 100644--- a/ui/src/components/ui/file-card.tsx+++ b/ui/src/components/ui/file-card.tsx@@ -9,7 +9,7 @@ import { isProxyMediaUrl } from '@/lib/mediaProxy';import { cn } from '@/lib/utils';// Download card for an agent-reply file that was rewritten to the same-origin-// media proxy (``/api/sessions/<id>/media/<token>``). Rendered by the shared+// media proxy (``/api/media/<token>``). Rendered by the shared// Markdown renderer in place of a plain ``[label](proxy)`` link. The icon tile// is tinted by file type; the type + size come from a lightweight ``/meta``// fetch so we don't have to download the file to label it. Composed from thediff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex ac566b7b6..a99db3612 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -646,7 +646,7 @@ export const ChatPage: React.FC = () => {}}if (m.text) {- const re = /!\[[^\]]*\]\((\/api\/sessions\/[^)\s]+\/media\/[^)\s]+)\)/g;+ const re = /!\[[^\]]*\]\((\/api\/media\/[^)\s]+)\)/g;let match: RegExpExecArray | null;while ((match = re.exec(m.text)) !== null) push(match[1]);}diff --git a/ui/src/lib/mediaProxy.ts b/ui/src/lib/mediaProxy.tsindex c5cc5ffcc..a5e877928 100644--- a/ui/src/lib/mediaProxy.ts+++ b/ui/src/lib/mediaProxy.ts@@ -1,10 +1,10 @@// A same-origin agent-media proxy URL, minted server-side by-// ``core/workbench_media`` (``/api/sessions/<id>/media/<token>``). These are the-// ONLY image/file URLs the workbench trusts to fetch or render without an-// explicit user click — they hit our own server, never a third-party host. Used-// by the Markdown renderer (inline images), the FileCard (metadata fetch), and-// the user-message attachment renderer to enforce one same-origin policy.-const MEDIA_PROXY_RE = /^\/api\/sessions\/[^/]+\/media\/[^/?#]+/;+// ``core/workbench_media`` (``/api/media/<token>``). These are the ONLY+// image/file URLs the workbench trusts to fetch or render without an explicit+// user click — they hit our own server, never a third-party host. Used by the+// Markdown renderer (inline images), the FileCard (metadata fetch), and the+// user-message attachment renderer to enforce one same-origin policy.+const MEDIA_PROXY_RE = /^\/api\/media\/[^/?#]+/;export function isProxyMediaUrl(url: string | null | undefined): boolean {return !!url && MEDIA_PROXY_RE.test(url);diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex afc0ad6b6..22347a608 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3252,16 +3252,17 @@ _INLINE_SAFE_MEDIA_TYPES = {}[email protected]("/api/sessions/<session_id>/media/<token>", methods=["GET"])-def sessions_media_get(session_id: str, token: str):[email protected]("/api/media/<token>", methods=["GET"])+def media_get(token: str):"""Serve a registered chat-media file (agent reply / upload) by opaque token.- The token — not a path — is the capability: only files registered for this- session in ``media_objects`` are reachable, so the proxy can't be steered to- an arbitrary file. Lives under ``/api/*`` so the remote-access auth- middleware already gates it, and a same-origin ``<img>`` / anchor GET carries- the session cookie. Defaults to ``inline`` (so images render in ``<img>`` and- PDFs preview); ``?download=1`` forces an attachment download.+ The token — not a path, not a session — is the capability: only files we+ minted into ``media_objects`` are reachable, and the same token resolves to+ one stable URL the browser can cache across messages/sessions. Lives under+ ``/api/*`` so the remote-access auth middleware already gates it, and a+ same-origin ``<img>`` / anchor GET carries the session cookie. Defaults to+ ``inline`` (so images render in ``<img>`` and PDFs preview); ``?download=1``+ forces an attachment download."""from urllib.parse import quote@@ -3270,7 +3271,7 @@ def sessions_media_get(session_id: str, token: str):engine = _projects_engine()with engine.connect() as conn:row = media_service.get_by_token(conn, token)- if not row or row.get("session_id") != session_id or row.get("revoked_at"):+ if not row or row.get("revoked_at"):return jsonify({"error": "not_found"}), 404stored = row["local_path"]try:@@ -3297,8 +3298,8 @@ def sessions_media_get(session_id: str, token: str):return response[email protected]("/api/sessions/<session_id>/media/<token>/meta", methods=["GET"])-def sessions_media_meta(session_id: str, token: str):[email protected]("/api/media/<token>/meta", methods=["GET"])+def media_meta(token: str):"""Lightweight metadata for a media token so the UI file card can show thename / type / size without downloading the file. Same token gate as thefile route."""@@ -3307,7 +3308,7 @@ def sessions_media_meta(session_id: str, token: str):engine = _projects_engine()with engine.connect() as conn:row = media_service.get_by_token(conn, token)- if not row or row.get("session_id") != session_id or row.get("revoked_at"):+ if not row or row.get("revoked_at"):return jsonify({"error": "not_found"}), 404return jsonify({@@ -3384,7 +3385,7 @@ def sessions_attachments_create(session_id: str):"mime": mime,"size": len(raw),"kind": kind,- "url": f"/api/sessions/{session_id}/media/{token}",+ "url": f"/api/media/{token}",}),201,