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.

add Show Page access controls

Maxb46d93b25a31
diff --git a/core/show_pages.py b/core/show_pages.py
index c9eb35403..5712a3831 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -251,6 +251,47 @@ def require_show_page_management(
raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+def require_show_page_sharing_control(
+ connection: Connection,
+ session_id: str,
+ *,
+ user_context: Any = None,
+) -> None:
+ """Require resource-owner authority for anonymous publication changes."""
+
+ from storage import resource_access_service
+
+ session_id = validate_session_id(session_id)
+ context = _resolve_resource_access_context(user_context)
+ if not resource_access_service.can_control_resource_sharing(
+ context,
+ "show_page",
+ session_id,
+ connection=connection,
+ ):
+ raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+
+
+def require_show_page_access_management(
+ connection: Connection,
+ session_id: str,
+ *,
+ user_context: Any = None,
+) -> None:
+ """Require authority to manage the audience or make sharing more restrictive."""
+
+ from storage import resource_access_service
+
+ session_id = validate_session_id(session_id)
+ context = _resolve_resource_access_context(user_context)
+ if not resource_access_service.can_manage_show_page_access(
+ context,
+ session_id,
+ connection=connection,
+ ):
+ raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+
+
def private_url(session_id: str, *, config: V2Config | None = None) -> str | None:
base = base_public_url(config)
if not base:
@@ -394,6 +435,14 @@ class ShowPageStore:
def _require_resource_management(connection, session_id: str, user_context: Any) -> None:
require_show_page_management(connection, session_id, user_context=user_context)
+ @staticmethod
+ def _require_sharing_control(connection, session_id: str, user_context: Any) -> None:
+ require_show_page_sharing_control(connection, session_id, user_context=user_context)
+
+ @staticmethod
+ def _require_access_management(connection, session_id: str, user_context: Any) -> None:
+ require_show_page_access_management(connection, session_id, user_context=user_context)
+
@staticmethod
def _require_create_access(user_context: Any) -> None:
if user_context.can_manage_instance:
@@ -404,7 +453,12 @@ class ShowPageStore:
def _register_created_resource_policy(connection, session_id: str, user_context: Any) -> None:
from storage import resource_access_service
- if not (user_context.is_remote and user_context.is_active_organization_member and user_context.subject):
+ if not (
+ user_context.is_remote
+ and user_context.can_manage_instance
+ and user_context.is_active_organization_member
+ and user_context.subject
+ ):
return
resource_access_service.ensure_resource_policy(
connection,
@@ -437,6 +491,7 @@ class ShowPageStore:
.first()
)
if existing is not None:
+ self._register_created_resource_policy(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing)
self._require_create_access(context)
@@ -473,6 +528,7 @@ class ShowPageStore:
.first()
)
if existing is not None:
+ self._register_created_resource_policy(conn, session_id, context)
self._require_resource_access(conn, session_id, context)
return _page_from_row(existing), False
self._require_create_access(context)
@@ -535,7 +591,14 @@ class ShowPageStore:
if existing is not None:
# Check management before reporting a terminal lifecycle state so an
# unauthorized remote user cannot probe page/session details.
- page = self.require_management(session_id, user_context=context)
+ if visibility == VISIBILITY_PUBLIC:
+ with self.engine.connect() as conn:
+ self._require_sharing_control(conn, session_id, context)
+ page = existing
+ else:
+ with self.engine.connect() as conn:
+ self._require_access_management(conn, session_id, context)
+ page = existing
else:
page = None
# Reject republish BEFORE ``ensure`` so it doesn't first materialize a
@@ -558,7 +621,10 @@ class ShowPageStore:
if visibility == VISIBILITY_PUBLIC and not page.share_id:
values["share_id"] = self._unique_share_id()
with self.engine.begin() as conn:
- self._require_resource_management(conn, session_id, context)
+ if visibility == VISIBILITY_PUBLIC:
+ self._require_sharing_control(conn, session_id, context)
+ else:
+ self._require_access_management(conn, session_id, 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
@@ -582,7 +648,9 @@ class ShowPageStore:
context = _resolve_resource_access_context(user_context)
existing = self.get(session_id)
if existing is not None:
- page = self.require_management(session_id, user_context=context)
+ 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:
@@ -604,7 +672,7 @@ class ShowPageStore:
new_share_id = self._unique_share_id()
now = _utc_now_iso()
with self.engine.begin() as conn:
- self._require_resource_management(conn, session_id, context)
+ self._require_sharing_control(conn, session_id, context)
conn.execute(
update(show_pages)
.where(show_pages.c.session_id == session_id)
@@ -634,7 +702,8 @@ class ShowPageStore:
new_share_id = validate_share_id(share_id)
existing = self.get(session_id)
if existing is not None:
- self.require_management(session_id, user_context=context)
+ 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
@@ -650,7 +719,7 @@ class ShowPageStore:
previous_share_id: str | None = None
try:
with self.engine.begin() as conn:
- self._require_resource_management(conn, session_id, context)
+ 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
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 45f6fba27..00c54b9dd 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -572,6 +572,49 @@ def _policy_allows_management(context: ResourceUserContext, policy: Mapping[str,
)
+def _policy_allows_owner_control(
+ context: ResourceUserContext,
+ policy: Mapping[str, Any] | None,
+) -> bool:
+ """Allow high-impact sharing actions only to the resource owner."""
+
+ if context.is_trusted_local:
+ return True
+ if policy is None:
+ return context.is_instance_owner
+ if not context.can_use_resource(str(policy.get("resource_kind") or "")):
+ return False
+ owner_user_id = _clean_optional_string(policy.get("owner_user_id"))
+ if not (owner_user_id and context.subject and owner_user_id == context.subject):
+ return False
+ organization_id = _clean_optional_string(policy.get("organization_id"))
+ return bool(
+ not organization_id
+ or context.is_active_organization_member
+ and context.organization_id == organization_id
+ )
+
+
+def _policy_allows_show_page_access_management(
+ context: ResourceUserContext,
+ policy: Mapping[str, Any] | None,
+) -> bool:
+ """Allow Show Page owners and Organization managers to narrow access."""
+
+ if _policy_allows_owner_control(context, policy):
+ return True
+ if policy is None or policy.get("resource_kind") != "show_page":
+ return False
+ organization_id = _clean_optional_string(policy.get("organization_id"))
+ return bool(
+ organization_id
+ and context.can_use_resource("show_page")
+ and context.is_active_organization_member
+ and context.organization_id == organization_id
+ and context.organization_role in {"owner", "admin"}
+ ) or _policy_allows_management(context, policy)
+
+
def can_use_resource_policy_snapshot(
user_context: ResourceUserContext | Mapping[str, Any] | None,
policy: Mapping[str, Any] | None,
@@ -639,6 +682,38 @@ def can_manage_resource_acl(
return _policy_allows_management(context, policy)
+def can_manage_show_page_access(
+ user_context: ResourceUserContext | Mapping[str, Any] | None,
+ resource_id: str,
+ *,
+ connection: Connection | None = None,
+) -> bool:
+ """Return whether the caller may manage a Show Page audience or narrow sharing."""
+
+ context = _as_context(user_context)
+ identifier = _required_identifier(resource_id, code="invalid_resource_id")
+ with _connection(connection) as conn:
+ policy = _policy_row(conn, "show_page", identifier)
+ return _policy_allows_show_page_access_management(context, policy)
+
+
+def can_control_resource_sharing(
+ user_context: ResourceUserContext | Mapping[str, Any] | None,
+ resource_kind: str,
+ resource_id: str,
+ *,
+ connection: Connection | None = None,
+) -> bool:
+ """Return whether the resource owner may widen anonymous sharing."""
+
+ context = _as_context(user_context)
+ kind = _validate_resource_kind(resource_kind)
+ identifier = _required_identifier(resource_id, code="invalid_resource_id")
+ with _connection(connection) as conn:
+ policy = _policy_row(conn, kind, identifier)
+ return _policy_allows_owner_control(context, policy)
+
+
def _row_resource_id(row: Any) -> str | None:
keys = ("resource_id", "id", "session_id", "name", "key")
if isinstance(row, Mapping):
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index 30ea61e95..c3d8c0598 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -208,26 +208,38 @@ def test_show_page_scope_without_group_context_fails_closed(monkeypatch, tmp_pat
assert excinfo.value.code == "resource_access_forbidden"
-def test_remote_instance_owner_admin_can_manage_pages_without_use_access(monkeypatch, tmp_path) -> None:
+def test_remote_organization_admin_can_restrict_pages_without_use_access(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
store = _seed_show_pages_with_policies()
admin = _organization_context(
"admin-1",
group_ids=frozenset({"group-sales"}),
organization_role="admin",
- instance_role="owner",
+ instance_role="viewer",
)
+ owner = _organization_context("owner-1", instance_role="owner")
try:
with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
store.require_access("ses-private", user_context=admin)
- private_page = store.update_visibility("ses-private", "public", user_context=admin)
- rotated, previous_share_id = store.rotate_share("ses-private", user_context=admin)
- custom, rotated_share_id = store.set_share_id("ses-private", "admin-link", user_context=admin)
+ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
+ store.update_visibility("ses-private", "public", user_context=admin)
- assert private_page.visibility == "public"
- assert previous_share_id == private_page.share_id
+ public_page = store.update_visibility("ses-private", "public", user_context=owner)
+ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
+ store.rotate_share("ses-private", user_context=admin)
+ with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
+ store.set_share_id("ses-private", "admin-link", user_context=admin)
+ assert store.update_visibility("ses-private", "private", user_context=admin).visibility == "private"
+
+ republished = store.update_visibility("ses-private", "public", user_context=owner)
+ rotated, previous_share_id = store.rotate_share("ses-private", user_context=owner)
+ custom, rotated_share_id = store.set_share_id("ses-private", "owner-link", user_context=owner)
+
+ assert public_page.visibility == "public"
+ assert republished.visibility == "public"
+ assert previous_share_id == republished.share_id
assert rotated_share_id == rotated.share_id
- assert custom.share_id == "admin-link"
+ assert custom.share_id == "owner-link"
with pytest.raises(ShowPageError, match="Show Page access is not permitted"):
store.require_access("ses-scope", user_context=admin)
@@ -236,6 +248,141 @@ def test_remote_instance_owner_admin_can_manage_pages_without_use_access(monkeyp
store.close()
+def test_remote_show_page_owner_can_control_sharing_without_instance_owner_role(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = _seed_show_pages_with_policies()
+ page_owner = _organization_context("owner-1", instance_role="viewer")
+ try:
+ published = store.update_visibility("ses-private", "public", user_context=page_owner)
+ closed = store.update_visibility("ses-private", "private", user_context=page_owner)
+ republished = store.update_visibility("ses-private", "public", user_context=page_owner)
+ rotated, previous_share_id = store.rotate_share("ses-private", user_context=page_owner)
+ customized, rotated_share_id = store.set_share_id(
+ "ses-private",
+ "page-owner-link",
+ user_context=page_owner,
+ )
+
+ assert published.visibility == "public"
+ assert closed.visibility == "private"
+ assert previous_share_id == republished.share_id
+ assert rotated_share_id == rotated.share_id
+ assert customized.share_id == "page-owner-link"
+ finally:
+ store.close()
+
+
+def test_organization_admin_can_read_show_page_access_metadata_without_use_access(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = _seed_show_pages_with_policies()
+ store.close()
+ admin = _organization_context(
+ "admin-1",
+ group_ids=frozenset({"group-sales"}),
+ organization_role="admin",
+ instance_role="viewer",
+ )
+ monkeypatch.setattr(resource_access_service, "resolve_resource_access_context", lambda _value=None: admin)
+
+ payload = api.get_show_page_access("ses-scope")
+
+ assert payload["access_level"] == "scope"
+ assert payload["can_manage"] is True
+ assert payload["can_publish_public"] is False
+
+
+def test_existing_organization_page_is_registered_privately_by_the_instance_owner(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-legacy")
+ page = store.ensure(
+ "ses-legacy",
+ user_context=_organization_context("owner-1", instance_role="owner"),
+ )
+ with store.engine.connect() as connection:
+ policy = resource_access_service.get_resource_policy(
+ "show_page",
+ page.session_id,
+ connection=connection,
+ )
+ assert policy is not None
+ assert policy["organization_id"] == "org-1"
+ assert policy["owner_user_id"] == "owner-1"
+ assert policy["access_level"] == "private"
+ finally:
+ store.close()
+
+
+def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ personal_store = ShowPageStore()
+ try:
+ personal_store.ensure("ses-personal")
+ finally:
+ personal_store.close()
+
+ personal = app.test_client().get("/api/show-pages/ses-personal/access")
+ assert personal.status_code == 200
+ assert personal.get_json() == {
+ "ok": True,
+ "mode": "personal",
+ "instance_id": None,
+ "organization_id": None,
+ "access_level": "private",
+ "group_ids": [],
+ "policy_revision": None,
+ "last_applied_control_plane_revision": None,
+ "can_manage": True,
+ "can_publish_public": True,
+ "public_link_enabled": False,
+ }
+
+ config = _save_config(tmp_path)
+ store = ShowPageStore()
+ try:
+ store.ensure("ses-organization")
+ with store.engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="show_page",
+ resource_id="ses-organization",
+ organization_id="org-1",
+ owner_user_id="owner-1",
+ access_level="scope",
+ group_ids=["group-engineering"],
+ policy_revision=4,
+ last_applied_control_plane_revision=4,
+ )
+ finally:
+ store.close()
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(config, subject="owner-1", groups=["group-engineering"], instance_role="owner"),
+ domain="alex.avibe.bot",
+ )
+ organization = client.get(
+ "/api/show-pages/ses-organization/access",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ assert organization.status_code == 200
+ assert organization.get_json() == {
+ "ok": True,
+ "mode": "organization",
+ "instance_id": "inst_123",
+ "organization_id": "org-1",
+ "access_level": "scope",
+ "group_ids": ["group-engineering"],
+ "policy_revision": 4,
+ "last_applied_control_plane_revision": 4,
+ "can_manage": True,
+ "can_publish_public": True,
+ "public_link_enabled": False,
+ }
+
+
def test_remote_dock_filters_private_pins_and_authorizes_mutations(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index 9af9f24e0..5b38ed3da 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -1,18 +1,22 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, Copy, LayoutGrid, Loader2, Plus, Share2 } from 'lucide-react';
+import { Check, Copy, LayoutGrid, Loader2, Plus, RotateCw, Share2 } from 'lucide-react';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
-import { Select } from '../ui/select';
import { Switch } from '../ui/switch';
import { useApi } from '../../context/ApiContext';
import { showDockId, useDock } from '../../context/DockContext';
import { copyTextToClipboard } from '../../lib/utils';
import { isIosDevice, isRealMobileSafari, isStandalonePwa } from '../../lib/platform';
import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';
+import {
+ canChangeShowPagePublicLink,
+ type ShowPageAccess,
+} from '../../lib/showPageAccess';
import { ShowPageShareIdField } from './ShowPageShareIdField';
+import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
import { useShowPageInventory, type ShowPage } from '../useShowPages';
type ShowPagePayload = ShowPageLinkInfo & {
@@ -25,8 +29,8 @@ type ShowPagePayload = ShowPageLinkInfo & {
};
// Share affordance shown only while the Show Page is open (the in-chat view).
-// A popover with the page link (copy + native share) and a public/private
-// toggle that flips visibility in place via the existing show-pages API.
+// A popover with authenticated audience controls, an independent anonymous
+// public-link switch, and link actions for the current serving route.
export const ShowPageShareControl: React.FC<{
sessionId: string;
// Lets the chat view re-point the iframe at the route that now serves the
@@ -64,6 +68,9 @@ export const ShowPageShareControl: React.FC<{
: { ...inventoryPage, ...local }) as ShowPagePayload;
}, [inventoryPage, localPayload, sessionId]);
const [loading, setLoading] = useState(false);
+ const [accessLoading, setAccessLoading] = useState(false);
+ const [access, setAccess] = useState<ShowPageAccess | null>(null);
+ const [accessError, setAccessError] = useState(false);
const [busy, setBusy] = useState(false);
const [copied, setCopied] = useState(false);
// A visibility mutation is authoritative: it always applies its result and
@@ -96,6 +103,11 @@ export const ShowPageShareControl: React.FC<{
// view would keep the iframe inert (pointer-events:none) on the next Show Page.
useEffect(() => () => onOpenChange?.(false), [onOpenChange]);
+ useEffect(() => {
+ setAccess(null);
+ setAccessError(false);
+ }, [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
@@ -118,15 +130,32 @@ export const ShowPageShareControl: React.FC<{
const refresh = () => {
const seq = ++reqSeq.current;
setLoading(!payload);
- api
- .ensureShowPage(sessionId)
- .then((res: ShowPagePayload) => {
+ setAccessLoading(!access);
+ setAccessError(false);
+ void (async () => {
+ try {
+ const res: ShowPagePayload = await api.ensureShowPage(sessionId);
if (seq !== reqSeq.current) return;
applyPayload(res);
if (!inventoryPage) reload();
- })
- .catch(() => undefined)
- .finally(() => setLoading(false));
+ } catch {
+ // An archived Show Page cannot be ensured, but its applied access
+ // metadata is still useful and is loaded below.
+ } finally {
+ setLoading(false);
+ }
+
+ try {
+ const nextAccess = await api.getShowPageAccess(sessionId);
+ if (seq !== reqSeq.current) return;
+ setAccess(nextAccess);
+ } catch {
+ if (seq !== reqSeq.current) return;
+ setAccessError(true);
+ } finally {
+ setAccessLoading(false);
+ }
+ })();
};
const handleOpenChange = (next: boolean) => {
@@ -142,6 +171,22 @@ export const ShowPageShareControl: React.FC<{
.then((res: ShowPagePayload) => {
// Authoritative server state: always apply it, and invalidate any
// in-flight refresh read so a stale read can't revert us afterwards.
+ applyPayload(res);
+ setAccess((current) => current ? {
+ ...current,
+ public_link_enabled: next === 'public',
+ } : current);
+ reqSeq.current += 1;
+ })
+ .catch(() => undefined)
+ .finally(() => setBusy(false));
+ };
+
+ const rotatePublicLink = () => {
+ setBusy(true);
+ api
+ .rotateShowPageShare(sessionId)
+ .then((res: ShowPagePayload) => {
applyPayload(res);
reqSeq.current += 1;
})
@@ -190,73 +235,114 @@ export const ShowPageShareControl: React.FC<{
</div>
) : !payload ? (
<p className="py-1 text-sm text-muted">{t('chat.showPage.loadError')}</p>
- ) : 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 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>
- {canNativeShare && (
+ {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={nativeShare}
- aria-label={t('chat.showPage.nativeShare')}
- title={t('chat.showPage.nativeShare')}
+ onClick={copyLink}
+ aria-label={t('chat.showPage.copyLink')}
+ title={t('chat.showPage.copyLink')}
>
- <Share2 className="size-3.5" />
+ {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>
+ )}
+
+ <div className="border-t border-border pt-3">
+ <ShowPageWorkspaceAccessControl
+ access={access}
+ active={open}
+ sessionId={sessionId}
+ />
+ {accessError ? (
+ <p className="mt-2 text-[11px] leading-snug text-destructive">
+ {t('chat.showPage.accessLoadError')}
+ </p>
+ ) : null}
</div>
- <div>
+ <div className="border-t border-border pt-3">
<div className="flex items-center justify-between gap-3">
- <span className="text-sm">{t('chat.showPage.access')}</span>
- <Select
- value={isPublic ? 'public' : 'private'}
- disabled={busy}
- onChange={(e) => setVisibilityTo(e.target.value)}
- wrapperClassName="w-auto"
- className="h-8 text-sm"
- aria-label={t('chat.showPage.access')}
- >
- <option value="private">{t('chat.showPage.visibilityPrivate')}</option>
- <option value="public">{t('chat.showPage.visibilityPublic')}</option>
- </Select>
+ <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>
- <p className="mt-1.5 text-xs text-muted">
- {isPublic ? t('chat.showPage.publicDesc') : t('chat.showPage.privateDesc')}
- </p>
+ {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}
</div>
- {payload && isPublic && (
+ {isPublic && !offline ? (
<div>
<div className="mb-1.5 text-sm">{t('chat.showPage.customLink')}</div>
<ShowPageShareIdField
sessionId={sessionId}
shareId={payload.share_id}
- disabled={busy}
+ disabled={busy || !access?.can_publish_public}
onSaved={(res) => {
// Authoritative server state, same handling as a visibility
// change: apply it and invalidate any in-flight refresh read.
@@ -265,15 +351,15 @@ export const ShowPageShareControl: React.FC<{
}}
/>
</div>
- )}
+ ) : null}
- {payload && isPublic && !payload.url_available && (
+ {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 && (
+ {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" />
@@ -301,7 +387,7 @@ export const ShowPageShareControl: React.FC<{
</a>
)}
</div>
- )}
+ ) : null}
</>
)}
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
new file mode 100644
index 000000000..5415605cd
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -0,0 +1,61 @@
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ShowPageAccess } from '@/lib/showPageAccess';
+import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
+ ok: true,
+ mode: 'organization',
+ instance_id: 'inst-1',
+ organization_id: 'org-1',
+ access_level: 'private',
+ group_ids: [],
+ policy_revision: 4,
+ last_applied_control_plane_revision: 4,
+ can_manage: true,
+ can_publish_public: true,
+ public_link_enabled: false,
+ ...overrides,
+});
+
+const renderControl = (value: ShowPageAccess) => renderToStaticMarkup(
+ <ShowPageWorkspaceAccessControl access={value} active={false} sessionId="session-1" />,
+);
+
+describe('ShowPageWorkspaceAccessControl', () => {
+ it('renders Personal as a fixed Private audience without Organization choices', () => {
+ const html = renderControl(access({
+ mode: 'personal',
+ instance_id: null,
+ organization_id: null,
+ policy_revision: null,
+ last_applied_control_plane_revision: null,
+ }));
+
+ expect(html).toContain('chat.showPage.workspaceLevels.private');
+ expect(html).not.toContain('chat.showPage.workspaceLevels.public');
+ expect(html).not.toContain('chat.showPage.workspaceLevels.scope');
+ expect(html).not.toContain('<select');
+ });
+
+ it('renders all Organization audiences and keeps the public wire value labeled as Organization', () => {
+ const html = renderControl(access({ access_level: 'public' }));
+
+ expect(html).toContain('value="private"');
+ expect(html).toContain('value="public" selected=""');
+ expect(html).toContain('value="scope"');
+ expect(html).toContain('chat.showPage.workspaceLevels.public');
+ });
+
+ it('keeps the Organization audience read-only for a non-owner viewer', () => {
+ const html = renderControl(access({ can_manage: false, can_publish_public: false }));
+
+ expect(html).toContain('<select disabled=""');
+ expect(html).toContain('chat.showPage.workspaceReadOnly');
+ });
+});
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
new file mode 100644
index 000000000..af0763b89
--- /dev/null
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -0,0 +1,378 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import clsx from 'clsx';
+import {
+ Building2,
+ CloudOff,
+ Loader2,
+ LockKeyhole,
+ LogIn,
+ RefreshCw,
+ TriangleAlert,
+ Users,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Select } from '@/components/ui/select';
+import {
+ isRevisionConflict,
+ jsonBody,
+ OrganizationApiError,
+ organizationRequest,
+} from '@/features/organization/api/client';
+import type {
+ CloudManagementSession,
+ OrganizationGroup,
+ OrganizationResource,
+ ResourceAccessLevel,
+} from '@/features/organization/api/types';
+import { organizationAuthorizationReturnPath } from '@/features/organization/policy';
+import {
+ buildShowPageAccessPatch,
+ showPageAudienceLabelKey,
+ showPageAudienceLevels,
+ showPageSyncPresentation,
+ type ShowPageAccess,
+} from '@/lib/showPageAccess';
+
+type ManagementGate =
+ | 'idle'
+ | 'loading'
+ | 'authorization_required'
+ | 'cloud_not_connected'
+ | 'subject_mismatch'
+ | 'ready'
+ | 'conflict'
+ | 'unreachable'
+ | 'error';
+
+type ResourceResponse = { resource: OrganizationResource };
+
+const LEVEL_ICONS = {
+ private: LockKeyhole,
+ public: Building2,
+ scope: Users,
+} satisfies Record<ResourceAccessLevel, typeof LockKeyhole>;
+
+function gateForError(error: unknown): ManagementGate {
+ if (!(error instanceof OrganizationApiError)) return 'unreachable';
+ if (error.code === 'cloud_management_subject_mismatch') return 'subject_mismatch';
+ if (error.status === 401) return 'authorization_required';
+ if (error.status === 409 && error.code === 'cloud_management_not_connected') {
+ return 'cloud_not_connected';
+ }
+ if (error.retryable || error.status >= 500) return 'unreachable';
+ return 'error';
+}
+
+function sessionGate(session: CloudManagementSession): ManagementGate {
+ if (session.connected) return 'ready';
+ return session.state;
+}
+
+export function ShowPageWorkspaceAccessControl({
+ access,
+ active,
+ sessionId,
+}: {
+ access: ShowPageAccess | null;
+ active: boolean;
+ sessionId: string;
+}) {
+ const { t } = useTranslation();
+ const [gate, setGate] = useState<ManagementGate>('idle');
+ const [resource, setResource] = useState<OrganizationResource | null>(null);
+ const [groups, setGroups] = useState<OrganizationGroup[]>([]);
+ const [level, setLevel] = useState<ResourceAccessLevel>(access?.access_level ?? 'private');
+ const [groupIds, setGroupIds] = useState<string[]>(access?.group_ids ?? []);
+ const [saving, setSaving] = useState(false);
+ const generationRef = useRef(0);
+
+ const organizationId = access?.organization_id ?? null;
+ const instanceId = access?.instance_id ?? null;
+ const canManage = access?.can_manage === true;
+
+ const accessPath = useMemo(() => {
+ if (!organizationId || !instanceId) return null;
+ return `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/resources/${encodeURIComponent(instanceId)}/show_page/${encodeURIComponent(sessionId)}/access`;
+ }, [instanceId, organizationId, sessionId]);
+
+ const loadManagement = useCallback(async () => {
+ if (!access || access.mode !== 'organization' || !canManage || !organizationId || !accessPath) {
+ return;
+ }
+ const generation = ++generationRef.current;
+ setGate('loading');
+ try {
+ const session = await organizationRequest<CloudManagementSession>('/api/cloud-management/session');
+ if (generation !== generationRef.current) return;
+ const nextGate = sessionGate(session);
+ if (!session.connected) {
+ setGate(nextGate);
+ setResource(null);
+ setGroups([]);
+ return;
+ }
+ const [resourceResult, groupResult] = await Promise.all([
+ organizationRequest<ResourceResponse>(accessPath),
+ organizationRequest<{ groups: OrganizationGroup[] }>(
+ `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,
+ ),
+ ]);
+ if (generation !== generationRef.current) return;
+ const nextResource = resourceResult.resource;
+ setResource(nextResource);
+ setGroups(groupResult.groups);
+ setLevel(nextResource.access?.access_level ?? access.access_level);
+ setGroupIds(nextResource.access?.group_ids ?? access.group_ids);
+ setGate('ready');
+ } catch (error) {
+ if (generation !== generationRef.current) return;
+ setGate(gateForError(error));
+ }
+ }, [access, accessPath, canManage, organizationId]);
+
+ useEffect(() => {
+ generationRef.current += 1;
+ setResource(null);
+ setGroups([]);
+ setLevel(access?.access_level ?? 'private');
+ setGroupIds(access?.group_ids ?? []);
+ setGate('idle');
+ if (active && access?.mode === 'organization' && access.can_manage) {
+ void loadManagement();
+ }
+ return () => {
+ generationRef.current += 1;
+ };
+ }, [access, active, loadManagement]);
+
+ const visibleGroups = groups.filter((group) => !group.archived_at || groupIds.includes(group.id));
+ const toggleGroup = (group: OrganizationGroup) => {
+ const selected = groupIds.includes(group.id);
+ if (group.archived_at && !selected) return;
+ setGroupIds((current) => selected
+ ? current.filter((id) => id !== group.id)
+ : [...current, group.id]);
+ };
+
+ const currentLevel = resource?.access?.access_level ?? access?.access_level ?? 'private';
+ const currentGroupIds = resource?.access?.group_ids ?? access?.group_ids ?? [];
+ const revision = resource?.access?.revision ?? access?.policy_revision ?? null;
+ const patch = revision === null ? null : buildShowPageAccessPatch(level, groupIds, revision);
+ const normalizedCurrentGroups = currentLevel === 'scope' ? [...currentGroupIds].sort() : [];
+ const normalizedDraftGroups = patch?.group_ids ? [...patch.group_ids].sort() : [];
+ const dirty = Boolean(
+ patch
+ && (level !== currentLevel
+ || normalizedCurrentGroups.join('\u0000') !== normalizedDraftGroups.join('\u0000')),
+ );
+ const editable = access?.mode === 'organization' && canManage && gate === 'ready' && !saving;
+
+ const save = async () => {
+ if (!accessPath || !patch || !dirty || !editable) return;
+ setSaving(true);
+ try {
+ const result = await organizationRequest<ResourceResponse>(accessPath, {
+ method: 'PATCH',
+ body: jsonBody(patch),
+ });
+ setResource(result.resource);
+ setLevel(result.resource.access?.access_level ?? level);
+ setGroupIds(result.resource.access?.group_ids ?? []);
+ setGate('ready');
+ } catch (error) {
+ setGate(isRevisionConflict(error) ? 'conflict' : gateForError(error));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const startAuthorization = async () => {
+ setGate('loading');
+ try {
+ const result = await organizationRequest<{ authorize_url: string }>(
+ '/api/cloud-management/session/start',
+ {
+ method: 'POST',
+ body: jsonBody({
+ mode: 'interactive',
+ next: organizationAuthorizationReturnPath(
+ window.location.pathname,
+ window.location.search,
+ ),
+ }),
+ },
+ );
+ window.location.assign(result.authorize_url);
+ } catch (error) {
+ setGate(gateForError(error));
+ }
+ };
+
+ const LevelIcon = LEVEL_ICONS[level];
+ const syncPresentation = resource ? showPageSyncPresentation(resource.sync.status) : null;
+
+ return (
+ <section className="space-y-2.5" aria-label={t('chat.showPage.workspaceAccess')}>
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-sm font-medium">{t('chat.showPage.workspaceAccess')}</div>
+ <div className="mt-0.5 text-[11px] leading-snug text-muted">
+ {t('chat.showPage.workspaceAccessDesc')}
+ </div>
+ </div>
+ {!access ? (
+ <Loader2 className="size-4 shrink-0 animate-spin text-muted" />
+ ) : access.mode === 'personal' ? (
+ <span className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 text-xs">
+ <LockKeyhole className="size-3.5 text-muted" />
+ {t(showPageAudienceLabelKey('private'))}
+ </span>
+ ) : (
+ <Select
+ value={level}
+ disabled={!editable}
+ onChange={(event) => setLevel(event.target.value as ResourceAccessLevel)}
+ wrapperClassName="w-[148px] shrink-0"
+ className="h-8 text-xs"
+ aria-label={t('chat.showPage.workspaceAccess')}
+ >
+ {showPageAudienceLevels('organization').map((candidate) => (
+ <option key={candidate} value={candidate}>
+ {t(showPageAudienceLabelKey(candidate))}
+ </option>
+ ))}
+ </Select>
+ )}
+ </div>
+
+ {access?.mode === 'organization' ? (
+ <div className="flex items-start gap-2 text-[11px] leading-snug text-muted">
+ <LevelIcon className="mt-0.5 size-3.5 shrink-0" />
+ <span>{t(`chat.showPage.workspaceHelp.${level}`)}</span>
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && level === 'scope' && gate === 'ready' ? (
+ <fieldset>
+ <legend className="mb-1.5 text-[11px] font-medium">
+ {t('chat.showPage.selectedGroups')}
+ </legend>
+ <div className="max-h-36 space-y-0.5 overflow-y-auto rounded-md border border-border p-1">
+ {visibleGroups.map((group) => {
+ const selected = groupIds.includes(group.id);
+ const disabled = !editable || Boolean(group.archived_at && !selected);
+ return (
+ <button
+ key={group.id}
+ type="button"
+ role="checkbox"
+ aria-checked={selected}
+ disabled={disabled}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded px-1.5 py-1.5 text-left text-xs',
+ disabled ? 'cursor-not-allowed opacity-60' : 'hover:bg-foreground/[0.04]',
+ )}
+ onClick={() => toggleGroup(group)}
+ >
+ <Checkbox checked={selected} presentational />
+ <span className="min-w-0 flex-1 truncate">{group.name}</span>
+ {group.archived_at ? (
+ <span className="text-[10px] text-muted">{t('chat.showPage.archivedGroup')}</span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ {!patch ? (
+ <p className="mt-1.5 text-[11px] text-gold">{t('chat.showPage.groupRequired')}</p>
+ ) : null}
+ </fieldset>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && gate === 'loading' ? (
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t('chat.showPage.loadingWorkspaceAccess')}
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && gate === 'authorization_required' ? (
+ <div className="flex items-center justify-between gap-2 border-t border-border pt-2">
+ <span className="text-[11px] leading-snug text-muted">
+ {t('chat.showPage.organizationSignInDesc')}
+ </span>
+ <Button type="button" size="sm" variant="outline" className="h-7 shrink-0" onClick={() => void startAuthorization()}>
+ <LogIn className="size-3.5" />
+ {t('chat.showPage.organizationSignIn')}
+ </Button>
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && gate === 'cloud_not_connected' ? (
+ <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.organizationUnavailable')}
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && gate === 'subject_mismatch' ? (
+ <div className="flex items-start gap-1.5 text-[11px] leading-snug text-destructive">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
+ {t('chat.showPage.organizationSubjectMismatch')}
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && ['conflict', 'unreachable', '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">
+ {t(`chat.showPage.workspaceErrors.${gate}`)}
+ </span>
+ <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0" onClick={() => void loadManagement()} aria-label={t('common.retry')} title={t('common.retry')}>
+ <RefreshCw className="size-3.5" />
+ </Button>
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && !canManage ? (
+ <p className="text-[11px] leading-snug text-muted">
+ {t('chat.showPage.workspaceReadOnly')}
+ </p>
+ ) : null}
+
+ {syncPresentation ? (
+ <div
+ className={clsx(
+ 'flex items-center gap-1.5 text-[11px] leading-snug',
+ syncPresentation.tone === 'error' ? 'text-destructive' : 'text-gold',
+ )}
+ >
+ {syncPresentation.tone === 'error' ? (
+ <TriangleAlert className="size-3.5 shrink-0" />
+ ) : (
+ <Loader2 className="size-3.5 shrink-0 animate-spin" />
+ )}
+ {t(syncPresentation.key)}
+ </div>
+ ) : null}
+
+ {access?.mode === 'organization' && canManage && gate === 'ready' ? (
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={!dirty || !patch || saving}
+ onClick={() => void save()}
+ >
+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : null}
+ {t('chat.showPage.applyWorkspaceAccess')}
+ </Button>
+ </div>
+ ) : null}
+ </section>
+ );
+}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ddbdf8af7..497f31ad5 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -7,6 +7,7 @@ import type { TurnActivityGroupWire } from '../lib/agentActivity';
import type { AgentGraphParams, AgentGraphResult, AgentGraphVisibility } from '../lib/agentGraph';
import { visibilityActivityEvents } from '../lib/sessionVisibilityEvents';
import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';
+import type { ShowPageAccess } from '../lib/showPageAccess';
import {
WorkbenchEventReconnectLoop,
type WorkbenchEventConnectionState,
@@ -15,6 +16,7 @@ import type { DockDoc } from './DockContext';
import { normalizeSessionInfo, type InstanceCapabilities, type SessionInfo } from '../lib/sessionInfo';
export type { InstanceCapabilities, SessionInfo };
+export type { ShowPageAccess };
// The workbench Dock API response shape ({ ok, dock }); the Dock document type
// itself lives with the DockProvider that owns reconciliation.
@@ -409,6 +411,7 @@ export type ApiContextType = {
toggleAdmin: (userId: string, isAdmin: boolean, platform?: string) => Promise<any>;
removeUser: (userId: string, platform?: string) => Promise<any>;
getShowPages: () => Promise<any>;
+ getShowPageAccess: (sessionId: string) => Promise<ShowPageAccess>;
getWebPushStatus: (payload?: WebPushStatusPayload) => Promise<WebPushStatus>;
getWebPushVapidPublicKey: () => Promise<{ ok: boolean; public_key: string }>;
subscribeWebPush: (
@@ -2539,6 +2542,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
removeUser: (userId, platform) =>
deleteJson(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`),
getShowPages: () => getJson('/api/show-pages'),
+ getShowPageAccess: (sessionId) => getJson(`/api/show-pages/${encodeURIComponent(sessionId)}/access`),
getWebPushStatus: (payload) =>
payload ? postJson('/api/web-push/status', payload) : getJson('/api/web-push/status'),
getWebPushVapidPublicKey: () => getJson('/api/web-push/vapid-public-key'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index bb9c2c889..00842b45e 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2750,11 +2750,50 @@
"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",
+ "workspaceAccess": "Workspace access",
+ "workspaceAccessDesc": "Who can open this page after signing in.",
+ "workspaceLevels": {
+ "private": "Private",
+ "public": "Organization",
+ "scope": "Selected groups"
+ },
+ "workspaceHelp": {
+ "private": "Only the Show Page owner can open it through this access rule.",
+ "public": "All active Organization members 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",
+ "archivedGroup": "Archived",
+ "groupRequired": "Select at least one group.",
+ "applyWorkspaceAccess": "Apply",
+ "loadingWorkspaceAccess": "Loading Organization access…",
+ "workspaceReadOnly": "Only the Show Page owner or an Organization manager can change this audience.",
+ "organizationSignIn": "Sign in",
+ "organizationSignInDesc": "Sign in to avibe.bot to change the Organization audience.",
+ "organizationUnavailable": "This Avibe is not connected to avibe.bot Organization management.",
+ "organizationSubjectMismatch": "The signed-in avibe.bot account does not match this Avibe session.",
+ "workspaceErrors": {
+ "conflict": "This audience changed elsewhere. Reload the latest version.",
+ "unreachable": "Organization access is temporarily unavailable.",
+ "error": "Organization access could not be loaded."
+ },
+ "workspaceSync": {
+ "pending": "This audience change is waiting to be applied on this Avibe.",
+ "offline": "This Avibe is offline. The audience change will apply after it reconnects.",
+ "error": "This Avibe could not apply the audience change."
+ },
+ "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.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 53cef1e8d..7539647d7 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2750,11 +2750,50 @@
"shareTitle": "分享这个 Show Page",
"copyLink": "复制链接",
"nativeShare": "系统分享",
+ "rotateLink": "更换公开链接",
"access": "权限",
"visibilityPublic": "公开",
"visibilityPrivate": "私有",
"publicDesc": "任何人都可以通过链接查看",
"privateDesc": "只有你能查看",
+ "workspaceAccess": "登录访问范围",
+ "workspaceAccessDesc": "控制登录后哪些人可以打开此页面。",
+ "workspaceLevels": {
+ "private": "私有",
+ "public": "组织",
+ "scope": "指定群组"
+ },
+ "workspaceHelp": {
+ "private": "此规则下只有页面所有者可以打开。",
+ "public": "组织内所有活跃成员均可打开,同时仍受 Avibe 和项目权限限制。",
+ "scope": "只有指定群组的活跃成员可以打开,同时仍受 Avibe 和项目权限限制。"
+ },
+ "selectedGroups": "指定群组",
+ "archivedGroup": "已归档",
+ "groupRequired": "至少选择一个群组。",
+ "applyWorkspaceAccess": "应用",
+ "loadingWorkspaceAccess": "正在加载组织权限…",
+ "workspaceReadOnly": "只有页面所有者或组织管理者可以修改此访问范围。",
+ "organizationSignIn": "登录",
+ "organizationSignInDesc": "登录 avibe.bot 后才能修改组织访问范围。",
+ "organizationUnavailable": "当前 Avibe 尚未连接 avibe.bot 的组织管理功能。",
+ "organizationSubjectMismatch": "当前登录的 avibe.bot 账号与此 Avibe 会话不一致。",
+ "workspaceErrors": {
+ "conflict": "访问范围已在其他位置更新,请重新加载最新版本。",
+ "unreachable": "组织权限暂时不可用。",
+ "error": "无法加载组织权限。"
+ },
+ "workspaceSync": {
+ "pending": "访问范围变更正在等待应用到当前 Avibe。",
+ "offline": "当前 Avibe 已离线,重新连接后会应用访问范围变更。",
+ "error": "当前 Avibe 无法应用访问范围变更。"
+ },
+ "accessLoadError": "无法加载权限详情,分享设置已停用。",
+ "publicLink": "公开链接",
+ "publicLinkOnDesc": "任何人都可以通过链接直接打开,无需登录。",
+ "publicLinkOffDesc": "匿名访问已关闭;登录后的访问范围由上方设置控制。",
+ "publicLinkOwnerOnly": "只有页面所有者可以更换、自定义或重新开启此链接。",
+ "publicLinkOffline": "此页面离线期间无法修改公开链接。",
"customLink": "自定义链接",
"offlineNote": "这个 Show Page 已离线,暂时无法分享。",
"publicUnavailable": "连接 Avibe Cloud 后才能获得别人可打开的公开链接。",
diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.ts
new file mode 100644
index 000000000..2a534b12d
--- /dev/null
+++ b/ui/src/lib/showPageAccess.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from 'vitest';
+
+import { isRevisionConflict, OrganizationApiError } from '@/features/organization/api/client';
+import {
+ buildShowPageAccessPatch,
+ canChangeShowPagePublicLink,
+ showPageAudienceLabelKey,
+ showPageAudienceLevels,
+ showPageSyncPresentation,
+ type ShowPageAccess,
+} from './showPageAccess';
+
+const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({
+ ok: true,
+ mode: 'organization',
+ instance_id: 'inst-1',
+ organization_id: 'org-1',
+ access_level: 'private',
+ group_ids: [],
+ policy_revision: 4,
+ last_applied_control_plane_revision: 4,
+ can_manage: true,
+ can_publish_public: true,
+ public_link_enabled: false,
+ ...overrides,
+});
+
+describe('Show Page access policy helpers', () => {
+ it('keeps Personal authenticated access private', () => {
+ expect(showPageAudienceLevels('personal')).toEqual(['private']);
+ });
+
+ it('offers all three Organization audiences', () => {
+ expect(showPageAudienceLevels('organization')).toEqual(['private', 'public', 'scope']);
+ });
+
+ it('presents the public wire value as Organization access', () => {
+ expect(showPageAudienceLabelKey('public')).toBe('chat.showPage.workspaceLevels.public');
+ });
+
+ it('requires at least one group for scoped access and normalizes duplicates', () => {
+ expect(buildShowPageAccessPatch('scope', [], 4)).toBeNull();
+ expect(buildShowPageAccessPatch('scope', ['group-1', ' group-1 ', 'group-2'], 4)).toEqual({
+ access_level: 'scope',
+ group_ids: ['group-1', 'group-2'],
+ if_match_revision: 4,
+ });
+ });
+
+ it('keeps Public link 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('distinguishes pending, offline, and error sync states', () => {
+ expect(showPageSyncPresentation('pending')).toEqual({
+ key: 'chat.showPage.workspaceSync.pending',
+ tone: 'pending',
+ });
+ expect(showPageSyncPresentation('offline')).toEqual({
+ key: 'chat.showPage.workspaceSync.offline',
+ tone: 'pending',
+ });
+ expect(showPageSyncPresentation('error')).toEqual({
+ key: 'chat.showPage.workspaceSync.error',
+ tone: 'error',
+ });
+ });
+
+ it('recognizes a Resource revision conflict without treating generic errors as conflicts', () => {
+ expect(isRevisionConflict(new OrganizationApiError(409, {
+ error: 'resource_sync_conflict',
+ current_revision: 5,
+ }))).toBe(true);
+ expect(isRevisionConflict(new OrganizationApiError(502, {
+ error: 'cloud_management_unavailable',
+ retryable: true,
+ }))).toBe(false);
+ });
+});
diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.ts
new file mode 100644
index 000000000..10e96f693
--- /dev/null
+++ b/ui/src/lib/showPageAccess.ts
@@ -0,0 +1,69 @@
+import type { ResourceAccessLevel, SyncStatus } from '@/features/organization/api/types';
+
+export type ShowPageAccess = {
+ ok: true;
+ mode: 'personal' | 'organization';
+ instance_id: string | null;
+ organization_id: string | null;
+ access_level: ResourceAccessLevel;
+ group_ids: string[];
+ policy_revision: number | null;
+ last_applied_control_plane_revision: number | null;
+ can_manage: boolean;
+ can_publish_public: boolean;
+ public_link_enabled: boolean;
+};
+
+export type ShowPageAccessPatch = {
+ access_level: ResourceAccessLevel;
+ group_ids: string[];
+ if_match_revision: number;
+};
+
+export const showPageAudienceLevels = (
+ mode: ShowPageAccess['mode'],
+): ResourceAccessLevel[] => (
+ mode === 'organization' ? ['private', 'public', 'scope'] : ['private']
+);
+
+export const showPageAudienceLabelKey = (level: ResourceAccessLevel): string => (
+ `chat.showPage.workspaceLevels.${level}`
+);
+
+export function buildShowPageAccessPatch(
+ level: ResourceAccessLevel,
+ groupIds: string[],
+ revision: number,
+): ShowPageAccessPatch | null {
+ const normalizedGroupIds = level === 'scope'
+ ? [...new Set(groupIds.map((id) => id.trim()).filter(Boolean))]
+ : [];
+ if (level === 'scope' && normalizedGroupIds.length === 0) return null;
+ return {
+ access_level: level,
+ group_ids: normalizedGroupIds,
+ if_match_revision: revision,
+ };
+}
+
+export function canChangeShowPagePublicLink(
+ access: ShowPageAccess | null,
+ nextEnabled: boolean,
+): boolean {
+ if (!access) return false;
+ return nextEnabled ? access.can_publish_public : access.can_manage;
+}
+
+export function showPageSyncPresentation(status: SyncStatus): {
+ key: string;
+ tone: 'muted' | 'pending' | 'error';
+} | null {
+ if (status === 'in_sync' || status === 'none' || status === 'deleted') return null;
+ if (status === 'error') {
+ return { key: 'chat.showPage.workspaceSync.error', tone: 'error' };
+ }
+ if (status === 'offline') {
+ return { key: 'chat.showPage.workspaceSync.offline', tone: 'pending' };
+ }
+ return { key: 'chat.showPage.workspaceSync.pending', tone: 'pending' };
+}
diff --git a/vibe/api.py b/vibe/api.py
index 48eb88211..46b7e97b3 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1229,6 +1229,64 @@ def ensure_show_page(session_id: str) -> dict:
return {"ok": True, "existed": not created, **_apply_session_meta([payload])[0]}
+def get_show_page_access(session_id: str) -> dict:
+ """Return the applied authenticated audience and sharing authority."""
+
+ from core.show_pages import ShowPageError, ShowPageStore
+ from storage import resource_access_service
+
+ context = resource_access_service.resolve_resource_access_context()
+ store = ShowPageStore()
+ try:
+ page = store.get(session_id)
+ if page is None:
+ raise ShowPageError("This session has no Show Page.", code="show_page_not_found")
+ with store.engine.connect() as connection:
+ policy = resource_access_service.get_resource_policy(
+ "show_page",
+ page.session_id,
+ connection=connection,
+ )
+ can_use = resource_access_service.can_use_resource(
+ context,
+ "show_page",
+ page.session_id,
+ connection=connection,
+ )
+ can_manage = resource_access_service.can_manage_show_page_access(
+ context,
+ page.session_id,
+ connection=connection,
+ )
+ can_publish_public = resource_access_service.can_control_resource_sharing(
+ context,
+ "show_page",
+ page.session_id,
+ connection=connection,
+ )
+ if not (can_use or can_manage):
+ raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")
+ finally:
+ store.close()
+
+ organization_id = policy.get("organization_id") if policy else None
+ return {
+ "ok": True,
+ "mode": "organization" if organization_id else "personal",
+ "instance_id": context.instance_id,
+ "organization_id": organization_id,
+ "access_level": policy.get("access_level", "private") if policy else "private",
+ "group_ids": list(policy.get("group_ids") or []) if policy else [],
+ "policy_revision": policy.get("policy_revision") if policy else None,
+ "last_applied_control_plane_revision": (
+ policy.get("last_applied_control_plane_revision") if policy else None
+ ),
+ "can_manage": can_manage,
+ "can_publish_public": can_publish_public,
+ "public_link_enabled": page.visibility == "public",
+ }
+
+
def rotate_show_page_share(session_id: str) -> dict:
"""Revoke the current public link and issue a new one (public pages only)."""
from core.show_pages import ShowPageStore, show_page_payload
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 97f0fdc42..1068629ba 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -278,6 +278,7 @@ _VIEWER_HTTP_RULES = tuple(
r"^/api/org/(?:context|groups)$",
r"^/api/resource-policies$",
r"^/api/show-pages$",
+ r"^/api/show-pages/[^/]+/access$",
r"^/api/show-pages/[^/]+/icon$",
)
)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d82d656ce..135214344 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4394,6 +4394,20 @@ def show_page_ensure_post(session_id):
return _show_page_error_response(exc)
[email protected]("/api/show-pages/<session_id>/access", methods=["GET"])
+def show_page_access_get(session_id):
+ from core.show_pages import ShowPageError
+ from vibe import api
+
+ try:
+ response = jsonify(api.get_show_page_access(session_id))
+ response.headers["Cache-Control"] = "no-store, private"
+ response.headers["Vary"] = "Cookie"
+ return response
+ except ShowPageError as exc:
+ return _show_page_error_response(exc)
+
+
@app.route("/api/show-pages/<session_id>/rotate-share", methods=["POST"])
def show_page_rotate_share_post(session_id):
from core.show_pages import ShowPageError