Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(show-pages): add workspace access controls
Maxff8c5d24d0c3
diff --git a/core/show_pages.py b/core/show_pages.pyindex 8c4c1bc3a..655fa5868 100644--- a/core/show_pages.py+++ b/core/show_pages.py@@ -759,26 +759,66 @@ class ShowPageStore:raise ShowPageError("Show Page access is not permitted.", code="resource_access_forbidden")@staticmethod- def _register_created_resource_policy(connection, session_id: str, user_context: Any) -> None:+ def _resolve_instance_ownership() -> dict[str, Any]:+ from vibe import permissions++ return permissions.resolve_current_instance_ownership()++ @staticmethod+ def _reconcile_resource_policy(+ connection,+ session_id: str,+ user_context: Any,+ ownership: dict[str, Any],+ ) -> dict[str, Any]:from storage import resource_access_service- if not (user_context.subject and user_context.has_role("editor")):- return- resource_access_service.ensure_resource_policy(+ owner_user_id = (+ user_context.subject+ if user_context.subject and user_context.has_role("editor")+ else None+ )+ return resource_access_service.reconcile_show_page_resource_policy(connection,- resource_kind="show_page",resource_id=session_id,- organization_id=user_context.organization_id,- owner_user_id=user_context.subject,+ ownership=ownership,+ owner_user_id=owner_user_id,owner_email=user_context.email,- access_level="private",- created_by_user_id=user_context.subject,- updated_by_user_id=user_context.subject,)+ def reconcile_resource_policy(+ self,+ session_id: str,+ *,+ user_context: Any = None,+ ) -> dict[str, Any]:+ """Resolve ownership outside SQLite, then reconcile one existing page."""++ session_id = validate_session_id(session_id)+ context = _resolve_resource_access_context(user_context)+ ownership = self._resolve_instance_ownership()+ with self.engine.begin() as connection:+ exists = connection.execute(+ select(show_pages.c.session_id)+ .where(show_pages.c.session_id == session_id)+ .limit(1)+ ).scalar_one_or_none()+ if exists is None:+ raise ShowPageError(+ "This session has no Show Page.",+ code="show_page_not_found",+ )+ return self._reconcile_resource_policy(+ connection,+ session_id,+ context,+ ownership,+ )+def ensure(self, session_id: str, *, user_context: Any = None) -> ShowPage:session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)+ ownership = self._resolve_instance_ownership()now = _utc_now_iso()page = ShowPage(session_id=session_id,@@ -796,6 +836,7 @@ class ShowPageStore:.first())if existing is not None:+ self._reconcile_resource_policy(conn, session_id, context, ownership)self._require_project_edit_access(conn, session_id, context)self._require_resource_access(conn, session_id, context)return _page_from_row(existing)@@ -812,7 +853,7 @@ class ShowPageStore:updated_at=page.updated_at,))- self._register_created_resource_policy(conn, session_id, context)+ self._reconcile_resource_policy(conn, session_id, context, ownership)return pagedef ensure_active(self, session_id: str, *, user_context: Any = None) -> tuple[ShowPage, bool]:@@ -827,6 +868,7 @@ class ShowPageStore:"""session_id = validate_session_id(session_id)context = _resolve_resource_access_context(user_context)+ ownership = self._resolve_instance_ownership()now = _utc_now_iso()with self.engine.begin() as conn:existing = (@@ -835,6 +877,7 @@ class ShowPageStore:.first())if existing is not None:+ self._reconcile_resource_policy(conn, session_id, context, ownership)self._require_project_edit_access(conn, session_id, context)self._require_resource_access(conn, session_id, context)return _page_from_row(existing), False@@ -889,9 +932,14 @@ class ShowPageStore:"Could not allocate a unique share ID.",code="share_id_allocation_failed",)- if created:- self._register_created_resource_policy(conn, session_id, context)- self._require_resource_access(conn, session_id, context)+ reconciliation = self._reconcile_resource_policy(+ conn,+ session_id,+ context,+ ownership,+ )+ if not (created and reconciliation["status"] == "pending"):+ self._require_resource_access(conn, session_id, context)return _page_from_row(row), createddef is_archived(self, session_id: str) -> bool:diff --git a/docs/plans/2026-08-18-current-instance-permissions.md b/docs/plans/2026-08-18-current-instance-permissions.mdindex 0f4123a2a..47b204f17 100644--- a/docs/plans/2026-08-18-current-instance-permissions.md+++ b/docs/plans/2026-08-18-current-instance-permissions.md@@ -4,8 +4,14 @@Issue #1507 replaces the embedded Organization administration surface with aPermissions page for exactly the paired Avibe instance. Backend PR #239 is the-wire authority; this implementation targets its merged head-`8bf0024d87d1cb6a64be31b8a8068e89162a9153`.+instance and Project wire authority; this implementation targets its merged+head `8bf0024d87d1cb6a64be31b8a8068e89162a9153`.++Issue #1522 extends that boundary to Show Page Workspace access. Backend PR+#251 is the Resource ACL wire authority and is deployed to Production. Link+access remains the local `ShowAccess` aggregate delivered by #1501; Workspace+access is the exact-current-instance Resource ACL. Neither axis derives or+mutates the other.## Contract@@ -14,6 +20,8 @@ The browser calls only same-origin routes:- `GET /api/permissions`- `PUT /api/permissions/authorized-users`- `PUT /api/permissions/projects/{project_id}/access`+- `GET /api/permissions/resources/{resource_kind}/{resource_id}/access`+- `PUT /api/permissions/resources/{resource_kind}/{resource_id}/access`The local service obtains `backend_url`, `instance_id`, and `instance_secret`from `V2Config.remote_access.vibe_cloud.runtime_credentials()`. It never accepts@@ -23,12 +31,54 @@ use `X-Vibe-Device-Secret` against:- `GET /api/v1/instances/{instance_id}/permissions`- `PUT /api/v1/instances/{instance_id}/permissions/authorized-users`- `PUT /api/v1/instances/{instance_id}/permissions/projects/{project_id}/access`+- `GET /api/v1/instances/{instance_id}/permissions/resources/{resource_kind}/{resource_id}/access`+- `PUT /api/v1/instances/{instance_id}/permissions/resources/{resource_kind}/{resource_id}/access`Reads require the existing authenticated instance session. Mutations require`AuthorizationContext.can_manage_instance` both in the central HTTP policy andagain in the handler. Backend `local_mutation_allowed` remains an independentwrite gate for Cloud-owned policy.+Resource writes contain `access_level`, `group_ids`, and+`if_match_revision`. The browser also sends the local-only+`if_match_instance_id` pairing precondition; the local service validates and+strips it before Backend contact. Resource responses must match the requested+instance, kind, and ID exactly.++## Show Page Ownership++The current paired instance, never a browser claim, owns every Show Page in+that instance. The shared local ownership fence has four states:++- `unmanaged`: no authoritative pairing exists; retain standalone compatibility.+- `personal`: the exact current instance is authoritatively Personal.+- `organization`: the exact current instance and Organization ID are known.+- `organization_pending`: the instance is known to be Organization-owned, but+ its exact Organization ID is temporarily unavailable.++The last known exact instance/Organization binding is persisted in SQLite and+is used only while it still matches the current paired instance. A re-pair does+not inherit the old binding. Resolution may contact Backend, but it happens+outside SQLite transactions and failure never blocks Show Page creation or+runtime.++Every new or existing Show Page passes through one idempotent reconciliation:++- missing policy + Personal creates a private Personal policy;+- missing policy + Organization creates a private policy for the exact+ Organization;+- missing policy + Organization pending remains private and pending;+- a null Organization policy adopts the exact Organization without changing+ owner/audit data, ACL level, groups, policy revision, or applied revision;+- the same Organization is unchanged;+- another Organization, or an Organization policy on a Personal instance, is+ an integrity conflict and is never overwritten.++Pending, conflicting, and mismatched concrete Show Page policies fail closed+for non-owners across use, management, owner-control, and list filtering. The+Instance Owner may still inspect and recover them. Link access mode, share ID,+Limited emails, revision, and availability are outside this reconciliation.+## State Model- Live instance-managed: owner-capable sessions can edit users/groups and@@ -41,6 +91,10 @@ write gate for Cloud-owned policy.- Applying: projection and Project sync status are rendered explicitly.- Conflict: the editor draft remains open, authoritative state is refreshed,and retry is explicit with the refreshed revision.+- Organization pending: Show Page Workspace access is unavailable and private;+ it never appears Personal merely because the exact binding is unavailable.+- Ownership conflict: the mismatched policy remains untouched, non-owner use is+ denied, and the Share UI exposes a diagnosable unavailable state.- Denied: session authorization and paired-credential failures are not treatedas offline or empty data.- Empty: a successful live projection with no access entries or Projects is a@@ -55,6 +109,15 @@ write gate for Cloud-owned policy.for Personal and Organization instances.- Preserve #1498 local Show Page Private/Limited/Public policy while removingthe independent Cloud Management OAuth/resource-proxy control.+- Reconcile Show Page ownership in the shared storage/service path and expose a+ separate neutral Workspace section in the Share popover.+- Map Workspace `Private`, `Organization`, and `Selected groups` to wire+ `private`, `public`, and `scope`; retain already-bound archived groups while+ preventing new archived selections.+- On a Resource revision conflict, refresh the authoritative resource while+ preserving the browser draft and any newly observed bound archived group.+- Constrain the Share popover to Radix's available height and make it vertically+ scrollable on desktop and mobile.- Delete the obsolete Organization UI, Cloud-management OAuth/cookies/proxies,scenarios, tests, and stale plan after the replacement path is covered.- Keep English and Chinese copy in exact key parity.@@ -62,8 +125,13 @@ write gate for Cloud-owned policy.## Verification- Focused Python API/client/cache tests and authorization policy tests.+- Focused Show Page ownership/reconciliation tests covering new, legacy,+ idempotent, offline, pending, Personal, same-Organization, and conflict paths.- Focused Vitest coverage for navigation, authority, offline, applying, denied,empty, and draft-preserving conflict behavior.+- Focused Vitest coverage for Workspace modes, active and archived groups,+ Personal/pending/conflict states, stale-response fencing, and Link/Workspace+ independence.- Closed-loop current-instance Permissions scenario catalog and harness cases,while retaining AUTH-SETUP-401 through AUTH-SETUP-404 for #1498.- Ruff on changed Python, UI production build, `git diff --check`, and local@@ -76,3 +144,4 @@ write gate for Cloud-owned policy.- Cloud Management OAuth, management-token cookies, or embedded consent.- Uploading #1498 local exact-email Show Page guest lists to Backend.- Implementing future Cloud-owned per-Show-Page policy distribution.+- Transferring an explicitly bound resource between Organizations.diff --git a/storage/resource_access_service.py b/storage/resource_access_service.pyindex b1c76a730..ef7baa976 100644--- a/storage/resource_access_service.py+++ b/storage/resource_access_service.py@@ -31,8 +31,13 @@ ACCESS_LEVELS = frozenset({"public", "scope", "private"})ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"RESOURCE_ORGANIZATIONS_META_KEY = "resource_access_organizations"+SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY = "show_page_instance_ownership"HARNESS_ACCESS_FORBIDDEN_CODE = "harness_access_forbidden"+_SHOW_PAGE_OWNERSHIP_MODES = frozenset(+ {"unmanaged", "personal", "organization", "organization_pending"}+)+class ResourceAccessError(ValueError):"""A stable, non-sensitive policy or intent validation error."""@@ -311,6 +316,234 @@ def _connection(connection: Connection | None) -> Iterator[Connection]:yield active_connection+def _configured_show_page_instance() -> tuple[str, str] | None:+ try:+ from config.v2_config import V2Config++ cloud = V2Config.load().remote_access.vibe_cloud+ credentials = cloud.runtime_credentials()+ except (FileNotFoundError, OSError, TypeError, ValueError):+ return None+ if credentials is None:+ return None+ return credentials[1], cloud.instance_kind+++def _stored_show_page_instance_ownership(connection: Connection) -> dict[str, Any] | None:+ raw_value = connection.execute(+ select(state_meta.c.value_json).where(+ state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY+ )+ ).scalar_one_or_none()+ try:+ payload = json.loads(raw_value) if raw_value else None+ except (TypeError, ValueError):+ return None+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ return None+ instance_id = _clean_optional_string(payload.get("instance_id"))+ mode = payload.get("mode")+ organization_id = _clean_optional_string(payload.get("organization_id"))+ if instance_id is None or mode not in {"personal", "organization"}:+ return None+ if mode == "organization" and organization_id is None:+ return None+ if mode == "personal" and organization_id is not None:+ return None+ return {+ "mode": mode,+ "instance_id": instance_id,+ "organization_id": organization_id,+ "source": "stored",+ }+++def current_show_page_instance_ownership(+ *,+ connection: Connection | None = None,+) -> dict[str, Any]:+ """Return the persisted ownership fence for the exact current pairing."""++ configured = _configured_show_page_instance()+ if configured is None:+ return {+ "mode": "unmanaged",+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }+ instance_id, instance_kind = configured+ with _connection(connection) as conn:+ stored = _stored_show_page_instance_ownership(conn)+ exact_stored = stored if stored and stored["instance_id"] == instance_id else None+ if instance_kind == "personal":+ return {+ "mode": "personal",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+ if instance_kind == "organization":+ if exact_stored and exact_stored["mode"] == "organization":+ return exact_stored+ return {+ "mode": "organization_pending",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+ if exact_stored is not None:+ return exact_stored+ return {+ "mode": "unmanaged",+ "instance_id": instance_id,+ "organization_id": None,+ "source": "config",+ }+++def remember_show_page_instance_ownership(+ connection: Connection,+ ownership: Mapping[str, Any],+) -> dict[str, Any]:+ """Persist an authoritative binding only while its exact pairing is current."""++ configured = _configured_show_page_instance()+ instance_id = _clean_optional_string(ownership.get("instance_id"))+ mode = ownership.get("mode")+ organization_id = _clean_optional_string(ownership.get("organization_id"))+ if (+ configured is None+ or instance_id != configured[0]+ or mode not in {"personal", "organization"}+ or (mode == "organization") != bool(organization_id)+ ):+ return current_show_page_instance_ownership(connection=connection)+ payload = {+ "schema_version": 1,+ "instance_id": instance_id,+ "mode": mode,+ "organization_id": organization_id,+ }+ connection.execute(+ state_meta.delete().where(state_meta.c.key == SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY)+ )+ connection.execute(+ state_meta.insert().values(+ key=SHOW_PAGE_INSTANCE_OWNERSHIP_META_KEY,+ value_json=json.dumps(payload, separators=(",", ":")),+ updated_at=_utc_now_iso(),+ )+ )+ return {**payload, "source": str(ownership.get("source") or "live")}+++def reconcile_show_page_resource_policy(+ connection: Connection,+ *,+ resource_id: str,+ ownership: Mapping[str, Any],+ owner_user_id: str | None,+ owner_email: str | None = None,+) -> dict[str, Any]:+ """Reconcile one Show Page policy without changing either access axis."""++ identifier = _required_identifier(resource_id, code="invalid_resource_id")+ mode = ownership.get("mode")+ if mode not in _SHOW_PAGE_OWNERSHIP_MODES:+ raise ResourceAccessError("invalid_show_page_ownership")+ if mode in {"personal", "organization"}:+ fence = remember_show_page_instance_ownership(connection, ownership)+ else:+ fence = current_show_page_instance_ownership(connection=connection)+ mode = fence["mode"]+ policy = _policy_row(connection, "show_page", identifier)+ policy_organization = _clean_optional_string(+ policy.get("organization_id") if policy else None+ )++ if mode == "unmanaged":+ status = "unmanaged"+ elif mode == "organization_pending":+ status = "pending"+ elif mode == "personal":+ if policy is None:+ policy = ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id=identifier,+ organization_id=None,+ owner_user_id=owner_user_id,+ owner_email=owner_email,+ access_level="private",+ created_by_user_id=owner_user_id,+ updated_by_user_id=owner_user_id,+ )+ status = "created"+ else:+ status = "unchanged" if policy_organization is None else "conflict"+ else:+ organization_id = _required_identifier(+ fence.get("organization_id"), code="invalid_organization_id"+ )+ if policy is None:+ policy = ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id=identifier,+ organization_id=organization_id,+ owner_user_id=owner_user_id,+ owner_email=owner_email,+ access_level="private",+ created_by_user_id=owner_user_id,+ updated_by_user_id=owner_user_id,+ )+ status = "created"+ elif policy_organization is None:+ connection.execute(+ resource_access_policies.update()+ .where(resource_access_policies.c.resource_kind == "show_page")+ .where(resource_access_policies.c.resource_id == identifier)+ .values(organization_id=organization_id)+ )+ connection.execute(+ resource_access_groups.update()+ .where(resource_access_groups.c.resource_kind == "show_page")+ .where(resource_access_groups.c.resource_id == identifier)+ .values(organization_id=organization_id)+ )+ remember_resource_organization(connection, organization_id)+ policy = _policy_row(connection, "show_page", identifier)+ status = "adopted"+ else:+ status = (+ "unchanged" if policy_organization == organization_id else "conflict"+ )+ serialized = _serialize_policy(connection, policy) if policy else None+ return {"status": status, "ownership": fence, "policy": serialized}+++def _show_page_policy_matches_instance_ownership(+ ownership: Mapping[str, Any],+ policy: Mapping[str, Any] | None,+) -> bool:+ mode = ownership.get("mode")+ if mode == "unmanaged":+ return True+ if mode == "organization_pending":+ return False+ policy_organization = _clean_optional_string(+ policy.get("organization_id") if policy else None+ )+ if mode == "personal":+ return policy_organization is None+ return bool(+ mode == "organization"+ and policy_organization+ and policy_organization == _clean_optional_string(ownership.get("organization_id"))+ )++def _stored_resource_organizations(connection: Connection) -> set[str]:raw_value = connection.execute(select(state_meta.c.value_json).where(state_meta.c.key == RESOURCE_ORGANIZATIONS_META_KEY)@@ -559,6 +792,8 @@ def _policy_allows(resource_id: str,policy: Mapping[str, Any] | None,group_ids: Sequence[str],+ *,+ show_page_ownership: Mapping[str, Any] | None = None,) -> bool:if context.is_instance_owner:return True@@ -571,6 +806,15 @@ def _policy_allows(return Trueif resource_kind == "show_page" and context.can_use_show_page(resource_id):return True+ if (+ resource_kind == "show_page"+ and show_page_ownership is not None+ and not _show_page_policy_matches_instance_ownership(+ show_page_ownership,+ policy,+ )+ ):+ return Falseif context.instance_access_source == "show_page_email":return Falseif not context.can_use_resource(resource_kind):@@ -700,7 +944,19 @@ def can_use_resource(with _connection(connection) as conn:policy = _policy_row(conn, kind, identifier)groups = _policy_groups(conn, kind, identifier) if policy else []- return _policy_allows(context, kind, identifier, policy, groups)+ ownership = (+ current_show_page_instance_ownership(connection=conn)+ if kind == "show_page"+ else None+ )+ return _policy_allows(+ context,+ kind,+ identifier,+ policy,+ groups,+ show_page_ownership=ownership,+ )def can_manage_resource_acl(@@ -715,6 +971,15 @@ def can_manage_resource_acl(identifier = _required_identifier(resource_id, code="invalid_resource_id")with _connection(connection) as conn:policy = _policy_row(conn, kind, identifier)+ if (+ kind == "show_page"+ and not context.is_instance_owner+ and not _show_page_policy_matches_instance_ownership(+ current_show_page_instance_ownership(connection=conn),+ policy,+ )+ ):+ return Falsereturn _policy_allows_management(context, policy)@@ -730,6 +995,14 @@ def can_manage_show_page_access(identifier = _required_identifier(resource_id, code="invalid_resource_id")with _connection(connection) as conn:policy = _policy_row(conn, "show_page", identifier)+ if (+ not context.is_instance_owner+ and not _show_page_policy_matches_instance_ownership(+ current_show_page_instance_ownership(connection=conn),+ policy,+ )+ ):+ return Falsereturn _policy_allows_show_page_access_management(context, policy)@@ -747,6 +1020,15 @@ def can_control_resource_sharing(identifier = _required_identifier(resource_id, code="invalid_resource_id")with _connection(connection) as conn:policy = _policy_row(conn, kind, identifier)+ if (+ kind == "show_page"+ and not context.is_instance_owner+ and not _show_page_policy_matches_instance_ownership(+ current_show_page_instance_ownership(connection=conn),+ policy,+ )+ ):+ return Falsereturn _policy_allows_owner_control(context, policy)@@ -796,6 +1078,11 @@ def filter_accessible_resources(identifier: _policy_groups(conn, kind, identifier)for identifier in policies}+ ownership = (+ current_show_page_instance_ownership(connection=conn)+ if kind == "show_page"+ else None+ )return [rowfor row, identifier in candidates@@ -806,6 +1093,7 @@ def filter_accessible_resources(identifier,policies.get(identifier),groups.get(identifier, []),+ show_page_ownership=ownership,)]diff --git a/tests/scenario_harness/permissions.py b/tests/scenario_harness/permissions.pyindex 9d56b1335..88568a5d1 100644--- a/tests/scenario_harness/permissions.py+++ b/tests/scenario_harness/permissions.py@@ -50,6 +50,7 @@ class PermissionsScenarioHarness:self.backend_available = Trueself.backend_requests: list[dict] = []self.projection = self._projection()+ self.resource = self._resource()self._backend_patch = patch.object(permissions.requests,"request",@@ -148,6 +149,27 @@ class PermissionsScenarioHarness:},}+ @staticmethod+ def _resource() -> dict:+ return {+ "instance_id": "inst-current",+ "resource_kind": "show_page",+ "resource_id": "ses-resource",+ "display_name": "Scenario Show Page",+ "owner_user_id": "subject-owner",+ "access": {+ "access_level": "private",+ "group_ids": [],+ "revision": 0,+ },+ "sync": {+ "status": "in_sync",+ "desired_acl_revision": 0,+ "applied_acl_revision": 0,+ "last_synced_at": None,+ },+ }+def _backend_request(self, method: str, url: str, **kwargs):request_record = {"method": method,@@ -166,6 +188,10 @@ class PermissionsScenarioHarness:path = urlsplit(url).pathif method == "GET" and path.endswith("/permissions"):return _BackendResponse(200, self.projection)+ if method == "GET" and path.endswith(+ "/permissions/resources/show_page/ses-resource/access"+ ):+ return _BackendResponse(200, {"resource": self.resource})if self.projection["instance"]["permission_authority"] == "cloud":return _BackendResponse(403, {"error": "permission_authority_cloud"})payload = request_record["json"] or {}@@ -216,6 +242,28 @@ class PermissionsScenarioHarness:"authorization_revision": self.projection["instance"]["authorization_revision"],},)+ if method == "PUT" and path.endswith(+ "/permissions/resources/show_page/ses-resource/access"+ ):+ current = self.resource["access"]["revision"]+ if payload.get("if_match_revision") != current:+ return _BackendResponse(+ 409,+ {"error": "permission_revision_conflict", "current_revision": current},+ )+ next_revision = current + 1+ self.resource["access"] = {+ "access_level": payload.get("access_level"),+ "group_ids": deepcopy(payload.get("group_ids", [])),+ "revision": next_revision,+ }+ self.resource["sync"].update(+ {+ "status": "pending",+ "desired_acl_revision": next_revision,+ }+ )+ return _BackendResponse(200, {"ok": True, "resource": self.resource})return _BackendResponse(404, {"error": "project_not_found"})def acknowledge_project(self) -> None:diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yamlindex ba418ad8b..fa0df96ac 100644--- a/tests/scenarios/permissions/catalog.yaml+++ b/tests/scenarios/permissions/catalog.yaml@@ -101,3 +101,12 @@ scenarios:given: Current-instance Permissions and local Show Page sharing are installedwhen: Registered routes and frontend sources are inventoriedthen: No Management OAuth proxy or embedded Organization route remains+ - id: PERMISSIONS-011+ name: Show Page Workspace access round-trips through exact-instance Resource ACL+ status: covered+ kind: mutation+ layer: scenario+ test: tests/scenarios/permissions/test_permissions_scenarios.py::test_permissions_011_show_page_resource_acl_round_trip_and_conflict+ given: A paired Instance Owner has a canonical private Show Page Resource ACL+ when: The owner saves Selected groups and then submits a stale revision+ then: The canonical policy round-trips without a browser target field and the stale write changes nothingdiff --git a/tests/scenarios/permissions/observations.yaml b/tests/scenarios/permissions/observations.yamlindex a31f9c751..0caae1fa4 100644--- a/tests/scenarios/permissions/observations.yaml+++ b/tests/scenarios/permissions/observations.yaml@@ -29,3 +29,14 @@ observations:- cache only sanitized successful projections bound to the paired instance- never mask credential or authorization failures with cached policy- keep revisions explicit on every mutation+ - id: OBS-PERMISSIONS-003+ source: issue_contract+ related_scenarios:+ - PERMISSIONS-011+ summary: Show Page Workspace access is the exact-current-instance Resource ACL while link and Limited-email access remain local and independent.+ previous_assumption: The Show Page access panel could derive Organization ownership from a browser claim or a hidden Cloud-management session.+ observed_behavior: The local service resolves pairing ownership, proxies canonical Resource ACL reads and writes, and preserves stale drafts on revision conflict.+ required_updates:+ - bind every Resource ACL request to the paired instance and strip the browser match field before Backend contact+ - preserve local link visibility and Limited-email grants as separate policy dimensions+ - treat ownership uncertainty or mismatch as fail-closed without overwriting an existing policydiff --git a/tests/scenarios/permissions/test_permissions_scenarios.py b/tests/scenarios/permissions/test_permissions_scenarios.pyindex 56bfd7707..dea238d70 100644--- a/tests/scenarios/permissions/test_permissions_scenarios.py+++ b/tests/scenarios/permissions/test_permissions_scenarios.py@@ -1,5 +1,6 @@from __future__ import annotations+from copy import deepcopyfrom pathlib import Pathimport pytest@@ -219,5 +220,69 @@ def test_permissions_010_legacy_management_surfaces_are_absent() -> None:show_control = root / "ui" / "src" / "components" / "workbench" / "ShowPageShareControl.tsx"source = show_control.read_text(encoding="utf-8")assert "cloud-management" not in source- assert "ShowPageWorkspaceAccessControl" not in source+ assert "ShowPageWorkspaceAccessControl" in sourceassert "ShowPageSharingSettings" in source+++def test_permissions_011_show_page_resource_acl_round_trip_and_conflict(harness) -> None:+ """Scenario: PERMISSIONS-011."""+ client = harness.local_client()+ resource_path = "/api/permissions/resources/show_page/ses-resource/access"++ initial = client.get(resource_path)+ write = client.put(+ resource_path,+ json={+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 0,+ "if_match_instance_id": "inst-current",+ },+ headers=harness.csrf(client),+ )+ readback = client.get(resource_path)++ assert initial.status_code == 200+ assert initial.get_json()["resource"]["access"] == {+ "access_level": "private",+ "group_ids": [],+ "revision": 0,+ }+ assert write.status_code == 200+ assert write.get_json()["resource"]["access"] == {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "revision": 1,+ }+ assert readback.status_code == 200+ assert readback.get_json()["resource"] == write.get_json()["resource"]+ backend_write = next(+ request+ for request in harness.backend_requests+ if request["method"] == "PUT" and "/permissions/resources/" in request["url"]+ )+ assert backend_write["json"] == {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 0,+ }++ before_conflict = deepcopy(harness.resource)+ conflict = client.put(+ resource_path,+ json={+ "access_level": "public",+ "group_ids": [],+ "if_match_revision": 0,+ "if_match_instance_id": "inst-current",+ },+ headers=harness.csrf(client),+ )++ assert conflict.status_code == 409+ assert conflict.get_json() == {+ "ok": False,+ "error": "permission_revision_conflict",+ "current_revision": 1,+ }+ assert harness.resource == before_conflictdiff --git a/tests/test_permissions.py b/tests/test_permissions.pyindex fd47d5b1f..493d7d5d5 100644--- a/tests/test_permissions.py+++ b/tests/test_permissions.py@@ -132,6 +132,33 @@ def _complete_projection(instance_id: str = "inst-123") -> dict:return projection+def _resource(+ instance_id: str = "inst-123",+ resource_kind: str = "show_page",+ resource_id: str = "page-1",+ *,+ revision: int = 4,+) -> dict:+ return {+ "instance_id": instance_id,+ "resource_kind": resource_kind,+ "resource_id": resource_id,+ "display_name": "Page",+ "owner_user_id": "owner-1",+ "access": {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "revision": revision,+ },+ "sync": {+ "status": "in_sync",+ "desired_acl_revision": revision,+ "applied_acl_revision": revision,+ "last_synced_at": "2026-08-18T06:00:00.000Z",+ },+ }++_MISSING = object()@@ -337,6 +364,82 @@ def test_permissions_client_binds_requests_to_paired_instance(monkeypatch) -> No]+def test_resource_access_client_binds_identity_and_strips_local_pairing_precondition(+ monkeypatch,+) -> None:+ captured = []++ def request(method, url, **kwargs):+ captured.append((method, url, kwargs.get("json")))+ resource = _resource(revision=5 if method == "PUT" else 4)+ return _Response(+ 200,+ {"ok": True, "resource": resource} if method == "PUT" else {"resource": resource},+ )++ monkeypatch.setattr(permissions.requests, "request", request)++ read = permissions.get_resource_access("show_page", "page-1", _config())+ written = permissions.update_resource_access(+ "show_page",+ "page-1",+ {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ _config(),+ )++ expected_url = (+ "https://backend.example/api/v1/instances/inst-123/permissions/"+ "resources/show_page/page-1/access"+ )+ assert read == {"resource": _resource(revision=4)}+ assert written == {"ok": True, "resource": _resource(revision=5)}+ assert captured == [+ ("GET", expected_url, None),+ (+ "PUT",+ expected_url,+ {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ },+ ),+ ]+++ ("field", "value"),+ [+ ("instance_id", "inst-other"),+ ("resource_kind", "agent"),+ ("resource_id", "page-other"),+ ],+)+def test_resource_access_client_rejects_response_identity_mismatch(+ monkeypatch,+ field,+ value,+) -> None:+ resource = _resource()+ resource[field] = value+ monkeypatch.setattr(+ permissions.requests,+ "request",+ lambda *_args, **_kwargs: _Response(200, {"resource": resource}),+ )++ with pytest.raises(+ permissions.PermissionsInvalidResponseError,+ match="permissions_resource_mismatch",+ ):+ permissions.get_resource_access("show_page", "page-1", _config())++def test_permissions_response_enriches_legacy_display_from_the_exact_pairing() -> None:config = _config()config.remote_access.vibe_cloud.public_url = "https://max-incus-1-app.avibe.bot"@@ -1363,6 +1466,18 @@ def test_permissions_http_policy_allows_viewer_reads_but_owner_only_mutations()http_authorization_policy("PUT", "/api/permissions/projects/project-1/access").minimum_role== "owner")+ assert (+ http_authorization_policy(+ "GET", "/api/permissions/resources/show_page/page-1/access"+ ).minimum_role+ == "viewer"+ )+ assert (+ http_authorization_policy(+ "PUT", "/api/permissions/resources/show_page/page-1/access"+ ).minimum_role+ == "owner"+ )def test_permissions_projection_get_is_private_and_not_cached(monkeypatch) -> None:@@ -1528,3 +1643,188 @@ def test_permissions_same_origin_route_surfaces_a_changed_pairing(monkeypatch) -"ok": False,"error": "permissions_pairing_changed",}+++def test_resource_access_same_origin_routes_forward_exact_identity_and_conflict(+ monkeypatch,+) -> None:+ client = app.test_client()+ headers = csrf_headers(client)+ captured = []++ def get_resource(resource_kind, resource_id):+ captured.append(("GET", resource_kind, resource_id, None))+ return {"resource": _resource(resource_id=resource_id)}++ def update_resource(resource_kind, resource_id, payload):+ captured.append(("PUT", resource_kind, resource_id, payload))+ raise permissions.PermissionsBackendError(+ 409,+ {"error": "permission_revision_conflict", "current_revision": 7},+ )++ monkeypatch.setattr(permissions, "get_resource_access", get_resource)+ monkeypatch.setattr(permissions, "update_resource_access", update_resource)+ read = client.get("/api/permissions/resources/show_page/page-1/access")+ write = client.put(+ "/api/permissions/resources/show_page/page-1/access",+ json={+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ headers=headers,+ )++ assert read.status_code == 200+ assert read.headers["Cache-Control"] == "private, no-store"+ assert read.get_json()["resource"]["resource_id"] == "page-1"+ assert write.status_code == 409+ assert write.get_json() == {+ "ok": False,+ "error": "permission_revision_conflict",+ "current_revision": 7,+ }+ assert captured == [+ ("GET", "show_page", "page-1", None),+ (+ "PUT",+ "show_page",+ "page-1",+ {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ ),+ ]+++ "payload",+ [+ {+ "access_level": "scope",+ "group_ids": [],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ {+ "access_level": "private",+ "group_ids": ["group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ {+ "access_level": "scope",+ "group_ids": ["group-1", "group-1"],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ {+ "access_level": "scope",+ "group_ids": ["group-1"],+ "if_match_revision": True,+ "if_match_instance_id": "inst-123",+ },+ ],+)+def test_resource_access_same_origin_route_rejects_invalid_payload_before_backend(+ monkeypatch,+ payload,+) -> None:+ called = False++ def update_resource(*_args):+ nonlocal called+ called = True+ return {"ok": True}++ monkeypatch.setattr(permissions, "update_resource_access", update_resource)+ client = app.test_client()+ response = client.put(+ "/api/permissions/resources/show_page/page-1/access",+ json=payload,+ headers=csrf_headers(client),+ )++ assert response.status_code == 422+ assert response.get_json() == {"ok": False, "error": "invalid_request"}+ assert called is False+++def test_resource_access_route_rejects_page_scoped_guest_before_backend(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = save_config(tmp_path)+ backend_called = False++ def get_resource(*_args):+ nonlocal backend_called+ backend_called = True+ return {"resource": _resource()}++ monkeypatch.setattr(permissions, "get_resource_access", get_resource)+ client = app.test_client()+ client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ remote_session_cookie(+ config,+ "[email protected]",+ "guest-1",+ session_claims={+ "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,+ "vibe_instance_role": "viewer",+ "vibe_instance_access_source": "show_page_email",+ "vibe_show_page_id": "page-1",+ },+ ),+ domain="alex.avibe.bot",+ )++ response = client.get(+ "/api/permissions/resources/show_page/page-1/access",+ base_url="https://alex.avibe.bot",+ environ_base=remote_peer(),+ )++ assert response.status_code == 403+ assert response.get_json() == {+ "ok": False,+ "error": "show_page_access_forbidden",+ }+ assert backend_called is False+++def test_resource_access_route_surfaces_cloud_authority_failure(monkeypatch) -> None:+ monkeypatch.setattr(+ permissions,+ "update_resource_access",+ lambda *_args: (_ for _ in ()).throw(+ permissions.PermissionsBackendError(+ 403,+ {"error": "permission_authority_cloud"},+ )+ ),+ )+ client = app.test_client()+ response = client.put(+ "/api/permissions/resources/show_page/page-1/access",+ json={+ "access_level": "private",+ "group_ids": [],+ "if_match_revision": 4,+ "if_match_instance_id": "inst-123",+ },+ headers=csrf_headers(client),+ )++ assert response.status_code == 403+ assert response.get_json() == {+ "ok": False,+ "error": "permission_authority_cloud",+ }diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.pyindex d045a8658..34f5ea363 100644--- a/tests/test_resource_acl_show_pages.py+++ b/tests/test_resource_acl_show_pages.py@@ -13,7 +13,7 @@ from storage.importer import ensure_sqlite_statefrom storage.models import agent_sessions, show_pagesfrom tests.ui_server_test_helpers import _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headers-from vibe import api, internal_client, remote_access, ui_server+from vibe import api, internal_client, permissions, remote_access, ui_serverfrom vibe.ui_server import app@@ -53,6 +53,7 @@ def _organization_cookie("vibe_organization_member_id": f"member-{subject}","vibe_organization_role": organization_role,"vibe_membership_version": "membership-v2",+ "vibe_instance_authorization_revision": 0,}if groups is not None:claims["vibe_group_ids"] = groups@@ -64,6 +65,30 @@ def _organization_cookie()+def _paired_config(tmp_path, *, instance_kind: str):+ config = _save_config(tmp_path)+ cloud = config.remote_access.vibe_cloud+ cloud.backend_url = "https://backend.example"+ cloud.instance_secret = "device-secret"+ cloud.instance_kind = instance_kind+ config.save()+ return config+++def _ownership(+ mode: str,+ *,+ organization_id: str | None = None,+ source: str = "live",+) -> dict:+ return {+ "mode": mode,+ "instance_id": "inst_123",+ "organization_id": organization_id,+ "source": source,+ }++def _seed_show_pages_with_policies() -> ShowPageStore:store = ShowPageStore()for session_id in ("ses-private", "ses-public", "ses-scope"):@@ -259,8 +284,17 @@ def test_remote_show_page_access_does_not_bypass_acl(assert page.status_code == (200 if instance_role == "owner" else 302)-def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_path) -> None:+def test_show_page_creation_uses_exact_instance_organization_without_request_claims(+ monkeypatch,+ tmp_path,+) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )owner_context = _organization_context("owner-1", instance_role="owner")store = ShowPageStore()try:@@ -284,10 +318,7 @@ def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_p}],},)- created = store.ensure(- session["id"],- user_context=_organization_context("member-1", instance_role="editor"),- )+ created = store.ensure(session["id"])assert created.session_id == session["id"]with store.engine.connect() as connection:created_policy = resource_access_service.get_resource_policy(@@ -295,7 +326,7 @@ def test_remote_show_page_creation_persists_real_org_identity(monkeypatch, tmp_p)assert created_policy is not Noneassert created_policy["organization_id"] == "org-1"- assert created_policy["owner_user_id"] == "member-1"+ assert created_policy["owner_user_id"] is Noneassert "is_trusted_local" not in created_policypage = store.ensure("ses-org-public", user_context=owner_context)with store.engine.begin() as connection:@@ -535,28 +566,53 @@ def test_organization_admin_can_read_show_page_access_metadata_without_use_accesapi.get_show_page_access("ses-scope")-def test_opening_existing_organization_page_does_not_register_new_policy(monkeypatch, tmp_path) -> None:+def test_existing_show_page_is_adopted_idempotently_without_changing_link_access(+ monkeypatch,+ tmp_path,+) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))store = ShowPageStore()try:store.ensure("ses-legacy")- page = store.ensure(+ applied = store.apply_access("ses-legacy",- user_context=_organization_context("owner-1", instance_role="owner"),+ expected_revision=0,+ target_access_mode="limited",+ target_share_id="stable-link",+ target_emails=["[email protected]"],+ )+ store.set_offline("ses-legacy", True)+ before = store.get_access("ses-legacy")+ assert applied.status == "applied"+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),)+ page = store.ensure("ses-legacy")+ store.ensure("ses-legacy")with store.engine.connect() as connection:policy = resource_access_service.get_resource_policy("show_page",page.session_id,connection=connection,)- assert policy is None+ after = store.get_access("ses-legacy")+ assert policy is not None+ assert policy["organization_id"] == "org-1"+ assert policy["access_level"] == "private"+ assert policy["policy_revision"] == 0+ assert before == after+ assert page.offlinefinally: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_home = tmp_path / "personal"+ monkeypatch.setenv("AVIBE_HOME", str(personal_home))+ _paired_config(personal_home, instance_kind="personal")personal_store = ShowPageStore()try:personal_store.ensure("ses-personal")@@ -568,32 +624,39 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkassert personal.get_json() == {"ok": True,"mode": "personal",- "instance_id": None,+ "ownership_status": "unchanged",+ "instance_id": "inst_123","organization_id": None,+ "policy_organization_id": None,"access_level": "private","group_ids": [],- "policy_revision": None,+ "policy_revision": 0,"last_applied_control_plane_revision": None,"can_use": True,"can_manage": True,"can_publish_public": True,}- config = _save_config(tmp_path)+ organization_home = tmp_path / "organization"+ monkeypatch.setenv("AVIBE_HOME", str(organization_home))+ config = _paired_config(organization_home, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )store = ShowPageStore()try:store.ensure("ses-organization")with store.engine.begin() as connection:- resource_access_service.ensure_resource_policy(+ resource_access_service.apply_control_plane_intent(connection,+ organization_id="org-1",resource_kind="show_page",resource_id="ses-organization",- organization_id="org-1",- owner_user_id="owner-1",+ revision=4,access_level="scope",group_ids=["group-engineering"],- policy_revision=4,- last_applied_control_plane_revision=4,)finally:store.close()@@ -619,8 +682,10 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monkassert organization.get_json() == {"ok": True,"mode": "organization",+ "ownership_status": "unchanged","instance_id": "inst_123","organization_id": "org-1",+ "policy_organization_id": "org-1","access_level": "scope","group_ids": ["group-engineering"],"policy_revision": 4,@@ -631,6 +696,232 @@ def test_show_page_access_api_distinguishes_personal_and_organization_modes(monk}+def test_null_organization_adoption_preserves_policy_and_show_access(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ store.ensure("ses-adopt")+ applied = store.apply_access(+ "ses-adopt",+ expected_revision=0,+ target_access_mode="limited",+ target_share_id="adopt-link",+ target_emails=["[email protected]"],+ )+ with store.engine.begin() as connection:+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id="ses-adopt",+ organization_id=None,+ owner_user_id="owner-1",+ owner_email="[email protected]",+ access_level="private",+ policy_revision=4,+ last_applied_control_plane_revision=3,+ )+ before_access = store.get_access("ses-adopt")+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )++ store.ensure("ses-adopt")+ store.ensure("ses-adopt")++ with store.engine.connect() as connection:+ policy = resource_access_service.get_resource_policy(+ "show_page",+ "ses-adopt",+ connection=connection,+ )+ assert applied.status == "applied"+ assert store.get_access("ses-adopt") == before_access+ assert policy is not None+ assert policy["organization_id"] == "org-1"+ assert policy["owner_user_id"] == "owner-1"+ assert policy["owner_email"] == "[email protected]"+ assert policy["access_level"] == "private"+ assert policy["group_ids"] == []+ assert policy["policy_revision"] == 4+ assert policy["last_applied_control_plane_revision"] == 3+ finally:+ store.close()+++def test_same_organization_retry_preserves_acl_revision_and_groups(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )+ store = ShowPageStore()+ try:+ store.ensure(+ "ses-same-org",+ user_context=_organization_context("owner-1", instance_role="owner"),+ )+ with store.engine.begin() as connection:+ resource_access_service.apply_control_plane_intent(+ connection,+ organization_id="org-1",+ resource_kind="show_page",+ resource_id="ses-same-org",+ revision=7,+ access_level="scope",+ group_ids=["group-engineering"],+ )+ before = resource_access_service.get_resource_policy(+ "show_page", "ses-same-org", connection=connection+ )++ store.ensure(+ "ses-same-org",+ user_context=_organization_context("owner-1", instance_role="owner"),+ )++ with store.engine.connect() as connection:+ after = resource_access_service.get_resource_policy(+ "show_page", "ses-same-org", connection=connection+ )+ assert after == before+ finally:+ store.close()+++def test_cross_organization_policy_conflict_fails_closed_without_breaking_link_guest(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ store = ShowPageStore()+ try:+ store.ensure("ses-conflict")+ with store.engine.begin() as connection:+ resource_access_service.ensure_resource_policy(+ connection,+ resource_kind="show_page",+ resource_id="ses-conflict",+ organization_id="org-other",+ owner_user_id="owner-other",+ access_level="public",+ policy_revision=5,+ last_applied_control_plane_revision=5,+ )+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "resolve_current_instance_ownership",+ lambda: _ownership("organization", organization_id="org-1"),+ )+ store.ensure("ses-conflict")++ response = api.get_show_page_access("ses-conflict")+ with store.engine.connect() as connection:+ policy = resource_access_service.get_resource_policy(+ "show_page", "ses-conflict", connection=connection+ )+ link_guest = resource_access_service.can_use_resource(+ resource_access_service.ResourceUserContext(+ subject="guest-1",+ email="[email protected]",+ instance_role="viewer",+ instance_access_source="show_page_email",+ show_page_id="ses-conflict",+ is_remote=True,+ ),+ "show_page",+ "ses-conflict",+ connection=connection,+ )+ with pytest.raises(ShowPageError):+ store.require_access(+ "ses-conflict",+ user_context=_organization_context("member-1"),+ )+ assert store.list(user_context=_organization_context("member-1")) == []+ assert response["ownership_status"] == "conflict"+ assert response["organization_id"] == "org-1"+ assert response["policy_organization_id"] == "org-other"+ assert policy is not None+ assert policy["organization_id"] == "org-other"+ assert policy["access_level"] == "public"+ assert policy["policy_revision"] == 5+ assert link_guest is True+ finally:+ store.close()+++def test_organization_pending_is_stable_private_and_does_not_block_local_creation(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _paired_config(tmp_path, instance_kind="organization")+ monkeypatch.setattr(+ permissions,+ "get_current_permissions",+ lambda _config=None: (_ for _ in ()).throw(+ permissions.PermissionsUnavailableError("permissions_backend_unavailable")+ ),+ )+ store = ShowPageStore()+ try:+ created = store.ensure("ses-pending")+ response = api.get_show_page_access("ses-pending")+ with store.engine.connect() as connection:+ policy = resource_access_service.get_resource_policy(+ "show_page", "ses-pending", connection=connection+ )+ assert created.session_id == "ses-pending"+ assert policy is None+ assert response["mode"] == "organization_pending"+ assert response["ownership_status"] == "pending"+ assert response["access_level"] == "private"+ assert response["organization_id"] is None+ assert response["can_use"] is True+ finally:+ store.close()+++def test_last_known_organization_binding_is_exact_instance_scoped(monkeypatch, tmp_path) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path, instance_kind="organization")+ store = ShowPageStore()+ try:+ with store.engine.begin() as connection:+ resource_access_service.remember_show_page_instance_ownership(+ connection,+ _ownership("organization", organization_id="org-1"),+ )+ monkeypatch.setattr(+ permissions,+ "get_current_permissions",+ lambda _config=None: (_ for _ in ()).throw(+ permissions.PermissionsUnavailableError("permissions_backend_unavailable")+ ),+ )+ offline = permissions.resolve_current_instance_ownership()+ assert offline == _ownership(+ "organization",+ organization_id="org-1",+ source="stored",+ )++ config.remote_access.vibe_cloud.instance_id = "inst-new"+ config.save()+ repaired = permissions.resolve_current_instance_ownership()+ assert repaired["mode"] == "organization_pending"+ assert repaired["instance_id"] == "inst-new"+ assert repaired["organization_id"] is None+ finally:+ store.close()++def test_show_page_access_api_reports_missing_page_as_definitive_denial(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsxindex c55b9f7ac..d212b59b3 100644--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx@@ -3,11 +3,25 @@ import { createInstance } from 'i18next';import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { renderToStaticMarkup } from 'react-dom/server';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import en from '../../i18n/en.json';+import type { ShowPageAccess } from '../../lib/showPageAccess';import { ShowPageShareControl } from './ShowPageShareControl';+const permissionsApi = vi.hoisted(() => ({+ getPermissions: vi.fn(),+ getResourceAccess: vi.fn(),+ updateResourceAccess: vi.fn(),+}));++vi.mock('@/features/permissions/api', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/features/permissions/api')>()),+ getPermissions: permissionsApi.getPermissions,+ getResourceAccess: permissionsApi.getResourceAccess,+ updateResourceAccess: permissionsApi.updateResourceAccess,+}));+const api = {ensureShowPage: vi.fn(),getShowPageAccess: vi.fn(),@@ -51,6 +65,12 @@ vi.mock('../useShowPages', () => ({}),}));+beforeEach(() => {+ permissionsApi.getPermissions.mockReset();+ permissionsApi.getResourceAccess.mockReset();+ permissionsApi.updateResourceAccess.mockReset();+});+afterEach(() => {cleanup();vi.clearAllMocks();@@ -71,6 +91,23 @@ const renderControl = (compact: boolean) =></I18nextProvider>,);+const showPageAccess = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({+ ok: true,+ mode: 'unmanaged',+ ownership_status: 'unmanaged',+ instance_id: null,+ organization_id: null,+ policy_organization_id: null,+ access_level: 'private',+ group_ids: [],+ policy_revision: null,+ last_applied_control_plane_revision: null,+ can_use: true,+ can_manage: false,+ can_publish_public: false,+ ...overrides,+});+describe('ShowPageShareControl trigger presentation', () => {it('renders the header-sized trigger by default', () => {const html = renderControl(false);@@ -100,13 +137,11 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {// The app-window call site: no initialAccess, no instance authority. The// payload read is gated on access, so it must start only once access// resolves — the first open still shows the link.- api.getShowPageAccess.mockResolvedValue({- ok: true,- mode: 'local',+ api.getShowPageAccess.mockResolvedValue(showPageAccess({can_use: true,can_manage: false,can_publish_public: false,- });+ }));api.ensureShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',@@ -132,14 +167,68 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {});});+ it('keeps Link access usable while Workspace access is still loading', async () => {+ const organizationAccess = showPageAccess({+ mode: 'organization',+ ownership_status: 'unchanged',+ instance_id: 'inst-1',+ organization_id: 'org-1',+ policy_organization_id: 'org-1',+ can_manage: true,+ can_publish_public: true,+ });+ const pending = new Promise(() => undefined);+ permissionsApi.getPermissions.mockReturnValue(pending);+ permissionsApi.getResourceAccess.mockReturnValue(pending);+ api.getShowPageAccess.mockResolvedValue(organizationAccess);+ api.ensureShowPage.mockResolvedValue({+ session_id: 'ses-1',+ visibility: 'private',+ active_url: '/show/ses-1/',+ share_id: null,+ url_available: true,+ offline: false,+ title: null,+ });+ api.getShowAccessSettings.mockResolvedValue({+ show_access: {+ page_id: 'ses-1',+ access_mode: 'private',+ share_id: null,+ revision: 3,+ normalized_emails: [],+ },+ });++ render(+ <I18nextProvider i18n={i18n}>+ <ShowPageShareControl+ sessionId="ses-1"+ initialAccess={organizationAccess}+ canManageInstance+ />+ </I18nextProvider>,+ );+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));++ expect(await screen.findByRole('radiogroup', { name: 'Link access' })).toBeTruthy();+ expect(screen.getByText('Loading Workspace access…')).toBeTruthy();+ expect(api.getShowAccessSettings).toHaveBeenCalledWith('ses-1');+ expect(permissionsApi.getPermissions).toHaveBeenCalledOnce();+ expect(permissionsApi.getResourceAccess).toHaveBeenCalledWith({+ resource_kind: 'show_page',+ resource_id: 'ses-1',+ });+ const popover = document.querySelector('.overflow-y-auto');+ expect(popover?.classList.contains('max-h-[var(--radix-popover-content-available-height)]')).toBe(true);+ });+it('never loads the payload when access resolves without page use', async () => {- api.getShowPageAccess.mockResolvedValue({- ok: true,- mode: 'local',+ api.getShowPageAccess.mockResolvedValue(showPageAccess({can_use: false,can_manage: true,can_publish_public: false,- });+ }));render(<I18nextProvider i18n={i18n}>@@ -164,13 +253,11 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {// A caller holding access (the chat header passes initialAccess) reads the// payload and access in parallel — the post-access hook must NOT fire a// second ensure request.- api.getShowPageAccess.mockResolvedValue({- ok: true,- mode: 'local',+ api.getShowPageAccess.mockResolvedValue(showPageAccess({can_use: true,can_manage: true,can_publish_public: true,- });+ }));api.ensureShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'private',@@ -185,13 +272,11 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {<I18nextProvider i18n={i18n}><ShowPageShareControlsessionId="ses-1"- initialAccess={{- ok: true,- mode: 'local',+ initialAccess={showPageAccess({can_use: true,can_manage: true,can_publish_public: true,- } as never}+ })}/></I18nextProvider>,);@@ -206,13 +291,11 @@ 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',+ api.getShowPageAccess.mockResolvedValue(showPageAccess({can_use: true,can_manage: false,can_publish_public: false,- });+ }));api.ensureShowPage.mockResolvedValue({session_id: 'ses-1',visibility: 'limited',@@ -243,13 +326,11 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {let release: (() => void) | null = null;api.getShowPageAccess.mockImplementation(() => new Promise((resolve) => {- release = () => resolve({- ok: true,- mode: 'local',+ release = () => resolve(showPageAccess({can_use: false,can_manage: true,can_publish_public: false,- });+ }));}),);diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsxindex d37152ee5..1e8ccb922 100644--- a/ui/src/components/workbench/ShowPageShareControl.tsx+++ b/ui/src/components/workbench/ShowPageShareControl.tsx@@ -15,6 +15,7 @@ import { copyHref, type ShowPageLinkInfo } from '../../lib/showPageLinks';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;@@ -222,7 +223,7 @@ export const ShowPageShareControl: React.FC<{</PopoverTrigger><PopoverContentalign="end"- className="w-[min(22rem,calc(100vw-1rem))] space-y-3"+ className="max-h-[var(--radix-popover-content-available-height)] w-[min(22rem,calc(100vw-1rem))] space-y-3 overflow-y-auto"data-window-owner-id={ownerWindowId}onInteractOutside={(event) => {if (confirmationOpen) event.preventDefault();@@ -294,6 +295,17 @@ export const ShowPageShareControl: React.FC<{</div>) : null}+ {access ? (+ <div className="border-t border-border pt-3">+ <ShowPageWorkspaceAccessControl+ access={access}+ active={open}+ canManageInstance={canManageInstance}+ sessionId={sessionId}+ />+ </div>+ ) : null}+{payload ? (<div className="border-t border-border pt-3"><div className="flex items-center justify-between gap-3">diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsxnew file mode 100644index 000000000..9b6b981fe--- /dev/null+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx@@ -0,0 +1,423 @@+/** @vitest-environment jsdom */++import { act, cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { PermissionsApiError } from '@/features/permissions/api';+import type {+ DirectoryGroup,+ PermissionResource,+ PermissionsResponse,+ ResourceAccessResponse,+} from '@/features/permissions/types';+import type { ShowPageAccess } from '@/lib/showPageAccess';++import { ShowPageWorkspaceAccessControl } from './ShowPageWorkspaceAccessControl';++const api = vi.hoisted(() => ({+ getPermissions: vi.fn(),+ getResourceAccess: vi.fn(),+ updateResourceAccess: vi.fn(),+}));++vi.mock('@/features/permissions/api', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/features/permissions/api')>()),+ getPermissions: api.getPermissions,+ getResourceAccess: api.getResourceAccess,+ updateResourceAccess: api.updateResourceAccess,+}));++const translations: Record<string, string> = {+ 'chat.showPage.workspaceAccess': 'Workspace access',+ 'chat.showPage.workspaceAccessDesc': 'Controls authenticated access inside this Avibe. Link access remains separate.',+ 'chat.showPage.loadingWorkspaceAccess': 'Loading Workspace access...',+ 'chat.showPage.workspacePersonal': 'This Show Page belongs to a Personal Avibe.',+ 'chat.showPage.workspaceUnmanaged': 'Workspace access is unavailable until this Avibe is paired.',+ 'chat.showPage.workspacePending': 'Organization ownership is known, but its exact binding is temporarily unavailable. Access remains private.',+ 'chat.showPage.workspaceOwnershipConflict': 'This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.',+ 'chat.showPage.workspaceModes.private': 'Private',+ 'chat.showPage.workspaceModes.organization': 'Organization',+ 'chat.showPage.workspaceModes.scope': 'Selected groups',+ 'chat.showPage.workspaceHelp.private': 'Only the page owner and Instance Owner can use it.',+ 'chat.showPage.workspaceHelp.public': 'Authenticated members of this Organization can use it.',+ 'chat.showPage.workspaceHelp.scope': 'Only members of the selected Organization groups can use it.',+ 'chat.showPage.workspaceGroups': 'Organization groups',+ 'chat.showPage.workspaceArchived': 'Archived',+ 'chat.showPage.workspaceNoGroups': 'No active groups are available.',+ 'chat.showPage.workspaceGroupRequired': 'Select at least one group.',+ 'chat.showPage.workspaceRevisionConflict': 'Workspace access changed elsewhere. Your draft was kept on the latest revision.',+ 'chat.showPage.workspaceOffline': 'The last known policy is shown while Permissions is offline. Editing is disabled.',+ 'chat.showPage.workspaceReadOnly': 'Avibe Cloud owns this policy. Edit it in Avibe Cloud.',+ 'chat.showPage.workspaceOwnerOnly': 'Only the Instance Owner can change Workspace access.',+ 'chat.showPage.workspaceLoadError': 'Workspace access could not be loaded.',+ 'chat.showPage.applyWorkspaceAccess': 'Apply',+ 'chat.showPage.workspaceSync.pending': 'The policy is waiting for this Avibe to apply it.',+ 'chat.showPage.workspaceSync.offline': 'This Avibe has not acknowledged the latest policy.',+ 'chat.showPage.workspaceSync.error': 'The latest policy could not be applied.',+ 'common.retry': 'Retry',+};++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { defaultValue?: string }) => (+ translations[key] ?? options?.defaultValue ?? key+ ),+ }),+}));++const activeGroup: DirectoryGroup = {+ id: 'group-active',+ name: 'Design',+ archived_at: null,+};++const archivedGroup: DirectoryGroup = {+ id: 'group-archived',+ name: 'Retired Team',+ archived_at: '2026-08-18T00:00:00Z',+};++const newArchivedGroup: DirectoryGroup = {+ id: 'group-new-archived',+ name: 'Former Operations',+ archived_at: '2026-08-18T01:00:00Z',+};++const showPageAccess = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({+ ok: true,+ mode: 'organization',+ ownership_status: 'unchanged',+ instance_id: 'inst-1',+ organization_id: 'org-1',+ policy_organization_id: 'org-1',+ access_level: 'private',+ group_ids: [],+ policy_revision: 4,+ last_applied_control_plane_revision: 4,+ can_use: true,+ can_manage: true,+ can_publish_public: true,+ ...overrides,+});++const permissions = ({+ groups = [activeGroup],+ offline = false,+ permissionAuthority = 'instance',+ localMutationAllowed = true,+}: {+ groups?: DirectoryGroup[];+ offline?: boolean;+ permissionAuthority?: 'instance' | 'cloud';+ localMutationAllowed?: boolean;+} = {}): PermissionsResponse => ({+ ok: true,+ source: offline ? 'cache' : 'live',+ offline,+ cached_at: offline ? 1 : null,+ projection: {+ schema_version: 1,+ instance: {+ id: 'inst-1',+ organization: { id: 'org-1', name: 'Example Organization' },+ access_mode: 'allowlist',+ permission_authority: permissionAuthority,+ local_mutation_allowed: localMutationAllowed,+ authorization_revision: 7,+ },+ capabilities: ['instance.permissions.read', 'instance.permissions.mutate'],+ access: { owner: { email: '[email protected]', role: 'owner' }, entries: [] },+ directory: { members: [], groups },+ projects: [],+ policy_sync: {+ status: offline ? 'offline' : 'in_sync',+ projects: { active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 },+ resources: { active: 1, error: 0, offline: 0, applying: 0, in_sync: 1 },+ },+ },+});++const resource = ({+ sessionId = 'ses-1',+ level = 'private',+ groupIds = [],+ revision = 4,+ status = 'in_sync',+}: {+ sessionId?: string;+ level?: PermissionResource['access']['access_level'];+ groupIds?: string[];+ revision?: number;+ status?: PermissionResource['sync']['status'];+} = {}): PermissionResource => ({+ instance_id: 'inst-1',+ resource_kind: 'show_page',+ resource_id: sessionId,+ display_name: sessionId,+ owner_user_id: 'owner-1',+ access: { access_level: level, group_ids: groupIds, revision },+ sync: {+ status,+ desired_acl_revision: revision,+ applied_acl_revision: status === 'in_sync' ? revision : Math.max(0, revision - 1),+ last_synced_at: null,+ },+});++const renderControl = (+ access: ShowPageAccess = showPageAccess(),+ options: { sessionId?: string; canManageInstance?: boolean } = {},+) => render(+ <ShowPageWorkspaceAccessControl+ access={access}+ active+ canManageInstance={options.canManageInstance ?? true}+ sessionId={options.sessionId ?? 'ses-1'}+ />,+);++function deferred<T>() {+ let resolve: (value: T) => void = () => undefined;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++beforeEach(() => {+ api.getPermissions.mockReset();+ api.getPermissions.mockResolvedValue(permissions());+ api.getResourceAccess.mockReset();+ api.getResourceAccess.mockResolvedValue({ resource: resource() });+ api.updateResourceAccess.mockReset();+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('ShowPageWorkspaceAccessControl', () => {+ it('saves Organization and selected-group policies and reloads the canonical group selection', async () => {+ api.updateResourceAccess+ .mockResolvedValueOnce({ ok: true, resource: resource({ level: 'public', revision: 5 }) })+ .mockResolvedValueOnce({+ ok: true,+ resource: resource({ level: 'scope', groupIds: ['group-active'], revision: 6 }),+ });+ const user = userEvent.setup();+ const view = renderControl();++ await user.click(await screen.findByRole('radio', { name: 'Organization' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));+ expect(api.updateResourceAccess).toHaveBeenLastCalledWith(+ { resource_kind: 'show_page', resource_id: 'ses-1' },+ 'public',+ [],+ 4,+ 'inst-1',+ );++ await user.click(screen.getByRole('radio', { name: 'Selected groups' }));+ await user.click(screen.getByRole('checkbox', { name: 'Design' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));+ expect(api.updateResourceAccess).toHaveBeenLastCalledWith(+ { resource_kind: 'show_page', resource_id: 'ses-1' },+ 'scope',+ ['group-active'],+ 5,+ 'inst-1',+ );++ view.unmount();+ api.getResourceAccess.mockResolvedValue({+ resource: resource({ level: 'scope', groupIds: ['group-active'], revision: 6 }),+ });+ renderControl();++ expect((await screen.findByRole('radio', { name: 'Selected groups' })).getAttribute('aria-checked')).toBe('true');+ expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');+ });++ it('keeps bound archived groups visible and selected without offering unbound archived groups', async () => {+ api.getPermissions.mockResolvedValue(permissions({+ groups: [activeGroup, archivedGroup, newArchivedGroup],+ }));+ api.getResourceAccess.mockResolvedValue({+ resource: resource({ level: 'scope', groupIds: ['group-archived'] }),+ });+ api.updateResourceAccess.mockResolvedValue({+ ok: true,+ resource: resource({+ level: 'scope',+ groupIds: ['group-active', 'group-archived'],+ revision: 5,+ }),+ });+ const user = userEvent.setup();+ renderControl();++ const archived = await screen.findByRole('checkbox', { name: 'Retired Team' });+ expect(archived.getAttribute('aria-checked')).toBe('true');+ expect((archived as HTMLButtonElement).disabled).toBe(true);+ expect(screen.getByText('Archived')).toBeTruthy();+ expect(screen.queryByText('Former Operations')).toBeNull();++ await user.click(screen.getByRole('radio', { name: 'Organization' }));+ await user.click(screen.getByRole('radio', { name: 'Selected groups' }));+ expect(screen.getByRole('checkbox', { name: 'Retired Team' }).getAttribute('aria-checked')).toBe('true');++ await user.click(screen.getByRole('checkbox', { name: 'Design' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));+ expect(api.updateResourceAccess).toHaveBeenCalledWith(+ { resource_kind: 'show_page', resource_id: 'ses-1' },+ 'scope',+ ['group-active', 'group-archived'],+ 4,+ 'inst-1',+ );+ });++ it('preserves the draft across a 409 and folds newly bound archived groups into the retry', async () => {+ api.getPermissions+ .mockResolvedValueOnce(permissions())+ .mockResolvedValueOnce(permissions({ groups: [activeGroup, archivedGroup] }));+ api.getResourceAccess+ .mockResolvedValueOnce({ resource: resource() })+ .mockResolvedValueOnce({+ resource: resource({ level: 'scope', groupIds: ['group-archived'], revision: 5 }),+ });+ api.updateResourceAccess+ .mockRejectedValueOnce(new PermissionsApiError(409, {+ error: 'permission_revision_conflict',+ current_revision: 5,+ }))+ .mockResolvedValueOnce({+ ok: true,+ resource: resource({+ level: 'scope',+ groupIds: ['group-active', 'group-archived'],+ revision: 6,+ }),+ });+ const user = userEvent.setup();+ renderControl();++ await user.click(await screen.findByRole('radio', { name: 'Selected groups' }));+ await user.click(screen.getByRole('checkbox', { name: 'Design' }));+ await user.click(screen.getByRole('button', { name: 'Apply' }));++ expect(await screen.findByText(/Your draft was kept/)).toBeTruthy();+ expect(screen.getByRole('checkbox', { name: 'Design' }).getAttribute('aria-checked')).toBe('true');+ const archived = screen.getByRole('checkbox', { name: 'Retired Team' });+ expect(archived.getAttribute('aria-checked')).toBe('true');+ expect((archived as HTMLButtonElement).disabled).toBe(true);++ await user.click(screen.getByRole('button', { name: 'Apply' }));+ expect(api.updateResourceAccess).toHaveBeenLastCalledWith(+ { resource_kind: 'show_page', resource_id: 'ses-1' },+ 'scope',+ ['group-active', 'group-archived'],+ 5,+ 'inst-1',+ );+ });++ it('fails closed for personal, pending, and conflicting ownership without contacting Permissions', () => {+ const personal = renderControl(showPageAccess({+ mode: 'personal',+ ownership_status: 'unchanged',+ organization_id: null,+ policy_organization_id: null,+ }));+ expect(screen.getByText(/belongs to a Personal Avibe/)).toBeTruthy();+ personal.unmount();++ const pending = renderControl(showPageAccess({+ mode: 'organization_pending',+ ownership_status: 'pending',+ organization_id: null,+ policy_organization_id: null,+ }));+ expect(screen.getByText(/temporarily unavailable/)).toBeTruthy();+ pending.unmount();++ renderControl(showPageAccess({+ ownership_status: 'conflict',+ policy_organization_id: 'org-other',+ }));+ expect(screen.getByText(/different ownership domain/)).toBeTruthy();+ expect(api.getPermissions).not.toHaveBeenCalled();+ expect(api.getResourceAccess).not.toHaveBeenCalled();+ });++ it('renders offline, Cloud-owned, and non-owner policy as read-only', async () => {+ api.getPermissions.mockResolvedValue(permissions({ offline: true }));+ const offline = renderControl();+ expect(await screen.findByText(/last known policy/)).toBeTruthy();+ expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);+ offline.unmount();++ api.getPermissions.mockResolvedValue(permissions({+ permissionAuthority: 'cloud',+ localMutationAllowed: false,+ }));+ const cloud = renderControl();+ expect(await screen.findByText(/Avibe Cloud owns this policy/)).toBeTruthy();+ expect((screen.getByRole('button', { name: 'Apply' }) as HTMLButtonElement).disabled).toBe(true);+ cloud.unmount();++ api.getPermissions.mockResolvedValue(permissions());+ renderControl(showPageAccess(), { canManageInstance: false });+ expect(await screen.findByText(/Only the Instance Owner/)).toBeTruthy();+ expect((screen.getByRole('radio', { name: 'Private' }) as HTMLButtonElement).disabled).toBe(true);+ });++ it('ignores an older session response after the control switches pages', async () => {+ const oldPermissions = deferred<PermissionsResponse>();+ const oldResource = deferred<ResourceAccessResponse>();+ const oldGroup = { id: 'group-old', name: 'Old Page Group', archived_at: null };+ const nextGroup = { id: 'group-next', name: 'Next Page Group', archived_at: null };+ api.getPermissions+ .mockImplementationOnce(() => oldPermissions.promise)+ .mockResolvedValueOnce(permissions({ groups: [nextGroup] }));+ api.getResourceAccess.mockImplementation((identity: { resource_id: string }) => (+ identity.resource_id === 'ses-old'+ ? oldResource.promise+ : Promise.resolve({+ resource: resource({+ sessionId: 'ses-next',+ level: 'scope',+ groupIds: ['group-next'],+ }),+ })+ ));+ const view = renderControl(showPageAccess(), { sessionId: 'ses-old' });++ view.rerender(+ <ShowPageWorkspaceAccessControl+ access={showPageAccess()}+ active+ canManageInstance+ sessionId="ses-next"+ />,+ );+ expect(await screen.findByRole('checkbox', { name: 'Next Page Group' })).toBeTruthy();++ await act(async () => {+ oldPermissions.resolve(permissions({ groups: [oldGroup] }));+ oldResource.resolve({+ resource: resource({+ sessionId: 'ses-old',+ level: 'scope',+ groupIds: ['group-old'],+ }),+ });+ await Promise.resolve();+ });++ expect(screen.getByRole('checkbox', { name: 'Next Page Group' })).toBeTruthy();+ expect(screen.queryByText('Old Page Group')).toBeNull();+ });+});diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsxnew file mode 100644index 000000000..7a0532220--- /dev/null+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx@@ -0,0 +1,381 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { CloudOff, Loader2, RefreshCw, Save, TriangleAlert } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { SegmentedRadio } from '@/components/ui/segmented';+import {+ getPermissions,+ getResourceAccess,+ isRevisionConflict,+ PermissionsApiError,+ updateResourceAccess,+} from '@/features/permissions/api';+import type {+ DirectoryGroup,+ PermissionResource,+ PermissionsResponse,+ ResourceAccessLevel,+} from '@/features/permissions/types';+import type { ShowPageAccess } from '@/lib/showPageAccess';++type Gate = 'idle' | 'loading' | 'ready' | 'conflict' | 'error';++type Draft = {+ level: ResourceAccessLevel;+ groupIds: string[];+};++const uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();++const resourceIdentityMatches = (+ resource: PermissionResource,+ sessionId: string,+ instanceId: string,+): boolean => resource.instance_id === instanceId+ && resource.resource_kind === 'show_page'+ && resource.resource_id === sessionId;++const organizationMatches = (+ permissions: PermissionsResponse,+ instanceId: string,+ organizationId: string,+): boolean => permissions.projection.instance.id === instanceId+ && permissions.projection.instance.organization?.id === organizationId;++export function ShowPageWorkspaceAccessControl({+ access,+ active,+ canManageInstance,+ sessionId,+}: {+ access: ShowPageAccess | null;+ active: boolean;+ canManageInstance: boolean;+ sessionId: string;+}) {+ const { t } = useTranslation();+ const [gate, setGate] = useState<Gate>('idle');+ const [resource, setResource] = useState<PermissionResource | null>(null);+ const [permissions, setPermissions] = useState<PermissionsResponse | null>(null);+ const [groups, setGroups] = useState<DirectoryGroup[]>([]);+ const [level, setLevel] = useState<ResourceAccessLevel>('private');+ const [groupIds, setGroupIds] = useState<string[]>([]);+ const [saving, setSaving] = useState(false);+ const [errorCode, setErrorCode] = useState<string | null>(null);+ const generationRef = useRef(0);+ const sessionIdRef = useRef(sessionId);+ const draftRef = useRef<Draft>({ level, groupIds });+ sessionIdRef.current = sessionId;+ draftRef.current = { level, groupIds };++ const instanceId = access?.instance_id ?? null;+ const organizationId = access?.organization_id ?? null;+ const ownershipConflict = access?.ownership_status === 'conflict';+ const organizationReady = access?.mode === 'organization'+ && !ownershipConflict+ && Boolean(instanceId && organizationId);++ const adopt = useCallback((next: PermissionResource, nextGroups: DirectoryGroup[]) => {+ setResource(next);+ setGroups(nextGroups);+ setLevel(next.access.access_level);+ setGroupIds(uniqueSorted(next.access.group_ids));+ }, []);++ const load = useCallback(async (+ settledGate: Gate = 'ready',+ preservedDraft?: Draft,+ ) => {+ if (!instanceId || !organizationId) return;+ const generation = ++generationRef.current;+ const requestSessionId = sessionId;+ setGate('loading');+ setErrorCode(null);+ try {+ const [nextPermissions, nextResource] = await Promise.all([+ getPermissions(),+ getResourceAccess({ resource_kind: 'show_page', resource_id: requestSessionId }),+ ]);+ if (+ generation !== generationRef.current+ || requestSessionId !== sessionIdRef.current+ ) return;+ if (+ !organizationMatches(nextPermissions, instanceId, organizationId)+ || !resourceIdentityMatches(nextResource.resource, requestSessionId, instanceId)+ ) {+ throw new Error('Show Page Workspace identity mismatch');+ }+ const directoryGroups = [...nextPermissions.projection.directory.groups];+ const knownIds = new Set(directoryGroups.map((group) => group.id));+ for (const boundId of nextResource.resource.access.group_ids) {+ if (!knownIds.has(boundId)) {+ directoryGroups.push({ id: boundId, name: boundId, archived_at: 'unknown' });+ }+ }+ setPermissions(nextPermissions);+ if (preservedDraft) {+ const archivedIds = new Set(+ directoryGroups+ .filter((group) => group.archived_at !== null)+ .map((group) => group.id),+ );+ const newlyBoundArchived = nextResource.resource.access.group_ids.filter(+ (groupId) => archivedIds.has(groupId),+ );+ setResource(nextResource.resource);+ setGroups(directoryGroups);+ setLevel(preservedDraft.level);+ setGroupIds(preservedDraft.level === 'scope'+ ? uniqueSorted([...preservedDraft.groupIds, ...newlyBoundArchived])+ : []);+ } else {+ adopt(nextResource.resource, directoryGroups);+ }+ setGate(settledGate);+ } catch (caught) {+ if (+ generation !== generationRef.current+ || requestSessionId !== sessionIdRef.current+ ) return;+ setErrorCode(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');+ setGate('error');+ }+ }, [adopt, instanceId, organizationId, sessionId]);++ useEffect(() => {+ generationRef.current += 1;+ setGate('idle');+ setResource(null);+ setPermissions(null);+ setGroups([]);+ setLevel('private');+ setGroupIds([]);+ setSaving(false);+ setErrorCode(null);+ if (active && organizationReady) void load();+ return () => {+ generationRef.current += 1;+ };+ }, [active, load, organizationReady, sessionId]);++ const visibleGroups = useMemo(() => {+ const bound = new Set(resource?.access.group_ids ?? []);+ return groups.filter((group) => group.archived_at === null || bound.has(group.id));+ }, [groups, resource]);+ const targetGroupIds = level === 'scope' ? uniqueSorted(groupIds) : [];+ const dirty = Boolean(+ resource+ && (+ resource.access.access_level !== level+ || uniqueSorted(resource.access.group_ids).join('\u0000') !== targetGroupIds.join('\u0000')+ )+ );+ const localMutationAllowed = Boolean(+ permissions+ && !permissions.offline+ && permissions.projection.instance.local_mutation_allowed+ && permissions.projection.capabilities.includes('instance.permissions.mutate')+ );+ const editable = canManageInstance+ && localMutationAllowed+ && gate !== 'loading'+ && !saving;+ const invalid = level === 'scope' && targetGroupIds.length === 0;++ const save = async () => {+ if (!resource || !instanceId || !dirty || invalid || !editable) return;+ const generation = generationRef.current;+ const requestSessionId = sessionId;+ const draft = draftRef.current;+ setSaving(true);+ setErrorCode(null);+ try {+ const result = await updateResourceAccess(+ { resource_kind: 'show_page', resource_id: requestSessionId },+ draft.level,+ draft.level === 'scope' ? uniqueSorted(draft.groupIds) : [],+ resource.access.revision,+ instanceId,+ );+ if (+ generation !== generationRef.current+ || requestSessionId !== sessionIdRef.current+ ) return;+ if (!resourceIdentityMatches(result.resource, requestSessionId, instanceId)) {+ throw new Error('Show Page Workspace identity mismatch');+ }+ adopt(result.resource, groups);+ setGate('ready');+ } catch (caught) {+ if (+ generation !== generationRef.current+ || requestSessionId !== sessionIdRef.current+ ) return;+ if (isRevisionConflict(caught)) {+ setSaving(false);+ await load('conflict', draft);+ return;+ }+ setErrorCode(caught instanceof PermissionsApiError ? caught.code : 'permissions_unavailable');+ setGate('error');+ } finally {+ if (+ generation === generationRef.current+ && requestSessionId === sessionIdRef.current+ ) setSaving(false);+ }+ };++ return (+ <section className="space-y-2.5" aria-label={t('chat.showPage.workspaceAccess')}>+ <div>+ <div className="text-sm font-medium">{t('chat.showPage.workspaceAccess')}</div>+ <p className="mt-0.5 text-[11px] leading-snug text-muted">+ {t('chat.showPage.workspaceAccessDesc')}+ </p>+ </div>++ {access?.mode === 'personal' || access?.mode === 'unmanaged' ? (+ <p className="text-[11px] leading-snug text-muted">+ {t(access.mode === 'personal'+ ? 'chat.showPage.workspacePersonal'+ : 'chat.showPage.workspaceUnmanaged')}+ </p>+ ) : access?.mode === 'organization_pending' ? (+ <div className="flex items-start gap-1.5 text-[11px] leading-snug text-gold-ink">+ <CloudOff className="mt-0.5 size-3.5 shrink-0" />+ {t('chat.showPage.workspacePending')}+ </div>+ ) : ownershipConflict ? (+ <div className="flex items-start gap-1.5 text-[11px] leading-snug text-destructive-ink">+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />+ {t('chat.showPage.workspaceOwnershipConflict')}+ </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.loadingWorkspaceAccess')}+ </div>+ ) : resource ? (+ <>+ <SegmentedRadio<ResourceAccessLevel>+ value={level}+ onChange={(next) => {+ if (!editable) return;+ setLevel(next);+ }}+ disabled={!editable}+ ariaLabel={t('chat.showPage.workspaceAccess')}+ tone="muted"+ options={[+ { id: 'private', label: t('chat.showPage.workspaceModes.private') },+ { id: 'public', label: t('chat.showPage.workspaceModes.organization') },+ { id: 'scope', label: t('chat.showPage.workspaceModes.scope') },+ ]}+ />+ <p className="text-[11px] leading-snug text-muted">+ {t(`chat.showPage.workspaceHelp.${level}`)}+ </p>++ {level === 'scope' ? (+ <div className="space-y-1" aria-label={t('chat.showPage.workspaceGroups')}>+ {visibleGroups.length ? visibleGroups.map((group) => {+ const checked = groupIds.includes(group.id);+ const archived = group.archived_at !== null;+ return (+ <div+ key={group.id}+ className="flex min-h-8 items-center gap-2 rounded-md px-1.5 py-1 text-xs"+ >+ <Checkbox+ checked={checked}+ disabled={!editable || archived}+ onCheckedChange={(next) => {+ if (!editable || archived) return;+ setGroupIds((current) => uniqueSorted(+ next+ ? [...current, group.id]+ : current.filter((value) => value !== group.id),+ ));+ }}+ label={group.name}+ />+ <span className="min-w-0 flex-1 truncate">{group.name}</span>+ {archived ? (+ <span className="shrink-0 text-[10px] text-muted">+ {t('chat.showPage.workspaceArchived')}+ </span>+ ) : null}+ </div>+ );+ }) : (+ <p className="text-[11px] text-muted">{t('chat.showPage.workspaceNoGroups')}</p>+ )}+ {invalid ? (+ <p className="text-[11px] text-gold-ink">+ {t('chat.showPage.workspaceGroupRequired')}+ </p>+ ) : null}+ </div>+ ) : null}++ {gate === 'conflict' ? (+ <div className="flex items-start gap-1.5 text-[11px] leading-snug text-gold-ink">+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />+ {t('chat.showPage.workspaceRevisionConflict')}+ </div>+ ) : null}+ {!localMutationAllowed ? (+ <p className="text-[11px] leading-snug text-muted">+ {t(permissions?.offline+ ? 'chat.showPage.workspaceOffline'+ : 'chat.showPage.workspaceReadOnly')}+ </p>+ ) : !canManageInstance ? (+ <p className="text-[11px] leading-snug text-muted">+ {t('chat.showPage.workspaceOwnerOnly')}+ </p>+ ) : null}+ {resource.sync.status !== 'in_sync' ? (+ <p className="text-[11px] leading-snug text-muted">+ {t(`chat.showPage.workspaceSync.${resource.sync.status}`)}+ </p>+ ) : null}+ <div className="flex justify-end">+ <Button+ type="button"+ size="sm"+ className="h-7"+ disabled={!dirty || invalid || !editable}+ onClick={() => void save()}+ >+ {saving ? <Loader2 className="size-3.5 animate-spin" /> : <Save className="size-3.5" />}+ {t('chat.showPage.applyWorkspaceAccess')}+ </Button>+ </div>+ </>+ ) : null}++ {gate === 'error' ? (+ <div className="flex items-start justify-between gap-2 text-[11px] leading-snug text-destructive-ink">+ <span>{t(`permissions.errors.${errorCode}`, {+ defaultValue: t('chat.showPage.workspaceLoadError'),+ })}</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}+ </section>+ );+}diff --git a/ui/src/features/permissions/api.ts b/ui/src/features/permissions/api.tsindex 1edd9c6d8..1a5c9baf1 100644--- a/ui/src/features/permissions/api.ts+++ b/ui/src/features/permissions/api.ts@@ -4,10 +4,13 @@ import type {AccessEntry,AuthorizedUsersWriteResponse,PermissionProject,+ PermissionResource,PermissionsErrorPayload,PermissionsResponse,ProjectAccessWriteResponse,ProjectBinding,+ ResourceAccessResponse,+ ResourceAccessWriteResponse,} from './types';export class PermissionsApiError extends Error {@@ -87,6 +90,31 @@ export const updateProjectAccess = (},);+export const getResourceAccess = (+ resource: Pick<PermissionResource, 'resource_kind' | 'resource_id'>,+): Promise<ResourceAccessResponse> => permissionsRequest(+ `/api/permissions/resources/${encodeURIComponent(resource.resource_kind)}/${encodeURIComponent(resource.resource_id)}/access`,+);++export const updateResourceAccess = (+ resource: Pick<PermissionResource, 'resource_kind' | 'resource_id'>,+ accessLevel: PermissionResource['access']['access_level'],+ groupIds: string[],+ revision: number,+ instanceId: string,+): Promise<ResourceAccessWriteResponse> => permissionsRequest(+ `/api/permissions/resources/${encodeURIComponent(resource.resource_kind)}/${encodeURIComponent(resource.resource_id)}/access`,+ {+ method: 'PUT',+ body: JSON.stringify({+ access_level: accessLevel,+ group_ids: groupIds,+ if_match_revision: revision,+ if_match_instance_id: instanceId,+ }),+ },+);+export const isRevisionConflict = (error: unknown): error is PermissionsApiError => (error instanceof PermissionsApiError&& error.status === 409diff --git a/ui/src/features/permissions/types.ts b/ui/src/features/permissions/types.tsindex 868b2141f..105d1f35a 100644--- a/ui/src/features/permissions/types.ts+++ b/ui/src/features/permissions/types.ts@@ -2,6 +2,7 @@ export type AccessRole = 'viewer' | 'editor';export type PrincipalKind = 'email' | 'email_domain' | 'organization_group';export type ProjectSyncStatus = 'in_sync' | 'pending' | 'offline' | 'error' | 'deleted';export type ResourceAccessLevel = 'public' | 'scope' | 'private';+export type ResourceSyncStatus = 'in_sync' | 'pending' | 'offline' | 'error';export type AccessEntry = {kind: PrincipalKind;@@ -105,6 +106,35 @@ export type ProjectAccessWriteResponse = {authorization_revision: number;};+export type PermissionResource = {+ instance_id: string;+ resource_kind: 'agent' | 'vault_secret' | 'skill' | 'show_page';+ resource_id: string;+ display_name: string;+ owner_user_id: string | null;+ access: {+ access_level: ResourceAccessLevel;+ group_ids: string[];+ revision: number;+ };+ sync: {+ status: ResourceSyncStatus;+ desired_acl_revision: number;+ applied_acl_revision: number;+ last_synced_at: string | null;+ last_sync_error?: string;+ };+};++export type ResourceAccessResponse = {+ resource: PermissionResource;+};++export type ResourceAccessWriteResponse = {+ ok: true;+ resource: PermissionResource;+};+export type PermissionsErrorPayload = {error?: string;current_revision?: number;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 029d7916e..0277ca4b1 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3548,6 +3548,38 @@"sharingAccess": "Link access","sharingAccessDesc": "Controls the shared /p link independently from Workspace access.","loadingSharingAccess": "Loading link access…",+ "workspaceAccess": "Workspace access",+ "workspaceAccessDesc": "Controls authenticated access inside this Avibe. Link access remains separate.",+ "loadingWorkspaceAccess": "Loading Workspace access…",+ "workspacePersonal": "This Show Page belongs to a Personal Avibe.",+ "workspaceUnmanaged": "Workspace access is unavailable until this Avibe is paired.",+ "workspacePending": "Organization ownership is known, but its exact binding is temporarily unavailable. Access remains private.",+ "workspaceOwnershipConflict": "This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.",+ "workspaceModes": {+ "private": "Private",+ "organization": "Organization",+ "scope": "Selected groups"+ },+ "workspaceHelp": {+ "private": "Only the page owner and Instance Owner can use it.",+ "public": "Authenticated members of this Organization can use it.",+ "scope": "Only members of the selected Organization groups can use it."+ },+ "workspaceGroups": "Organization groups",+ "workspaceArchived": "Archived",+ "workspaceNoGroups": "No active groups are available.",+ "workspaceGroupRequired": "Select at least one group.",+ "workspaceRevisionConflict": "Workspace access changed elsewhere. Your draft was kept on the latest revision.",+ "workspaceOffline": "The last known policy is shown while Permissions is offline. Editing is disabled.",+ "workspaceReadOnly": "Avibe Cloud owns this policy. Edit it in Avibe Cloud.",+ "workspaceOwnerOnly": "Only the Instance Owner can change Workspace access.",+ "workspaceLoadError": "Workspace access could not be loaded.",+ "applyWorkspaceAccess": "Apply",+ "workspaceSync": {+ "pending": "The policy is waiting for this Avibe to apply it.",+ "offline": "This Avibe has not acknowledged the latest policy.",+ "error": "The latest policy could not be applied."+ },"sharingModes": {"private": "Private","limited": "Limited",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ef0497a18..f27aae0bd 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3548,6 +3548,38 @@"sharingAccess": "链接访问","sharingAccessDesc": "独立控制分享链接 /p,不改变 Workspace 权限。","loadingSharingAccess": "正在加载链接访问设置…",+ "workspaceAccess": "Workspace 访问",+ "workspaceAccessDesc": "控制此 Avibe 内的已登录访问;与链接访问相互独立。",+ "loadingWorkspaceAccess": "正在加载 Workspace 访问设置…",+ "workspacePersonal": "此 Show Page 属于 Personal Avibe。",+ "workspaceUnmanaged": "此 Avibe 配对后才能使用 Workspace 访问。",+ "workspacePending": "已知此 Avibe 属于 Organization,但暂时无法取得精确绑定;访问保持私有。",+ "workspaceOwnershipConflict": "此 Show Page 绑定到了其他所有权域;解决冲突前访问保持私有。",+ "workspaceModes": {+ "private": "私有",+ "organization": "Organization",+ "scope": "指定群组"+ },+ "workspaceHelp": {+ "private": "只有页面所有者和 Instance Owner 可以使用。",+ "public": "此 Organization 的已登录成员可以使用。",+ "scope": "只有所选 Organization 群组的成员可以使用。"+ },+ "workspaceGroups": "Organization 群组",+ "workspaceArchived": "已归档",+ "workspaceNoGroups": "暂无可选的活跃群组。",+ "workspaceGroupRequired": "请至少选择一个群组。",+ "workspaceRevisionConflict": "Workspace 访问已在其他位置更新;你的草稿已保留到最新版本。",+ "workspaceOffline": "Permissions 离线时显示上次已知策略,暂不可编辑。",+ "workspaceReadOnly": "此策略由 Avibe Cloud 管理,请前往 Avibe Cloud 修改。",+ "workspaceOwnerOnly": "只有 Instance Owner 可以修改 Workspace 访问。",+ "workspaceLoadError": "无法加载 Workspace 访问设置。",+ "applyWorkspaceAccess": "应用",+ "workspaceSync": {+ "pending": "策略正在等待此 Avibe 应用。",+ "offline": "此 Avibe 尚未确认最新策略。",+ "error": "无法应用最新策略。"+ },"sharingModes": {"private": "私有","limited": "指定用户",diff --git a/ui/src/lib/showPageAccess.test.ts b/ui/src/lib/showPageAccess.test.tsindex 8c001d1eb..bcb9fff06 100644--- a/ui/src/lib/showPageAccess.test.ts+++ b/ui/src/lib/showPageAccess.test.ts@@ -16,8 +16,10 @@ import {const access = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess => ({ok: true,mode: 'organization',+ ownership_status: 'unchanged',instance_id: 'inst-1',organization_id: 'org-1',+ policy_organization_id: 'org-1',access_level: 'private',group_ids: [],policy_revision: 4,diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.tsindex 76636166e..6c4fa53ad 100644--- a/ui/src/lib/showPageAccess.ts+++ b/ui/src/lib/showPageAccess.ts@@ -1,9 +1,11 @@import type { ResourceAccessLevel } from '@/features/permissions/types';export type ShowPageAccess = {ok: true;- mode: 'personal' | 'organization';+ mode: 'unmanaged' | 'personal' | 'organization' | 'organization_pending';+ ownership_status: 'unmanaged' | 'created' | 'adopted' | 'unchanged' | 'pending' | 'conflict';instance_id: string | null;organization_id: string | null;+ policy_organization_id: string | null;access_level: ResourceAccessLevel;group_ids: string[];policy_revision: number | null;@@ -86,7 +88,13 @@ function isShowPageAccess(value: unknown): value is ShowPageAccess {if (!value || typeof value !== 'object') return false;const candidate = value as Partial<ShowPageAccess>;return candidate.ok === true- && (candidate.mode === 'personal' || candidate.mode === 'organization')+ && (+ candidate.mode === 'unmanaged'+ || candidate.mode === 'personal'+ || candidate.mode === 'organization'+ || candidate.mode === 'organization_pending'+ )+ && typeof candidate.ownership_status === 'string'&& typeof candidate.can_use === 'boolean'&& typeof candidate.can_manage === 'boolean'&& typeof candidate.can_publish_public === 'boolean';diff --git a/vibe/api.py b/vibe/api.pyindex acc2b0270..3ab8aa5ee 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1688,12 +1688,12 @@ def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:page = store.get(session_id)if page is None:raise ShowPageError("This session has no Show Page.", code="show_page_not_found")+ reconciliation = store.reconcile_resource_policy(+ page.session_id,+ user_context=context,+ )with store.engine.connect() as connection:- policy = resource_access_service.get_resource_policy(- "show_page",- page.session_id,- connection=connection,- )+ policy = reconciliation["policy"]can_use = resource_access_service.can_use_resource(context,"show_page",@@ -1716,15 +1716,16 @@ def get_show_page_access(session_id: str, *, user_context: Any = None) -> dict:finally:store.close()- organization_id = policy.get("organization_id") if policy else None- instance_id = context.instance_id- if context.is_instance_owner and organization_id and not instance_id:- instance_id = V2Config.load().remote_access.vibe_cloud.instance_id or None+ ownership = reconciliation["ownership"]+ organization_id = ownership.get("organization_id")+ policy_organization_id = policy.get("organization_id") if policy else Nonereturn {"ok": True,- "mode": "organization" if organization_id else "personal",- "instance_id": instance_id,+ "mode": ownership["mode"],+ "ownership_status": reconciliation["status"],+ "instance_id": ownership.get("instance_id"),"organization_id": organization_id,+ "policy_organization_id": policy_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,diff --git a/vibe/authorization.py b/vibe/authorization.pyindex 5d2388e03..69e455650 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -346,6 +346,7 @@ _VIEWER_HTTP_RULES = tuple(r"^/api/org/(?:context|groups)$",r"^/api/resource-policies$",r"^/api/permissions$",+ r"^/api/permissions/resources/[^/]+/[^/]+/access$",r"^/api/show-pages$",r"^/api/show-pages/[^/]+/access$",r"^/api/show-pages/[^/]+/icon$",diff --git a/vibe/permissions.py b/vibe/permissions.pyindex e20cbf3d3..c01420b38 100644--- a/vibe/permissions.py+++ b/vibe/permissions.py@@ -32,6 +32,9 @@ _ACCESS_ROLES = frozenset({"viewer", "editor"})_ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})_PROJECT_ACCESS_MODES = frozenset({"inherit", "restricted"})_PROJECT_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error", "deleted"})+_RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill", "show_page"})+_RESOURCE_ACCESS_LEVELS = frozenset({"private", "public", "scope"})+_RESOURCE_SYNC_STATUSES = frozenset({"in_sync", "pending", "offline", "error"})_POLICY_SYNC_STATUSES = frozenset({"none", "in_sync", "applying", "offline", "error"})_SYNC_COUNT_KEYS = ("active", "error", "offline", "applying", "in_sync")_PROJECT_ID_PATH_SEPARATORS = frozenset({"/", "\\"})@@ -175,6 +178,19 @@ def _require_project_id(value: Any) -> None:_invalid_response()+def _require_resource_identity(resource_kind: Any, resource_id: Any) -> tuple[str, str]:+ _require_enum(resource_kind, _RESOURCE_KINDS)+ if (+ not isinstance(resource_id, str)+ or resource_id != resource_id.strip()+ or not resource_id+ or len(resource_id) > 200+ or any(ord(char) < 32 or ord(char) == 127 for char in resource_id)+ ):+ raise PermissionsInvalidResponseError("invalid_resource_id")+ return resource_kind, resource_id++def _require_enum(value: Any, allowed: frozenset[str]) -> None:if not isinstance(value, str) or value not in allowed:_invalid_response()@@ -360,6 +376,88 @@ def _validated_project_result(payload: Any, project_id: str) -> dict[str, Any]:return result+def _validate_resource(+ value: Any,+ *,+ instance_id: str,+ resource_kind: str,+ resource_id: str,+) -> dict[str, Any]:+ resource = _require_mapping(value)+ _require_keys(+ resource,+ "instance_id",+ "resource_kind",+ "resource_id",+ "display_name",+ "owner_user_id",+ "access",+ "sync",+ )+ if (+ resource["instance_id"] != instance_id+ or resource["resource_kind"] != resource_kind+ or resource["resource_id"] != resource_id+ ):+ raise PermissionsInvalidResponseError("permissions_resource_mismatch")+ _require_string(resource["display_name"])+ _require_nonempty_string(resource["owner_user_id"], nullable=True)++ access = _require_mapping(resource["access"])+ _require_keys(access, "access_level", "group_ids", "revision")+ _require_enum(access["access_level"], _RESOURCE_ACCESS_LEVELS)+ group_ids = _require_list(access["group_ids"])+ for group_id in group_ids:+ _require_nonempty_string(group_id)+ if len(group_ids) != len(set(group_ids)):+ _invalid_response()+ if access["access_level"] == "scope":+ if not group_ids:+ _invalid_response()+ elif group_ids:+ _invalid_response()+ _require_nonnegative_integer(access["revision"])++ sync = _require_mapping(resource["sync"])+ _require_keys(+ sync,+ "status",+ "desired_acl_revision",+ "applied_acl_revision",+ "last_synced_at",+ )+ _require_enum(sync["status"], _RESOURCE_SYNC_STATUSES)+ _require_nonnegative_integer(sync["desired_acl_revision"])+ _require_nonnegative_integer(sync["applied_acl_revision"])+ _require_string(sync["last_synced_at"], nullable=True)+ if "last_sync_error" in sync:+ _require_string(sync["last_sync_error"])+ return resource+++def _validated_resource_result(+ payload: Any,+ *,+ instance_id: str,+ resource_kind: str,+ resource_id: str,+ mutation: bool,+) -> dict[str, Any]:+ result = _require_mapping(_strip_sensitive(payload))+ _require_keys(result, "resource")+ if mutation:+ _require_keys(result, "ok")+ if result["ok"] is not True:+ _invalid_response()+ result["resource"] = _validate_resource(+ result["resource"],+ instance_id=instance_id,+ resource_kind=resource_kind,+ resource_id=resource_id,+ )+ return result++def _runtime_credentials(config: V2Config) -> tuple[str, str, str]:credentials = config.remote_access.vibe_cloud.runtime_credentials()if credentials is None:@@ -643,6 +741,100 @@ def update_project_access(return {**result, "instance_id": instance_id}+def get_resource_access(+ resource_kind: str,+ resource_id: str,+ config: V2Config | None = None,+) -> dict[str, Any]:+ resource_kind, resource_id = _require_resource_identity(resource_kind, resource_id)+ config, load_current_config = _request_config(config)+ payload_result, instance_id = _backend_request(+ config,+ load_current_config,+ "GET",+ f"resources/{quote(resource_kind, safe='')}/{quote(resource_id, safe='')}/access",+ )+ return _validated_resource_result(+ payload_result,+ instance_id=instance_id,+ resource_kind=resource_kind,+ resource_id=resource_id,+ mutation=False,+ )+++def update_resource_access(+ resource_kind: str,+ resource_id: str,+ payload: Mapping[str, Any],+ config: V2Config | None = None,+) -> dict[str, Any]:+ resource_kind, resource_id = _require_resource_identity(resource_kind, resource_id)+ config, load_current_config = _request_config(config)+ expected_instance_id, backend_payload = _mutation_payload(payload)+ payload_result, instance_id = _backend_request(+ config,+ load_current_config,+ "PUT",+ f"resources/{quote(resource_kind, safe='')}/{quote(resource_id, safe='')}/access",+ backend_payload,+ expected_instance_id=expected_instance_id,+ )+ return _validated_resource_result(+ payload_result,+ instance_id=instance_id,+ resource_kind=resource_kind,+ resource_id=resource_id,+ mutation=True,+ )+++def resolve_current_instance_ownership(+ config: V2Config | None = None,+) -> dict[str, Any]:+ """Resolve exact-instance ownership without trusting browser claims."""++ from storage import resource_access_service++ try:+ config = config or V2Config.load()+ credentials = config.remote_access.vibe_cloud.runtime_credentials()+ except (FileNotFoundError, OSError, TypeError, ValueError):+ credentials = None+ if credentials is None:+ return {+ "mode": "unmanaged",+ "instance_id": None,+ "organization_id": None,+ "source": "config",+ }++ current = resource_access_service.current_show_page_instance_ownership()+ if current["mode"] in {"personal", "organization"}:+ return current+ try:+ result = get_current_permissions(config)+ except PermissionsError:+ return current+ instance = result.projection["instance"]+ organization = instance.get("organization")+ if isinstance(organization, Mapping):+ return {+ "mode": "organization",+ "instance_id": credentials[1],+ "organization_id": organization["id"],+ "source": result.source,+ }+ if "organization" in instance or config.remote_access.vibe_cloud.instance_kind == "personal":+ return {+ "mode": "personal",+ "instance_id": credentials[1],+ "organization_id": None,+ "source": result.source,+ }+ return current++def _local_instance_display(config: V2Config,instance_id: str,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex ebd0b5b37..01d3df5de 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2674,6 +2674,35 @@ def _permissions_mutation_payload(return payload+def _resource_access_mutation_payload(payload: Any):+ if not isinstance(payload, dict) or set(payload) != {+ "access_level",+ "group_ids",+ "if_match_revision",+ "if_match_instance_id",+ }:+ return None+ access_level = payload.get("access_level")+ group_ids = payload.get("group_ids")+ revision = payload.get("if_match_revision")+ instance_id = payload.get("if_match_instance_id")+ if (+ access_level not in {"private", "public", "scope"}+ or not isinstance(group_ids, list)+ or any(not isinstance(group_id, str) or not group_id.strip() for group_id in group_ids)+ or len(group_ids) != len(set(group_ids))+ or not isinstance(revision, int)+ or isinstance(revision, bool)+ or revision < 0+ or not isinstance(instance_id, str)+ or not instance_id+ ):+ return None+ if (access_level == "scope") != bool(group_ids):+ return None+ return payload++@app.get("/api/permissions", include_in_schema=False)async def current_instance_permissions_get(starlette_request: FastAPIRequest):async def handler():@@ -2764,6 +2793,73 @@ async def current_instance_permissions_project_access_put(return await _dispatch_native_ui_request(starlette_request, handler)+ "/api/permissions/resources/{resource_kind}/{resource_id}/access",+ include_in_schema=False,+)+async def current_instance_permissions_resource_access_get(+ resource_kind: str,+ resource_id: str,+ starlette_request: FastAPIRequest,+):+ async def handler():+ from vibe import permissions++ authorization_context = getattr(g, "authorization_context", None)+ if authorization_context is None or not authorization_context.can_read_instance:+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403+ try:+ result = await asyncio.to_thread(+ permissions.get_resource_access,+ resource_kind,+ resource_id,+ )+ response = jsonify(result)+ response.headers["Cache-Control"] = "private, no-store"+ return response+ except Exception as error:+ return _permissions_error_response(error)++ return await _dispatch_native_ui_request(starlette_request, handler)+++ "/api/permissions/resources/{resource_kind}/{resource_id}/access",+ include_in_schema=False,+)+async def current_instance_permissions_resource_access_put(+ resource_kind: str,+ resource_id: str,+ starlette_request: FastAPIRequest,+):+ async def handler():+ from vibe import permissions++ authorization_context = getattr(g, "authorization_context", None)+ if authorization_context is None or not authorization_context.can_manage_instance:+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403+ try:+ body = await starlette_request.body()+ raw_payload = await starlette_request.json() if body else None+ except (json.JSONDecodeError, UnicodeDecodeError):+ raw_payload = None+ payload = _resource_access_mutation_payload(raw_payload)+ if payload is None:+ return jsonify({"ok": False, "error": "invalid_request"}), 422+ try:+ result = await asyncio.to_thread(+ permissions.update_resource_access,+ resource_kind,+ resource_id,+ payload,+ )+ return jsonify(result)+ except Exception as error:+ return _permissions_error_response(error)++ return await _dispatch_native_ui_request(starlette_request, handler)++_PROJECT_RESOURCE_PATHS = (("project", re.compile(r"^/api/projects/([^/]+)(?:/agents-md)?$")),("session", re.compile(r"^/api/sessions/([^/]+)(?:/.*)?$")),