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(workbench): rich media in chat — agent images/files, upload, voice (#393)

Call White7699f2e0aec9
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 972c65dd5..fd7123c53 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -849,6 +849,19 @@ class MessageHandler(BaseHandler):
if not isinstance(attachment, FileAttachment):
continue
+ # Already on local disk (e.g. an avibe workbench upload, saved by the
+ # UI server before dispatch) — there is nothing to download, so pass
+ # it straight through to the agent turn. IM attachments arrive with a
+ # ``url`` and no ``local_path`` and fall through to the download path.
+ if attachment.local_path and os.path.isfile(attachment.local_path):
+ if attachment.size is None:
+ try:
+ attachment.size = os.path.getsize(attachment.local_path)
+ except OSError:
+ pass
+ processed.append(attachment)
+ continue
+
try:
im_client = self._get_im_client(context)
# Download the file content. Some platforms receive a thin
diff --git a/core/internal_server.py b/core/internal_server.py
index 2c45b4f5d..658c4cf76 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -518,13 +518,20 @@ def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContex
"""
text = payload.get("text")
- if not isinstance(text, str) or not text.strip():
- raise ValueError("text is required")
+ text = text if isinstance(text, str) else ""
session_id = payload.get("session_id")
if not isinstance(session_id, str) or not session_id.strip():
raise ValueError("session_id is required")
+ # A turn may be text-only, attachments-only (the agent reads the files), or
+ # both. ``files`` are already-local web uploads resolved from media tokens.
+ from core.workbench_media import file_attachments_from_specs
+
+ files = file_attachments_from_specs(payload.get("files"))
+ if not text.strip() and not files:
+ raise ValueError("text or files is required")
+
context = _build_session_context(
session_id,
user_id=payload.get("user_id"),
@@ -532,6 +539,7 @@ def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContex
platform=payload.get("platform"),
thread_id=payload.get("thread_id"),
message_id=payload.get("message_id"),
+ files=files,
)
return text, context
@@ -544,6 +552,7 @@ def _build_session_context(
platform: Optional[str] = None,
thread_id: Optional[str] = None,
message_id: Optional[str] = None,
+ files: Optional[list] = None,
) -> MessageContext:
"""Build the avibe ``MessageContext`` for a workbench session.
@@ -590,6 +599,7 @@ def _build_session_context(
thread_id=thread_id,
message_id=message_id,
platform_specific=platform_specific,
+ files=files,
)
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index e3b5a36d8..43cd00a0e 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -652,7 +652,19 @@ class ConsolidatedMessageDispatcher:
# A failed terminal result persists as type='error' so it shows in
# the transcript/inbox like any terminal message but is NOT counted
# as an unread agent reply (unread queries are result-only). Codex P2.
- persist_agent_message(target_context, "error" if is_error else "result", persist_text)
+ result_type = "error" if is_error else "result"
+ if target_context.platform == "avibe":
+ # Keep the ``file://`` links in the persisted avibe text so the
+ # workbench media-proxy rewrite (in ``persist_agent_message``)
+ # can turn them into inline images / file cards. ``persist_text``
+ # already has them stripped to plain labels for IM delivery.
+ avibe_text = (
+ process_reply(text, include_quick_replies=quick_replies_on, keep_file_links=True).text
+ or persist_text
+ )
+ persist_agent_message(target_context, result_type, avibe_text)
+ else:
+ persist_agent_message(target_context, result_type, persist_text)
if primary_message_id and display_text:
# Stream the delivered result to live consumers (avibe SSE).
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 1de4a3628..99b5c561c 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -186,6 +186,22 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: st
# is left to the agent-id wiring later; the session already carries it.
spec = context.platform_specific or {}
agent_name = spec.get("vibe_agent_name") or (spec.get("agent_session_target") or {}).get("agent_name")
+ # Workbench Chat only: rewrite ``file://`` links in the persisted copy
+ # to same-origin media-proxy URLs so the browser renders agent images
+ # inline + files as download cards. IM rows keep the raw ``file://``
+ # (the dispatcher uploads those to the platform separately). Scoped to
+ # the user-visible result/notify rows so we don't mint tokens for the
+ # hidden intermediate assistant/tool_call stream.
+ if context.platform == "avibe" and message_type in ("result", "notify", "error") and row_session_id:
+ try:
+ 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
+ )
+ except Exception:
+ logger.exception("persist_agent_message: media rewrite failed")
appended_row = _append_quietly(
conn,
scope_id=scope_id,
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 08cf2981f..02f35b9e4 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -90,15 +90,23 @@ _UNTERMINATED_SILENT_RE = re.compile(r"<silent\b[^>]*>.*\Z", re.IGNORECASE | re.
# ---------------------------------------------------------------------------
-def process_reply(text: str, *, include_quick_replies: bool = True) -> EnhancedReply:
+def process_reply(
+ text: str, *, include_quick_replies: bool = True, keep_file_links: bool = False
+) -> EnhancedReply:
"""Parse *text* and return an ``EnhancedReply``.
The returned ``.text`` has file-link markup converted to plain labels and
the trailing button block stripped when quick replies are enabled.
+
+ When *keep_file_links* is True the ``file://`` markdown is left intact in the
+ returned text (the links are still reported in ``.files``). The avibe
+ workbench needs the links in place so it can rewrite them to media-proxy URLs
+ for inline rendering; IM keeps the default (links stripped to plain labels and
+ uploaded to the platform separately).
"""
text = strip_silent_blocks(text)
files = _extract_file_links(text)
- text_no_files = _strip_file_links(text) if files else text
+ text_no_files = text if keep_file_links else (_strip_file_links(text) if files else text)
if include_quick_replies:
buttons, text_clean = _extract_buttons(text_no_files)
else:
diff --git a/core/session_turns.py b/core/session_turns.py
index 2101263b4..d45b563a5 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -329,6 +329,7 @@ class SessionTurnManager:
source when it finally runs (#84). Returns True if a turn was started, False
on an empty queue / failure."""
from core.inbox_events import bus
+ from core.workbench_media import file_attachments_from_specs, resolve_attachment_specs
from storage import messages_service
from storage.db import create_sqlite_engine
@@ -341,6 +342,7 @@ class SessionTurnManager:
scheduled_message_id = None
user_row = None
inbox_row = None
+ attachment_specs: list = []
try:
engine = create_sqlite_engine()
with engine.begin() as conn:
@@ -366,8 +368,20 @@ class SessionTurnManager:
messages_service.delete_queued(conn, [r["id"] for r in segment])
if not is_scheduled:
texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]
- if not texts:
+ # Carry attachments queued in this user segment so a file
+ # attached while the agent was busy still reaches the merged
+ # turn. An attachment-ONLY segment has empty texts but must
+ # still run (the agent reads the files), so guard on both.
+ queued_attachments = [
+ att
+ for r in segment
+ for att in ((r.get("content") or {}).get("attachments") or [])
+ ]
+ if not texts and not queued_attachments:
return False
+ attachment_specs = resolve_attachment_specs(
+ conn, session_id=session_id, attachments=queued_attachments
+ )
user_row = messages_service.append(
conn,
scope_id=segment[0]["scope_id"],
@@ -377,6 +391,7 @@ class SessionTurnManager:
source="user",
message_type="user",
text="\n".join(texts),
+ content={"attachments": queued_attachments} if queued_attachments else None,
)
inbox_row = messages_service.get_inbox_session(conn, session_id)
except Exception:
@@ -406,6 +421,8 @@ class SessionTurnManager:
return False
if not is_scheduled:
+ # Carry the queued segment's uploaded files into the merged turn.
+ context.files = file_attachments_from_specs(attachment_specs)
await self._run(session_id, context, user_row.get("text") or "")
else:
# Restore the scheduled run's delivery / source provenance onto the rebuilt
diff --git a/core/workbench_media.py b/core/workbench_media.py
new file mode 100644
index 000000000..d5bd3dc5b
--- /dev/null
+++ b/core/workbench_media.py
@@ -0,0 +1,175 @@
+"""Rewrite agent-reply ``file://`` links into same-origin media-proxy URLs.
+
+The IM path (``core/message_dispatcher`` + ``core/reply_enhancer``) strips
+``file://`` markdown links out of the reply text and uploads the referenced
+files to the IM platform. The avibe workbench Chat needs the opposite: keep the
+link **in place** in the Markdown but point it at a same-origin proxy URL, so
+the browser can render an agent-produced image inline (and a file as a download
+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 link
+looks 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.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from pathlib import Path
+from urllib.parse import urlparse
+
+from sqlalchemy.engine import Connection
+
+from config.paths import get_attachments_dir
+from core.reply_enhancer import _FILE_LINK_RE, _file_uri_to_local_path
+from storage import media_service
+
+logger = 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:
+ """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.
+ """
+ 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)
+ if parsed.scheme != "file":
+ return match.group(0)
+ path = _file_uri_to_local_path(parsed)
+ if not os.path.isabs(path):
+ logger.warning("workbench_media: skipping non-absolute file link: %s", url)
+ return match.group(0)
+ safe_path = _safe_resolved_path(path, roots)
+ if safe_path is None:
+ logger.warning("workbench_media: refusing media outside safe roots: %s", path)
+ return match.group(0)
+ try:
+ token = media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind="image" if bang == "!" else "file",
+ source="agent_reply",
+ local_path=safe_path,
+ file_name=label or os.path.basename(safe_path),
+ )
+ 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 _FILE_LINK_RE.sub(_replace, text)
+
+
+def resolve_attachment_specs(conn: Connection, *, session_id: str, attachments) -> list[dict]:
+ """Resolve UI-sent attachment refs (media tokens) to agent-turn file specs.
+
+ The browser only ever holds opaque tokens (never local paths); this maps each
+ token back to its on-disk file via ``media_objects``, scoped to the session,
+ and returns JSON-friendly ``{name, mimetype, path, size}`` dicts. Shared by
+ the send path (→ dispatch payload) and the queue-flush path (→ rebuilt turn)
+ so both carry the same uploaded files into the agent turn.
+ """
+ specs: list[dict] = []
+ for attachment in attachments or []:
+ if not isinstance(attachment, dict):
+ continue
+ token = attachment.get("token")
+ if not token:
+ continue
+ row = media_service.get_by_token(conn, token)
+ if not row or row.get("session_id") != session_id or row.get("revoked_at"):
+ continue
+ specs.append(
+ {
+ "name": row.get("file_name"),
+ "mimetype": row.get("content_type"),
+ "path": row.get("local_path"),
+ "size": row.get("size_bytes"),
+ }
+ )
+ return specs
+
+
+def file_attachments_from_specs(specs) -> list | None:
+ """Build ``FileAttachment`` objects from JSON file specs (already-local web
+ uploads — ``{name, mimetype, path, size}``). Returns ``None`` when empty so
+ ``MessageContext.files`` stays falsy for text-only turns. Shared by the
+ dispatch payload (internal_server) and the queue-flush re-run (session_turns).
+ """
+ from modules.im.base import FileAttachment
+
+ files = []
+ for spec in specs or []:
+ if not isinstance(spec, dict):
+ continue
+ path = spec.get("path")
+ if not path:
+ continue
+ files.append(
+ FileAttachment(
+ name=spec.get("name") or "attachment",
+ mimetype=spec.get("mimetype") or "application/octet-stream",
+ local_path=path,
+ size=spec.get("size"),
+ )
+ )
+ return files or None
diff --git a/docs/plans/workbench-chat-media-io.md b/docs/plans/workbench-chat-media-io.md
new file mode 100644
index 000000000..827ca1f40
--- /dev/null
+++ b/docs/plans/workbench-chat-media-io.md
@@ -0,0 +1,229 @@
+# Workbench Chat — Rich Media Input/Output
+
+Branch: `feat/workbench-chat-media-io`
+
+Source: page feedback on `/chat/:sessionId` (the avibe Workbench chat page).
+Three requirements:
+
+1. **Composer textarea not vertically centered** — looks shifted down.
+2. **Composer input affordances** — an attachment button (upload file/image
+ and send) and a voice button (record → avibe.bot ASR → fill the box).
+3. **Agent reply media** — agent replies must render images inline and files
+ as downloadable cards, reusing the IM `file://` parsing flow but adapted to
+ the web surface (image-proxy URL instead of IM upload).
+
+## Locked decisions (agreed with product owner)
+
+- **D1 = A.** Image/file proxy uses an **opaque token** mapped server-side, not
+ a raw path in the URL. Only files the agent actually referenced (or the user
+ uploaded) in this session are reachable. No general "read any file" surface.
+- **D2 = as proposed.** The Markdown renderer inlines a real `<img>` **only**
+ for same-origin proxy URLs; any external image URL keeps the existing
+ click-through behavior (no silent fetch → no IP/metadata leak).
+- **D3.** Voice button is available only when paired with Vibe Cloud (same gate
+ as Settings · Messaging audio transcription). Independent of the inbound-IM
+ `audio_asr.enabled` toggle.
+- **D4.** Attachments upload on select, show as removable chips, and may be sent
+ with no text (the messages API already supports content-only rows).
+- **Unified proxy.** Agent-reply images, agent-reply files, and user-uploaded
+ attachment previews **all** go through the **same** token + table + endpoint.
+- **In-place rewrite (owner refinement).** Images/files are rewritten **in
+ place** inside the Markdown body (the `file://` URL is replaced with the proxy
+ URL where it already sits) — never relocated to the end of the message. The
+ frontend decides the visual purely from the element type + URL shape:
+ `![]()` → inline image, `[]()` to a proxy URL → file card.
+- **File card.** A filename card with a **download** button and a **preview
+ (eye)** button. Same treatment for user-uploaded files.
+
+## Architecture: the media proxy (shared spine for #2 + #3)
+
+### New table `media_objects` (SQLAlchemy Core + Alembic)
+
+Add to `storage/models.py` and a new migration
+`storage/alembic/versions/20260602_0007_media_objects.py`. Fields are kept wide
+and extensible (content type and format are first-class, per owner request):
+
+| column | type | notes |
+| --- | --- | --- |
+| `token` | String PK | opaque url-safe id (the only thing in the URL) |
+| `scope_id` | String FK scopes.id CASCADE | owning scope (access + cleanup) |
+| `session_id` | String FK agent_sessions.id SET NULL | owning session |
+| `message_id` | String, null | originating message (linked post-insert; optional) |
+| `kind` | String | `image` \| `file` (extensible: `video`/`audio`) |
+| `source` | String | `agent_reply` \| `user_upload` |
+| `local_path` | Text | absolute path on disk |
+| `file_name` | Text | display / download filename |
+| `content_type` | String, null | MIME used for the HTTP response |
+| `file_ext` | String, null | extension / format |
+| `size_bytes` | Integer, null | size at registration (re-stat on serve) |
+| `created_at` | String | ISO8601 |
+| `expires_at` | String, null | optional TTL |
+| `revoked_at` | String, null | optional invalidation |
+
+Indexes: `(session_id)`, `(scope_id, created_at)`.
+
+New service `storage/media_service.py` (mirrors `messages_service.py` style):
+- `register(conn, *, scope_id, session_id, kind, source, local_path, file_name,
+ content_type, file_ext, size_bytes) -> token`
+- `get_by_token(conn, token) -> row | None`
+
+### New endpoint `GET /api/sessions/<session_id>/media/<token>`
+
+In `vibe/ui_server.py`. Auto-protected by the existing remote-access cookie
+middleware (it is under `/api/*`, not exempt); `<img>`/anchor GETs carry the
+same-origin session cookie, so they load without extra wiring. CSRF only guards
+mutating verbs, so GET is fine.
+
+Behavior (reuses the `_show_page_file_response` safety pattern):
+- look up token → 404 if missing / revoked / expired;
+- (defense) require the row's `session_id` to match the path;
+- `resolve(strict=True)` the path, 404 if the file is gone;
+- serve via `FileResponse(path, media_type=content_type)` with
+ `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`;
+- default `Content-Disposition: inline` (preview / `<img>`); `?download=1`
+ switches to `attachment; filename=...`.
+
+Optional `GET .../media/<token>/meta` → `{name, content_type, size, kind}` for
+richer file cards (size + type icon) without an extra full download. MVP can
+derive name/ext from the link label and lazy-`HEAD` for size.
+
+## #1 — Textarea vertical centering
+
+Root cause (`ui/src/components/workbench/ChatPage.tsx`, `Compose`):
+- the input row uses `items-end` (so the send button stays at the bottom when
+ the textarea grows multi-line), but with a single line the text is pushed to
+ the bottom → looks low;
+- the `textareaRef` is declared but unused — there is no auto-resize.
+
+Fix:
+- wire auto-resize on `textareaRef` (`height='auto'; height=min(scrollHeight,
+ 160)`), keep `max-h-40`;
+- give the textarea `min-h-9` (match the 36px button) and tune `py` so a single
+ line is vertically centered within that min-height; keep row `items-end` so
+ multi-line still grows upward with the button pinned at the bottom.
+- Verify pixel-for-pixel against the design.pen compose-bar frame.
+- Forward-compatible with #2 (left-side 36px buttons align on the same baseline).
+
+## #2 — Attachment + voice buttons
+
+Composer gets two left-side `ghost`/`icon` buttons (paperclip, mic), mirroring
+the right-side send/stop button.
+
+### Attachments
+- `POST /api/sessions/<id>/attachments` (multipart) → save under
+ `get_attachments_dir()/<scope>/` (same root as IM), register in
+ `media_objects` (`source=user_upload`), return `{id/token, name, mime, size,
+ url}` (url = the proxy URL, used for the chip thumbnail).
+- Composer shows removable chips; send writes them into `content.attachments`.
+- The web dispatch must carry the local paths into the agent turn: extend the
+ `dispatch_async` payload + the internal dispatch handler to pass files into
+ `AgentRequest.files` (reuse the IM mechanism at
+ `core/handlers/message_handler.py:373`). For already-local files we skip the
+ IM "download" step and build `FileAttachment(local_path=...)` directly.
+
+### Voice (ASR)
+- Record with `MediaRecorder` (webm/opus, which `core/audio_asr.py` supports).
+- `POST /api/asr/transcribe` (multipart) → save temp file → wrap as
+ `FileAttachment(local_path=...)` → `AudioAsrService.transcribe_attachments()`
+ → return `{text}` → fill the composer (do **not** auto-send).
+- Reuses 100% of `core/audio_asr.py` + Vibe Cloud device-secret auth.
+- Button gated on Vibe Cloud pairing (D3); disabled + hint otherwise.
+- **Backend dependency:** the avibe.bot endpoint `/v1/audio/transcriptions`
+ lives on `avibe-bot-backend` branch `feature/audio-transcriptions` and is not
+ yet merged/deployed. UI + local endpoint can land first; end-to-end voice
+ waits on that deploy.
+
+### Status (② implemented)
+
+- ✅ Upload `POST /api/sessions/<id>/attachments` (base64 JSON → save under
+ `attachments/avibe/<id>/` → register `media_objects` source=user_upload →
+ token + proxy URL). base64-over-JSON keeps it on the auth+CSRF compat route
+ (no multipart, no `ui_compat` expansion).
+- ✅ Attachment → agent turn: tokens resolved server-side
+ (`workbench_media.resolve_attachment_specs`) → dispatch payload `files` →
+ `internal_server._build_dispatch_payload` builds `FileAttachment(local_path)`
+ → `MessageContext.files` → existing `message_handler`/`AgentRequest.files`
+ (backends only need `local_path`). `_process_file_attachments` now passes
+ already-local files through (no download). Queue-flush carries queued
+ attachments too, so a file attached while busy isn't lost.
+- ✅ Voice `POST /api/asr/transcribe` (base64 audio → temp file →
+ `AudioAsrService.transcribe_attachments` → `{text}`) + `GET /api/asr/status`
+ to gate the mic button on pairing.
+- ✅ Composer: paperclip (upload + removable chips), mic (MediaRecorder →
+ transcribe → fill box, never auto-send), attachment-only send runs a turn.
+- ✅ User-bubble rendering of `content.attachments` (image thumbnails + FileCard).
+- ✅ unit tests extended (`resolve_attachment_specs`, `MessageContext(files=)`),
+ ruff clean, UI build clean.
+- ⏳ residual: live regression (upload → agent reads file; voice needs the
+ avibe.bot ASR endpoint deployed per the dependency above).
+
+## #3 — Agent reply images + files
+
+### Server-side rewrite (controller process)
+Injection point: `core/message_mirror.py` `persist_agent_message(context,
+canonical_type, text)` — the unified persist entry for all platforms. Gate the
+rewrite on `context.platform == "avibe"` and `canonical_type in {result,
+notify}` so IM mirror rows and intermediate streaming rows are untouched.
+
+Reuse `core/reply_enhancer.py` `_extract_file_links` / `FileLink` (the
+`(!?)\[...\]\((file://...)\)` parser, `is_image` from the `!`). For each link:
+1. register it in `media_objects` (kind from `is_image`, content_type from
+ mimetypes, name from label/basename) → token;
+2. replace the `file://...` URL **in place** with `/api/sessions/<sid>/media/
+ <token>`, preserving the `!`/`[]` structure and position.
+
+The rewritten text is what gets persisted (`content_text`) and streamed via
+`message.new`. New module `core/workbench_media.py` holds the transform so the
+extraction primitive stays shared with the IM enhancer.
+
+> Confirmed: `core/system_prompt_injection.py` `_BASE_CAPABILITIES_PROMPT` is
+> platform-agnostic and carries the "Send files" `file://` instruction, so avibe
+> agents emit `file://` links the same as IM turns → the rewrite triggers.
+
+### Status (③ implemented)
+
+- ✅ `media_objects` table + migration `20260602_0011` + `media_service`.
+- ✅ `core/workbench_media.rewrite_agent_media` + hook in `persist_agent_message`
+ (avibe, result/notify only).
+- ✅ `GET /api/sessions/<id>/media/<token>` (+ `/meta`) proxy.
+- ✅ `markdown.tsx` img/a overrides + `file-card.tsx`.
+- ✅ unit tests (`tests/test_workbench_media.py`, 3 pass), `ruff` clean, UI build clean.
+- ⏳ residual: end-to-end check in the running workbench (real agent reply with a
+ saved image/file) — best done in the Docker regression env.
+
+### Frontend rendering (`ui/src/components/ui/markdown.tsx`)
+- `img` override: if `src` matches the proxy route (relative `^/api/sessions/
+ [^/]+/media/`) → render a real inline `<img>` (lazy, `max-width:100%`,
+ rounded); otherwise keep the current click-through link (D2 preserved).
+- `a` override: if `href` matches the proxy route → render the **file card**
+ (filename + type icon + download + preview eye) instead of a plain link;
+ otherwise unchanged.
+- New `FileCard` component (reuse Card + Button + Badge). Download →
+ `href + '?download=1'`; preview eye → open `href` (inline) in a new tab /
+ lightbox.
+
+### design.pen
+Add two chat-media styles (inline image, file download card) to the workbench
+chat frames; map every token before coding the card. (Draw after this spec is
+locked.)
+
+## Sequence
+
+1. **#1** textarea centering (UI only, fast).
+2. **#3** media spine: table + migration + `media_service` + proxy endpoint +
+ `workbench_media` rewrite + markdown img/a overrides + FileCard + design.pen.
+3. **#2** attachments (upload endpoint + dispatch threading + chips) and voice
+ (transcribe endpoint + MediaRecorder), reusing the spine.
+
+Single branch, atomic commits, one PR at the checkpoint (or split output/input
+if the diff gets large).
+
+## Evidence layers to update
+
+- unit: `media_service` register/get, `workbench_media` rewrite (image vs file,
+ in-place, external-URL untouched), ASR endpoint wrap.
+- contract: proxy endpoint (auth, 404 on bad/expired token, disposition,
+ content-type), attachments upload shape.
+- scenario: n/a yet (no catalog entry for workbench media); add if one emerges.
+- manual: render side-by-side vs design.pen; verify inline image + file card +
+ voice fill on the running UI.
diff --git a/storage/alembic/versions/20260602_0013_media_objects.py b/storage/alembic/versions/20260602_0013_media_objects.py
new file mode 100644
index 000000000..d587b1905
--- /dev/null
+++ b/storage/alembic/versions/20260602_0013_media_objects.py
@@ -0,0 +1,74 @@
+"""media_objects proxy-token table for workbench chat media
+
+Backs the same-origin media proxy that renders agent-reply images inline and
+files as download cards in the avibe workbench Chat. A local file referenced by
+an agent reply (``file://``) — or uploaded by the user — is registered here and
+served over ``/api/sessions/<session_id>/media/<token>``; the URL carries only
+the opaque token, never a path.
+
+Revision ID: 20260602_0013
+Revises: 20260601_0012
+Create Date: 2026-06-02
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260602_0013"
+down_revision = "20260601_0012"
+branch_labels = None
+depends_on = None
+
+
+def _tables() -> set[str]:
+ bind = op.get_bind()
+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}
+
+
+def upgrade() -> None:
+ if "media_objects" not in _tables():
+ op.create_table(
+ "media_objects",
+ sa.Column("token", sa.String(), primary_key=True),
+ sa.Column(
+ "scope_id",
+ sa.String(),
+ sa.ForeignKey("scopes.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column(
+ "session_id",
+ sa.String(),
+ sa.ForeignKey("agent_sessions.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ sa.Column(
+ "message_id",
+ sa.String(),
+ sa.ForeignKey("messages.id", ondelete="SET NULL"),
+ nullable=True,
+ ),
+ sa.Column("kind", sa.String(), nullable=False),
+ sa.Column("source", sa.String(), nullable=False),
+ sa.Column("local_path", sa.Text(), nullable=False),
+ sa.Column("file_name", sa.Text(), nullable=True),
+ sa.Column("content_type", sa.String(), nullable=True),
+ sa.Column("file_ext", sa.String(), nullable=True),
+ sa.Column("size_bytes", sa.Integer(), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("expires_at", sa.String(), nullable=True),
+ sa.Column("revoked_at", sa.String(), nullable=True),
+ )
+ op.create_index("ix_media_objects_session", "media_objects", ["session_id"], if_not_exists=True)
+ op.create_index(
+ "ix_media_objects_scope_created",
+ "media_objects",
+ ["scope_id", "created_at"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("media_objects")
diff --git a/storage/media_service.py b/storage/media_service.py
new file mode 100644
index 000000000..515f16da3
--- /dev/null
+++ b/storage/media_service.py
@@ -0,0 +1,88 @@
+"""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
+ever putting a filesystem path in the URL. Both agent-reply media (rewritten in
+``core/workbench_media``) and user uploads register here, so the proxy endpoint
+and the UI file card have one shape to read.
+"""
+
+from __future__ import annotations
+
+import mimetypes
+import secrets
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+from sqlalchemy import select
+from sqlalchemy.engine import Connection
+
+from storage.models import media_objects
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _new_token() -> str:
+ # URL-safe, unguessable; the token IS the capability to fetch the file.
+ return secrets.token_urlsafe(16)
+
+
+def register(
+ conn: Connection,
+ *,
+ scope_id: str,
+ session_id: Optional[str],
+ kind: str,
+ source: str,
+ local_path: str,
+ file_name: Optional[str] = None,
+ content_type: Optional[str] = None,
+ message_id: Optional[str] = None,
+) -> str:
+ """Register *local_path* under a fresh token and return the token.
+
+ ``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.name
+ ext = (path.suffix.lower().lstrip(".") or None)
+ ctype = content_type or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+ size: Optional[int] = None
+ try:
+ if path.is_file():
+ size = path.stat().st_size
+ except OSError:
+ size = None
+
+ token = _new_token()
+ conn.execute(
+ media_objects.insert().values(
+ token=token,
+ scope_id=scope_id,
+ session_id=session_id,
+ message_id=message_id,
+ kind=kind,
+ source=source,
+ local_path=str(local_path),
+ file_name=name,
+ content_type=ctype,
+ file_ext=ext,
+ size_bytes=size,
+ created_at=_utc_now_iso(),
+ expires_at=None,
+ revoked_at=None,
+ )
+ )
+ return token
+
+
+def get_by_token(conn: Connection, token: str) -> Optional[dict[str, Any]]:
+ """Return the media row for *token* as a plain dict, or ``None``."""
+ if not token:
+ return None
+ row = conn.execute(select(media_objects).where(media_objects.c.token == token)).mappings().first()
+ return dict(row) if row else None
diff --git a/storage/models.py b/storage/models.py
index efd85d625..590eca3bf 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -319,6 +319,37 @@ messages = Table(
Index("ix_messages_author_created", "author", "created_at"),
)
+# 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.
+media_objects = Table(
+ "media_objects",
+ metadata,
+ Column("token", String, primary_key=True),
+ Column("scope_id", String, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=False),
+ Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),
+ Column("message_id", String, ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),
+ Column("kind", String, nullable=False),
+ Column("source", String, nullable=False),
+ Column("local_path", Text, nullable=False),
+ Column("file_name", Text, nullable=True),
+ Column("content_type", String, nullable=True),
+ Column("file_ext", String, nullable=True),
+ Column("size_bytes", 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"),
+)
+
imported_state_tables = [
show_pages,
background_runs,
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 8a4f4dca0..3ac0b8906 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -16,7 +16,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260601_0012"
+HEAD_REVISION = "20260602_0013"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -40,6 +40,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "agent_runs" in tables
assert "show_pages" in tables
assert "show_session_events" in tables
+ assert "media_objects" in tables
background_columns = {
row[1]
for row in conn.execute(
diff --git a/tests/test_workbench_media.py b/tests/test_workbench_media.py
new file mode 100644
index 000000000..bfde44c86
--- /dev/null
+++ b/tests/test_workbench_media.py
@@ -0,0 +1,244 @@
+"""Unit tests for the workbench chat-media proxy spine.
+
+Covers ``storage.media_service`` (token mint + readback, derived content-type /
+ext / size) and ``core.workbench_media.rewrite_agent_media`` (in-place file://
+rewrite, image vs file kind, external URLs untouched). Uses an isolated temp
+SQLite migrated to head, so it never touches real ``~/.vibe_remote`` state.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from sqlalchemy import select
+
+from core.workbench_media import rewrite_agent_media
+from storage import media_service, settings_service
+from storage.db import create_sqlite_engine
+from storage.migrations import run_migrations
+from storage.models import agent_sessions, media_objects
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _seed_scope_and_session(conn) -> str:
+ scope_id = settings_service.upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj-1",
+ now=_now(),
+ supports_threads=False,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="sess_x",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor",
+ native_session_id="native",
+ status="active",
+ metadata_json="{}",
+ created_at=_now(),
+ updated_at=_now(),
+ )
+ )
+ return scope_id
+
+
+def test_register_and_get_by_token(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ shot = tmp_path / "shot.png"
+ shot.write_bytes(b"\x89PNG\r\n\x1a\n")
+
+ 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="image",
+ source="agent_reply",
+ local_path=str(shot),
+ file_name="shot.png",
+ )
+
+ with engine.connect() as conn:
+ row = media_service.get_by_token(conn, token)
+ assert media_service.get_by_token(conn, "does-not-exist") is None
+
+ assert row is not None
+ assert row["kind"] == "image"
+ assert row["source"] == "agent_reply"
+ assert row["content_type"] == "image/png"
+ assert row["file_ext"] == "png"
+ assert row["size_bytes"] == 8
+ assert row["local_path"] == str(shot)
+ assert row["session_id"] == "sess_x"
+
+
+def test_rewrite_in_place_image_file_and_external(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ img = tmp_path / "a.png"
+ img.write_bytes(b"x")
+ doc = tmp_path / "r.pdf"
+ doc.write_bytes(b"y")
+
+ text = (
+ f"See ![chart](file://{img}) and the [report](file://{doc}); "
+ f"also [docs](https://example.com/x)."
+ )
+
+ 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)
+ )
+
+ # Both file:// links are rewritten in place to same-origin proxy URLs.
+ assert "file://" not in out
+ assert out.startswith("See ![chart](/api/sessions/sess_x/media/")
+ assert "the [report](/api/sessions/sess_x/media/" in out
+ # External URL is left untouched (no token, no rewrite).
+ assert "[docs](https://example.com/x)" in out
+
+ with engine.connect() as conn:
+ rows = conn.execute(select(media_objects)).mappings().all()
+ assert sorted(r["kind"] for r in rows) == ["file", "image"]
+ assert all(r["source"] == "agent_reply" for r in rows)
+
+
+def test_resolve_attachment_specs(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ doc = tmp_path / "doc.pdf"
+ doc.write_bytes(b"%PDF-1.4 hello")
+
+ from core.workbench_media import resolve_attachment_specs
+
+ 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(doc),
+ file_name="doc.pdf",
+ )
+
+ with engine.connect() as conn:
+ specs = resolve_attachment_specs(
+ conn,
+ session_id="sess_x",
+ attachments=[{"token": token}, {"token": "bad"}, {"nope": 1}],
+ )
+ cross = resolve_attachment_specs(conn, session_id="other", attachments=[{"token": token}])
+
+ assert len(specs) == 1
+ assert specs[0]["path"] == str(doc)
+ assert specs[0]["mimetype"] == "application/pdf"
+ assert specs[0]["name"] == "doc.pdf"
+ # A token from another session must not resolve (defense in depth).
+ assert cross == []
+
+
+def test_message_context_accepts_files():
+ # internal_server builds MessageContext(files=...) for web turns; guard the
+ # contract that the dataclass takes a files kwarg.
+ from modules.im.base import FileAttachment, MessageContext
+
+ ctx = MessageContext(
+ user_id="u",
+ channel_id="c",
+ platform="avibe",
+ files=[FileAttachment(name="a.png", mimetype="image/png", local_path="/tmp/a.png")],
+ )
+ assert ctx.files and ctx.files[0].local_path == "/tmp/a.png"
+
+
+def test_rewrite_noop_without_file_links(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ text = "Plain reply with a [link](https://example.com) and no files."
+ with engine.begin() as conn:
+ scope_id = _seed_scope_and_session(conn)
+ out = rewrite_agent_media(conn, scope_id=scope_id, session_id="sess_x", text=text)
+ assert out == text
+ with engine.connect() as conn:
+ assert conn.execute(select(media_objects)).first() is None
+
+
+def test_process_reply_keep_file_links():
+ # The avibe result path persists with keep_file_links=True so the proxy
+ # rewrite can still see the file:// links; the IM default strips them.
+ from core.reply_enhancer import process_reply
+
+ raw = "Here ![chart](file:///tmp/c.png) and [doc](file:///tmp/d.pdf)\n\n---\n[OK]"
+
+ default = process_reply(raw)
+ assert "file://" not in default.text
+ assert "![chart]" not in default.text
+ assert len(default.files) == 2
+
+ kept = process_reply(raw, keep_file_links=True)
+ assert "![chart](file:///tmp/c.png)" in kept.text
+ assert "[doc](file:///tmp/d.pdf)" in kept.text
+ assert "[OK]" not in kept.text # trailing quick-reply block still stripped
+ assert len(kept.files) == 2
+
+
+def test_rewrite_refuses_paths_outside_safe_roots(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)"
+ 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
+ with engine.connect() as conn:
+ assert conn.execute(select(media_objects)).first() is None
+
+
+def test_rewrite_allows_paths_under_workdir(tmp_path):
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+
+ from core.workbench_media import rewrite_agent_media
+
+ workdir = tmp_path / "proj"
+ workdir.mkdir()
+ img = workdir / "out.png"
+ img.write_bytes(b"x")
+ text = f"![out](file://{img})"
+ 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)
+ )
+ assert "/api/sessions/sess_x/media/" in out
+ 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())
diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsx
new file mode 100644
index 000000000..373cb327c
--- /dev/null
+++ b/ui/src/components/ui/file-card.tsx
@@ -0,0 +1,103 @@
+import * as React from 'react';
+import { useTranslation } from 'react-i18next';
+import { Download, Eye, File, FileArchive, FileText, Image as ImageIcon } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { apiFetch } from '@/lib/apiFetch';
+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
+// 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 the
+// design-system ``Button`` (ghost/icon) rather than hand-rolled controls.
+
+const IMAGE_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'bmp', 'avif', 'ico', 'heic']);
+const ARCHIVE_EXT = new Set(['zip', 'tar', 'gz', 'tgz', 'rar', '7z', 'bz2', 'xz']);
+const DOC_EXT = new Set(['doc', 'docx', 'txt', 'md', 'rtf', 'csv', 'json', 'log', 'yaml', 'yml', 'xml', 'html']);
+
+// Literal class strings (Tailwind can't see interpolated names) so the tint
+// utilities are actually generated.
+function kindOf(ext: string): { Icon: LucideIcon; tile: string } {
+ if (IMAGE_EXT.has(ext)) return { Icon: ImageIcon, tile: 'bg-cyan/15 text-cyan' };
+ if (ARCHIVE_EXT.has(ext)) return { Icon: FileArchive, tile: 'bg-gold/15 text-gold' };
+ if (ext === 'pdf') return { Icon: FileText, tile: 'bg-cyan/15 text-cyan' };
+ if (DOC_EXT.has(ext)) return { Icon: FileText, tile: 'bg-violet/15 text-violet' };
+ return { Icon: File, tile: 'bg-mint/15 text-mint' };
+}
+
+function formatSize(bytes?: number | null): string {
+ if (!bytes || bytes <= 0) return '';
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
+ let value = bytes;
+ let i = 0;
+ while (value >= 1024 && i < units.length - 1) {
+ value /= 1024;
+ i += 1;
+ }
+ return `${value >= 10 || i === 0 ? Math.round(value) : value.toFixed(1)} ${units[i]}`;
+}
+
+function nodeText(node: React.ReactNode): string {
+ if (node == null || node === false || node === true) return '';
+ if (typeof node === 'string' || typeof node === 'number') return String(node);
+ if (Array.isArray(node)) return node.map(nodeText).join('');
+ if (React.isValidElement(node)) return nodeText((node.props as { children?: React.ReactNode }).children);
+ return '';
+}
+
+type Meta = { name?: string; ext?: string; size?: number | null };
+
+export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> = ({ href, children }) => {
+ const { t } = useTranslation();
+ const label = nodeText(children).trim();
+ const [meta, setMeta] = React.useState<Meta | null>(null);
+
+ React.useEffect(() => {
+ // Only fetch metadata for our own media proxy — never auto-call an arbitrary
+ // host that slipped into a non-proxy href.
+ if (!isProxyMediaUrl(href)) return;
+ let alive = true;
+ apiFetch(`${href}/meta`)
+ .then((res) => (res.ok ? res.json() : null))
+ .then((data) => {
+ if (alive && data) setMeta(data);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [href]);
+
+ const ext = (meta?.ext || label.split('.').pop() || '').toLowerCase();
+ const { Icon, tile } = kindOf(ext);
+ const title = label || meta?.name || 'file';
+ const metaLine = [ext ? ext.toUpperCase() : null, formatSize(meta?.size) || null].filter(Boolean).join(' · ');
+
+ 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">
+ <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" aria-label={t('chat.media.download')}>
+ <a href={`${href}?download=1`} download>
+ <Download className="size-4" />
+ </a>
+ </Button>
+ </span>
+ </span>
+ );
+};
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsx
index 8970c4fdd..6d48ad751 100644
--- a/ui/src/components/ui/markdown.tsx
+++ b/ui/src/components/ui/markdown.tsx
@@ -2,6 +2,8 @@ import * as React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
+import { FileCard } from '@/components/ui/file-card';
+import { isProxyMediaUrl } from '@/lib/mediaProxy';
import { cn } from '@/lib/utils';
// Shared markdown renderer. react-markdown + remark-gfm (tables, strikethrough,
@@ -27,24 +29,44 @@ export const Markdown: React.FC<{ content: string; className?: string; interacti
// Markdown here is untrusted (agent replies, user-authored prompts) and
// can embed images. The default <img> renderer would auto-fetch any URL
// the moment the view opens (``![](http://attacker/x)``), leaking the
- // viewer's IP / network metadata to an attacker-chosen host. Render
- // images as click-through links instead so nothing is fetched without
- // an explicit user action — or as plain text when non-interactive.
+ // viewer's IP / network metadata to an attacker-chosen host. So we only
+ // render a real inline <img> for our OWN same-origin media proxy; every
+ // other URL stays a click-through link (or plain text when
+ // non-interactive) so nothing is fetched without an explicit action.
img: ({ src, alt }) => {
if (!src) return null;
- const label = `🖼 ${alt || String(src)}`;
+ const url = String(src);
+ if (interactive && isProxyMediaUrl(url)) {
+ return <img src={url} alt={alt || ''} loading="lazy" />;
+ }
+ const label = `🖼 ${alt || url}`;
return interactive ? (
- <a href={String(src)} target="_blank" rel="noopener noreferrer nofollow">
+ <a href={url} target="_blank" rel="noopener noreferrer nofollow">
{label}
</a>
) : (
<span>{label}</span>
);
},
+ // Links to our media proxy are agent-produced files → render the
+ // download card (filename + type + download / preview). Other links keep
+ // the normal anchor (interactive) or collapse to plain text inside a
+ // clickable row (non-interactive).
+ a: ({ href, children }) => {
+ const url = href ? String(href) : '';
+ if (interactive && url && isProxyMediaUrl(url)) {
+ return <FileCard href={url}>{children}</FileCard>;
+ }
+ if (!interactive) return <span>{children}</span>;
+ return (
+ <a href={url} target="_blank" rel="noopener noreferrer nofollow">
+ {children}
+ </a>
+ );
+ },
...(interactive
? {}
: {
- a: ({ children }: { children?: React.ReactNode }) => <span>{children}</span>,
// GFM task lists render a checkbox <input>; even disabled, an
// <input> nested in the sidebar row <button> is invalid interactive
// content, so show the state as a plain glyph instead.
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index d5eda25e8..b48c6b2bd 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -8,14 +8,16 @@ import { useApi } from '../../context/ApiContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import type { VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
+import { isProxyMediaUrl } from '../../lib/mediaProxy';
import { formatLocalDateTime } from '../../lib/relativeTime';
import { fetchBackendModels } from '../../lib/backendModels';
import { resolveEffortOptions } from '../../lib/effortOptions';
import { Button } from '../ui/button';
+import { FileCard } from '../ui/file-card';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
-import { Composer } from './Composer';
+import { Composer, type ComposerAttachment } from './Composer';
// While a turn is in flight, reconcile the working/Stop state against the
// controller on this cadence (the backend ``GET /turn-state`` is authoritative).
@@ -420,10 +422,11 @@ export const ChatPage: React.FC = () => {
}, [working, syncTurnState]);
const sendMessage = useCallback(
- async (text: string) => {
+ async (text: string, attachments?: ComposerAttachment[]) => {
// NB: no ``working`` guard — sending WHILE a turn runs is the queue
// feature; the backend enqueues it (202) instead of refusing.
- if (!sessionId || !text.trim()) return;
+ const ready = (attachments ?? []).filter((a) => a.status === 'ready');
+ if (!sessionId || (!text.trim() && ready.length === 0)) return;
markWorking();
setError(null);
try {
@@ -432,10 +435,27 @@ export const ChatPage: React.FC = () => {
// stream — we don't hold the response open. ``apiFetch`` attaches the
// CSRF token that ``protect_mutating_ui_requests`` requires under
// remote-access mode (raw ``fetch`` would 403).
+ const requestBody =
+ ready.length > 0
+ ? {
+ text,
+ content: {
+ text,
+ attachments: ready.map((a) => ({
+ token: a.token,
+ name: a.name,
+ mime: a.mime,
+ size: a.size,
+ kind: a.kind,
+ url: a.url,
+ })),
+ },
+ }
+ : { text };
const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ text }),
+ body: JSON.stringify(requestBody),
});
const body = await response.json().catch(() => null);
// If the user switched chats while this POST was in flight, the response
@@ -460,6 +480,9 @@ export const ChatPage: React.FC = () => {
if (sessionId === sessionIdRef.current) {
setWorking(false);
setError(err?.message ?? String(err));
+ // Signal the composer the send didn't start so it restores the text +
+ // uploaded chips — the user can retry without re-uploading (Codex r5).
+ return false;
}
}
},
@@ -652,6 +675,7 @@ export const ChatPage: React.FC = () => {
onSend={sendMessage}
onStop={stopMessage}
busy={working}
+ sessionId={sessionId ?? ''}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
/>
@@ -704,14 +728,15 @@ const QueueStrip: React.FC<{
};
interface ComposeProps {
- onSend: (text: string) => void;
+ onSend: (text: string, attachments?: ComposerAttachment[]) => void;
onStop: () => void;
busy: boolean;
+ sessionId: string;
initialDraft: string | null;
onDraftChange: (text: string) => void;
}
-const Compose: React.FC<ComposeProps> = ({ onSend, onStop, busy, initialDraft, onDraftChange }) => (
+const Compose: React.FC<ComposeProps> = ({ onSend, onStop, busy, sessionId, initialDraft, onDraftChange }) => (
// shrink-0 pins the bar at the bottom of the fixed-height chat container; the
// gradient fades the transcript out behind it (no opaque band / hard border)
// so the input sits close to the bottom edge. The input row is the shared
@@ -724,6 +749,7 @@ const Compose: React.FC<ComposeProps> = ({ onSend, onStop, busy, initialDraft, o
onSend={onSend}
onStop={onStop}
busy={busy}
+ sessionId={sessionId}
initialDraft={initialDraft}
onDraftChange={onDraftChange}
/>
@@ -1205,6 +1231,10 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio
// task / watch / webhook). Tag it so the user understands why the agent
// replied without them sending anything (cyan "Scheduled task" / "Watch").
const isHarness = !isNotify && !isAgent && !isSystem && message.source === 'harness';
+ // User-uploaded attachments ride in ``content.attachments`` (agent-reply media
+ // is rewritten inline into the text instead, handled by the Markdown renderer).
+ const rawAttachments = (message.content as { attachments?: Array<Record<string, unknown>> })?.attachments;
+ const messageAttachments = Array.isArray(rawAttachments) ? rawAttachments : [];
return (
<div
className={clsx(
@@ -1254,8 +1284,34 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio
) : (
<div className="whitespace-pre-wrap text-[13px] text-foreground">{message.text}</div>
)
- ) : (
+ ) : messageAttachments.length === 0 ? (
<div className="text-[13px] text-muted">—</div>
+ ) : null}
+ {messageAttachments.length > 0 && (
+ <div className="mt-1 flex flex-col gap-2">
+ {messageAttachments.map((att, i) => {
+ const url = String(att?.url || '');
+ if (!url) return null;
+ // Only inline-render images served from our own media proxy; a
+ // non-proxy url (direct API caller / malformed content) falls back
+ // to a click-through FileCard so it can't auto-fetch a remote host.
+ const isImage =
+ (att?.kind === 'image' || String(att?.mime || '').startsWith('image/')) && isProxyMediaUrl(url);
+ return isImage ? (
+ <img
+ key={i}
+ src={url}
+ alt={typeof att?.name === 'string' ? att.name : ''}
+ loading="lazy"
+ className="max-h-60 max-w-full rounded-lg border border-border"
+ />
+ ) : (
+ <FileCard key={i} href={url}>
+ {typeof att?.name === 'string' ? att.name : 'file'}
+ </FileCard>
+ );
+ })}
+ </div>
)}
</div>
);
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 480a6e9be..5dd9045b7 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1,14 +1,47 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Send, Square } from 'lucide-react';
+import { Loader2, Mic, Paperclip, Send, Square, X } from 'lucide-react';
+import clsx from 'clsx';
+import { apiFetch } from '../../lib/apiFetch';
import { cn } from '../../lib/utils';
import { Button } from '../ui/button';
+export type ComposerAttachment = {
+ localId: string;
+ token: string;
+ name: string;
+ mime: string;
+ size: number;
+ kind: 'image' | 'file';
+ url: string;
+ status: 'uploading' | 'ready' | 'error';
+};
+
+// Read a File/Blob as bare base64 (no ``data:...,`` prefix) for the JSON upload
+// + transcribe endpoints — the auth/CSRF-guarded compat route parses JSON, not
+// multipart, so binaries ride as base64.
+function readFileAsBase64(file: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(reader.error);
+ reader.onload = () => {
+ const result = String(reader.result || '');
+ const comma = result.indexOf(',');
+ resolve(comma >= 0 ? result.slice(comma + 1) : result);
+ };
+ reader.readAsDataURL(file);
+ });
+}
+
export interface ComposerProps {
- /** Fired with the trimmed text when the user sends. Return (or resolve to)
- * ``false`` to signal the send couldn't start, so the box keeps the text. */
- onSend: (text: string) => boolean | void | Promise<boolean | void>;
+ /** Fired with the trimmed text (+ ready attachments) when the user sends.
+ * Return (or resolve to) ``false`` to signal the send couldn't start, so the
+ * box keeps the text + attachments. */
+ onSend: (
+ text: string,
+ attachments?: ComposerAttachment[],
+ ) => boolean | void | Promise<boolean | void>;
/** A turn is running — the send button becomes a Stop button. */
busy?: boolean;
/** Pressed while busy. */
@@ -23,12 +56,16 @@ export interface ComposerProps {
disabled?: boolean;
/** Override the row container — e.g. a narrower max-width on the home canvas. */
className?: string;
+ /** When set, enables file upload + voice input scoped to this session. The
+ * Workbench home leaves it unset → a plain text-only composer. */
+ sessionId?: string;
}
-// The chat-style input row: an auto-growing textarea + a Send/Stop icon button.
-// Shared by the chat view (ChatPage) and the Workbench home so both use one
-// input component instead of each hand-rolling its own. Owns its draft value;
-// callers react via onSend / onDraftChange. design.pen kxEkn.
+// The chat-style input row: an auto-growing textarea + a Send/Stop icon button,
+// plus (when ``sessionId`` is set) attachment upload and voice input on the left.
+// Shared by the chat view (ChatPage) and the Workbench home so both use one input
+// component instead of each hand-rolling its own. Owns its draft value; callers
+// react via onSend / onDraftChange. design.pen kxEkn.
export const Composer: React.FC<ComposerProps> = ({
onSend,
busy = false,
@@ -38,23 +75,186 @@ export const Composer: React.FC<ComposerProps> = ({
placeholder,
disabled = false,
className,
+ sessionId,
}) => {
const { t } = useTranslation();
const [value, setValue] = useState('');
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
+ const valueRef = useRef('');
// Seed once from a saved draft, but only while the box is untouched so a
// late-arriving draft can't clobber live typing.
const draftAppliedRef = useRef(false);
// Blocks a same-tick double-submit before the optimistic clear re-renders.
const pendingRef = useRef(false);
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
+ const [asrAvailable, setAsrAvailable] = useState(false);
+ const [recording, setRecording] = useState(false);
+ const [transcribing, setTranscribing] = useState(false);
+ const recorderRef = useRef<MediaRecorder | null>(null);
+ const chunksRef = useRef<Blob[]>([]);
+ const streamRef = useRef<MediaStream | null>(null);
+ const unmountedRef = useRef(false);
+
+ // Upload + voice are scoped to a session (the upload endpoint needs one); the
+ // home composer leaves them off.
+ const mediaEnabled = Boolean(sessionId);
+
useEffect(() => {
if (draftAppliedRef.current || initialDraft == null) return;
draftAppliedRef.current = true;
if (initialDraft) setValue((cur) => (cur ? cur : initialDraft));
}, [initialDraft]);
+ // Keep a ref of the latest value so the async voice-fill can append without a
+ // stale closure.
+ useEffect(() => {
+ valueRef.current = value;
+ }, [value]);
+
+ // Auto-grow the textarea with its content. ``min-h-9`` floors it at the 36px
+ // send-button height so a single line sits vertically centered against the
+ // button; ``max-h-40`` (160px) caps it, after which it scrolls.
+ useEffect(() => {
+ const el = textareaRef.current;
+ if (!el) return;
+ el.style.height = 'auto';
+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
+ }, [value]);
+
+ // The mic button only appears when transcription is wired up (Vibe Cloud
+ // paired + enabled), so it never dead-ends on click.
+ useEffect(() => {
+ if (!mediaEnabled) return;
+ let alive = true;
+ apiFetch('/api/asr/status')
+ .then((res) => (res.ok ? res.json() : null))
+ .then((data) => {
+ if (alive) setAsrAvailable(Boolean(data?.available));
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ }, [mediaEnabled]);
+
+ // Release the mic + suppress post-unmount setState if the composer unmounts
+ // mid-recording (it remounts on every session switch).
+ useEffect(() => {
+ // Reset on setup (StrictMode runs cleanup→setup twice on mount, so a stale
+ // ``true`` from the first cleanup would otherwise wedge voice input).
+ unmountedRef.current = false;
+ return () => {
+ unmountedRef.current = true;
+ try {
+ recorderRef.current?.stop();
+ } catch {
+ /* already stopped */
+ }
+ streamRef.current?.getTracks().forEach((track) => track.stop());
+ };
+ }, []);
+
+ // Clear staged attachments when the session changes so a chip uploaded in one
+ // chat can't ride into another — defense in depth on top of ChatPage keying
+ // the composer by session.
+ useEffect(() => {
+ setAttachments([]);
+ }, [sessionId]);
+
+ const removeAttachment = (localId: string) => {
+ setAttachments((cur) => cur.filter((a) => a.localId !== localId));
+ };
+
+ const uploadFiles = async (files: File[]) => {
+ if (!sessionId) return;
+ for (const file of files) {
+ const localId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const kind: 'image' | 'file' = file.type.startsWith('image/') ? 'image' : 'file';
+ setAttachments((cur) => [
+ ...cur,
+ { localId, token: '', name: file.name, mime: file.type || 'application/octet-stream', size: file.size, kind, url: '', status: 'uploading' },
+ ]);
+ try {
+ const data = await readFileAsBase64(file);
+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/attachments`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: file.name, mime: file.type, data }),
+ });
+ const json = await res.json().catch(() => null);
+ if (!res.ok || !json?.token) throw new Error('upload failed');
+ setAttachments((cur) =>
+ cur.map((a) =>
+ a.localId === localId
+ ? { ...a, token: json.token, url: json.url, mime: json.mime || a.mime, size: json.size ?? a.size, kind: json.kind || a.kind, status: 'ready' }
+ : a,
+ ),
+ );
+ } catch {
+ setAttachments((cur) => cur.map((a) => (a.localId === localId ? { ...a, status: 'error' } : a)));
+ }
+ }
+ };
+
+ const startRecording = async () => {
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ streamRef.current = stream;
+ const recorder = new MediaRecorder(stream);
+ chunksRef.current = [];
+ recorder.ondataavailable = (e) => {
+ if (e.data.size) chunksRef.current.push(e.data);
+ };
+ recorder.onstop = async () => {
+ stream.getTracks().forEach((track) => track.stop());
+ streamRef.current = null;
+ if (unmountedRef.current) return;
+ setRecording(false);
+ const blob = new Blob(chunksRef.current, { type: recorder.mimeType || 'audio/webm' });
+ if (!blob.size) return;
+ setTranscribing(true);
+ try {
+ const data = await readFileAsBase64(blob);
+ const res = await apiFetch('/api/asr/transcribe', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'voice.webm', mime: blob.type || 'audio/webm', data }),
+ });
+ const json = await res.json().catch(() => null);
+ if (!unmountedRef.current && res.ok && json?.text) {
+ // Append the transcript into the box (never auto-send) via the draft
+ // path so it persists if the user switches away before sending.
+ const next = valueRef.current ? `${valueRef.current} ${json.text}` : String(json.text);
+ update(next);
+ }
+ } finally {
+ if (!unmountedRef.current) setTranscribing(false);
+ }
+ };
+ recorderRef.current = recorder;
+ recorder.start();
+ setRecording(true);
+ } catch {
+ // getUserMedia may have handed us a live stream before MediaRecorder
+ // construction / start() threw — release it so the mic doesn't stay on.
+ streamRef.current?.getTracks().forEach((track) => track.stop());
+ streamRef.current = null;
+ setRecording(false);
+ }
+ };
+
+ const toggleRecording = () => {
+ if (recording) recorderRef.current?.stop();
+ else void startRecording();
+ };
+
const trimmed = value.trim();
- const canSubmit = trimmed.length > 0 && !disabled;
+ const readyAttachments = attachments.filter((a) => a.status === 'ready');
+ const uploading = attachments.some((a) => a.status === 'uploading');
+ // Send on text OR a ready attachment (attachment-only runs a turn so the agent
+ // reads the files); blocked while an upload is still in flight.
+ const canSubmit = (trimmed.length > 0 || readyAttachments.length > 0) && !uploading && !disabled;
const update = (next: string) => {
setValue(next);
@@ -64,72 +264,150 @@ export const Composer: React.FC<ComposerProps> = ({
const submit = async () => {
if (!canSubmit || pendingRef.current) return;
const submitted = trimmed;
+ const sent = readyAttachments;
pendingRef.current = true;
- // Clear optimistically so the box can't be re-submitted (canSubmit goes
- // false) and a slow send can't wipe text typed in the meantime.
+ // Clear optimistically so the box can't be re-submitted and a slow send can't
+ // wipe text typed in the meantime.
setValue('');
onDraftChange?.('');
+ setAttachments([]);
try {
- // If the caller reports the send couldn't start (the home composer's
- // no-project nudge / create-session error), restore the prompt for retry
- // — but only if the user hasn't already typed something new.
- const started = await onSend(submitted);
- if (started === false) setValue((cur) => (cur ? cur : submitted));
+ // If the caller reports the send couldn't start (home no-project nudge),
+ // restore the prompt + attachments for retry — unless the user typed anew.
+ const started = await onSend(submitted, sent);
+ if (started === false) {
+ setValue((cur) => (cur ? cur : submitted));
+ setAttachments((cur) => (cur.length ? cur : sent));
+ }
} finally {
pendingRef.current = false;
}
};
return (
- <div
- className={cn(
- 'mx-auto flex w-full max-w-[1080px] items-end gap-2 rounded-2xl border border-border-strong bg-surface-2 py-2 pl-3.5 pr-2 shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]',
- className,
- )}
- >
- <textarea
- ref={textareaRef}
- value={value}
- onChange={(e) => update(e.target.value)}
- onKeyDown={(e) => {
- // Enter sends; Shift+Enter inserts a newline. ``isComposing`` guards
- // against submitting mid-IME composition (CJK), where Enter commits
- // the candidate rather than the message.
- if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
- e.preventDefault();
- submit();
- }
- }}
- rows={1}
- placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
- className="max-h-40 flex-1 resize-none bg-transparent py-1.5 text-[13px] text-foreground outline-none placeholder:text-muted"
- />
- {/* 36px (size-9) icon button: pink-soft Stop while a turn runs, else a
- flat mint Send — design-system variants, not a glowy brand CTA. */}
- {busy ? (
- <Button
- type="button"
- variant="destructive-soft"
- size="icon"
- onClick={onStop}
- aria-label={t('chat.compose.stop')}
- className="size-9 shrink-0"
- >
- <Square className="size-4" />
- </Button>
- ) : (
- <Button
- type="button"
- variant="default"
- size="icon"
- onClick={submit}
- disabled={!canSubmit}
- aria-label={t('chat.compose.send')}
- className="size-9 shrink-0"
- >
- <Send className="size-4" />
- </Button>
+ <div className={cn('mx-auto flex w-full max-w-[1080px] flex-col gap-2', className)}>
+ {mediaEnabled && attachments.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {attachments.map((att) => (
+ <div
+ key={att.localId}
+ className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 py-1 pl-1.5 pr-1 text-[12px]"
+ >
+ {att.status === 'uploading' ? (
+ <span className="grid size-7 place-items-center rounded text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ ) : att.kind === 'image' && att.url ? (
+ <img src={att.url} alt="" className="size-7 rounded object-cover" />
+ ) : (
+ <span className="grid size-7 place-items-center rounded bg-cyan/15 text-cyan">
+ <Paperclip className="size-3.5" />
+ </span>
+ )}
+ <span className={clsx('max-w-[160px] truncate', att.status === 'error' ? 'text-pink' : 'text-foreground')}>
+ {att.name}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => removeAttachment(att.localId)}
+ aria-label={t('chat.compose.removeAttachment')}
+ className="size-5 shrink-0 text-muted hover:text-foreground"
+ >
+ <X className="size-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
)}
+ <div
+ className={cn(
+ 'flex w-full items-end gap-2 rounded-2xl border border-border-strong bg-surface-2 py-2 pr-2 shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]',
+ mediaEnabled ? 'pl-2' : 'pl-3.5',
+ )}
+ >
+ {mediaEnabled && (
+ <>
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ onChange={(e) => {
+ if (e.target.files?.length) void uploadFiles(Array.from(e.target.files));
+ e.target.value = '';
+ }}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => fileInputRef.current?.click()}
+ aria-label={t('chat.compose.attach')}
+ className="size-9 shrink-0"
+ >
+ <Paperclip className="size-4" />
+ </Button>
+ {asrAvailable && (
+ <Button
+ type="button"
+ variant={recording ? 'destructive-soft' : 'ghost'}
+ size="icon"
+ onClick={toggleRecording}
+ disabled={transcribing}
+ aria-label={t(recording ? 'chat.compose.stopRecording' : 'chat.compose.voice')}
+ className={clsx('size-9 shrink-0', recording && 'animate-pulse')}
+ >
+ {transcribing ? <Loader2 className="size-4 animate-spin" /> : <Mic className="size-4" />}
+ </Button>
+ )}
+ </>
+ )}
+ <textarea
+ ref={textareaRef}
+ value={value}
+ onChange={(e) => update(e.target.value)}
+ onKeyDown={(e) => {
+ // Enter sends; Shift+Enter inserts a newline. ``isComposing`` guards
+ // against submitting mid-IME composition (CJK), where Enter commits
+ // the candidate rather than the message.
+ if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ rows={1}
+ placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
+ className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
+ />
+ {/* 36px (size-9) icon button: pink-soft Stop while a turn runs, else a
+ flat mint Send — design-system variants, not a glowy brand CTA. */}
+ {busy ? (
+ <Button
+ type="button"
+ variant="destructive-soft"
+ size="icon"
+ onClick={onStop}
+ aria-label={t('chat.compose.stop')}
+ className="size-9 shrink-0"
+ >
+ <Square className="size-4" />
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ variant="default"
+ size="icon"
+ onClick={submit}
+ disabled={!canSubmit}
+ aria-label={t('chat.compose.send')}
+ className="size-9 shrink-0"
+ >
+ <Send className="size-4" />
+ </Button>
+ )}
+ </div>
</div>
);
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index a53b03510..595bb84cc 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1602,7 +1602,15 @@
"hint": "Enter to send",
"send": "Send",
"sending": "Sending…",
- "stop": "Stop"
+ "stop": "Stop",
+ "attach": "Attach files",
+ "voice": "Voice input",
+ "stopRecording": "Stop recording",
+ "removeAttachment": "Remove"
+ },
+ "media": {
+ "preview": "Preview",
+ "download": "Download"
},
"queue": {
"title": "Queued · {{count}}",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d31124535..3fb5f7d09 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1601,7 +1601,15 @@
"hint": "Enter 发送",
"send": "发送",
"sending": "发送中…",
- "stop": "停止"
+ "stop": "停止",
+ "attach": "添加附件",
+ "voice": "语音输入",
+ "stopRecording": "停止录音",
+ "removeAttachment": "移除"
+ },
+ "media": {
+ "preview": "预览",
+ "download": "下载"
},
"queue": {
"title": "排队中 · {{count}}",
diff --git a/ui/src/lib/mediaProxy.ts b/ui/src/lib/mediaProxy.ts
new file mode 100644
index 000000000..c5cc5ffcc
--- /dev/null
+++ b/ui/src/lib/mediaProxy.ts
@@ -0,0 +1,11 @@
+// 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\/[^/?#]+/;
+
+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.py
index a3c4eeae5..afc0ad6b6 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3220,6 +3220,247 @@ def sessions_messages_list(session_id: str):
return jsonify(result)
+# Content types the media proxy is willing to serve ``inline``. 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).
+# ``<img>`` ignores Content-Disposition, so inline image rendering still works.
+_INLINE_SAFE_MEDIA_TYPES = {
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+ "image/avif",
+ "image/bmp",
+ "image/x-icon",
+ "image/heic",
+ "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",
+}
+
+
[email protected]("/api/sessions/<session_id>/media/<token>", methods=["GET"])
+def sessions_media_get(session_id: str, 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.
+ """
+ from urllib.parse import quote
+
+ from storage import media_service
+
+ 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"):
+ return jsonify({"error": "not_found"}), 404
+ stored = row["local_path"]
+ try:
+ candidate = Path(stored).resolve(strict=True)
+ except (OSError, ValueError):
+ return jsonify({"error": "not_found"}), 404
+ # Re-validate at serve time: ``stored`` is the canonical (symlink-free) path
+ # captured at registration. If it now resolves elsewhere — a symlink swapped
+ # in to escape to e.g. ~/.vibe_remote/config.json — or is no longer a regular
+ # 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"
+ response = send_file(candidate, mimetype=mime_type)
+ response.headers["X-Content-Type-Options"] = "nosniff"
+ response.headers["Referrer-Policy"] = "no-referrer"
+ 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
+ disposition = "attachment" if force_download else "inline"
+ response.headers["Content-Disposition"] = f"{disposition}; filename*=UTF-8''{quote(filename)}"
+ return response
+
+
[email protected]("/api/sessions/<session_id>/media/<token>/meta", methods=["GET"])
+def sessions_media_meta(session_id: str, 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 storage import media_service
+
+ 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"):
+ return jsonify({"error": "not_found"}), 404
+ return jsonify(
+ {
+ "kind": row.get("kind"),
+ "name": row.get("file_name"),
+ "content_type": row.get("content_type"),
+ "ext": row.get("file_ext"),
+ "size": row.get("size_bytes"),
+ }
+ )
+
+
[email protected]("/api/sessions/<session_id>/attachments", methods=["POST"])
+def sessions_attachments_create(session_id: str):
+ """Persist a user-uploaded file (base64 JSON) and register it for the media
+ proxy. Returns an opaque token + proxy URL; the browser never holds a path.
+ base64-over-JSON keeps uploads on the existing auth + CSRF-guarded compat
+ route (the compat layer parses JSON, not multipart)."""
+ import base64
+ import re
+ import uuid
+
+ from config import paths
+ from core.services import sessions as workbench_sessions_service
+ from storage import media_service
+
+ payload = request.json or {}
+ name = (payload.get("name") or "upload").strip() or "upload"
+ mime = (payload.get("mime") or payload.get("content_type") or "application/octet-stream").strip()
+ data_b64 = payload.get("data") or ""
+ if not isinstance(data_b64, str) or not data_b64:
+ return jsonify({"error": "data is required"}), 400
+ if data_b64.startswith("data:") and "," in data_b64:
+ data_b64 = data_b64.split(",", 1)[1]
+ try:
+ raw = base64.b64decode(data_b64)
+ except Exception:
+ return jsonify({"error": "invalid base64"}), 400
+ if not raw:
+ return jsonify({"error": "empty file"}), 400
+ if len(raw) > 25 * 1024 * 1024:
+ return jsonify({"error": "file too large"}), 413
+
+ engine = _projects_engine()
+ try:
+ with engine.connect() as conn:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ except LookupError:
+ return jsonify({"error": "session_not_found"}), 404
+
+ safe = re.sub(r"[^A-Za-z0-9._-]+", "_", name.rsplit("/", 1)[-1]).strip("_") or "upload"
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ upload_dir.mkdir(parents=True, exist_ok=True)
+ local_path = upload_dir / f"{uuid.uuid4().hex[:8]}_{safe}"
+ local_path.write_bytes(raw)
+
+ kind = "image" if mime.startswith("image/") else "file"
+ with engine.begin() as conn:
+ token = media_service.register(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ kind=kind,
+ source="user_upload",
+ local_path=str(local_path.resolve()),
+ file_name=name,
+ content_type=mime,
+ )
+ return (
+ jsonify(
+ {
+ "token": token,
+ "name": name,
+ "mime": mime,
+ "size": len(raw),
+ "kind": kind,
+ "url": f"/api/sessions/{session_id}/media/{token}",
+ }
+ ),
+ 201,
+ )
+
+
[email protected]("/api/asr/transcribe", methods=["POST"])
+async def asr_transcribe():
+ """Transcribe recorded audio (base64 JSON) via the avibe.bot ASR client and
+ return the text for the composer to fill in. Reuses ``AudioAsrService`` — the
+ same client the IM voice-note path uses — so it needs only a V2Config."""
+ import base64
+ import tempfile
+ import uuid
+
+ from core.audio_asr import AudioAsrService
+ from core.services import settings as settings_service
+ from modules.im.base import FileAttachment
+
+ payload = request.json or {}
+ data_b64 = payload.get("data") or ""
+ if not isinstance(data_b64, str) or not data_b64:
+ return jsonify({"error": "data is required"}), 400
+ if data_b64.startswith("data:") and "," in data_b64:
+ data_b64 = data_b64.split(",", 1)[1]
+ try:
+ raw = base64.b64decode(data_b64)
+ except Exception:
+ return jsonify({"error": "invalid base64"}), 400
+ if not raw:
+ return jsonify({"error": "empty audio"}), 400
+ if len(raw) > 25 * 1024 * 1024:
+ return jsonify({"error": "file too large"}), 413
+
+ name = (payload.get("name") or "voice.webm").strip() or "voice.webm"
+ mime = (payload.get("mime") or "audio/webm").strip()
+
+ try:
+ config = settings_service.load_config()
+ except Exception:
+ logger.warning("asr_transcribe: failed to load config", exc_info=True)
+ return jsonify({"error": "config_unavailable"}), 503
+ service = AudioAsrService(config)
+ if not service.is_available():
+ return jsonify({"error": "asr_unavailable"}), 400
+
+ suffix = Path(name).suffix or ".webm"
+ tmp_path = Path(tempfile.gettempdir()) / f"vibe_asr_{uuid.uuid4().hex[:8]}{suffix}"
+ tmp_path.write_bytes(raw)
+ try:
+ attachment = FileAttachment(name=name, mimetype=mime, local_path=str(tmp_path), size=len(raw))
+ transcripts = await service.transcribe_attachments([attachment])
+ finally:
+ try:
+ tmp_path.unlink()
+ except OSError:
+ pass
+ if not transcripts:
+ return jsonify({"error": "transcription_failed"}), 502
+ return jsonify({"text": transcripts[0].text})
+
+
[email protected]("/api/asr/status", methods=["GET"])
+def asr_status():
+ """Whether voice transcription is available (Vibe Cloud paired + enabled) so
+ the composer can show/hide the mic button instead of guessing."""
+ from core.audio_asr import AudioAsrService
+ from core.services import settings as settings_service
+
+ try:
+ config = settings_service.load_config()
+ return jsonify({"available": bool(AudioAsrService(config).is_available())})
+ except Exception:
+ return jsonify({"available": False})
+
+
@app.route("/api/sessions/<session_id>/messages", methods=["POST"])
async def sessions_messages_create(session_id: str):
"""Persist a user message and fire-and-forget the agent turn.
@@ -3259,6 +3500,19 @@ async def sessions_messages_create(session_id: str):
or ""
)
+ # Resolve uploaded-attachment refs (media tokens the browser holds) to local
+ # file specs the agent turn can read. Done here (not in the browser) so a
+ # filesystem path never leaves the server.
+ attachment_specs: list = []
+ raw_attachments = content.get("attachments") if isinstance(content, dict) else None
+ if raw_attachments:
+ from core.workbench_media import resolve_attachment_specs
+
+ with engine.connect() as conn:
+ attachment_specs = resolve_attachment_specs(
+ conn, session_id=session_id, attachments=raw_attachments
+ )
+
def _persist_user_row() -> dict:
"""Reserve the user's row as ``pending`` (hidden from transcript/queue/
inbox) + clear any saved draft, WITHOUT publishing. This locks the row's
@@ -3318,9 +3572,10 @@ async def sessions_messages_create(session_id: str):
# Reserve the row FIRST (pending), then decide by the dispatch outcome.
message = _persist_user_row()
- # Content-only message (attachment, no text): nothing to run + the
- # dispatch endpoint requires text, so just promote + publish, no turn.
- if not dispatch_text.strip():
+ # No text AND no attachments: nothing for the agent to act on, so just
+ # promote + publish the row, no turn. Attachments WITHOUT text still run a
+ # turn (the agent reads the files), so they aren't caught here.
+ if not dispatch_text.strip() and not attachment_specs:
return jsonify(_promote_and_publish(message)), 201
# Session/page-scoped model (the web Chat): fire-and-forget the turn; the
# reply arrives over ``message.new``. The controller atomically either lets
@@ -3332,6 +3587,7 @@ async def sessions_messages_create(session_id: str):
"text": dispatch_text,
"scope_id": session["scope_id"],
"user_message_id": message.get("id"),
+ "files": attachment_specs,
}
try:
result = await internal_client.dispatch_async(dispatch_payload)