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.

Persist Show Page session events (#356)

Call White3f76445f2814
diff --git a/core/show_pages.py b/core/show_pages.py
index 5791c25ea..d3fc4b955 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -1,6 +1,8 @@
from __future__ import annotations
import re
+import hashlib
+import hmac
import secrets
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -22,6 +24,9 @@ VISIBILITY_PUBLIC = "public"
VISIBILITY_OFFLINE = "offline"
VISIBILITIES = {VISIBILITY_PRIVATE, VISIBILITY_PUBLIC, VISIBILITY_OFFLINE}
SHARE_ID_BYTES = 8
+SHOW_EVENT_WRITE_TOKEN_COOKIE = "vibe_show_event_token"
+SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"
+SHOW_CLI_EVENT_TOKEN_HEADER = "X-Vibe-Show-Cli-Token"
_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
_LIKE_ESCAPE = "\\"
AVIBE_CLOUD_CONNECT_GUIDANCE = (
@@ -67,6 +72,40 @@ def show_page_dir(session_id: str) -> Path:
return paths.get_show_page_dir(validate_session_id(session_id))
+def show_event_write_token(session_id: str) -> str:
+ return hmac.new(
+ _load_or_create_show_event_secret().encode("utf-8"),
+ validate_session_id(session_id).encode("utf-8"),
+ hashlib.sha256,
+ ).hexdigest()
+
+
+def show_cli_event_token() -> str:
+ return hmac.new(
+ _load_or_create_show_event_secret().encode("utf-8"),
+ b"cli-show-events",
+ hashlib.sha256,
+ ).hexdigest()
+
+
+def _load_or_create_show_event_secret() -> str:
+ secret_path = paths.get_state_dir() / "show_event_secret"
+ try:
+ secret = secret_path.read_text(encoding="utf-8").strip()
+ except OSError:
+ secret = ""
+ if secret:
+ return secret
+ secret = secrets.token_urlsafe(48)
+ secret_path.parent.mkdir(parents=True, exist_ok=True)
+ secret_path.write_text(secret, encoding="utf-8")
+ try:
+ secret_path.chmod(0o600)
+ except OSError:
+ pass
+ return secret
+
+
def ensure_show_page_dir(session_id: str) -> Path:
page_dir = show_page_dir(session_id)
page_dir.mkdir(parents=True, exist_ok=True)
@@ -494,6 +533,34 @@ import "@avibe/show-ui/styles.css"
import "./styles.css"
import App from "./App"
+type VibeShowRuntimeConfig = {
+ sessionId?: string
+ basePath: string
+ eventsPath: string
+ streamPath: string
+ writeToken?: string
+}
+
+declare global {
+ var __AVIBE_SHOW__: VibeShowRuntimeConfig | undefined
+}
+
+function readCookie(name: string): string | undefined {
+ const prefix = `${name}=`
+ const item = document.cookie.split("; ").find((value) => value.startsWith(prefix))
+ return item ? decodeURIComponent(item.slice(prefix.length)) : undefined
+}
+
+globalThis.__AVIBE_SHOW__ = {
+ sessionId: window.location.pathname.match(/\\/show\\/([^/]+)/)?.[1]
+ ? decodeURIComponent(window.location.pathname.match(/\\/show\\/([^/]+)/)![1])
+ : undefined,
+ basePath: window.location.pathname.match(/^(.*\\/(?:show|p)\\/[^/]+\\/)$/)?.[1] || window.location.pathname.replace(/[^/]*$/, ""),
+ eventsPath: "__show/events",
+ streamPath: "__show/events?stream=1",
+ writeToken: readCookie("vibe_show_event_token")
+}
+
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
diff --git a/core/show_session_events.py b/core/show_session_events.py
new file mode 100644
index 000000000..45bb87a36
--- /dev/null
+++ b/core/show_session_events.py
@@ -0,0 +1,253 @@
+from __future__ import annotations
+
+import json
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select, update
+
+from config import paths
+from core.services import sessions as workbench_sessions_service
+from storage import messages_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+from storage.models import agent_sessions, show_session_events
+
+DEFAULT_MARK_SCOPE = "default"
+SUPPORTED_EVENT_TYPES = {"assistant.mark.created", "human.intent.submitted", "human.annotation.created"}
+
+
+class ShowSessionEventError(ValueError):
+ def __init__(self, message: str, *, code: str):
+ super().__init__(message)
+ self.code = code
+
+
+@dataclass(frozen=True)
+class ShowSessionEventStore:
+ db_path: Path | None = None
+
+ def __post_init__(self) -> None:
+ if self.db_path is None:
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ else:
+ from storage.migrations import run_migrations
+
+ run_migrations(self.db_path)
+ object.__setattr__(self, "engine", create_sqlite_engine(self.db_path))
+
+ def close(self) -> None:
+ self.engine.dispose()
+
+ def append(self, session_id: str, payload: dict[str, Any]) -> dict[str, Any]:
+ event_type = _validate_event_type(payload.get("type"))
+ actor = _actor_for_event(event_type)
+ event_payload = _normalize_event_payload(event_type, payload)
+ anchor = _normalize_json_object(payload.get("anchor"))
+ scope = _event_scope(event_type, event_payload)
+ transcript_text = _format_transcript_text(event_type, event_payload, anchor)
+ event_id = _event_id(payload, event_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).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")
+
+ 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(
+ conn,
+ scope_id=session["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="agent" if actor == "assistant" 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,
+ },
+ 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)
+
+ event = {
+ "id": event_id,
+ "session_id": session_id,
+ "scope_id": session["scope_id"],
+ "type": event_type,
+ "actor": actor,
+ "scope": scope,
+ "anchor": anchor,
+ "payload": event_payload,
+ "transcript_text": transcript_text,
+ "message_id": message_id,
+ "message": message,
+ "created_at": created_at,
+ }
+ return event
+
+ def list(self, session_id: str, *, after_id: str | None = None, limit: int = 100) -> dict[str, Any]:
+ effective_limit = min(max(int(limit), 1), 500)
+ with self.engine.connect() as conn:
+ query = select(show_session_events).where(show_session_events.c.session_id == session_id)
+ if after_id:
+ anchor = conn.execute(
+ select(show_session_events.c.created_at).where(show_session_events.c.id == after_id)
+ ).scalar_one_or_none()
+ if anchor is not None:
+ query = query.where(
+ (show_session_events.c.created_at > anchor)
+ | (
+ (show_session_events.c.created_at == anchor)
+ & (show_session_events.c.id > after_id)
+ )
+ )
+ query = query.order_by(show_session_events.c.created_at.asc(), show_session_events.c.id.asc()).limit(
+ effective_limit
+ )
+ rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+ return {
+ "events": rows,
+ "next_after_id": rows[-1]["id"] if len(rows) == effective_limit else None,
+ }
+
+
+def _validate_event_type(raw: Any) -> str:
+ event_type = str(raw or "").strip()
+ if event_type not in SUPPORTED_EVENT_TYPES:
+ raise ShowSessionEventError(f"Unsupported show event type: {event_type}", code="unsupported_event_type")
+ return event_type
+
+
+def _actor_for_event(event_type: str) -> str:
+ return "assistant" if event_type.startswith("assistant.") else "human"
+
+
+def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if event_type == "assistant.mark.created":
+ mark = _normalize_json_object(payload.get("mark") or payload.get("payload"))
+ target = _required_text(mark.get("target"), "mark.target")
+ body = _required_text(mark.get("body") or mark.get("comment"), "mark.body")
+ return {
+ "id": _text_or_none(mark.get("id")) or _new_id("mark"),
+ "role": "assistant",
+ "scope": _text_or_none(mark.get("scope")) or DEFAULT_MARK_SCOPE,
+ "target": target,
+ "body": body,
+ "createdAt": _text_or_none(mark.get("createdAt")) or _utc_now_iso(),
+ }
+ return _normalize_json_object(payload.get("payload") or payload)
+
+
+def _normalize_json_object(raw: Any) -> dict[str, Any]:
+ return raw if isinstance(raw, dict) else {}
+
+
+def _event_scope(event_type: str, payload: dict[str, Any]) -> str:
+ if event_type == "assistant.mark.created":
+ return _text_or_none(payload.get("scope")) or DEFAULT_MARK_SCOPE
+ return _text_or_none(payload.get("scope")) or DEFAULT_MARK_SCOPE
+
+
+def _event_id(original_payload: dict[str, Any], event_payload: dict[str, Any]) -> str:
+ return (
+ _text_or_none(original_payload.get("id"))
+ or _text_or_none(event_payload.get("id"))
+ or _new_id("show_evt")
+ )
+
+
+def _format_transcript_text(event_type: str, payload: dict[str, Any], anchor: dict[str, Any]) -> str:
+ if event_type == "assistant.mark.created":
+ lines = [
+ f"[agent-mark:{payload.get('scope') or DEFAULT_MARK_SCOPE}] {payload.get('target')}",
+ "",
+ str(payload.get("body") or "").strip(),
+ ]
+ selector = _text_or_none(anchor.get("selector"))
+ if selector:
+ lines.extend(["", f"Anchor: {selector}"])
+ text = _text_or_none(anchor.get("text"))
+ if text:
+ lines.append(f"Text: {text}")
+ return "\n".join(lines)
+
+ label = "annotation" if event_type == "human.annotation.created" else "intent"
+ text = _text_or_none(payload.get("text") or payload.get("comment") or payload.get("value"))
+ return f"[show-{label}:{payload.get('scope') or DEFAULT_MARK_SCOPE}] {text or _json_dumps(payload)}"
+
+
+def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": row["id"],
+ "session_id": row["session_id"],
+ "type": row["event_type"],
+ "actor": row["actor"],
+ "scope": row["scope"],
+ "anchor": _json_loads(row.get("anchor_json"), {}),
+ "payload": _json_loads(row.get("payload_json"), {}),
+ "transcript_text": row.get("transcript_text"),
+ "message_id": row.get("message_id"),
+ "created_at": row.get("created_at"),
+ }
+
+
+def _required_text(raw: Any, field: str) -> str:
+ value = _text_or_none(raw)
+ if not value:
+ raise ShowSessionEventError(f"{field} is required.", code="invalid_payload")
+ return value
+
+
+def _text_or_none(raw: Any) -> str | None:
+ if raw is None:
+ return None
+ value = str(raw).strip()
+ return value or None
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _new_id(prefix: str) -> str:
+ return f"{prefix}_{uuid.uuid4().hex[:16]}"
+
+
+def _json_dumps(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _json_loads(value: Any, fallback: Any) -> Any:
+ try:
+ return json.loads(value or "")
+ except Exception:
+ return fallback
diff --git a/storage/alembic/versions/20260530_0009_show_session_events.py b/storage/alembic/versions/20260530_0009_show_session_events.py
new file mode 100644
index 000000000..5c941a573
--- /dev/null
+++ b/storage/alembic/versions/20260530_0009_show_session_events.py
@@ -0,0 +1,54 @@
+"""show session events
+
+Revision ID: 20260530_0009
+Revises: 20260530_0008
+Create Date: 2026-05-30
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260530_0009"
+down_revision = "20260530_0008"
+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 "show_session_events" not in _tables():
+ op.create_table(
+ "show_session_events",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("session_id", sa.String(), nullable=False),
+ sa.Column("event_type", sa.String(), nullable=False),
+ sa.Column("actor", sa.String(), nullable=False),
+ sa.Column("scope", sa.String(), nullable=False),
+ sa.Column("anchor_json", sa.Text(), nullable=False),
+ sa.Column("payload_json", sa.Text(), nullable=False),
+ sa.Column("transcript_text", sa.Text(), nullable=True),
+ sa.Column("message_id", sa.String(), sa.ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ )
+ op.create_index(
+ "ix_show_session_events_session_created",
+ "show_session_events",
+ ["session_id", "created_at"],
+ if_not_exists=True,
+ )
+ op.create_index(
+ "ix_show_session_events_type_created",
+ "show_session_events",
+ ["event_type", "created_at"],
+ if_not_exists=True,
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("show_session_events")
diff --git a/storage/importer.py b/storage/importer.py
index 893f56c69..5b7bc1370 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -245,6 +245,9 @@ def _set_data_migration_marker(conn: Connection, key: str, metadata: dict[str, A
def _run_sqlite_data_migrations(conn: Connection) -> dict[str, int]:
counts: dict[str, int] = {}
+ scope_agent_names = _backfill_scope_agent_names(conn)
+ if scope_agent_names:
+ counts["scope_agent_names_backfilled"] = scope_agent_names
if not _has_data_migration_marker(conn, ROUTING_CANONICAL_FIELDS_MARKER):
migrated = _migrate_scope_routing_to_canonical_fields(conn)
_set_data_migration_marker(
@@ -257,6 +260,27 @@ def _run_sqlite_data_migrations(conn: Connection) -> dict[str, int]:
return counts
+def _backfill_scope_agent_names(conn: Connection) -> int:
+ migrated = 0
+ now = _utc_now_iso()
+ for backend in ("opencode", "claude", "codex"):
+ rows = _legacy_scope_rows_for_backend(conn, backend)
+ if not rows:
+ continue
+ default_agent_name: str | None = None
+ for scope_id, settings_json in rows:
+ agent_name = _explicit_agent_name_from_settings_json(settings_json)
+ if not agent_name:
+ if default_agent_name is None:
+ default_agent_name = _ensure_backend_default_agent(conn, backend, now)
+ if not default_agent_name:
+ continue
+ agent_name = default_agent_name
+ _backfill_scope_agent_name(conn, scope_id, settings_json, agent_name, now)
+ migrated += 1
+ return migrated
+
+
def _migrate_scope_routing_to_canonical_fields(conn: Connection) -> int:
migrated = 0
rows = conn.execute(
@@ -479,21 +503,7 @@ def _migrate_session_state_for_import(state: SessionState, *, primary_platform:
def _backfill_imported_scope_agent_names(conn: Connection) -> None:
- now = _utc_now_iso()
- for backend in ("opencode", "claude", "codex"):
- rows = _legacy_scope_rows_for_backend(conn, backend)
- if not rows:
- continue
- default_agent_name: str | None = None
- for scope_id, settings_json in rows:
- agent_name = _explicit_agent_name_from_settings_json(settings_json)
- if not agent_name:
- if default_agent_name is None:
- default_agent_name = _ensure_backend_default_agent(conn, backend, now)
- if not default_agent_name:
- continue
- agent_name = default_agent_name
- _backfill_scope_agent_name(conn, scope_id, settings_json, agent_name, now)
+ _backfill_scope_agent_names(conn)
def _legacy_scope_rows_for_backend(conn: Connection, backend: str):
diff --git a/storage/migrations.py b/storage/migrations.py
index bba521920..98a888c45 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -1,16 +1,19 @@
from __future__ import annotations
import sqlite3
+from importlib import import_module
from pathlib import Path
+from types import SimpleNamespace
from alembic import command
from alembic.config import Config
from config import paths
-from storage.db import sqlite_url
+from storage.db import create_sqlite_engine, sqlite_url
INITIAL_REVISION = "20260501_0001"
-LATEST_SCHEMA_REVISION = "20260526_0006"
+LATEST_SCHEMA_REVISION = "20260530_0009"
+REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"
INITIAL_TABLES = {
"state_meta",
"agents",
@@ -20,7 +23,8 @@ INITIAL_TABLES = {
"agent_sessions",
"runtime_records",
}
-HEAD_TABLES = INITIAL_TABLES | {"run_definitions", "agent_runs", "show_pages", "messages"}
+HEAD_TABLES = INITIAL_TABLES | {"run_definitions", "agent_runs", "show_pages", "messages", "show_session_events"}
+PRE_SHOW_SESSION_EVENTS_HEAD_TABLES = HEAD_TABLES - {"show_session_events"}
HEAD_REQUIRED_COLUMNS = {
"agents": {"enabled"},
"scope_settings": {"agent_name"},
@@ -149,7 +153,7 @@ def _repair_unreleased_head_schema_drift(db_path: Path) -> None:
tables = _table_names(conn)
_repair_initial_required_columns(conn, tables)
tables = _table_names(conn)
- if not HEAD_TABLES.issubset(tables):
+ if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables):
return
if "alembic_version" not in tables:
return
@@ -157,7 +161,7 @@ def _repair_unreleased_head_schema_drift(db_path: Path) -> None:
if version not in {("20260515_0002",), ("20260522_0003",), ("20260523_0004",)}:
return
- if not _head_schema_ready(conn, tables) and _repair_head_required_columns(conn, tables):
+ if not _pre_show_session_events_head_schema_ready(conn, tables) and _repair_head_required_columns(conn, tables):
conn.commit()
@@ -199,12 +203,52 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
if not _head_schema_ready(conn, tables):
missing = _missing_head_schema_description(conn, tables)
raise RuntimeError(f"existing SQLite head schema is incomplete; missing: {missing}")
+ _run_remove_legacy_default_agent_migration(db_path)
command.stamp(cfg, LATEST_SCHEMA_REVISION)
+ _run_post_stamp_data_migrations(db_path)
+ return
+ if PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables):
+ if not _pre_show_session_events_head_schema_ready(conn, tables):
+ _repair_head_required_columns(conn, tables)
+ conn.commit()
+ tables = _table_names(conn)
+ if not _pre_show_session_events_head_schema_ready(conn, tables):
+ missing = _missing_pre_show_session_events_head_schema_description(conn, tables)
+ raise RuntimeError(f"existing SQLite head schema is incomplete; missing: {missing}")
+ _run_remove_legacy_default_agent_migration(db_path)
+ command.stamp(cfg, REMOVE_LEGACY_DEFAULT_AGENT_REVISION)
+ _run_post_stamp_data_migrations(db_path)
return
command.stamp(cfg, INITIAL_REVISION)
+def _run_remove_legacy_default_agent_migration(db_path: Path) -> None:
+ revision_module = import_module("storage.alembic.versions.20260530_0008_remove_legacy_default_agent")
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ original_op = revision_module.op
+ revision_module.op = SimpleNamespace(get_bind=lambda: conn)
+ try:
+ revision_module.upgrade()
+ finally:
+ revision_module.op = original_op
+ finally:
+ engine.dispose()
+
+
+def _run_post_stamp_data_migrations(db_path: Path) -> None:
+ from storage.importer import _run_sqlite_data_migrations
+
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ _run_sqlite_data_migrations(conn)
+ finally:
+ engine.dispose()
+
+
def _table_names(conn: sqlite3.Connection) -> set[str]:
return {
row[0]
@@ -224,8 +268,14 @@ def _head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
return all(required_columns.issubset(_column_names(conn, table)) for table, required_columns in HEAD_REQUIRED_COLUMNS.items())
+def _pre_show_session_events_head_schema_ready(conn: sqlite3.Connection, tables: set[str]) -> bool:
+ if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables):
+ return False
+ return all(required_columns.issubset(_column_names(conn, table)) for table, required_columns in HEAD_REQUIRED_COLUMNS.items())
+
+
def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) -> bool:
- if not HEAD_TABLES.issubset(tables):
+ if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables):
return False
changed = False
changed = _repair_initial_required_columns(conn, tables) or changed
@@ -376,3 +426,18 @@ def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str])
if missing_columns:
missing_parts.append(f"{table}.{', '.join(sorted(missing_columns))}")
return "; ".join(missing_parts) or "unknown head schema drift"
+
+
+def _missing_pre_show_session_events_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:
+ missing_parts = (
+ [f"tables {', '.join(sorted(PRE_SHOW_SESSION_EVENTS_HEAD_TABLES - tables))}"]
+ if not PRE_SHOW_SESSION_EVENTS_HEAD_TABLES.issubset(tables)
+ else []
+ )
+ for table, required_columns in HEAD_REQUIRED_COLUMNS.items():
+ if table not in tables:
+ continue
+ missing_columns = required_columns - _column_names(conn, table)
+ if missing_columns:
+ missing_parts.append(f"{table}.{', '.join(sorted(missing_columns))}")
+ return "; ".join(missing_parts) or "unknown head schema drift"
diff --git a/storage/models.py b/storage/models.py
index e8560d8e1..f7031a725 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -255,6 +255,23 @@ show_pages = Table(
Index("ix_show_pages_visibility", "visibility"),
)
+show_session_events = Table(
+ "show_session_events",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("session_id", String, nullable=False),
+ Column("event_type", String, nullable=False),
+ Column("actor", String, nullable=False),
+ Column("scope", String, nullable=False),
+ Column("anchor_json", Text, nullable=False),
+ Column("payload_json", Text, nullable=False),
+ Column("transcript_text", Text, nullable=True),
+ Column("message_id", String, ForeignKey("messages.id", ondelete="SET NULL"), nullable=True),
+ Column("created_at", String, nullable=False),
+ Index("ix_show_session_events_session_created", "session_id", "created_at"),
+ Index("ix_show_session_events_type_created", "event_type", "created_at"),
+)
+
# Platform-agnostic chat message store. Every IM adapter (Slack, Discord,
# Telegram, Lark, WeChat, Avibe/Web UI) writes user+agent turns here so the
# workbench Inbox and per-session history can read from a single ORM
@@ -298,4 +315,5 @@ imported_state_tables = [
runtime_records,
scopes,
messages,
+ show_session_events,
]
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index cef34c5e2..3c763a6d1 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -2,7 +2,7 @@ import json
from config import paths
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
-from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir, show_page_payload
+from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir, show_cli_event_token, show_page_payload
from storage.pagination import PageRequest
from vibe import cli
@@ -17,7 +17,7 @@ def test_show_without_subcommand_prints_help(capsys):
assert cli.cmd_show(args) == 0
captured = capsys.readouterr()
assert "Manage the one visual Show Page attached to an Agent Session." in captured.out
- assert "usage: vibe show [-h] {list,path,status,update} ..." in captured.out
+ assert "usage: vibe show [-h] {list,path,status,update,mark} ..." in captured.out
assert "vibe show list" in captured.out
assert "vibe show path --session-id sesk8m4q2p7x" in captured.out
@@ -165,6 +165,11 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):
index_html = index_path.read_text(encoding="utf-8")
assert 'src="./src/main.tsx"' in index_html
assert "Ready to visualize" in index_html
+ main_tsx = (page_dir / "src" / "main.tsx").read_text(encoding="utf-8")
+ assert "globalThis.__AVIBE_SHOW__" in main_tsx
+ assert "declare global" in main_tsx
+ assert 'eventsPath: "__show/events"' in main_tsx
+ assert 'writeToken: readCookie("vibe_show_event_token")' in main_tsx
assert "Ready to visualize" in (page_dir / "src" / "App.tsx").read_text(encoding="utf-8")
assert (page_dir / "api" / "health.ts").exists()
@@ -343,3 +348,172 @@ def test_show_update_rotate_share_fails_while_private(monkeypatch, tmp_path, cap
assert cli.cmd_show_update(args) == 1
payload = json.loads(capsys.readouterr().err)
assert payload["code"] == "not_public"
+
+
+def test_show_mark_cli_records_event_and_message(monkeypatch, tmp_path, capsys):
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions, messages, show_session_events
+ from storage.settings_service import upsert_scope
+ from storage import messages_service
+ from sqlalchemy import select
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_show", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses123",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_ses123",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "mark",
+ "--session-id",
+ "ses123",
+ "--target",
+ "mark-default-summary",
+ "--body",
+ "Review this summary.",
+ "--json",
+ ]
+ )
+ assert cli.cmd_show(args) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["ok"] is True
+ assert payload["event"]["type"] == "assistant.mark.created"
+ assert payload["event"]["message_id"]
+ assert payload["event"]["transcript_text"].startswith("[agent-mark:default] mark-default-summary")
+
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]
+ assert "Review this summary." in conn.execute(select(messages.c.content_text)).scalar_one()
+
+
+def test_show_mark_cli_posts_to_live_ui_when_running(monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+
+ captured = {}
+
+ class _Response:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return json.dumps(
+ {
+ "ok": True,
+ "event": {
+ "id": "show_evt_live",
+ "session_id": "ses123",
+ "scope_id": "scope123",
+ "type": "assistant.mark.created",
+ "actor": "assistant",
+ "scope": "default",
+ "anchor": {},
+ "payload": {},
+ "transcript_text": "[agent-mark:default] mark-default-summary\n\nReview this summary.",
+ "message_id": "msg_live",
+ "message": {"id": "msg_live"},
+ "created_at": "now",
+ },
+ }
+ ).encode("utf-8")
+
+ def _urlopen(request, timeout):
+ captured["url"] = request.full_url
+ captured["client"] = request.headers["X-vibe-show-client"]
+ captured["cli_token"] = request.headers["X-vibe-show-cli-token"]
+ captured["payload"] = json.loads(request.data.decode("utf-8"))
+ captured["timeout"] = timeout
+ return _Response()
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
+
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "mark",
+ "--session-id",
+ "ses123",
+ "--target",
+ "mark-default-summary",
+ "--body",
+ "Review this summary.",
+ "--json",
+ ]
+ )
+ assert cli.cmd_show(args) == 0
+
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["event"]["id"] == "show_evt_live"
+ assert captured["url"] == "http://127.0.0.1:5123/api/show/sessions/ses123/events"
+ assert captured["client"] == "cli"
+ assert captured["cli_token"] == show_cli_event_token()
+ assert captured["payload"]["type"] == "assistant.mark.created"
+ assert captured["timeout"] == 3
+
+
+def test_show_mark_cli_posts_to_configured_ui_host_when_running(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ config = _save_config()
+ config.remote_access.vibe_cloud.enabled = False
+ config.ui.setup_host = "100.97.103.112"
+ config.ui.setup_port = 15130
+ config.save()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": 123})
+
+ captured = {}
+
+ class _Response:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return None
+
+ def read(self):
+ return json.dumps({"ok": True, "event": {"id": "show_evt_live"}}).encode("utf-8")
+
+ def _urlopen(request, timeout):
+ captured["url"] = request.full_url
+ captured["timeout"] = timeout
+ return _Response()
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
+
+ event = cli._post_show_mark_to_live_ui(
+ "ses123",
+ {"type": "assistant.mark.created", "mark": {"target": "summary", "body": "body"}},
+ )
+
+ assert event == {"id": "show_evt_live"}
+ assert captured["url"] == "http://100.97.103.112:15130/api/show/sessions/ses123/events"
+ assert captured["timeout"] == 3
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
new file mode 100644
index 000000000..552c74586
--- /dev/null
+++ b/tests/test_show_session_events.py
@@ -0,0 +1,163 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+from core.show_session_events import ShowSessionEventError, ShowSessionEventStore
+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.settings_service import upsert_scope
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _seed_session(session_id: str = "ses_mark") -> str:
+ from storage import messages_service
+
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ last_active_at = "2000-01-01T00:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_show_events",
+ now=now,
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_" + session_id,
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=last_active_at,
+ )
+ )
+ return scope_id
+
+
+def test_show_event_store_records_assistant_mark_and_transcript_message(isolated_state):
+ _seed_session()
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ previous_active_at = conn.execute(
+ select(agent_sessions.c.last_active_at).where(agent_sessions.c.id == "ses_mark")
+ ).scalar_one()
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "mark-default-summary",
+ "body": "Review this summary again.",
+ },
+ "anchor": {
+ "selector": "[mark-default='summary']",
+ "text": "Quarterly summary",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ assert event["type"] == "assistant.mark.created"
+ assert event["scope_id"]
+ assert event["scope"] == "default"
+ assert event["message_id"]
+ assert event["message"]["id"] == event["message_id"]
+ assert "[agent-mark:default] mark-default-summary" in event["transcript_text"]
+ assert "Anchor: [mark-default='summary']" in event["transcript_text"]
+
+ with engine.connect() as conn:
+ event_row = conn.execute(select(show_session_events)).mappings().one()
+ message_row = conn.execute(select(messages).where(messages.c.id == event["message_id"])).mappings().one()
+ last_active_at = conn.execute(
+ select(agent_sessions.c.last_active_at).where(agent_sessions.c.id == "ses_mark")
+ ).scalar_one()
+
+ assert event_row["id"] == event["id"]
+ assert json.loads(event_row["payload_json"])["body"] == "Review this summary again."
+ assert message_row["author"] == "agent"
+ assert message_row["platform"] == "avibe"
+ assert message_row["native_message_id"] == f"show:{event['id']}"
+ assert "Review this summary again." in message_row["content_text"]
+ assert last_active_at != previous_active_at
+
+
+def test_show_event_store_rejects_unknown_session(isolated_state):
+ store = ShowSessionEventStore()
+ try:
+ with pytest.raises(ShowSessionEventError) as raised:
+ store.append(
+ "ses_missing",
+ {
+ "type": "assistant.mark.created",
+ "mark": {"target": "summary", "body": "body"},
+ },
+ )
+ finally:
+ store.close()
+
+ assert raised.value.code == "session_not_found"
+
+
+def test_show_event_store_uses_server_created_at_for_storage_cursor(monkeypatch, isolated_state):
+ _seed_session()
+ monkeypatch.setattr("core.show_session_events._utc_now_iso", lambda: "2026-05-30T10:00:00+00:00")
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "summary",
+ "body": "body",
+ "createdAt": "1999-01-01T00:00:00+00:00",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ assert event["created_at"] == "2026-05-30T10:00:00+00:00"
+ assert event["payload"]["createdAt"] == "1999-01-01T00:00:00+00:00"
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ event_row = conn.execute(select(show_session_events)).mappings().one()
+
+ assert event_row["created_at"] == "2026-05-30T10:00:00+00:00"
+
+
+def test_show_event_store_lists_after_cursor(isolated_state):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ first = store.append("ses_mark", {"type": "assistant.mark.created", "mark": {"target": "a", "body": "one"}})
+ second = store.append("ses_mark", {"type": "assistant.mark.created", "mark": {"target": "b", "body": "two"}})
+ page = store.list("ses_mark", after_id=first["id"])
+ finally:
+ store.close()
+
+ assert [event["id"] for event in page["events"]] == [second["id"]]
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 03aff1a5e..2e6a922bc 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 = "20260530_0008"
+HEAD_REVISION = "20260530_0009"
def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
@@ -39,6 +39,7 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "run_definitions" in tables
assert "agent_runs" in tables
assert "show_pages" in tables
+ assert "show_session_events" in tables
background_columns = {
row[1]
for row in conn.execute(
@@ -88,6 +89,95 @@ def test_run_migrations_stamps_existing_initial_schema(tmp_path: Path) -> None:
assert version == (HEAD_REVISION,)
+def test_run_migrations_runs_legacy_default_cleanup_when_stamping_existing_head_schema(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-default', 'default', 'default', 'Default Vibe Remote agent.', 'opencode',
+ null, null, null, 1, 'builtin', null, '{"builtin":true}', 'now', 'now'
+ );
+ insert into state_meta (key, value_json, updated_at)
+ values ('default_agent_name', '"default"', 'now');
+ """
+ )
+ conn.commit()
+ assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
+
+ run_migrations(db_path)
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ agents = dict(conn.execute("select name, backend from agents"))
+ default_pointer = conn.execute(
+ "select value_json from state_meta where key = 'default_agent_name'"
+ ).fetchone()[0]
+
+ assert version == (HEAD_REVISION,)
+ assert "default" not in agents
+ assert agents["opencode"] == "opencode"
+ assert json.loads(default_pointer) == "opencode"
+
+
+def test_run_migrations_stamps_pre_show_events_head_schema_at_0008_then_upgrades(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ conn.executescript(
+ """
+ insert into agents (
+ id, name, normalized_name, description, backend, model, reasoning_effort,
+ system_prompt, enabled, source, source_ref, metadata_json, created_at, updated_at
+ ) values (
+ 'agent-default', 'default', 'default', 'Default Vibe Remote agent.', 'opencode',
+ null, null, null, 1, 'builtin', null, '{"builtin":true}', 'now', 'now'
+ );
+ insert into state_meta (key, value_json, updated_at)
+ values ('default_agent_name', '"default"', 'now');
+ """
+ )
+ conn.execute("drop table show_session_events")
+ conn.execute("drop index if exists ix_show_session_events_session_created")
+ conn.execute("drop index if exists ix_show_session_events_type_created")
+ conn.commit()
+ assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
+ assert conn.execute("select name from sqlite_master where name = 'show_session_events'").fetchone() is None
+
+ run_migrations(db_path)
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ show_events = conn.execute("select name from sqlite_master where name = 'show_session_events'").fetchone()
+ background_tables = conn.execute("select count(*) from run_definitions").fetchone()
+ agents = dict(conn.execute("select name, backend from agents"))
+ default_pointer = conn.execute(
+ "select value_json from state_meta where key = 'default_agent_name'"
+ ).fetchone()[0]
+ assert version == (HEAD_REVISION,)
+ assert show_events == ("show_session_events",)
+ assert background_tables == (0,)
+ assert "default" not in agents
+ assert agents["opencode"] == "opencode"
+ assert json.loads(default_pointer) == "opencode"
+
+
def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
engine = create_sqlite_engine(db_path)
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 5ca0cb3a2..a39b0a5b9 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -6,7 +6,7 @@ from pathlib import Path
import pytest
from config import paths
-from core.show_pages import ShowPageStore, ensure_show_page_dir
+from core.show_pages import ShowPageStore, ensure_show_page_dir, show_cli_event_token
from core.show_runtime import ShowRuntimeManager, _runtime_platform_tag, _safe_extract_tar, set_show_runtime_manager_for_tests
from tests.test_ui_remote_access_auth import _mock_interface, _remote_peer, _save_config
from vibe import remote_access
@@ -63,6 +63,35 @@ def _create_show_page(session_id: str, visibility: str) -> str | None:
store.close()
+def _create_agent_session(session_id: str) -> None:
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = messages_service._utc_now_iso()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_show", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_" + session_id,
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -184,6 +213,383 @@ def test_private_show_page_proxies_runtime_api_methods(monkeypatch, tmp_path):
assert manager.calls[0][3] == b'{"ping":true}'
+def test_private_show_page_records_show_event(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ token = "session-write-token"
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: token)
+ published = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data)))
+
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "mark-default-summary",
+ "body": "Review this summary.",
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert payload["ok"] is True
+ assert payload["event"]["type"] == "assistant.mark.created"
+ assert payload["event"]["message_id"]
+ assert "Review this summary." in payload["event"]["transcript_text"]
+ assert [event_type for event_type, _data in published] == ["show.event", "message.new", "session.activity"]
+ assert published[1][1]["id"] == payload["event"]["message_id"]
+ assert published[2][1]["scope_id"] == payload["event"]["scope_id"]
+
+ events_response = app.test_client().get("/show/ses123/__show/events", base_url="http://127.0.0.1:5123")
+ assert events_response.status_code == 200
+ assert events_response.get_json()["events"][0]["id"] == payload["event"]["id"]
+
+
+def test_private_show_page_rejects_show_event_without_write_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+
+ client = app.test_client()
+ page_response = client.get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ assert page_response.status_code == 200
+
+ response = client.post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "mark-default-summary", "body": "Review this summary."},
+ },
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "show_event_write_forbidden"
+
+
+def test_private_show_page_rejects_other_session_write_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+
+ response = app.test_client().post(
+ "/show/ses123/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": "token-other-session",
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "mark-default-summary", "body": "Review this summary."},
+ },
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "show_event_write_forbidden"
+
+
+def test_private_show_page_sets_show_event_write_cookie(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ monkeypatch.setattr("vibe.ui_server.show_event_write_token", lambda session_id: f"token-{session_id}")
+
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ cookies = "\n".join(response.headers.getlist("set-cookie"))
+ assert "vibe_show_event_token=token-ses123" in cookies
+ assert "Path=/show/ses123/" in cookies
+ assert response.headers["content-security-policy"] == "frame-ancestors 'none'"
+
+
+def test_public_show_page_clears_show_event_write_cookie(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+
+ response = app.test_client().get(f"/p/{share_id}/", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ cookies = "\n".join(response.headers.getlist("set-cookie"))
+ assert "vibe_show_event_token=" in cookies
+ assert "Max-Age=0" in cookies
+
+
+def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+ from vibe.ui_server import _show_events_stream
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "private")
+ store = ShowSessionEventStore()
+ try:
+ for index in range(501):
+ store.append(
+ "ses123",
+ {
+ "id": f"show_evt_{index:03d}",
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": f"target-{index:03d}",
+ "body": f"body-{index:03d}",
+ "createdAt": f"2026-05-30T00:{index // 60:02d}:{index % 60:02d}+00:00",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ async def _collect_replay() -> str:
+ response = await _show_events_stream("ses123")
+ iterator = response.body_iterator.__aiter__()
+ chunks = []
+ try:
+ for _ in range(502):
+ chunk = await iterator.__anext__()
+ chunks.append(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk)
+ finally:
+ await iterator.aclose()
+ return "".join(chunks)
+
+ body = asyncio.run(_collect_replay())
+
+ assert body.startswith(": show events connected")
+ assert body.count("event: show.event") == 501
+ assert '"id": "show_evt_000"' in body
+ assert '"id": "show_evt_500"' in body
+
+
+def test_public_show_page_events_redact_internal_ids(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses123",
+ {
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "summary",
+ "body": "body",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ response = app.test_client().get(f"/p/{share_id}/__show/events", base_url="http://127.0.0.1:5123")
+
+ assert response.status_code == 200
+ public_event = response.get_json()["events"][0]
+ assert public_event["id"] == event["id"]
+ assert public_event["type"] == "assistant.mark.created"
+ assert public_event["payload"]["body"] == "body"
+ assert "session_id" not in public_event
+ assert "scope_id" not in public_event
+ assert "message_id" not in public_event
+ assert "message" not in public_event
+
+
+def test_public_show_events_stream_redacts_internal_ids(monkeypatch, tmp_path):
+ from core.show_session_events import ShowSessionEventStore
+ from vibe.ui_server import _show_events_stream
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ _create_show_page("ses123", "public")
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses123",
+ {
+ "id": "show_evt_public",
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "summary",
+ "body": "body",
+ },
+ },
+ )
+ finally:
+ store.close()
+
+ async def _collect_replay() -> str:
+ response = await _show_events_stream("ses123", public=True)
+ iterator = response.body_iterator.__aiter__()
+ chunks = []
+ try:
+ for _ in range(2):
+ chunk = await iterator.__anext__()
+ chunks.append(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk)
+ finally:
+ await iterator.aclose()
+ return "".join(chunks)
+
+ body = asyncio.run(_collect_replay())
+
+ assert f'"id": "{event["id"]}"' in body
+ assert '"session_id"' not in body
+ assert '"scope_id"' not in body
+ assert '"message_id"' not in body
+ assert '"message"' not in body
+
+
+def test_cli_show_event_ingress_records_and_publishes(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ published = []
+ monkeypatch.setattr("vibe.sse_broker.broker.publish", lambda event_type, data: published.append((event_type, data)))
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ "X-Vibe-Show-Cli-Token": show_cli_event_token(),
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {
+ "target": "mark-default-summary",
+ "body": "Review this summary.",
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ payload = response.get_json()
+ assert payload["event"]["type"] == "assistant.mark.created"
+ assert payload["event"]["message_id"]
+ assert [event_type for event_type, _data in published] == ["show.event", "message.new", "session.activity"]
+
+
+def test_cli_show_event_ingress_requires_cli_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "mark-default-summary", "body": "Review this summary."},
+ },
+ )
+
+ assert response.status_code == 403
+
+
+def test_cli_show_event_ingress_allows_configured_host_with_cli_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.enabled = False
+ config.ui.setup_host = "10.1.2.3"
+ config.save()
+ _create_agent_session("ses123")
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/events",
+ base_url="http://10.1.2.3:5123",
+ environ_base={"REMOTE_ADDR": "10.50.0.5"},
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ "X-Vibe-Show-Cli-Token": show_cli_event_token(),
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "mark-default-summary", "body": "Review this summary."},
+ },
+ )
+
+ assert response.status_code == 201
+
+
+def test_cli_show_event_ingress_rejects_configured_host_without_cli_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.enabled = False
+ config.ui.setup_host = "10.1.2.3"
+ config.save()
+ _create_agent_session("ses123")
+
+ response = app.test_client().post(
+ "/api/show/sessions/ses123/events",
+ base_url="http://10.1.2.3:5123",
+ environ_base={"REMOTE_ADDR": "10.50.0.5"},
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "mark-default-summary", "body": "Review this summary."},
+ },
+ )
+
+ assert response.status_code == 403
+
+
+def test_public_show_page_events_are_read_only(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+
+ response = app.test_client().post(
+ f"/p/{share_id}/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers={
+ "Origin": "http://127.0.0.1:5123",
+ "Content-Type": "application/json",
+ },
+ json={
+ "type": "assistant.mark.created",
+ "mark": {"target": "summary", "body": "body"},
+ },
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "public_show_events_read_only"
+
+
def test_private_show_page_api_mutation_rejects_missing_origin(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/vibe/cli.py b/vibe/cli.py
index dabdbd3a0..4ed27cfed 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -11,6 +11,8 @@ import signal
import subprocess
import sys
import time
+import urllib.error
+import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
from textwrap import dedent
@@ -477,6 +479,7 @@ def _show_examples_text() -> str:
path Create or resolve the local workspace.
status Inspect local path, visibility, active URL, and share state.
update Switch visibility, rotate public share links, or take the page offline.
+ mark Add an assistant mark event to the session.
Visibility:
private Authenticated Web UI URL under /show/<session-id>/.
@@ -490,12 +493,14 @@ def _show_examples_text() -> str:
vibe show status --session-id sesk8m4q2p7x --json
vibe show update --session-id sesk8m4q2p7x --visibility public
vibe show update --session-id sesk8m4q2p7x --visibility offline
+ vibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."
More:
vibe show list --help
vibe show path --help
vibe show status --help
vibe show update --help
+ vibe show mark --help
"""
)
@@ -549,6 +554,22 @@ def _show_update_examples_text() -> str:
)
+def _show_mark_examples_text() -> str:
+ return dedent(
+ """\
+ Add an assistant-authored mark event to the session's Show Page event stream.
+ The mark is also projected into the session transcript as an assistant message.
+
+ Target should be a short mark id or selector understood by the Show Page, usually
+ a value produced by @avibe/show-sdk's mark helpers.
+
+ Examples:
+ vibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."
+ vibe show mark --session-id sesk8m4q2p7x --scope default --target summary --body-file ./comment.txt --json
+ """
+ )
+
+
def _print_json(payload: dict) -> None:
print(json.dumps(payload, indent=2))
@@ -4159,6 +4180,125 @@ def cmd_show_update(args):
store.close()
+def _read_cli_text_argument(*, value: str | None, file_path: str | None, field_name: str) -> str:
+ if file_path:
+ source = sys.stdin.read() if file_path == "-" else Path(file_path).read_text(encoding="utf-8")
+ text = source.strip()
+ else:
+ text = (value or "").strip()
+ if not text:
+ raise TaskCliError(
+ f"{field_name} is required",
+ code="invalid_arguments",
+ help_command="vibe show mark --help",
+ )
+ return text
+
+
+def _ui_show_events_host(config: V2Config) -> str:
+ host = (getattr(config.ui, "setup_host", "") or "").strip() or "127.0.0.1"
+ if host in {"0.0.0.0", "*"}:
+ return "127.0.0.1"
+ if host == "::":
+ return "[::1]"
+ if ":" in host and not (host.startswith("[") and host.endswith("]")):
+ return f"[{host}]"
+ return host
+
+
+def _local_show_events_url(session_id: str) -> str | None:
+ from urllib.parse import quote
+
+ try:
+ config = V2Config.load()
+ except Exception:
+ return None
+ status = runtime.read_status()
+ port = getattr(config.ui, "setup_port", None)
+ if not status.get("ui_pid") or not port:
+ return None
+ return f"http://{_ui_show_events_host(config)}:{int(port)}/api/show/sessions/{quote(session_id, safe='')}/events"
+
+
+def _post_show_mark_to_live_ui(session_id: str, payload: dict) -> dict | None:
+ from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_token
+
+ url = _local_show_events_url(session_id)
+ if not url:
+ return None
+ body = json.dumps(payload).encode("utf-8")
+ request = urllib.request.Request(
+ url,
+ data=body,
+ method="POST",
+ headers={
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Client": "cli",
+ SHOW_CLI_EVENT_TOKEN_HEADER: show_cli_event_token(),
+ },
+ )
+ try:
+ with urllib.request.urlopen(request, timeout=3) as response:
+ parsed = json.loads(response.read().decode("utf-8"))
+ except (OSError, TimeoutError, urllib.error.URLError, urllib.error.HTTPError, json.JSONDecodeError, ValueError):
+ return None
+ return parsed.get("event") if isinstance(parsed, dict) and parsed.get("ok") is True else None
+
+
+def cmd_show_mark(args):
+ from core.show_pages import ShowPageStore
+ from core.show_session_events import ShowSessionEventStore
+
+ page_store = ShowPageStore()
+ event_store = None
+ try:
+ page = page_store.ensure(args.session_id)
+ target = _read_cli_text_argument(value=args.target, file_path=None, field_name="--target")
+ body = _read_cli_text_argument(value=args.body, file_path=args.body_file, field_name="--body")
+ payload = {
+ "type": "assistant.mark.created",
+ "mark": {
+ "scope": args.scope or "default",
+ "target": target,
+ "body": body,
+ },
+ }
+ if args.anchor_selector:
+ payload["anchor"] = {"selector": args.anchor_selector}
+ if args.anchor_text:
+ payload["anchor"]["text"] = args.anchor_text
+ event = _post_show_mark_to_live_ui(args.session_id, payload)
+ if event is None:
+ event_store = ShowSessionEventStore()
+ event = event_store.append(args.session_id, payload)
+ result = _show_page_result(
+ page,
+ message="Assistant mark recorded.",
+ extra={
+ "event": event,
+ "event_id": event["id"],
+ "message_id": event.get("message_id"),
+ },
+ )
+ if getattr(args, "json", False):
+ _print_json(result)
+ else:
+ _print_show_page_result(result)
+ print("")
+ print("Mark:")
+ print(f" Event: {event['id']}")
+ print(f" Message: {event.get('message_id') or 'none'}")
+ print(f" Target: {target}")
+ return 0
+ except Exception as exc:
+ _print_show_page_error(exc)
+ return 1
+ finally:
+ page_store.close()
+ if event_store is not None:
+ event_store.close()
+
+
def cmd_show(args):
if args.show_command is None:
args.show_help_parser.print_help()
@@ -4171,6 +4311,8 @@ def cmd_show(args):
return cmd_show_status(args)
if args.show_command == "update":
return cmd_show_update(args)
+ if args.show_command == "mark":
+ return cmd_show_mark(args)
raise TaskCliError(
"show command is required",
code="invalid_arguments",
@@ -4614,7 +4756,7 @@ def build_parser():
error_hint="Run one of the show subcommands below. Start with: vibe show path --session-id <session-id>",
)
show_parser.set_defaults(show_help_parser=show_parser)
- show_subparsers = show_parser.add_subparsers(dest="show_command", metavar="{list,path,status,update}")
+ show_subparsers = show_parser.add_subparsers(dest="show_command", metavar="{list,path,status,update,mark}")
show_subparsers.required = False
show_list_parser = show_subparsers.add_parser(
@@ -4705,6 +4847,25 @@ def build_parser():
)
show_update_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+ show_mark_parser = show_subparsers.add_parser(
+ "mark",
+ help="Record an assistant mark event for a Show Page",
+ description="Add an assistant-authored mark event to the Show Page event stream and session transcript.",
+ epilog=_show_mark_examples_text(),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe show mark --help",
+ error_hint="Pass --session-id, --target, and --body or --body-file.",
+ )
+ show_mark_parser.add_argument("--session-id", required=True, help="Agent Session ID for the Show Page.")
+ show_mark_parser.add_argument("--scope", default="default", help='Mark scope. Defaults to "default".')
+ show_mark_parser.add_argument("--target", required=True, help="Target mark id or selector.")
+ mark_body_group = show_mark_parser.add_mutually_exclusive_group(required=True)
+ mark_body_group.add_argument("--body", help="Assistant mark body text.")
+ mark_body_group.add_argument("--body-file", help="Read assistant mark body from a UTF-8 file, or '-' for stdin.")
+ show_mark_parser.add_argument("--anchor-selector", help="Optional DOM selector for the anchored element.")
+ show_mark_parser.add_argument("--anchor-text", help="Optional selected or summarized anchor text.")
+ show_mark_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+
task_parser = subparsers.add_parser(
"task",
help="Manage scheduled tasks",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index a3b72e0c2..60713b88a 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -29,6 +29,13 @@ from vibe.ui_compat import CompatApp, Response, TEST_REMOTE_ADDR_HEADER, g, json
from config import paths
from config.v2_config import CONFIG_LOCK, V2Config
+from core.show_pages import (
+ SHOW_CLI_EVENT_TOKEN_HEADER,
+ SHOW_EVENT_WRITE_TOKEN_COOKIE,
+ SHOW_EVENT_WRITE_TOKEN_HEADER,
+ show_cli_event_token,
+ show_event_write_token,
+)
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
@@ -193,14 +200,29 @@ def _current_origin() -> str:
def _is_mutation_guard_exempt() -> bool:
if request.path in {"/auth/callback"}:
return True
+ if _is_cli_show_event_request():
+ return True
return (
request.path == "/e2e/simulate-interaction"
and os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes")
)
+def _is_cli_show_event_request() -> bool:
+ token = request.headers.get(SHOW_CLI_EVENT_TOKEN_HEADER)
+ return (
+ request.method == "POST"
+ and re.fullmatch(r"/api/show/sessions/[^/]+/events", request.path or "") is not None
+ and request.headers.get("X-Vibe-Show-Client") == "cli"
+ and bool(token)
+ and hmac.compare_digest(token, show_cli_event_token())
+ )
+
+
def _is_show_api_mutation() -> bool:
- return (request.path.startswith("/show/") or request.path.startswith("/p/")) and "/api/" in request.path
+ if not (request.path.startswith("/show/") or request.path.startswith("/p/")):
+ return False
+ return "/api/" in request.path or "/__show/" in request.path
def _ensure_csrf_cookie(response: Response) -> Response:
@@ -3676,7 +3698,7 @@ def _show_page_runtime_unavailable_response():
def _is_show_api_asset(asset_path: str) -> bool:
relative = (asset_path or "").strip("/")
- return relative == "api" or relative.startswith("api/")
+ return relative == "api" or relative.startswith("api/") or relative == "__show" or relative.startswith("__show/")
def _show_page_file_response(root: Path, asset_path: str):
@@ -3696,6 +3718,181 @@ def _show_page_file_response(root: Path, asset_path: str):
return response
+def _show_session_event_error_response(exc: Exception):
+ code = getattr(exc, "code", "show_session_event_failed")
+ status = 404 if code == "session_not_found" else 400
+ return jsonify({"ok": False, "code": code, "error": str(exc)}), status
+
+
+def _show_session_event_store():
+ from core.show_session_events import ShowSessionEventStore
+
+ return ShowSessionEventStore()
+
+
+def _show_events_payload_from_request() -> dict[str, Any]:
+ payload = request.json
+ return payload if isinstance(payload, dict) else {}
+
+
+def _show_event_write_authorized(session_id: str) -> bool:
+ token = request.headers.get(SHOW_EVENT_WRITE_TOKEN_HEADER)
+ if not token:
+ return False
+ try:
+ expected = show_event_write_token(session_id)
+ except Exception:
+ return False
+ return hmac.compare_digest(token, expected)
+
+
+def _show_event_response_from_payload(session_id: str, payload: dict[str, Any]):
+ store = _show_session_event_store()
+ try:
+ event_payload = store.append(session_id, payload)
+ except Exception as exc:
+ return _show_session_event_error_response(exc)
+ finally:
+ store.close()
+
+ _publish_show_session_event(event_payload)
+ return jsonify({"ok": True, "event": event_payload}), 201
+
+
+def _publish_show_session_event(event_payload: dict[str, Any]) -> None:
+ from vibe.sse_broker import broker
+
+ broker.publish("show.event", event_payload)
+ message = event_payload.get("message")
+ if isinstance(message, dict):
+ broker.publish("message.new", message)
+ broker.publish(
+ "session.activity",
+ {
+ "session_id": event_payload.get("session_id"),
+ "scope_id": event_payload.get("scope_id"),
+ "event": "show_event",
+ },
+ )
+
+
+def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
+ if not public:
+ return event_payload
+ return {
+ key: value
+ for key, value in event_payload.items()
+ if key not in {"session_id", "scope_id", "message_id", "message"}
+ }
+
+
+def _show_events_list_payload(payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
+ if not public:
+ return payload
+ return {
+ **payload,
+ "events": [
+ _show_event_response_payload(event_payload, public=True)
+ 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):
+ import asyncio
+
+ from fastapi.responses import StreamingResponse
+
+ from vibe.sse_broker import broker
+
+ def _event_visible(event_payload: dict[str, Any]) -> bool:
+ return event_payload.get("session_id") == session_id
+
+ async def generate():
+ sub_id, queue = broker.subscribe()
+ replayed_ids: set[str] = set()
+ try:
+ store = _show_session_event_store()
+ try:
+ cursor = after_id
+ yield ": show events connected\n\n"
+ while True:
+ batch = store.list(session_id, after_id=cursor, limit=500)
+ events = batch["events"]
+ if not events:
+ break
+ 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))
+ cursor = batch.get("next_after_id")
+ if not cursor:
+ break
+ finally:
+ store.close()
+
+ while True:
+ try:
+ event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ if event_type != "show.event":
+ continue
+ decoded = json.loads(payload)
+ event_payload = decoded.get("data") if isinstance(decoded, dict) else None
+ if isinstance(event_payload, dict) and _event_visible(event_payload):
+ event_id = event_payload.get("id")
+ if isinstance(event_id, str) and event_id in replayed_ids:
+ continue
+ if isinstance(event_id, str):
+ replayed_ids.add(event_id)
+ yield _sse_frame("show.event", _show_event_response_payload(event_payload, public=public))
+ except asyncio.TimeoutError:
+ yield ": ping\n\n"
+ except asyncio.CancelledError:
+ raise
+ finally:
+ broker.unsubscribe(sub_id)
+
+ def _sse_frame(event_type: str, data: Any) -> str:
+ return f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
+
+ return StreamingResponse(
+ generate(),
+ media_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+
+async def _show_events_response(session_id: str, *, public: bool = False):
+ 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 None, public=public)
+ store = _show_session_event_store()
+ try:
+ try:
+ limit = int(request.args.get("limit") or 100)
+ 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))
+ finally:
+ store.close()
+
+ if request.method != "POST":
+ return jsonify({"ok": False, "code": "method_not_allowed"}), 405
+ if not _show_event_write_authorized(session_id):
+ return jsonify({"ok": False, "code": "show_event_write_forbidden"}), 403
+
+ return _show_event_response_from_payload(session_id, _show_events_payload_from_request())
+
+
[email protected]("/api/show/sessions/<session_id>/events", methods=["POST"])
+def show_session_events_create(session_id: str):
+ if not _is_cli_show_event_request():
+ return jsonify({"ok": False, "code": "forbidden"}), 403
+ return _show_event_response_from_payload(session_id, _show_events_payload_from_request())
+
+
async def _show_page_runtime_response(
session_id: str,
asset_path: str,
@@ -3756,6 +3953,22 @@ def _rewrite_show_runtime_location(session_id: str, location: str, *, external_p
return urlunsplit(("", "", public_path, parsed.query, parsed.fragment))
+def _with_show_event_write_cookie(response: Response, session_id: str, *, enabled: bool) -> Response:
+ if enabled:
+ response.headers["Content-Security-Policy"] = "frame-ancestors 'none'"
+ response.set_cookie(
+ SHOW_EVENT_WRITE_TOKEN_COOKIE,
+ show_event_write_token(session_id),
+ httponly=False,
+ secure=request.is_secure,
+ samesite="Strict",
+ path=f"/show/{quote(session_id, safe='')}/",
+ )
+ else:
+ response.delete_cookie(SHOW_EVENT_WRITE_TOKEN_COOKIE, path=f"/show/{quote(session_id, safe='')}/")
+ return response
+
+
def stop_show_runtime_on_shutdown() -> None:
from core.show_runtime import stop_show_runtime_manager
@@ -3803,15 +4016,22 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_offline_response()
if page.visibility != "private":
return _show_page_not_found_response()
+ if asset_path.strip("/") in {"__show/events", "__events"}:
+ return await _show_events_response(page.session_id)
+ response = None
if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):
try:
starlette_request = request._request
- return await _show_page_runtime_response(page.session_id, asset_path, starlette_request)
+ response = await _show_page_runtime_response(page.session_id, asset_path, starlette_request)
except Exception:
if _is_show_api_asset(asset_path):
return _show_page_runtime_unavailable_response()
logger.debug("Show runtime unavailable; serving static Show Page", exc_info=True)
- return _show_page_file_response(show_page_dir(page.session_id), asset_path)
+ if response is None:
+ response = _show_page_file_response(show_page_dir(page.session_id), asset_path)
+ if request.method in {"GET", "HEAD"}:
+ return _with_show_event_write_cookie(response, page.session_id, enabled=True)
+ return response
finally:
store.close()
@@ -3853,10 +4073,15 @@ async def serve_public_show_page(share_id, asset_path):
return _show_page_offline_response()
if page.visibility != "public":
return _show_page_not_found_response()
+ if asset_path.strip("/") in {"__show/events", "__events"}:
+ if request.method != "GET":
+ return jsonify({"ok": False, "code": "public_show_events_read_only"}), 403
+ return await _show_events_response(page.session_id, public=True)
+ response = None
if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):
try:
starlette_request = request._request
- return await _show_page_runtime_response(
+ response = await _show_page_runtime_response(
page.session_id,
asset_path,
starlette_request,
@@ -3866,7 +4091,11 @@ async def serve_public_show_page(share_id, asset_path):
if _is_show_api_asset(asset_path):
return _show_page_runtime_unavailable_response()
logger.debug("Show runtime unavailable; serving static public Show Page", exc_info=True)
- return _show_page_file_response(show_page_dir(page.session_id), asset_path)
+ if response is None:
+ response = _show_page_file_response(show_page_dir(page.session_id), asset_path)
+ if request.method in {"GET", "HEAD"}:
+ return _with_show_event_write_cookie(response, page.session_id, enabled=False)
+ return response
finally:
store.close()