Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(show): add authenticated annotation controls (#948)

Call Whitea684cfb0bfa3
diff --git a/core/show_pages.py b/core/show_pages.py
index a770f8bac..17db6e3f3 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -127,6 +127,18 @@ def show_event_write_token(session_id: str) -> str:
).hexdigest()
+def show_public_event_write_token(share_id: str, session_id: str) -> str:
+ share_value = (share_id or "").strip()
+ if not share_value:
+ raise ShowPageError("A public share ID is required.", code="missing_share_id")
+ session_value = validate_session_id(session_id)
+ return hmac.new(
+ _load_or_create_show_event_secret().encode("utf-8"),
+ f"public-share:{share_value}:session:{session_value}".encode("utf-8"),
+ hashlib.sha256,
+ ).hexdigest()
+
+
def show_cli_event_token() -> str:
return hmac.new(
_load_or_create_show_event_secret().encode("utf-8"),
@@ -1353,6 +1365,10 @@ type VibeShowRuntimeConfig = {
eventsPath?: string
streamPath?: string
writeToken?: string
+ annotation?: {
+ authenticated: boolean
+ mePath: string
+ }
}
declare global {
@@ -1368,6 +1384,7 @@ function readCookie(name: string): string | undefined {
const injected: VibeShowRuntimeConfig = globalThis.__AVIBE_SHOW__ ?? {}
globalThis.__AVIBE_SHOW__ = {
+ ...injected,
sessionId: injected.sessionId ?? (window.location.pathname.match(/\\/show\\/([^/]+)/)?.[1]
? decodeURIComponent(window.location.pathname.match(/\\/show\\/([^/]+)/)![1])
: undefined),
diff --git a/core/show_session_events.py b/core/show_session_events.py
index bb5992260..eb8c52441 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -17,18 +17,22 @@ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_
from storage.models import agent_sessions, show_session_events
DEFAULT_MARK_SCOPE = "default"
-SUPPORTED_EVENT_TYPES = {
- "assistant.mark.created",
- "assistant.mark.updated",
- "assistant.mark.resolved",
- "assistant.page.updated",
+HUMAN_EVENT_TYPES = {
"human.intent.submitted",
"human.annotation.created",
"human.annotation.updated",
"human.annotation.resolved",
"human.annotation.dismissed",
+}
+SUPPORTED_EVENT_TYPES = {
+ "assistant.mark.created",
+ "assistant.mark.updated",
+ "assistant.mark.resolved",
+ "assistant.page.updated",
"system.runtime.status",
"system.runtime.error",
+ "system.annotation.control",
+ *HUMAN_EVENT_TYPES,
}
ANNOTATION_EVENT_TYPES = {
"human.annotation.created",
@@ -68,14 +72,24 @@ class ShowSessionEventStore:
def close(self) -> None:
self.engine.dispose()
- def append(self, session_id: str, payload: dict[str, Any]) -> dict[str, Any]:
+ def append(
+ self,
+ session_id: str,
+ payload: dict[str, Any],
+ *,
+ author: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
validate_show_event_payload_session(session_id, payload)
event_type = _validate_event_type(payload.get("type"))
actor = _actor_for_event(event_type)
event_payload = _normalize_event_payload(event_type, payload)
+ if actor == "human":
+ event_payload.pop("author", None)
anchor = _event_anchor(event_type, payload, event_payload)
scope = _event_scope(event_type, event_payload)
transcript_text = _format_transcript_text(event_type, event_payload, anchor)
+ if actor == "human":
+ event_payload["author"] = _normalize_human_author(author)
event_id = _event_id(payload, event_payload)
created_at = _utc_now_iso()
@@ -122,6 +136,7 @@ class ShowSessionEventStore:
"show_event_id": event_id,
"show_event_type": event_type,
"show_event_scope": scope,
+ **({"author": event_payload["author"]} if actor == "human" else {}),
},
native_message_id=f"show:{event_id}",
)
@@ -266,6 +281,17 @@ def _normalize_event_payload(event_type: str, payload: dict[str, Any]) -> dict[s
if event_type == "human.annotation.resolved":
normalized["resolvedAt"] = _text_or_none(normalized.get("resolvedAt")) or _utc_now_iso()
return normalized
+ if event_type == "system.annotation.control":
+ control = _normalize_json_object(payload.get("payload") or payload)
+ action = _text_or_none(control.get("action"))
+ mode = _text_or_none(control.get("mode"))
+ if action not in {"enable", "disable", "set-mode"}:
+ raise ShowSessionEventError("annotation control action is invalid.", code="invalid_payload")
+ if mode is not None and mode not in {"smart", "screenshot"}:
+ raise ShowSessionEventError("annotation control mode is invalid.", code="invalid_payload")
+ if action == "set-mode" and mode is None:
+ raise ShowSessionEventError("annotation control mode is required.", code="invalid_payload")
+ return {"action": action, **({"mode": mode} if mode is not None else {})}
normalized = _normalize_json_object(payload.get("payload") or payload)
if not normalized:
normalized = {}
@@ -279,6 +305,15 @@ def _normalize_json_object(raw: Any) -> dict[str, Any]:
return raw if isinstance(raw, dict) else {}
+def _normalize_human_author(author: dict[str, str] | None) -> dict[str, str]:
+ if not isinstance(author, dict) or author.get("kind") != "user":
+ return {"kind": "local"}
+ email = _text_or_none(author.get("email"))
+ if not email:
+ return {"kind": "local"}
+ return {"kind": "user", "email": email}
+
+
def _json_object_list(raw: Any) -> list[dict[str, Any]]:
if not isinstance(raw, list):
return []
@@ -312,6 +347,8 @@ def _event_id(original_payload: dict[str, Any], event_payload: dict[str, Any]) -
def _format_transcript_text(event_type: str, payload: dict[str, Any], anchor: dict[str, Any]) -> str:
+ if event_type == "system.annotation.control":
+ return ""
if event_type.startswith("assistant.mark."):
action = event_type.split(".")[-1]
lines = [
diff --git a/docs/plans/show-page-annotation-phase1.md b/docs/plans/show-page-annotation-phase1.md
new file mode 100644
index 000000000..7fe2bd6df
--- /dev/null
+++ b/docs/plans/show-page-annotation-phase1.md
@@ -0,0 +1,345 @@
+# Show Page Annotation — Phase 1: Default Overlay, Control Surfaces, Authenticated Writes
+
+Status: approved for implementation (owner sign-off 2026-07-20, design frames approved).
+Owner decisions baked in: snapDOM for capture, "workbench access = logged-in user"
+auth model, desktop header segmented control (collapsed by default), mobile popup
+mode picker with last-mode memory.
+
+## Summary
+
+The annotation pipeline already exists end to end: `show_session_events`
+persistence, transcript projection (`metadata.source = "show_page"`), optional
+agent dispatch (`payload.dispatch: true`), SSE streaming, `vibe show mark` /
+`vibe show event` CLI, and a feature-complete `AnnotationOverlay`
+(smart/screenshot) in `@avibe/show-sdk/react`. What is missing is the product
+surface: nothing mounts the overlay, nothing controls it, screenshot capture
+depends on `getDisplayMedia` (unavailable on iOS), and event writes are
+capability-token based rather than identity based.
+
+Phase 1 closes exactly that gap:
+
+1. Every Show Page (private and public) automatically gets the annotation
+ overlay via server-side HTML injection — no scaffold changes, old pages
+ included.
+2. One annotation state machine with four control surfaces: chat header
+ control, in-page floating toolbar (standalone tabs), `window` API, and an
+ agent-driven SSE control event (+ CLI).
+3. Event writes carry an authenticated user identity. Public pages accept
+ writes only from logged-in workbench users.
+4. Overlay visuals rebuilt to the approved design (design.pen frames
+ `H8oicB`, `i6HVWm`, `kn94D`, `urZTa`, `WVGjS` in `avibe-docs/design.pen`).
+5. Screenshot capture switches to same-origin DOM rendering (snapDOM) with
+ `getDisplayMedia` as a desktop-only fallback.
+
+## Non-Goals (Phase 1)
+
+- No screenshot attachment storage; the captured image still travels inside
+ the event payload (Phase 3 moves it to attachments). Cap capture size
+ (long edge ≤ 2048 px) to bound payload growth.
+- No rich chat card rendering for `show_page` messages (Phase 3).
+- No overlay theming; the overlay ships a self-contained fixed dark floating
+ style (mint/violet accents) that works over light and dark pages.
+- No freeze-mode entry point, no multiple screenshot drafts.
+- The legacy `AgentationToggle` in the main workbench UI stays untouched.
+- No role hierarchy; identity is recorded to make future roles possible.
+
+## Architecture
+
+```
+ ┌────────────────────────────────────────────┐
+ Chat header ────┤ postMessage: avibe:annotation:control/state │
+ (embedded host) └────────────────────────────────────────────┘
+ │ same-origin iframe
+ ▼
+ Show Page HTML ── injected <script module> bootstrap ── mounts AnnotationOverlay
+ ▲ (separate React root,
+ vibe show annotate ── SSE ───┘ portal to body)
+ (system.annotation.control)
+```
+
+- **Injection point (avibe)**: `vibe/ui_server.py` already injects the
+ `__AVIBE_SHOW__` config script into private Show Page HTML
+ (`_inject_show_runtime_config`). Phase 1 extends this to also inject a
+ `<script type="module">` tag loading the runtime-served annotation bootstrap,
+ and performs the same injection on public `/p/` HTML (config **without**
+ `writeToken`).
+- **Bootstrap module (vibe-show-runtime)**: the runtime dev server exposes a
+ session-independent entry (e.g. `__show/annotation.js` resolved as a Vite
+ virtual module / vendor asset) that imports the SDK overlay and mounts it in
+ its own React root appended to `document.body`. It must not touch the user
+ app's module graph beyond sharing the runtime-managed React instance, and it
+ must never crash the host page (top-level try/catch, bail silently).
+- **Host detection (overlay, runtime side)**: `location.search` contains
+ `vibe-embed=1` → `embedded` host (chat iframe): floating toolbar hidden, mode
+ pill shown, controlled via postMessage. Otherwise `standalone`: floating
+ FAB/toolbar shown (bottom-right), full local control.
+- **Auth-aware UI**: overlay asks `GET <basePath>__show/me`; when
+ `canAnnotate` is false (anonymous public visitor) the FAB stays hidden.
+
+## Frozen Interface Contracts
+
+Field names below are frozen. Deviations route through the orchestrator, never
+lane-to-lane.
+
+### 1. Injected config (extends existing `__AVIBE_SHOW__`)
+
+```ts
+globalThis.__AVIBE_SHOW__ = {
+ sessionId: string,
+ basePath: string,
+ eventsPath: string, // unchanged
+ streamPath: string, // unchanged
+ writeToken?: string, // private pages only (unchanged)
+ annotation: {
+ authenticated: boolean, // server-known auth state at render time
+ mePath: string, // "__show/me" relative to basePath
+ }
+}
+```
+
+### 2. Overlay window API (runtime/SDK)
+
+```ts
+__AVIBE_SHOW__.annotation.api = {
+ enable(mode?: "smart" | "screenshot"): void, // no mode → last-used (localStorage), default "smart"
+ disable(): void,
+ setMode(mode: "smart" | "screenshot"): void,
+ getState(): { enabled: boolean; mode: "smart" | "screenshot"; available: boolean },
+ subscribe(cb: (s: ReturnType<typeof getState>) => void): () => void,
+}
+```
+
+Mode memory: `localStorage` key `avibe:annotation-mode:<sessionId>`.
+
+### 3. postMessage protocol (same-origin, chat parent ↔ iframe)
+
+```ts
+// parent → iframe
+{ type: "avibe:annotation:control", action: "enable" | "disable" | "set-mode", mode?: "smart" | "screenshot" }
+{ type: "avibe:annotation:query" }
+// iframe → parent (on mount, on every state change, and in reply to query)
+{ type: "avibe:annotation:state", enabled: boolean, mode: "smart" | "screenshot", available: boolean }
+```
+
+`enable` without `mode` uses the remembered mode. `available:false` means the
+overlay is mounted but writes are not possible (anonymous public visitor).
+
+### 4. Agent control event (SSE) + CLI
+
+New event type accepted by the pipeline: `system.annotation.control`
+(actor `system`), payload:
+
+```ts
+{ action: "enable" | "disable" | "set-mode", mode?: "smart" | "screenshot" }
+```
+
+- No transcript projection (`transcript_text` empty ⇒ no chat message).
+- Never dispatches an agent turn.
+- Reaches the page through the existing `show.event` SSE stream; the overlay
+ subscribes and applies it in both hosts.
+- CLI: `vibe show annotate [--session-id <id>] (--on | --off | --mode smart|screenshot)`
+ → posts this event via the existing CLI show-event path. `--on --mode X` is
+ one event with `action:"enable", mode:"X"`.
+
+### 5. Authenticated writes
+
+- Every accepted human event write records the author into the event payload
+ and message metadata:
+
+```ts
+payload.author = { kind: "user" | "local", email?: string }
+```
+
+ Remote (avibe.bot OAuth session): `{ kind: "user", email }` — the email from
+ the validated OAuth session. Local LAN / same-machine (no OAuth configured):
+ `{ kind: "local" }`.
+
+ Contract note (revised 2026-07-20 after Lane A finding): role hierarchy
+ (owner/member/…) is a control-plane concept that does not exist on the
+ device today — the OAuth session carries only `email`/`sub`/`instance_id`,
+ and no role claim is issued anywhere. Recording the stable `email` IS the
+ forward-compatibility hook: a future role system maps emails to roles at
+ read time; stored events never need rewriting. Do not invent a role at
+ write time.
+- Private `/show/<sid>/__show/events` POST: unchanged token requirement
+ (`X-Vibe-Show-Token`), now additionally records `author`.
+- Public `/p/<share>/__show/events` POST (**revised 2026-07-20 v2** after the
+ Lane A security finding — all public shares are same-origin, so a cookie +
+ static custom header can be forged by any same-origin page script against
+ any other share). Requirements, all three:
+ 1. a valid workbench OAuth session (unchanged), AND
+ 2. `X-Vibe-Show-Token` carrying the **share-scoped write token** issued by
+ `GET /p/<share>/__show/me` (see below) — an HMAC bound to this share,
+ distinct from the private session token, AND
+ 3. a `Referer` whose path starts with `/p/<share>/`; missing or mismatched
+ → `403 public_show_events_origin_mismatch`.
+ Anonymous / no-session → `403 public_show_events_login_required`. The
+ `X-Vibe-Show-Client` header requirement is DROPPED (superseded by the
+ token).
+- New endpoint on both surfaces: `GET <basePath>__show/me` →
+ `{ authenticated: boolean, canAnnotate: boolean, writeToken?: string }`.
+ `writeToken` is present iff `canAnnotate` is true: on the public surface it
+ is the share-scoped token above; on the private surface it equals the
+ session write token (uniform overlay logic: injected token ?? me.writeToken).
+ Anonymous GET is allowed and returns `false/false` without a token.
+- GET/stream visibility is unchanged (public stays redacted read-only).
+- **Accepted residual risk (recorded, not fixed in Phase 1)**: pages under
+ one origin are one browser trust domain — a page could `window.open` a
+ sibling page and drive its DOM/overlay. This matches the existing
+ same-origin Show Page trust model (issue #577 decision: all page content is
+ authored by this machine's agent). Revisit with origin isolation only if
+ third-party-authored content ever becomes renderable.
+
+### 6. Chat iframe host marker
+
+The workbench chat appends `vibe-embed=1` to the Show Page iframe `src` query
+string. No other component may repurpose this parameter.
+
+### 7. Bootstrap asset path
+
+The injected tag is exactly
+`<script type="module" src="{basePath}__show/annotation.js"></script>`.
+Lane A guarantees `__show/annotation.js` is NOT treated as an events/API path
+and proxies through to the runtime on both `/show/` and `/p/` surfaces (public
+surface uses the same immutable-safe serving as other runtime assets). Lane R
+guarantees the runtime serves a JS module at
+`/sessions/<sessionId>/app/__show/annotation.js` for every session workspace,
+including pre-existing ones.
+
+## Lane Split
+
+Three lanes, mutually exclusive file scopes. Contracts above are the only
+coupling; no lane-to-lane negotiation.
+
+### Lane R — `vibe-show-runtime` (overlay, bootstrap, capture)
+
+Scope: `packages/sdk/**`, `packages/runtime/**`, `examples/**` (optional demo),
+docs touched only for README pointers. Do not touch `packages/ui` (SDK must not
+depend on the UI package — CONTRIBUTING boundary).
+
+1. Visual rebuild of `AnnotationOverlay` + `CommentPopover` + markers to the
+ approved design: dark floating chrome (`#11111C` surfaces, mint `#5BFFA0`
+ human accents, violet `#7C5BFF` agent accents), anchor chip + intent chips
+ (评论/修改/疑问/批准 ⇒ intent `comment|change|question|approve`), severity
+ accents, numbered markers (user mint / resolved gray / agent violet bot),
+ screenshot region chrome (dim masks, corner handles, numbered items, batch
+ card), mode pill, mobile bottom-sheet comment card (touch targets ≥ 44 px),
+ standalone FAB ⇄ pill-toolbar. Self-contained styles; no external CSS deps.
+2. Host modes: `embedded` (hide toolbar, show pill, obey postMessage) vs
+ `standalone` (FAB + toolbar) per `vibe-embed=1` detection.
+3. Control plane: window API (contract §2), postMessage listener/broadcaster
+ (§3), SSE `system.annotation.control` handling (§4), mode memory
+ (localStorage key in §2), auth gating via `__show/me` (§5 v2) — hide FAB /
+ show "login required" hint when `canAnnotate` is false. Write token
+ resolution is uniform: injected `__AVIBE_SHOW__.writeToken` ??
+ `me.writeToken`; every event POST sends it via `X-Vibe-Show-Token` on both
+ surfaces.
+4. Bootstrap entry served by the runtime (contract "Bootstrap module"):
+ mounts overlay automatically, resilient to user-page errors, no scaffold
+ edits, works for existing session workspaces.
+5. Capture: add `@zumer/snapdom` as a runtime-managed dependency, lazy-loaded
+ on first screenshot-mode activation. Strategy: snapDOM same-origin DOM
+ render (crop to region, long edge ≤ 2048) → fallback `getDisplayMedia`
+ (desktop only) → error message. Keep the existing payload shape.
+6. Tests: `npm run check` green; unit tests for control plane state machine,
+ mode memory, host detection, and capture strategy selection (mock snapdom).
+
+### Lane A — `avibe` backend (injection, auth, control event, CLI)
+
+Scope: `vibe/ui_server.py`, `vibe/cli.py`, `vibe/i18n/**`, `core/show_pages.py`,
+`core/show_session_events.py`, `storage/**` (only if a migration is truly
+needed — prefer payload-level author, no schema change), `tests/**`,
+`docs/plans/` updates. Do not touch `ui/**`.
+
+1. Extend HTML injection: annotation bootstrap `<script module>` on private
+ **and** public Show Page HTML; config gains `annotation` block (§1); public
+ config carries no `writeToken`.
+2. `GET __show/me` on both surfaces (§5 v2), including the share-scoped
+ `writeToken` issuance when `canAnnotate` is true.
+3. Public events POST (§5 v2): OAuth session + share-scoped
+ `X-Vibe-Show-Token` + Referer path-prefix check. Anonymous →
+ `public_show_events_login_required`; missing/mismatched Referer →
+ `public_show_events_origin_mismatch`; bad token →
+ `show_event_write_forbidden`. Author recording on all accepted writes;
+ private POST: author recording added.
+4. New event type `system.annotation.control` (§4): accepted, persisted,
+ SSE-published, empty transcript, never dispatched.
+5. CLI `vibe show annotate` (§4) following existing `vibe show mark` patterns
+ (session resolution, `--json`, live-UI post path).
+6. Tests: extend `tests/test_show_pages*.py` / `test_show_session_events.py` /
+ `test_ui_show_pages.py` patterns — injection on both surfaces, me endpoint
+ matrix, anonymous vs logged-in public POST, author recording, control event
+ no-transcript/no-dispatch, CLI arg handling. `ruff check` on touched files.
+
+### Lane C — `avibe` chat UI (header control, bridge)
+
+Scope: `ui/src/**` only (ChatPage, new components under
+`ui/src/components/workbench/`, `ui/src/i18n/en.json`, `ui/src/i18n/zh.json`).
+Do not touch `vibe/**`, `core/**`, `tests/**`.
+
+1. Header annotation control, visible only in Show Page mode, placed left of
+ the back-to-chat button (design frames `H8oicB`/`kn94D`):
+ - Desktop: collapsed = one 28 px icon button (`message-square-plus`);
+ active = segmented group (toggle + Smart + 截图) with mint accent.
+ - Mobile (`md` breakpoint down): single button opening a Popover
+ (existing `ui` primitive) per frame `WVGjS`: Smart / 截图 radio rows +
+ "关闭标注" row; button itself toggles on with remembered mode.
+2. postMessage bridge to the iframe (§3): send control, receive state, keep
+ button/segment state in sync, disable control until first `state`
+ (`available` gating + tooltip when unavailable).
+3. Append `vibe-embed=1` to the iframe src (§6).
+4. Reuse `ui/src/components/ui/` primitives (Button, Popover, Tooltip …);
+ all strings through i18n (en + zh).
+5. Validation: `cd ui && npm run build` green; no `setState` in effect bodies
+ (UI CI gate).
+
+## Sequencing & Integration
+
+1. All three lanes start in parallel; contracts are frozen by this document.
+2. Each lane: own worktree under `.worktrees/<repo>/<branch>/`, branch from
+ the repo default branch (`avibe`: master, `vibe-show-runtime`: main),
+ non-draft PR, Codex review loop to zero unresolved threads, CI green. Lanes
+ do not merge; the orchestrator gates and merges.
+3. Merge order: R (runtime main) → A → C (A/C independent; R first so the
+ bootstrap asset exists for regression source builds).
+4. End-to-end verification by the orchestrator in the local Incus regression
+ environment (github-source runtime) against the acceptance list below.
+
+## Acceptance Criteria
+
+1. Chat visual mode (private page): header control enables Smart → click an
+ element → comment card → send → message appears in the chat transcript
+ (`source: show_page`, author recorded) and triggers an agent reply streamed
+ back; screenshot mode captures without any screen-share prompt.
+2. Same flows on iPhone-class viewport: popover mode picker, bottom-sheet
+ comment card, snapDOM capture works (no `getDisplayMedia` dependency).
+3. Standalone tab (`/show/<sid>/` direct): FAB → toolbar controls everything;
+ same event flows.
+4. `vibe show annotate --on --mode screenshot` flips the live page into
+ screenshot mode; `--off` exits; no chat message is produced by control
+ events.
+5. Public `/p/<share>/`: anonymous — markers/read-only visible, no compose
+ affordance, POST rejected (`public_show_events_login_required`); after
+ logging into the workbench in the same browser — annotation works and the
+ recorded author identity matches the logged-in email. Negative cases: a
+ POST replaying the OAuth cookie against a DIFFERENT share (wrong
+ share-scoped token or wrong Referer path) is rejected
+ (`show_event_write_forbidden` / `public_show_events_origin_mismatch`).
+6. Esc exits annotation mode; while active, page controls do not fire; after
+ disable, the page behaves exactly as before injection.
+7. Gates: runtime `npm run check`; avibe `ruff check` + focused pytest;
+ `ui npm run build`; Codex review clean on every PR.
+
+## References
+
+- Design: `avibe-docs/design.pen` frames `H8oicB` (chat smart), `i6HVWm`
+ (chat screenshot), `kn94D` (components & rules), `urZTa` (mobile sheet),
+ `WVGjS` (mobile mode popup).
+- Existing pipeline: `core/show_session_events.py`,
+ `vibe/ui_server.py` (§ show events / show page serving),
+ `avibe/docs/plans/show-session-event-pipeline.md`.
+- SDK inventory: `vibe-show-runtime/packages/sdk/src/{index.ts,react.tsx}`,
+ roadmap `vibe-show-runtime/docs/agent-os-implementation-plan.md`
+ (this phase completes M6/M8.5 mounting + M12 auth posture).
+- Capture: snapDOM (`@zumer/snapdom`), chosen 2026-07-20 (~42 KB gzip, zero
+ deps; iOS Safari lacks `getDisplayMedia`).
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 8435f3729..e0f62e789 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -14,7 +14,9 @@ from core.show_pages import (
_extract_icon_path,
ensure_show_page_dir,
show_cli_event_token,
+ show_event_write_token,
show_page_payload,
+ show_public_event_write_token,
)
from storage.pagination import PageRequest
from vibe import cli
@@ -59,6 +61,17 @@ def _stub_runtime_prepare_dependencies(
return calls
+def test_public_show_write_token_is_share_scoped_and_distinct(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ first = show_public_event_write_token("share-one", "ses-one")
+
+ assert first == show_public_event_write_token("share-one", "ses-one")
+ assert first != show_public_event_write_token("share-two", "ses-one")
+ assert first != show_public_event_write_token("share-one", "ses-two")
+ assert first != show_event_write_token("share-one")
+
+
def test_show_without_subcommand_prints_help(capsys):
parser = cli.build_parser()
args = parser.parse_args(["show"])
@@ -69,7 +82,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,mark,event} ..." in captured.out
+ assert "usage: vibe show [-h] {list,path,status,update,mark,event,annotate} ..." in captured.out
assert "vibe show list" in captured.out
assert "vibe show path --session-id sesk8m4q2p7x" in captured.out
@@ -732,12 +745,16 @@ def test_show_page_dir_creates_default_index(monkeypatch, tmp_path):
assert "declare global" in main_tsx
assert "const injected: VibeShowRuntimeConfig = globalThis.__AVIBE_SHOW__ ?? {}" in main_tsx
assert "globalThis.__AVIBE_SHOW__ = {" in main_tsx
+ assert "...injected," in main_tsx
assert main_tsx.index("const injected: VibeShowRuntimeConfig") < main_tsx.index("globalThis.__AVIBE_SHOW__ = {")
assert "sessionId: injected.sessionId ??" in main_tsx
assert "basePath: injected.basePath ??" in main_tsx
assert 'eventsPath: injected.eventsPath ?? "__show/events"' in main_tsx
assert 'streamPath: injected.streamPath ?? "__show/events?stream=1"' in main_tsx
assert 'writeToken: injected.writeToken ?? readCookie("vibe_show_event_token")' in main_tsx
+ assert "annotation?: {" in main_tsx
+ assert "authenticated: boolean" in main_tsx
+ assert "mePath: string" in main_tsx
# The runtime-owned shell just renders <App/>; routing is NOT moved into
# main.tsx/index.html, so adding a page never requires touching the shell.
assert 'import App from "./App"' in main_tsx
@@ -2308,6 +2325,211 @@ def test_show_event_cli_records_generic_event(monkeypatch, tmp_path, capsys):
assert "Clarify this." in conn.execute(select(messages.c.content_text)).scalar_one()
+def test_show_annotate_cli_posts_single_enable_event_to_live_ui(monkeypatch, tmp_path, capsys):
+ 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
+
+ monkeypatch.setenv("AVIBE_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": 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_control",
+ "type": "system.annotation.control",
+ "payload": {"action": "enable", "mode": "screenshot"},
+ "message_id": None,
+ },
+ }
+ ).encode("utf-8")
+
+ def _urlopen(request, timeout):
+ captured["payload"] = json.loads(request.data.decode("utf-8"))
+ captured["url"] = request.full_url
+ return _Response()
+
+ monkeypatch.setattr(cli.urllib.request, "urlopen", _urlopen)
+ args = cli.build_parser().parse_args(
+ [
+ "show",
+ "annotate",
+ "--session-id",
+ "ses123",
+ "--on",
+ "--mode",
+ "screenshot",
+ "--json",
+ ]
+ )
+
+ assert cli.cmd_show(args) == 0
+ result = json.loads(capsys.readouterr().out)
+ assert result["event"]["id"] == "show_evt_control"
+ assert captured["payload"] == {
+ "type": "system.annotation.control",
+ "payload": {"action": "enable", "mode": "screenshot"},
+ }
+ assert captured["url"] == "http://127.0.0.1:5123/api/show/sessions/ses123/events"
+
+
+def test_show_annotate_cli_defaults_session_and_records_offline_control(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("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setenv("AVIBE_SESSION_ID", "sesCaller")
+ paths.ensure_data_dirs()
+ _save_config()
+ ensure_sqlite_state()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": None})
+
+ 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="sesCaller",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="anchor_sesCaller",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ args = cli.build_parser().parse_args(["show", "annotate", "--mode", "smart", "--json"])
+ assert cli.cmd_show(args) == 0
+
+ result = json.loads(capsys.readouterr().out)
+ assert result["session_id"] == "sesCaller"
+ assert result["session_default_notice"]["session_id"] == "sesCaller"
+ assert result["event"]["payload"] == {"action": "set-mode", "mode": "smart"}
+ assert result["event"]["transcript_text"] == ""
+ assert result["event"]["message_id"] is None
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).scalar_one() == result["event"]["id"]
+ assert conn.execute(select(messages.c.id)).first() is None
+
+
+def test_show_annotate_cli_rejects_off_with_mode(monkeypatch, tmp_path, capsys):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+
+ args = cli.build_parser().parse_args(
+ ["show", "annotate", "--session-id", "ses123", "--off", "--mode", "smart", "--json"]
+ )
+
+ assert cli.cmd_show(args) == 1
+ assert json.loads(capsys.readouterr().err)["code"] == "invalid_arguments"
+
+
+ ("session_id", "status", "expected_code"),
+ [
+ ("ses-missing", None, "session_not_found"),
+ ("ses-archived", "archived", "session_archived"),
+ ],
+)
+def test_show_annotate_cli_does_not_create_page_for_unwritable_session(
+ monkeypatch,
+ tmp_path,
+ capsys,
+ session_id,
+ status,
+ expected_code,
+):
+ 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_pages
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+ ensure_sqlite_state()
+ monkeypatch.setattr(cli.runtime, "read_status", lambda: {"ui_pid": None})
+
+ engine = create_sqlite_engine()
+ if status is not None:
+ 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=status,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+ args = cli.build_parser().parse_args(
+ ["show", "annotate", "--session-id", session_id, "--on", "--json"]
+ )
+
+ assert cli.cmd_show(args) == 1
+ assert json.loads(capsys.readouterr().err)["code"] == expected_code
+ with engine.connect() as conn:
+ assert conn.execute(select(show_pages.c.session_id)).first() is None
+
+
def test_show_event_defaults_to_caller_session(monkeypatch, tmp_path, capsys):
from sqlalchemy import select
diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.py
index b54650851..93d1f3346 100644
--- a/tests/test_show_session_events.py
+++ b/tests/test_show_session_events.py
@@ -131,6 +131,7 @@ def test_show_event_store_records_human_annotation_with_anchor_context(isolated_
assert event["actor"] == "human"
assert event["scope"] == "default"
assert event["payload"]["status"] == "pending"
+ assert event["payload"]["author"] == {"kind": "local"}
assert event["message_id"]
assert "[show-annotation:default:created] question" in event["transcript_text"]
assert "Clarify this claim." in event["transcript_text"]
@@ -141,6 +142,107 @@ def test_show_event_store_records_human_annotation_with_anchor_context(isolated_
message_row = conn.execute(select(messages).where(messages.c.id == event["message_id"])).mappings().one()
assert message_row["author"] == "user"
+ assert json.loads(message_row["metadata_json"])["author"] == {"kind": "local"}
+
+
+def test_show_event_store_records_remote_human_author_in_event_and_message(isolated_state):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Review this."},
+ },
+ author={"kind": "user", "email": "[email protected]"},
+ )
+ finally:
+ store.close()
+
+ assert event["payload"]["author"] == {"kind": "user", "email": "[email protected]"}
+ assert event["message"]["metadata"]["author"] == {
+ "kind": "user",
+ "email": "[email protected]",
+ }
+
+
+def test_show_event_store_keeps_remote_author_out_of_intent_fallback_text(isolated_state):
+ _seed_session()
+
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "human.intent.submitted",
+ "payload": {
+ "intent": "choose",
+ "author": {"kind": "user", "email": "[email protected]"},
+ },
+ },
+ author={"kind": "user", "email": "[email protected]"},
+ )
+ finally:
+ store.close()
+
+ assert event["payload"]["author"] == {"kind": "user", "email": "[email protected]"}
+ assert "[email protected]" not in event["transcript_text"]
+ assert "[email protected]" not in event["transcript_text"]
+ assert '"author"' not in event["transcript_text"]
+
+
+def test_annotation_control_event_has_no_transcript_or_dispatch(isolated_state):
+ from vibe.ui_server import _show_event_requests_dispatch
+
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ "ses_mark",
+ {
+ "type": "system.annotation.control",
+ "payload": {"action": "enable", "mode": "screenshot"},
+ },
+ )
+ finally:
+ store.close()
+
+ assert event["actor"] == "system"
+ assert event["payload"] == {"action": "enable", "mode": "screenshot"}
+ assert event["transcript_text"] == ""
+ assert event["message_id"] is None
+ assert event["message"] is None
+ assert _show_event_requests_dispatch(event) is False
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ assert conn.execute(select(show_session_events.c.id)).scalar_one() == event["id"]
+ assert conn.execute(select(messages.c.id)).first() is None
+
+
+ "control",
+ [
+ {"action": "toggle"},
+ {"action": "enable", "mode": "area"},
+ {"action": "set-mode"},
+ ],
+)
+def test_annotation_control_event_rejects_invalid_payload(isolated_state, control):
+ _seed_session()
+ store = ShowSessionEventStore()
+ try:
+ with pytest.raises(ShowSessionEventError) as exc_info:
+ store.append(
+ "ses_mark",
+ {"type": "system.annotation.control", "payload": control},
+ )
+ finally:
+ store.close()
+
+ assert exc_info.value.code == "invalid_payload"
def test_show_event_store_rejects_mismatched_session_id(isolated_state):
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 7baa2d899..c27890552 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -19,6 +19,8 @@ from core.show_pages import (
ShowPageStore,
ensure_show_page_dir,
show_cli_event_token,
+ show_event_write_token,
+ show_public_event_write_token,
)
from core.show_runtime import (
ShowRuntimeManager,
@@ -805,7 +807,10 @@ def test_private_show_page_injects_runtime_event_config(monkeypatch, tmp_path):
assert '"eventsPath":"/show/ses123/__show/events"' in body
assert '"streamPath":"/show/ses123/__show/events?stream=1"' in body
assert '"writeToken":"token-ses123"' in body
- assert body.index("globalThis.__AVIBE_SHOW__") < body.index('type="module"')
+ assert '"annotation":{"authenticated":true,"mePath":"__show/me"}' in body
+ assert '<script type="module" src="/show/ses123/__show/annotation.js"></script>' in body
+ assert body.index("globalThis.__AVIBE_SHOW__") < body.index('/src/main.tsx')
+ assert body.index('/src/main.tsx') < body.index('/show/ses123/__show/annotation.js')
assert "cookie" not in manager.calls[0][2]
assert response.headers["cache-control"] == "no-store"
assert "etag" not in response.headers
@@ -813,6 +818,72 @@ def test_private_show_page_injects_runtime_event_config(monkeypatch, tmp_path):
assert "last-modified" not in response.headers
[email protected]("authenticated", [False, True])
+def test_public_show_page_injects_auth_aware_annotation_config(monkeypatch, tmp_path, authenticated):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><html><head></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>'
+ )
+ set_show_runtime_manager_for_tests(manager)
+ client = app.test_client()
+ if authenticated:
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+ try:
+ response = client.get(
+ f"/p/{share_id}/",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ body = response.content.decode("utf-8")
+ base_path = f"/p/{share_id}/"
+ assert f'"sessionId":"{share_id}"' in body
+ assert '"sessionId":"ses123"' not in body
+ assert f'"basePath":"{base_path}"' in body
+ assert f'"eventsPath":"{base_path}__show/events"' in body
+ assert f'"streamPath":"{base_path}__show/events?stream=1"' in body
+ expected_auth = "true" if authenticated else "false"
+ assert f'"annotation":{{"authenticated":{expected_auth},"mePath":"__show/me"}}' in body
+ assert f'<script type="module" src="{base_path}__show/annotation.js"></script>' in body
+ assert '"writeToken"' not in body
+ assert body.index('/src/main.tsx') < body.index(f'{base_path}__show/annotation.js')
+ assert response.headers["Referrer-Policy"] == "same-origin"
+
+
[email protected]("surface", ["private", "public"])
+def test_show_annotation_bootstrap_asset_proxies_to_runtime(monkeypatch, tmp_path, surface):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ if surface == "private":
+ _create_show_page("ses123", "private")
+ path = "/show/ses123/__show/annotation.js"
+ else:
+ share_id = _create_show_page("ses123", "public")
+ path = f"/p/{share_id}/__show/annotation.js"
+ manager = _FakeShowRuntimeManager(
+ body=b"export const mounted = true;",
+ extra_headers={"content-type": "text/javascript", "cache-control": "no-cache"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(path, base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const mounted = true;"
+ assert manager.calls[0][1] == "/sessions/ses123/app/__show/annotation.js"
+
+
def test_private_show_page_does_not_inject_runtime_event_config_into_attachment_html(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1020,7 +1091,8 @@ def test_public_show_page_does_not_inject_write_runtime_config(monkeypatch, tmp_
assert response.status_code == 200
body = response.content.decode("utf-8")
- assert "globalThis.__AVIBE_SHOW__=Object.assign" not in body
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" in body
+ assert '"writeToken"' not in body
assert "token-ses123" not in body
@@ -1613,6 +1685,86 @@ 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_me_is_always_available(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+
+ response = app.test_client().get(
+ "/show/ses123/__show/me",
+ base_url="http://127.0.0.1:5123",
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "authenticated": True,
+ "canAnnotate": True,
+ "writeToken": show_event_write_token("ses123"),
+ }
+ assert response.headers["cache-control"] == "no-store, private"
+
+
+def test_public_show_me_is_anonymous_without_oauth_session(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+
+ response = app.test_client().get(
+ f"/p/{share_id}/__show/me",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {"authenticated": False, "canAnnotate": False}
+
+
+def test_public_show_me_accepts_valid_workbench_session(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get(
+ f"/p/{share_id}/__show/me",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "authenticated": True,
+ "canAnnotate": True,
+ "writeToken": show_public_event_write_token(share_id, "ses123"),
+ }
+ assert response.get_json()["writeToken"] != show_event_write_token("ses123")
+
+
+def test_public_show_me_treats_no_oauth_local_access_as_authenticated(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ share_id = _create_show_page("ses123", "public")
+
+ response = app.test_client().get(
+ f"/p/{share_id}/__show/me",
+ base_url="http://127.0.0.1:5123",
+ )
+
+ assert response.status_code == 200
+ assert response.get_json() == {
+ "authenticated": True,
+ "canAnnotate": True,
+ "writeToken": show_public_event_write_token(share_id, "ses123"),
+ }
+
+
def test_private_show_page_rejects_mismatched_event_session_id(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1688,6 +1840,38 @@ def test_private_show_page_dispatches_human_show_event(monkeypatch, tmp_path):
assert "show.dispatch" in [event_type for event_type, _data in published]
+def test_private_show_page_publishes_annotation_control_without_message_or_dispatch(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_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": "system.annotation.control",
+ "payload": {"action": "enable", "mode": "smart", "dispatch": True},
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ assert event["payload"] == {"action": "enable", "mode": "smart"}
+ assert event["message_id"] is None
+ assert event["transcript_text"] == ""
+ assert [event_type for event_type, _data in published] == ["show.event", "session.activity"]
+
+
def test_private_show_page_dispatches_screenshot_annotation_batch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1805,6 +1989,42 @@ def test_private_show_page_rejects_other_session_write_token(monkeypatch, tmp_pa
assert response.get_json()["code"] == "show_event_write_forbidden"
+def test_private_show_page_records_remote_oauth_author(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _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)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ "/show/ses123/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers={
+ "Origin": "https://alex.avibe.bot",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": token,
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Remote review."},
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ expected_author = {"kind": "user", "email": "[email protected]"}
+ assert event["payload"]["author"] == expected_author
+ assert event["message"]["metadata"]["author"] == expected_author
+
+
def test_private_show_page_sets_show_event_write_cookie(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2198,7 +2418,23 @@ def test_cli_show_event_ingress_rejects_configured_host_without_cli_token(monkey
assert response.status_code == 403
-def test_public_show_page_events_are_read_only(monkeypatch, tmp_path):
+def _public_show_write_headers(
+ share_id: str,
+ *,
+ origin: str = "https://alex.avibe.bot",
+ token_share_id: str | None = None,
+ token_session_id: str = "ses123",
+ referer_share_id: str | None = None,
+) -> dict[str, str]:
+ return {
+ "Origin": origin,
+ "Referer": f"{origin}/p/{referer_share_id or share_id}/",
+ "Content-Type": "application/json",
+ "X-Vibe-Show-Token": show_public_event_write_token(token_share_id or share_id, token_session_id),
+ }
+
+
+def test_public_show_page_events_require_login(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_create_agent_session("ses123")
@@ -2206,19 +2442,333 @@ def test_public_show_page_events_are_read_only(monkeypatch, tmp_path):
response = app.test_client().post(
f"/p/{share_id}/__show/events",
- base_url="http://127.0.0.1:5123",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
headers={
- "Origin": "http://127.0.0.1:5123",
+ "Origin": "https://alex.avibe.bot",
"Content-Type": "application/json",
},
json={
- "type": "assistant.mark.created",
- "mark": {"target": "summary", "body": "body"},
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Anonymous review."},
},
)
assert response.status_code == 403
- assert response.get_json()["code"] == "public_show_events_read_only"
+ assert response.get_json()["code"] == "public_show_events_login_required"
+
+
+def test_public_show_page_events_require_share_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers={
+ "Origin": "https://alex.avibe.bot",
+ "Referer": f"https://alex.avibe.bot/p/{share_id}/",
+ "Content-Type": "application/json",
+ },
+ json={
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Missing share token."},
+ },
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "show_event_write_forbidden"
+
+
+ "referer",
+ [None, "https://alex.avibe.bot/p/other-share/"],
+)
+def test_public_show_page_events_require_matching_share_referer(monkeypatch, tmp_path, referer):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+ headers = _public_show_write_headers(share_id)
+ if referer is None:
+ headers.pop("Referer")
+ else:
+ headers["Referer"] = referer
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=headers,
+ json={"type": "human.annotation.created", "annotation": {"comment": "Wrong page."}},
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "public_show_events_origin_mismatch"
+
+
+def test_public_show_page_events_reject_cross_share_token(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id, token_share_id="other-share"),
+ json={"type": "human.annotation.created", "annotation": {"comment": "Wrong token."}},
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "show_event_write_forbidden"
+
+
+def test_public_show_page_events_reject_token_from_previous_share_owner(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id, token_session_id="ses-previous"),
+ json={"type": "human.annotation.created", "annotation": {"comment": "Stale token."}},
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["code"] == "show_event_write_forbidden"
+
+
+def test_public_show_page_events_accept_oauth_user_and_record_author(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Authenticated review.",
+ "author": {"kind": "local"},
+ },
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ expected_author = {"kind": "user", "email": "[email protected]"}
+ assert event["payload"]["author"] == {"kind": "user"}
+ assert "session_id" not in event
+ assert "scope_id" not in event
+ assert "message_id" not in event
+ assert "message" not in event
+
+ assert published[0]["message"]["metadata"]["author"] == expected_author
+
+ listed = client.get(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ ).get_json()["events"][0]
+ assert listed["payload"]["author"] == {"kind": "user"}
+ assert "[email protected]" not in json.dumps(listed)
+
+
+def test_public_show_page_events_accept_injected_share_session_id(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "sessionId": share_id,
+ "type": "human.annotation.created",
+ "annotation": {"session_id": share_id, "comment": "Authenticated review."},
+ },
+ )
+
+ assert response.status_code == 201
+ assert "sessionId" not in published[0]["payload"]
+ assert "session_id" not in published[0]["payload"]
+
+
+def test_public_show_page_intent_fallback_does_not_expose_author_email(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={"type": "human.intent.submitted", "payload": {"intent": "choose"}},
+ )
+
+ assert response.status_code == 201
+ assert "[email protected]" not in response.content.decode("utf-8")
+ listed = client.get(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ assert "[email protected]" not in listed.content.decode("utf-8")
+
+
+def test_public_show_page_events_ignore_client_event_id_and_dispatch(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ dispatch_calls = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+ monkeypatch.setattr("vibe.ui_server._dispatch_show_event_if_requested", dispatch_calls.append)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={
+ "id": "forged\nid: injected",
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Review this.", "dispatch": True},
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ assert event["id"] != "forged\nid: injected"
+ assert "\n" not in event["id"]
+ assert "dispatch" not in event["payload"]
+ assert "dispatch" not in published[0]["payload"]
+ assert dispatch_calls == []
+
+
[email protected]("event_type", ["assistant.mark.created", "system.annotation.control"])
+def test_public_show_page_events_reject_non_human_types(monkeypatch, tmp_path, event_type):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-2"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.post(
+ f"/p/{share_id}/__show/events",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ headers=_public_show_write_headers(share_id),
+ json={"type": event_type, "payload": {"action": "enable"}},
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "unsupported_event_type"
+
+
+def test_public_show_page_events_accept_no_oauth_local_access(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ _create_agent_session("ses123")
+ share_id = _create_show_page("ses123", "public")
+ published = []
+ monkeypatch.setattr("vibe.ui_server._publish_show_session_event", published.append)
+
+ response = app.test_client().post(
+ f"/p/{share_id}/__show/events",
+ base_url="http://127.0.0.1:5123",
+ headers=_public_show_write_headers(share_id, origin="http://127.0.0.1:5123"),
+ json={
+ "type": "human.annotation.created",
+ "annotation": {"comment": "Local review."},
+ },
+ )
+
+ assert response.status_code == 201
+ event = response.get_json()["event"]
+ assert event["payload"]["author"] == {"kind": "local"}
+ assert "session_id" not in event
+ assert "scope_id" not in event
+ assert "message_id" not in event
+ assert "message" not in event
+ assert published[0]["message"]["metadata"]["author"] == {"kind": "local"}
def test_private_show_page_api_mutation_rejects_missing_origin(monkeypatch, tmp_path):
@@ -4352,5 +4902,6 @@ def test_public_show_page_passes_runtime_importmap_through_unmodified(monkeypatc
# the public-surface rewriter untouched (they are not under the `/show/<id>/` base).
assert f'<script type="importmap">{import_map}</script>' in text
assert '<link rel="stylesheet" href="/_show-runtime/vendor/abc123/index.css">' in text
- # Public pages never receive the private write-config injection.
- assert "globalThis.__AVIBE_SHOW__=Object.assign" not in text
+ # Public pages receive read/auth config but never the private write token.
+ assert "globalThis.__AVIBE_SHOW__=Object.assign" in text
+ assert '"writeToken"' not in text
diff --git a/vibe/cli.py b/vibe/cli.py
index e0ecf7e72..f2c2a4f08 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -873,6 +873,7 @@ def _show_examples_text() -> str:
update Switch visibility, set a custom public link, rotate share links, or take the page offline.
mark Add an assistant mark event to the session.
event Record a generic annotation-layer event.
+ annotate Control the page's annotation overlay.
Visibility:
private Authenticated Web UI URL under /show/<session-id>/.
@@ -888,6 +889,7 @@ def _show_examples_text() -> str:
vibe show update --session-id sesk8m4q2p7x --visibility offline
vibe show mark --session-id sesk8m4q2p7x --target mark-default-summary --body "Review this summary."
vibe show event --session-id sesk8m4q2p7x --event-json @./show-event.json --json
+ vibe show annotate --session-id sesk8m4q2p7x --on --mode screenshot
More:
vibe show list --help
@@ -896,6 +898,7 @@ def _show_examples_text() -> str:
vibe show update --help
vibe show mark --help
vibe show event --help
+ vibe show annotate --help
"""
)
@@ -980,6 +983,21 @@ def _show_event_examples_text() -> str:
)
+def _show_annotate_examples_text() -> str:
+ return dedent(
+ """\
+ Control the annotation overlay through the Show Page event stream.
+ Control events do not create transcript messages or dispatch Agent turns.
+
+ Examples:
+ vibe show annotate --session-id sesk8m4q2p7x --on
+ vibe show annotate --session-id sesk8m4q2p7x --on --mode screenshot
+ vibe show annotate --session-id sesk8m4q2p7x --mode smart
+ vibe show annotate --session-id sesk8m4q2p7x --off --json
+ """
+ )
+
+
def _print_json(payload: dict) -> None:
print(json.dumps(payload, indent=2))
@@ -10605,6 +10623,73 @@ def cmd_show_event(args):
event_store.close()
+def cmd_show_annotate(args):
+ from core.show_pages import ShowPageStore
+ from core.show_session_events import ShowSessionEventStore
+
+ page_store = ShowPageStore()
+ event_store = None
+ try:
+ session_id, session_default_notice = _resolve_show_session_id(
+ args,
+ help_command="vibe show annotate --help",
+ )
+ if not (args.annotation_on or args.annotation_off or args.mode):
+ raise TaskCliError(
+ "pass --on, --off, or --mode",
+ code="invalid_arguments",
+ help_command="vibe show annotate --help",
+ )
+ if args.annotation_off and args.mode:
+ raise TaskCliError(
+ "--off cannot be combined with --mode",
+ code="invalid_arguments",
+ help_command="vibe show annotate --help",
+ )
+
+ page, _created = page_store.ensure_active(session_id)
+ if args.annotation_on:
+ control = {"action": "enable", **({"mode": args.mode} if args.mode else {})}
+ elif args.annotation_off:
+ control = {"action": "disable"}
+ else:
+ control = {"action": "set-mode", "mode": args.mode}
+ payload = {"type": "system.annotation.control", "payload": control}
+ event = _post_show_event_to_live_ui(session_id, payload)
+ if event is None:
+ event_store = ShowSessionEventStore()
+ event = event_store.append(session_id, payload)
+
+ result = _show_page_result(
+ page,
+ message="Annotation control recorded.",
+ extra={
+ **({"session_default_notice": session_default_notice} if session_default_notice else {}),
+ "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("Annotation:")
+ print(f" Event: {event['id']}")
+ print(f" Action: {event['payload']['action']}")
+ if event["payload"].get("mode"):
+ print(f" Mode: {event['payload']['mode']}")
+ 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()
@@ -10621,6 +10706,8 @@ def cmd_show(args):
return cmd_show_mark(args)
if args.show_command == "event":
return cmd_show_event(args)
+ if args.show_command == "annotate":
+ return cmd_show_annotate(args)
raise TaskCliError(
"show command is required",
code="invalid_arguments",
@@ -11853,7 +11940,10 @@ 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,event}")
+ show_subparsers = show_parser.add_subparsers(
+ dest="show_command",
+ metavar="{list,path,status,update,mark,event,annotate}",
+ )
show_subparsers.required = False
show_list_parser = show_subparsers.add_parser(
@@ -11996,6 +12086,26 @@ def build_parser():
)
show_event_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")
+ show_annotate_parser = show_subparsers.add_parser(
+ "annotate",
+ help="Control the Show Page annotation overlay",
+ description="Enable, disable, or change the mode of the Show Page annotation overlay.",
+ epilog=_show_annotate_examples_text(),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe show annotate --help",
+ error_hint="Pass --on, --off, or --mode smart|screenshot.",
+ )
+ show_annotate_parser.add_argument("--session-id", help="Agent Session ID for the Show Page.")
+ annotate_toggle = show_annotate_parser.add_mutually_exclusive_group()
+ annotate_toggle.add_argument("--on", dest="annotation_on", action="store_true", help="Enable annotation.")
+ annotate_toggle.add_argument("--off", dest="annotation_off", action="store_true", help="Disable annotation.")
+ show_annotate_parser.add_argument(
+ "--mode",
+ choices=("smart", "screenshot"),
+ help="Set annotation mode; with --on, enable directly in this mode.",
+ )
+ show_annotate_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 7975d2fc4..d89fbfa3f 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -44,8 +44,9 @@ from core.show_pages import (
SHOW_PAGE_ICON_MAX_UPLOAD_BYTES,
show_cli_event_token,
show_event_write_token,
+ show_public_event_write_token,
)
-from core.show_session_events import show_event_payload_session_mismatch
+from core.show_session_events import HUMAN_EVENT_TYPES, show_event_payload_session_mismatch
from core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_id
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
from vibe.i18n import get_supported_languages, t
@@ -8214,9 +8215,15 @@ def _show_page_runtime_unavailable_response():
def _is_show_api_asset(asset_path: str) -> bool:
relative = (asset_path or "").strip("/")
+ if relative == "__show/annotation.js":
+ return False
return relative == "api" or relative.startswith("api/") or relative == "__show" or relative.startswith("__show/")
+def _is_show_annotation_asset(asset_path: str) -> bool:
+ return (asset_path or "").strip("/") == "__show/annotation.js"
+
+
def _is_show_page_entry_asset(asset_path: str) -> bool:
relative = (asset_path or "").strip("/")
return relative in {"", "index.html"}
@@ -8404,7 +8411,81 @@ def _show_event_write_authorized(session_id: str) -> bool:
return hmac.compare_digest(token, expected)
-def _show_event_response_from_payload(session_id: str, payload: dict[str, Any]):
+def _public_show_event_write_authorized(share_id: str, session_id: str) -> bool:
+ token = request.headers.get(SHOW_EVENT_WRITE_TOKEN_HEADER)
+ if not token:
+ return False
+ try:
+ expected = show_public_event_write_token(share_id, session_id)
+ except Exception:
+ return False
+ return hmac.compare_digest(token, expected)
+
+
+def _public_show_referer_matches(share_id: str) -> bool:
+ referer = request.headers.get("Referer")
+ if not referer:
+ return False
+ expected_path = f"/p/{quote(share_id, safe='')}/"
+ return urlsplit(referer).path.startswith(expected_path)
+
+
+def _sanitize_public_show_event_payload(payload: dict[str, Any]) -> dict[str, Any]:
+ sanitized = dict(payload)
+ for key in ("id", "dispatch", "sessionId", "session_id"):
+ sanitized.pop(key, None)
+ for key in ("payload", "annotation", "mark"):
+ nested = sanitized.get(key)
+ if isinstance(nested, dict):
+ sanitized[key] = {
+ nested_key: value
+ for nested_key, value in nested.items()
+ if nested_key not in {"dispatch", "sessionId", "session_id"}
+ }
+ return sanitized
+
+
+def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
+ from vibe import remote_access
+
+ config = _load_remote_access_config()
+ if config is not None:
+ session = remote_access.parse_session_cookie(
+ config,
+ request.cookies.get(remote_access.SESSION_COOKIE_NAME),
+ )
+ email = str(session.get("email", "")).strip() if session is not None else ""
+ if email:
+ return {"kind": "user", "email": email}
+
+ cloud = config.remote_access.vibe_cloud
+ if public and cloud.enabled:
+ return None
+
+ if public and not (_is_local_request(config) or _is_loopback_origin_proxy_request()):
+ return None
+ return {"kind": "local"}
+
+
+def _show_me_response(author: dict[str, str] | None, *, write_token: str | None = None):
+ authenticated = author is not None
+ payload = {"authenticated": authenticated, "canAnnotate": authenticated}
+ if authenticated and write_token:
+ payload["writeToken"] = write_token
+ response = jsonify(payload)
+ response.headers["Cache-Control"] = "no-store, private"
+ response.headers["Vary"] = "Cookie"
+ return response
+
+
+def _show_event_response_from_payload(
+ session_id: str,
+ payload: dict[str, Any],
+ *,
+ author: dict[str, str] | None = None,
+ public: bool = False,
+ allow_dispatch: bool = True,
+):
if show_event_payload_session_mismatch(session_id, payload):
return (
jsonify(
@@ -8418,15 +8499,16 @@ 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)
+ event_payload = store.append(session_id, payload, author=author)
except Exception as exc:
return _show_session_event_error_response(exc)
finally:
store.close()
_publish_show_session_event(event_payload)
- _dispatch_show_event_if_requested(event_payload)
- return jsonify({"ok": True, "event": event_payload}), 201
+ if allow_dispatch:
+ _dispatch_show_event_if_requested(event_payload)
+ return jsonify({"ok": True, "event": _show_event_response_payload(event_payload, public=public)}), 201
def record_local_show_event(session_id: str, payload: dict[str, Any], *, dispatch_sync: bool = False) -> dict[str, Any]:
@@ -8539,11 +8621,19 @@ def _publish_show_dispatch_event(event_payload: dict[str, Any], event_name: str,
def _show_event_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
if not public:
return event_payload
- return {
+ public_event = {
key: value
for key, value in event_payload.items()
if key not in {"session_id", "scope_id", "message_id", "message"}
}
+ payload = public_event.get("payload")
+ if isinstance(payload, dict):
+ public_payload = dict(payload)
+ author = public_payload.get("author")
+ if isinstance(author, dict) and "email" in author:
+ public_payload["author"] = {key: value for key, value in author.items() if key != "email"}
+ public_event["payload"] = public_payload
+ return public_event
def _show_dispatch_response_payload(event_payload: dict[str, Any], *, public: bool = False) -> dict[str, Any]:
@@ -8671,7 +8761,11 @@ async def _show_events_response(session_id: str, *, public: bool = False):
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())
+ return _show_event_response_from_payload(
+ session_id,
+ _show_events_payload_from_request(),
+ author=_show_request_author(),
+ )
@app.route("/api/show/sessions/<session_id>/events", methods=["POST"])
@@ -8840,7 +8934,9 @@ async def _show_page_runtime_response(
starlette_request: FastAPIRequest,
*,
external_prefix: str | None = None,
- inject_private_config: bool = False,
+ inject_show_config: bool = False,
+ show_authenticated: bool = False,
+ show_config_session_id: str | None = None,
):
from core.show_runtime import get_show_runtime_manager
@@ -8904,8 +9000,21 @@ async def _show_page_runtime_response(
external_prefix=external_prefix,
)
content = _rewrite_public_show_runtime_client(content, response_headers, external_prefix=external_prefix)
- if _should_inject_show_runtime_config(proxied.status_code, response_headers, inject_private_config=inject_private_config):
- content = _inject_show_runtime_config(content, session_id)
+ if _should_inject_show_runtime_config(
+ proxied.status_code,
+ response_headers,
+ inject_show_config=inject_show_config,
+ ):
+ base_path = f"{external_prefix.rstrip('/')}/" if external_prefix else f"/show/{quote(session_id, safe='')}/"
+ content = _inject_show_runtime_config(
+ content,
+ show_config_session_id or session_id,
+ base_path=base_path,
+ authenticated=show_authenticated,
+ include_write_token=external_prefix is None,
+ )
+ if external_prefix:
+ response_headers["Referrer-Policy"] = "same-origin"
_mark_show_runtime_document_no_store(response_headers)
elif _is_show_page_entry_asset(asset_path) and 200 <= proxied.status_code < 300:
# The entry document is per-session/per-share dynamic (it embeds the import map
@@ -8920,9 +9029,9 @@ def _should_inject_show_runtime_config(
status_code: int,
headers: dict[str, str],
*,
- inject_private_config: bool,
+ inject_show_config: bool,
) -> bool:
- if not inject_private_config or status_code != 200:
+ if not inject_show_config or status_code != 200:
return False
if _show_response_is_attachment(_response_header(headers, "content-disposition")):
return False
@@ -9163,20 +9272,46 @@ def _show_response_is_attachment(content_disposition: str | None) -> bool:
return bool(content_disposition and content_disposition.lstrip().lower().startswith("attachment"))
-def _show_runtime_config_payload(session_id: str) -> dict[str, str]:
- session_path = quote(session_id, safe="")
- events_path = f"/show/{session_path}/__show/events"
- return {
+def _show_runtime_config_payload(
+ session_id: str,
+ *,
+ base_path: str,
+ authenticated: bool,
+ include_write_token: bool,
+) -> dict[str, Any]:
+ events_path = f"{base_path}__show/events"
+ payload: dict[str, Any] = {
"sessionId": session_id,
- "basePath": f"/show/{session_path}/",
+ "basePath": base_path,
"eventsPath": events_path,
"streamPath": f"{events_path}?stream=1",
- "writeToken": show_event_write_token(session_id),
+ "annotation": {
+ "authenticated": authenticated,
+ "mePath": "__show/me",
+ },
}
+ if include_write_token:
+ payload["writeToken"] = show_event_write_token(session_id)
+ return payload
-def _show_runtime_config_script(session_id: str) -> str:
- payload = json.dumps(_show_runtime_config_payload(session_id), ensure_ascii=False, separators=(",", ":"))
+def _show_runtime_config_script(
+ session_id: str,
+ *,
+ base_path: str,
+ authenticated: bool,
+ include_write_token: bool,
+) -> str:
+ payload = json.dumps(
+ _show_runtime_config_payload(
+ session_id,
+ base_path=base_path,
+ authenticated=authenticated,
+ include_write_token=include_write_token,
+ ),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
payload = payload.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
return (
"<script>"
@@ -9188,12 +9323,25 @@ def _show_runtime_config_script(session_id: str) -> str:
)
-def _inject_show_runtime_config(content: bytes, session_id: str) -> bytes:
+def _inject_show_runtime_config(
+ content: bytes,
+ session_id: str,
+ *,
+ base_path: str,
+ authenticated: bool,
+ include_write_token: bool,
+) -> bytes:
try:
html = content.decode("utf-8")
except UnicodeDecodeError:
return content
- script = _show_runtime_config_script(session_id)
+ script = _show_runtime_config_script(
+ session_id,
+ base_path=base_path,
+ authenticated=authenticated,
+ include_write_token=include_write_token,
+ )
+ bootstrap = f'<script type="module" src="{base_path}__show/annotation.js"></script>'
module_match = _SHOW_RUNTIME_MODULE_SCRIPT_RE.search(html)
if module_match:
html = f"{html[: module_match.start()]}{script}\n {html[module_match.start() :]}"
@@ -9203,6 +9351,12 @@ def _inject_show_runtime_config(content: bytes, session_id: str) -> bytes:
html = html.replace("</body>", f"{script}\n </body>", 1)
else:
html = f"{script}\n{html}"
+ if "</body>" in html:
+ html = html.replace("</body>", f"{bootstrap}\n </body>", 1)
+ elif "</html>" in html:
+ html = html.replace("</html>", f"{bootstrap}\n</html>", 1)
+ else:
+ html = f"{html}\n{bootstrap}"
return html.encode("utf-8")
@@ -9322,6 +9476,13 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_not_found_response()
if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):
return _show_page_file_not_found_response()
+ if asset_path.strip("/") == "__show/me":
+ if request.method not in {"GET", "HEAD"}:
+ return jsonify({"ok": False, "code": "method_not_allowed"}), 405
+ return _show_me_response(
+ {"kind": "local"},
+ write_token=show_event_write_token(page.session_id),
+ )
if asset_path.strip("/") in {"__show/events", "__events"}:
return await _show_events_response(page.session_id)
page_dir = ensure_show_page_dir(page.session_id)
@@ -9333,10 +9494,11 @@ async def serve_private_show_page(session_id, asset_path):
page.session_id,
asset_path,
starlette_request,
- inject_private_config=request.method == "GET" and not _is_show_api_asset(asset_path),
+ inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),
+ show_authenticated=True,
)
except Exception:
- if _is_show_api_asset(asset_path):
+ if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
return _show_page_runtime_unavailable_response()
if _is_show_page_entry_asset(asset_path):
response = _show_page_recovery_response(page.session_id)
@@ -9393,10 +9555,47 @@ async def serve_public_show_page(share_id, asset_path):
return _show_page_not_found_response()
if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id, public=True):
return _show_page_file_not_found_response()
+ if asset_path.strip("/") == "__show/me":
+ if request.method not in {"GET", "HEAD"}:
+ return jsonify({"ok": False, "code": "method_not_allowed"}), 405
+ author = _show_request_author(public=True)
+ return _show_me_response(
+ author,
+ write_token=(
+ show_public_event_write_token(share_id, page.session_id) if author is not None else None
+ ),
+ )
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)
+ if request.method == "GET":
+ return await _show_events_response(page.session_id, public=True)
+ if request.method != "POST":
+ return jsonify({"ok": False, "code": "method_not_allowed"}), 405
+ author = _show_request_author(public=True)
+ if author is None:
+ return jsonify({"ok": False, "code": "public_show_events_login_required"}), 403
+ if not _public_show_referer_matches(share_id):
+ return jsonify({"ok": False, "code": "public_show_events_origin_mismatch"}), 403
+ if not _public_show_event_write_authorized(share_id, page.session_id):
+ return jsonify({"ok": False, "code": "show_event_write_forbidden"}), 403
+ payload = _sanitize_public_show_event_payload(_show_events_payload_from_request())
+ if str(payload.get("type") or "").strip() not in HUMAN_EVENT_TYPES:
+ return (
+ jsonify(
+ {
+ "ok": False,
+ "code": "unsupported_event_type",
+ "error": "Public Show Page writes require a supported human event type.",
+ }
+ ),
+ 400,
+ )
+ return _show_event_response_from_payload(
+ page.session_id,
+ payload,
+ author=author,
+ public=True,
+ allow_dispatch=False,
+ )
if request.method in {"GET", "HEAD"}:
if shim_response := _show_runtime_public_client_shim_response(asset_path):
return shim_response
@@ -9410,9 +9609,12 @@ async def serve_public_show_page(share_id, asset_path):
asset_path,
starlette_request,
external_prefix=f"/p/{quote(share_id, safe='')}",
+ inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),
+ show_authenticated=_show_request_author(public=True) is not None,
+ show_config_session_id=share_id,
)
except Exception:
- if _is_show_api_asset(asset_path):
+ if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
return _show_page_runtime_unavailable_response()
if _is_show_page_entry_asset(asset_path):
response = _show_page_recovery_response(page.session_id)