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.

Materialize Show Page annotation screenshots (#964)

Call Whitee396c7649b31
diff --git a/core/show_session_events.py b/core/show_session_events.py
index a053ccdf6..b38cf081c 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import json
import uuid
+from contextlib import ExitStack
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
@@ -92,74 +93,87 @@ class ShowSessionEventStore:
event_id = _event_id(payload, {})
created_at = _utc_now_iso()
- with self.engine.begin() as conn:
- session = conn.execute(
- select(agent_sessions.c.id, agent_sessions.c.scope_id, agent_sessions.c.status)
- .where(agent_sessions.c.id == session_id)
- .limit(1)
- ).mappings().first()
- if session is None:
- raise ShowSessionEventError("Agent session not found.", code="session_not_found")
- # Archive is terminal: a still-open Show Page must not keep writing
- # events (which dispatch as new agent work) into an archived session.
- if session["status"] == "archived":
- raise ShowSessionEventError("Agent session is archived.", code="session_archived")
-
- stored_payload = payload
- if event_type == "assistant.mark.resolved":
- stored_payload = _prepare_mark_resolution(conn, session_id, payload)
- event_payload = _normalize_event_payload(event_type, stored_payload)
- if records_author:
- event_payload.pop("author", None)
- anchor = _event_anchor(event_type, stored_payload, event_payload)
- scope = _event_scope(event_type, event_payload)
- transcript_text = (
- ""
- if event_type == "assistant.mark.resolved" and author is not None
- else _format_transcript_text(event_type, event_payload, anchor)
- )
- if records_author:
- event_payload["author"] = _normalize_human_author(author)
-
- conn.execute(
- show_session_events.insert().values(
- id=event_id,
- session_id=session_id,
- event_type=event_type,
- actor=actor,
- scope=scope,
- anchor_json=_json_dumps(anchor),
- payload_json=_json_dumps(event_payload),
- transcript_text=transcript_text,
- message_id=None,
- created_at=created_at,
- )
- )
- message: dict[str, Any] | None = None
- message_id: str | None = None
- if transcript_text:
- message = messages_service.append(
+ with ExitStack() as cleanup:
+ with self.engine.begin() as conn:
+ session = conn.execute(
+ select(agent_sessions.c.id, agent_sessions.c.scope_id, agent_sessions.c.status)
+ .where(agent_sessions.c.id == session_id)
+ .limit(1)
+ ).mappings().first()
+ if session is None:
+ raise ShowSessionEventError("Agent session not found.", code="session_not_found")
+ # Archive is terminal: a still-open Show Page must not keep writing
+ # events (which dispatch as new agent work) into an archived session.
+ if session["status"] == "archived":
+ raise ShowSessionEventError("Agent session is archived.", code="session_archived")
+
+ stored_payload = payload
+ if event_type == "assistant.mark.resolved":
+ stored_payload = _prepare_mark_resolution(conn, session_id, payload)
+ event_payload = _normalize_event_payload(event_type, stored_payload)
+ event_payload, screenshot_path = _materialize_annotation_screenshot(
conn,
- scope_id=session["scope_id"],
+ event_type=event_type,
+ event_payload=event_payload,
session_id=session_id,
- platform="avibe",
- author="agent" if actor in {"assistant", "system"} else "user",
- text=transcript_text,
- content={"text": transcript_text, "show_event_type": event_type},
- metadata={
- "source": "show_page",
- "show_event_id": event_id,
- "show_event_type": event_type,
- "show_event_scope": scope,
- **({"author": event_payload["author"]} if "author" in event_payload else {}),
- },
- native_message_id=f"show:{event_id}",
+ scope_id=session["scope_id"],
+ )
+ if screenshot_path is not None:
+ cleanup.callback(Path(screenshot_path).unlink, missing_ok=True)
+ if records_author:
+ event_payload.pop("author", None)
+ anchor = _event_anchor(event_type, stored_payload, event_payload)
+ scope = _event_scope(event_type, event_payload)
+ transcript_text = (
+ ""
+ if event_type == "assistant.mark.resolved" and author is not None
+ else _format_transcript_text(event_type, event_payload, anchor)
)
- message_id = message["id"]
+ if records_author:
+ event_payload["author"] = _normalize_human_author(author)
+
conn.execute(
- update(show_session_events).where(show_session_events.c.id == event_id).values(message_id=message_id)
+ show_session_events.insert().values(
+ id=event_id,
+ session_id=session_id,
+ event_type=event_type,
+ actor=actor,
+ scope=scope,
+ anchor_json=_json_dumps(anchor),
+ payload_json=_json_dumps(event_payload),
+ transcript_text=transcript_text,
+ message_id=None,
+ created_at=created_at,
+ )
)
- workbench_sessions_service.touch_session(conn, session_id)
+ message: dict[str, Any] | None = None
+ message_id: str | None = None
+ if transcript_text:
+ message = messages_service.append(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="agent" if actor in {"assistant", "system"} else "user",
+ text=transcript_text,
+ content={"text": transcript_text, "show_event_type": event_type},
+ metadata={
+ "source": "show_page",
+ "show_event_id": event_id,
+ "show_event_type": event_type,
+ "show_event_scope": scope,
+ **({"author": event_payload["author"]} if "author" in event_payload else {}),
+ },
+ native_message_id=f"show:{event_id}",
+ )
+ message_id = message["id"]
+ conn.execute(
+ update(show_session_events)
+ .where(show_session_events.c.id == event_id)
+ .values(message_id=message_id)
+ )
+ workbench_sessions_service.touch_session(conn, session_id)
+ cleanup.pop_all()
event = {
"id": event_id,
@@ -451,6 +465,65 @@ def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[s
return normalized
+def _materialize_annotation_screenshot(
+ conn: Any,
+ *,
+ event_type: str,
+ event_payload: dict[str, Any],
+ session_id: str,
+ scope_id: str,
+) -> tuple[dict[str, Any], str | None]:
+ if event_type not in ANNOTATION_EVENT_TYPES:
+ return event_payload, None
+ screenshot = _normalize_json_object(event_payload.get("screenshot"))
+ if "dataUrl" not in screenshot:
+ return event_payload, None
+
+ from core.workbench_media import InvalidShowScreenshot, materialize_show_screenshot
+
+ try:
+ materialized = materialize_show_screenshot(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ data_url=screenshot.get("dataUrl"),
+ )
+ except InvalidShowScreenshot as exc:
+ raise ShowSessionEventError(str(exc), code="invalid_payload") from exc
+
+ declared_content_type = _text_or_none(screenshot.get("mimeType"))
+ if declared_content_type is not None and declared_content_type.lower() != materialized.content_type:
+ Path(materialized.path).unlink(missing_ok=True)
+ raise ShowSessionEventError(
+ "screenshot.mimeType does not match the encoded image.",
+ code="invalid_payload",
+ )
+
+ for field, actual in (("width", materialized.width), ("height", materialized.height)):
+ declared = screenshot.get(field)
+ if declared is None:
+ continue
+ if isinstance(declared, bool) or not isinstance(declared, (int, float)) or declared != actual:
+ Path(materialized.path).unlink(missing_ok=True)
+ raise ShowSessionEventError(
+ f"screenshot.{field} does not match the encoded image.",
+ code="invalid_payload",
+ )
+
+ normalized_screenshot = dict(screenshot)
+ normalized_screenshot.pop("dataUrl", None)
+ normalized_screenshot.update(
+ {
+ "attachmentId": materialized.attachment_id,
+ "path": materialized.path,
+ "mimeType": materialized.content_type,
+ "width": materialized.width,
+ "height": materialized.height,
+ }
+ )
+ return {**event_payload, "screenshot": normalized_screenshot}, materialized.path
+
+
def _normalize_json_object(raw: Any) -> dict[str, Any]:
return raw if isinstance(raw, dict) else {}
@@ -561,14 +634,19 @@ def _format_transcript_text(event_type: str, payload: dict[str, Any], anchor: di
screenshot = _normalize_json_object(payload.get("screenshot"))
if screenshot:
screenshot_ref = _text_or_none(
- screenshot.get("attachmentId")
+ screenshot.get("path")
+ or screenshot.get("attachmentId")
or screenshot.get("assetId")
or screenshot.get("id")
or screenshot.get("url")
or screenshot.get("src")
)
- lines.append(f"Screenshot: {screenshot_ref or 'captured region'}")
- screenshot_region = _format_rect(screenshot.get("region") or screenshot.get("rect"))
+ screenshot_dimensions = _format_dimensions(screenshot.get("width"), screenshot.get("height"))
+ dimensions_suffix = f" ({screenshot_dimensions})" if screenshot_dimensions else ""
+ lines.append(f"Screenshot: {screenshot_ref or 'captured region'}{dimensions_suffix}")
+ screenshot_region = _format_rect(
+ screenshot.get("capturedRegion") or screenshot.get("region") or screenshot.get("rect")
+ )
if screenshot_region:
lines.append(f"Screenshot region: {screenshot_region}")
screenshot_items = _json_object_list(screenshot.get("items"))
@@ -736,6 +814,14 @@ def _format_point(raw: Any) -> str | None:
return f"x:{_format_scalar(x)}, y:{_format_scalar(y)}"
+def _format_dimensions(width: Any, height: Any) -> str | None:
+ formatted_width = _format_scalar(width)
+ formatted_height = _format_scalar(height)
+ if formatted_width is None or formatted_height is None:
+ return None
+ return f"{formatted_width}x{formatted_height}"
+
+
def _format_classification(raw: Any) -> str | None:
if isinstance(raw, dict):
return _text_or_none(raw.get("mode") or raw.get("kind") or raw.get("type"))
diff --git a/core/workbench_media.py b/core/workbench_media.py
index a3814bd83..2dbf1ed47 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -16,18 +16,45 @@ frontend renders images vs files purely from element type.
from __future__ import annotations
+import base64
+import binascii
+import io
import logging
import os
+import re
+import uuid
+from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlparse
from sqlalchemy.engine import Connection
+from config import paths
from core.reply_enhancer import _FILE_LINK_RE, _file_uri_to_local_path
from storage import media_service
logger = logging.getLogger(__name__)
+MAX_SHOW_SCREENSHOT_LONG_EDGE = 2048
+MAX_SHOW_SCREENSHOT_BYTES = 25 * 1024 * 1024
+_SHOW_SCREENSHOT_DATA_URL_RE = re.compile(
+ r"\Adata:(image/(?P<format>png|webp));base64,(?P<data>[A-Za-z0-9+/=]+)\Z",
+ re.IGNORECASE,
+)
+
+
+class InvalidShowScreenshot(ValueError):
+ """Raised when an annotation screenshot cannot be safely materialized."""
+
+
+@dataclass(frozen=True)
+class MaterializedShowScreenshot:
+ attachment_id: str
+ path: str
+ content_type: str
+ width: int
+ height: int
+
def register_agent_reply_media(
conn: Connection,
@@ -50,6 +77,85 @@ def register_agent_reply_media(
)
+def materialize_show_screenshot(
+ conn: Connection,
+ *,
+ scope_id: str,
+ session_id: str,
+ data_url: object,
+) -> MaterializedShowScreenshot:
+ """Persist an annotation screenshot and register it with the media proxy.
+
+ Show Page clients still submit a data URL. This boundary validates the
+ encoded image, writes it into the existing session attachment tree, and
+ returns the opaque media token plus the canonical path for the local agent.
+ """
+ if not isinstance(data_url, str):
+ raise InvalidShowScreenshot("screenshot.dataUrl must be a PNG or WebP data URL.")
+ match = _SHOW_SCREENSHOT_DATA_URL_RE.fullmatch(data_url)
+ if match is None:
+ raise InvalidShowScreenshot("screenshot.dataUrl must be a PNG or WebP data URL.")
+
+ encoded = match.group("data")
+ if len(encoded) > ((MAX_SHOW_SCREENSHOT_BYTES + 2) // 3) * 4:
+ raise InvalidShowScreenshot("screenshot.dataUrl is too large.")
+ try:
+ raw = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise InvalidShowScreenshot("screenshot.dataUrl contains invalid base64.") from exc
+ if not raw or len(raw) > MAX_SHOW_SCREENSHOT_BYTES:
+ raise InvalidShowScreenshot("screenshot.dataUrl is empty or too large.")
+
+ image_format = match.group("format").lower()
+ content_type = f"image/{image_format}"
+ if image_format == "png":
+ valid_signature = raw.startswith(b"\x89PNG\r\n\x1a\n")
+ else:
+ valid_signature = len(raw) >= 12 and raw[:4] == b"RIFF" and raw[8:12] == b"WEBP"
+ if not valid_signature:
+ raise InvalidShowScreenshot(f"screenshot.dataUrl is not a valid {image_format.upper()} image.")
+
+ try:
+ import imagesize
+
+ width, height = imagesize.get(io.BytesIO(raw))
+ except Exception as exc:
+ raise InvalidShowScreenshot("screenshot.dataUrl image dimensions could not be read.") from exc
+ if width <= 0 or height <= 0:
+ raise InvalidShowScreenshot("screenshot.dataUrl image dimensions could not be read.")
+ if max(width, height) > MAX_SHOW_SCREENSHOT_LONG_EDGE:
+ raise InvalidShowScreenshot(
+ f"screenshot.dataUrl long edge exceeds {MAX_SHOW_SCREENSHOT_LONG_EDGE}px."
+ )
+
+ upload_dir = paths.get_attachments_dir() / "avibe" / session_id
+ upload_dir.mkdir(parents=True, exist_ok=True)
+ local_path = upload_dir / f"screenshot_{uuid.uuid4().hex[:16]}.{image_format}"
+ try:
+ local_path.write_bytes(raw)
+ canonical_path = str(local_path.resolve(strict=True))
+ token = media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind="image",
+ source="show_annotation",
+ local_path=canonical_path,
+ file_name=local_path.name,
+ content_type=content_type,
+ )
+ except Exception:
+ local_path.unlink(missing_ok=True)
+ raise
+ return MaterializedShowScreenshot(
+ attachment_id=token,
+ path=canonical_path,
+ content_type=content_type,
+ width=int(width),
+ height=int(height),
+ )
+
+
def rewrite_agent_media(conn: Connection, *, scope_id: str | None, session_id: str, text: str) -> str:
"""Return *text* with ``file://`` links rewritten to media-proxy URLs.
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index 49fcda83d..35a6f1942 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -1,6 +1,9 @@
from __future__ import annotations
+import base64
import json
+import struct
+import zlib
from pathlib import Path
import pytest
@@ -9,7 +12,7 @@ from sqlalchemy import select
from core.show_session_events import ShowSessionEventError, ShowSessionEventStore, _format_transcript_text
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
-from storage.models import agent_sessions, messages, show_session_events
+from storage.models import agent_sessions, media_objects, messages, show_session_events
from storage.settings_service import upsert_scope
@@ -52,6 +55,25 @@ def _seed_session(session_id: str = "ses_mark") -> str:
return scope_id
+def _png_bytes(width: int, height: int) -> bytes:
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
+
+ header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
+ scanlines = (b"\x00" + b"\x00\x00\x00" * width) * height
+ return (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", header)
+ + chunk(b"IDAT", zlib.compress(scanlines))
+ + chunk(b"IEND", b"")
+ )
+
+
+def _image_data_url(content_type: str, raw: bytes) -> str:
+ return f"data:{content_type};base64,{base64.b64encode(raw).decode('ascii')}"
+
+
def test_show_event_store_records_assistant_mark_and_transcript_message(isolated_state):
_seed_session()
engine = create_sqlite_engine()
@@ -343,6 +365,140 @@ def test_show_event_store_records_element_group_annotation_context(isolated_stat
assert "Matched elements: 2" in event["transcript_text"]
+def test_show_event_store_materializes_screenshot_attachment(isolated_state):
+ scope_id = _seed_session()
+ raw = _png_bytes(4, 3)
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "intent": "review",
+ "comment": "Review the captured area.",
+ "screenshot": {
+ "attachmentId": "screenshot_client_only",
+ "mimeType": "image/png",
+ "width": 4,
+ "height": 3,
+ "capturedRegion": {"x": 24, "y": 32, "width": 640, "height": 360},
+ "dataUrl": _image_data_url("image/png", raw),
+ "items": [{"label": "1", "comment": "This counter looks stale."}],
+ },
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ screenshot = event["payload"]["screenshot"]
+ local_path = Path(screenshot["path"])
+ assert screenshot["attachmentId"] != "screenshot_client_only"
+ assert screenshot["mimeType"] == "image/png"
+ assert screenshot["width"] == 4
+ assert screenshot["height"] == 3
+ assert screenshot["capturedRegion"] == {"x": 24, "y": 32, "width": 640, "height": 360}
+ assert screenshot["items"] == [{"label": "1", "comment": "This counter looks stale."}]
+ assert "dataUrl" not in screenshot
+ assert local_path.is_absolute()
+ assert local_path.parent == isolated_state / "attachments" / "avibe" / "ses_mark"
+ assert local_path.read_bytes() == raw
+ assert f"Screenshot: {local_path} (4x3)" in event["transcript_text"]
+ assert "Screenshot region: x:24, y:32, 640x360" in event["transcript_text"]
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ media_row = conn.execute(select(media_objects)).mappings().one()
+ stored_payload = json.loads(conn.execute(select(show_session_events.c.payload_json)).scalar_one())
+ assert media_row["token"] == screenshot["attachmentId"]
+ assert media_row["scope_id"] == scope_id
+ assert media_row["session_id"] == "ses_mark"
+ assert media_row["source"] == "show_annotation"
+ assert media_row["local_path"] == str(local_path)
+ assert "dataUrl" not in stored_payload["screenshot"]
+
+
+def test_show_event_store_materializes_webp_without_conversion(isolated_state):
+ _seed_session()
+ raw = base64.b64decode("UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA")
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Review this image.",
+ "screenshot": {
+ "mimeType": "image/webp",
+ "width": 1,
+ "height": 1,
+ "capturedRegion": {"x": 0, "y": 0, "width": 1, "height": 1},
+ "dataUrl": _image_data_url("image/webp", raw),
+ "items": [],
+ },
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ screenshot = event["payload"]["screenshot"]
+ local_path = Path(screenshot["path"])
+ assert screenshot["mimeType"] == "image/webp"
+ assert local_path.suffix == ".webp"
+ assert local_path.read_bytes() == raw
+
+
+ "data_url,mime_type,width,height",
+ [
+ ("not-a-data-url", "image/png", 1, 1),
+ ("data:image/png;base64,%%%%", "image/png", 1, 1),
+ (_image_data_url("image/webp", _png_bytes(1, 1)), "image/webp", 1, 1),
+ (_image_data_url("image/png", _png_bytes(1, 1)), "image/webp", 1, 1),
+ (_image_data_url("image/png", _png_bytes(2049, 1)), "image/png", 2049, 1),
+ ],
+)
+def test_show_event_store_rejects_invalid_screenshot_data_url(
+ isolated_state, data_url, mime_type, width, height
+):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_mark",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Invalid screenshot.",
+ "screenshot": {
+ "mimeType": mime_type,
+ "width": width,
+ "height": height,
+ "capturedRegion": {"x": 0, "y": 0, "width": width, "height": height},
+ "dataUrl": data_url,
+ "items": [],
+ },
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "invalid_payload"
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events)).first() is None
+ assert conn.execute(select(media_objects)).first() is None
+ attachment_root = isolated_state / "attachments"
+ assert not attachment_root.exists() or not any(path.is_file() for path in attachment_root.rglob("*"))
+
+
def test_show_event_store_records_screenshot_annotation_batch(isolated_state):
_seed_session()
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 3e85eba56..673091bee 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -1,12 +1,15 @@
import asyncio
+import base64
import hashlib
import io
import json
import os
import socket
import ssl
+import struct
import tarfile
import urllib.error
+import zlib
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
@@ -113,6 +116,22 @@ def _create_show_page(session_id: str, visibility: str) -> str | None:
store.close()
+def _screenshot_png(width: int, height: int) -> tuple[bytes, str]:
+ def chunk(kind: bytes, data: bytes) -> bytes:
+ checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
+
+ header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
+ scanlines = (b"\x00" + b"\x00\x00\x00" * width) * height
+ raw = (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", header)
+ + chunk(b"IDAT", zlib.compress(scanlines))
+ + chunk(b"IEND", b"")
+ )
+ return raw, f"data:image/png;base64,{base64.b64encode(raw).decode('ascii')}"
+
+
def _create_show_page_record(session_id: str, visibility: str) -> str | None:
store = ShowPageStore()
try:
@@ -1879,6 +1898,7 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
_create_show_page("ses123", "private")
token = "session-write-token"
monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ raw, data_url = _screenshot_png(4, 3)
dispatches = []
dispatch_done = asyncio.Event()
@@ -1905,7 +1925,11 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
"dispatch": True,
"screenshot": {
"attachmentId": "show_asset_screenshot_1",
- "region": {"x": 24, "y": 32, "width": 640, "height": 360},
+ "mimeType": "image/png",
+ "width": 4,
+ "height": 3,
+ "capturedRegion": {"x": 24, "y": 32, "width": 640, "height": 360},
+ "dataUrl": data_url,
"items": [
{
"label": "1",
@@ -1915,7 +1939,7 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
{
"label": "2",
"comment": "Crop this empty area.",
- "region": {"x": 420, "y": 240, "width": 160, "height": 72},
+ "rect": {"x": 420, "y": 240, "width": 160, "height": 72},
},
],
},
@@ -1925,16 +1949,29 @@ def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, t
assert response.status_code == 201
payload = response.get_json()
- assert payload["event"]["payload"]["primaryAnchor"] == "screenshot"
+ event = payload["event"]
+ screenshot = event["payload"]["screenshot"]
+ assert event["payload"]["primaryAnchor"] == "screenshot"
+ assert "dataUrl" not in screenshot
+ assert screenshot["attachmentId"] != "show_asset_screenshot_1"
+ assert Path(screenshot["path"]).read_bytes() == raw
asyncio.run(asyncio.wait_for(dispatch_done.wait(), timeout=1))
assert dispatches
transcript = dispatches[0]["text"]
assert "Anchor kind: screenshot" in transcript
- assert "Screenshot: show_asset_screenshot_1" in transcript
+ assert f"Screenshot: {screenshot['path']} (4x3)" in transcript
assert "Screenshot region: x:24, y:32, 640x360" in transcript
assert "1. This counter looks stale. (x:120, y:80)" in transcript
assert "2. Crop this empty area. (x:420, y:240, 160x72)" in transcript
+ media_response = app.test_client().get(
+ f"/api/media/{screenshot['attachmentId']}",
+ base_url="http://127.0.0.1:5123",
+ )
+ assert media_response.status_code == 200
+ assert media_response.content == raw
+ assert media_response.headers["content-type"] == "image/png"
+
def test_private_show_page_rejects_show_event_without_write_token(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -2217,10 +2254,14 @@ def test_public_show_events_stream_redacts_nested_dispatch_ids(monkeypatch, tmp_
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_agent_session("ses123")
- _create_show_page("ses123", "public")
+ share_id = _create_show_page("ses123", "public")
async def _collect_live_dispatch() -> str:
- response = await _show_events_stream("ses123", public=True)
+ response = await _show_events_stream(
+ "ses123",
+ public=True,
+ public_share_id=share_id,
+ )
iterator = response.body_iterator.__aiter__()
chunks = []
try:
@@ -2336,6 +2377,58 @@ def test_public_show_events_stream_redacts_internal_ids(monkeypatch, tmp_path):
assert '"message"' not in body
+def test_public_show_events_stream_redacts_screenshot_path(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+ from vibe.ui_server import _show_events_stream
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ _, data_url = _screenshot_png(4, 3)
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses123",
+ {
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Review this screenshot.",
+ "screenshot": {
+ "mimeType": "image/png",
+ "width": 4,
+ "height": 3,
+ "capturedRegion": {"x": 0, "y": 0, "width": 40, "height": 30},
+ "dataUrl": data_url,
+ "items": [],
+ },
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ async def collect_replay() -> str:
+ response = await _show_events_stream(
+ "ses123",
+ public=True,
+ public_share_id=share_id,
+ )
+ iterator = response.body_iterator.__aiter__()
+ try:
+ chunks = [await iterator.__anext__(), await iterator.__anext__()]
+ finally:
+ await iterator.aclose()
+ return "".join(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk for chunk in chunks)
+
+ body = asyncio.run(collect_replay())
+ screenshot = event["payload"]["screenshot"]
+ assert screenshot["path"] not in body
+ assert '"path"' not in body
+ assert screenshot["attachmentId"] in body
+ assert f"/p/{share_id}/__show/media/{screenshot['attachmentId']}" in body
+
+
def test_cli_show_event_ingress_records_and_publishes(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2683,6 +2776,86 @@ def test_public_show_page_events_accept_oauth_user_and_record_author(monkeypatch
assert "[email protected]" not in json.dumps(listed)
+def test_public_show_page_redacts_materialized_screenshot_path(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ raw, data_url = _screenshot_png(4, 3)
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Review this screenshot.",
+ "screenshot": {
+ "attachmentId": "screenshot_client_only",
+ "mimeType": "image/png",
+ "width": 4,
+ "height": 3,
+ "capturedRegion": {"x": 0, "y": 0, "width": 40, "height": 30},
+ "dataUrl": data_url,
+ "items": [],
+ },
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ internal_event = published[0]
+ internal_screenshot = internal_event["payload"]["screenshot"]
+ assert Path(internal_screenshot["path"]).is_file()
+ assert internal_screenshot["path"] in internal_event["transcript_text"]
+
+ public_event = response.get_json()["event"]
+ public_screenshot = public_event["payload"]["screenshot"]
+ assert "path" not in public_screenshot
+ assert public_screenshot["attachmentId"] == internal_screenshot["attachmentId"]
+ assert internal_screenshot["path"] not in public_event["transcript_text"]
+ assert f"Screenshot: {internal_screenshot['attachmentId']} (4x3)" in public_event["transcript_text"]
+ assert public_screenshot["url"] == (
+ f"/p/{share_id}/__show/media/{internal_screenshot['attachmentId']}"
+ )
+
+ anonymous_media = app.test_client().get(
+ public_screenshot["url"],
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ assert anonymous_media.status_code == 200
+ assert anonymous_media.content == raw
+ assert anonymous_media.headers["content-type"] == "image/png"
+
+ _create_agent_session("ses456")
+ other_share_id = _create_show_page("ses456", "public")
+ cross_share_media = app.test_client().get(
+ f"/p/{other_share_id}/__show/media/{internal_screenshot['attachmentId']}",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ assert cross_share_media.status_code == 404
+
+ listed = client.get(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ ).get_json()["events"][0]
+ assert "path" not in listed["payload"]["screenshot"]
+ assert internal_screenshot["path"] not in json.dumps(listed)
+
+
def test_public_show_page_accepts_mark_read_receipt_and_records_reader(monkeypatch, tmp_path):
from core.show_session_events import ShowSessionEventStore
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bd4b68565..551c8cd54 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6984,6 +6984,15 @@ def media_get(token: str):
``inline`` (so images render in ``<img>`` and PDFs preview); ``?download=1``
forces an attachment download.
"""
+ return _registered_media_response(token)
+
+
+def _registered_media_response(
+ token: str,
+ *,
+ expected_session_id: str | None = None,
+ expected_source: str | None = None,
+):
from urllib.parse import quote
from storage import media_service
@@ -6993,6 +7002,10 @@ def media_get(token: str):
row = media_service.get_by_token(conn, token)
if not row or row.get("revoked_at"):
return jsonify({"error": "not_found"}), 404
+ if expected_session_id is not None and row.get("session_id") != expected_session_id:
+ return jsonify({"error": "not_found"}), 404
+ if expected_source is not None and row.get("source") != expected_source:
+ return jsonify({"error": "not_found"}), 404
stored = row["local_path"]
try:
candidate = Path(stored).resolve(strict=True)
@@ -8616,6 +8629,7 @@ def _show_event_response_from_payload(
*,
author: dict[str, str] | None = None,
public: bool = False,
+ public_share_id: str | None = None,
allow_dispatch: bool = True,
):
if show_event_payload_session_mismatch(session_id, payload):
@@ -8640,7 +8654,19 @@ def _show_event_response_from_payload(
_publish_show_session_event(event_payload)
if allow_dispatch:
_dispatch_show_event_if_requested(event_payload)
- return jsonify({"ok": True, "event": _show_event_response_payload(event_payload, public=public)}), 201
+ return (
+ jsonify(
+ {
+ "ok": True,
+ "event": _show_event_response_payload(
+ event_payload,
+ public=public,
+ public_share_id=public_share_id,
+ ),
+ }
+ ),
+ 201,
+ )
def record_local_show_event(session_id: str, payload: dict[str, Any], *, dispatch_sync: bool = False) -> dict[str, Any]:
@@ -8775,7 +8801,12 @@ def _publish_show_dispatch_event(event_payload: dict[str, Any], event_name: str,
)
-def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
+def _show_event_response_payload(
+ event_payload: dict[str, Any],
+ *,
+ public: bool = False,
+ public_share_id: str | None = None,
+) -> dict[str, Any]:
if not public:
return event_payload
public_event = {
@@ -8789,6 +8820,26 @@ def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool
author = public_payload.get("author")
if isinstance(author, dict) and "email" in author:
public_payload["author"] = {key: value for key, value in author.items() if key != "email"}
+ screenshot = public_payload.get("screenshot")
+ if isinstance(screenshot, dict):
+ local_path = screenshot.get("path")
+ public_screenshot = {key: value for key, value in screenshot.items() if key != "path"}
+ attachment_id = public_screenshot.get("attachmentId")
+ if (
+ public_share_id
+ and isinstance(local_path, str)
+ and local_path
+ and isinstance(attachment_id, str)
+ and attachment_id
+ ):
+ public_screenshot["url"] = (
+ f"/p/{quote(public_share_id, safe='')}/__show/media/{quote(attachment_id, safe='')}"
+ )
+ public_payload["screenshot"] = public_screenshot
+ transcript_text = public_event.get("transcript_text")
+ if isinstance(local_path, str) and local_path and isinstance(transcript_text, str):
+ public_ref = str(public_screenshot.get("attachmentId") or "screenshot attachment")
+ public_event["transcript_text"] = transcript_text.replace(local_path, public_ref)
public_event["payload"] = public_payload
return public_event
@@ -8815,20 +8866,35 @@ def _redact_public_dispatch_value(value: Any) -> Any:
return value
-def _show_events_list_payload(payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
+def _show_events_list_payload(
+ payload: dict[str, Any],
+ *,
+ public: bool = False,
+ public_share_id: str | None = None,
+) -> dict[str, Any]:
if not public:
return payload
return {
**payload,
"events": [
- _show_event_response_payload(event_payload, public=True)
+ _show_event_response_payload(
+ event_payload,
+ public=True,
+ public_share_id=public_share_id,
+ )
for event_payload in payload.get("events", [])
if isinstance(event_payload, dict)
],
}
-async def _show_events_stream(session_id: str, *, after_id: str | None = None, public: bool = False):
+async def _show_events_stream(
+ session_id: str,
+ *,
+ after_id: str | None = None,
+ public: bool = False,
+ public_share_id: str | None = None,
+):
import asyncio
from fastapi.responses import StreamingResponse
@@ -8854,7 +8920,14 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, p
for event_payload in events:
if isinstance(event_payload.get("id"), str):
replayed_ids.add(event_payload["id"])
- yield _sse_frame("show.event", _show_event_response_payload(event_payload, public=public))
+ yield _sse_frame(
+ "show.event",
+ _show_event_response_payload(
+ event_payload,
+ public=public,
+ public_share_id=public_share_id,
+ ),
+ )
cursor = batch.get("next_after_id")
if not cursor:
break
@@ -8872,7 +8945,14 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, p
continue
if isinstance(event_id, str):
replayed_ids.add(event_id)
- yield _sse_frame("show.event", _show_event_response_payload(event_payload, public=public))
+ yield _sse_frame(
+ "show.event",
+ _show_event_response_payload(
+ event_payload,
+ public=public,
+ public_share_id=public_share_id,
+ ),
+ )
elif event_type == "show.dispatch" and isinstance(event_payload, dict) and _event_visible(event_payload):
yield _sse_frame("show.dispatch", _show_dispatch_response_payload(event_payload, public=public))
except asyncio.TimeoutError:
@@ -8894,13 +8974,19 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, p
)
-async def _show_events_response(session_id: str, *, public: bool = False):
+async def _show_events_response(
+ session_id: str,
+ *,
+ public: bool = False,
+ public_share_id: str | None = None,
+):
if request.method == "GET":
if request.args.get("stream") == "1":
return await _show_events_stream(
session_id,
after_id=request.args.get("after_id") or _last_event_id_from_request(),
public=public,
+ public_share_id=public_share_id,
)
store = _show_session_event_store()
try:
@@ -8909,7 +8995,13 @@ async def _show_events_response(session_id: str, *, public: bool = False):
except (TypeError, ValueError):
limit = 100
payload = store.list(session_id, after_id=request.args.get("after_id") or None, limit=limit)
- return jsonify(_show_events_list_payload(payload, public=public))
+ return jsonify(
+ _show_events_list_payload(
+ payload,
+ public=public,
+ public_share_id=public_share_id,
+ )
+ )
finally:
store.close()
@@ -9722,9 +9814,24 @@ async def serve_public_show_page(share_id, asset_path):
show_public_event_write_token(share_id, page.session_id) if author is not None else None
),
)
+ if asset_path.strip("/").startswith("__show/media/"):
+ if request.method not in {"GET", "HEAD"}:
+ return jsonify({"ok": False, "code": "method_not_allowed"}), 405
+ token = asset_path.strip("/").removeprefix("__show/media/")
+ if not token or "/" in token:
+ return _show_page_file_not_found_response()
+ return _registered_media_response(
+ token,
+ expected_session_id=page.session_id,
+ expected_source="show_annotation",
+ )
if asset_path.strip("/") in {"__show/events", "__events"}:
if request.method == "GET":
- return await _show_events_response(page.session_id, public=True)
+ return await _show_events_response(
+ page.session_id,
+ public=True,
+ public_share_id=share_id,
+ )
if request.method != "POST":
return jsonify({"ok": False, "code": "method_not_allowed"}), 405
author = _show_request_author(public=True)
@@ -9752,6 +9859,7 @@ async def serve_public_show_page(share_id, asset_path):
payload,
author=author,
public=True,
+ public_share_id=share_id,
allow_dispatch=False,
)
if request.method in {"GET", "HEAD"}: