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 local unified access settings (#1501)

Maxf67b3c821cef
diff --git a/core/internal_server.py b/core/internal_server.py
index 4d4bfd142..bcc50f88b 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -202,6 +202,8 @@ def create_app(
# ``manager.cancel`` / ``manager.send_now``), not in side sets here.
in_flight = manager.in_flight
app.state.in_flight_dispatches = in_flight
+ show_access_write_lock = asyncio.Lock()
+ app.state.show_access_write_lock = show_access_write_lock
def _publish_scheduled_queue_growth(session_id: str, state: str) -> None:
if state != "queued":
@@ -612,6 +614,115 @@ def create_app(
async def _health() -> dict[str, Any]:
return {"ok": True, "service": "vibe-remote-internal", "version": 1}
+ @app.post("/internal/show-access/settings-read")
+ async def _show_access_settings_read(request: Request) -> Any:
+ from core.show_pages import ShowPageError, ShowPageStore, show_access_payload
+
+ payload = await _safe_json(request)
+ if set(payload) != {"page_id"} or not isinstance(payload.get("page_id"), str):
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "invalid_show_access_settings_request"},
+ )
+ page_id = payload["page_id"]
+
+ def _read() -> dict[str, Any]:
+ store = ShowPageStore()
+ try:
+ show_access = store.get_access(page_id)
+ finally:
+ store.close()
+ if show_access is None:
+ raise ShowPageError(
+ "This session has no Show Page.",
+ code="show_page_not_found",
+ )
+ if show_access.page_id != page_id:
+ raise RuntimeError("show_access_page_identity_mismatch")
+ return {"show_access": show_access_payload(show_access)}
+
+ try:
+ return await asyncio.to_thread(_read)
+ except ShowPageError as exc:
+ status = 404 if exc.code == "show_page_not_found" else 400
+ return JSONResponse(
+ status_code=status,
+ content={"ok": False, "error": exc.code},
+ )
+ except Exception:
+ logger.exception("internal ShowAccess settings read failed")
+ return JSONResponse(
+ status_code=500,
+ content={"ok": False, "error": "show_access_internal_failure"},
+ )
+
+ @app.post("/internal/show-access/apply")
+ async def _show_access_apply(request: Request) -> Any:
+ from core.show_pages import ShowPageError, ShowPageStore, show_access_payload
+
+ payload = await _safe_json(request)
+ required = {
+ "page_id",
+ "expected_revision",
+ "target_access_mode",
+ "target_share_id",
+ "target_emails",
+ }
+ if (
+ set(payload) != required
+ or not isinstance(payload.get("page_id"), str)
+ or isinstance(payload.get("expected_revision"), bool)
+ or not isinstance(payload.get("expected_revision"), int)
+ or payload["expected_revision"] < 0
+ or not isinstance(payload.get("target_access_mode"), str)
+ or not (
+ payload.get("target_share_id") is None
+ or isinstance(payload.get("target_share_id"), str)
+ )
+ or not isinstance(payload.get("target_emails"), list)
+ or any(not isinstance(email, str) for email in payload["target_emails"])
+ ):
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "invalid_show_access_apply_request"},
+ )
+ page_id = payload["page_id"]
+
+ def _apply() -> dict[str, Any]:
+ store = ShowPageStore()
+ try:
+ result = store.apply_access(
+ page_id,
+ expected_revision=payload["expected_revision"],
+ target_access_mode=payload["target_access_mode"],
+ target_share_id=payload["target_share_id"],
+ target_emails=payload["target_emails"],
+ )
+ finally:
+ store.close()
+ if result.show_access.page_id != page_id:
+ raise RuntimeError("show_access_page_identity_mismatch")
+ return {
+ "status": result.status,
+ "show_access": show_access_payload(result.show_access),
+ }
+
+ try:
+ async with show_access_write_lock:
+ return await asyncio.to_thread(_apply)
+ except ShowPageError as exc:
+ status = 404 if exc.code == "show_page_not_found" else 400
+ return JSONResponse(
+ status_code=status,
+ content={"ok": False, "error": exc.code},
+ )
+ except Exception:
+ logger.exception("internal ShowAccess apply failed")
+ return JSONResponse(
+ status_code=500,
+ content={"ok": False, "error": "show_access_internal_failure"},
+ )
+
@app.get("/internal/turn-state/{session_id}")
async def _turn_state(session_id: str) -> Any:
"""HTTP adapter: whether a turn is running, delegated to the turn owner
diff --git a/core/show_pages.py b/core/show_pages.py
index d345b6b92..8c4c1bc3a 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -13,7 +13,7 @@ from pathlib import Path
from typing import Any
from urllib.parse import unquote, urljoin, urlsplit
-from sqlalchemy import insert, or_, select, update
+from sqlalchemy import delete, insert, or_, select, update
from sqlalchemy.engine import Connection
from sqlalchemy.exc import IntegrityError
@@ -23,13 +23,24 @@ from core.avibe_cloud import avibe_cloud_connect_guidance, base_public_url
from core.show_git import format_agent_contract
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
-from storage.models import agent_sessions, show_pages
+from storage.models import agent_sessions, show_page_authorized_emails, show_pages
from storage.pagination import PageRequest, PageResult, page_sequence
VISIBILITY_PRIVATE = "private"
+VISIBILITY_LIMITED = "limited"
VISIBILITY_PUBLIC = "public"
VISIBILITY_OFFLINE = "offline"
-VISIBILITIES = {VISIBILITY_PRIVATE, VISIBILITY_PUBLIC, VISIBILITY_OFFLINE}
+VISIBILITIES = {
+ VISIBILITY_PRIVATE,
+ VISIBILITY_LIMITED,
+ VISIBILITY_PUBLIC,
+ VISIBILITY_OFFLINE,
+}
+ACCESS_MODE_PRIVATE = "private"
+ACCESS_MODE_LIMITED = "limited"
+ACCESS_MODE_PUBLIC = "public"
+ACCESS_MODES = {ACCESS_MODE_PRIVATE, ACCESS_MODE_LIMITED, ACCESS_MODE_PUBLIC}
+SHOW_ACCESS_EMAIL_MAX_COUNT = 64
SHARE_ID_BYTES = 8
SHOW_EVENT_WRITE_TOKEN_COOKIE = "vibe_show_event_token"
SHOW_EVENT_WRITE_TOKEN_HEADER = "X-Vibe-Show-Token"
@@ -60,6 +71,16 @@ SHOW_PAGE_ICON_CONTENT_TYPES: dict[str, str] = {
"gif": "image/gif",
}
_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
+_EMAIL_ATOM = r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+"
+_DNS_LABEL = r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"
+_NORMALIZED_EMAIL_PATTERN = re.compile(
+ rf"^{_EMAIL_ATOM}(?:\.{_EMAIL_ATOM})*@{_DNS_LABEL}(?:\.{_DNS_LABEL})*$"
+)
+_ASCII_SURROUNDING_WHITESPACE = " \t\r\n\f\v"
+_ASCII_LOWER_TRANSLATION = str.maketrans(
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
+ "abcdefghijklmnopqrstuvwxyz",
+)
# A custom public share suffix lands directly in the ``/p/<share_id>/`` URL, so
# keep it to URL-safe slug characters: start and end alphanumeric, with dash and
# underscore allowed in between. 3–64 chars balances "memorable" against trivial
@@ -79,7 +100,8 @@ class ShowPageError(ValueError):
@dataclass(frozen=True)
class ShowPage:
session_id: str
- visibility: str
+ access_mode: str
+ access_revision: int
share_id: str | None
offline_at: str | None
created_at: str
@@ -87,7 +109,28 @@ class ShowPage:
@property
def offline(self) -> bool:
- return self.visibility == VISIBILITY_OFFLINE
+ return self.offline_at is not None
+
+ @property
+ def visibility(self) -> str:
+ """Compatibility projection for callers not yet migrated to ShowAccess."""
+
+ return VISIBILITY_OFFLINE if self.offline else self.access_mode
+
+
+@dataclass(frozen=True)
+class ShowAccess:
+ page_id: str
+ access_mode: str
+ share_id: str | None
+ revision: int
+ normalized_emails: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class ShowAccessApplyResult:
+ status: str
+ show_access: ShowAccess
def get_show_page_resource_metadata(connection: Connection, session_id: str) -> dict[str, str] | None:
@@ -144,6 +187,42 @@ def validate_share_id(share_id: str) -> str:
return value
+def normalize_show_access_email(raw: str) -> str:
+ if not isinstance(raw, str):
+ raise ShowPageError("Invalid Show Page email.", code="invalid_email")
+ value = raw.strip(_ASCII_SURROUNDING_WHITESPACE).translate(
+ _ASCII_LOWER_TRANSLATION
+ )
+ if (
+ len(value) > 320
+ or not value
+ or _NORMALIZED_EMAIL_PATTERN.fullmatch(value) is None
+ ):
+ raise ShowPageError("Invalid Show Page email.", code="invalid_email")
+ return value
+
+
+def normalize_show_access_emails(emails: list[str] | tuple[str, ...]) -> tuple[str, ...]:
+ if not isinstance(emails, (list, tuple)):
+ raise ShowPageError("Invalid Show Page email list.", code="invalid_email")
+ if len(emails) > SHOW_ACCESS_EMAIL_MAX_COUNT:
+ raise ShowPageError(
+ f"A Show Page may grant access to at most {SHOW_ACCESS_EMAIL_MAX_COUNT} emails.",
+ code="invalid_email",
+ )
+ return tuple(sorted({normalize_show_access_email(email) for email in emails}))
+
+
+def show_access_payload(show_access: ShowAccess) -> dict[str, Any]:
+ return {
+ "page_id": show_access.page_id,
+ "access_mode": show_access.access_mode,
+ "share_id": show_access.share_id,
+ "revision": show_access.revision,
+ "normalized_emails": list(show_access.normalized_emails),
+ }
+
+
def show_page_dir(session_id: str) -> Path:
return paths.get_show_page_dir(validate_session_id(session_id))
@@ -206,7 +285,10 @@ def _utc_now_iso() -> str:
def _new_share_id() -> str:
- return secrets.token_urlsafe(SHARE_ID_BYTES).rstrip("_-")
+ while True:
+ candidate = secrets.token_urlsafe(SHARE_ID_BYTES).strip("_-")
+ if _SHARE_ID_PATTERN.fullmatch(candidate):
+ return candidate
def _like_pattern(value: str, *, prefix: bool = False, contains: bool = False) -> str:
@@ -257,7 +339,7 @@ def require_show_page_sharing_control(
*,
user_context: Any = None,
) -> None:
- """Require resource-owner authority for anonymous publication changes."""
+ """Require resource-owner authority for shared-audience changes."""
from storage import resource_access_service
@@ -328,6 +410,190 @@ class ShowPageStore:
row = conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1)).mappings().first()
return _page_from_row(row) if row else None
+ def get_access(self, page_id: str) -> ShowAccess | None:
+ page_id = validate_session_id(page_id)
+ with self.engine.connect() as conn:
+ row = (
+ conn.execute(
+ select(show_pages)
+ .where(show_pages.c.session_id == page_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ return _show_access_from_row(conn, row) if row else None
+
+ def require_access_settings(
+ self,
+ page_id: str,
+ *,
+ user_context: Any = None,
+ ) -> ShowAccess:
+ page_id = validate_session_id(page_id)
+ context = _resolve_resource_access_context(user_context)
+ with self.engine.connect() as conn:
+ row = (
+ conn.execute(
+ select(show_pages)
+ .where(show_pages.c.session_id == page_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ raise ShowPageError(
+ "This session has no Show Page.",
+ code="show_page_not_found",
+ )
+ self._require_sharing_control(conn, page_id, context)
+ return _show_access_from_row(conn, row)
+
+ def apply_access(
+ self,
+ page_id: str,
+ *,
+ expected_revision: int,
+ target_access_mode: str,
+ target_share_id: str | None,
+ target_emails: list[str] | tuple[str, ...],
+ user_context: Any = None,
+ ) -> ShowAccessApplyResult:
+ page_id = validate_session_id(page_id)
+ context = _resolve_resource_access_context(user_context)
+ current = self.require_access_settings(page_id, user_context=context)
+
+ try:
+ if (
+ isinstance(expected_revision, bool)
+ or not isinstance(expected_revision, int)
+ or expected_revision < 0
+ ):
+ raise ShowPageError("Invalid ShowAccess revision.", code="invalid_revision")
+ if target_access_mode not in ACCESS_MODES:
+ raise ShowPageError("Invalid ShowAccess mode.", code="invalid_access_mode")
+ normalized_share_id = (
+ validate_share_id(target_share_id)
+ if target_share_id is not None
+ else None
+ )
+ if target_access_mode == ACCESS_MODE_PRIVATE and normalized_share_id is None:
+ normalized_share_id = current.share_id
+ normalized_emails = normalize_show_access_emails(target_emails)
+ if target_access_mode == ACCESS_MODE_LIMITED:
+ if normalized_share_id is None or not normalized_emails:
+ raise ShowPageError(
+ "Limited ShowAccess requires a share ID and at least one email.",
+ code="invalid_show_access",
+ )
+ elif normalized_emails:
+ raise ShowPageError(
+ "Only Limited ShowAccess may contain emails.",
+ code="invalid_show_access",
+ )
+ if target_access_mode == ACCESS_MODE_PUBLIC and normalized_share_id is None:
+ raise ShowPageError(
+ "Public ShowAccess requires a share ID.",
+ code="invalid_show_access",
+ )
+ except (ShowPageError, TypeError):
+ return ShowAccessApplyResult(status="invalid", show_access=current)
+
+ status = "applied"
+ now = _utc_now_iso()
+ try:
+ with self.engine.begin() as conn:
+ row = (
+ conn.execute(
+ select(show_pages)
+ .where(show_pages.c.session_id == page_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ raise ShowPageError(
+ "This session has no Show Page.",
+ code="show_page_not_found",
+ )
+ self._require_sharing_control(conn, page_id, context)
+ current = _show_access_from_row(conn, row)
+ if current.revision != expected_revision:
+ return ShowAccessApplyResult(
+ status="conflict",
+ show_access=current,
+ )
+ canonical_target = (
+ target_access_mode,
+ normalized_share_id,
+ normalized_emails,
+ )
+ canonical_current = (
+ current.access_mode,
+ current.share_id,
+ current.normalized_emails,
+ )
+ if canonical_target == canonical_current:
+ return ShowAccessApplyResult(
+ status="no_change",
+ show_access=current,
+ )
+ archived = conn.execute(
+ select(agent_sessions.c.status)
+ .where(agent_sessions.c.id == page_id)
+ .limit(1)
+ ).scalar_one_or_none()
+ if archived == "archived":
+ return ShowAccessApplyResult(
+ status="invalid",
+ show_access=current,
+ )
+ result = conn.execute(
+ update(show_pages)
+ .where(
+ show_pages.c.session_id == page_id,
+ show_pages.c.access_revision == expected_revision,
+ )
+ .values(
+ access_mode=target_access_mode,
+ share_id=normalized_share_id,
+ access_revision=expected_revision + 1,
+ updated_at=now,
+ )
+ )
+ if not result.rowcount:
+ status = "conflict"
+ else:
+ conn.execute(
+ delete(show_page_authorized_emails).where(
+ show_page_authorized_emails.c.session_id == page_id
+ )
+ )
+ if normalized_emails:
+ conn.execute(
+ insert(show_page_authorized_emails),
+ [
+ {
+ "session_id": page_id,
+ "normalized_email": email,
+ "created_at": now,
+ }
+ for email in normalized_emails
+ ],
+ )
+ except IntegrityError:
+ status = "share_id_taken"
+
+ latest = self.get_access(page_id)
+ if latest is None:
+ raise ShowPageError(
+ "This session has no Show Page.",
+ code="show_page_not_found",
+ )
+ return ShowAccessApplyResult(status=status, show_access=latest)
+
def get_by_share_id(self, share_id: str) -> ShowPage | None:
share_id = (share_id or "").strip()
if not share_id:
@@ -392,7 +658,13 @@ class ShowPageStore:
raise ShowPageError(f"Unsupported visibility: {visibility}", code="invalid_visibility")
statement = select(show_pages)
if visibility is not None:
- statement = statement.where(show_pages.c.visibility == visibility)
+ if visibility == VISIBILITY_OFFLINE:
+ statement = statement.where(show_pages.c.offline_at.is_not(None))
+ else:
+ statement = statement.where(
+ show_pages.c.offline_at.is_(None),
+ show_pages.c.access_mode == visibility,
+ )
if session_id:
statement = statement.where(show_pages.c.session_id.like(_like_pattern(session_id, prefix=True), escape=_LIKE_ESCAPE))
if updated_after:
@@ -401,13 +673,14 @@ class ShowPageStore:
statement = statement.where(show_pages.c.updated_at <= updated_before)
if query:
pattern = _like_pattern(query, contains=True)
- statement = statement.where(
- or_(
- show_pages.c.session_id.like(pattern, escape=_LIKE_ESCAPE),
- show_pages.c.share_id.like(pattern, escape=_LIKE_ESCAPE),
- show_pages.c.visibility.like(pattern, escape=_LIKE_ESCAPE),
- )
- )
+ clauses = [
+ show_pages.c.session_id.like(pattern, escape=_LIKE_ESCAPE),
+ show_pages.c.share_id.like(pattern, escape=_LIKE_ESCAPE),
+ show_pages.c.access_mode.like(pattern, escape=_LIKE_ESCAPE),
+ ]
+ if query.lower() in VISIBILITY_OFFLINE:
+ clauses.append(show_pages.c.offline_at.is_not(None))
+ statement = statement.where(or_(*clauses))
statement = statement.order_by(show_pages.c.updated_at.desc(), show_pages.c.session_id.asc())
with self.engine.connect() as conn:
rows = conn.execute(statement).mappings().all()
@@ -509,8 +782,9 @@ class ShowPageStore:
now = _utc_now_iso()
page = ShowPage(
session_id=session_id,
- visibility=VISIBILITY_PRIVATE,
- share_id=None,
+ access_mode=ACCESS_MODE_PRIVATE,
+ access_revision=0,
+ share_id=self._unique_share_id(),
offline_at=None,
created_at=now,
updated_at=now,
@@ -530,7 +804,8 @@ class ShowPageStore:
conn.execute(
insert(show_pages).values(
session_id=page.session_id,
- visibility=page.visibility,
+ access_mode=page.access_mode,
+ access_revision=page.access_revision,
share_id=page.share_id,
offline_at=page.offline_at,
created_at=page.created_at,
@@ -581,27 +856,41 @@ class ShowPageStore:
"Cannot create a Show Page for an archived session.",
code="session_archived",
)
- result = conn.execute(
- insert(show_pages)
- .prefix_with("OR IGNORE")
- .values(
- session_id=session_id,
- visibility=VISIBILITY_PRIVATE,
- share_id=None,
- offline_at=None,
- created_at=now,
- updated_at=now,
+ created = False
+ row = None
+ for _ in range(20):
+ result = conn.execute(
+ insert(show_pages)
+ .prefix_with("OR IGNORE")
+ .values(
+ session_id=session_id,
+ access_mode=ACCESS_MODE_PRIVATE,
+ access_revision=0,
+ share_id=_new_share_id(),
+ offline_at=None,
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ created = bool(result.rowcount and result.rowcount > 0)
+ row = (
+ conn.execute(
+ select(show_pages)
+ .where(show_pages.c.session_id == session_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is not None:
+ break
+ if row is None:
+ raise ShowPageError(
+ "Could not allocate a unique share ID.",
+ code="share_id_allocation_failed",
)
- )
- created = bool(result.rowcount and result.rowcount > 0)
if created:
self._register_created_resource_policy(conn, session_id, context)
- row = (
- conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))
- .mappings()
- .first()
- )
- assert row is not None
self._require_resource_access(conn, session_id, context)
return _page_from_row(row), created
@@ -615,15 +904,87 @@ class ShowPageStore:
).scalar_one_or_none()
return status == "archived"
+ def set_offline(
+ self,
+ session_id: str,
+ offline: bool,
+ *,
+ user_context: Any = None,
+ ) -> ShowPage:
+ """Change operational availability without changing ShowAccess."""
+
+ session_id = validate_session_id(session_id)
+ context = _resolve_resource_access_context(user_context)
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ row = (
+ conn.execute(
+ select(show_pages)
+ .where(show_pages.c.session_id == session_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ if row is None:
+ raise ShowPageError(
+ "This session has no Show Page.",
+ code="show_page_not_found",
+ )
+ current_visibility = (
+ VISIBILITY_OFFLINE
+ if row["offline_at"] is not None
+ else str(row["access_mode"])
+ )
+ target_visibility = (
+ VISIBILITY_OFFLINE if offline else str(row["access_mode"])
+ )
+ self._require_visibility_transition_control(
+ conn,
+ session_id,
+ context,
+ current_visibility=current_visibility,
+ target_visibility=target_visibility,
+ )
+ if not offline:
+ status = conn.execute(
+ select(agent_sessions.c.status)
+ .where(agent_sessions.c.id == session_id)
+ .limit(1)
+ ).scalar_one_or_none()
+ if status == "archived":
+ raise ShowPageError(
+ "Cannot bring back the Show Page of an archived session.",
+ code="session_archived",
+ )
+ target_offline_at = (row["offline_at"] or now) if offline else None
+ if target_offline_at != row["offline_at"]:
+ conn.execute(
+ update(show_pages)
+ .where(show_pages.c.session_id == session_id)
+ .values(offline_at=target_offline_at, updated_at=now)
+ )
+ updated = self.get(session_id)
+ assert updated is not None
+ return updated
+
def update_visibility(self, session_id: str, visibility: str, *, user_context: Any = None) -> ShowPage:
+ """Compatibility adapter over orthogonal availability and ShowAccess.
+
+ New audience callers use :meth:`apply_access`. The legacy CLI still uses
+ this adapter, but Web callers have no second audience write path.
+ """
+
session_id = validate_session_id(session_id)
context = _resolve_resource_access_context(user_context)
- if visibility not in VISIBILITIES:
+ if visibility not in {
+ VISIBILITY_PRIVATE,
+ VISIBILITY_PUBLIC,
+ VISIBILITY_OFFLINE,
+ }:
raise ShowPageError(f"Unsupported visibility: {visibility}", code="invalid_visibility")
existing = self.get(session_id)
if existing is not None:
- # Check management before reporting a terminal lifecycle state so an
- # unauthorized remote user cannot probe page/session details.
with self.engine.connect() as conn:
self._require_visibility_transition_control(
conn,
@@ -635,10 +996,6 @@ class ShowPageStore:
page = existing
else:
page = None
- # Reject republish BEFORE ``ensure`` so it doesn't first materialize a
- # default (private) page row for an archived session — that would leave
- # ``/show/<id>/`` enabled for a terminal session. The in-txn check below
- # is the atomic authority for the concurrent-archive race.
if visibility != VISIBILITY_OFFLINE and self.is_archived(session_id):
raise ShowPageError(
"Cannot republish the Show Page of an archived session.",
@@ -646,83 +1003,81 @@ class ShowPageStore:
)
if page is None:
page = self.ensure(session_id, user_context=context)
- now = _utc_now_iso()
- values: dict[str, Any] = {
- "visibility": visibility,
- "updated_at": now,
- "offline_at": now if visibility == VISIBILITY_OFFLINE else None,
- }
- if visibility == VISIBILITY_PUBLIC and not page.share_id:
- values["share_id"] = self._unique_share_id()
- with self.engine.begin() as conn:
- current_visibility = conn.execute(
- select(show_pages.c.visibility).where(show_pages.c.session_id == session_id)
- ).scalar_one()
- # Re-evaluate against the in-transaction row so a concurrent transition
- # to offline cannot turn an access-manager operation into a republish.
- self._require_visibility_transition_control(
- conn,
+
+ if visibility != VISIBILITY_OFFLINE:
+ access = self.require_access_settings(session_id, user_context=context)
+ result = self.apply_access(
session_id,
- context,
- current_visibility=current_visibility,
- target_visibility=visibility,
+ expected_revision=access.revision,
+ target_access_mode=visibility,
+ target_share_id=access.share_id,
+ target_emails=[],
+ user_context=context,
)
- # Archive is terminal and takes the page offline on purpose — never let
- # an archived session's page be brought back online / re-shared. Checked
- # in the SAME txn as the write so a concurrent archive can't slip in
- # between the check and the update (TOCTOU); raising here rolls back.
- if visibility != VISIBILITY_OFFLINE:
- status = conn.execute(
- select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
- ).scalar_one_or_none()
- if status == "archived":
- raise ShowPageError(
- "Cannot republish the Show Page of an archived session.",
- code="session_archived",
- )
- conn.execute(update(show_pages).where(show_pages.c.session_id == session_id).values(**values))
- updated = self.get(session_id)
- assert updated is not None
- return updated
+ if result.status == "conflict":
+ raise ShowPageError(
+ "ShowAccess changed concurrently.",
+ code="show_access_conflict",
+ )
+ if result.status not in {"applied", "no_change"}:
+ raise ShowPageError(
+ "ShowAccess could not be updated.",
+ code=result.status,
+ )
+ return self.set_offline(session_id, False, user_context=context)
+
+ return self.set_offline(session_id, True, user_context=context)
- def rotate_share(self, session_id: str, *, user_context: Any = None) -> tuple[ShowPage, str | None]:
+ def rotate_share(
+ self,
+ session_id: str,
+ *,
+ user_context: Any = None,
+ ) -> tuple[ShowPage, str | None]:
session_id = validate_session_id(session_id)
context = _resolve_resource_access_context(user_context)
- existing = self.get(session_id)
- if existing is not None:
- with self.engine.connect() as conn:
- self._require_sharing_control(conn, session_id, context)
- page = existing
- else:
- page = None
- # Same guard as update_visibility, before ``ensure`` materializes a page:
- # an archived session is terminal, so its share link can't be rotated /
- # re-enabled (and a stale/direct call must not create a default page).
if self.is_archived(session_id):
raise ShowPageError(
"Cannot rotate the share link of an archived session.",
code="session_archived",
)
- if page is None:
- page = self.ensure(session_id, user_context=context)
- if page.visibility != VISIBILITY_PUBLIC:
+ if self.get(session_id) is None:
+ self.ensure(session_id, user_context=context)
+ access = self.require_access_settings(session_id, user_context=context)
+ if access.access_mode not in {ACCESS_MODE_LIMITED, ACCESS_MODE_PUBLIC}:
raise ShowPageError(
- "Share links can only be rotated while the Show Page is public.",
- code="not_public",
+ "Share links can only be rotated while the Show Page is shared.",
+ code="not_shared",
)
- previous_share_id = page.share_id
- new_share_id = self._unique_share_id()
- now = _utc_now_iso()
- with self.engine.begin() as conn:
- self._require_sharing_control(conn, session_id, context)
- conn.execute(
- update(show_pages)
- .where(show_pages.c.session_id == session_id)
- .values(share_id=new_share_id, updated_at=now)
+ previous_share_id = access.share_id
+ for _ in range(20):
+ result = self.apply_access(
+ session_id,
+ expected_revision=access.revision,
+ target_access_mode=access.access_mode,
+ target_share_id=_new_share_id(),
+ target_emails=access.normalized_emails,
+ user_context=context,
)
- updated = self.get(session_id)
- assert updated is not None
- return updated, previous_share_id
+ if result.status == "share_id_taken":
+ continue
+ if result.status == "conflict":
+ raise ShowPageError(
+ "ShowAccess changed concurrently.",
+ code="show_access_conflict",
+ )
+ if result.status not in {"applied", "no_change"}:
+ raise ShowPageError(
+ "The share link could not be rotated.",
+ code=result.status,
+ )
+ updated = self.get(session_id)
+ assert updated is not None
+ return updated, previous_share_id
+ raise ShowPageError(
+ "Could not allocate a unique share ID.",
+ code="share_id_allocation_failed",
+ )
def set_share_id(
self,
@@ -731,83 +1086,47 @@ class ShowPageStore:
*,
user_context: Any = None,
) -> tuple[ShowPage, str | None]:
- """Set a custom public share suffix; return (page, previous_share_id).
-
- A custom suffix is just a chosen value for the same ``share_id`` that
- ``rotate_share`` would otherwise randomize, so this mirrors that method:
- archived sessions are terminal (guarded before ``ensure`` materializes a
- page), and the suffix can only be set while the page is public. Setting a
- new value revokes the previous public URL, exactly like a rotate.
- """
+ """Replace a shared page's stable suffix through the ShowAccess writer."""
session_id = validate_session_id(session_id)
context = _resolve_resource_access_context(user_context)
new_share_id = validate_share_id(share_id)
- existing = self.get(session_id)
- if existing is not None:
- with self.engine.connect() as conn:
- self._require_sharing_control(conn, session_id, context)
- # Pre-guard before ``ensure`` so a stale/direct call never materializes a
- # default page for an archived (terminal) session. The in-txn re-reads
- # below are the atomic authority for the concurrent-archive / concurrent
- # visibility-flip race.
if self.is_archived(session_id):
raise ShowPageError(
"Cannot change the share link of an archived session.",
code="session_archived",
)
- if existing is None:
+ if self.get(session_id) is None:
self.ensure(session_id, user_context=context)
- now = _utc_now_iso()
- previous_share_id: str | None = None
- try:
- with self.engine.begin() as conn:
- self._require_sharing_control(conn, session_id, context)
- # Read visibility, archive status, and the current suffix in the
- # SAME transaction as the write so a concurrent flip to private/
- # offline, an archive, or another session claiming the suffix
- # can't slip between the check and the update; raising rolls back.
- row = (
- conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))
- .mappings()
- .first()
- )
- if row is None or row["visibility"] != VISIBILITY_PUBLIC:
- raise ShowPageError(
- "A custom link can only be set while the Show Page is public.",
- code="not_public",
- )
- status = conn.execute(
- select(agent_sessions.c.status).where(agent_sessions.c.id == session_id)
- ).scalar_one_or_none()
- if status == "archived":
- raise ShowPageError(
- "Cannot change the share link of an archived session.",
- code="session_archived",
- )
- previous_share_id = row["share_id"]
- if new_share_id != previous_share_id:
- # Idempotent when unchanged (skips the write, so no self-
- # collision and no updated_at churn). Otherwise reject a
- # suffix held by another session; the unique constraint is
- # the final authority (IntegrityError below).
- taken_by = conn.execute(
- select(show_pages.c.session_id).where(show_pages.c.share_id == new_share_id).limit(1)
- ).scalar_one_or_none()
- if taken_by is not None and taken_by != session_id:
- raise ShowPageError(
- "That custom link is already taken. Pick another.",
- code="share_id_taken",
- )
- conn.execute(
- update(show_pages)
- .where(show_pages.c.session_id == session_id)
- .values(share_id=new_share_id, updated_at=now)
- )
- except IntegrityError:
+ access = self.require_access_settings(session_id, user_context=context)
+ if access.access_mode not in {ACCESS_MODE_LIMITED, ACCESS_MODE_PUBLIC}:
+ raise ShowPageError(
+ "A custom link can only be set while the Show Page is shared.",
+ code="not_shared",
+ )
+ previous_share_id = access.share_id
+ result = self.apply_access(
+ session_id,
+ expected_revision=access.revision,
+ target_access_mode=access.access_mode,
+ target_share_id=new_share_id,
+ target_emails=access.normalized_emails,
+ user_context=context,
+ )
+ if result.status == "share_id_taken":
raise ShowPageError(
"That custom link is already taken. Pick another.",
code="share_id_taken",
)
+ if result.status == "conflict":
+ raise ShowPageError(
+ "ShowAccess changed concurrently.",
+ code="show_access_conflict",
+ )
+ if result.status not in {"applied", "no_change"}:
+ raise ShowPageError(
+ "The custom link could not be applied.",
+ code=result.status,
+ )
updated = self.get(session_id)
assert updated is not None
return updated, previous_share_id
@@ -823,7 +1142,8 @@ class ShowPageStore:
def _page_from_row(row: Any) -> ShowPage:
return ShowPage(
session_id=str(row["session_id"]),
- visibility=str(row["visibility"]),
+ access_mode=str(row["access_mode"]),
+ access_revision=int(row["access_revision"]),
share_id=str(row["share_id"]) if row["share_id"] else None,
offline_at=str(row["offline_at"]) if row["offline_at"] else None,
created_at=str(row["created_at"]),
@@ -831,6 +1151,25 @@ def _page_from_row(row: Any) -> ShowPage:
)
+def _show_access_from_row(connection: Connection, row: Any) -> ShowAccess:
+ page_id = str(row["session_id"])
+ emails = tuple(
+ str(value)
+ for value in connection.execute(
+ select(show_page_authorized_emails.c.normalized_email)
+ .where(show_page_authorized_emails.c.session_id == page_id)
+ .order_by(show_page_authorized_emails.c.normalized_email.asc())
+ ).scalars()
+ )
+ return ShowAccess(
+ page_id=page_id,
+ access_mode=str(row["access_mode"]),
+ share_id=str(row["share_id"]) if row["share_id"] else None,
+ revision=int(row["access_revision"]),
+ normalized_emails=emails,
+ )
+
+
class _IconLinkFinder(HTMLParser):
"""Capture the first ``<link rel="icon">`` href — and the ``<base href>`` in
effect before it — from an HTML document.
@@ -1330,6 +1669,8 @@ def show_page_payload(page: ShowPage, *, config: V2Config | None = None) -> dict
return {
"session_id": page.session_id,
"visibility": page.visibility,
+ "access_mode": page.access_mode,
+ "access_revision": page.access_revision,
"path": str(path),
# Opaque cache token (not a path): non-null iff a servable icon exists, and
# it changes when the icon file changes so the frontend's ?v=<token> busts
diff --git a/docs/plans/admin-show-pages.md b/docs/plans/admin-show-pages.md
index 2b999bb01..cf6dbd0eb 100644
--- a/docs/plans/admin-show-pages.md
+++ b/docs/plans/admin-show-pages.md
@@ -1,40 +1,15 @@
-# Admin "Show Pages" management page
+# Admin Show Pages management page (superseded)
-## Background
-Show Pages (`core/show_pages.py`) are per-session managed React pages, each `private` / `public` / `offline`. The CLI (`vibe show list/status/update`) manages them, but there is no Web UI. Add a `/admin/show-pages` page + sidebar entry so users can manage every Show Page from the console.
+This historical plan was implemented before Show Pages moved into the Workbench
+App Library. Its separate `Private / Public / Offline` visibility control,
+per-action public-link mutations, and dedicated Admin navigation are retired.
-Design is locked in `design.pen` frame **`m7wqzf`** ("vibe-remote — Show Pages (Dark)"); sidebar item added to shared component `kSWgv`.
+The current design is documented in
+[`show-access-local-settings.md`](show-access-local-settings.md):
-## Goal (user-approved)
-Admin can: list all Show Pages (private + public + offline), newest-first; per row see a friendly title + current status + live link; switch private↔public, take offline, restore from offline; rotate a public link; copy / open links.
-
-## Design decisions
-- **Status colors:** Public = gold, Private = cyan, Offline = grey/muted. Expanded-row selection glow stays mint (generic "selected" accent, not a status).
-- **Row label = `session.title` if set, else `session_id`** (mono). No channel/scope middle fallback (user decision 2026-06-02). Full `session_id` always shown in the expanded Details.
-- **3-way visibility segmented `[Private | Public | Offline]`** is the core switch (maps to `update --visibility`), covering restore-from-offline.
-- **Public extras:** copy link, open, rotate link (revokes + reissues).
-- **Cloud reachability:** when Avibe Cloud is not connected (`url_available == false`), show a gold warning by the live link; hidden when connected.
-- Row sub-line: `platform · agent` context.
-
-## Backend reuse (no new store logic)
-- `ShowPageStore.list_page()` already filters + orders `updated_at desc` + paginates. `show_page_payload()` returns visibility / urls / `url_available` / `url_guidance` / `share_id` / timestamps. Reuse as-is.
-- New `storage/sessions_service.read_session_titles(session_ids) -> {id: title}` (batch read of `agent_sessions.title`).
-- New `vibe/api.py`: `list_show_pages()`, `set_show_page_visibility(session_id, visibility)`, `rotate_show_page_share(session_id)` — wrap the store + title enrichment, return `{ok, ...}` dicts (mirror `get_vibe_agents` style).
-- New `ui_server.py` routes: `GET /api/show-pages`, `POST /api/show-pages/<sid>/visibility`, `POST /api/show-pages/<sid>/rotate-share`. `ShowPageError` -> mapped error response (mirror `_vibe_agent_result_response`).
-
-## Frontend
-- `AppShell.tsx`: add `adminItems` entry `{ to:'/admin/show-pages', label:t('nav.showPages'), icon: MonitorPlay }` between Users and Settings.
-- `App.tsx`: route `/admin/show-pages -> <ShowPagesPage/>`.
-- `components/ShowPagesPage.tsx`: header + search, visibility filter segmented, table (SESSION / VISIBILITY / LIVE LINK / UPDATED / actions), expandable row -> segmented + copy/open + rotate + Details. Reuse `Badge`/`Button`/ui primitives + `UserList` list/row layout classes. Client-side filter/search; fetch all via `getShowPages`.
-- `context/ApiContext.tsx`: `getShowPages()`, `setShowPageVisibility(sid, vis)`, `rotateShowPageShare(sid)`.
-- `i18n/en.json` + `zh.json`: `nav.showPages` + `showPages.*` keys.
-
-## Build order
-1. Backend: `sessions_service.read_session_titles` + `api` fns + routes + pytest.
-2. Frontend: ApiContext + i18n + AppShell nav + App route + ShowPagesPage; `npm run build`.
-3. Verify the built page side-by-side vs design frame `m7wqzf`.
-
-## Evidence layers
-- unit: pytest for `api.list_show_pages` (title join), visibility update, rotate-share, error mapping (canned sqlite state).
-- build: `npm run build` in `ui/`; `ruff check` on changed Python.
-- manual: render `/admin/show-pages` vs the design frame.
+- audience is applied atomically as `Private / Limited / Fully public`;
+- availability is an independent online/offline control;
+- the App Library expanded row and the Show Page Share popover reuse the same
+ access editor;
+- legacy Web visibility, link-rotation, custom-link, and hosted-email mutation
+ surfaces must not be restored.
diff --git a/docs/plans/dock-pinned-show-page-apps.md b/docs/plans/dock-pinned-show-page-apps.md
index 88225698a..4e3ffb7c7 100644
--- a/docs/plans/dock-pinned-show-page-apps.md
+++ b/docs/plans/dock-pinned-show-page-apps.md
@@ -222,7 +222,7 @@ the same objects. Decision: fold it into the App Library.
(Not every Show Page is an app; every session has a page, so the full
inventory must not masquerade as the app list.)
- *Show Pages*: the full inventory (today's admin page content: status,
- visibility private/public/offline, link + share-id, open) **plus a
+ access mode, availability, active link/custom suffix, open) **plus a
per-row "Pin to Dock" toggle** — pinning is the "install" gesture.
- Same data sources (`/api/show-pages` + `/api/dock`), two projections; no
new backend.
diff --git a/docs/plans/show-access-local-settings.md b/docs/plans/show-access-local-settings.md
new file mode 100644
index 000000000..fc53cda85
--- /dev/null
+++ b/docs/plans/show-access-local-settings.md
@@ -0,0 +1,78 @@
+# Local ShowAccess Settings Lane
+
+## Background
+
+Issue #1498 separates per-page guest membership from Instance authorization.
+Local Avibe owns each page's access mode, stable `/p` binding, exact-email list,
+and revision. Avibe Backend must not store or decide that membership.
+
+This implementation consumes the contract in PR #1496 at head
+`ff3ee55e389decc48496d03925b5c77328d5fecb`. The contract is not copied into
+this branch. This PR requires #1496 to merge first.
+
+## Goal
+
+Deliver the local settings aggregate and its owner-facing UI:
+
+- persist `private | limited | public`, stable share ID, revision, and normalized
+ exact emails in local SQLite;
+- apply mode, share ID, and the complete email set atomically with revision CAS;
+- serialize settings writes in the controller and cross the UI-process boundary
+ over the verified internal socket;
+- expose identity-checked, non-cacheable settings read/apply HTTP endpoints;
+- present one sharing control for Private, Limited, and Fully public while
+ keeping operational availability independent;
+- directly retire the old hosted-email CRUD UI/client and the old visibility,
+ rotate-link, and share-ID Web mutation surfaces.
+
+## Design
+
+`ShowPageStore.apply_access` is the transactional aggregate writer. Canonical
+changes advance the revision once; canonical no-ops do not. A stale revision or
+share-ID collision returns the current snapshot without a partial email change.
+
+The UI server authorizes the route page before IPC. The controller owns write
+serialization and performs SQLite work outside its event loop. Route page ID,
+HTTP request page ID, IPC request page ID, controller result page ID, and HTTP
+result page ID must all match before any exact-email data is returned.
+
+The sharing UI submits one Apply request. A CAS conflict reloads the latest
+snapshot. A share-ID collision keeps the user's draft. Narrowing access asks for
+confirmation. Availability remains editable independently of the audience and
+does not change the access revision.
+
+## Lane Boundary
+
+This lane does not implement Limited `/p` identity login or admission, remove
+the legacy `show_page_email` Instance authorization source, or add shared Runtime
+containment. Those are separate #1498 implementation lanes consuming #1496's
+identity and Runtime contracts. Until those lanes land, this PR must not claim
+end-to-end Limited guest access.
+
+## Verification
+
+- [x] Store invariants, email canonicalization, CAS, no-op, collision, and rollback
+- [x] Migration upgrade/downgrade and released local page-shape preservation
+- [x] Controller settings read/apply, malformed request, identity, and serialization
+- [x] Internal client round trip, unavailable socket, and timeout behavior
+- [x] HTTP authorization, identity equality, cache policy, and retryable failures
+- [x] Three-mode UI, Limited-only fields, single Apply, CAS reload, and collision draft
+- [x] Deleted-component, client, route, i18n, and hosted-email residue guard
+- [x] Full focused backend and frontend suites
+- [x] Production UI build
+- [x] Desktop and mobile browser acceptance
+
+## Review-loop scope decision
+
+Three findings-bearing review heads exposed distinct root-cause classes: route
+selection and hidden draft state, incomplete Limited-mode product projection and
+stale async UI continuations, then an ambiguous IPC deadline around serialized
+writes. The third-head audit traced the complete settings Apply path.
+
+The controller's SQLite write runs in a worker thread and cannot be cancelled
+reliably after the IPC request is accepted. A finite client read deadline could
+therefore report failure while the write later commits. The smallest complete,
+contract-preserving fix is operation-aware transport timing: settings reads keep
+a finite deadline, while Apply bounds connection establishment only and waits for
+the controller's definitive CAS result. Controller serialization and aggregate
+semantics remain unchanged.
diff --git a/docs/plans/show-page-email-access.md b/docs/plans/show-page-email-access.md
deleted file mode 100644
index e3b71d05b..000000000
--- a/docs/plans/show-page-email-access.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# ShowPage Email Access
-
-## Goal
-
-Allow a ShowPage owner to grant exact email addresses access to one ShowPage.
-Organization ShowPages retain the same email audience and additionally support
-the whole Organization or selected Organization groups.
-
-Anonymous Public links remain an independent sharing switch.
-
-## Authorization Contract
-
-- A grant is keyed by `instance_id + show_page_id + normalized_email`.
-- The OIDC request carries the target `show_page_id`.
-- A user admitted only by that grant receives `vibe_instance_access_source =
- show_page_email`, `vibe_instance_role = viewer`, and a signed
- `vibe_show_page_id` claim.
-- Existing Instance owner, email, domain, group, and public-instance access wins
- before the ShowPage-only grant so existing users keep their broader access.
-- When a broader user also has the target ShowPage email grant, the broader
- source and role remain unchanged while the signed `vibe_show_page_id` is
- retained as an independent exact-page entitlement.
-- The exact-page entitlement bypass applies only to ShowPage routes and
- ShowPage-specific APIs. Generic Session APIs still require their normal
- Project/session ACL so a page grant cannot expose the owner's transcript.
-- A broader browser session that predates a page grant reauthorizes once when
- the requested ShowPage is otherwise forbidden, allowing the control plane to
- refresh the signed exact-page entitlement without requiring logout.
-- A `show_page_email` browser session may serve only the exact
- `/show/<vibe_show_page_id>` route subtree and required public static assets.
- Workbench, Chat, other Sessions, Agents, files, Cloud capabilities, APIs, and
- other ShowPages fail closed.
-- ShowPage resource authorization independently requires the requested resource
- ID to equal the signed `vibe_show_page_id`.
-- Replacing an email audience bumps the paired Instance authorization revision
- when and only when the normalized set changes, invalidating existing sessions
- after the normal revision refresh.
-
-## Management Contract
-
-- The local Avibe service exposes owner-authorized ShowPage email GET/PUT APIs.
-- Those handlers call a paired-device-authenticated control-plane endpoint; the
- device secret never reaches the browser.
-- Personal and Organization instances use the same email-grant endpoint.
-- Organization audience/group management continues through the existing
- Organization management flow and remains orthogonal to email grants.
-
-## Verification
-
-- Backend store, route, authorization, authorize-request, frozen-code, and ID
- token tests.
-- App OIDC claim, cookie, exact-route, exact-resource, API, and UI tests.
-- Regression coverage proving one email grant cannot open another ShowPage or
- any Workbench/API surface.
diff --git a/docs/plans/workbench-search-include-archived.md b/docs/plans/workbench-search-include-archived.md
index 8c3aaafda..416dd513c 100644
--- a/docs/plans/workbench-search-include-archived.md
+++ b/docs/plans/workbench-search-include-archived.md
@@ -415,8 +415,7 @@ that the server can answer `409 session_archived`:**
| `api.updateSession` (PATCH) | `patch` — title, agent re-route, model, pin, scope | `SessionArchivedError` → `_session_archived_response` | **API seam (r5)** |
| `api.forkSession` | `askInNewSession` (Quote → Ask in a new session) | `_session_fork_error_response` | ~~**API seam (r5)**~~ **FALSE WHEN WRITTEN — flat body, code destroyed. Fixed r6.** |
| `api.ensureShowPage` | `toggleShowPage` | `core/show_pages.ensure_active` | **API seam (r5)**, re-verified r6 |
-| `api.setShowPageVisibility` / `rotateShowPageShare` / `uploadShowPageIcon` (+ its `api.updateSession` rename) | `ShowPageShareControl` → `useShowPages` store | `core/show_pages` guards, `vibe/api.py:1235` | **API seam (r5)**, re-verified r6 |
-| `api.setShowPageShareId` | `ShowPageShareIdField` (inside the Share popover) | `core/show_pages` guard | **API seam (r5)**, re-verified r6 |
+| Show Page access / availability / icon mutations (+ the `api.updateSession` rename) | `ShowPageShareControl` and its inventory store | `core/show_pages` guards | **API seam (r5)**, re-verified r6; access mutations were later consolidated by the unified ShowAccess editor |
| Show-event POST (annotation submit) | the annotation overlay **inside the Show Page iframe** | `core/show_session_events.py:165` | out of reach — see below |
**The "converges via API seam" column was an assertion, not a verification** — see
@@ -449,7 +448,7 @@ helper's error passes through, so it announces the fact once via a new
layer choice. Only its *message* is per-verb: `errors.session_archived` (what
`handleApiError` resolves) is Show-Page-worded and wrong for a rename, so the
catch substitutes the new `chat.archived.editBlocked`.
-- the child-component calls (Share visibility / rotate / share-id / icon, and the
+- the child-component calls (unified access Apply / availability / icon, and the
store's own rename) converge without ChatPage plumbing a callback into any of them.
- a future session-scoped write inherits it.
@@ -620,9 +619,8 @@ returns (`vibe/ui_server.py`), then to a body assertion. Two rows were wrong:
| `api.updateSession` | `_session_archived_response` → structured | held (r4b/r5) |
| `api.forkSession` | `_session_fork_error_response` → **flat `{"error": "<sentence>", "code": …}`** | **WRONG — code destroyed. Fixed** |
| `api.ensureShowPage` | `_show_page_error_response` → structured | held |
-| `api.setShowPageVisibility` | `_show_page_error_response` → structured | held |
-| `api.setShowPageShareId` | `_show_page_error_response` → structured | held |
-| `api.rotateShowPageShare` | `_show_page_error_response` → structured | held |
+| Show Page access Apply | `_show_page_error_response` → structured | held; later consolidated into revision-CAS Apply |
+| Show Page availability | `_show_page_error_response` → structured | held |
| `api.uploadShowPageIcon` | `_show_page_icon_upload_error` → structured | held |
| store rename (`useShowPages` → `api.updateSession`) | same as `updateSession` | held |
| `api.cancelSession` / `removeQueuedMessage` / `sendQueuedNow` / `setSessionDraft` | no archive guard at all | held (not `session_archived`-capable) |
diff --git a/storage/alembic/versions/20260817_0055_local_show_access.py b/storage/alembic/versions/20260817_0055_local_show_access.py
new file mode 100644
index 000000000..62b6420f3
--- /dev/null
+++ b/storage/alembic/versions/20260817_0055_local_show_access.py
@@ -0,0 +1,210 @@
+"""make Show Page audience local and independent from availability
+
+Revision ID: 20260817_0055
+Revises: 20260815_0054
+Create Date: 2026-08-17
+"""
+
+from __future__ import annotations
+
+import secrets
+import re
+
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.exc import IntegrityError
+
+revision = "20260817_0055"
+down_revision = "20260815_0054"
+branch_labels = None
+depends_on = None
+
+_SHARE_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{1,62}[A-Za-z0-9]$")
+
+
+def _tables() -> set[str]:
+ return {
+ str(row[0])
+ for row in op.get_bind()
+ .exec_driver_sql("select name from sqlite_master where type = 'table'")
+ .fetchall()
+ }
+
+
+def _indexes(table_name: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in op.get_bind()
+ .exec_driver_sql(f'pragma index_list("{table_name}")')
+ .fetchall()
+ }
+
+
+def _columns(table_name: str) -> set[str]:
+ return {
+ str(row[1])
+ for row in op.get_bind()
+ .exec_driver_sql(f'pragma table_info("{table_name}")')
+ .fetchall()
+ }
+
+
+def _new_share_id() -> str:
+ while True:
+ candidate = secrets.token_urlsafe(8).strip("_-")
+ if _SHARE_ID_PATTERN.fullmatch(candidate):
+ return candidate
+
+
+def _allocate_missing_share_ids() -> None:
+ bind = op.get_bind()
+ session_ids = [
+ str(row[0])
+ for row in bind.exec_driver_sql(
+ "select session_id from show_pages where share_id is null order by session_id"
+ ).fetchall()
+ ]
+ for session_id in session_ids:
+ while True:
+ try:
+ bind.execute(
+ sa.text(
+ "update show_pages set share_id = :share_id "
+ "where session_id = :session_id and share_id is null"
+ ),
+ {"session_id": session_id, "share_id": _new_share_id()},
+ )
+ break
+ except IntegrityError:
+ continue
+
+
+def _ensure_authorized_email_table() -> None:
+ if "show_page_authorized_emails" not in _tables():
+ op.create_table(
+ "show_page_authorized_emails",
+ sa.Column(
+ "session_id",
+ sa.String(),
+ sa.ForeignKey("show_pages.session_id", ondelete="CASCADE"),
+ primary_key=True,
+ ),
+ sa.Column("normalized_email", sa.String(), primary_key=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.CheckConstraint(
+ "length(normalized_email) between 3 and 320",
+ name="ck_show_page_authorized_emails_length",
+ ),
+ )
+ op.create_index(
+ "ix_show_page_authorized_emails_email",
+ "show_page_authorized_emails",
+ ["normalized_email"],
+ if_not_exists=True,
+ )
+
+
+def upgrade() -> None:
+ columns = _columns("show_pages")
+ # Unversioned databases created from current metadata are stamped at the
+ # replay floor before later migrations run. Their ShowAccess schema is
+ # already current, so this revision must be replay-safe.
+ if "access_mode" in columns and "visibility" not in columns:
+ _allocate_missing_share_ids()
+ op.create_index(
+ "ix_show_pages_access_mode",
+ "show_pages",
+ ["access_mode"],
+ if_not_exists=True,
+ )
+ _ensure_authorized_email_table()
+ return
+
+ op.add_column(
+ "show_pages",
+ sa.Column("access_mode", sa.String(), nullable=True),
+ )
+ op.add_column(
+ "show_pages",
+ sa.Column("access_revision", sa.Integer(), nullable=False, server_default="0"),
+ )
+ op.execute(
+ sa.text(
+ "update show_pages set access_mode = case visibility "
+ "when 'public' then 'public' else 'private' end"
+ )
+ )
+ # Legacy offline rows did not retain their previous audience. Preserve the
+ # operational state and fail closed instead of guessing that a retained
+ # share_id meant the page used to be public.
+ op.execute(
+ sa.text(
+ "update show_pages set offline_at = coalesce(offline_at, updated_at, created_at) "
+ "where visibility = 'offline'"
+ )
+ )
+ _allocate_missing_share_ids()
+
+ if "ix_show_pages_visibility" in _indexes("show_pages"):
+ op.drop_index("ix_show_pages_visibility", table_name="show_pages")
+ with op.batch_alter_table("show_pages") as batch_op:
+ batch_op.alter_column(
+ "access_mode",
+ existing_type=sa.String(),
+ nullable=False,
+ server_default="private",
+ )
+ batch_op.create_check_constraint(
+ "ck_show_pages_access_mode",
+ "access_mode in ('private', 'limited', 'public')",
+ )
+ batch_op.create_check_constraint(
+ "ck_show_pages_access_revision",
+ "access_revision >= 0",
+ )
+ batch_op.drop_column("visibility")
+ op.create_index(
+ "ix_show_pages_access_mode",
+ "show_pages",
+ ["access_mode"],
+ if_not_exists=True,
+ )
+
+ _ensure_authorized_email_table()
+
+
+def downgrade() -> None:
+ if "show_page_authorized_emails" in _tables():
+ op.drop_table("show_page_authorized_emails")
+
+ op.add_column(
+ "show_pages",
+ sa.Column("visibility", sa.String(), nullable=True),
+ )
+ # Older releases cannot represent Limited. Mapping it to private disables
+ # the shared route while retaining the inactive stable slug.
+ op.execute(
+ sa.text(
+ "update show_pages set visibility = case "
+ "when offline_at is not null then 'offline' "
+ "when access_mode = 'public' then 'public' else 'private' end"
+ )
+ )
+ if "ix_show_pages_access_mode" in _indexes("show_pages"):
+ op.drop_index("ix_show_pages_access_mode", table_name="show_pages")
+ with op.batch_alter_table("show_pages") as batch_op:
+ batch_op.drop_constraint("ck_show_pages_access_revision", type_="check")
+ batch_op.drop_constraint("ck_show_pages_access_mode", type_="check")
+ batch_op.alter_column(
+ "visibility",
+ existing_type=sa.String(),
+ nullable=False,
+ )
+ batch_op.drop_column("access_revision")
+ batch_op.drop_column("access_mode")
+ op.create_index(
+ "ix_show_pages_visibility",
+ "show_pages",
+ ["visibility"],
+ if_not_exists=True,
+ )
diff --git a/storage/migrations.py b/storage/migrations.py
index a2f5daed4..6b5d703b3 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -52,6 +52,7 @@ HEAD_TABLES = INITIAL_TABLES | {
"run_definitions",
"agent_runs",
"show_pages",
+ "show_page_authorized_emails",
"messages",
"message_deliveries",
"session_turns",
@@ -146,6 +147,8 @@ HEAD_REQUIRED_COLUMNS = PRE_SHOW_SESSION_EVENTS_REQUIRED_COLUMNS | {
},
}
HEAD_ONLY_REQUIRED_COLUMNS = {
+ "show_pages": {"access_mode", "access_revision", "share_id", "offline_at"},
+ "show_page_authorized_emails": {"session_id", "normalized_email", "created_at"},
"web_push_subscriptions": {"device_id"},
"remote_access_authorizations": {
"instance_id",
diff --git a/storage/models.py b/storage/models.py
index 33672c881..e5e7ff78e 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -389,14 +389,38 @@ show_pages = Table(
"show_pages",
metadata,
Column("session_id", String, primary_key=True),
- Column("visibility", String, nullable=False),
+ Column("access_mode", String, nullable=False, server_default="private"),
+ Column("access_revision", Integer, nullable=False, server_default="0"),
Column("share_id", String, nullable=True),
Column("offline_at", String, nullable=True),
Column("created_at", String, nullable=False),
Column("updated_at", String, nullable=False),
UniqueConstraint("share_id", name="uq_show_pages_share_id"),
+ CheckConstraint(
+ "access_mode in ('private', 'limited', 'public')",
+ name="ck_show_pages_access_mode",
+ ),
+ CheckConstraint("access_revision >= 0", name="ck_show_pages_access_revision"),
Index("ix_show_pages_share_id", "share_id"),
- Index("ix_show_pages_visibility", "visibility"),
+ Index("ix_show_pages_access_mode", "access_mode"),
+)
+
+show_page_authorized_emails = Table(
+ "show_page_authorized_emails",
+ metadata,
+ Column(
+ "session_id",
+ String,
+ ForeignKey("show_pages.session_id", ondelete="CASCADE"),
+ primary_key=True,
+ ),
+ Column("normalized_email", String, primary_key=True),
+ Column("created_at", String, nullable=False),
+ CheckConstraint(
+ "length(normalized_email) between 3 and 320",
+ name="ck_show_page_authorized_emails_length",
+ ),
+ Index("ix_show_page_authorized_emails_email", "normalized_email"),
)
show_session_events = Table(
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 042675e86..c58dcd664 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -1479,7 +1479,7 @@ def archive_session(
conn.execute(
update(show_pages)
.where(show_pages.c.session_id == session_id)
- .values(visibility="offline", offline_at=now, updated_at=now)
+ .values(offline_at=now, updated_at=now)
)
payload = get_session(conn, session_id, authorization_context=context)
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index d742ec15c..b799ee7d5 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -159,6 +159,10 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("POST", "/api/sessions/session-1/messages"),
("POST", "/api/sessions/session-1/attachments"),
("POST", "/api/sessions/session-1/cancel"),
+ ("POST", "/api/show-pages/session-1/ensure"),
+ ("POST", "/api/show-pages/session-1/availability"),
+ ("POST", "/api/show-pages/session-1/access-settings/read"),
+ ("POST", "/api/show-pages/session-1/access-settings/apply"),
)
for method, path in editor_examples:
assert http_authorization_policy(method, path).minimum_role == "editor", path
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 1b066aa3c..a77468706 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -1099,3 +1099,174 @@ def test_socket_verifier_skips_posix_mode_check_on_windows(monkeypatch, socket_p
monkeypatch.setattr(internal_client, "_CHECK_POSIX_SOCKET_MODE", False)
assert internal_client._verified_socket_path(socket_path) == socket_path
+
+
+def test_show_access_clients_round_trip(socket_path):
+ app = FastAPI()
+ captured: list[tuple[str, dict]] = []
+
+ @app.post("/internal/show-access/settings-read")
+ async def _read(payload: dict):
+ captured.append(("read", payload))
+ return {
+ "show_access": {
+ "page_id": payload["page_id"],
+ "access_mode": "private",
+ "share_id": "stable-link",
+ "revision": 3,
+ "normalized_emails": [],
+ }
+ }
+
+ @app.post("/internal/show-access/apply")
+ async def _apply(payload: dict):
+ captured.append(("apply", payload))
+ return {
+ "status": "applied",
+ "show_access": {
+ "page_id": payload["page_id"],
+ "access_mode": payload["target_access_mode"],
+ "share_id": payload["target_share_id"],
+ "revision": payload["expected_revision"] + 1,
+ "normalized_emails": payload["target_emails"],
+ },
+ }
+
+ read_payload = {"page_id": "ses-show-access"}
+ apply_payload = {
+ "page_id": "ses-show-access",
+ "expected_revision": 3,
+ "target_access_mode": "limited",
+ "target_share_id": "stable-link",
+ "target_emails": ["[email protected]"],
+ }
+
+ async def _exercise():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch(
+ "vibe.internal_client.httpx.AsyncHTTPTransport",
+ return_value=fake_transport,
+ ):
+ loaded = await internal_client.show_access_settings_read(
+ read_payload,
+ socket_path=socket_path,
+ )
+ applied = await internal_client.show_access_apply(
+ apply_payload,
+ socket_path=socket_path,
+ )
+ return loaded, applied
+
+ loaded, applied = asyncio.run(_exercise())
+
+ assert loaded["status_code"] == 200
+ assert loaded["body"]["show_access"]["page_id"] == "ses-show-access"
+ assert applied == {
+ "status_code": 200,
+ "body": {
+ "status": "applied",
+ "show_access": {
+ "page_id": "ses-show-access",
+ "access_mode": "limited",
+ "share_id": "stable-link",
+ "revision": 4,
+ "normalized_emails": ["[email protected]"],
+ },
+ },
+ }
+ assert captured == [("read", read_payload), ("apply", apply_payload)]
+
+
+ "operation",
+ [
+ lambda socket_path: internal_client.show_access_settings_read(
+ {"page_id": "ses-show-access"},
+ socket_path=socket_path,
+ ),
+ lambda socket_path: internal_client.show_access_apply(
+ {
+ "page_id": "ses-show-access",
+ "expected_revision": 0,
+ "target_access_mode": "private",
+ "target_share_id": None,
+ "target_emails": [],
+ },
+ socket_path=socket_path,
+ ),
+ ],
+)
+def test_show_access_clients_report_missing_controller_socket(tmp_path, operation):
+ with pytest.raises(internal_client.InternalServerUnavailable):
+ asyncio.run(operation(tmp_path / "missing.sock"))
+
+
+def test_show_access_settings_read_reports_read_timeout(socket_path):
+ class _TimingOutClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def post(self, _path, json):
+ raise httpx.ReadTimeout(f"timed out applying {json['page_id']}")
+
+ with patch(
+ "vibe.internal_client.httpx.AsyncClient",
+ return_value=_TimingOutClient(),
+ ):
+ with pytest.raises(internal_client.InternalServerTimeout):
+ asyncio.run(
+ internal_client.show_access_settings_read(
+ {"page_id": "ses-show-access"},
+ socket_path=socket_path,
+ )
+ )
+
+
+def test_show_access_apply_waits_for_a_definitive_controller_result(socket_path):
+ captured: dict[str, httpx.Timeout] = {}
+
+ class _Client:
+ def __init__(self, **kwargs):
+ captured["timeout"] = kwargs["timeout"]
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args):
+ return None
+
+ async def post(self, _path, json):
+ return httpx.Response(
+ 200,
+ json={
+ "status": "no_change",
+ "show_access": {
+ "page_id": json["page_id"],
+ "access_mode": "private",
+ "share_id": "stable-link",
+ "revision": json["expected_revision"],
+ "normalized_emails": [],
+ },
+ },
+ )
+
+ with patch("vibe.internal_client.httpx.AsyncClient", _Client):
+ result = asyncio.run(
+ internal_client.show_access_apply(
+ {
+ "page_id": "ses-show-access",
+ "expected_revision": 0,
+ "target_access_mode": "private",
+ "target_share_id": "stable-link",
+ "target_emails": [],
+ },
+ socket_path=socket_path,
+ )
+ )
+
+ assert result["body"]["status"] == "no_change"
+ assert captured["timeout"].connect == 1.0
+ assert captured["timeout"].read is None
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 81dc62b81..7c910c0e9 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -8492,3 +8492,247 @@ def test_build_session_context_respects_explicit_channel_override(monkeypatch, t
context = internal_server._build_session_context(session["id"], channel_id="D_EXPLICIT")
assert context.channel_id == "D_EXPLICIT"
+
+
+def test_show_access_settings_read_returns_controller_snapshot(monkeypatch):
+ from core import show_pages
+
+ captured: list[str] = []
+
+ class _Store:
+ def get_access(self, page_id):
+ captured.append(page_id)
+ return show_pages.ShowAccess(
+ page_id=page_id,
+ access_mode="limited",
+ share_id="stable-link",
+ revision=7,
+ normalized_emails=("[email protected]", "[email protected]"),
+ )
+
+ def close(self):
+ captured.append("closed")
+
+ monkeypatch.setattr(show_pages, "ShowPageStore", _Store)
+ app = internal_server.create_app(_build_controller_double())
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ "/internal/show-access/settings-read",
+ json={"page_id": "ses-show-access"},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "show_access": {
+ "page_id": "ses-show-access",
+ "access_mode": "limited",
+ "share_id": "stable-link",
+ "revision": 7,
+ "normalized_emails": ["[email protected]", "[email protected]"],
+ }
+ }
+ assert captured == ["ses-show-access", "closed"]
+
+
+ ("path", "payload", "error"),
+ [
+ (
+ "/internal/show-access/settings-read",
+ {"page_id": "ses-show-access", "extra": True},
+ "invalid_show_access_settings_request",
+ ),
+ (
+ "/internal/show-access/apply",
+ {
+ "page_id": "ses-show-access",
+ "expected_revision": True,
+ "target_access_mode": "limited",
+ "target_share_id": "stable-link",
+ "target_emails": ["[email protected]"],
+ },
+ "invalid_show_access_apply_request",
+ ),
+ ],
+)
+def test_show_access_internal_routes_reject_malformed_payloads(path, payload, error):
+ app = internal_server.create_app(_build_controller_double())
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(path, json=payload)
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 400
+ assert response.json() == {"ok": False, "error": error}
+
+
[email protected]("status", ["conflict", "share_id_taken"])
+def test_show_access_apply_preserves_atomic_result_status(monkeypatch, status):
+ from core import show_pages
+
+ captured: dict = {}
+
+ class _Store:
+ def apply_access(self, page_id, **kwargs):
+ captured.update(page_id=page_id, **kwargs)
+ return show_pages.ShowAccessApplyResult(
+ status=status,
+ show_access=show_pages.ShowAccess(
+ page_id=page_id,
+ access_mode="public",
+ share_id="current-link",
+ revision=9,
+ normalized_emails=(),
+ ),
+ )
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr(show_pages, "ShowPageStore", _Store)
+ app = internal_server.create_app(_build_controller_double())
+ payload = {
+ "page_id": "ses-show-access",
+ "expected_revision": 8,
+ "target_access_mode": "limited",
+ "target_share_id": "candidate-link",
+ "target_emails": ["[email protected]"],
+ }
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post("/internal/show-access/apply", json=payload)
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "status": status,
+ "show_access": {
+ "page_id": "ses-show-access",
+ "access_mode": "public",
+ "share_id": "current-link",
+ "revision": 9,
+ "normalized_emails": [],
+ },
+ }
+ assert captured == {
+ "page_id": "ses-show-access",
+ "expected_revision": 8,
+ "target_access_mode": "limited",
+ "target_share_id": "candidate-link",
+ "target_emails": ["[email protected]"],
+ }
+
+
+def test_show_access_internal_identity_mismatch_fails_closed(monkeypatch):
+ from core import show_pages
+
+ class _Store:
+ def get_access(self, _page_id):
+ return show_pages.ShowAccess(
+ page_id="ses-other",
+ access_mode="limited",
+ share_id="secret-link",
+ revision=2,
+ normalized_emails=("[email protected]",),
+ )
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr(show_pages, "ShowPageStore", _Store)
+ app = internal_server.create_app(_build_controller_double())
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ return await client.post(
+ "/internal/show-access/settings-read",
+ json={"page_id": "ses-show-access"},
+ )
+
+ response = asyncio.run(_exercise())
+
+ assert response.status_code == 500
+ assert response.json() == {
+ "ok": False,
+ "error": "show_access_internal_failure",
+ }
+ assert "[email protected]" not in response.text
+
+
+def test_show_access_apply_serializes_controller_writes(monkeypatch):
+ from core import show_pages
+
+ first_entered = threading.Event()
+ release_first = threading.Event()
+ calls: list[str] = []
+ calls_lock = threading.Lock()
+
+ class _Store:
+ def apply_access(self, page_id, **_kwargs):
+ with calls_lock:
+ calls.append(page_id)
+ call_number = len(calls)
+ if call_number == 1:
+ first_entered.set()
+ assert release_first.wait(timeout=2)
+ return show_pages.ShowAccessApplyResult(
+ status="no_change",
+ show_access=show_pages.ShowAccess(
+ page_id=page_id,
+ access_mode="private",
+ share_id="stable-link",
+ revision=0,
+ normalized_emails=(),
+ ),
+ )
+
+ def close(self):
+ return None
+
+ monkeypatch.setattr(show_pages, "ShowPageStore", _Store)
+ app = internal_server.create_app(_build_controller_double())
+ payload = {
+ "expected_revision": 0,
+ "target_access_mode": "private",
+ "target_share_id": "stable-link",
+ "target_emails": [],
+ }
+
+ async def _exercise():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ first = asyncio.create_task(
+ client.post(
+ "/internal/show-access/apply",
+ json={"page_id": "ses-first", **payload},
+ )
+ )
+ assert await asyncio.to_thread(first_entered.wait, 2)
+ second = asyncio.create_task(
+ client.post(
+ "/internal/show-access/apply",
+ json={"page_id": "ses-second", **payload},
+ )
+ )
+ await asyncio.sleep(0.05)
+ with calls_lock:
+ assert calls == ["ses-first"]
+ release_first.set()
+ return await asyncio.gather(first, second)
+
+ responses = asyncio.run(_exercise())
+
+ assert [response.status_code for response in responses] == [200, 200]
+ assert calls == ["ses-first", "ses-second"]
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index d2415ac4f..d89caaacb 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -1058,19 +1058,35 @@ def test_startup_show_page_prewarm_targets_recent_non_offline(monkeypatch, tmp_p
try:
store.ensure("ses-old")
store.update_visibility("ses-public", "public")
+ limited = store.ensure("ses-limited")
+ result = store.apply_access(
+ "ses-limited",
+ expected_revision=limited.access_revision,
+ target_access_mode="limited",
+ target_share_id=limited.share_id,
+ target_emails=["[email protected]"],
+ )
+ assert result.status == "applied"
store.update_visibility("ses-offline", "offline")
store.ensure("ses-new")
finally:
store.close()
- out = api.startup_show_page_prewarm_targets(limit=2)
+ out = api.startup_show_page_prewarm_targets(limit=3)
- assert out["limit"] == 2
- assert [page["session_id"] for page in out["pages"]] == ["ses-new", "ses-public"]
+ assert out["limit"] == 3
+ assert [page["session_id"] for page in out["pages"]] == [
+ "ses-new",
+ "ses-limited",
+ "ses-public",
+ ]
assert out["pages"][0]["context"] == "private"
- assert out["pages"][1]["visibility"] == "public"
- assert out["pages"][1]["context"] == "shared"
- assert out["pages"][1]["base_path"].startswith("/p/")
+ assert out["pages"][1]["visibility"] == "limited"
+ assert out["pages"][1]["context"] == "private"
+ assert out["pages"][1]["base_path"] is None
+ assert out["pages"][2]["visibility"] == "public"
+ assert out["pages"][2]["context"] == "shared"
+ assert out["pages"][2]["base_path"].startswith("/p/")
def test_startup_show_page_prewarm_limit_env(monkeypatch):
diff --git a/tests/test_remote_resource_acl_sync.py b/tests/test_remote_resource_acl_sync.py
index 9bf4edb3d..e98747bbb 100644
--- a/tests/test_remote_resource_acl_sync.py
+++ b/tests/test_remote_resource_acl_sync.py
@@ -147,7 +147,8 @@ def _seed_named_resources() -> dict[str, str]:
connection.execute(
show_pages.insert().values(
session_id=resource_ids["show_page"],
- visibility="private",
+ access_mode="private",
+ access_revision=0,
share_id=None,
offline_at=None,
created_at=created_at,
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index 9f0eebdf0..d045a8658 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -5,7 +5,7 @@ from sqlalchemy import select
from config import paths
from core.dock_store import BUILTIN_DOCK_IDS, DockError
-from core.show_pages import ShowPageError, ShowPageStore, public_url
+from core.show_pages import ShowPageError, ShowPageStore
from storage import media_service, project_access_service, projects_service, resource_access_service
from storage import workbench_sessions_service as sessions_service
from storage.db import create_sqlite_engine
@@ -13,7 +13,7 @@ from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, show_pages
from tests.ui_server_test_helpers import _remote_peer, _save_config
from tests.ui_server_test_helpers import csrf_headers
-from vibe import api, remote_access, ui_server
+from vibe import api, internal_client, remote_access, ui_server
from vibe.ui_server import app
@@ -227,8 +227,8 @@ def test_remote_show_page_access_does_not_bypass_acl(
environ_base=_remote_peer(),
)
mutation = client.post(
- "/api/show-pages/ses-public/visibility",
- json={"visibility": "offline"},
+ "/api/show-pages/ses-public/availability",
+ json={"offline": True},
headers=csrf_headers(client, "https://alex.avibe.bot"),
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
@@ -249,8 +249,12 @@ def test_remote_show_page_access_does_not_bypass_acl(
assert {item["session_id"] for item in pages} == expected
if instance_role == "owner":
assert all(item.get("path") for item in pages)
+ assert all(item["can_manage"] for item in pages)
+ assert all(item["can_publish_public"] for item in pages)
else:
assert all("path" not in item for item in pages)
+ assert all(not item["can_manage"] for item in pages)
+ assert all(not item["can_publish_public"] for item in pages)
assert mutation.status_code == (200 if instance_role == "owner" else 403)
assert page.status_code == (200 if instance_role == "owner" else 302)
@@ -313,11 +317,10 @@ def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_p
access_level="public",
group_ids=[],
)
- updated = store.get(page.session_id)
- assert updated is not None
- assert updated.visibility == "private"
- assert updated.share_id is None
- assert public_url(updated.share_id) is None
+ updated = store.get(page.session_id)
+ assert updated is not None
+ assert updated.visibility == "private"
+ assert updated.share_id
finally:
store.close()
@@ -367,7 +370,7 @@ def test_organization_admin_without_instance_owner_role_cannot_manage_pages(monk
store.close()
-def test_access_only_manager_visibility_response_does_not_expose_page_payload(monkeypatch, tmp_path) -> None:
+def test_access_only_manager_availability_response_does_not_expose_page_payload(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
store = _seed_show_pages_with_policies()
@@ -392,10 +395,10 @@ def test_access_only_manager_visibility_response_does_not_expose_page_payload(mo
)
with pytest.raises(ShowPageError):
- api.set_show_page_visibility("ses-private", "private")
+ api.set_show_page_availability("ses-private", True)
-def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:
+def test_excluded_scoped_owner_availability_mutations_do_not_expose_page_payload(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
store = _seed_show_pages_with_policies()
@@ -414,11 +417,11 @@ def test_excluded_scoped_owner_share_mutations_do_not_expose_page_payload(monkey
lambda _value=None: excluded_owner,
)
- rotated = api.rotate_show_page_share("ses-scope")
- customized = api.set_show_page_share_id("ses-scope", "excluded-owner-link")
+ offline = api.set_show_page_availability("ses-scope", True)
+ online = api.set_show_page_availability("ses-scope", False)
- assert rotated["ok"] is True
- assert customized["ok"] is True
+ assert offline["ok"] is True
+ assert online["ok"] is True
def test_remote_show_page_editor_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:
@@ -487,26 +490,32 @@ def test_remote_show_page_viewer_mutations_are_instance_role_denied(monkeypatch,
json={},
**request_options,
)
- published = client.post(
- f"/api/show-pages/{session_id}/visibility",
- json={"visibility": "public"},
+ availability = client.post(
+ f"/api/show-pages/{session_id}/availability",
+ json={"offline": True},
**request_options,
)
- rotated = client.post(
- f"/api/show-pages/{session_id}/rotate-share",
- json={},
+ settings = client.post(
+ f"/api/show-pages/{session_id}/access-settings/read",
+ json={"page_id": session_id},
**request_options,
)
- customized = client.post(
- f"/api/show-pages/{session_id}/share-id",
- json={"share_id": "viewer-owner-link"},
+ applied = client.post(
+ f"/api/show-pages/{session_id}/access-settings/apply",
+ json={
+ "page_id": session_id,
+ "expected_revision": 0,
+ "target_access_mode": "public",
+ "target_share_id": "viewer-owner-link",
+ "target_emails": [],
+ },
**request_options,
)
assert ensured.status_code == 403
- assert published.status_code == 403
- assert rotated.status_code == 403
- assert customized.status_code == 403
+ assert availability.status_code == 403
+ assert settings.status_code == 403
+ assert applied.status_code == 403
def test_organization_admin_can_read_show_page_access_metadata_without_use_access(monkeypatch, tmp_path) -> None:
@@ -568,7 +577,6 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk
"can_use": True,
"can_manage": True,
"can_publish_public": True,
- "public_link_enabled": False,
}
config = _save_config(tmp_path)
@@ -620,7 +628,6 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk
"can_use": True,
"can_manage": True,
"can_publish_public": True,
- "public_link_enabled": False,
}
@@ -633,206 +640,244 @@ def test_show_page_access_api_reports_missing_page_as_definitive_denial(monkeypa
assert response.get_json()["code"] == "show_page_not_found"
-def test_show_page_owner_can_read_and_replace_exact_email_grants(monkeypatch, tmp_path) -> None:
+def _show_access_payload(page_id: str, *, revision: int = 0) -> dict:
+ return {
+ "page_id": page_id,
+ "access_mode": "private",
+ "share_id": "stable-link",
+ "revision": revision,
+ "normalized_emails": [],
+ }
+
+
+def test_show_access_owner_read_and_apply_use_controller_ipc(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = ShowPageStore()
try:
- store.ensure("ses-email-access")
+ store.ensure("ses-access-settings")
finally:
store.close()
+ calls: list[tuple[str, dict]] = []
- calls: list[tuple] = []
- monkeypatch.setattr(
- remote_access,
- "get_show_page_authorized_emails",
- lambda show_page_id: calls.append(("GET", show_page_id))
- or {"emails": ["[email protected]"]},
+ async def _read(payload):
+ calls.append(("read", payload))
+ return {
+ "status_code": 200,
+ "body": {"show_access": _show_access_payload("ses-access-settings")},
+ }
+
+ async def _apply(payload):
+ calls.append(("apply", payload))
+ return {
+ "status_code": 200,
+ "body": {
+ "status": "applied",
+ "show_access": {
+ **_show_access_payload("ses-access-settings", revision=1),
+ "access_mode": "limited",
+ "normalized_emails": ["[email protected]"],
+ },
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "show_access_settings_read", _read)
+ monkeypatch.setattr(internal_client, "show_access_apply", _apply)
+ client = app.test_client()
+ headers = csrf_headers(client)
+ loaded = client.post(
+ "/api/show-pages/ses-access-settings/access-settings/read",
+ json={"page_id": "ses-access-settings"},
+ headers=headers,
)
- monkeypatch.setattr(
- remote_access,
- "replace_show_page_authorized_emails",
- lambda show_page_id, emails: calls.append(("PUT", show_page_id, emails))
- or {"emails": emails, "changed": True},
+ request_payload = {
+ "page_id": "ses-access-settings",
+ "expected_revision": 0,
+ "target_access_mode": "limited",
+ "target_share_id": "stable-link",
+ "target_emails": ["[email protected]"],
+ }
+ applied = client.post(
+ "/api/show-pages/ses-access-settings/access-settings/apply",
+ json=request_payload,
+ headers=headers,
)
- client = app.test_client()
- loaded = client.get("/api/show-pages/ses-email-access/authorized-emails")
- replaced = client.put(
- "/api/show-pages/ses-email-access/authorized-emails",
- json={"emails": [" [email protected] ", "[email protected]"]},
+ assert loaded.status_code == 200
+ assert loaded.headers["Cache-Control"] == "private, no-store"
+ assert loaded.headers["Vary"] == "Cookie"
+ assert loaded.get_json()["show_access"]["page_id"] == "ses-access-settings"
+ assert applied.status_code == 200
+ assert applied.get_json()["status"] == "applied"
+ assert calls == [
+ ("read", {"page_id": "ses-access-settings"}),
+ ("apply", request_payload),
+ ]
+
+
+def test_show_access_route_identity_mismatch_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ async def _unexpected(_payload):
+ pytest.fail("identity mismatch must not reach controller IPC")
+
+ monkeypatch.setattr(internal_client, "show_access_settings_read", _unexpected)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-route/access-settings/read",
+ json={"page_id": "ses-other"},
headers=csrf_headers(client),
)
- assert loaded.status_code == 200
- assert loaded.get_json() == {"ok": True, "emails": ["[email protected]"]}
- assert loaded.headers["Cache-Control"] == "no-store, private"
- assert replaced.status_code == 200
- assert replaced.get_json() == {
- "ok": True,
- "emails": ["[email protected]"],
- "changed": True,
+ assert response.status_code == 400
+ assert response.get_json() == {
+ "ok": False,
+ "error": "show_access_page_identity_mismatch",
}
- assert calls == [
- ("GET", "ses-email-access"),
- ("PUT", "ses-email-access", ["[email protected]"]),
- ]
- ("subject", "organization_role", "instance_role"),
- [
- ("member-1", "member", "viewer"),
- ],
-)
-def test_show_page_email_grants_reject_non_owner_without_contacting_backend(
- monkeypatch,
- tmp_path,
- subject: str,
- organization_role: str,
- instance_role: str,
-) -> None:
+def test_show_access_malformed_apply_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ async def _unexpected(_payload):
+ pytest.fail("malformed request must not reach controller IPC")
+
+ monkeypatch.setattr(internal_client, "show_access_apply", _unexpected)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-route/access-settings/apply",
+ json={
+ "page_id": "ses-route",
+ "expected_revision": True,
+ "target_access_mode": "limited",
+ "target_share_id": ["not-a-string"],
+ "target_emails": ["[email protected]"],
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert response.get_json()["error"] == "invalid_show_access_apply_request"
+
+
+def test_show_access_non_owner_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
store = _seed_show_pages_with_policies()
store.close()
+ viewer = _organization_context("member-1", instance_role="viewer")
monkeypatch.setattr(
resource_access_service,
"resolve_resource_access_context",
- lambda _value=None: resource_access_service.ResourceUserContext(
- subject=subject,
- email=f"{subject}@example.com",
- instance_role=instance_role,
- instance_access_source="email",
- is_remote=True,
- ),
- )
- monkeypatch.setattr(
- remote_access,
- "get_show_page_authorized_emails",
- lambda _show_page_id: pytest.fail("backend must not be contacted"),
+ lambda _value=None: viewer,
)
- response = app.test_client().get(
- "/api/show-pages/ses-public/authorized-emails"
+ async def _unexpected(_payload):
+ pytest.fail("unauthorized request must not reach controller IPC")
+
+ monkeypatch.setattr(internal_client, "show_access_settings_read", _unexpected)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-public/access-settings/read",
+ json={"page_id": "ses-public"},
+ headers=csrf_headers(client),
)
assert response.status_code == 403
assert response.get_json()["code"] == "resource_access_forbidden"
-def test_show_page_email_grants_report_unavailable_without_cloud_pairing(
- monkeypatch, tmp_path
-) -> None:
+def test_show_access_internal_identity_mismatch_hides_email_data(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
store = ShowPageStore()
try:
- store.ensure("ses-email-access")
+ store.ensure("ses-access-settings")
finally:
store.close()
- response = app.test_client().get(
- "/api/show-pages/ses-email-access/authorized-emails"
+ async def _mismatched(_payload):
+ return {
+ "status_code": 200,
+ "body": {
+ "show_access": {
+ **_show_access_payload("ses-other"),
+ "access_mode": "limited",
+ "normalized_emails": ["[email protected]"],
+ }
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "show_access_settings_read", _mismatched)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-access-settings/access-settings/read",
+ json={"page_id": "ses-access-settings"},
+ headers=csrf_headers(client),
)
- assert response.status_code == 400
- assert response.get_json()["code"] == "show_page_email_access_not_configured"
+ assert response.status_code == 502
+ assert response.get_json() == {
+ "ok": False,
+ "error": "show_access_internal_protocol_error",
+ }
+ assert "[email protected]" not in response.text
-def test_show_page_email_grants_report_transient_device_failures_as_retryable(
- monkeypatch, tmp_path
-) -> None:
+def test_show_access_controller_unavailable_is_retryable(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
store = ShowPageStore()
try:
- store.ensure("ses-email-access-transient")
+ store.ensure("ses-access-settings")
finally:
store.close()
- monkeypatch.setattr(
- remote_access,
- "get_show_page_authorized_emails",
- lambda _show_page_id: (_ for _ in ()).throw(
- RuntimeError("resource_acl_device_unavailable")
- ),
- )
- response = app.test_client().get(
- "/api/show-pages/ses-email-access-transient/authorized-emails"
+ async def _unavailable(_payload):
+ raise internal_client.InternalServerUnavailable("missing controller socket")
+
+ monkeypatch.setattr(internal_client, "show_access_settings_read", _unavailable)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-access-settings/access-settings/read",
+ json={"page_id": "ses-access-settings"},
+ headers=csrf_headers(client),
)
assert response.status_code == 503
- assert response.get_json()["code"] == "show_page_email_access_transient"
+ assert response.get_json()["error"] == "show_access_controller_unavailable"
-def test_show_page_email_grant_device_requests_freeze_the_target(monkeypatch, tmp_path) -> None:
+def test_show_access_conflict_returns_current_snapshot(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
- calls: list[tuple] = []
- monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda cfg, method, suffix, payload=None: calls.append(
- (cfg, method, suffix, payload)
- )
- or (
- {"emails": ["[email protected]"]}
- if method == "GET"
- else {
- "emails": ["[email protected]"],
- "changed": True,
- "authorization_revision": 9,
- }
- ),
- )
- revisions: list[int] = []
- monkeypatch.setattr(
- remote_access,
- "_replace_authorization_revision",
- lambda _config, revision: revisions.append(revision) or revision,
- )
-
- loaded = remote_access.get_show_page_authorized_emails("session/one", config)
- replaced = remote_access.replace_show_page_authorized_emails(
- "session/one",
- config,
- )
-
- assert loaded == {"emails": ["[email protected]"]}
- assert replaced == {"emails": ["[email protected]"], "changed": True}
- assert calls == [
- (config, "GET", "show-pages/session%2Fone/authorized-emails", None),
- (
- config,
- "PUT",
- "show-pages/session%2Fone/authorized-emails",
- {"emails": ["[email protected]"]},
- ),
- ]
- assert revisions == [9]
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-access-settings")
+ finally:
+ store.close()
+ async def _conflict(_payload):
+ return {
+ "status_code": 200,
+ "body": {
+ "status": "conflict",
+ "show_access": _show_access_payload("ses-access-settings", revision=3),
+ },
+ }
-def test_show_page_email_grant_change_requires_authorization_revision(monkeypatch, tmp_path) -> None:
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
- monkeypatch.setattr(remote_access, "_resource_acl_sync_configured", lambda _config: True)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *_args, **_kwargs: {
- "emails": ["[email protected]"],
- "changed": True,
+ monkeypatch.setattr(internal_client, "show_access_apply", _conflict)
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses-access-settings/access-settings/apply",
+ json={
+ "page_id": "ses-access-settings",
+ "expected_revision": 2,
+ "target_access_mode": "public",
+ "target_share_id": "stable-link",
+ "target_emails": [],
},
+ headers=csrf_headers(client),
)
- with pytest.raises(RuntimeError, match="show_page_email_access_invalid_response"):
- remote_access.replace_show_page_authorized_emails(
- "session-one",
- config,
- )
+ assert response.status_code == 200
+ assert response.get_json()["status"] == "conflict"
+ assert response.get_json()["show_access"]["revision"] == 3
def test_remote_org_dock_requires_admin_owner_role(monkeypatch, tmp_path) -> None:
diff --git a/tests/test_session_archive.py b/tests/test_session_archive.py
index a34436b5e..8b9964efa 100644
--- a/tests/test_session_archive.py
+++ b/tests/test_session_archive.py
@@ -121,7 +121,13 @@ def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:
_insert_run(conn, run_id="run_done", session_id=sid, status="succeeded")
conn.execute(
show_pages.insert().values(
- session_id=sid, visibility="public", share_id="shareX", created_at=NOW, updated_at=NOW
+ session_id=sid,
+ access_mode="public",
+ access_revision=0,
+ share_id="shareX",
+ offline_at=None,
+ created_at=NOW,
+ updated_at=NOW,
)
)
vs.create_secret(conn, name="ARCHIVE_KEY", protection="protected", sealed=Sealed("ct", "nonce", "wrap"))
@@ -223,7 +229,6 @@ def test_archive_reclaims_bound_resources(tmp_path: Path) -> None:
assert runs["run_done"]["status"] == "succeeded" # terminal → untouched
page = conn.execute(select(show_pages).where(show_pages.c.session_id == sid)).mappings().first()
- assert page["visibility"] == "offline"
assert page["offline_at"] is not None
grant_row = conn.execute(select(vault_grants).where(vault_grants.c.id == grant["id"])).mappings().one()
reserved_grant_row = conn.execute(
diff --git a/tests/test_show_page_legacy_ui_removed.py b/tests/test_show_page_legacy_ui_removed.py
new file mode 100644
index 000000000..693e95bfb
--- /dev/null
+++ b/tests/test_show_page_legacy_ui_removed.py
@@ -0,0 +1,125 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def test_hosted_email_routes_and_clients_are_removed() -> None:
+ production_sources = [
+ ROOT / "vibe" / "api.py",
+ ROOT / "vibe" / "authorization.py",
+ ROOT / "vibe" / "remote_access.py",
+ ROOT / "vibe" / "ui_server.py",
+ ROOT / "tests" / "test_instance_authorization.py",
+ ]
+ forbidden = {
+ "authorized-emails",
+ "get_show_page_authorized_emails",
+ "replace_show_page_authorized_emails",
+ "/visibility",
+ "/rotate-share",
+ "/share-id",
+ "set_show_page_visibility",
+ "rotate_show_page_share",
+ "set_show_page_share_id",
+ "public_link_enabled",
+ }
+
+ for source_path in production_sources:
+ source = source_path.read_text(encoding="utf-8")
+ for symbol in forbidden:
+ assert symbol not in source, f"legacy hosted-email surface remains in {source_path}: {symbol}"
+
+
+def test_legacy_show_page_frontend_surface_is_removed() -> None:
+ component_dir = ROOT / "ui" / "src" / "components" / "workbench"
+ assert not (component_dir / "ShowPageEmailAccessEditor.tsx").exists()
+ assert not (component_dir / "ShowPageShareIdField.tsx").exists()
+
+ forbidden = {
+ "ShowPageEmailAccessEditor",
+ "ShowPageShareIdField",
+ "getShowPageAuthorizedEmails",
+ "replaceShowPageAuthorizedEmails",
+ "setShowPageVisibility",
+ "rotateShowPageShare",
+ "setShowPageShareId",
+ "public_link_enabled",
+ }
+ frontend_sources = [
+ path
+ for path in (ROOT / "ui" / "src").rglob("*")
+ if path.suffix in {".ts", ".tsx"} and ".test." not in path.name
+ ]
+ for source_path in frontend_sources:
+ source = source_path.read_text(encoding="utf-8")
+ for symbol in forbidden:
+ assert symbol not in source, f"legacy frontend surface remains in {source_path}: {symbol}"
+
+
+def test_legacy_show_page_copy_is_removed_from_both_locales() -> None:
+ removed_show_pages_keys = {
+ "visibilityLabel",
+ "visibilityOffline",
+ "shareLink",
+ "rotate",
+ "rotateHint",
+ }
+ removed_chat_keys = {
+ "rotateLink",
+ "visibilityPublic",
+ "visibilityPrivate",
+ "publicDesc",
+ "privateDesc",
+ "emailAccess",
+ "emailAccessDesc",
+ "emailAccessEmpty",
+ "emailAccessLimit",
+ "applyEmailAccess",
+ "loadingEmailAccess",
+ "emailAccessUnavailable",
+ "emailAccessError",
+ "publicLink",
+ "publicLinkOnDesc",
+ "publicLinkOffDesc",
+ "publicLinkOwnerOnly",
+ "publicLinkOffline",
+ "customLink",
+ "offlineNote",
+ "publicUnavailable",
+ "sharingOffline",
+ }
+
+ for locale in ("en", "zh"):
+ payload = json.loads(
+ (ROOT / "ui" / "src" / "i18n" / f"{locale}.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ assert removed_show_pages_keys.isdisjoint(payload["showPages"])
+ assert removed_chat_keys.isdisjoint(payload["chat"]["showPage"])
+ assert "show_page_email_access_transient" not in payload["errors"]
+
+
+def test_legacy_show_page_ui_plans_are_removed() -> None:
+ plans_dir = ROOT / "docs" / "plans"
+ assert not (plans_dir / "show-page-email-access.md").exists()
+
+ forbidden = {
+ "ShowPageEmailAccessEditor",
+ "ShowPageShareIdField",
+ "getShowPageAuthorizedEmails",
+ "replaceShowPageAuthorizedEmails",
+ "setShowPageVisibility",
+ "rotateShowPageShare",
+ "setShowPageShareId",
+ "visibility private/public/offline",
+ "Share visibility / rotate / share-id",
+ }
+ for source_path in plans_dir.glob("*.md"):
+ source = source_path.read_text(encoding="utf-8")
+ for symbol in forbidden:
+ assert symbol not in source, f"legacy Show Page UI plan remains in {source_path}: {symbol}"
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index d5eb1e900..35ae9ceb5 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -7,6 +7,7 @@ import pytest
from config import paths
from config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
from core.show_pages import (
+ SHOW_ACCESS_EMAIL_MAX_COUNT,
ShowPage,
ShowPageError,
ShowPageStore,
@@ -389,7 +390,7 @@ def test_store_defaults_to_private_and_rotates_public_share(monkeypatch, tmp_pat
try:
page = store.ensure("ses123")
assert page.visibility == "private"
- assert page.share_id is None
+ assert page.share_id
public_page = store.update_visibility("ses123", "public")
assert public_page.visibility == "public"
@@ -422,7 +423,7 @@ def test_rotate_share_requires_public(monkeypatch, tmp_path):
try:
store.rotate_share("ses123")
except ShowPageError as exc:
- assert exc.code == "not_public"
+ assert exc.code == "not_shared"
else:
raise AssertionError("rotate_share should fail while private")
finally:
@@ -475,7 +476,7 @@ def test_set_share_id_requires_public(monkeypatch, tmp_path):
store = ShowPageStore()
try:
store.ensure("ses123") # defaults to private
- _expect_show_page_error(lambda: store.set_share_id("ses123", "my-demo"), "not_public")
+ _expect_show_page_error(lambda: store.set_share_id("ses123", "my-demo"), "not_shared")
finally:
store.close()
@@ -528,6 +529,271 @@ def test_set_share_id_is_idempotent(monkeypatch, tmp_path):
store.close()
+def test_show_access_apply_normalizes_and_no_op_does_not_advance_revision(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-access")
+ applied = store.apply_access(
+ "ses-access",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=[
+ ],
+ )
+ assert applied.status == "applied"
+ assert applied.show_access.revision == 1
+ assert applied.show_access.normalized_emails == (
+ )
+
+ no_change = store.apply_access(
+ "ses-access",
+ expected_revision=1,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]", " [email protected] "],
+ )
+ assert no_change.status == "no_change"
+ assert no_change.show_access.revision == 1
+ assert no_change.show_access == applied.show_access
+ finally:
+ store.close()
+
+
+ "email",
+ [
+ "guest@@example.com",
+ "guest@exam_ple.com",
+ ],
+)
+def test_show_access_apply_rejects_email_outside_contract(monkeypatch, tmp_path, email) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-invalid-email")
+ result = store.apply_access(
+ "ses-invalid-email",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=[email],
+ )
+
+ assert result.status == "invalid"
+ assert result.show_access.revision == 0
+ assert result.show_access.access_mode == "private"
+ assert result.show_access.normalized_emails == ()
+ finally:
+ store.close()
+
+
+def test_show_access_apply_rejects_email_audience_over_limit_without_write(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-email-limit")
+ allowed_emails = [
+ f"guest-{index}@example.com"
+ for index in range(SHOW_ACCESS_EMAIL_MAX_COUNT)
+ ]
+ allowed = store.apply_access(
+ "ses-email-limit",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=allowed_emails,
+ )
+ result = store.apply_access(
+ "ses-email-limit",
+ expected_revision=allowed.show_access.revision,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=[*allowed_emails, "[email protected]"],
+ )
+
+ assert allowed.status == "applied"
+ assert len(allowed.show_access.normalized_emails) == SHOW_ACCESS_EMAIL_MAX_COUNT
+ assert result.status == "invalid"
+ assert result.show_access == allowed.show_access
+ finally:
+ store.close()
+
+
+ ("mode", "share_id", "emails"),
+ [
+ ("limited", "stable-link", []),
+ ("limited", None, ["[email protected]"]),
+ ("public", None, []),
+ ("public", "stable-link", ["[email protected]"]),
+ ("private", "stable-link", ["[email protected]"]),
+ ],
+)
+def test_show_access_apply_enforces_closed_mode_invariants(
+ monkeypatch, tmp_path, mode, share_id, emails
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-invalid-mode")
+ result = store.apply_access(
+ "ses-invalid-mode",
+ expected_revision=0,
+ target_access_mode=mode,
+ target_share_id=share_id,
+ target_emails=emails,
+ )
+
+ assert result.status == "invalid"
+ assert result.show_access.revision == 0
+ assert result.show_access.access_mode == "private"
+ assert result.show_access.normalized_emails == ()
+ finally:
+ store.close()
+
+
+def test_show_access_private_retains_binding_and_leaving_limited_clears_emails(
+ monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-stable-access")
+ limited = store.apply_access(
+ "ses-stable-access",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]"],
+ )
+ private = store.apply_access(
+ "ses-stable-access",
+ expected_revision=limited.show_access.revision,
+ target_access_mode="private",
+ target_share_id=None,
+ target_emails=[],
+ )
+
+ assert private.status == "applied"
+ assert private.show_access.access_mode == "private"
+ assert private.show_access.share_id == page.share_id
+ assert private.show_access.normalized_emails == ()
+ assert private.show_access.revision == 2
+ finally:
+ store.close()
+
+
+def test_show_access_stale_revision_has_no_write(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-conflict")
+ limited = store.apply_access(
+ "ses-conflict",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]"],
+ )
+ conflict = store.apply_access(
+ "ses-conflict",
+ expected_revision=0,
+ target_access_mode="public",
+ target_share_id="replacement-link",
+ target_emails=[],
+ )
+
+ assert conflict.status == "conflict"
+ assert conflict.show_access == limited.show_access
+ assert store.get_access("ses-conflict") == limited.show_access
+ finally:
+ store.close()
+
+
+def test_show_access_share_collision_rolls_back_whole_aggregate(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ first = store.ensure("ses-first")
+ second = store.ensure("ses-second")
+ first_limited = store.apply_access(
+ "ses-first",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id="taken-link",
+ target_emails=["[email protected]"],
+ )
+ second_limited = store.apply_access(
+ "ses-second",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=second.share_id,
+ target_emails=["[email protected]"],
+ )
+ assert first_limited.status == second_limited.status == "applied"
+
+ collision = store.apply_access(
+ "ses-second",
+ expected_revision=1,
+ target_access_mode="limited",
+ target_share_id="taken-link",
+ target_emails=["[email protected]"],
+ )
+
+ assert collision.status == "share_id_taken"
+ assert collision.show_access == second_limited.show_access
+ assert collision.show_access.share_id == second.share_id
+ assert collision.show_access.normalized_emails == ("[email protected]",)
+ assert store.get_by_share_id("taken-link").session_id == first.session_id
+ finally:
+ store.close()
+
+
+def test_show_access_and_availability_are_independent(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-offline-access")
+ limited = store.apply_access(
+ "ses-offline-access",
+ expected_revision=0,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]"],
+ )
+ offline = store.set_offline("ses-offline-access", True)
+ assert offline.offline is True
+ assert store.get_access("ses-offline-access") == limited.show_access
+
+ public = store.apply_access(
+ "ses-offline-access",
+ expected_revision=1,
+ target_access_mode="public",
+ target_share_id=page.share_id,
+ target_emails=[],
+ )
+ assert public.status == "applied"
+ assert public.show_access.revision == 2
+ assert public.show_access.access_mode == "public"
+ assert store.get("ses-offline-access").offline is True
+ finally:
+ store.close()
+
+
def test_set_share_id_rejects_archived_session(monkeypatch, tmp_path):
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
@@ -981,7 +1247,8 @@ def test_extract_icon_path_accepts_whitelisted_image_extensions(tmp_path):
def _icon_page(session_id: str) -> ShowPage:
return ShowPage(
session_id=session_id,
- visibility="private",
+ access_mode="private",
+ access_revision=0,
share_id=None,
offline_at=None,
created_at="2026-01-01T00:00:00Z",
@@ -1761,7 +2028,7 @@ def test_show_path_cli_json_creates_page(monkeypatch, tmp_path, capsys):
assert payload["visibility"] == "private"
assert payload["active_url"] == "https://alex.avibe.bot/show/ses123/"
assert payload["private_url"] == "https://alex.avibe.bot/show/ses123/"
- assert payload["public_url"] is None
+ assert payload["public_url"].startswith("https://alex.avibe.bot/p/")
assert payload["url_available"] is True
assert payload["url_guidance"] is None
assert "Do not send implementation details such as local paths to the user unless they ask for them." in payload["next_actions"]
@@ -2011,6 +2278,14 @@ def test_show_list_cli_filters_visibility(monkeypatch, tmp_path, capsys):
store = ShowPageStore()
try:
store.ensure("ses-private")
+ limited = store.ensure("ses-limited")
+ store.apply_access(
+ "ses-limited",
+ expected_revision=limited.access_revision,
+ target_access_mode="limited",
+ target_share_id=limited.share_id,
+ target_emails=["[email protected]"],
+ )
store.update_visibility("ses-public", "public")
finally:
store.close()
@@ -2022,6 +2297,17 @@ def test_show_list_cli_filters_visibility(monkeypatch, tmp_path, capsys):
assert "Count: 1" in output
assert "Filter: visibility=private" in output
assert "- ses-private" in output
+ assert "- ses-limited" not in output
+ assert "- ses-public" not in output
+
+ args = cli.build_parser().parse_args(["show", "list", "--visibility", "limited"])
+ assert cli.cmd_show_list(args) == 0
+
+ output = capsys.readouterr().out
+ assert "Count: 1" in output
+ assert "Filter: visibility=limited" in output
+ assert "- ses-private" not in output
+ assert "- ses-limited" in output
assert "- ses-public" not in output
@@ -2047,6 +2333,31 @@ def test_show_page_payload_requires_enabled_avibe_cloud(monkeypatch, tmp_path):
store.close()
+def test_show_page_payload_does_not_advertise_limited_link_before_guest_admission(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ _save_config()
+
+ store = ShowPageStore()
+ try:
+ page = store.ensure("ses-limited-link")
+ limited = store.apply_access(
+ page.session_id,
+ expected_revision=page.access_revision,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]"],
+ )
+ payload = show_page_payload(store.get(page.session_id))
+
+ assert limited.status == "applied"
+ assert payload["visibility"] == "limited"
+ assert payload["active_url"] is None
+ assert payload["public_url"].endswith(f"/p/{page.share_id}/")
+ finally:
+ store.close()
+
+
def test_show_update_cli_reports_transition_urls(monkeypatch, tmp_path, capsys):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
@@ -2130,7 +2441,7 @@ def test_show_update_rotate_share_fails_while_private(monkeypatch, tmp_path, cap
args = parser.parse_args(["show", "update", "--session-id", "ses123", "--rotate-share", "--json"])
assert cli.cmd_show_update(args) == 1
payload = json.loads(capsys.readouterr().err)
- assert payload["code"] == "not_public"
+ assert payload["code"] == "not_shared"
def _seed_show_cli_session(session_id: str = "ses123") -> None:
diff --git a/tests/test_show_pages_admin_api.py b/tests/test_show_pages_admin_api.py
index 0f0adbef8..81836a3b7 100644
--- a/tests/test_show_pages_admin_api.py
+++ b/tests/test_show_pages_admin_api.py
@@ -1,9 +1,7 @@
-"""Web UI admin Show Pages API: listing (with title join), visibility, rotate."""
+"""Web UI admin Show Pages API: listing and orthogonal availability."""
-import pytest
-
-from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
-from tests.ui_server_test_helpers import _save_config
+from core.show_pages import ShowPageStore, ensure_show_page_dir
+from tests.ui_server_test_helpers import _save_config, csrf_headers
from vibe import api
from vibe.ui_server import app
@@ -77,6 +75,8 @@ def test_list_show_pages_orders_newest_first_and_joins_title(monkeypatch, tmp_pa
assert by_id["ses_titled"]["agent"] == "Claude"
assert by_id["ses_titled"]["visibility"] == "public"
assert by_id["ses_titled"]["share_id"]
+ assert by_id["ses_titled"]["can_manage"] is True
+ assert by_id["ses_titled"]["can_publish_public"] is True
# IM-dispatch sessions persist title=None; the UI falls back to the id.
assert by_id["ses_plain"]["title"] is None
assert by_id["ses_plain"]["visibility"] == "private"
@@ -118,49 +118,37 @@ def test_list_show_pages_preserves_archived_agent_display_name(monkeypatch, tmp_
store.close()
-def test_set_show_page_visibility_public_then_offline(monkeypatch, tmp_path):
+def test_set_show_page_availability_preserves_configured_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
_seed_session("ses_x")
- _set_visibility("ses_x", "private")
-
- public = api.set_show_page_visibility("ses_x", "public")
- assert public["ok"] is True
- assert public["visibility"] == "public"
- assert public["share_id"]
+ _set_visibility("ses_x", "public")
- offline = api.set_show_page_visibility("ses_x", "offline")
+ offline = api.set_show_page_availability("ses_x", True)
assert offline["visibility"] == "offline"
assert offline["offline"] is True
assert offline["offline_at"]
+ share_id = offline["share_id"]
+ online = api.set_show_page_availability("ses_x", False)
+ assert online["visibility"] == "public"
+ assert online["offline"] is False
+ assert online["share_id"] == share_id
-def test_set_show_page_visibility_rejects_invalid(monkeypatch, tmp_path):
+
+def test_show_page_availability_route_rejects_non_boolean_payload(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
- _seed_session("ses_x")
- with pytest.raises(ShowPageError) as excinfo:
- api.set_show_page_visibility("ses_x", "bogus")
- assert excinfo.value.code == "invalid_visibility"
+ client = app.test_client()
+ response = client.post(
+ "/api/show-pages/ses_x/availability",
+ json={"offline": "yes"},
+ headers=csrf_headers(client),
+ )
-
-def test_rotate_share_requires_public_and_revokes_previous(monkeypatch, tmp_path):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _save_config(tmp_path)
- _seed_session("ses_x")
- _set_visibility("ses_x", "private")
-
- with pytest.raises(ShowPageError) as excinfo:
- api.rotate_show_page_share("ses_x")
- assert excinfo.value.code == "not_public"
-
- public = api.set_show_page_visibility("ses_x", "public")
- rotated = api.rotate_show_page_share("ses_x")
- assert rotated["ok"] is True
- assert rotated["share_id"]
- assert rotated["share_id"] != public["share_id"]
- assert rotated["previous_share_id"] == public["share_id"]
+ assert response.status_code == 400
+ assert response.get_json()["code"] == "invalid_availability"
def test_show_pages_list_route_returns_payload(monkeypatch, tmp_path):
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 76025b1ab..1126927b0 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -31,7 +31,7 @@ from vibe.message_types import build_partial_index_predicate
pytestmark = pytest.mark.no_sqlite_template
-HEAD_REVISION = "20260815_0054"
+HEAD_REVISION = "20260817_0055"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type in "
@@ -50,6 +50,139 @@ MESSAGE_PARTIAL_INDEX_PREDICATES = {
}
+def test_local_show_access_migration_round_trip_preserves_pages_and_fails_closed(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ run_migrations(db_path, revision="20260815_0054")
+ legacy_rows = [
+ ("private-null", "private", None, None),
+ ("private-stable", "private", "private-link", None),
+ ("public-null", "public", None, None),
+ ("public-stable", "public", "public-link", None),
+ ("offline-null", "offline", None, None),
+ ("offline-stable", "offline", "offline-link", "2026-08-16T00:00:00Z"),
+ ]
+ with sqlite3.connect(db_path) as conn:
+ conn.executemany(
+ """
+ insert into show_pages (
+ session_id, visibility, share_id, offline_at, created_at, updated_at
+ ) values (?, ?, ?, ?, '2026-08-15T00:00:00Z', '2026-08-16T00:00:00Z')
+ """,
+ legacy_rows,
+ )
+
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ conn.execute("pragma foreign_keys = on")
+ columns = {row[1] for row in conn.execute("pragma table_info(show_pages)")}
+ rows = {
+ row[0]: row[1:]
+ for row in conn.execute(
+ "select session_id, access_mode, access_revision, share_id, offline_at "
+ "from show_pages order by session_id"
+ )
+ }
+ assert "visibility" not in columns
+ assert {"access_mode", "access_revision", "share_id", "offline_at"}.issubset(columns)
+ assert rows["private-null"][0:2] == ("private", 0)
+ assert rows["private-stable"] == ("private", 0, "private-link", None)
+ assert rows["public-null"][0:2] == ("public", 0)
+ assert rows["public-stable"] == ("public", 0, "public-link", None)
+ assert rows["offline-null"][0] == "private"
+ assert rows["offline-null"][3] == "2026-08-16T00:00:00Z"
+ assert rows["offline-stable"] == (
+ "private",
+ 0,
+ "offline-link",
+ "2026-08-16T00:00:00Z",
+ )
+ assert all(row[2] for row in rows.values())
+
+ show_indexes = {row[1] for row in conn.execute("pragma index_list(show_pages)")}
+ email_indexes = {
+ row[1]
+ for row in conn.execute("pragma index_list(show_page_authorized_emails)")
+ }
+ assert {"ix_show_pages_share_id", "ix_show_pages_access_mode"}.issubset(show_indexes)
+ assert "ix_show_page_authorized_emails_email" in email_indexes
+ foreign_key = conn.execute(
+ "pragma foreign_key_list(show_page_authorized_emails)"
+ ).fetchone()
+ assert foreign_key is not None
+ assert foreign_key[2] == "show_pages"
+ assert foreign_key[6].upper() == "CASCADE"
+
+ with pytest.raises(sqlite3.IntegrityError):
+ conn.execute(
+ "update show_pages set access_mode = 'other' where session_id = 'private-null'"
+ )
+ with pytest.raises(sqlite3.IntegrityError):
+ conn.execute(
+ "update show_pages set access_revision = -1 where session_id = 'private-null'"
+ )
+
+ conn.execute(
+ "update show_pages set access_mode = 'limited', access_revision = 3 "
+ "where session_id = 'private-stable'"
+ )
+ conn.execute(
+ "insert into show_page_authorized_emails values (?, ?, ?)",
+ ("private-stable", "[email protected]", "2026-08-17T00:00:00Z"),
+ )
+ conn.execute(
+ "insert into show_page_authorized_emails values (?, ?, ?)",
+ ("private-null", "[email protected]", "2026-08-17T00:00:00Z"),
+ )
+ conn.execute("delete from show_pages where session_id = 'private-null'")
+ assert conn.execute(
+ "select count(*) from show_page_authorized_emails "
+ "where session_id = 'private-null'"
+ ).fetchone() == (0,)
+
+ command.downgrade(migrations.alembic_config(db_path), "20260815_0054")
+ with sqlite3.connect(db_path) as conn:
+ columns = {row[1] for row in conn.execute("pragma table_info(show_pages)")}
+ downgraded = dict(
+ conn.execute(
+ "select session_id, visibility from show_pages order by session_id"
+ )
+ )
+ retained_slugs = dict(
+ conn.execute("select session_id, share_id from show_pages order by session_id")
+ )
+ assert "visibility" in columns
+ assert "access_mode" not in columns
+ assert "access_revision" not in columns
+ assert "show_page_authorized_emails" not in {
+ row[0]
+ for row in conn.execute(
+ "select name from sqlite_master where type = 'table'"
+ )
+ }
+ assert downgraded["private-stable"] == "private"
+ assert downgraded["public-null"] == "public"
+ assert downgraded["public-stable"] == "public"
+ assert downgraded["offline-null"] == "offline"
+ assert downgraded["offline-stable"] == "offline"
+ assert retained_slugs["private-stable"] == "private-link"
+ assert retained_slugs["public-stable"] == "public-link"
+ assert retained_slugs["offline-stable"] == "offline-link"
+
+ run_migrations(db_path)
+ with sqlite3.connect(db_path) as conn:
+ reupgraded = conn.execute(
+ "select access_mode, access_revision, share_id from show_pages "
+ "where session_id = 'private-stable'"
+ ).fetchone()
+ email_count = conn.execute(
+ "select count(*) from show_page_authorized_emails"
+ ).fetchone()
+ assert reupgraded == ("private", 0, "private-link")
+ assert email_count == (0,)
+
+
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
row = conn.execute("select sql from sqlite_master where type = 'index' and name = ?", (name,)).fetchone()
assert row is not None
@@ -3991,6 +4124,12 @@ def test_run_migrations_backfills_existing_session_policy_only_for_targeted_defi
engine.dispose()
with sqlite3.connect(db_path) as conn:
+ # This fixture stamps the database at 0002 and then exercises every later
+ # migration. Current metadata has already replaced the 0004-era
+ # ``show_pages.visibility`` shape, so remove the future tables instead of
+ # presenting 0004 with an impossible hybrid schema.
+ conn.execute("drop table show_page_authorized_emails")
+ conn.execute("drop table show_pages")
conn.execute("update run_definitions set session_policy = null")
conn.execute(
"""
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 65b094a19..669dba5b3 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -729,14 +729,6 @@ def _machine_coded_error_builders():
"show_page_not_found",
404,
),
- (
- "show_page_email_transient",
- lambda: ui_server._show_page_error_response(
- _Coded("temporary failure", "show_page_email_access_transient")
- ),
- "show_page_email_access_transient",
- 503,
- ),
("dock", lambda: ui_server._dock_error_response(_Coded("nope", "show_page_not_found")), "show_page_not_found", 404),
(
"show_page_icon",
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index effb8f2b4..863700d50 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -179,7 +179,20 @@ def _create_show_page(session_id: str, visibility: str) -> str | None:
(page_dir / "app.js").write_text("window.showPage = true;", encoding="utf-8")
store = ShowPageStore()
try:
- page = store.update_visibility(session_id, visibility)
+ if visibility == "limited":
+ page = store.ensure(session_id)
+ result = store.apply_access(
+ session_id,
+ expected_revision=page.access_revision,
+ target_access_mode="limited",
+ target_share_id=page.share_id,
+ target_emails=["[email protected]"],
+ )
+ assert result.status == "applied"
+ page = store.get(session_id)
+ assert page is not None
+ else:
+ page = store.update_visibility(session_id, visibility)
# The factory represents a page that has been published to this test
# Organization. Runtime access still requires the caller's Instance role;
# this ACL only supplies the independent Show Page entitlement.
@@ -437,6 +450,30 @@ def test_public_show_page_serves_from_authed_route(monkeypatch, tmp_path):
assert b"Show Page" in response.content
+def test_limited_show_page_uses_authed_editor_route_but_not_anonymous_route(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "limited")
+
+ editor = app.test_client().get(
+ "/show/ses123/",
+ base_url="http://127.0.0.1:5123",
+ )
+ shared = app.test_client().get(
+ f"/p/{share_id}/",
+ base_url="http://127.0.0.1:5123",
+ )
+
+ assert editor.status_code == 200
+ assert b"Show Page" in editor.content
+ # Limited guest admission belongs to the identity/shared-Runtime delivery
+ # lane. Until that lands, the anonymous route remains fail-closed.
+ assert shared.status_code == 404
+
+
def test_public_show_page_still_requires_remote_login(monkeypatch, tmp_path):
# Auth parity: serving public pages here adds no anonymous exposure — the
# authed route still bounces a remote request without a session to login
@@ -6303,17 +6340,22 @@ def test_private_show_page_hmr_websocket_accepts_setup_host_local_peer(monkeypat
]
-def test_public_show_page_hmr_websocket_accepts_local_peer(monkeypatch, tmp_path):
- # Amendment §2.3: the HMR socket serves public pages too, so a public page's
- # /show/ HMR socket gets PAST the visibility gate (then fails at the fake
[email protected]("visibility", ["limited", "public"])
+def test_shared_mode_show_page_hmr_websocket_accepts_local_peer(
+ monkeypatch,
+ tmp_path,
+ visibility,
+):
+ # The HMR socket serves all authenticated editor modes, so a shared-mode
+ # /show/ HMR socket gets PAST the audience gate (then fails at the fake
# runtime proxy with 1011 — not the 1008 visibility rejection an offline page
- # would get), keeping live HMR for a page pinned while public.
+ # would get), keeping live HMR when the audience changes.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
config.ui.setup_host = "192.168.2.3"
config.save()
_mock_interface(monkeypatch, "192.168.2.3", 24)
- _create_show_page("ses123", "public")
+ _create_show_page("ses123", visibility)
manager = _FakeShowRuntimeManager()
set_show_runtime_manager_for_tests(manager)
try:
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 4f875d432..803b3abe4 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -123,7 +123,7 @@
"@typescript-eslint/no-explicit-any": 5
},
"src/context/ApiContext.tsx": {
- "@typescript-eslint/no-explicit-any": 51,
+ "@typescript-eslint/no-explicit-any": 50,
"react-refresh/only-export-components": 1
},
"src/context/DockProvider.tsx": {
diff --git a/ui/src/apps/appLibrary.ts b/ui/src/apps/appLibrary.ts
index 77b2372d4..dda19ed4e 100644
--- a/ui/src/apps/appLibrary.ts
+++ b/ui/src/apps/appLibrary.ts
@@ -83,11 +83,11 @@ export function partitionByDock(rows: readonly AppRow[], order: readonly string[
return { docked, undocked };
}
-export type ShowPageFilter = 'all' | 'public' | 'private' | 'offline';
+export type ShowPageFilter = 'all' | 'public' | 'limited' | 'private' | 'offline';
export interface FilterablePage {
session_id: string;
- visibility: 'public' | 'private' | 'offline';
+ visibility: 'public' | 'limited' | 'private' | 'offline';
title: string | null;
}
diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsx
index b23ba5cb9..2b090fe66 100644
--- a/ui/src/components/ShowPagesPage.tsx
+++ b/ui/src/components/ShowPagesPage.tsx
@@ -13,7 +13,6 @@ import {
Pencil,
Plus,
RefreshCw,
- RotateCw,
TriangleAlert,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -25,28 +24,29 @@ import { useWindowManager } from '../context/WindowManagerContext';
import { copyTextToClipboard } from '../lib/utils';
import { internalPwaLinkTarget, openLinkInNewContext } from '../lib/pwaNavigation';
import { copyHref, displayLink } from '../lib/showPageLinks';
-import type { ShowPageVisibilityResult } from '../lib/showPageAccess';
import { type ShowPage, type ShowPagesController, type Visibility } from './useShowPages';
import { appTabHref, isAppleContextClick, tabModifierLabel, type LaunchModifiers } from '../apps/appLaunch';
import { filterShowPages, type ShowPageFilter } from '../apps/appLibrary';
import { SHARED_ACTION_ZONE } from '../apps/rowLayout';
import { ShowPageAvatarTile } from '../apps/showPageAvatarTile';
-import { ShowPageShareIdField } from './workbench/ShowPageShareIdField';
+import { ShowPageSharingSettings } from './workbench/ShowPageSharingSettings';
import { SearchField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Input } from './ui/input';
-import { SegmentedRadio, type SegmentedTone } from './ui/segmented';
+import { SegmentedRadio } from './ui/segmented';
+import { Switch } from './ui/switch';
const LABEL = 'font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted';
// Visibility → badge variant, active segmented tone, and status dot. The row
// tile is now a letter avatar (hashed by session), so visibility reads from the
// badge rather than a per-state icon.
-const STATUS: Record<Visibility, { badge: 'warning' | 'info' | 'secondary'; tone: SegmentedTone; dot: string }> = {
- public: { badge: 'warning', tone: 'gold', dot: 'bg-gold' },
- private: { badge: 'info', tone: 'cyan', dot: 'bg-cyan' },
- offline: { badge: 'secondary', tone: 'muted', dot: 'bg-muted' },
+const STATUS: Record<Visibility, { badge: 'warning' | 'info' | 'secondary'; dot: string }> = {
+ public: { badge: 'warning', dot: 'bg-gold' },
+ limited: { badge: 'info', dot: 'bg-mint' },
+ private: { badge: 'info', dot: 'bg-cyan' },
+ offline: { badge: 'secondary', dot: 'bg-muted' },
};
interface RowProps {
@@ -62,10 +62,9 @@ interface RowProps {
onToggleInstall: (next: boolean) => void;
onRename: (title: string | null) => Promise<void>;
onUploadIcon: (file: File) => Promise<void>;
- onSetVisibility: (visibility: Visibility) => void;
- onRotate: () => void;
+ onSetOffline: (offline: boolean) => void;
onCopy: () => void;
- onShareIdSaved: (payload: ShowPageVisibilityResult, sessionId: string) => void;
+ onReload: () => void;
}
function ShowPageRow({
@@ -80,10 +79,9 @@ function ShowPageRow({
onToggleInstall,
onRename,
onUploadIcon,
- onSetVisibility,
- onRotate,
+ onSetOffline,
onCopy,
- onShareIdSaved,
+ onReload,
}: RowProps) {
const { t, i18n } = useTranslation();
const status = STATUS[page.visibility];
@@ -215,26 +213,39 @@ function ShowPageRow({
<IconEditor page={page} disabled={busy} onUploadIcon={onUploadIcon} />
</div>
- <div className="flex flex-col gap-2">
- <span className={LABEL}>{t('showPages.visibilityLabel')}</span>
- <div className="max-w-[360px]">
- <SegmentedRadio<Visibility>
- value={page.visibility}
- tone={status.tone}
- disabled={busy}
- ariaLabel={t('showPages.visibilityLabel')}
- onChange={onSetVisibility}
- options={[
- { id: 'private', label: t('showPages.status.private') },
- { id: 'public', label: t('showPages.status.public') },
- { id: 'offline', label: t('showPages.visibilityOffline') },
- ]}
- />
+ <div className="flex max-w-[420px] items-center justify-between gap-3">
+ <div>
+ <span className={LABEL}>{t('chat.showPage.availability')}</span>
+ <p className="mt-1 text-[11px] text-muted">
+ {t(page.offline ? 'chat.showPage.availabilityOffline' : 'chat.showPage.availabilityOnline')}
+ </p>
</div>
+ <Switch
+ checked={page.offline}
+ disabled={busy || (page.offline ? !page.can_publish_public : !page.can_manage)}
+ onCheckedChange={onSetOffline}
+ label={t('chat.showPage.offline')}
+ />
</div>
+ {page.can_publish_public ? (
+ <div className="max-w-[420px] border-t border-border pt-4">
+ <ShowPageSharingSettings
+ active={expanded}
+ canManage
+ sessionId={page.session_id}
+ onApplied={onReload}
+ />
+ </div>
+ ) : null}
+
{page.visibility === 'offline' ? (
<p className="text-[12px] text-muted">{t('showPages.offlineNoLink')}</p>
+ ) : page.visibility === 'limited' ? (
+ <div className="flex items-start gap-2 text-[12px] text-muted">
+ <TriangleAlert size={14} className="mt-0.5 shrink-0 text-gold-ink" />
+ <span>{t('chat.showPage.sharingHelp.limited')}</span>
+ </div>
) : (
<div className="flex flex-col gap-2">
<span className={LABEL}>{t('showPages.liveLink')}</span>
@@ -280,34 +291,9 @@ function ShowPageRow({
</div>
)}
- {page.visibility === 'public' ? (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-2">
- <span className={LABEL}>{t('showPages.shareId.label')}</span>
- <div className="max-w-[360px]">
- <ShowPageShareIdField
- sessionId={page.session_id}
- shareId={page.share_id}
- disabled={busy}
- onSaved={onShareIdSaved}
- />
- </div>
- </div>
- <div className="flex flex-col gap-2">
- <span className={LABEL}>{t('showPages.shareLink')}</span>
- <div className="flex flex-wrap items-center gap-3">
- <Button type="button" variant="secondary" size="sm" onClick={onRotate} disabled={busy}>
- <RotateCw size={14} />
- {t('showPages.rotate')}
- </Button>
- <span className="text-[11px] text-muted">{t('showPages.rotateHint')}</span>
- </div>
- </div>
- </div>
- ) : null}
</div>
- <div className="flex flex-col gap-3 rounded-xl border border-border bg-foreground/[0.02] p-4">
+ <div className="flex flex-col gap-3 rounded-md border border-border bg-foreground/[0.02] p-4">
<span className={LABEL}>{t('showPages.details')}</span>
{([
{ k: t('showPages.detail.session'), v: page.session_id, mono: true, to: `/chat/${page.session_id}` },
@@ -490,11 +476,9 @@ const IconEditor: React.FC<{
export function ShowPagesView({
pages,
busyId,
- setVisibility,
- rotate,
+ setOffline,
rename,
uploadIcon,
- onShareIdSaved,
reload,
onOpenApp,
}: ShowPagesController & {
@@ -567,6 +551,7 @@ export function ShowPagesView({
options={[
{ id: 'all', label: t('showPages.filter.all') },
{ id: 'public', label: t('showPages.filter.public') },
+ { id: 'limited', label: t('showPages.filter.limited') },
{ id: 'private', label: t('showPages.filter.private') },
{ id: 'offline', label: t('showPages.filter.offline') },
]}
@@ -593,10 +578,9 @@ export function ShowPagesView({
onToggleInstall={(next) => (next ? pin(page.session_id) : unpin(page.session_id))}
onRename={(title) => rename(page, title)}
onUploadIcon={(file) => uploadIcon(page, file)}
- onSetVisibility={(visibility) => setVisibility(page, visibility)}
- onRotate={() => rotate(page)}
+ onSetOffline={(offline) => setOffline(page, offline)}
onCopy={() => copy(page)}
- onShareIdSaved={onShareIdSaved}
+ onReload={reload}
/>
))
)}
diff --git a/ui/src/components/useShowPages.test.ts b/ui/src/components/useShowPages.test.ts
index 50a0cc2ae..bef648e06 100644
--- a/ui/src/components/useShowPages.test.ts
+++ b/ui/src/components/useShowPages.test.ts
@@ -5,6 +5,10 @@ import { replaceShowPageTitleIfCurrent, type ShowPage } from './useShowPages';
const page = (title: string | null): ShowPage => ({
session_id: 'session-1',
visibility: 'private',
+ access_mode: 'private',
+ access_revision: 0,
+ can_manage: true,
+ can_publish_public: true,
title,
platform: null,
agent: null,
diff --git a/ui/src/components/useShowPages.ts b/ui/src/components/useShowPages.ts
index ad562ee61..2f7038713 100644
--- a/ui/src/components/useShowPages.ts
+++ b/ui/src/components/useShowPages.ts
@@ -3,11 +3,9 @@ import { useTranslation } from 'react-i18next';
import { useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
-import { isShowPageVisibilityPayload, type ShowPageVisibilityResult } from '../lib/showPageAccess';
import {
getShowPagesInventoryStore,
type ShowPage,
- type Visibility,
} from '../lib/showPagesStore';
export { replaceShowPageTitleIfCurrent } from '../lib/showPagesStore';
@@ -44,32 +42,25 @@ export function useShowPageInventory(enabled = true) {
};
}
-// The Show Pages inventory: fetch + the visibility / share-id / rotate mutations,
-// with their toasts. Lifted out of the view so the App Library owns one copy of
+// The Show Pages inventory and availability mutations, with their toasts.
+// Lifted out of the view so the App Library owns one copy of
// the pages state and projects it into both the Apps and Show Pages views (kept
// in a hook module so the view file exports only components — fast-refresh safe).
export function useShowPages() {
const api = useApi();
const { showToast } = useToast();
const { t } = useTranslation();
- const { pages, loading, loaded, mergePage, removePage, replaceTitleIfCurrent, reload } =
+ const { pages, loading, loaded, mergePage, replaceTitleIfCurrent, reload } =
useShowPageInventory();
const [busyId, setBusyId] = useState<string | null>(null);
- const setVisibility = async (page: ShowPage, visibility: Visibility) => {
- if (page.visibility === visibility || busyId) return;
+ const setOffline = async (page: ShowPage, offline: boolean) => {
+ if (page.offline === offline || busyId) return;
setBusyId(page.session_id);
try {
- const res = await api.setShowPageVisibility<ShowPage>(page.session_id, visibility);
- if (isShowPageVisibilityPayload(res)) {
- mergePage(res);
- } else {
- // The caller lost page-use access between render and mutation. The
- // metadata-only response deliberately contains no page identifiers or
- // links, so withdraw the retained inventory row immediately.
- removePage(page.session_id);
- reload();
- }
+ const res = await api.setShowPageAvailability(page.session_id, offline);
+ if (res?.session_id === page.session_id) mergePage(res as ShowPage);
+ else reload();
showToast(t('showPages.toast.updated'));
} catch {
// ApiContext surfaces a toast on failure.
@@ -78,37 +69,6 @@ export function useShowPages() {
}
};
- const rotate = async (page: ShowPage) => {
- if (busyId) return;
- setBusyId(page.session_id);
- try {
- const res = await api.rotateShowPageShare(page.session_id);
- if (isShowPageVisibilityPayload(res)) {
- mergePage(res);
- } else {
- removePage(page.session_id);
- reload();
- }
- showToast(t('showPages.toast.rotated'));
- } catch {
- // handled by ApiContext
- } finally {
- setBusyId(null);
- }
- };
-
- // The custom-link field owns its own request/validation; we only merge the
- // returned payload (new share_id, updated_at) and confirm.
- const onShareIdSaved = (next: ShowPageVisibilityResult, sessionId: string) => {
- if (isShowPageVisibilityPayload(next)) {
- mergePage(next as unknown as ShowPage);
- } else {
- removePage(sessionId);
- reload();
- }
- showToast(t('showPages.shareId.toast.saved'));
- };
-
const rename = async (page: ShowPage, title: string | null) => {
const previousTitle = page.title?.trim() || null;
const nextTitle = title?.trim() || null;
@@ -140,7 +100,7 @@ export function useShowPages() {
}
};
- return { pages, loading, loaded, busyId, setVisibility, rotate, rename, uploadIcon, onShareIdSaved, reload };
+ return { pages, loading, loaded, busyId, setOffline, rename, uploadIcon, reload };
}
export type ShowPagesController = ReturnType<typeof useShowPages>;
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 1eff9f0df..d329c09fa 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -25,7 +25,7 @@ import {
isVaultApprovalRequest,
placeVaultProvisionRequests,
} from '../../lib/vaultRequestPlacement';
-import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+import { editorPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';
import {
showPageHeaderAccess,
showPageRestoreAccessDecision,
@@ -912,8 +912,8 @@ export const ChatPage: React.FC = () => {
);
// Every write that goes through the shared JSON helpers (updateSession,
- // forkSession, ensureShowPage, the Show Page visibility / share-id / rotate /
- // icon mutations …) reports its archived 409 through this one API-layer
+ // forkSession, ensureShowPage, Show Page access / availability / icon
+ // mutations …) reports its archived 409 through this one API-layer
// subscription, including the ones issued by components this page owns rather
// than by the page itself. ``sendMessage`` is the exception by construction: it
// uses a raw ``apiFetch`` so it can read ``queued``/``already_answered`` off a
@@ -1860,11 +1860,11 @@ export const ChatPage: React.FC = () => {
});
}, [deepLinkMessageId, openShowPage, readOnly, session?.id, sessionId, showChatSignal, showPageRestoreAccess]);
- // When the share control resolves the page (open) or flips its visibility, the
- // serving route changes (private → /show/, public → /p/). Re-point the iframe
- // so it never stays on a route that now 404s.
+ // Keep the author preview on the authenticated route. The guest-facing /p
+ // route has separate admission rules and intentionally rejects Limited pages
+ // until signed-in guest admission is available.
const handleShowPagePayload = useCallback((next: ShowPageLinkInfo) => {
- const path = localPath(next);
+ const path = editorPath(next);
if (path) setShowPageUrl(showPageEmbeddedPath(path));
}, []);
@@ -2465,8 +2465,7 @@ export const ChatPage: React.FC = () => {
/>
{showPageActive && showPageUrl && (
- // The session's Show Page (same-origin /show/<id>/ private or /p/<share>/
- // public; URL resolved from ensureShowPage) fills the chat area while the
+ // The session's authenticated /show/<id>/ author surface fills the chat area while the
// header bar stays. The chat surface below is kept mounted but hidden.
//
// Sandbox is deliberately LIGHT: `allow-same-origin` is required (the page
diff --git a/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx b/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx
deleted file mode 100644
index c8a1af4f1..000000000
--- a/ui/src/components/workbench/ShowPageEmailAccessEditor.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import clsx from 'clsx';
-import { CloudOff, Loader2, Mail, Plus, RefreshCw, X } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { Button } from '@/components/ui/button';
-import { ConfirmDialog } from '@/components/ui/confirm-dialog';
-import { Input } from '@/components/ui/input';
-import { ApiError, useApi } from '@/context/ApiContext';
-import {
- normalizeShowPageAuthorizedEmail,
- requiresShowPageEmailRevocationConfirmation,
-} from '@/lib/showPageAccess';
-
-type EmailAccessGate = 'idle' | 'loading' | 'ready' | 'unavailable' | 'error';
-
-const normalizedSet = (emails: string[]): string[] => [...new Set(emails)].sort();
-
-const emailAccessUnavailable = (error: unknown): boolean => error instanceof ApiError
- && [
- 'show_page_email_access_not_configured',
- 'show_page_email_access_unavailable',
- ].includes(error.code ?? '');
-
-export function ShowPageEmailAccessEditor({
- active,
- canManage,
- sessionId,
- onConfirmationOpenChange,
- ownerWindowId,
-}: {
- active: boolean;
- canManage: boolean;
- sessionId: string;
- onConfirmationOpenChange?: (open: boolean) => void;
- /** Attribute this control's body-portalled ConfirmDialog to its owning app window. */
- ownerWindowId?: string;
-}) {
- const { t } = useTranslation();
- const api = useApi();
- const [gate, setGate] = useState<EmailAccessGate>('idle');
- const [emails, setEmails] = useState<string[]>([]);
- const [savedEmails, setSavedEmails] = useState<string[]>([]);
- const [draft, setDraft] = useState('');
- const [draftInvalid, setDraftInvalid] = useState(false);
- const [saving, setSaving] = useState(false);
- const [confirmNarrowing, setConfirmNarrowing] = useState(false);
- const generationRef = useRef(0);
- const setConfirmationOpen = useCallback((next: boolean) => {
- setConfirmNarrowing(next);
- onConfirmationOpenChange?.(next);
- }, [onConfirmationOpenChange]);
-
- const load = useCallback(async () => {
- const generation = ++generationRef.current;
- setGate('loading');
- try {
- const result = await api.getShowPageAuthorizedEmails(sessionId);
- if (generation !== generationRef.current) return;
- const next = normalizedSet(result.emails);
- setEmails(next);
- setSavedEmails(next);
- setGate('ready');
- } catch (error) {
- if (generation !== generationRef.current) return;
- setGate(emailAccessUnavailable(error) ? 'unavailable' : 'error');
- }
- }, [api, sessionId]);
-
- useEffect(() => {
- generationRef.current += 1;
- setGate('idle');
- setEmails([]);
- setSavedEmails([]);
- setDraft('');
- setDraftInvalid(false);
- setSaving(false);
- setConfirmationOpen(false);
- if (active && canManage) void load();
- return () => {
- generationRef.current += 1;
- };
- }, [active, canManage, load, sessionId, setConfirmationOpen]);
-
- const dirty = useMemo(
- () => emails.join('\u0000') !== savedEmails.join('\u0000'),
- [emails, savedEmails],
- );
-
- if (!canManage) return null;
-
- const addDraft = () => {
- const normalized = normalizeShowPageAuthorizedEmail(draft);
- if (!normalized) {
- setDraftInvalid(true);
- return;
- }
- setEmails((current) => normalizedSet([...current, normalized]));
- setDraft('');
- setDraftInvalid(false);
- };
-
- const commit = async () => {
- if (!dirty || saving || draft.trim()) return;
- setConfirmationOpen(false);
- setSaving(true);
- try {
- const result = await api.replaceShowPageAuthorizedEmails(sessionId, emails);
- const next = normalizedSet(result.emails);
- setEmails(next);
- setSavedEmails(next);
- setGate('ready');
- } catch (error) {
- setGate(emailAccessUnavailable(error) ? 'unavailable' : 'error');
- } finally {
- setSaving(false);
- }
- };
-
- const save = () => {
- if (!dirty || saving || draft.trim()) return;
- if (requiresShowPageEmailRevocationConfirmation(savedEmails, emails)) {
- setConfirmNarrowing(true);
- return;
- }
- void commit();
- };
-
- return (
- <>
- <div className="space-y-2.5 border-t border-border pt-2.5">
- <div className="flex items-start gap-2">
- <Mail className="mt-0.5 size-3.5 shrink-0 text-muted" />
- <div className="min-w-0">
- <div className="text-xs font-medium">{t('chat.showPage.emailAccess')}</div>
- <p className="mt-0.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.emailAccessDesc')}
- </p>
- </div>
- </div>
-
- {gate === 'loading' || gate === 'idle' ? (
- <div className="flex items-center gap-1.5 text-[11px] text-muted">
- <Loader2 className="size-3.5 animate-spin" />
- {t('chat.showPage.loadingEmailAccess')}
- </div>
- ) : null}
-
- {gate === 'unavailable' ? (
- <div className="flex items-start gap-1.5 text-[11px] leading-snug text-muted">
- <CloudOff className="mt-0.5 size-3.5 shrink-0" />
- {t('chat.showPage.emailAccessUnavailable')}
- </div>
- ) : null}
-
- {gate === 'error' ? (
- <div className="flex items-center justify-between gap-2">
- <span className="text-[11px] leading-snug text-destructive-ink">
- {t('chat.showPage.emailAccessError')}
- </span>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-7 shrink-0"
- onClick={() => void load()}
- aria-label={t('common.retry')}
- title={t('common.retry')}
- >
- <RefreshCw className="size-3.5" />
- </Button>
- </div>
- ) : null}
-
- {gate === 'ready' ? (
- <>
- <div className="flex items-start gap-1.5">
- <div className="min-w-0 flex-1">
- <Input
- type="email"
- value={draft}
- disabled={saving || emails.length >= 64}
- onChange={(event) => {
- setDraft(event.target.value);
- if (draftInvalid) setDraftInvalid(false);
- }}
- onKeyDown={(event) => {
- if (event.key !== 'Enter') return;
- event.preventDefault();
- addDraft();
- }}
- placeholder={t('chat.showPage.emailPlaceholder')}
- aria-label={t('chat.showPage.emailAccess')}
- aria-invalid={draftInvalid || undefined}
- className={clsx('h-8 text-xs', draftInvalid && 'border-destructive')}
- />
- {draftInvalid ? (
- <p className="mt-1 text-[11px] text-destructive-ink">
- {t('chat.showPage.emailInvalid')}
- </p>
- ) : null}
- </div>
- <Button
- type="button"
- size="icon"
- variant="outline"
- className="size-8 shrink-0"
- disabled={saving || !draft.trim() || emails.length >= 64}
- onClick={addDraft}
- aria-label={t('chat.showPage.addEmail')}
- title={t('chat.showPage.addEmail')}
- >
- <Plus className="size-3.5" />
- </Button>
- </div>
-
- {emails.length ? (
- <div className="max-h-32 divide-y divide-border overflow-y-auto rounded-md border border-border">
- {emails.map((email) => (
- <div key={email} className="flex min-h-8 items-center gap-2 px-2">
- <span className="min-w-0 flex-1 truncate font-mono text-[11px]">{email}</span>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-6 shrink-0"
- disabled={saving}
- onClick={() => setEmails((current) => current.filter((value) => value !== email))}
- aria-label={t('chat.showPage.removeEmail', { email })}
- title={t('chat.showPage.removeEmail', { email })}
- >
- <X className="size-3" />
- </Button>
- </div>
- ))}
- </div>
- ) : (
- <p className="text-[11px] leading-snug text-muted">
- {t('chat.showPage.emailAccessEmpty')}
- </p>
- )}
-
- <div className="flex items-center justify-between gap-3">
- <span className="text-[10px] text-muted">{t('chat.showPage.emailAccessLimit')}</span>
- <Button
- type="button"
- size="sm"
- variant="outline"
- className="h-7"
- disabled={!dirty || saving || Boolean(draft.trim())}
- onClick={save}
- >
- {saving ? <Loader2 className="size-3.5 animate-spin" /> : null}
- {t('chat.showPage.applyEmailAccess')}
- </Button>
- </div>
- </>
- ) : null}
- </div>
- <ConfirmDialog
- open={confirmNarrowing}
- onOpenChange={setConfirmationOpen}
- title={t('organization.resources.narrowTitle')}
- description={t('organization.resources.narrowBody')}
- confirmLabel={t('organization.actions.saveChanges')}
- onConfirm={commit}
- windowOwnerId={ownerWindowId}
- />
- </>
- );
-}
diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsx
index e4c0f953b..c55b9f7ac 100644
--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx
@@ -11,12 +11,11 @@ import { ShowPageShareControl } from './ShowPageShareControl';
const api = {
ensureShowPage: vi.fn(),
getShowPageAccess: vi.fn(),
- getShowPageAuthorizedEmails: vi.fn(),
- replaceShowPageAuthorizedEmails: vi.fn(),
+ getShowAccessSettings: vi.fn(),
+ applyShowAccess: vi.fn(),
listOrganizationResources: vi.fn(),
listOrganizationGroups: vi.fn(),
- setShowPageVisibility: vi.fn(),
- rotateShowPageShare: vi.fn(),
+ setShowPageAvailability: vi.fn(),
};
vi.mock('../../context/ApiContext', () => ({
@@ -107,7 +106,6 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_use: true,
can_manage: false,
can_publish_public: false,
- public_link_enabled: false,
});
api.ensureShowPage.mockResolvedValue({
session_id: 'ses-1',
@@ -141,7 +139,6 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_use: false,
can_manage: true,
can_publish_public: false,
- public_link_enabled: false,
});
render(
@@ -173,7 +170,6 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_use: true,
can_manage: true,
can_publish_public: true,
- public_link_enabled: false,
});
api.ensureShowPage.mockResolvedValue({
session_id: 'ses-1',
@@ -195,7 +191,6 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_use: true,
can_manage: true,
can_publish_public: true,
- public_link_enabled: false,
} as never}
/>
</I18nextProvider>,
@@ -210,6 +205,38 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
});
});
+ it('does not present a Limited shared link before guest admission exists', async () => {
+ api.getShowPageAccess.mockResolvedValue({
+ ok: true,
+ mode: 'local',
+ can_use: true,
+ can_manage: false,
+ can_publish_public: false,
+ });
+ api.ensureShowPage.mockResolvedValue({
+ session_id: 'ses-1',
+ visibility: 'limited',
+ active_url: '/p/stable-link/',
+ share_id: 'stable-link',
+ url_available: true,
+ offline: false,
+ title: null,
+ });
+
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ShowPageShareControl sessionId="ses-1" />
+ </I18nextProvider>,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));
+
+ expect(await screen.findByText(
+ 'Configure the email audience now; the shared link is not active yet.',
+ )).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Copy link' })).toBeNull();
+ expect(screen.queryByDisplayValue('/p/stable-link/')).toBeNull();
+ });
+
it('shows the loading state while a first access read is pending', async () => {
// The app-window caller has no access yet: while the access read is in
// flight the popover must show the loading row, not the load-error text.
@@ -222,7 +249,6 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
can_use: false,
can_manage: true,
can_publish_public: false,
- public_link_enabled: false,
});
}),
);
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index ab857f4b3..3561c2aee 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
+import { Check, Copy, LayoutGrid, Loader2, Plus, Share2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { Check, Copy, LayoutGrid, Loader2, Plus, RotateCw, Share2 } from 'lucide-react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
@@ -9,49 +9,28 @@ import { Switch } from '../ui/switch';
import { useApi } from '../../context/ApiContext';
import { useDock } from '../../context/DockContext';
import { showDockId } from '../../context/dockDoc';
-import { copyTextToClipboard } from '../../lib/utils';
import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';
+import type { ShowPageAccess } from '../../lib/showPageAccess';
import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';
-import {
- canChangeShowPagePublicLink,
- isShowPageVisibilityPayload,
- showPageShareCapabilities,
- type ShowPageAccess,
- type ShowPageVisibilityResult,
-} from '../../lib/showPageAccess';
-import { ShowPageShareIdField } from './ShowPageShareIdField';
-import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
+import { copyTextToClipboard } from '../../lib/utils';
import { useShowPageInventory, type ShowPage } from '../useShowPages';
+import { ShowPageSharingSettings } from './ShowPageSharingSettings';
+import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
type ShowPagePayload = ShowPageLinkInfo & {
url_available: boolean;
url_guidance?: string | null;
offline: boolean;
- // The live session title (joined server-side by ensureShowPage); labels the
- // pinned-app confirmation. Null for untitled IM-dispatch sessions.
title?: string | null;
};
-// Share affordance for the current session's Show Page. Resource managers may
-// open the audience controls without receiving access to the page content;
-// page links render only when the caller can use the page; an access-only
-// manager receives a metadata-only control for revoking an existing public link.
export const ShowPageShareControl: React.FC<{
sessionId: string;
initialAccess?: ShowPageAccess | null;
- // Dock mutations use Instance authority, not Show Page resource authority.
canManageInstance?: boolean;
- // Lets the chat view re-point the iframe at the route that now serves the
- // page when visibility flips (private↔public swap the serving route).
onPayloadChange?: (payload: ShowPageLinkInfo) => void;
- // The popover floats over the Show Page iframe; the chat view makes the iframe
- // inert while it is open so an outside tap there falls through to the parent
- // document and Radix can dismiss (a tap inside an iframe never reaches us).
onOpenChange?: (open: boolean) => void;
- // Keep a single icon trigger at every viewport size (window title bars),
- // matching the compact annotate control's chrome styling.
compact?: boolean;
- // Associate portalled popover focus with its owning app window.
ownerWindowId?: string;
}> = ({
sessionId,
@@ -65,76 +44,59 @@ export const ShowPageShareControl: React.FC<{
const { t } = useTranslation();
const api = useApi();
const dock = useDock();
- const { pages, mergePage, removePage, reload } = useShowPageInventory();
+ const { pages, mergePage, reload } = useShowPageInventory();
const inventoryPage = pages.find((page) => page.session_id === sessionId);
const [open, setOpen] = useState(false);
- const [workspaceConfirmationOpen, setWorkspaceConfirmationOpen] = useState(false);
+ const [confirmationOpen, setConfirmationOpen] = useState(false);
const [localPayload, setLocalPayload] = useState<ShowPagePayload | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [accessLoading, setAccessLoading] = useState(false);
+ const [access, setAccess] = useState<ShowPageAccess | null>(initialAccess);
+ const [accessError, setAccessError] = useState(false);
+ const [availabilityBusy, setAvailabilityBusy] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const reqSeq = useRef(0);
+ const hasObservedPayloadRef = useRef(false);
+
const candidatePayload = useMemo<ShowPagePayload | null>(() => {
const local = localPayload?.session_id === sessionId ? localPayload : null;
if (!inventoryPage) return local;
if (!local) return inventoryPage as ShowPagePayload;
-
- // A mutation/ensure response is newer than the retained inventory until its
- // merge reaches this render. Prefer it while the share identity differs so
- // onPayloadChange never re-points ChatPage at a revoked cached URL. Once the
- // shared store catches up, inventory resumes as the live source of truth.
- const inventoryCaughtUp =
- inventoryPage.visibility === local.visibility &&
- inventoryPage.active_url === local.active_url &&
- inventoryPage.share_id === local.share_id &&
- inventoryPage.offline === local.offline &&
- inventoryPage.url_available === local.url_available;
+ const inventoryCaughtUp = inventoryPage.visibility === local.visibility
+ && inventoryPage.active_url === local.active_url
+ && inventoryPage.share_id === local.share_id
+ && inventoryPage.offline === local.offline
+ && inventoryPage.url_available === local.url_available;
return (inventoryCaughtUp
? { ...local, ...inventoryPage }
: { ...inventoryPage, ...local }) as ShowPagePayload;
}, [inventoryPage, localPayload, sessionId]);
- const [loading, setLoading] = useState(false);
- const [accessLoading, setAccessLoading] = useState(false);
- const [access, setAccess] = useState<ShowPageAccess | null>(initialAccess);
- const [accessError, setAccessError] = useState(false);
- const shareCapabilities = showPageShareCapabilities(access, {
- accessInvalid: accessError,
- canManageInstance,
- });
- const payload = shareCapabilities.canReadPayload ? candidatePayload : null;
- const [busy, setBusy] = useState(false);
- const [copied, setCopied] = useState(false);
- // A visibility mutation is authoritative: it always applies its result and
- // clears its own busy state, and it invalidates any refresh read issued
- // before it resolved. A refresh (read) only applies if no newer request has
- // superseded it. reqSeq orders the reads; a mutation bumps it on resolve.
- const reqSeq = useRef(0);
- const hasObservedPayloadRef = useRef(false);
+
+ const canReadPayload = !accessError && (canManageInstance || access?.can_use === true);
+ const payload = canReadPayload ? candidatePayload : null;
+ const offline = payload?.visibility === 'offline' || payload?.offline === true;
+ const link = payload && !offline ? copyHref(payload) ?? '' : '';
+ const canNativeShare = typeof navigator !== 'undefined' && typeof navigator.share === 'function';
+ const iosStandalone = isIosDevice() && isStandalonePwa();
+ const showAddToHome = !!link && (iosStandalone || isRealMobileSafari());
const applyPayload = (next: ShowPagePayload) => {
setLocalPayload(next);
mergePage(next as ShowPage);
};
- const applyMutationResult = (
- result: ShowPageVisibilityResult<ShowPagePayload>,
- options: { publicLinkEnabled?: boolean } = {},
- ) => {
- const canReadResult = isShowPageVisibilityPayload(result);
- if (canReadResult) {
- applyPayload(result as ShowPagePayload);
- } else {
- // Access can change after this control renders. A metadata-only response
- // deliberately has no page identity or link, so withdraw every retained
- // copy before revalidating the inventory instead of merging malformed data.
- setLocalPayload(null);
- removePage(sessionId);
+ const reloadPayload = async () => {
+ const seq = ++reqSeq.current;
+ if (!canReadPayload) {
+ reload();
+ return;
+ }
+ try {
+ const next: ShowPagePayload = await api.ensureShowPage(sessionId);
+ if (seq === reqSeq.current) applyPayload(next);
+ } catch {
reload();
}
- setAccess((current) => current ? {
- ...current,
- can_use: canReadResult ? current.can_use : false,
- public_link_enabled: canReadResult
- ? options.publicLinkEnabled ?? current.public_link_enabled
- : result.public_link_enabled,
- } : current);
- reqSeq.current += 1;
};
useEffect(() => {
@@ -142,17 +104,11 @@ export const ShowPageShareControl: React.FC<{
const hasFreshLocalPayload = localPayload?.session_id === sessionId;
if (!hasObservedPayloadRef.current) {
hasObservedPayloadRef.current = true;
- // ChatPage just resolved ensureShowPage before mounting this control. Do
- // not overwrite that fresh route with the retained inventory's first
- // snapshot; a revalidated store update or local response may notify it.
if (!hasFreshLocalPayload) return;
}
onPayloadChange?.(payload);
}, [localPayload, onPayloadChange, payload, sessionId]);
- // If we unmount while open (a route/session change tears down Show Page mode),
- // Radix won't fire onOpenChange, so report closed here — otherwise the chat
- // view would keep the iframe inert (pointer-events:none) on the next Show Page.
useEffect(() => () => onOpenChange?.(false), [onOpenChange]);
useEffect(() => {
@@ -160,33 +116,8 @@ export const ShowPageShareControl: React.FC<{
setAccessError(false);
}, [initialAccess, sessionId]);
- const offline = payload?.visibility === 'offline' || payload?.offline === true;
- const isPublic = payload?.visibility === 'public';
- // Absolute, copyable href; falls back to the same-origin route when Avibe
- // Cloud is off (payload urls null). The field shows this full url so a manual
- // select/copy yields the same link as the Copy button.
- const link = payload ? copyHref(payload) ?? '' : '';
- const canNativeShare = typeof navigator !== 'undefined' && typeof navigator.share === 'function';
- // "Add to Home Screen" only works where Safari's page-share flow is reachable:
- // real iOS Safari (tapping opens the Show Page top-level, then the user shares
- // that), or an installed iOS standalone PWA (a same-origin link stays trapped in
- // scope, so the user copies the link and opens it in Safari). iOS Chrome/Firefox
- // and IM in-app browsers report iOS too but can't reach that flow, so we don't
- // show steps they can't complete — matching the InstallHint nudge's gating.
- const iosStandalone = isIosDevice() && isStandalonePwa();
- const showAddToHome = !!link && (iosStandalone || isRealMobileSafari());
-
- // Re-fetch on every open so a visibility/share change made elsewhere (e.g. the
- // admin Show Pages page) is reflected; keep the last payload visible while
- // refreshing so reopening doesn't flash a spinner.
const refresh = () => {
const seq = ++reqSeq.current;
- // Callers that already hold authority (instance managers, or a caller that
- // passed initialAccess) read the payload and the access in parallel like
- // before. A caller with NEITHER (the app window title bar) must sequence:
- // the payload read is gated on access, so it starts only after access
- // resolves — otherwise a granted can_use arrives with no payload behind it
- // until the popover is reopened.
const loadPayload = async (granted: boolean) => {
if (!granted) {
setLoading(false);
@@ -194,13 +125,12 @@ export const ShowPageShareControl: React.FC<{
}
setLoading(!payload);
try {
- const res: ShowPagePayload = await api.ensureShowPage(sessionId);
+ const result: ShowPagePayload = await api.ensureShowPage(sessionId);
if (seq !== reqSeq.current) return;
- applyPayload(res);
+ applyPayload(result);
if (!inventoryPage) reload();
} catch {
- // An archived Show Page cannot be ensured, but its applied access
- // metadata is still useful and is loaded below.
+ // Archived pages can still expose access metadata, but cannot be ensured.
} finally {
setLoading(false);
}
@@ -216,18 +146,12 @@ export const ShowPageShareControl: React.FC<{
setAccess(nextAccess);
} catch {
if (seq !== reqSeq.current) return;
- // A failed refresh cannot leave the previous authority actionable. The
- // payload stays cached for a later successful refresh, but is withdrawn
- // while accessError invalidates this control's authorization state.
setAccess(null);
setAccessError(true);
return;
} finally {
setAccessLoading(false);
}
- // Only the sequenced caller loads here: the parallel branch already
- // started its payload read alongside this one — loading twice would
- // duplicate the ensure request and the inventory merge.
if (thenLoadPayload) {
await loadPayload(canManageInstance || nextAccess?.can_use === true);
}
@@ -243,49 +167,26 @@ export const ShowPageShareControl: React.FC<{
const handleOpenChange = (next: boolean) => {
setOpen(next);
- if (!next) setWorkspaceConfirmationOpen(false);
+ if (!next) setConfirmationOpen(false);
onOpenChange?.(next);
if (next) refresh();
};
- const setVisibilityTo = (next: string) => {
- setBusy(true);
- api
- .setShowPageVisibility<ShowPagePayload>(sessionId, next)
- .then((res) => {
- // Authoritative server state: apply it and invalidate any in-flight
- // refresh read so a stale read cannot revert us afterwards.
- applyMutationResult(res, { publicLinkEnabled: next === 'public' });
- })
- .catch(() => undefined)
- .finally(() => setBusy(false));
+ const handleShowAccessApplied = () => {
+ void reloadPayload();
};
- const revokePublicLinkWithoutPayload = () => {
- if (!shareCapabilities.canRevokePublicLinkWithoutPayload) return;
- setBusy(true);
- api
- .setShowPageVisibility(sessionId, 'private')
- .then(() => {
- // Do not retain the mutation payload: this manager can revoke anonymous
- // access but cannot read the page, its link, or its share identifier.
- setAccess((current) => current ? {
- ...current,
- public_link_enabled: false,
- } : current);
+ const setOffline = (next: boolean) => {
+ if (!payload || availabilityBusy) return;
+ setAvailabilityBusy(true);
+ void api.setShowPageAvailability(sessionId, next)
+ .then((result) => {
+ if (result && result.session_id === sessionId) applyPayload(result as ShowPagePayload);
+ else reload();
reqSeq.current += 1;
})
.catch(() => undefined)
- .finally(() => setBusy(false));
- };
-
- const rotatePublicLink = () => {
- setBusy(true);
- api
- .rotateShowPageShare(sessionId)
- .then((res: ShowPageVisibilityResult<ShowPagePayload>) => applyMutationResult(res))
- .catch(() => undefined)
- .finally(() => setBusy(false));
+ .finally(() => setAvailabilityBusy(false));
};
const copyLink = async () => {
@@ -301,7 +202,7 @@ export const ShowPageShareControl: React.FC<{
try {
await navigator.share({ title: t('chat.showPage.title'), url: link });
} catch {
- // user dismissed the share sheet, or it is unavailable — no-op
+ // The native sheet may be dismissed without changing state.
}
};
@@ -316,88 +217,82 @@ export const ShowPageShareControl: React.FC<{
? 'size-6 shrink-0 rounded-md text-muted hover:bg-foreground/[0.06] hover:text-foreground'
: 'size-7 shrink-0'}
aria-label={t('chat.showPage.share')}
- title={t('chat.showPage.share')}
>
<Share2 className="size-3.5" />
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
- className="w-80 space-y-3"
+ className="w-[min(22rem,calc(100vw-1rem))] space-y-3"
data-window-owner-id={ownerWindowId}
onInteractOutside={(event) => {
- if (workspaceConfirmationOpen) event.preventDefault();
+ if (confirmationOpen) event.preventDefault();
}}
>
<div className="text-sm font-medium">{t('chat.showPage.shareTitle')}</div>
- {/* Access-less callers (the app-window title bar) resolve access first, so
- the access read itself is part of the loading presentation — without
- it the popover would flash the load-error text for the whole request. */}
{(loading || accessLoading) && !access ? (
- <div className="flex items-center gap-2 py-2 text-sm text-muted">
+ <div className="flex h-9 items-center gap-2 text-sm text-muted">
<Loader2 className="size-4 animate-spin" />
{t('common.loading')}
</div>
) : !payload && !access ? (
<p className="py-1 text-sm text-muted">{t('chat.showPage.loadError')}</p>
- ) : payload ? (
- <>
- {offline ? (
- <p className="py-1 text-sm text-muted">{t('chat.showPage.offlineNote')}</p>
- ) : (
- <div className="flex items-center gap-1.5">
- <Input
- id="show-share-link"
- readOnly
- value={link}
- onFocus={(e) => e.currentTarget.select()}
- className="h-8 min-w-0 flex-1 text-xs"
- />
- <Button
- type="button"
- variant="outline"
- size="icon"
- className="size-8 shrink-0"
- disabled={!link}
- onClick={copyLink}
- aria-label={t('chat.showPage.copyLink')}
- title={t('chat.showPage.copyLink')}
- >
- {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
- </Button>
- {isPublic ? (
- <Button
- type="button"
- variant="outline"
- size="icon"
- className="size-8 shrink-0"
- disabled={busy || !access?.can_publish_public}
- onClick={rotatePublicLink}
- aria-label={t('chat.showPage.rotateLink')}
- title={t('chat.showPage.rotateLink')}
- >
- <RotateCw className="size-3.5" />
- </Button>
- ) : null}
- {canNativeShare && (
- <Button
- type="button"
- variant="outline"
- size="icon"
- className="size-8 shrink-0"
- disabled={!link}
- onClick={nativeShare}
- aria-label={t('chat.showPage.nativeShare')}
- title={t('chat.showPage.nativeShare')}
- >
- <Share2 className="size-3.5" />
- </Button>
- )}
- </div>
- )}
+ ) : null}
+
+ {payload && !offline && payload.visibility !== 'limited' ? (
+ <div className="flex items-center gap-1.5">
+ <Input
+ id="show-share-link"
+ readOnly
+ value={link}
+ onFocus={(event) => event.currentTarget.select()}
+ className="h-8 min-w-0 flex-1 text-xs"
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="size-8 shrink-0"
+ disabled={!link}
+ onClick={copyLink}
+ aria-label={t('chat.showPage.copyLink')}
+ >
+ {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
+ </Button>
+ {canNativeShare ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ className="size-8 shrink-0"
+ disabled={!link}
+ onClick={nativeShare}
+ aria-label={t('chat.showPage.nativeShare')}
+ >
+ <Share2 className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ ) : null}
- </>
+ {payload && !offline && payload.visibility === 'limited' ? (
+ <p className="text-[11px] leading-snug text-muted">
+ {t('chat.showPage.sharingHelp.limited')}
+ </p>
+ ) : null}
+
+ {access?.can_publish_public ? (
+ <div className="border-t border-border pt-3">
+ <ShowPageSharingSettings
+ active={open}
+ canManage
+ sessionId={sessionId}
+ onApplied={handleShowAccessApplied}
+ onConfirmationOpenChange={setConfirmationOpen}
+ ownerWindowId={ownerWindowId}
+ />
+ </div>
) : null}
<div className="border-t border-border pt-3">
@@ -405,7 +300,7 @@ export const ShowPageShareControl: React.FC<{
access={access}
active={open}
sessionId={sessionId}
- onConfirmationOpenChange={setWorkspaceConfirmationOpen}
+ onConfirmationOpenChange={setConfirmationOpen}
ownerWindowId={ownerWindowId}
/>
{accessError ? (
@@ -415,130 +310,52 @@ export const ShowPageShareControl: React.FC<{
) : null}
</div>
- {shareCapabilities.canRevokePublicLinkWithoutPayload ? (
+ {payload ? (
<div className="border-t border-border pt-3">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
- <div className="text-sm font-medium">{t('chat.showPage.publicLink')}</div>
+ <div className="text-sm font-medium">{t('chat.showPage.availability')}</div>
<p className="mt-0.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.publicLinkOnDesc')}
+ {t(offline ? 'chat.showPage.availabilityOffline' : 'chat.showPage.availabilityOnline')}
</p>
</div>
<Switch
- checked
- disabled={
- busy
- || accessLoading
- || !canChangeShowPagePublicLink(access, false)
- }
- onCheckedChange={(next) => {
- if (!next) revokePublicLinkWithoutPayload();
- }}
- label={t('chat.showPage.publicLink')}
+ checked={Boolean(offline)}
+ disabled={availabilityBusy || (offline ? !access?.can_publish_public : !access?.can_manage)}
+ onCheckedChange={setOffline}
+ label={t('chat.showPage.offline')}
/>
</div>
- <p className="mt-1.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.publicLinkOwnerOnly')}
- </p>
</div>
) : null}
- {payload ? (
- <>
- <div className="border-t border-border pt-3">
- <div className="flex items-center justify-between gap-3">
- <div className="min-w-0">
- <div className="text-sm font-medium">{t('chat.showPage.publicLink')}</div>
- <p className="mt-0.5 text-[11px] leading-snug text-muted">
- {isPublic ? t('chat.showPage.publicLinkOnDesc') : t('chat.showPage.publicLinkOffDesc')}
- </p>
- </div>
- <Switch
- checked={isPublic}
- disabled={
- offline
- || busy
- || accessLoading
- || !canChangeShowPagePublicLink(access, !isPublic)
- }
- onCheckedChange={(next) => setVisibilityTo(next ? 'public' : 'private')}
- label={t('chat.showPage.publicLink')}
- />
- </div>
- {isPublic && access && !access.can_publish_public ? (
- <p className="mt-1.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.publicLinkOwnerOnly')}
- </p>
- ) : null}
- {offline ? (
- <p className="mt-1.5 text-[11px] leading-snug text-muted">
- {t('chat.showPage.publicLinkOffline')}
- </p>
- ) : null}
+ {showAddToHome ? (
+ <div className="border-t border-border pt-3">
+ <div className="flex items-center gap-1.5 text-xs font-medium text-foreground">
+ <Plus className="size-3.5 shrink-0 text-cyan-ink" />
+ {t('chat.showPage.addToHomeTitle')}
</div>
-
- {isPublic && !offline ? (
- <div>
- <div className="mb-1.5 text-sm">{t('chat.showPage.customLink')}</div>
- <ShowPageShareIdField
- sessionId={sessionId}
- shareId={payload.share_id}
- disabled={busy || !access?.can_publish_public}
- onSaved={(res) => {
- // Custom-link updates can also return metadata only when
- // page-use access changed while the editor was open.
- applyMutationResult(res as ShowPageVisibilityResult<ShowPagePayload>);
- }}
- />
- </div>
- ) : null}
-
- {isPublic && !payload.url_available ? (
- <div className="rounded-md border border-border px-2.5 py-2 text-xs text-muted">
- {t('chat.showPage.publicUnavailable')}
- </div>
- ) : null}
-
- {showAddToHome && !offline ? (
- <div className="rounded-md border border-border bg-foreground/[0.02] px-2.5 py-2">
- <div className="flex items-center gap-1.5 text-xs font-medium text-foreground">
- <Plus className="size-3.5 shrink-0 text-cyan-ink" />
- {t('chat.showPage.addToHomeTitle')}
- </div>
- {iosStandalone ? (
- // Installed PWA: a same-origin link can't hand off to Safari
- // (it stays trapped in scope), so the user must copy the link
- // and open it in Safari — the Copy button above does that.
- <p className="mt-1 text-xs leading-relaxed text-muted">
- {t('chat.showPage.addToHomeBodyPwa')}
- </p>
- ) : (
- // Safari: the popover sits in the workbench while the Show Page
- // is framed, so Safari's own Share targets the workbench URL.
- // Open the Show Page top-level first (new tab) — then the user's
- // Share → Add to Home Screen captures the Show Page, not us.
- <a
- href={link}
- target="_blank"
- rel="noopener noreferrer"
- className="mt-1 block text-xs leading-relaxed text-foreground underline underline-offset-2"
- >
- {t('chat.showPage.addToHomeBodySafari')}
- </a>
- )}
- </div>
- ) : null}
- </>
+ {iosStandalone ? (
+ <p className="mt-1 text-xs leading-relaxed text-muted">
+ {t('chat.showPage.addToHomeBodyPwa')}
+ </p>
+ ) : (
+ <a
+ href={link}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="mt-1 block text-xs leading-relaxed text-foreground underline underline-offset-2"
+ >
+ {t('chat.showPage.addToHomeBodySafari')}
+ </a>
+ )}
+ </div>
) : null}
- {/* Pin to Dock — records the session's Show Page as a Dock app. Deliberately
- OUTSIDE the visibility branches: pinning is independent of public/private
- (a private page can be pinned) and never changes visibility or deletes the
- page. Shown only when the page exists and the caller can manage the Instance. */}
- {payload && shareCapabilities.canManageDock && (
+ {payload && canManageInstance ? (
<div className="border-t border-border pt-3">
<div className="flex items-center gap-3">
- <span className="grid size-9 shrink-0 place-items-center rounded-lg border border-border bg-foreground/[0.03] text-cyan-ink">
+ <span className="grid size-9 shrink-0 place-items-center rounded-md border border-border bg-foreground/[0.03] text-cyan-ink">
<LayoutGrid className="size-4" />
</span>
<div className="min-w-0 flex-1">
@@ -548,11 +365,6 @@ export const ShowPageShareControl: React.FC<{
<Switch
checked={dock.isDocked(showDockId(sessionId))}
onCheckedChange={(next) => {
- // "Pin to Dock" controls DOCK membership (§7.1c two-layer model):
- // ON docks (installing first if this page isn't installed yet —
- // pinning IS installing, §7.2); OFF undocks but keeps it installed
- // (uninstalling is the Library's 移出). Toggling off no longer
- // uninstalls, and undocking elsewhere now unchecks this switch.
if (next) {
void (dock.isPinned(sessionId) ? dock.dock(showDockId(sessionId)) : dock.pin(sessionId));
} else {
@@ -562,7 +374,7 @@ export const ShowPageShareControl: React.FC<{
label={t('chat.showPage.pinToDock')}
/>
</div>
- {dock.isDocked(showDockId(sessionId)) && (
+ {dock.isDocked(showDockId(sessionId)) ? (
<div className="mt-2 flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.08] px-2.5 py-1.5 text-xs text-foreground">
<Check className="size-3.5 shrink-0 text-mint-ink" />
<span className="truncate">
@@ -571,9 +383,9 @@ export const ShowPageShareControl: React.FC<{
})}
</span>
</div>
- )}
+ ) : null}
</div>
- )}
+ ) : null}
</PopoverContent>
</Popover>
);
diff --git a/ui/src/components/workbench/ShowPageShareIdField.tsx b/ui/src/components/workbench/ShowPageShareIdField.tsx
deleted file mode 100644
index 45685e036..000000000
--- a/ui/src/components/workbench/ShowPageShareIdField.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import React, { useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Check, Loader2 } from 'lucide-react';
-import clsx from 'clsx';
-
-import { Button } from '../ui/button';
-import { Input } from '../ui/input';
-import { ApiError, useApi } from '../../context/ApiContext';
-import { isValidShareId, SHARE_ID_MAX_LENGTH } from '../../lib/showPageLinks';
-import type { ShowPageVisibilityResult } from '../../lib/showPageAccess';
-
-// Editable custom suffix for a public Show Page's /p/<share_id>/ URL. Shared by
-// the in-chat share popover and the admin Show Pages page so both surfaces get
-// the same validation, error mapping, and save affordance. The caller renders
-// its own label (each surface has its own label style) and gates rendering on
-// public visibility; this owns the input row + helper/error line.
-export const ShowPageShareIdField: React.FC<{
- sessionId: string;
- shareId: string | null;
- // External busy (e.g. a visibility change in flight) disables the field.
- disabled?: boolean;
- // Receives the updated payload so the caller can refresh its link/iframe.
- onSaved: (payload: ShowPageVisibilityResult, sessionId: string) => void;
-}> = ({ sessionId, shareId, disabled, onSaved }) => {
- const { t } = useTranslation();
- const api = useApi();
- const current = shareId ?? '';
- const [draft, setDraft] = useState(current);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [saved, setSaved] = useState(false);
- const savedTimer = useRef<number | null>(null);
-
- // Resync when the saved suffix changes elsewhere (a rotate, or a save from the
- // other surface): the prefilled draft should track the authoritative value.
- useEffect(() => {
- setDraft(shareId ?? '');
- setError(null);
- }, [shareId]);
-
- useEffect(
- () => () => {
- if (savedTimer.current) window.clearTimeout(savedTimer.current);
- },
- [],
- );
-
- const trimmed = draft.trim();
- const changed = trimmed !== current;
- const clientValid = isValidShareId(trimmed);
- // Flag a format problem only once the user has typed something new and
- // invalid — never yell at the untouched prefilled value or an empty field.
- const formatError = changed && trimmed.length > 0 && !clientValid;
- const canSave = changed && clientValid && !busy && !disabled;
-
- const save = async () => {
- if (!canSave) return;
- setBusy(true);
- setError(null);
- try {
- const res = await api.setShowPageShareId(sessionId, trimmed);
- onSaved(res, sessionId);
- setSaved(true);
- if (savedTimer.current) window.clearTimeout(savedTimer.current);
- savedTimer.current = window.setTimeout(() => setSaved(false), 1600);
- } catch (err) {
- // The server is the authority on uniqueness; map its code to a field-level
- // message (a global toast also fires from the shared error handler).
- const code = err instanceof ApiError ? err.code : null;
- setError(
- code === 'share_id_taken'
- ? t('showPages.shareId.errors.taken')
- : code === 'invalid_share_id' || code === 'missing_share_id'
- ? t('showPages.shareId.errors.invalid')
- : t('showPages.shareId.errors.generic'),
- );
- } finally {
- setBusy(false);
- }
- };
-
- const isError = !!error || formatError;
- const message = error ?? (formatError ? t('showPages.shareId.errors.invalid') : t('showPages.shareId.hint'));
-
- return (
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center gap-1.5">
- <span className="shrink-0 font-mono text-xs text-muted">/p/</span>
- <Input
- value={draft}
- spellCheck={false}
- autoCapitalize="none"
- autoCorrect="off"
- maxLength={SHARE_ID_MAX_LENGTH}
- disabled={busy || disabled}
- onChange={(e) => {
- setDraft(e.target.value);
- setError(null);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- void save();
- }
- }}
- placeholder={current || t('showPages.shareId.placeholder')}
- aria-label={t('showPages.shareId.label')}
- aria-invalid={isError || undefined}
- className="h-8 flex-1 text-xs"
- />
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="h-8 shrink-0"
- disabled={!canSave}
- onClick={() => void save()}
- >
- {busy ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : saved ? (
- <Check className="size-3.5" />
- ) : (
- t('common.save')
- )}
- </Button>
- </div>
- <p className={clsx('text-[11px] leading-snug', isError ? 'text-destructive-ink' : 'text-muted')}>{message}</p>
- </div>
- );
-};
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.test.tsx b/ui/src/components/workbench/ShowPageSharingSettings.test.tsx
new file mode 100644
index 000000000..667c5f142
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageSharingSettings.test.tsx
@@ -0,0 +1,250 @@
+/** @vitest-environment jsdom */
+import { createInstance } from 'i18next';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../../i18n/en.json';
+import type { ShowAccess, ShowAccessApplyResult } from '../../lib/showPageAccess';
+import { ShowPageSharingSettings } from './ShowPageSharingSettings';
+
+const api = {
+ getShowAccessSettings: vi.fn(),
+ applyShowAccess: vi.fn(),
+};
+
+vi.mock('../../context/ApiContext', () => ({
+ useApi: () => api,
+}));
+
+vi.mock('@/context/ApiContext', () => ({
+ useApi: () => api,
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const showAccess = (overrides: Partial<ShowAccess> = {}): ShowAccess => ({
+ page_id: 'ses-1',
+ access_mode: 'private',
+ share_id: 'stable-link',
+ revision: 0,
+ normalized_emails: [],
+ ...overrides,
+});
+
+const settings = (sessionId = 'ses-1') => (
+ <I18nextProvider i18n={i18n}>
+ <ShowPageSharingSettings active canManage sessionId={sessionId} />
+ </I18nextProvider>
+);
+const renderSettings = (sessionId = 'ses-1') => render(settings(sessionId));
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('ShowPageSharingSettings', () => {
+ it('offers the three closed modes and shows Limited-only fields', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ renderSettings();
+
+ expect(await screen.findByRole('radio', { name: 'Private' })).toBeTruthy();
+ expect(screen.getByRole('radio', { name: 'Limited' })).toBeTruthy();
+ expect(screen.getByRole('radio', { name: 'Fully public' })).toBeTruthy();
+ expect(screen.queryByRole('textbox', { name: 'Limited access emails' })).toBeNull();
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Limited' }));
+
+ expect(screen.getByRole('textbox', { name: 'Limited access emails' })).toBeTruthy();
+ expect((screen.getByRole('textbox', { name: 'Custom link' }) as HTMLInputElement).value).toBe(
+ 'stable-link',
+ );
+ expect(screen.getByText('Add at least one email address.')).toBeTruthy();
+ });
+
+ it('submits mode, stable link, and normalized emails in one Apply', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Limited' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Limited access emails' }), {
+ target: { value: ' [email protected] ' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Add email' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+
+ await waitFor(() => {
+ expect(api.applyShowAccess).toHaveBeenCalledTimes(1);
+ });
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'limited',
+ target_share_id: 'stable-link',
+ target_emails: ['[email protected]'],
+ });
+ });
+
+ it('does not let a hidden Limited email draft block another mode', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({ access_mode: 'public', revision: 1 }),
+ });
+ renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Limited' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Limited access emails' }), {
+ target: { value: '[email protected]' },
+ });
+ fireEvent.click(screen.getByRole('radio', { name: 'Fully public' }));
+
+ const apply = screen.getByRole('button', { name: 'Apply' });
+ expect((apply as HTMLButtonElement).disabled).toBe(false);
+ fireEvent.click(apply);
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+ expect(api.applyShowAccess).toHaveBeenCalledWith('ses-1', {
+ expected_revision: 0,
+ target_access_mode: 'public',
+ target_share_id: 'stable-link',
+ target_emails: [],
+ });
+ });
+
+ it('disables new Limited email input at the audience limit', async () => {
+ api.getShowAccessSettings.mockResolvedValue({
+ show_access: showAccess({
+ access_mode: 'limited',
+ normalized_emails: Array.from({ length: 64 }, (_, index) => `guest-${index}@example.com`),
+ }),
+ });
+ renderSettings();
+
+ const input = await screen.findByRole('textbox', { name: 'Limited access emails' });
+ expect((input as HTMLInputElement).disabled).toBe(true);
+ expect(screen.getByText('Up to 64 email addresses.')).toBeTruthy();
+ });
+
+ it('reloads the latest snapshot after a CAS conflict', async () => {
+ api.getShowAccessSettings
+ .mockResolvedValueOnce({ show_access: showAccess() })
+ .mockResolvedValueOnce({
+ show_access: showAccess({ access_mode: 'public', revision: 3 }),
+ });
+ api.applyShowAccess.mockResolvedValue({
+ status: 'conflict',
+ show_access: showAccess({ access_mode: 'limited', revision: 2 }),
+ });
+ renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Fully public' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+
+ await waitFor(() => {
+ expect(api.getShowAccessSettings).toHaveBeenCalledTimes(2);
+ });
+ expect(screen.getByRole('radio', { name: 'Fully public' }).getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByText(/changed elsewhere/)).toBeTruthy();
+ });
+
+ it('keeps the slug draft visible after a collision', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ api.applyShowAccess.mockResolvedValue({
+ status: 'share_id_taken',
+ show_access: showAccess(),
+ });
+ renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Fully public' }));
+ fireEvent.change(screen.getByRole('textbox', { name: 'Custom link' }), {
+ target: { value: 'taken-link' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+
+ expect(await screen.findByText('That custom link is already taken. Pick another.')).toBeTruthy();
+ expect((screen.getByRole('textbox', { name: 'Custom link' }) as HTMLInputElement).value).toBe(
+ 'taken-link',
+ );
+ });
+
+ it('rejects a mismatched result identity without adopting its email list', async () => {
+ api.getShowAccessSettings.mockResolvedValue({ show_access: showAccess() });
+ api.applyShowAccess.mockResolvedValue({
+ status: 'applied',
+ show_access: showAccess({
+ page_id: 'ses-other',
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Fully public' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+
+ expect(await screen.findByText('Link access could not be loaded.')).toBeTruthy();
+ expect(screen.queryByText('[email protected]')).toBeNull();
+ });
+
+ it('discards an in-flight Apply result after the component moves to another session', async () => {
+ api.getShowAccessSettings.mockImplementation((sessionId: string) => Promise.resolve({
+ show_access: showAccess({
+ page_id: sessionId,
+ share_id: sessionId === 'ses-1' ? 'first-link' : 'second-link',
+ }),
+ }));
+ let resolveApply = (_result: ShowAccessApplyResult) => undefined;
+ api.applyShowAccess.mockReturnValue(new Promise<ShowAccessApplyResult>((resolve) => {
+ resolveApply = resolve;
+ }));
+ const view = renderSettings();
+ await screen.findByRole('radio', { name: 'Private' });
+
+ fireEvent.click(screen.getByRole('radio', { name: 'Fully public' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+ await waitFor(() => expect(api.applyShowAccess).toHaveBeenCalledTimes(1));
+
+ view.rerender(settings('ses-2'));
+ await waitFor(() => {
+ expect(screen.getByRole('radio', { name: 'Private' }).getAttribute('aria-checked')).toBe('true');
+ });
+ await act(async () => {
+ resolveApply({
+ status: 'applied',
+ show_access: showAccess({
+ access_mode: 'limited',
+ revision: 1,
+ normalized_emails: ['[email protected]'],
+ }),
+ });
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByRole('radio', { name: 'Private' }).getAttribute('aria-checked')).toBe('true');
+ });
+ expect(screen.queryByRole('textbox', { name: 'Limited access emails' })).toBeNull();
+ expect(screen.queryByText('[email protected]')).toBeNull();
+ expect(screen.queryByText('Link access could not be loaded.')).toBeNull();
+ });
+});
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.tsx b/ui/src/components/workbench/ShowPageSharingSettings.tsx
new file mode 100644
index 000000000..8a26cf4da
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageSharingSettings.tsx
@@ -0,0 +1,389 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import clsx from 'clsx';
+import { Loader2, Plus, RefreshCw, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { Input } from '@/components/ui/input';
+import { SegmentedRadio } from '@/components/ui/segmented';
+import { useApi } from '@/context/ApiContext';
+import {
+ normalizeShowAccessEmail,
+ showAccessDraftChanged,
+ showAccessTargetEmails,
+ SHOW_ACCESS_EMAIL_MAX_COUNT,
+ type ShowAccess,
+ type ShowAccessMode,
+} from '@/lib/showPageAccess';
+import { isValidShareId, SHARE_ID_MAX_LENGTH } from '@/lib/showPageLinks';
+
+type Gate = 'idle' | 'loading' | 'ready' | 'conflict' | 'share_id_taken' | 'invalid' | 'error';
+
+const normalizedSet = (emails: string[]): string[] => [...new Set(emails)].sort();
+
+const requiresNarrowingConfirmation = (
+ saved: ShowAccess,
+ mode: ShowAccessMode,
+ emails: string[],
+): boolean => {
+ if (saved.access_mode === 'public' && mode !== 'public') return true;
+ if (saved.access_mode !== 'limited') return false;
+ if (mode === 'private') return true;
+ if (mode !== 'limited') return false;
+ const next = new Set(emails);
+ return saved.normalized_emails.some((email) => !next.has(email));
+};
+
+export function ShowPageSharingSettings({
+ active,
+ canManage,
+ sessionId,
+ onApplied,
+ onConfirmationOpenChange,
+ ownerWindowId,
+}: {
+ active: boolean;
+ canManage: boolean;
+ sessionId: string;
+ onApplied?: (showAccess: ShowAccess) => void;
+ onConfirmationOpenChange?: (open: boolean) => void;
+ ownerWindowId?: string;
+}) {
+ const { t } = useTranslation();
+ const api = useApi();
+ const [gate, setGate] = useState<Gate>('idle');
+ const [saved, setSaved] = useState<ShowAccess | null>(null);
+ const [mode, setMode] = useState<ShowAccessMode>('private');
+ const [shareId, setShareId] = useState('');
+ const [emails, setEmails] = useState<string[]>([]);
+ const [emailDraft, setEmailDraft] = useState('');
+ const [emailInvalid, setEmailInvalid] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [confirmNarrowing, setConfirmNarrowing] = useState(false);
+ const generationRef = useRef(0);
+ const sessionIdRef = useRef(sessionId);
+ sessionIdRef.current = sessionId;
+
+ const setConfirmationOpen = useCallback((next: boolean) => {
+ setConfirmNarrowing(next);
+ onConfirmationOpenChange?.(next);
+ }, [onConfirmationOpenChange]);
+
+ const adopt = useCallback((showAccess: ShowAccess) => {
+ if (showAccess.page_id !== sessionId) throw new Error('ShowAccess page identity mismatch');
+ setSaved(showAccess);
+ setMode(showAccess.access_mode);
+ setShareId(showAccess.share_id ?? '');
+ setEmails(showAccess.normalized_emails);
+ setEmailDraft('');
+ setEmailInvalid(false);
+ }, [sessionId]);
+
+ const load = useCallback(async (settledGate: Gate = 'ready') => {
+ const generation = ++generationRef.current;
+ setGate('loading');
+ try {
+ const result = await api.getShowAccessSettings(sessionId);
+ if (generation !== generationRef.current) return;
+ adopt(result.show_access);
+ setGate(settledGate);
+ } catch {
+ if (generation !== generationRef.current) return;
+ setGate('error');
+ }
+ }, [adopt, api, sessionId]);
+
+ useEffect(() => {
+ generationRef.current += 1;
+ setSaved(null);
+ setMode('private');
+ setShareId('');
+ setEmails([]);
+ setEmailDraft('');
+ setEmailInvalid(false);
+ setSaving(false);
+ setConfirmationOpen(false);
+ setGate('idle');
+ if (active && canManage) void load();
+ return () => {
+ generationRef.current += 1;
+ };
+ }, [active, canManage, load, sessionId, setConfirmationOpen]);
+
+ const normalizedShareId = shareId.trim() || null;
+ const sharedMode = mode === 'limited' || mode === 'public';
+ const shareIdInvalid = sharedMode && (!normalizedShareId || !isValidShareId(normalizedShareId));
+ const targetEmails = useMemo(
+ () => showAccessTargetEmails(mode, emails),
+ [emails, mode],
+ );
+ const dirty = Boolean(
+ saved && showAccessDraftChanged(saved, mode, normalizedShareId, emails),
+ );
+ const draftBlocked = mode === 'limited'
+ && Boolean(emailDraft.replace(/^[\t\n\f\r\v ]+|[\t\n\f\r\v ]+$/g, ''));
+ const emailLimitReached = emails.length >= SHOW_ACCESS_EMAIL_MAX_COUNT;
+ const invalid = shareIdInvalid || (mode === 'limited' && targetEmails.length === 0);
+ const editable = canManage && gate !== 'loading' && !saving;
+
+ const addEmail = () => {
+ if (emailLimitReached) return;
+ const normalized = normalizeShowAccessEmail(emailDraft);
+ if (!normalized) {
+ setEmailInvalid(true);
+ return;
+ }
+ setEmails((current) => normalizedSet([...current, normalized]));
+ setEmailDraft('');
+ setEmailInvalid(false);
+ };
+
+ const commit = async () => {
+ if (!saved || !dirty || invalid || draftBlocked || !editable) return;
+ const generation = generationRef.current;
+ const requestSessionId = sessionId;
+ const isCurrent = () => (
+ generation === generationRef.current && requestSessionId === sessionIdRef.current
+ );
+ setSaving(true);
+ setConfirmationOpen(false);
+ try {
+ const result = await api.applyShowAccess(requestSessionId, {
+ expected_revision: saved.revision,
+ target_access_mode: mode,
+ target_share_id: normalizedShareId,
+ target_emails: targetEmails,
+ });
+ if (!isCurrent()) return;
+ if (result.show_access.page_id !== requestSessionId) throw new Error('ShowAccess page identity mismatch');
+ if (result.status === 'conflict') {
+ setSaving(false);
+ await load('conflict');
+ return;
+ }
+ if (result.status === 'share_id_taken' || result.status === 'invalid') {
+ setGate(result.status);
+ return;
+ }
+ adopt(result.show_access);
+ setGate('ready');
+ onApplied?.(result.show_access);
+ } catch {
+ if (!isCurrent()) return;
+ setGate('error');
+ } finally {
+ if (isCurrent()) setSaving(false);
+ }
+ };
+
+ const save = () => {
+ if (!saved || !dirty || invalid || draftBlocked || !editable) return;
+ if (requiresNarrowingConfirmation(saved, mode, targetEmails)) {
+ setConfirmationOpen(true);
+ return;
+ }
+ void commit();
+ };
+
+ if (!canManage) return null;
+
+ return (
+ <>
+ <section className="space-y-2.5" aria-label={t('chat.showPage.sharingAccess')}>
+ <div>
+ <div className="text-sm font-medium">{t('chat.showPage.sharingAccess')}</div>
+ <p className="mt-0.5 text-[11px] leading-snug text-muted">
+ {t('chat.showPage.sharingAccessDesc')}
+ </p>
+ </div>
+
+ {gate === 'loading' || gate === 'idle' ? (
+ <div className="flex h-9 items-center gap-1.5 text-[11px] text-muted">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t('chat.showPage.loadingSharingAccess')}
+ </div>
+ ) : saved ? (
+ <>
+ <SegmentedRadio<ShowAccessMode>
+ value={mode}
+ onChange={(next) => {
+ if (editable) setMode(next);
+ }}
+ disabled={!editable}
+ ariaLabel={t('chat.showPage.sharingAccess')}
+ options={[
+ { id: 'private', label: t('chat.showPage.sharingModes.private') },
+ { id: 'limited', label: t('chat.showPage.sharingModes.limited') },
+ { id: 'public', label: t('chat.showPage.sharingModes.public') },
+ ]}
+ />
+ <p className="text-[11px] leading-snug text-muted">
+ {t(`chat.showPage.sharingHelp.${mode}`)}
+ </p>
+
+ {mode === 'limited' ? (
+ <div className="space-y-2">
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-1">
+ <Input
+ type="email"
+ value={emailDraft}
+ disabled={!editable || emailLimitReached}
+ onChange={(event) => {
+ setEmailDraft(event.target.value);
+ setEmailInvalid(false);
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter') return;
+ event.preventDefault();
+ addEmail();
+ }}
+ placeholder={t('chat.showPage.emailPlaceholder')}
+ aria-label={t('chat.showPage.limitedEmails')}
+ aria-invalid={emailInvalid || undefined}
+ className={clsx('h-8 text-xs', emailInvalid && 'border-destructive')}
+ />
+ {emailInvalid ? (
+ <p className="mt-1 text-[11px] text-destructive-ink">
+ {t('chat.showPage.emailInvalid')}
+ </p>
+ ) : null}
+ </div>
+ <Button
+ type="button"
+ size="icon"
+ variant="outline"
+ className="size-8 shrink-0"
+ disabled={!editable || !emailDraft || emailLimitReached}
+ onClick={addEmail}
+ aria-label={t('chat.showPage.addEmail')}
+ >
+ <Plus className="size-3.5" />
+ </Button>
+ </div>
+ {emails.length ? (
+ <div className="max-h-32 divide-y divide-border overflow-y-auto rounded-md border border-border">
+ {emails.map((email) => (
+ <div key={email} className="flex min-h-8 items-center gap-2 px-2">
+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">{email}</span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-6 shrink-0"
+ disabled={!editable}
+ onClick={() => setEmails((current) => current.filter((value) => value !== email))}
+ aria-label={t('chat.showPage.removeEmail', { email })}
+ >
+ <X className="size-3" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <p className="text-[11px] text-destructive-ink">
+ {t('chat.showPage.limitedEmailRequired')}
+ </p>
+ )}
+ <p className="text-[11px] text-muted">
+ {t('chat.showPage.limitedEmailLimit', { count: SHOW_ACCESS_EMAIL_MAX_COUNT })}
+ </p>
+ </div>
+ ) : null}
+
+ {sharedMode ? (
+ <div className="space-y-1">
+ <div className="flex items-center gap-1.5">
+ <span className="shrink-0 font-mono text-xs text-muted">/p/</span>
+ <Input
+ value={shareId}
+ spellCheck={false}
+ autoCapitalize="none"
+ autoCorrect="off"
+ maxLength={SHARE_ID_MAX_LENGTH}
+ disabled={!editable}
+ onChange={(event) => {
+ setShareId(event.target.value);
+ if (gate === 'share_id_taken') setGate('ready');
+ }}
+ aria-label={t('showPages.shareId.label')}
+ aria-invalid={shareIdInvalid || gate === 'share_id_taken' || undefined}
+ className={clsx(
+ 'h-8 min-w-0 flex-1 font-mono text-xs',
+ (shareIdInvalid || gate === 'share_id_taken') && 'border-destructive',
+ )}
+ />
+ </div>
+ {shareIdInvalid || gate === 'share_id_taken' ? (
+ <p className="text-[11px] text-destructive-ink">
+ {gate === 'share_id_taken'
+ ? t('showPages.shareId.errors.taken')
+ : t('showPages.shareId.errors.invalid')}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+
+ {['conflict', 'invalid', 'error'].includes(gate) ? (
+ <div className="flex items-center justify-between gap-2 border-t border-border pt-2">
+ <span className="text-[11px] leading-snug text-destructive-ink">
+ {t(`chat.showPage.sharingErrors.${gate}`)}
+ </span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0"
+ onClick={() => void load()}
+ aria-label={t('common.retry')}
+ >
+ <RefreshCw className="size-3.5" />
+ </Button>
+ </div>
+ ) : null}
+
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={!dirty || invalid || draftBlocked || !editable}
+ onClick={save}
+ >
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : null}
+ {t('chat.showPage.applySharingAccess')}
+ </Button>
+ </div>
+ </>
+ ) : (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-destructive-ink">
+ {t('chat.showPage.sharingErrors.error')}
+ </span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7"
+ onClick={() => void load()}
+ aria-label={t('common.retry')}
+ >
+ <RefreshCw className="size-3.5" />
+ </Button>
+ </div>
+ )}
+ </section>
+ <ConfirmDialog
+ open={confirmNarrowing}
+ onOpenChange={setConfirmationOpen}
+ title={t('chat.showPage.narrowSharingTitle')}
+ description={t('chat.showPage.narrowSharingBody')}
+ confirmLabel={t('chat.showPage.applySharingAccess')}
+ onConfirm={commit}
+ windowOwnerId={ownerWindowId}
+ />
+ </>
+ );
+}
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
index e324448ba..3121c684e 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -11,16 +11,6 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock('@/context/ApiContext', () => ({
- ApiError: class ApiError extends Error {
- code = null;
- },
- useApi: () => ({
- getShowPageAuthorizedEmails: vi.fn(),
- replaceShowPageAuthorizedEmails: vi.fn(),
- }),
-}));
-
vi.mock('@/components/ui/confirm-dialog', () => ({
ConfirmDialog: ({ open, title }: { open: boolean; title: string }) => (
<div data-confirm-open={String(open)}>{title}</div>
@@ -39,7 +29,6 @@ const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
can_use: true,
can_manage: true,
can_publish_public: true,
- public_link_enabled: false,
...overrides,
});
@@ -68,7 +57,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('<button');
});
- it('gives Personal an email audience without Organization choices', () => {
+ it('keeps Personal workspace access private without link-sharing controls', () => {
const html = renderControl(access({
mode: 'personal',
instance_id: null,
@@ -81,7 +70,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).not.toContain('chat.showPage.workspaceLevels.public');
expect(html).not.toContain('chat.showPage.workspaceLevels.scope');
expect(html).not.toContain('<select');
- expect(html).toContain('chat.showPage.emailAccess');
+ expect(html).not.toContain('chat.showPage.limitedEmails');
});
it('renders all Organization audiences and keeps the public wire value labeled as Organization', () => {
@@ -91,7 +80,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('value="public" selected=""');
expect(html).toContain('value="scope"');
expect(html).toContain('chat.showPage.workspaceLevels.public');
- expect(html).toContain('chat.showPage.emailAccess');
+ expect(html).not.toContain('chat.showPage.limitedEmails');
});
it('keeps the Organization audience read-only for a non-owner viewer', () => {
@@ -99,13 +88,13 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(html).toContain('<select disabled=""');
expect(html).toContain('chat.showPage.workspaceReadOnly');
- expect(html).not.toContain('chat.showPage.emailAccessDesc');
+ expect(html).not.toContain('chat.showPage.limitedEmails');
});
- it('hides exact-email grants from an Organization admin who does not own the page', () => {
+ it('never nests local link sharing inside Workspace access', () => {
const html = renderControl(access({ can_manage: true, can_publish_public: false }));
- expect(html).not.toContain('chat.showPage.emailAccess');
+ expect(html).not.toContain('chat.showPage.limitedEmails');
});
it('mounts the established Organization audience-narrowing confirmation', () => {
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
index 2e78107e2..d3df03b1f 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -39,7 +39,6 @@ import {
showPageSyncPresentation,
type ShowPageAccess,
} from '@/lib/showPageAccess';
-import { ShowPageEmailAccessEditor } from './ShowPageEmailAccessEditor';
type ManagementGate =
| 'idle'
@@ -435,15 +434,6 @@ export function ShowPageWorkspaceAccessControl({
</div>
) : null}
- {access ? (
- <ShowPageEmailAccessEditor
- active={active}
- canManage={access.can_publish_public}
- sessionId={sessionId}
- onConfirmationOpenChange={onConfirmationOpenChange}
- ownerWindowId={ownerWindowId}
- />
- ) : null}
</section>
<ConfirmDialog
open={confirmNarrowing}
diff --git a/ui/src/components/workbench/sessionArchived.ts b/ui/src/components/workbench/sessionArchived.ts
index 686f946dc..d42e58089 100644
--- a/ui/src/components/workbench/sessionArchived.ts
+++ b/ui/src/components/workbench/sessionArchived.ts
@@ -148,9 +148,9 @@ export const isShowPageActive = (
* to create a missing one (``409 session_archived``, ``core/show_pages.py``).
* So Visualize can only end in that 409, or frame a page that is offline —
* never a working view.
- * - Share's mutations (``update_visibility``, ``set_share_id``, ``rotate_share``)
- * are refused by the same guard, and its popover re-ensures the page on open,
- * so it 409s before it can render anything.
+ * - Share's availability and access-settings mutations are refused by the same
+ * guard, and its popover re-ensures the page on open, so it 409s before it can
+ * render anything.
* - Annotating enqueues an annotation *message* into the session, which the
* messages POST refuses.
*
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index e8b9c7e81..1ea56a2a6 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -8,14 +8,14 @@ import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';
import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';
import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';
-import type { ShowPageLinkInfo } from '../lib/showPageLinks';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
import {
classifyShowPageAccessProbe,
type ShowPageAccess,
type ShowPageAccessProbe,
- type ShowPageAuthorizedEmails,
- type ShowPageVisibilityResult,
+ type ShowAccessApplyRequest,
+ type ShowAccessApplyResult,
+ type ShowAccessSettingsResult,
} from '../lib/showPageAccess';
import {
WorkbenchEventReconnectLoop,
@@ -510,11 +510,11 @@ export type ApiContextType = {
getShowPages: () => Promise<any>;
getShowPageAccess: (sessionId: string) => Promise<ShowPageAccess>;
probeShowPageAccess: (sessionId: string) => Promise<ShowPageAccessProbe>;
- getShowPageAuthorizedEmails: (sessionId: string) => Promise<ShowPageAuthorizedEmails>;
- replaceShowPageAuthorizedEmails: (
+ getShowAccessSettings: (sessionId: string) => Promise<ShowAccessSettingsResult>;
+ applyShowAccess: (
sessionId: string,
- emails: string[],
- ) => Promise<ShowPageAuthorizedEmails>;
+ payload: ShowAccessApplyRequest,
+ ) => Promise<ShowAccessApplyResult>;
getWebPushStatus: (payload?: WebPushStatusPayload) => Promise<WebPushStatus>;
getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;
subscribeWebPush: (
@@ -525,15 +525,9 @@ export type ApiContextType = {
) => Promise<WebPushSubscriptionResult>;
unsubscribeWebPush: (endpoint: string) => Promise<{ ok: boolean; disabled: boolean }>;
sendWebPushTest: (payload?: { title?: string; body?: string; url?: string; endpoint?: string }) => Promise<WebPushTestResult>;
- setShowPageVisibility: <Payload extends ShowPageLinkInfo = ShowPageLinkInfo>(
- sessionId: string,
- visibility: string,
- ) => Promise<ShowPageVisibilityResult<Payload>>;
+ setShowPageAvailability: (sessionId: string, offline: boolean) => Promise<any>;
/** Create the session's Show Page if absent; resolves to `{ existed, ... }`. */
ensureShowPage: (sessionId: string) => Promise<any>;
- rotateShowPageShare: (sessionId: string) => Promise<any>;
- /** Set a custom public link suffix (public pages only); rejects on a taken/invalid id. */
- setShowPageShareId: (sessionId: string, shareId: string) => Promise<any>;
/** Upload an image as the page's workspace-root favicon (multipart); resolves to the
* refreshed page payload carrying the fresh `icon_version` (§7.1j). */
uploadShowPageIcon: (sessionId: string, file: File) => Promise<any>;
@@ -2577,36 +2571,6 @@ export class ApiError extends Error {
}
}
-async function requestShowPageAuthorizedEmails(
- sessionId: string,
- init?: RequestInit,
-): Promise<ShowPageAuthorizedEmails> {
- const path = `/api/show-pages/${encodeURIComponent(sessionId)}/authorized-emails`;
- const response = await apiFetch(path, init);
- const payload: unknown = await response.json().catch(() => ({}));
- if (!response.ok) {
- const fallback = `Request failed: ${path} (${response.status})`;
- const parsed = selectApiErrorFields(payload, fallback);
- throw new ApiError(
- parsed?.fallback ?? fallback,
- response.status,
- parsed?.code ?? null,
- );
- }
- if (
- !payload
- || typeof payload !== 'object'
- || (payload as Partial<ShowPageAuthorizedEmails>).ok !== true
- || !Array.isArray((payload as Partial<ShowPageAuthorizedEmails>).emails)
- || (payload as Partial<ShowPageAuthorizedEmails>).emails?.some(
- (email) => typeof email !== 'string',
- )
- ) {
- throw new ApiError('Invalid Show Page email access response.', 502, null);
- }
- return payload as ShowPageAuthorizedEmails;
-}
-
const ApiContext = createContext<ApiContextType | undefined>(undefined);
const CONFIG_CACHE_TTL_MS = 30_000;
@@ -3320,14 +3284,13 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return { status: 'error', access: null };
}
},
- getShowPageAuthorizedEmails: (sessionId) => requestShowPageAuthorizedEmails(sessionId),
- replaceShowPageAuthorizedEmails: (sessionId, emails) => requestShowPageAuthorizedEmails(
- sessionId,
- {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ emails }),
- },
+ getShowAccessSettings: (sessionId) => postJson(
+ `/api/show-pages/${encodeURIComponent(sessionId)}/access-settings/read`,
+ { page_id: sessionId },
+ ),
+ applyShowAccess: (sessionId, payload) => postJson(
+ `/api/show-pages/${encodeURIComponent(sessionId)}/access-settings/apply`,
+ { page_id: sessionId, ...payload },
),
getWebPushStatus: (payload) =>
payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
@@ -3341,10 +3304,11 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
}),
unsubscribeWebPush: (endpoint) => deleteJson('/api/web-push/subscriptions', { endpoint }),
sendWebPushTest: (payload) => postJson('/api/web-push/test', payload ?? {}),
- setShowPageVisibility: (sessionId, visibility) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/visibility`, { visibility }),
+ setShowPageAvailability: (sessionId, offline) => postJson(
+ `/api/show-pages/${encodeURIComponent(sessionId)}/availability`,
+ { offline },
+ ),
ensureShowPage: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/ensure`, {}),
- rotateShowPageShare: (sessionId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/rotate-share`, {}),
- setShowPageShareId: (sessionId, shareId) => postJson(`/api/show-pages/${encodeURIComponent(sessionId)}/share-id`, { share_id: shareId }),
uploadShowPageIcon: async (sessionId, file) => {
// Multipart POST: the server names the on-disk file, so we send only the bytes
// and a filename hint. `requestJson` adds CSRF + surfaces errors like everything
diff --git a/ui/src/context/ApiErrorParse.test.ts b/ui/src/context/ApiErrorParse.test.ts
index 9cc26bbe8..36e42573d 100644
--- a/ui/src/context/ApiErrorParse.test.ts
+++ b/ui/src/context/ApiErrorParse.test.ts
@@ -86,12 +86,10 @@ describe('locating the session a session_archived response is about', () => {
// ...and the nested writes under it.
expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1/messages')).toBe('ses_1');
expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1/fork')).toBe('ses_1');
- // Show Page mutations are session-keyed under their own collection: ensure,
- // visibility, share-id, rotate-share, icon.
+ // Show Page mutations are session-keyed under their own collection.
expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/ensure')).toBe('ses_1');
- expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/visibility')).toBe('ses_1');
- expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/share-id')).toBe('ses_1');
- expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/rotate-share')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/availability')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/access-settings/apply')).toBe('ses_1');
expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/icon')).toBe('ses_1');
});
@@ -153,9 +151,7 @@ const ARCHIVED_CAPABLE_ROUTES: Array<[string, string, unknown]> = [
['api.updateSession', 'PATCH /api/sessions/ses_1', archivedBody('This session is archived and can no longer be changed.')],
['api.forkSession', '/api/sessions/ses_1/fork', archivedBody('agent session is archived: ses_1')],
['api.ensureShowPage', '/api/show-pages/ses_1/ensure', archivedBody("This session is archived, so its Show Page can't be changed.")],
- ['api.setShowPageVisibility', '/api/show-pages/ses_1/visibility', archivedBody('This session is archived.')],
- ['api.setShowPageShareId', '/api/show-pages/ses_1/share-id', archivedBody('This session is archived.')],
- ['api.rotateShowPageShare', '/api/show-pages/ses_1/rotate-share', archivedBody('This session is archived.')],
+ ['api.setShowPageAvailability', '/api/show-pages/ses_1/availability', archivedBody('This session is archived.')],
['api.uploadShowPageIcon', '/api/show-pages/ses_1/icon', archivedBody("This session is archived, so its Show Page can't be changed.")],
// The messages POST reads its own raw response in ChatPage, but api.sendSessionMessage
// exists on the seam too — so its body has to survive the parser as well.
diff --git a/ui/src/context/apiErrorParse.ts b/ui/src/context/apiErrorParse.ts
index 42406a85c..8c93c7c7b 100644
--- a/ui/src/context/apiErrorParse.ts
+++ b/ui/src/context/apiErrorParse.ts
@@ -37,7 +37,7 @@ export const selectApiErrorFields = (
* Every route that can answer ``409 session_archived`` puts the session id in the
* first segment after its collection: ``/api/sessions/<id>`` (PATCH), plus
* ``/messages`` and ``/fork`` under it, and ``/api/show-pages/<session_id>/…``
- * (ensure / visibility / share-id / rotate-share / icon). One pattern therefore
+ * (ensure / availability / access-settings / icon). One pattern therefore
* covers all of them, and a future session-scoped route inherits it.
*
* Deliberately UNANCHORED: some callers pass a human LABEL rather than a bare
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fa624e015..dc503134c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -177,7 +177,7 @@
},
"showPages": {
"title": "Show Pages",
- "subtitle": "Every agent session has a Show Page. Make it public, keep it private, or take it offline.",
+ "subtitle": "Manage Show Page access and availability.",
"searchPlaceholder": "Search by title or session…",
"allPages": "All pages",
"sortedRecent": "Sorted by most recent",
@@ -186,11 +186,13 @@
"all": "All",
"online": "Online",
"private": "Private",
+ "limited": "Limited",
"public": "Public",
"offline": "Offline"
},
"status": {
"private": "Private",
+ "limited": "Limited",
"public": "Public",
"offline": "Offline"
},
@@ -213,28 +215,17 @@
"updated": "App icon updated"
}
},
- "visibilityLabel": "Visibility",
- "visibilityOffline": "Offline",
"liveLink": "Live link",
"offlineNoLink": "This page is offline — bring it back with the control above to get a live link.",
"copy": "Copy",
"copied": "Copied",
"open": "Open",
"openApp": "Open app",
- "shareLink": "Share link",
- "rotate": "Rotate link",
- "rotateHint": "Generates a new link and disables the current one.",
"shareId": {
"label": "Custom link",
- "hint": "3–64 letters, numbers, dash, or underscore. Must be unique.",
- "placeholder": "my-page",
- "toast": {
- "saved": "Custom link updated"
- },
"errors": {
"taken": "That custom link is already taken. Pick another.",
- "invalid": "Use 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",
- "generic": "Couldn't update the custom link."
+ "invalid": "Use 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number."
}
},
"cloudOff": "Avibe Cloud is off — this link only opens on this device.",
@@ -1636,7 +1627,6 @@
"remote_access_unknown": "The operation did not finish. Refresh the status and try again; if it still fails, check the remote access runtime logs.",
"editor_config_write_forbidden": "Only messaging preferences can be saved from this role.",
"editor_config_write_invalid": "That messaging setting could not be saved.",
- "show_page_email_access_transient": "Email access is temporarily unavailable. Try again.",
"invalid_pairing_key": "This pairing key is invalid or expired. Create a new key at avibe.bot, then paste it here.",
"missing_pairing_key": "Paste the pairing key first.",
"invalid_pairing_backend_url": "The Avibe Cloud URL must be a valid HTTPS address.",
@@ -3553,12 +3543,31 @@
"shareTitle": "Share this Show Page",
"copyLink": "Copy link",
"nativeShare": "Share…",
- "rotateLink": "Replace public link",
"access": "Access",
- "visibilityPublic": "Public",
- "visibilityPrivate": "Private",
- "publicDesc": "Anyone with the link can view",
- "privateDesc": "Only you can view",
+ "sharingAccess": "Link access",
+ "sharingAccessDesc": "Controls the shared /p link independently from Workspace access.",
+ "loadingSharingAccess": "Loading link access…",
+ "sharingModes": {
+ "private": "Private",
+ "limited": "Limited",
+ "public": "Fully public"
+ },
+ "sharingHelp": {
+ "private": "The shared link is disabled.",
+ "limited": "Configure the email audience now; the shared link is not active yet.",
+ "public": "Anyone with the link can open the shared page."
+ },
+ "limitedEmails": "Limited access emails",
+ "limitedEmailRequired": "Add at least one email address.",
+ "limitedEmailLimit": "Up to {{count}} email addresses.",
+ "sharingErrors": {
+ "conflict": "Link access changed elsewhere. The latest version has been loaded.",
+ "invalid": "Review the mode, link, and email list.",
+ "error": "Link access could not be loaded."
+ },
+ "applySharingAccess": "Apply",
+ "narrowSharingTitle": "Restrict link access?",
+ "narrowSharingBody": "People who lose access will be denied on their next page request.",
"workspaceAccess": "Workspace access",
"workspaceAccessDesc": "Who can open this page after signing in.",
"workspaceLevels": {
@@ -3568,7 +3577,7 @@
},
"workspaceHelp": {
"private": "Only the Show Page owner can open it through this access rule.",
- "public": "Anyone with the Show Page link may open it when it is public.",
+ "public": "Any active Organization member may open it, subject to their Avibe and Project access.",
"scope": "Only active members of the selected groups may open it, subject to their Avibe and Project access."
},
"selectedGroups": "Selected groups",
@@ -3592,27 +3601,15 @@
"offline": "This Avibe is offline. The audience change will apply after it reconnects.",
"error": "This Avibe could not apply the audience change."
},
- "emailAccess": "Specific emails",
- "emailAccessDesc": "These signed-in email addresses can open only this Show Page.",
"emailPlaceholder": "[email protected]",
"addEmail": "Add email",
"removeEmail": "Remove {{email}}",
"emailInvalid": "Enter a valid email address.",
- "emailAccessEmpty": "No additional email addresses have access.",
- "emailAccessLimit": "Up to 64 email addresses",
- "applyEmailAccess": "Apply",
- "loadingEmailAccess": "Loading email access…",
- "emailAccessUnavailable": "Email access requires an Avibe Cloud connection.",
- "emailAccessError": "Email access could not be loaded.",
"accessLoadError": "Access details could not be loaded. Sharing changes are disabled.",
- "publicLink": "Public link",
- "publicLinkOnDesc": "Anyone with the link can open this page without signing in.",
- "publicLinkOffDesc": "Anonymous access is off. Signed-in access is controlled above.",
- "publicLinkOwnerOnly": "Only the Show Page owner can replace, customize, or re-enable this link.",
- "publicLinkOffline": "Public links cannot be changed while this Show Page is offline.",
- "customLink": "Custom link",
- "offlineNote": "This Show Page is offline and can't be shared right now.",
- "publicUnavailable": "Connect Avibe Cloud to get a public link others can open.",
+ "availability": "Availability",
+ "offline": "Offline",
+ "availabilityOnline": "Online and serving its configured access mode.",
+ "availabilityOffline": "Offline for everyone; link access is retained.",
"loadError": "Couldn't load this Show Page.",
"pinToDock": "Pin to Dock",
"pinToDockCaption": "Opens as an app from the Dock",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 266d45636..350fd1f3f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -177,7 +177,7 @@
},
"showPages": {
"title": "展示页面",
- "subtitle": "每个 Agent 会话都有一个展示页面。可以将其公开、保持私有,或下线。",
+ "subtitle": "管理 Show Page 的访问范围与在线状态。",
"searchPlaceholder": "按标题或会话搜索…",
"allPages": "全部页面",
"sortedRecent": "按最近活动排序",
@@ -186,11 +186,13 @@
"all": "全部",
"online": "在线",
"private": "私有",
+ "limited": "指定用户",
"public": "公开",
"offline": "已下线"
},
"status": {
"private": "私有",
+ "limited": "指定用户",
"public": "公开",
"offline": "已下线"
},
@@ -213,28 +215,17 @@
"updated": "应用图标已更新"
}
},
- "visibilityLabel": "可见性",
- "visibilityOffline": "下线",
"liveLink": "访问链接",
"offlineNoLink": "该页面已下线——用上方的开关重新上线即可获得访问链接。",
"copy": "复制",
"copied": "已复制",
"open": "打开",
"openApp": "打开应用",
- "shareLink": "分享链接",
- "rotate": "更换链接",
- "rotateHint": "生成新链接并使当前链接立即失效。",
"shareId": {
"label": "自定义链接",
- "hint": "3–64 位,可用字母、数字、短横线或下划线,需唯一。",
- "placeholder": "my-page",
- "toast": {
- "saved": "自定义链接已更新"
- },
"errors": {
"taken": "这个自定义链接已被占用,换一个。",
- "invalid": "请使用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",
- "generic": "更新自定义链接失败。"
+ "invalid": "请使用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。"
}
},
"cloudOff": "Avibe Cloud 未开启——此链接仅能在本机打开。",
@@ -1636,7 +1627,6 @@
"remote_access_unknown": "操作没有完成。请刷新状态后再试一次;如果仍然失败,请查看远程访问运行日志。",
"editor_config_write_forbidden": "当前角色只能保存消息偏好。",
"editor_config_write_invalid": "这条消息设置无法保存。",
- "show_page_email_access_transient": "邮箱权限暂时不可用,请重试。",
"invalid_pairing_key": "这个 pairing key 无效或已过期。请回到 avibe.bot 重新生成一个 key,然后粘贴到这里。",
"missing_pairing_key": "请先粘贴 pairing key。",
"invalid_pairing_backend_url": "Avibe Cloud 地址必须是有效的 HTTPS 地址。",
@@ -3553,12 +3543,31 @@
"shareTitle": "分享这个 Show Page",
"copyLink": "复制链接",
"nativeShare": "系统分享",
- "rotateLink": "更换公开链接",
"access": "权限",
- "visibilityPublic": "公开",
- "visibilityPrivate": "私有",
- "publicDesc": "任何人都可以通过链接查看",
- "privateDesc": "只有你能查看",
+ "sharingAccess": "链接访问",
+ "sharingAccessDesc": "独立控制分享链接 /p,不改变 Workspace 权限。",
+ "loadingSharingAccess": "正在加载链接访问设置…",
+ "sharingModes": {
+ "private": "私有",
+ "limited": "指定用户",
+ "public": "完全公开"
+ },
+ "sharingHelp": {
+ "private": "分享链接已停用。",
+ "limited": "可先配置邮箱名单;分享链接暂未启用。",
+ "public": "任何拿到链接的人都可以打开分享页面。"
+ },
+ "limitedEmails": "指定用户邮箱",
+ "limitedEmailRequired": "请至少添加一个邮箱。",
+ "limitedEmailLimit": "最多添加 {{count}} 个邮箱。",
+ "sharingErrors": {
+ "conflict": "链接访问设置已在其他位置更新,已载入最新版本。",
+ "invalid": "请检查访问模式、链接和邮箱列表。",
+ "error": "无法加载链接访问设置。"
+ },
+ "applySharingAccess": "应用",
+ "narrowSharingTitle": "收紧链接访问范围?",
+ "narrowSharingBody": "失去权限的用户在下一次请求页面时将被拒绝。",
"workspaceAccess": "登录访问范围",
"workspaceAccessDesc": "控制登录后哪些人可以打开此页面。",
"workspaceLevels": {
@@ -3592,27 +3601,15 @@
"offline": "当前 Avibe 已离线,重新连接后会应用访问范围变更。",
"error": "当前 Avibe 无法应用访问范围变更。"
},
- "emailAccess": "指定邮箱",
- "emailAccessDesc": "这些邮箱登录后只能打开当前 Show Page。",
"emailPlaceholder": "[email protected]",
"addEmail": "添加邮箱",
"removeEmail": "移除 {{email}}",
"emailInvalid": "请输入有效的邮箱地址。",
- "emailAccessEmpty": "尚未授权额外邮箱。",
- "emailAccessLimit": "最多 64 个邮箱",
- "applyEmailAccess": "应用",
- "loadingEmailAccess": "正在加载邮箱权限…",
- "emailAccessUnavailable": "连接 Avibe Cloud 后才能设置邮箱权限。",
- "emailAccessError": "无法加载邮箱权限。",
"accessLoadError": "无法加载权限详情,分享设置已停用。",
- "publicLink": "公开链接",
- "publicLinkOnDesc": "任何人都可以通过链接直接打开,无需登录。",
- "publicLinkOffDesc": "匿名访问已关闭;登录后的访问范围由上方设置控制。",
- "publicLinkOwnerOnly": "只有页面所有者可以更换、自定义或重新开启此链接。",
- "publicLinkOffline": "此页面离线期间无法修改公开链接。",
- "customLink": "自定义链接",
- "offlineNote": "这个 Show Page 已离线,暂时无法分享。",
- "publicUnavailable": "连接 Avibe Cloud 后才能获得别人可打开的公开链接。",
+ "availability": "在线状态",
+ "offline": "下线",
+ "availabilityOnline": "页面在线,并按当前链接访问模式提供服务。",
+ "availabilityOffline": "所有人暂时无法访问;链接访问设置会保留。",
"loadError": "无法加载这个 Show Page。",
"pinToDock": "固定到 Dock",
"pinToDockCaption": "作为应用从 Dock 打开",
diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.ts
index 0543ac3a8..a7a8183de 100644
--- a/ui/src/lib/showPageAccess.test.ts
+++ b/ui/src/lib/showPageAccess.test.ts
@@ -2,18 +2,19 @@ import { describe, expect, it } from 'vitest';
import { isRevisionConflict, OrganizationApiError } from '@/features/organization/api/client';
import {
+ SHOW_ACCESS_EMAIL_MAX_COUNT,
buildShowPageAccessPatch,
- canChangeShowPagePublicLink,
classifyShowPageAccessProbe,
- isShowPageVisibilityPayload,
- normalizeShowPageAuthorizedEmail,
- requiresShowPageEmailRevocationConfirmation,
- showPageShareCapabilities,
+ normalizeShowAccessEmail,
+ normalizeShowAccessEmails,
+ showAccessDraftChanged,
+ showAccessTargetEmails,
showPageHeaderAccess,
showPageAudienceLabelKey,
showPageAudienceLevels,
showPageRestoreAccessDecision,
showPageSyncPresentation,
+ type ShowAccess,
type ShowPageAccess,
} from './showPageAccess';
@@ -29,7 +30,6 @@ const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
can_use: true,
can_manage: true,
can_publish_public: true,
- public_link_enabled: false,
...overrides,
});
@@ -46,27 +46,54 @@ describe('Show Page access policy helpers', () => {
expect(showPageAudienceLabelKey('public')).toBe('chat.showPage.workspaceLevels.public');
});
- it('normalizes exact email grants with the backend validation contract', () => {
- expect(normalizeShowPageAuthorizedEmail(' [email protected] ')).toBe(
+ it('normalizes ShowAccess emails with the frozen ASCII contract', () => {
+ expect(normalizeShowAccessEmail(' [email protected] ')).toBe(
);
- expect(normalizeShowPageAuthorizedEmail('guest@example')).toBeNull();
- expect(normalizeShowPageAuthorizedEmail('guest@')).toBeNull();
+ expect(normalizeShowAccessEmails([
+ ])).toEqual(['[email protected]', '[email protected]']);
+ for (const invalid of [
+ 'guest@@example.com',
+ ]) {
+ expect(normalizeShowAccessEmail(invalid)).toBeNull();
+ }
+ expect(normalizeShowAccessEmails(
+ Array.from({ length: SHOW_ACCESS_EMAIL_MAX_COUNT + 1 }, (_, index) => (
+ `guest-${index}@example.com`
+ )),
+ )).toBeNull();
});
- it('requires confirmation only when saved email access is revoked', () => {
- expect(requiresShowPageEmailRevocationConfirmation(
- )).toBe(true);
- expect(requiresShowPageEmailRevocationConfirmation(
- )).toBe(false);
- expect(requiresShowPageEmailRevocationConfirmation(
+ it('keeps emails only for Limited and compares canonical drafts', () => {
+ const saved: ShowAccess = {
+ page_id: 'ses-1',
+ access_mode: 'limited',
+ share_id: 'stable-link',
+ revision: 4,
+ normalized_emails: ['[email protected]', '[email protected]'],
+ };
+ expect(showAccessTargetEmails('private', saved.normalized_emails)).toEqual([]);
+ expect(showAccessTargetEmails('public', saved.normalized_emails)).toEqual([]);
+ expect(showAccessTargetEmails('limited', ['[email protected]', '[email protected]'])).toEqual([
+ ]);
+ expect(showAccessDraftChanged(
+ saved,
+ 'limited',
+ 'stable-link',
)).toBe(false);
+ expect(showAccessDraftChanged(saved, 'public', 'stable-link', [])).toBe(true);
});
it('requires at least one group for scoped access and normalizes duplicates', () => {
@@ -78,62 +105,16 @@ describe('Show Page access policy helpers', () => {
});
});
- it('keeps Public link state out of Organization ACL mutations', () => {
+ it('keeps local ShowAccess state out of Organization ACL mutations', () => {
const patch = buildShowPageAccessPatch('public', ['ignored-group'], 4);
expect(patch).toEqual({
access_level: 'public',
group_ids: [],
if_match_revision: 4,
});
- expect(patch).not.toHaveProperty('public_link_enabled');
expect(patch).not.toHaveProperty('visibility');
});
- it('lets managers close a Public link but only resource owners open one', () => {
- const manager = access({ can_publish_public: false, public_link_enabled: true });
- expect(canChangeShowPagePublicLink(manager, false)).toBe(true);
- expect(canChangeShowPagePublicLink(manager, true)).toBe(false);
- expect(canChangeShowPagePublicLink(access(), true)).toBe(true);
- });
-
- it('lets an access-only manager revoke a Public link without reading its payload', () => {
- const manager = access({
- can_use: false,
- can_publish_public: false,
- public_link_enabled: true,
- });
-
- expect(showPageShareCapabilities(manager)).toEqual({
- canReadPayload: false,
- canRevokePublicLinkWithoutPayload: true,
- canManageDock: false,
- });
- expect(canChangeShowPagePublicLink(manager, false)).toBe(true);
- expect(canChangeShowPagePublicLink(manager, true)).toBe(false);
- });
-
- it('fails closed after an access refresh error and keeps Dock authority separate', () => {
- const manager = access({
- can_use: false,
- can_publish_public: false,
- public_link_enabled: true,
- });
-
- expect(showPageShareCapabilities(manager, { accessInvalid: true })).toEqual({
- canReadPayload: false,
- canRevokePublicLinkWithoutPayload: false,
- canManageDock: false,
- });
- expect(showPageShareCapabilities(null)).toEqual({
- canReadPayload: false,
- canRevokePublicLinkWithoutPayload: false,
- canManageDock: false,
- });
- expect(showPageShareCapabilities(null, { canManageInstance: true }).canReadPayload).toBe(true);
- expect(showPageShareCapabilities(access(), { canManageInstance: false }).canManageDock).toBe(false);
- expect(showPageShareCapabilities(access(), { canManageInstance: true }).canManageDock).toBe(true);
- });
-
it('separates page use from page-specific access management in the chat header', () => {
expect(showPageHeaderAccess(false, access({ can_use: true, can_manage: false }))).toEqual({
canOpen: true,
@@ -163,20 +144,6 @@ describe('Show Page access policy helpers', () => {
expect(showPageRestoreAccessDecision(true, null)).toBe('allow');
});
- it('distinguishes metadata-only visibility results from readable page payloads', () => {
- expect(isShowPageVisibilityPayload({
- ok: true,
- public_link_enabled: false,
- })).toBe(false);
- expect(isShowPageVisibilityPayload({
- ok: true,
- session_id: 'session-1',
- visibility: 'private',
- active_url: '/show/session-1/',
- share_id: null,
- })).toBe(true);
- });
-
it('distinguishes pending, offline, and error sync states', () => {
expect(showPageSyncPresentation('pending')).toEqual({
key: 'chat.showPage.workspaceSync.pending',
diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.ts
index e85c01779..460284698 100644
--- a/ui/src/lib/showPageAccess.ts
+++ b/ui/src/lib/showPageAccess.ts
@@ -1,6 +1,4 @@
import type { ResourceAccessLevel, SyncStatus } from '@/features/organization/api/types';
-import type { ShowPageLinkInfo } from './showPageLinks';
-
export type ShowPageAccess = {
ok: true;
mode: 'personal' | 'organization';
@@ -13,7 +11,6 @@ export type ShowPageAccess = {
can_use: boolean;
can_manage: boolean;
can_publish_public: boolean;
- public_link_enabled: boolean;
};
export type ShowPageAccessProbe =
@@ -21,37 +18,68 @@ export type ShowPageAccessProbe =
| { status: 'denied'; access: null }
| { status: 'error'; access: null };
-export type ShowPageVisibilityMetadata = {
- ok: true;
- public_link_enabled: boolean;
+export type ShowAccessMode = 'private' | 'limited' | 'public';
+
+export type ShowAccess = {
+ page_id: string;
+ access_mode: ShowAccessMode;
+ share_id: string | null;
+ revision: number;
+ normalized_emails: string[];
};
-export type ShowPageVisibilityPayload<Payload extends ShowPageLinkInfo = ShowPageLinkInfo> = {
- ok: true;
-} & Payload;
-export type ShowPageVisibilityResult<Payload extends ShowPageLinkInfo = ShowPageLinkInfo> =
- | ShowPageVisibilityPayload<Payload>
- | ShowPageVisibilityMetadata;
+export type ShowAccessSettingsResult = {
+ show_access: ShowAccess;
+};
-export type ShowPageAuthorizedEmails = {
- ok: true;
- emails: string[];
- changed?: boolean;
+export type ShowAccessApplyRequest = {
+ expected_revision: number;
+ target_access_mode: ShowAccessMode;
+ target_share_id: string | null;
+ target_emails: string[];
};
-const SHOW_PAGE_EMAIL_PATTERN = /^[a-z0-9._%+-]+@[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,}$/;
+export type ShowAccessApplyResult = {
+ status: 'applied' | 'no_change' | 'conflict' | 'share_id_taken' | 'invalid';
+ show_access: ShowAccess;
+};
+
+export const SHOW_ACCESS_EMAIL_MAX_COUNT = 64;
+const SHOW_ACCESS_EMAIL_PATTERN = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
+const ASCII_SURROUNDING_WHITESPACE = /^[\t\n\f\r\v ]+|[\t\n\f\r\v ]+$/g;
+
+export function normalizeShowAccessEmail(raw: string): string | null {
+ const normalized = raw
+ .replace(ASCII_SURROUNDING_WHITESPACE, '')
+ .replace(/[A-Z]/g, (value) => value.toLowerCase());
+ return normalized.length <= 320 && SHOW_ACCESS_EMAIL_PATTERN.test(normalized)
+ ? normalized
+ : null;
+}
+
+export function normalizeShowAccessEmails(emails: string[]): string[] | null {
+ if (emails.length > SHOW_ACCESS_EMAIL_MAX_COUNT) return null;
+ const normalized = emails.map(normalizeShowAccessEmail);
+ if (normalized.some((email) => email === null)) return null;
+ return [...new Set(normalized as string[])].sort();
+}
-export function normalizeShowPageAuthorizedEmail(raw: string): string | null {
- const normalized = raw.trim().toLowerCase();
- return SHOW_PAGE_EMAIL_PATTERN.test(normalized) ? normalized : null;
+export function showAccessTargetEmails(
+ mode: ShowAccessMode,
+ emails: string[],
+): string[] {
+ return mode === 'limited' ? [...new Set(emails)].sort() : [];
}
-export function requiresShowPageEmailRevocationConfirmation(
- savedEmails: string[],
- nextEmails: string[],
+export function showAccessDraftChanged(
+ saved: ShowAccess,
+ mode: ShowAccessMode,
+ shareId: string | null,
+ emails: string[],
): boolean {
- const next = new Set(nextEmails);
- return savedEmails.some((email) => !next.has(email));
+ return saved.access_mode !== mode
+ || saved.share_id !== shareId
+ || saved.normalized_emails.join('\u0000') !== showAccessTargetEmails(mode, emails).join('\u0000');
}
function isShowPageAccess(value: unknown): value is ShowPageAccess {
@@ -61,8 +89,7 @@ function isShowPageAccess(value: unknown): value is ShowPageAccess {
&& (candidate.mode === 'personal' || candidate.mode === 'organization')
&& typeof candidate.can_use === 'boolean'
&& typeof candidate.can_manage === 'boolean'
- && typeof candidate.can_publish_public === 'boolean'
- && typeof candidate.public_link_enabled === 'boolean';
+ && typeof candidate.can_publish_public === 'boolean';
}
export function classifyShowPageAccessProbe(
@@ -88,12 +115,6 @@ export function showPageRestoreAccessDecision(
return probe.access.can_use ? 'allow' : 'deny';
}
-export function isShowPageVisibilityPayload<Payload extends ShowPageLinkInfo>(
- result: ShowPageVisibilityResult<Payload>,
-): result is ShowPageVisibilityPayload<Payload> {
- return 'session_id' in result && typeof result.session_id === 'string';
-}
-
export function showPageHeaderAccess(
canManageInstance: boolean,
access: ShowPageAccess | null,
@@ -136,42 +157,6 @@ export function buildShowPageAccessPatch(
};
}
-export function canChangeShowPagePublicLink(
- access: ShowPageAccess | null,
- nextEnabled: boolean,
-): boolean {
- if (!access) return false;
- return nextEnabled ? access.can_publish_public : access.can_manage;
-}
-
-export function showPageShareCapabilities(
- access: ShowPageAccess | null,
- options: {
- accessInvalid?: boolean;
- canManageInstance?: boolean;
- } = {},
-): {
- canReadPayload: boolean;
- canRevokePublicLinkWithoutPayload: boolean;
- canManageDock: boolean;
-} {
- const accessValid = options.accessInvalid !== true;
- const canManageInstance = options.canManageInstance === true;
- return {
- canReadPayload: accessValid && (canManageInstance || access?.can_use === true),
- canRevokePublicLinkWithoutPayload: Boolean(
- accessValid
- && access
- && !access.can_use
- && access.can_manage
- && access.public_link_enabled,
- ),
- // Dock writes remain Instance-owner operations. Page-level use/manage
- // authority deliberately does not inherit this independent capability.
- canManageDock: canManageInstance,
- };
-}
-
export function showPageSyncPresentation(status: SyncStatus): {
key: string;
tone: 'muted' | 'pending' | 'error';
diff --git a/ui/src/lib/showPageLinks.test.ts b/ui/src/lib/showPageLinks.test.ts
new file mode 100644
index 000000000..b332b6913
--- /dev/null
+++ b/ui/src/lib/showPageLinks.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { copyHref, editorPath, liveHref, localPath, type ShowPageLinkInfo } from './showPageLinks';
+
+const page = (visibility: string): ShowPageLinkInfo => ({
+ session_id: 'ses/author',
+ visibility,
+ active_url: null,
+ share_id: 'shared-link',
+});
+
+describe('Show Page link routes', () => {
+ it('keeps authenticated editor frames on the author route for every online mode', () => {
+ expect(editorPath(page('private'))).toBe('/show/ses%2Fauthor/');
+ expect(editorPath(page('limited'))).toBe('/show/ses%2Fauthor/');
+ expect(editorPath(page('public'))).toBe('/show/ses%2Fauthor/');
+ expect(editorPath(page('offline'))).toBeNull();
+ expect(editorPath(page('unexpected'))).toBeNull();
+ });
+
+ it('does not expose Limited as a live link before signed-in guest admission exists', () => {
+ const limited = {
+ ...page('limited'),
+ active_url: 'https://show.example.test/p/shared-link/',
+ };
+ expect(localPath(limited)).toBeNull();
+ expect(liveHref(limited)).toBeNull();
+ expect(copyHref(limited)).toBeNull();
+ });
+
+ it('keeps public share links on the guest-facing route', () => {
+ expect(localPath(page('public'))).toBe('/p/shared-link/');
+ });
+});
diff --git a/ui/src/lib/showPageLinks.ts b/ui/src/lib/showPageLinks.ts
index 7d17f8703..888a32f6a 100644
--- a/ui/src/lib/showPageLinks.ts
+++ b/ui/src/lib/showPageLinks.ts
@@ -10,15 +10,29 @@ export type ShowPageLinkInfo = {
share_id: string | null;
};
-// Same-origin path a Show Page is served at locally. Null when the page is
-// offline (or public without a share id), where there is no live route.
+// Same-origin path a Show Page is served at locally. Null when there is no live
+// route, including Limited until signed-in guest admission is implemented.
export function localPath(page: ShowPageLinkInfo): string | null {
if (page.visibility === 'private') return `/show/${encodeURIComponent(page.session_id)}/`;
- if (page.visibility === 'public' && page.share_id) return `/p/${encodeURIComponent(page.share_id)}/`;
+ if (page.visibility === 'public' && page.share_id) {
+ return `/p/${encodeURIComponent(page.share_id)}/`;
+ }
+ return null;
+}
+
+// The Workbench always uses the authenticated author route. Shared /p links
+// have separate admission rules and may intentionally reject non-public pages.
+export function editorPath(page: ShowPageLinkInfo): string | null {
+ if (page.visibility === 'private' || page.visibility === 'limited' || page.visibility === 'public') {
+ return `/show/${encodeURIComponent(page.session_id)}/`;
+ }
return null;
}
export function liveHref(page: ShowPageLinkInfo): string | null {
+ // Limited is configurable in this lane, but its signed-in guest admission is
+ // not active yet. Ignore even a stale server-projected URL until that exists.
+ if (page.visibility === 'limited') return null;
return page.active_url || localPath(page);
}
@@ -35,7 +49,7 @@ export function displayLink(page: ShowPageLinkInfo): string | null {
return href ? href.replace(/^https?:\/\//, '') : null;
}
-// Custom public link suffix (the /p/<share_id>/ segment). Mirrors the server
+// Custom share-link suffix (the /p/<share_id>/ segment). Mirrors the server
// rule in core/show_pages.validate_share_id so the field can give instant
// feedback before the request; the server stays the authority on uniqueness.
export const SHARE_ID_MIN_LENGTH = 3;
diff --git a/ui/src/lib/showPagesStore.test.ts b/ui/src/lib/showPagesStore.test.ts
index f7a3bda6b..f8bf85aa2 100644
--- a/ui/src/lib/showPagesStore.test.ts
+++ b/ui/src/lib/showPagesStore.test.ts
@@ -9,6 +9,10 @@ import {
const page = (overrides: Partial<ShowPage> = {}): ShowPage => ({
session_id: 'session-1',
visibility: 'private',
+ access_mode: 'private',
+ access_revision: 0,
+ can_manage: true,
+ can_publish_public: true,
title: 'Dashboard',
platform: null,
agent: null,
diff --git a/ui/src/lib/showPagesStore.ts b/ui/src/lib/showPagesStore.ts
index eeee3316f..07fda778a 100644
--- a/ui/src/lib/showPagesStore.ts
+++ b/ui/src/lib/showPagesStore.ts
@@ -1,10 +1,14 @@
import type { ApiContextType } from '../context/ApiContext';
-export type Visibility = 'private' | 'public' | 'offline';
+export type Visibility = 'private' | 'limited' | 'public' | 'offline';
export interface ShowPage {
session_id: string;
visibility: Visibility;
+ access_mode: 'private' | 'limited' | 'public';
+ access_revision: number;
+ can_manage: boolean;
+ can_publish_public: boolean;
title: string | null;
platform: string | null;
agent: string | null;
diff --git a/vibe/api.py b/vibe/api.py
index edafa4012..cdc34ce6c 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1538,12 +1538,32 @@ def list_show_pages(*, user_context: Any = None) -> dict:
"""
from core.avibe_cloud import avibe_cloud_connect_guidance, avibe_cloud_url_available
from core.show_pages import ShowPageStore, show_page_payload
+ from storage import resource_access_service
config = V2Config.load()
+ context = resource_access_service.resolve_resource_access_context(user_context)
store = ShowPageStore()
try:
result = store.list_page(page_request=None, user_context=user_context)
pages = [show_page_payload(page, config=config) for page in result.items]
+ with store.engine.connect() as connection:
+ for payload in pages:
+ session_id = payload["session_id"]
+ payload["can_manage"] = (
+ resource_access_service.can_manage_show_page_access(
+ context,
+ session_id,
+ connection=connection,
+ )
+ )
+ payload["can_publish_public"] = (
+ resource_access_service.can_control_resource_sharing(
+ context,
+ "show_page",
+ session_id,
+ connection=connection,
+ )
+ )
finally:
store.close()
_apply_session_meta(pages)
@@ -1576,12 +1596,9 @@ def _show_page_mutation_response(
connection=connection,
)
if not can_use:
- # Audience managers may revoke an anonymous link without page-use
- # access. Do not return page paths, URLs, share IDs, or session metadata.
- return {
- "ok": True,
- "public_link_enabled": page.visibility == "public",
- }
+ # Access managers may take a page offline without page-use access. Do
+ # not return page paths, URLs, share IDs, audience, or session metadata.
+ return {"ok": True}
from core.show_pages import show_page_payload
payload = show_page_payload(page, config=config)
@@ -1592,25 +1609,22 @@ def _show_page_mutation_response(
}
-def set_show_page_visibility(
+def set_show_page_availability(
session_id: str,
- visibility: str,
+ offline: bool,
*,
user_context: Any = None,
) -> dict:
- """Switch a Show Page between private / public / offline.
+ """Change Show Page availability without mutating its configured audience."""
- Raises ``ShowPageError`` (a ``ValueError``) for invalid input, which the
- route layer maps to a 4xx response.
- """
from core.show_pages import ShowPageStore
config = V2Config.load()
store = ShowPageStore()
try:
- updated = store.update_visibility(
+ updated = store.set_offline(
session_id,
- visibility,
+ offline,
user_context=user_context,
)
return _show_page_mutation_response(
@@ -1704,11 +1718,10 @@ def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:
"can_use": can_use,
"can_manage": can_manage,
"can_publish_public": can_publish_public,
- "public_link_enabled": page.visibility == "public",
}
-def _require_show_page_email_access_owner(
+def require_show_access_settings_control(
session_id: str,
*,
user_context: Any = None,
@@ -1737,130 +1750,6 @@ def _require_show_page_email_access_owner(
store.close()
-def _show_page_email_access_error(exc: Exception):
- from core.show_pages import ShowPageError
- from vibe import remote_access
-
- known_codes = {
- "invalid_email",
- "too_many_entries",
- "show_page_email_access_not_configured",
- "show_page_email_access_invalid_response",
- }
- transient_code = "show_page_email_access_transient"
- if isinstance(exc, ShowPageError):
- return exc
- if isinstance(exc, remote_access.BackendRequestError):
- raw_code = str(exc.payload.get("error") or "")
- code = raw_code if raw_code in known_codes else (
- transient_code if exc.status >= 500 else "show_page_email_access_unavailable"
- )
- else:
- raw_code = str(exc)
- code = transient_code if raw_code in {
- "resource_acl_device_unavailable",
- "show_page_email_access_invalid_response",
- } else raw_code or "show_page_email_access_unavailable"
- if code not in known_codes and code != transient_code:
- code = "show_page_email_access_unavailable"
- return ShowPageError(code, code=code)
-
-
-def get_show_page_authorized_emails(
- session_id: str,
- *,
- user_context: Any = None,
-) -> dict:
- """Return exact email grants for one owner-managed Show Page."""
-
- from vibe import remote_access
-
- _require_show_page_email_access_owner(session_id, user_context=user_context)
- try:
- result = remote_access.get_show_page_authorized_emails(session_id)
- except Exception as exc:
- raise _show_page_email_access_error(exc) from exc
- return {"ok": True, "emails": result["emails"]}
-
-
-def replace_show_page_authorized_emails(
- session_id: str,
- emails: list[str],
- *,
- user_context: Any = None,
-) -> dict:
- """Replace one Show Page's exact email grants through paired-device auth."""
-
- from vibe import remote_access
-
- _require_show_page_email_access_owner(session_id, user_context=user_context)
- normalized = sorted({str(email).strip().lower() for email in emails if str(email).strip()})
- try:
- result = remote_access.replace_show_page_authorized_emails(session_id, normalized)
- except Exception as exc:
- raise _show_page_email_access_error(exc) from exc
- return {
- "ok": True,
- "emails": result["emails"],
- "changed": result["changed"],
- }
-
-
-def rotate_show_page_share(session_id: str, *, user_context: Any = None) -> dict:
- """Revoke the current public link and issue a new one (public pages only)."""
- from core.show_pages import ShowPageStore
-
- config = V2Config.load()
- store = ShowPageStore()
- try:
- updated, previous_share_id = store.rotate_share(
- session_id,
- user_context=user_context,
- )
- return _show_page_mutation_response(
- store,
- updated,
- config=config,
- additional_payload={"previous_share_id": previous_share_id},
- user_context=user_context,
- )
- finally:
- store.close()
-
-
-def set_show_page_share_id(
- session_id: str,
- share_id: str,
- *,
- user_context: Any = None,
-) -> dict:
- """Set a custom public link suffix (public pages only).
-
- Like ``rotate_show_page_share`` but with a caller-chosen value; setting it
- revokes the previous public URL. Raises ``ShowPageError`` for an invalid /
- taken suffix or a non-public page, which the route layer maps to a 4xx/409.
- """
- from core.show_pages import ShowPageStore
-
- config = V2Config.load()
- store = ShowPageStore()
- try:
- updated, previous_share_id = store.set_share_id(
- session_id,
- share_id,
- user_context=user_context,
- )
- return _show_page_mutation_response(
- store,
- updated,
- config=config,
- additional_payload={"previous_share_id": previous_share_id},
- user_context=user_context,
- )
- finally:
- store.close()
-
-
def upload_show_page_icon(
session_id: str,
data: bytes,
@@ -8540,7 +8429,12 @@ def startup_show_page_prewarm_targets(limit: int | None = None) -> dict:
if resolved_limit <= 0:
return {"ok": True, "limit": resolved_limit, "pages": []}
- from core.show_pages import ShowPageStore, VISIBILITY_PRIVATE, VISIBILITY_PUBLIC
+ from core.show_pages import (
+ ShowPageStore,
+ VISIBILITY_LIMITED,
+ VISIBILITY_PRIVATE,
+ VISIBILITY_PUBLIC,
+ )
from core.show_runtime import ShowRuntimeContext
from storage.pagination import PageRequest
@@ -8548,6 +8442,7 @@ def startup_show_page_prewarm_targets(limit: int | None = None) -> dict:
try:
candidates = [
*store.list_page(visibility=VISIBILITY_PRIVATE, page_request=PageRequest(limit=resolved_limit)).items,
+ *store.list_page(visibility=VISIBILITY_LIMITED, page_request=PageRequest(limit=resolved_limit)).items,
*store.list_page(visibility=VISIBILITY_PUBLIC, page_request=PageRequest(limit=resolved_limit)).items,
]
finally:
diff --git a/vibe/authorization.py b/vibe/authorization.py
index c8b8066ff..19d331727 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -347,7 +347,6 @@ _VIEWER_HTTP_RULES = tuple(
r"^/api/resource-policies$",
r"^/api/show-pages$",
r"^/api/show-pages/[^/]+/access$",
- r"^/api/show-pages/[^/]+/authorized-emails$",
r"^/api/show-pages/[^/]+/icon$",
)
)
@@ -405,8 +404,8 @@ _EDITOR_HTTP_RULES = tuple(
("POST", r"^/api/show/sessions/[^/]+/events$"),
("POST", r"^/api/show/sessions/[^/]+/prewarm$"),
("POST", r"^/api/show-pages/[^/]+/icon$"),
- ("POST", r"^/api/show-pages/[^/]+/(?:ensure|visibility|rotate-share|share-id)$"),
- ("PUT", r"^/api/show-pages/[^/]+/authorized-emails$"),
+ ("POST", r"^/api/show-pages/[^/]+/(?:ensure|availability)$"),
+ ("POST", r"^/api/show-pages/[^/]+/access-settings/(?:read|apply)$"),
)
)
diff --git a/vibe/cli.py b/vibe/cli.py
index feb4e0113..d06ac5051 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -15219,7 +15219,7 @@ def build_parser():
)
show_list_parser.add_argument(
"--visibility",
- choices=("private", "public", "offline"),
+ choices=("private", "limited", "public", "offline"),
help="Filter by Show Page visibility.",
)
show_list_parser.add_argument("--session-id", help="Filter by Agent Session ID prefix.")
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 275a5637a..de4b91377 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -1350,6 +1350,58 @@ async def end_running_agent(payload: dict[str, Any], *, socket_path: Optional[Pa
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def _show_access_request(
+ path: str,
+ payload: dict[str, Any],
+ *,
+ read_timeout: float | None,
+ socket_path: Optional[Path] = None,
+) -> dict[str, Any]:
+ target = await _verified_socket_path_async(socket_path)
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(read_timeout, connect=1.0),
+ ) as client:
+ resp = await client.post(path, json=payload)
+ except httpx.ReadTimeout as exc:
+ raise InternalServerTimeout(str(exc)) from exc
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
+async def show_access_settings_read(
+ payload: dict[str, Any],
+ *,
+ socket_path: Optional[Path] = None,
+) -> dict[str, Any]:
+ return await _show_access_request(
+ "/internal/show-access/settings-read",
+ payload,
+ read_timeout=10.0,
+ socket_path=socket_path,
+ )
+
+
+async def show_access_apply(
+ payload: dict[str, Any],
+ *,
+ socket_path: Optional[Path] = None,
+) -> dict[str, Any]:
+ return await _show_access_request(
+ "/internal/show-access/apply",
+ payload,
+ # Once accepted, the controller serializes this non-cancellable SQLite
+ # write. Wait for its definitive CAS result so a slow commit is never
+ # reported as a timeout that invites an ambiguous retry.
+ read_timeout=None,
+ socket_path=socket_path,
+ )
+
+
async def send_now(
session_id: str,
*,
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index d3f73aaf4..7371b4b70 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -1567,66 +1567,6 @@ def _device_json_request(
return parsed
-def _show_page_email_grant_suffix(show_page_id: str) -> str:
- encoded = urllib.parse.quote(show_page_id, safe="")
- return f"show-pages/{encoded}/authorized-emails"
-
-
-def get_show_page_authorized_emails(
- show_page_id: str,
- config: V2Config | None = None,
-) -> dict[str, Any]:
- """Load one Show Page's exact email grants through paired-device auth."""
-
- config = config or V2Config.load()
- if not _resource_acl_sync_configured(config):
- raise RuntimeError("show_page_email_access_not_configured")
- result = _device_json_request(
- config,
- "GET",
- _show_page_email_grant_suffix(show_page_id),
- )
- emails = result.get("emails")
- if not isinstance(emails, list) or any(not isinstance(email, str) for email in emails):
- raise RuntimeError("show_page_email_access_invalid_response")
- return {"emails": emails}
-
-
-def replace_show_page_authorized_emails(
- show_page_id: str,
- emails: list[str],
- config: V2Config | None = None,
-) -> dict[str, Any]:
- """Replace one Show Page's email grants without exposing the device secret."""
-
- config = config or V2Config.load()
- if not _resource_acl_sync_configured(config):
- raise RuntimeError("show_page_email_access_not_configured")
- result = _device_json_request(
- config,
- "PUT",
- _show_page_email_grant_suffix(show_page_id),
- {"emails": emails},
- )
- returned_emails = result.get("emails")
- if not isinstance(returned_emails, list) or any(
- not isinstance(email, str) for email in returned_emails
- ):
- raise RuntimeError("show_page_email_access_invalid_response")
- changed = bool(result.get("changed"))
- if changed and "authorization_revision" not in result:
- raise RuntimeError("show_page_email_access_invalid_response")
- if result.get("authorization_revision") is not None:
- try:
- _replace_authorization_revision(config, result["authorization_revision"])
- except ValueError as exc:
- raise RuntimeError("show_page_email_access_invalid_response") from exc
- return {
- "emails": returned_emails,
- "changed": changed,
- }
-
-
def sync_authorization_revision_once(
config: V2Config | None = None,
) -> dict[str, Any]:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 14392d180..72c562d4a 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -53,6 +53,7 @@ from core.show_pages import (
SHOW_EVENT_WRITE_TOKEN_COOKIE,
SHOW_EVENT_WRITE_TOKEN_HEADER,
SHOW_PAGE_ICON_MAX_UPLOAD_BYTES,
+ VISIBILITY_LIMITED,
VISIBILITY_OFFLINE,
VISIBILITY_PRIVATE,
VISIBILITY_PUBLIC,
@@ -3032,10 +3033,10 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):
except ShowPageError:
await websocket.close(code=1008)
return
- # Amendment (§2.3, 2026-07-13): the authed /show/ surface serves public
- # pages too, so a public page framed in the Dock app must also get live
- # HMR. Mirror the serve route's private+public visibility gate here.
- if page is None or page.visibility not in {"private", "public"}:
+ # The authenticated /show/ surface is the editor path for every online
+ # audience mode. Limited /p admission remains a separate shared-runtime
+ # boundary, but choosing Limited must not break the owner's live preview.
+ if page is None or page.visibility not in {"private", "limited", "public"}:
await websocket.close(code=1008)
return
finally:
@@ -5348,10 +5349,8 @@ def _show_page_error_response(exc):
status = 404
# A conflict (not a malformed request) when the page is in the wrong state or
# the chosen suffix is already claimed.
- elif code in {"not_public", "share_id_taken"}:
+ elif code in {"not_public", "not_shared", "share_id_taken", "show_access_conflict"}:
status = 409
- elif code == "show_page_email_access_transient":
- status = 503
else:
status = 400
return _coded_error_response(code, str(exc), status)
@@ -5446,20 +5445,27 @@ def show_pages_list_get():
return jsonify(payload)
[email protected]("/api/show-pages/<session_id>/visibility", methods=["POST"])
-def show_page_visibility_post(session_id):
[email protected]("/api/show-pages/<session_id>/availability", methods=["POST"])
+def show_page_availability_post(session_id):
from core.show_pages import ShowPageError
from vibe import api
- payload = request.json or {}
+ payload = request.json if isinstance(request.json, dict) else {}
+ if set(payload) != {"offline"} or not isinstance(payload.get("offline"), bool):
+ return _show_page_error_response(
+ ShowPageError("Invalid Show Page availability.", code="invalid_availability")
+ )
try:
context = _request_authorization_context()
return jsonify(
- _show_page_response_for_request(api.set_show_page_visibility(
- session_id,
- str(payload.get("visibility") or ""),
- user_context=context,
- ), context)
+ _show_page_response_for_request(
+ api.set_show_page_availability(
+ session_id,
+ payload["offline"],
+ user_context=context,
+ ),
+ context,
+ )
)
except ShowPageError as exc:
return _show_page_error_response(exc)
@@ -5504,87 +5510,128 @@ def show_page_access_get(session_id):
return _show_page_error_response(exc)
[email protected]("/api/show-pages/<session_id>/authorized-emails", methods=["GET"])
-def show_page_authorized_emails_get(session_id):
- from core.show_pages import ShowPageError
- from vibe import api
+def _show_access_http_response(body: dict[str, Any], status: int = 200):
+ response = jsonify(body)
+ response.status_code = status
+ response.headers["Cache-Control"] = "private, no-store"
+ response.headers["Vary"] = "Cookie"
+ return response
- try:
- response = jsonify(
- api.get_show_page_authorized_emails(
- session_id,
- user_context=_request_authorization_context(),
- )
+
+def _show_access_page_identity_matches(body: Any, page_id: str) -> bool:
+ return bool(
+ isinstance(body, dict)
+ and isinstance(body.get("show_access"), dict)
+ and body["show_access"].get("page_id") == page_id
+ )
+
+
+def _valid_show_access_apply_payload(payload: dict[str, Any]) -> bool:
+ return bool(
+ isinstance(payload.get("page_id"), str)
+ and not isinstance(payload.get("expected_revision"), bool)
+ and isinstance(payload.get("expected_revision"), int)
+ and payload["expected_revision"] >= 0
+ and isinstance(payload.get("target_access_mode"), str)
+ and (
+ payload.get("target_share_id") is None
+ or isinstance(payload.get("target_share_id"), str)
)
- response.headers["Cache-Control"] = "no-store, private"
- response.headers["Vary"] = "Cookie"
- return response
- except ShowPageError as exc:
- return _show_page_error_response(exc)
+ and isinstance(payload.get("target_emails"), list)
+ and all(isinstance(email, str) for email in payload["target_emails"])
+ )
[email protected]("/api/show-pages/<session_id>/authorized-emails", methods=["PUT"])
-def show_page_authorized_emails_put(session_id):
[email protected]("/api/show-pages/<session_id>/access-settings/read", methods=["POST"])
+async def show_page_access_settings_read(session_id):
from core.show_pages import ShowPageError
- from vibe import api
+ from vibe import api, internal_client
payload = request.json if isinstance(request.json, dict) else {}
- emails = payload.get("emails")
- if (
- not isinstance(emails, list)
- or len(emails) > 64
- or any(not isinstance(email, str) for email in emails)
- ):
- return _show_page_error_response(
- ShowPageError("Invalid Show Page email audience.", code="invalid_email")
+ if set(payload) != {"page_id"} or payload.get("page_id") != session_id:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_page_identity_mismatch"},
+ 400,
)
try:
- context = _request_authorization_context()
- return jsonify(
- _show_page_response_for_request(api.replace_show_page_authorized_emails(
- session_id,
- emails,
- user_context=context,
- ), context)
+ api.require_show_access_settings_control(
+ session_id,
+ user_context=_request_authorization_context(),
)
except ShowPageError as exc:
return _show_page_error_response(exc)
-
-
[email protected]("/api/show-pages/<session_id>/rotate-share", methods=["POST"])
-def show_page_rotate_share_post(session_id):
- from core.show_pages import ShowPageError
- from vibe import api
-
try:
- context = _request_authorization_context()
- return jsonify(
- _show_page_response_for_request(api.rotate_show_page_share(
- session_id,
- user_context=context,
- ), context)
+ result = await internal_client.show_access_settings_read(payload)
+ except internal_client.InternalServerUnavailable:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_controller_unavailable"},
+ 503,
)
- except ShowPageError as exc:
- return _show_page_error_response(exc)
+ except internal_client.InternalServerTimeout:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_controller_timeout"},
+ 504,
+ )
+ body = result.get("body") or {}
+ status = int(result.get("status_code") or 500)
+ if status == 200 and not _show_access_page_identity_matches(body, session_id):
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_internal_protocol_error"},
+ 502,
+ )
+ return _show_access_http_response(body, status)
[email protected]("/api/show-pages/<session_id>/share-id", methods=["POST"])
-def show_page_set_share_id_post(session_id):
[email protected]("/api/show-pages/<session_id>/access-settings/apply", methods=["POST"])
+async def show_page_access_settings_apply(session_id):
from core.show_pages import ShowPageError
- from vibe import api
+ from vibe import api, internal_client
- payload = request.json or {}
+ payload = request.json if isinstance(request.json, dict) else {}
+ required = {
+ "page_id",
+ "expected_revision",
+ "target_access_mode",
+ "target_share_id",
+ "target_emails",
+ }
+ if payload.get("page_id") != session_id:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_page_identity_mismatch"},
+ 400,
+ )
+ if set(payload) != required or not _valid_show_access_apply_payload(payload):
+ return _show_access_http_response(
+ {"ok": False, "error": "invalid_show_access_apply_request"},
+ 400,
+ )
try:
- context = _request_authorization_context()
- return jsonify(
- _show_page_response_for_request(api.set_show_page_share_id(
- session_id,
- str(payload.get("share_id") or ""),
- user_context=context,
- ), context)
+ api.require_show_access_settings_control(
+ session_id,
+ user_context=_request_authorization_context(),
)
except ShowPageError as exc:
return _show_page_error_response(exc)
+ try:
+ result = await internal_client.show_access_apply(payload)
+ except internal_client.InternalServerUnavailable:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_controller_unavailable"},
+ 503,
+ )
+ except internal_client.InternalServerTimeout:
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_controller_timeout"},
+ 504,
+ )
+ body = result.get("body") or {}
+ status = int(result.get("status_code") or 500)
+ if status == 200 and not _show_access_page_identity_matches(body, session_id):
+ return _show_access_http_response(
+ {"ok": False, "error": "show_access_internal_protocol_error"},
+ 502,
+ )
+ return _show_access_http_response(body, status)
def _show_page_icon_not_found():
@@ -13205,7 +13252,11 @@ def _show_annotation_capability(
return False
if public_share_id is not None:
return page.visibility == VISIBILITY_PUBLIC and page.share_id == public_share_id
- return page.visibility in {VISIBILITY_PRIVATE, VISIBILITY_PUBLIC}
+ return page.visibility in {
+ VISIBILITY_PRIVATE,
+ VISIBILITY_LIMITED,
+ VISIBILITY_PUBLIC,
+ }
def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
@@ -14737,10 +14788,9 @@ def redirect_private_show_page_to_canonical_path(session_id):
if exc.code == "resource_access_forbidden":
return _show_page_access_forbidden_response()
return _show_page_not_found_response()
- # Amendment (§2.3, 2026-07-13): the authed /show/ surface serves public
- # pages too, so the sibling no-trailing-slash canonical redirect must
- # accept public as well (offline still redirects to its offline page).
- if page.visibility not in {"private", "public", "offline"}:
+ # The authenticated editor surface accepts every configured audience;
+ # offline still redirects to the explanatory offline page.
+ if page.visibility not in {"private", "limited", "public", "offline"}:
return _show_page_not_found_response()
return redirect(f"/show/{quote(session_id, safe='')}/")
finally:
@@ -14773,15 +14823,11 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_not_found_response()
if page.visibility == "offline":
return _show_page_offline_response()
- # Amendment (2026-07-13, docs/plans/dock-pinned-show-page-apps.md §2.3): the
- # authed workbench `/show/<id>/` surface serves BOTH private and public
- # pages, so a Show Page pinned to the Dock while public still opens (a
- # pinned public page must not open a broken window). This is no new
- # exposure — the route stays behind workbench auth, and a public page is
- # already anonymously readable via `/p/<share_id>`, which remains the only
- # anonymous surface. `offline` (handled above) and any unexpected
- # visibility still fall through to not-found.
- if page.visibility not in {"private", "public"}:
+ # The Workbench editor route serves every online audience mode. This is
+ # no new anonymous exposure: `/show` stays behind Workbench and resource
+ # authorization, while `/p` owns shared navigation admission. `offline`
+ # (handled above) and unexpected states still fail closed.
+ if page.visibility not in {"private", "limited", "public"}:
return _show_page_not_found_response()
# A remote viewer is an untrusted viewer even on the private surface: keep
# its asset reads inside the page workspace so an authored symlink cannot