Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show): support annotation layer events (#360)
Call Whitedc54463aa782
diff --git a/core/show_session_events.py b/core/show_session_events.pyindex 45bb87a36..8b161ce33 100644--- a/core/show_session_events.py+++ b/core/show_session_events.py@@ -17,7 +17,25 @@ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_from storage.models import agent_sessions, show_session_eventsDEFAULT_MARK_SCOPE = "default"-SUPPORTED_EVENT_TYPES = {"assistant.mark.created", "human.intent.submitted", "human.annotation.created"}+SUPPORTED_EVENT_TYPES = {+ "assistant.mark.created",+ "assistant.mark.updated",+ "assistant.mark.resolved",+ "assistant.page.updated",+ "human.intent.submitted",+ "human.annotation.created",+ "human.annotation.updated",+ "human.annotation.resolved",+ "human.annotation.dismissed",+ "system.runtime.status",+ "system.runtime.error",+}+ANNOTATION_EVENT_TYPES = {+ "human.annotation.created",+ "human.annotation.updated",+ "human.annotation.resolved",+ "human.annotation.dismissed",+}class ShowSessionEventError(ValueError):@@ -46,7 +64,7 @@ class ShowSessionEventStore: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"))+ anchor = _normalize_json_object(payload.get("anchor") or event_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)@@ -81,7 +99,7 @@ class ShowSessionEventStore:scope_id=session["scope_id"],session_id=session_id,platform="avibe",- author="agent" if actor == "assistant" else "user",+ author="agent" if actor in {"assistant", "system"} else "user",text=transcript_text,content={"text": transcript_text, "show_event_type": event_type},metadata={@@ -148,23 +166,57 @@ def _validate_event_type(raw: Any) -> str:def _actor_for_event(event_type: str) -> str:- return "assistant" if event_type.startswith("assistant.") else "human"+ if event_type.startswith("assistant."):+ return "assistant"+ if event_type.startswith("system."):+ return "system"+ return "human"def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[str, Any]:- if event_type == "assistant.mark.created":+ if event_type.startswith("assistant.mark."):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")+ created_at = _text_or_none(mark.get("createdAt")) or _utc_now_iso()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(),+ "status": "resolved" if event_type == "assistant.mark.resolved" else _text_or_none(mark.get("status")) or "active",+ "createdAt": created_at,+ "updatedAt": _text_or_none(mark.get("updatedAt")) or created_at,+ "resolvedAt": _text_or_none(mark.get("resolvedAt")) if event_type != "assistant.mark.resolved" else _text_or_none(mark.get("resolvedAt")) or _utc_now_iso(),}- return _normalize_json_object(payload.get("payload") or payload)+ if event_type == "human.intent.submitted":+ intent_payload = _normalize_json_object(payload.get("payload") or payload)+ created_at = _text_or_none(intent_payload.get("createdAt")) or _utc_now_iso()+ normalized = dict(intent_payload)+ normalized.setdefault("id", _new_id("intent"))+ normalized["scope"] = _text_or_none(normalized.get("scope")) or DEFAULT_MARK_SCOPE+ normalized["createdAt"] = created_at+ return normalized+ if event_type in ANNOTATION_EVENT_TYPES:+ annotation = _normalize_json_object(payload.get("annotation") or payload.get("payload") or payload)+ created_at = _text_or_none(annotation.get("createdAt")) or _utc_now_iso()+ normalized = dict(annotation)+ normalized.setdefault("id", _new_id("annotation"))+ normalized["scope"] = _text_or_none(normalized.get("scope")) or DEFAULT_MARK_SCOPE+ normalized["status"] = _annotation_status_for_event(event_type, _text_or_none(normalized.get("status")))+ normalized["createdAt"] = created_at+ normalized["updatedAt"] = _text_or_none(normalized.get("updatedAt")) or created_at+ if event_type == "human.annotation.resolved":+ normalized["resolvedAt"] = _text_or_none(normalized.get("resolvedAt")) or _utc_now_iso()+ return normalized+ normalized = _normalize_json_object(payload.get("payload") or payload)+ if not normalized:+ normalized = {}+ normalized.setdefault("id", _new_id("runtime" if event_type.startswith("system.") else "page"))+ normalized.setdefault("createdAt", _utc_now_iso())+ normalized.setdefault("scope", DEFAULT_MARK_SCOPE)+ return normalizeddef _normalize_json_object(raw: Any) -> dict[str, Any]:@@ -172,23 +224,20 @@ def _normalize_json_object(raw: Any) -> dict[str, Any]:def _event_scope(event_type: str, payload: dict[str, Any]) -> str:- if event_type == "assistant.mark.created":+ if event_type.startswith("assistant.mark."):return _text_or_none(payload.get("scope")) or DEFAULT_MARK_SCOPEreturn _text_or_none(payload.get("scope")) or DEFAULT_MARK_SCOPEdef _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")- )+ return _text_or_none(original_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":+ if event_type.startswith("assistant.mark."):+ action = event_type.split(".")[-1]lines = [- f"[agent-mark:{payload.get('scope') or DEFAULT_MARK_SCOPE}] {payload.get('target')}",+ f"[agent-mark:{payload.get('scope') or DEFAULT_MARK_SCOPE}:{action}] {payload.get('target')}","",str(payload.get("body") or "").strip(),]@@ -200,9 +249,38 @@ def _format_transcript_text(event_type: str, payload: dict[str, Any], anchor: dilines.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)}"+ if event_type == "human.intent.submitted":+ text = _text_or_none(payload.get("text") or payload.get("comment") or payload.get("value"))+ label = _text_or_none(payload.get("intent") or payload.get("component")) or "intent"+ return f"[show-intent:{payload.get('scope') or DEFAULT_MARK_SCOPE}] {label}\n\n{text or _json_dumps(payload)}"++ if event_type in ANNOTATION_EVENT_TYPES:+ action = event_type.split(".")[-1]+ text = _text_or_none(payload.get("text") or payload.get("comment"))+ label = _text_or_none(payload.get("intent")) or "comment"+ lines = [f"[show-annotation:{payload.get('scope') or DEFAULT_MARK_SCOPE}:{action}] {label}"]+ if text:+ lines.extend(["", text])+ quote = _text_or_none(anchor.get("textQuote") or anchor.get("text"))+ if quote:+ lines.extend(["", f"Quote: {quote}"])+ selector = _text_or_none(anchor.get("selector"))+ if selector:+ lines.append(f"Anchor: {selector}")+ return "\n".join(lines)++ if event_type == "assistant.page.updated":+ summary = _text_or_none(payload.get("summary") or payload.get("text") or payload.get("body"))+ return f"[show-page-updated] {summary or _json_dumps(payload)}"++ if event_type == "system.runtime.error":+ text = _text_or_none(payload.get("error") or payload.get("message") or payload.get("status"))+ return f"[show-runtime-error] {text or _json_dumps(payload)}"++ if event_type == "system.runtime.status":+ return ""++ return _json_dumps(payload)def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:@@ -234,6 +312,14 @@ def _text_or_none(raw: Any) -> str | None:return value or None+def _annotation_status_for_event(event_type: str, requested: str | None) -> str:+ if event_type == "human.annotation.resolved":+ return "resolved"+ if event_type == "human.annotation.dismissed":+ return "dismissed"+ return requested or "pending"++def _utc_now_iso() -> str:return datetime.now(timezone.utc).isoformat()diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex 921f888bf..348b8c095 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -17,7 +17,7 @@ def test_show_without_subcommand_prints_help(capsys):assert cli.cmd_show(args) == 0captured = 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,mark} ..." in captured.out+ assert "usage: vibe show [-h] {list,path,status,update,mark,event} ..." in captured.outassert "vibe show list" in captured.outassert "vibe show path --session-id sesk8m4q2p7x" in captured.out@@ -461,7 +461,7 @@ def test_show_mark_cli_records_event_and_message(monkeypatch, tmp_path, capsys):assert payload["ok"] is Trueassert payload["event"]["type"] == "assistant.mark.created"assert payload["event"]["message_id"]- assert payload["event"]["transcript_text"].startswith("[agent-mark:default] mark-default-summary")+ assert payload["event"]["transcript_text"].startswith("[agent-mark:default:created] mark-default-summary")with engine.connect() as conn:assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]@@ -538,6 +538,244 @@ def test_show_mark_cli_posts_to_live_ui_when_running(monkeypatch, tmp_path, capsassert captured["timeout"] == 3+def test_show_event_cli_records_generic_event(monkeypatch, tmp_path, capsys):+ from sqlalchemy import select++ 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, messages, show_session_events+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _save_config()+ 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",+ "event",+ "--session-id",+ "ses123",+ "--event-json",+ json.dumps(+ {+ "type": "human.annotation.created",+ "annotation": {+ "intent": "question",+ "comment": "Clarify this.",+ "anchor": {"selector": "[mark-default='summary']", "textQuote": "summary"},+ },+ }+ ),+ "--json",+ ]+ )+ assert cli.cmd_show(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert payload["ok"] is True+ assert payload["event"]["type"] == "human.annotation.created"+ assert "Clarify this." in payload["event"]["transcript_text"]++ with engine.connect() as conn:+ assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]+ assert "Clarify this." in conn.execute(select(messages.c.content_text)).scalar_one()+++def test_show_event_cli_dispatch_flag_updates_annotation_payload(monkeypatch, tmp_path):+ 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": "human.annotation.created",+ "actor": "human",+ "scope": "default",+ "anchor": {},+ "payload": {"dispatch": True},+ "transcript_text": "[show-annotation:default:created] comment",+ "message_id": "msg_live",+ "message": {"id": "msg_live"},+ "created_at": "now",+ },+ }+ ).encode("utf-8")++ def _urlopen(request, timeout):+ captured["payload"] = json.loads(request.data.decode("utf-8"))+ return _Response()++ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)++ args = cli.build_parser().parse_args(+ [+ "show",+ "event",+ "--session-id",+ "ses123",+ "--event-json",+ json.dumps({"type": "human.annotation.created", "annotation": {"comment": "Clarify this."}}),+ "--dispatch",+ "--json",+ ]+ )+ assert cli.cmd_show(args) == 0++ assert captured["payload"]["annotation"]["dispatch"] is True+ assert "payload" not in captured["payload"]+++def test_show_event_cli_dispatch_preserves_top_level_payload(monkeypatch, tmp_path):+ 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"}}).encode("utf-8")++ def _urlopen(request, timeout):+ captured["payload"] = json.loads(request.data.decode("utf-8"))+ return _Response()++ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)++ args = cli.build_parser().parse_args(+ [+ "show",+ "event",+ "--session-id",+ "ses123",+ "--type",+ "human.intent.submitted",+ "--event-json",+ json.dumps({"comment": "Pick B", "intent": "choose"}),+ "--dispatch",+ "--json",+ ]+ )+ assert cli.cmd_show(args) == 0++ assert captured["payload"]["payload"]["comment"] == "Pick B"+ assert captured["payload"]["payload"]["intent"] == "choose"+ assert captured["payload"]["payload"]["dispatch"] is True+ assert captured["payload"]["type"] == "human.intent.submitted"+++def test_show_event_cli_dispatch_fallback_records_and_dispatches(monkeypatch, tmp_path, capsys):+ from sqlalchemy import select++ 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, show_session_events+ from storage.settings_service import upsert_scope++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _save_config()+ 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,+ )+ )++ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": None})+ dispatched = []++ async def _fake_run_dispatch(event):+ dispatched.append(event)++ monkeypatch.setattr("vibe.ui_server._run_show_event_dispatch", _fake_run_dispatch)++ args = cli.build_parser().parse_args(+ [+ "show",+ "event",+ "--session-id",+ "ses123",+ "--type",+ "human.intent.submitted",+ "--event-json",+ json.dumps({"comment": "Pick B"}),+ "--dispatch",+ "--json",+ ]+ )+ assert cli.cmd_show(args) == 0++ payload = json.loads(capsys.readouterr().out)+ assert payload["event"]["payload"]["comment"] == "Pick B"+ assert payload["event"]["payload"]["dispatch"] is True+ assert dispatched and dispatched[0]["id"] == payload["event"]["id"]+ with engine.connect() as conn:+ assert conn.execute(select(show_session_events.c.id)).scalar_one() == payload["event"]["id"]++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()diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.pyindex 552c74586..24be33319 100644--- a/tests/test_show_session_events.py+++ b/tests/test_show_session_events.py@@ -84,7 +84,7 @@ def test_show_event_store_records_assistant_mark_and_transcript_message(isolatedassert 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 "[agent-mark:default:created] mark-default-summary" in event["transcript_text"]assert "Anchor: [mark-default='summary']" in event["transcript_text"]with engine.connect() as conn:@@ -103,6 +103,154 @@ def test_show_event_store_records_assistant_mark_and_transcript_message(isolatedassert last_active_at != previous_active_at+def test_show_event_store_records_human_annotation_with_anchor_context(isolated_state):+ _seed_session()++ store = ShowSessionEventStore()+ try:+ event = store.append(+ "ses_mark",+ {+ "type": "human.annotation.created",+ "annotation": {+ "intent": "question",+ "severity": "important",+ "comment": "Clarify this claim.",+ "anchor": {+ "kind": "text-range",+ "selector": "[mark-default='summary']",+ "textQuote": "Quarterly summary",+ },+ },+ },+ )+ finally:+ store.close()++ assert event["type"] == "human.annotation.created"+ assert event["actor"] == "human"+ assert event["scope"] == "default"+ assert event["payload"]["status"] == "pending"+ assert event["message_id"]+ assert "[show-annotation:default:created] question" in event["transcript_text"]+ assert "Clarify this claim." in event["transcript_text"]+ assert "Quote: Quarterly summary" in event["transcript_text"]++ engine = create_sqlite_engine()+ with engine.connect() as conn:+ message_row = conn.execute(select(messages).where(messages.c.id == event["message_id"])).mappings().one()++ assert message_row["author"] == "user"+++def test_show_event_store_records_annotation_resolution(isolated_state):+ _seed_session()++ store = ShowSessionEventStore()+ try:+ event = store.append(+ "ses_mark",+ {+ "type": "human.annotation.resolved",+ "annotation": {+ "id": "annotation_1",+ "comment": "This is resolved.",+ },+ },+ )+ finally:+ store.close()++ assert event["payload"]["id"] == "annotation_1"+ assert event["payload"]["status"] == "resolved"+ assert "resolved" in event["transcript_text"]+++def test_show_event_store_keeps_object_ids_separate_from_event_ids(isolated_state):+ _seed_session()++ store = ShowSessionEventStore()+ try:+ created = store.append(+ "ses_mark",+ {+ "type": "assistant.mark.created",+ "mark": {+ "id": "mark_1",+ "target": "summary",+ "body": "Created.",+ },+ },+ )+ resolved = store.append(+ "ses_mark",+ {+ "type": "assistant.mark.resolved",+ "mark": {+ "id": "mark_1",+ "target": "summary",+ "body": "Resolved.",+ },+ },+ )+ finally:+ store.close()++ assert created["payload"]["id"] == "mark_1"+ assert resolved["payload"]["id"] == "mark_1"+ assert created["id"] != "mark_1"+ assert resolved["id"] != "mark_1"+ assert created["id"] != resolved["id"]+++def test_show_event_store_records_intent_dispatch_payload(isolated_state):+ _seed_session()++ store = ShowSessionEventStore()+ try:+ event = store.append(+ "ses_mark",+ {+ "type": "human.intent.submitted",+ "payload": {+ "component": "decision",+ "intent": "choose",+ "value": "B",+ "comment": "Pick B.",+ "dispatch": True,+ },+ },+ )+ finally:+ store.close()++ assert event["payload"]["dispatch"] is True+ assert "[show-intent:default] choose" in event["transcript_text"]+ assert "Pick B." in event["transcript_text"]+++def test_show_event_store_records_assistant_page_update(isolated_state):+ _seed_session()++ store = ShowSessionEventStore()+ try:+ event = store.append(+ "ses_mark",+ {+ "type": "assistant.page.updated",+ "payload": {+ "summary": "Updated the Show Page with the revised flow.",+ },+ },+ )+ finally:+ store.close()++ assert event["actor"] == "assistant"+ assert event["message_id"]+ assert "[show-page-updated] Updated the Show Page" in event["transcript_text"]++def test_show_event_store_rejects_unknown_session(isolated_state):store = ShowSessionEventStore()try:diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 193189dbd..15016e670 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -4,6 +4,7 @@ import ioimport jsonimport tarfilefrom pathlib import Path+from unittest.mock import patchimport pytest@@ -305,6 +306,54 @@ def test_private_show_page_records_show_event(monkeypatch, tmp_path):assert events_response.get_json()["events"][0]["id"] == payload["event"]["id"]+def test_private_show_page_dispatches_human_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)))+ dispatches = []+ dispatch_done = asyncio.Event()++ async def fake_stream_dispatch(payload, **kwargs):+ dispatches.append(payload)+ dispatch_done.set()+ yield "turn.start", {"session_id": payload["session_id"]}+ yield "turn.end", {"session_id": payload["session_id"]}++ with patch("vibe.internal_client.stream_dispatch", fake_stream_dispatch):+ 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": "human.intent.submitted",+ "payload": {+ "component": "decision",+ "intent": "choose",+ "value": "B",+ "comment": "Pick B.",+ "dispatch": True,+ },+ },+ )++ assert response.status_code == 201+ asyncio.run(asyncio.wait_for(dispatch_done.wait(), timeout=1))+ assert dispatches+ assert dispatches[0]["session_id"] == "ses123"+ assert "Pick B." in dispatches[0]["text"]+ assert dispatches[0]["user_message_id"] == response.get_json()["event"]["message_id"]+ assert "show.dispatch" in [event_type for event_type, _data in published]++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)@@ -430,10 +479,94 @@ def test_show_events_stream_replays_all_persisted_pages_before_live(monkeypatch,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 bodyassert '"id": "show_evt_000"' in bodyassert '"id": "show_evt_500"' in body+def test_show_events_stream_forwards_live_dispatch_events(monkeypatch, tmp_path):+ from vibe.sse_broker import broker+ 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")++ async def _collect_live_dispatch() -> str:+ response = await _show_events_stream("ses123")+ iterator = response.body_iterator.__aiter__()+ chunks = []+ try:+ chunks.append(await iterator.__anext__())+ broker.publish(+ "show.dispatch",+ {+ "session_id": "ses123",+ "scope_id": "scope123",+ "show_event_id": "show_evt_1",+ "event": "turn.chunk",+ "data": {"text": "hello"},+ },+ )+ chunks.append(await asyncio.wait_for(iterator.__anext__(), timeout=1))+ finally:+ await iterator.aclose()+ return "".join(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk for chunk in chunks)++ body = asyncio.run(_collect_live_dispatch())++ assert "event: show.dispatch" in body+ assert '"show_event_id": "show_evt_1"' in body+++def test_public_show_events_stream_redacts_nested_dispatch_ids(monkeypatch, tmp_path):+ from vibe.sse_broker import broker+ 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")++ async def _collect_live_dispatch() -> str:+ response = await _show_events_stream("ses123", public=True)+ iterator = response.body_iterator.__aiter__()+ chunks = []+ try:+ chunks.append(await iterator.__anext__())+ broker.publish(+ "show.dispatch",+ {+ "session_id": "ses123",+ "scope_id": "scope123",+ "show_event_id": "show_evt_1",+ "event": "turn.chunk",+ "data": {+ "text": "hello",+ "session_id": "ses123",+ "message_id": "msg123",+ "nested": {"scope_id": "scope123", "user_message_id": "msg123"},+ },+ },+ )+ chunks.append(await asyncio.wait_for(iterator.__anext__(), timeout=1))+ finally:+ await iterator.aclose()+ return "".join(chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk for chunk in chunks)++ body = asyncio.run(_collect_live_dispatch())++ assert "event: show.dispatch" in body+ assert '"show_event_id": "show_evt_1"' in body+ assert '"text": "hello"' in body+ assert '"session_id"' not in body+ assert '"scope_id"' not in body+ assert '"message_id"' not in body+ assert '"user_message_id"' not in body++def test_public_show_page_events_redact_internal_ids(monkeypatch, tmp_path):from core.show_session_events import ShowSessionEventStorediff --git a/vibe/cli.py b/vibe/cli.pyindex 1c57219c6..489eeea83 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -480,6 +480,7 @@ def _show_examples_text() -> str: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.+ event Record a generic annotation-layer event.Visibility:private Authenticated Web UI URL under /show/<session-id>/.@@ -494,6 +495,7 @@ def _show_examples_text() -> str:vibe show update --session-id sesk8m4q2p7x --visibility publicvibe show update --session-id sesk8m4q2p7x --visibility offlinevibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."+ vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --jsonMore:vibe show list --help@@ -501,6 +503,7 @@ def _show_examples_text() -> str:vibe show status --helpvibe show update --helpvibe show mark --help+ vibe show event --help""")@@ -570,6 +573,18 @@ def _show_mark_examples_text() -> str:)+def _show_event_examples_text() -> str:+ return dedent(+ """\+ Record any Show Page event supported by the annotation layer.++ Examples:+ vibe show event --session-id sesk8m4q2p7x --type assistant.page.updated --event-json '{"summary":"Updated the plan."}'+ vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --json+ """+ )++def _print_json(payload: dict) -> None:print(json.dumps(payload, indent=2))@@ -4220,7 +4235,7 @@ def _local_show_events_url(session_id: str) -> str | 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:+def _post_show_event_to_live_ui(session_id: str, payload: dict) -> dict | None:from core.show_pages import SHOW_CLI_EVENT_TOKEN_HEADER, show_cli_event_tokenurl = _local_show_events_url(session_id)@@ -4245,6 +4260,52 @@ def _post_show_mark_to_live_ui(session_id: str, payload: dict) -> dict | None:return parsed.get("event") if isinstance(parsed, dict) and parsed.get("ok") is True else None+def _post_show_mark_to_live_ui(session_id: str, payload: dict) -> dict | None:+ return _post_show_event_to_live_ui(session_id, payload)+++def _with_show_event_dispatch(payload: dict) -> dict:+ if isinstance(payload.get("annotation"), dict):+ return {**payload, "annotation": {**payload["annotation"], "dispatch": True}}+ if isinstance(payload.get("payload"), dict):+ return {**payload, "payload": {**payload["payload"], "dispatch": True}}+ event_fields = {"type", "id", "session_id", "sessionId", "created_at", "createdAt", "anchor", "message"}+ event_payload = {key: value for key, value in payload.items() if key not in event_fields}+ return {**payload, "payload": {**event_payload, "dispatch": True}}+++def _read_event_json_argument(value: str | None, file_path: str | None) -> dict:+ if value is None and file_path is None:+ return {}+ if value is not None and file_path is not None:+ raise TaskCliError(+ "use either --event-json or --event-json-file, not both",+ code="conflicting_event_json_inputs",+ help_command="vibe show event --help",+ )+ if file_path is not None:+ raw = _read_cli_text_argument(value=None, file_path=file_path, field_name="--event-json-file")+ else:+ raw = value or ""+ if raw.startswith("@"):+ raw = _read_cli_text_argument(value=None, file_path=raw[1:], field_name="--event-json")+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise TaskCliError(+ f"invalid event JSON: {exc}",+ code="invalid_event_json",+ help_command="vibe show event --help",+ ) from exc+ if not isinstance(payload, dict):+ raise TaskCliError(+ "event JSON must be an object",+ code="invalid_event_json",+ help_command="vibe show event --help",+ )+ return payload++def cmd_show_mark(args):from core.show_pages import ShowPageStorefrom core.show_session_events import ShowSessionEventStore@@ -4299,6 +4360,56 @@ def cmd_show_mark(args):event_store.close()+def cmd_show_event(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)+ payload = _read_event_json_argument(args.event_json, args.event_json_file)+ if args.type:+ payload = {**payload, "type": args.type}+ if args.dispatch:+ payload = _with_show_event_dispatch(payload)+ event = _post_show_event_to_live_ui(args.session_id, payload)+ if event is None:+ if args.dispatch:+ from vibe.ui_server import record_local_show_event++ event = record_local_show_event(args.session_id, payload, dispatch_sync=True)+ else:+ event_store = ShowSessionEventStore()+ event = event_store.append(args.session_id, payload)+ result = _show_page_result(+ page,+ message="Show event 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("Event:")+ print(f" Event: {event['id']}")+ print(f" Type: {event['type']}")+ print(f" Message: {event.get('message_id') or 'none'}")+ 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()@@ -4313,6 +4424,8 @@ def cmd_show(args):return cmd_show_update(args)if args.show_command == "mark":return cmd_show_mark(args)+ if args.show_command == "event":+ return cmd_show_event(args)raise TaskCliError("show command is required",code="invalid_arguments",@@ -4895,7 +5008,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,mark}")+ show_subparsers = show_parser.add_subparsers(dest="show_command", metavar="{list,path,status,update,mark,event}")show_subparsers.required = Falseshow_list_parser = show_subparsers.add_parser(@@ -5005,6 +5118,27 @@ def build_parser():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.")+ show_event_parser = show_subparsers.add_parser(+ "event",+ help="Record a generic Show Page event",+ description="Record a Show Page annotation, intent, page-update, runtime, or assistant mark event.",+ epilog=_show_event_examples_text(),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe show event --help",+ error_hint="Pass --session-id and either --event-json/--event-json-file or --type with JSON fields.",+ )+ show_event_parser.add_argument("--session-id", required=True, help="Agent Session ID for the Show Page.")+ show_event_parser.add_argument("--type", help="Show event type, for example human.annotation.created.")+ event_json_group = show_event_parser.add_mutually_exclusive_group(required=True)+ event_json_group.add_argument("--event-json", help="Inline JSON object, or @path to read JSON from a file.")+ event_json_group.add_argument("--event-json-file", help="Read event JSON from a UTF-8 file, or '-' for stdin.")+ show_event_parser.add_argument(+ "--dispatch",+ action="store_true",+ help="For human intent/annotation events, request an Agent turn after recording the event.",+ )+ show_event_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.pyindex 28c430a32..34b22a5bc 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -53,9 +53,11 @@ _SHOW_RUNTIME_REQUEST_HEADER_ALLOWLIST = {"content-type","if-modified-since","if-none-match",+ "last-event-id","pragma","range","user-agent",+ SHOW_EVENT_WRITE_TOKEN_HEADER.lower(),}_SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST = {"accept-ranges",@@ -3760,6 +3762,11 @@ def _show_events_payload_from_request() -> dict[str, Any]:return payload if isinstance(payload, dict) else {}+def _last_event_id_from_request() -> str | None:+ value = request.headers.get("Last-Event-ID")+ return value.strip() if isinstance(value, str) and value.strip() else None++def _show_event_write_authorized(session_id: str) -> bool:token = request.headers.get(SHOW_EVENT_WRITE_TOKEN_HEADER)if not token:@@ -3781,9 +3788,27 @@ def _show_event_response_from_payload(session_id: str, payload: dict[str, Any]):store.close()_publish_show_session_event(event_payload)+ _dispatch_show_event_if_requested(event_payload)return jsonify({"ok": True, "event": event_payload}), 201+def record_local_show_event(session_id: str, payload: dict[str, Any], *, dispatch_sync: bool = False) -> dict[str, Any]:+ store = _show_session_event_store()+ try:+ event_payload = store.append(session_id, payload)+ finally:+ store.close()+ _publish_show_session_event(event_payload)+ if dispatch_sync and _show_event_requests_dispatch(event_payload):+ try:+ asyncio.run(_run_show_event_dispatch(event_payload))+ except RuntimeError:+ _dispatch_show_event_if_requested(event_payload)+ else:+ _dispatch_show_event_if_requested(event_payload)+ return event_payload++def _publish_show_session_event(event_payload: dict[str, Any]) -> None:from vibe.sse_broker import broker@@ -3801,6 +3826,79 @@ def _publish_show_session_event(event_payload: dict[str, Any]) -> None:)+def _dispatch_show_event_if_requested(event_payload: dict[str, Any]) -> None:+ if not _show_event_requests_dispatch(event_payload):+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ thread = threading.Thread(+ target=lambda: asyncio.run(_run_show_event_dispatch(event_payload)),+ name="show-event-dispatch",+ daemon=True,+ )+ thread.start()+ return+ loop.create_task(_run_show_event_dispatch(event_payload))+++def _show_event_requests_dispatch(event_payload: dict[str, Any]) -> bool:+ if event_payload.get("actor") != "human":+ return False+ if event_payload.get("type") not in {"human.intent.submitted", "human.annotation.created"}:+ return False+ payload = event_payload.get("payload")+ if not isinstance(payload, dict):+ return False+ return bool(payload.get("dispatch"))+++async def _run_show_event_dispatch(event_payload: dict[str, Any]) -> None:+ from vibe import internal_client++ session_id = event_payload.get("session_id")+ scope_id = event_payload.get("scope_id")+ transcript_text = event_payload.get("transcript_text")+ if not isinstance(session_id, str) or not session_id or not isinstance(transcript_text, str) or not transcript_text.strip():+ return+ dispatch_payload = {+ "session_id": session_id,+ "text": transcript_text,+ "scope_id": scope_id,+ "user_message_id": event_payload.get("message_id"),+ "message_id": event_payload.get("message_id"),+ "platform": "avibe",+ "channel_id": session_id,+ }+ try:+ async for event_name, data in internal_client.stream_dispatch(dispatch_payload):+ _publish_show_dispatch_event(event_payload, event_name, data)+ except internal_client.InternalServerUnavailable as exc:+ _publish_show_dispatch_event(+ event_payload,+ "stream.error",+ {"reason": "internal_server_unavailable", "detail": str(exc)},+ )+ except Exception as exc: # pragma: no cover - defensive+ logger.exception("show event dispatch failed")+ _publish_show_dispatch_event(event_payload, "stream.error", {"reason": "dispatch_failed", "detail": str(exc)})+++def _publish_show_dispatch_event(event_payload: dict[str, Any], event_name: str, data: Any) -> None:+ from vibe.sse_broker import broker++ broker.publish(+ "show.dispatch",+ {+ "show_event_id": event_payload.get("id"),+ "session_id": event_payload.get("session_id"),+ "scope_id": event_payload.get("scope_id"),+ "event": event_name,+ "data": data,+ },+ )++def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:if not public:return event_payload@@ -3811,6 +3909,28 @@ def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool}+def _show_dispatch_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:+ if not public:+ return event_payload+ return {+ key: _redact_public_dispatch_value(value)+ for key, value in event_payload.items()+ if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}+ }+++def _redact_public_dispatch_value(value: Any) -> Any:+ if isinstance(value, dict):+ return {+ key: _redact_public_dispatch_value(nested)+ for key, nested in value.items()+ if key not in {"session_id", "scope_id", "message_id", "message", "user_message_id"}+ }+ if isinstance(value, list):+ return [_redact_public_dispatch_value(item) for item in value]+ return value++def _show_events_list_payload(payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:if not public:return payload@@ -3860,17 +3980,17 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, pwhile True:try:event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)- if event_type != "show.event":- continuedecoded = json.loads(payload)event_payload = decoded.get("data") if isinstance(decoded, dict) else None- if isinstance(event_payload, dict) and _event_visible(event_payload):+ if event_type == "show.event" and 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:continueif isinstance(event_id, str):replayed_ids.add(event_id)yield _sse_frame("show.event", _show_event_response_payload(event_payload, public=public))+ 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:yield ": ping\n\n"except asyncio.CancelledError:@@ -3879,7 +3999,9 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, pbroker.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"+ event_id = data.get("id") if isinstance(data, dict) else None+ prefix = f"id: {event_id}\n" if isinstance(event_id, str) and event_id else ""+ return f"{prefix}event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"return StreamingResponse(generate(),@@ -3891,7 +4013,11 @@ async def _show_events_stream(session_id: str, *, after_id: str | None = None, pasync 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)+ return await _show_events_stream(+ session_id,+ after_id=request.args.get("after_id") or _last_event_id_from_request(),+ public=public,+ )store = _show_session_event_store()try:try: