Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(permissions): preserve authority and cache progress

Maxe1de9c7c8221
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index ef7baa976..1b12aa17e 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -33,10 +33,18 @@ 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_CONFIGURATION_UNAVAILABLE = "configuration_unavailable"
_SHOW_PAGE_OWNERSHIP_MODES = frozenset(
- {"unmanaged", "personal", "organization", "organization_pending"}
+ {
+ "unmanaged",
+ "personal",
+ "organization",
+ "organization_pending",
+ SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ }
)
+_CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE = object()
class ResourceAccessError(ValueError):
@@ -316,17 +324,39 @@ def _connection(connection: Connection | None) -> Iterator[Connection]:
yield active_connection
-def _configured_show_page_instance() -> tuple[str, str] | None:
+def _configured_show_page_instance() -> tuple[str, str] | None | object:
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
+ if credentials is None:
+ return None
+ if not isinstance(credentials, (tuple, list)) or len(credentials) != 3:
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ instance_id = _clean_optional_string(credentials[1])
+ if instance_id is None or cloud.instance_kind not in {"personal", "organization"}:
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ except (
+ AttributeError,
+ FileNotFoundError,
+ IndexError,
+ KeyError,
+ OSError,
+ TypeError,
+ ValueError,
+ ):
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ return instance_id, cloud.instance_kind
+
+
+def _configuration_unavailable_ownership() -> dict[str, Any]:
+ return {
+ "mode": SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ "instance_id": None,
+ "organization_id": None,
+ "source": "config",
+ }
def _stored_show_page_instance_ownership(connection: Connection) -> dict[str, Any] | None:
@@ -365,6 +395,8 @@ def current_show_page_instance_ownership(
"""Return the persisted ownership fence for the exact current pairing."""
configured = _configured_show_page_instance()
+ if configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE:
+ return _configuration_unavailable_ownership()
if configured is None:
return {
"mode": "unmanaged",
@@ -414,6 +446,7 @@ def remember_show_page_instance_ownership(
organization_id = _clean_optional_string(ownership.get("organization_id"))
if (
configured is None
+ or configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
or instance_id != configured[0]
or mode not in {"personal", "organization"}
or (mode == "organization") != bool(organization_id)
@@ -466,6 +499,8 @@ def reconcile_show_page_resource_policy(
status = "unmanaged"
elif mode == "organization_pending":
status = "pending"
+ elif mode == SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE:
+ status = SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE
elif mode == "personal":
if policy is None:
policy = ensure_resource_policy(
@@ -530,7 +565,10 @@ def _show_page_policy_matches_instance_ownership(
mode = ownership.get("mode")
if mode == "unmanaged":
return True
- if mode == "organization_pending":
+ if mode in {
+ "organization_pending",
+ SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ }:
return False
policy_organization = _clean_optional_string(
policy.get("organization_id") if policy else None
@@ -804,6 +842,13 @@ def _policy_allows(
if resource_kind in {"skill", "vault_secret"}:
if context.is_remote and context.is_active_organization_member and context.has_role("editor"):
return True
+ if (
+ resource_kind == "show_page"
+ and show_page_ownership is not None
+ and show_page_ownership.get("mode")
+ == SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE
+ ):
+ return False
if resource_kind == "show_page" and context.can_use_show_page(resource_id):
return True
if (
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index 3ee2443cf..d8ecb1a1b 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -54,17 +54,38 @@ def _cache_projection_process(
original_write = permissions._write_cache # noqa: SLF001
if entered_write is not None:
- def delayed_write(instance_id: str, candidate: dict[str, Any]) -> None:
+ def delayed_write(
+ instance_id: str,
+ candidate: dict[str, Any],
+ *,
+ cache_order: int = 0,
+ ) -> None:
entered_write.set()
if not release_write.wait(10):
raise TimeoutError("cache write was not released")
- original_write(instance_id, candidate)
+ original_write(instance_id, candidate, cache_order=cache_order)
permissions._write_cache = delayed_write # noqa: SLF001
permissions._cache_projection("inst-123", projection) # noqa: SLF001
+def _delayed_cache_projection_process(
+ projection: dict[str, Any],
+ request_order: int,
+ ready,
+ release,
+) -> None:
+ ready.set()
+ if not release.wait(10):
+ raise TimeoutError("cache response was not released")
+ permissions._cache_projection( # noqa: SLF001
+ "inst-123",
+ projection,
+ request_order=request_order,
+ )
+
+
def _cache_mutation_rebase_process(
access_entries: list[dict[str, str]],
entered_lock,
@@ -645,6 +666,97 @@ def test_permissions_cache_revision_is_monotonic_across_processes() -> None:
assert cached.projection["instance"]["authorization_revision"] == 4
+def test_permissions_cache_equal_revision_retains_the_newest_complete_projection() -> None:
+ stale = _complete_projection()
+ stale["directory"]["members"][0]["email"] = "[email protected]"
+ stale["projects"][0]["display_name"] = "Stale Project"
+ stale["projects"][0]["access"]["revision"] = 3
+ stale["projects"][0]["sync"].update(
+ {
+ "status": "pending",
+ "desired_access_revision": 3,
+ "applied_access_revision": 2,
+ "last_synced_at": None,
+ }
+ )
+ stale["policy_sync"] = {
+ "status": "applying",
+ "projects": {"active": 1, "error": 0, "offline": 0, "applying": 1, "in_sync": 0},
+ "resources": {"active": 1, "error": 0, "offline": 0, "applying": 1, "in_sync": 0},
+ }
+ stale_cycle = deepcopy(stale["projects"][0])
+ stale_cycle["project_id"] = "project-cycle"
+ stale_cycle["display_name"] = "Stale Cycle"
+ stale_cycle["access"]["revision"] = 2
+ stale_cycle["sync"].update(
+ {
+ "status": "in_sync",
+ "desired_access_revision": 2,
+ "applied_access_revision": 2,
+ "last_synced_at": "2026-08-18T09:00:00.000Z",
+ }
+ )
+ stale["projects"].append(stale_cycle)
+ fresh = deepcopy(stale)
+ fresh["directory"]["members"][0]["email"] = "[email protected]"
+ fresh["projects"][0]["display_name"] = "Fresh Project"
+ fresh["projects"][0]["sync"].update(
+ {
+ "status": "in_sync",
+ "applied_access_revision": 3,
+ "last_synced_at": "2026-08-18T10:00:00.000Z",
+ }
+ )
+ fresh_cycle = fresh["projects"][1]
+ fresh_cycle["display_name"] = "Fresh Cycle"
+ fresh_cycle["access"]["revision"] = 3
+ fresh_cycle["sync"].update(
+ {
+ "status": "pending",
+ "desired_access_revision": 3,
+ "applied_access_revision": 2,
+ }
+ )
+ fresh["policy_sync"] = {
+ "status": "in_sync",
+ "projects": {"active": 1, "error": 0, "offline": 0, "applying": 0, "in_sync": 1},
+ "resources": {"active": 1, "error": 0, "offline": 0, "applying": 0, "in_sync": 1},
+ }
+ stale_order = permissions._cache_allocate_order("inst-123") # noqa: SLF001
+ fresh_order = permissions._cache_allocate_order("inst-123") # noqa: SLF001
+ context = mp.get_context("spawn")
+ ready = context.Event()
+ release = context.Event()
+ stale_writer = context.Process(
+ target=_delayed_cache_projection_process,
+ args=(stale, stale_order, ready, release),
+ )
+
+ try:
+ stale_writer.start()
+ assert ready.wait(10)
+ permissions._cache_projection( # noqa: SLF001
+ "inst-123",
+ fresh,
+ request_order=fresh_order,
+ )
+ release.set()
+ stale_writer.join(10)
+ assert stale_writer.exitcode == 0
+ finally:
+ release.set()
+ if stale_writer.is_alive():
+ stale_writer.terminate()
+ stale_writer.join(5)
+
+ cached = permissions._read_cache("inst-123") # noqa: SLF001
+ assert cached is not None
+ assert cached.cache_order == fresh_order
+ assert cached.projection["directory"] == fresh["directory"]
+ assert cached.projection["projects"] == fresh["projects"]
+ assert cached.projection["policy_sync"] == fresh["policy_sync"]
+
+
def test_permissions_cache_mutation_rebase_reads_complete_equal_revision_projection() -> None:
base = _complete_projection()
complete = deepcopy(base)
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index b3c37760e..f32134312 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -2,9 +2,11 @@ from __future__ import annotations
import pytest
+from config.v2_config import V2Config
from storage import resource_access_service
from storage.db import create_sqlite_engine
from storage.migrations import run_migrations
+from vibe import permissions
def _context(
@@ -84,6 +86,150 @@ def test_resource_acl_is_enforced_for_editors_and_unknown_kinds_fail_closed(tmp_
engine.dispose()
+ "load_error",
+ [
+ pytest.param(OSError("config unavailable"), id="io-error"),
+ pytest.param(AttributeError("config shape unavailable"), id="attribute-error"),
+ pytest.param(TypeError("config shape unavailable"), id="type-error"),
+ pytest.param(ValueError("config value unavailable"), id="value-error"),
+ ],
+)
+def test_show_page_config_reload_failure_fails_closed_for_every_runtime_authorizer(
+ monkeypatch,
+ tmp_path,
+ load_error: Exception,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ legacy_owner = _context(
+ "legacy-owner",
+ organization_id=None,
+ role=None,
+ instance_role="editor",
+ access_source="email_invitation",
+ )
+ link_guest = resource_access_service.ResourceUserContext(
+ subject="link-guest",
+ instance_role="viewer",
+ instance_access_source="show_page_email",
+ show_page_id="legacy-page",
+ is_remote=True,
+ )
+ local_owner = resource_access_service.instance_owner_context()
+
+ def fail_load(_cls, *_args, **_kwargs):
+ raise load_error
+
+ try:
+ with engine.begin() as connection:
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="show_page",
+ resource_id="legacy-page",
+ organization_id=None,
+ owner_user_id="legacy-owner",
+ access_level="private",
+ )
+ monkeypatch.setattr(V2Config, "load", classmethod(fail_load))
+
+ resolved = permissions.resolve_current_instance_ownership()
+ assert resolved["mode"] == (
+ resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE
+ )
+
+ with engine.begin() as connection:
+ reconciliation = resource_access_service.reconcile_show_page_resource_policy(
+ connection,
+ resource_id="legacy-page",
+ ownership=resolved,
+ owner_user_id="legacy-owner",
+ )
+ assert reconciliation["status"] == (
+ resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE
+ )
+ assert reconciliation["policy"]["organization_id"] is None
+ assert reconciliation["policy"]["owner_user_id"] == "legacy-owner"
+
+ with engine.connect() as connection:
+ ownership = resource_access_service.current_show_page_instance_ownership(
+ connection=connection
+ )
+ assert ownership["mode"] == (
+ resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE
+ )
+ assert not resource_access_service.can_use_resource(
+ legacy_owner,
+ "show_page",
+ "legacy-page",
+ connection=connection,
+ )
+ assert not resource_access_service.can_manage_resource_acl(
+ legacy_owner,
+ "show_page",
+ "legacy-page",
+ connection=connection,
+ )
+ assert not resource_access_service.can_manage_show_page_access(
+ legacy_owner,
+ "legacy-page",
+ connection=connection,
+ )
+ assert not resource_access_service.can_control_resource_sharing(
+ legacy_owner,
+ "show_page",
+ "legacy-page",
+ connection=connection,
+ )
+ assert resource_access_service.filter_accessible_resources(
+ legacy_owner,
+ "show_page",
+ [{"session_id": "legacy-page"}],
+ connection=connection,
+ ) == []
+ assert not resource_access_service.can_use_resource(
+ link_guest,
+ "show_page",
+ "legacy-page",
+ connection=connection,
+ )
+ assert resource_access_service.can_use_resource(
+ local_owner,
+ "show_page",
+ "legacy-page",
+ connection=connection,
+ )
+ finally:
+ engine.dispose()
+
+
+def test_show_page_unpaired_configuration_remains_explicitly_unmanaged(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ V2Config.default().save()
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ with engine.connect() as connection:
+ ownership = resource_access_service.current_show_page_instance_ownership(
+ connection=connection
+ )
+ assert ownership == {
+ "mode": "unmanaged",
+ "instance_id": None,
+ "organization_id": None,
+ "source": "config",
+ }
+ finally:
+ engine.dispose()
+
+
@pytest.mark.parametrize(
("previous_level", "previous_groups", "updated_level", "updated_groups", "expected"),
[
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index 51a174f82..09e92adbf 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -4,6 +4,7 @@ import pytest
from sqlalchemy import select
from config import paths
+from config.v2_config import V2Config
from core.dock_store import BUILTIN_DOCK_IDS, DockError
from core.show_pages import ShowPageError, ShowPageStore
from storage import media_service, project_access_service, projects_service, resource_access_service
@@ -90,6 +91,8 @@ def _ownership(
def _seed_show_pages_with_policies() -> ShowPageStore:
+ if not paths.get_config_path().exists():
+ V2Config.default().save()
store = ShowPageStore()
for session_id in ("ses-private", "ses-public", "ses-scope"):
store.ensure(session_id)
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
index 65dc44b7d..62ff76834 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -36,6 +36,7 @@ const translations: Record<string, string> = {
'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.workspaceConfigurationUnavailable': 'Workspace access cannot be verified while Avibe configuration is 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',
@@ -106,11 +107,18 @@ const showPageAccess = (overrides: Partial<ShowPageAccess> = {}): ShowPageAccess
const permissions = ({
groups = [activeGroup],
+ members = [{
+ id: 'owner-1',
+ email: '[email protected]',
+ organization_role: 'owner' as const,
+ group_ids: [],
+ }],
offline = false,
permissionAuthority = 'instance',
localMutationAllowed = true,
}: {
groups?: DirectoryGroup[];
+ members?: PermissionsResponse['projection']['directory']['members'];
offline?: boolean;
permissionAuthority?: 'instance' | 'cloud';
localMutationAllowed?: boolean;
@@ -131,7 +139,7 @@ const permissions = ({
},
capabilities: ['instance.permissions.read', 'instance.permissions.mutate'],
access: { owner: { email: '[email protected]', role: 'owner' }, entries: [] },
- directory: { members: [], groups },
+ directory: { members, groups },
projects: [],
policy_sync: {
status: offline ? 'offline' : 'in_sync',
@@ -145,12 +153,14 @@ const resource = ({
sessionId = 'ses-1',
level = 'private',
groupIds = [],
+ ownerUserId = 'owner-1',
revision = 4,
status = 'in_sync',
}: {
sessionId?: string;
level?: PermissionResource['access']['access_level'];
groupIds?: string[];
+ ownerUserId?: string | null;
revision?: number;
status?: PermissionResource['sync']['status'];
} = {}): PermissionResource => ({
@@ -158,7 +168,7 @@ const resource = ({
resource_kind: 'show_page',
resource_id: sessionId,
display_name: sessionId,
- owner_user_id: 'owner-1',
+ owner_user_id: ownerUserId,
access: { access_level: level, group_ids: groupIds, revision },
sync: {
status,
@@ -214,7 +224,21 @@ describe('ShowPageWorkspaceAccessControl', () => {
)).toBe(true);
expect(requiresResourcePolicyNarrowing('scope', ['group-active'], 'public', [])).toBe(false);
expect(requiresResourcePolicyNarrowing('private', [], 'public', [])).toBe(false);
- expect(requiresResourcePolicyNarrowing('private', [], 'scope', ['group-active'])).toBe(false);
+ expect(requiresResourcePolicyNarrowing('private', [], 'scope', ['group-active'])).toBe(true);
+ expect(requiresResourcePolicyNarrowing(
+ 'private',
+ [],
+ 'scope',
+ ['group-active'],
+ { isInstanceOwner: true },
+ )).toBe(false);
+ expect(requiresResourcePolicyNarrowing(
+ 'private',
+ [],
+ 'scope',
+ ['group-active'],
+ { organizationGroupIds: ['group-active'] },
+ )).toBe(false);
});
it('confirms a Workspace policy reduction before sending it', async () => {
@@ -310,6 +334,29 @@ describe('ShowPageWorkspaceAccessControl', () => {
);
});
+ it('confirms private-to-scope when the resource owner is outside the selected groups', async () => {
+ api.getPermissions.mockResolvedValue(permissions({
+ members: [{
+ id: 'project-owner',
+ email: '[email protected]',
+ organization_role: 'member',
+ group_ids: ['group-other'],
+ }],
+ }));
+ api.getResourceAccess.mockResolvedValue({
+ resource: resource({ ownerUserId: 'project-owner' }),
+ });
+ 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(screen.getByText('Narrow Workspace access?')).toBeTruthy();
+ expect(api.updateResourceAccess).not.toHaveBeenCalled();
+ });
+
it('keeps bound archived groups visible and selected without offering unbound archived groups', async () => {
api.getPermissions.mockResolvedValue(permissions({
groups: [activeGroup, archivedGroup, newArchivedGroup],
@@ -471,7 +518,7 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(api.updateResourceAccess).toHaveBeenCalledOnce();
});
- it('fails closed for personal, pending, and conflicting ownership without contacting Permissions', () => {
+ it('fails closed for personal, pending, unavailable, and conflicting ownership without contacting Permissions', () => {
const personal = renderControl(showPageAccess({
mode: 'personal',
ownership_status: 'unchanged',
@@ -490,6 +537,16 @@ describe('ShowPageWorkspaceAccessControl', () => {
expect(screen.getByText(/temporarily unavailable/)).toBeTruthy();
pending.unmount();
+ const unavailable = renderControl(showPageAccess({
+ mode: 'configuration_unavailable',
+ ownership_status: 'configuration_unavailable',
+ instance_id: null,
+ organization_id: null,
+ policy_organization_id: null,
+ }));
+ expect(screen.getByText(/cannot be verified/)).toBeTruthy();
+ unavailable.unmount();
+
renderControl(showPageAccess({
ownership_status: 'conflict',
policy_organization_id: 'org-other',
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
index 16cf556c1..387bfb57b 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -170,6 +170,22 @@ export function ShowPageWorkspaceAccessControl({
return groups.filter((group) => group.archived_at === null || bound.has(group.id));
}, [groups, resource]);
const targetGroupIds = level === 'scope' ? uniqueSorted(groupIds) : [];
+ const ownerMember = useMemo(
+ () => permissions?.projection.directory.members.find(
+ (member) => member.id === resource?.owner_user_id,
+ ) ?? null,
+ [permissions, resource],
+ );
+ const ownerContext = useMemo(() => ({
+ isInstanceOwner: resource?.owner_user_id === null
+ || Boolean(
+ ownerMember
+ && permissions?.projection.access.owner.email
+ && ownerMember.email.trim().toLowerCase()
+ === permissions.projection.access.owner.email.trim().toLowerCase(),
+ ),
+ organizationGroupIds: ownerMember?.group_ids ?? null,
+ }), [ownerMember, permissions, resource]);
const dirty = Boolean(
resource
&& (
@@ -245,6 +261,7 @@ export function ShowPageWorkspaceAccessControl({
resource.access.group_ids,
draft.level,
draft.level === 'scope' ? uniqueSorted(draft.groupIds) : [],
+ ownerContext,
)) {
setConfirmNarrowing(true);
return;
@@ -265,7 +282,12 @@ export function ShowPageWorkspaceAccessControl({
</p>
</div>
- {access?.mode === 'personal' || access?.mode === 'unmanaged' ? (
+ {access?.mode === 'configuration_unavailable' ? (
+ <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.workspaceConfigurationUnavailable')}
+ </div>
+ ) : access?.mode === 'personal' || access?.mode === 'unmanaged' ? (
<p className="text-[11px] leading-snug text-muted">
{t(access.mode === 'personal'
? 'chat.showPage.workspacePersonal'
diff --git a/ui/src/features/permissions/policy.ts b/ui/src/features/permissions/policy.ts
index cb03de1ed..4120a4ba3 100644
--- a/ui/src/features/permissions/policy.ts
+++ b/ui/src/features/permissions/policy.ts
@@ -8,6 +8,11 @@ import type {
export type ProjectAccessMode = 'inherit' | 'owner_only' | 'restricted';
+export type ResourcePolicyOwnerContext = {
+ isInstanceOwner?: boolean;
+ organizationGroupIds?: string[] | null;
+};
+
export function normalizePrincipal(kind: PrincipalKind, value: string): string {
const normalized = value.trim();
if (kind === 'organization_group') return normalized;
@@ -73,9 +78,15 @@ export function requiresResourcePolicyNarrowing(
currentGroupIds: string[],
nextLevel: ResourceAccessLevel,
nextGroupIds: string[],
+ ownerContext: ResourcePolicyOwnerContext = {},
): boolean {
if (currentLevel === 'public') return nextLevel !== 'public';
- if (currentLevel === 'private') return false;
+ if (currentLevel === 'private') {
+ if (nextLevel !== 'scope') return false;
+ if (ownerContext.isInstanceOwner === true) return false;
+ const ownerGroups = ownerContext.organizationGroupIds;
+ return !ownerGroups?.some((groupId) => nextGroupIds.includes(groupId));
+ }
if (nextLevel === 'private') return true;
if (nextLevel === 'public') return false;
const nextGroups = new Set(nextGroupIds);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 803834e8e..f552c732b 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3575,6 +3575,7 @@
"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.",
+ "workspaceConfigurationUnavailable": "Workspace access cannot be verified while Avibe configuration is 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",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 64e3591cc..bb2598724 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3575,6 +3575,7 @@
"workspacePersonal": "此 Show Page 属于 Personal Avibe。",
"workspaceUnmanaged": "此 Avibe 配对后才能使用 Workspace 访问。",
"workspacePending": "已知此 Avibe 属于 Organization,但暂时无法取得精确绑定;访问保持私有。",
+ "workspaceConfigurationUnavailable": "Avibe 配置暂时不可用,无法验证 Workspace 访问;访问保持私有。",
"workspaceOwnershipConflict": "此 Show Page 绑定到了其他所有权域;解决冲突前访问保持私有。",
"workspaceModes": {
"private": "私有",
diff --git a/ui/src/lib/showPageAccess.ts b/ui/src/lib/showPageAccess.ts
index 6c4fa53ad..3f194bd13 100644
--- a/ui/src/lib/showPageAccess.ts
+++ b/ui/src/lib/showPageAccess.ts
@@ -1,8 +1,8 @@
import type { ResourceAccessLevel } from '@/features/permissions/types';
export type ShowPageAccess = {
ok: true;
- mode: 'unmanaged' | 'personal' | 'organization' | 'organization_pending';
- ownership_status: 'unmanaged' | 'created' | 'adopted' | 'unchanged' | 'pending' | 'conflict';
+ mode: 'unmanaged' | 'personal' | 'organization' | 'organization_pending' | 'configuration_unavailable';
+ ownership_status: 'unmanaged' | 'created' | 'adopted' | 'unchanged' | 'pending' | 'conflict' | 'configuration_unavailable';
instance_id: string | null;
organization_id: string | null;
policy_organization_id: string | null;
@@ -93,6 +93,7 @@ function isShowPageAccess(value: unknown): value is ShowPageAccess {
|| candidate.mode === 'personal'
|| candidate.mode === 'organization'
|| candidate.mode === 'organization_pending'
+ || candidate.mode === 'configuration_unavailable'
)
&& typeof candidate.ownership_status === 'string'
&& typeof candidate.can_use === 'boolean'
diff --git a/vibe/permissions.py b/vibe/permissions.py
index bda5902c8..72ae6ff66 100644
--- a/vibe/permissions.py
+++ b/vibe/permissions.py
@@ -21,6 +21,7 @@ from config.v2_config import V2Config
CACHE_SCHEMA_VERSION = 1
CACHE_FILENAME = "permissions_projection.json"
+CACHE_ORDER_FILENAME = "permissions_projection.order"
DEFAULT_TIMEOUT_SECONDS = 8.0
_SENSITIVE_KEY_PARTS = ("secret", "token", "credential")
_CACHE_FALLBACK_HTTP_STATUSES = frozenset({408, 425, 429})
@@ -39,6 +40,20 @@ _POLICY_SYNC_STATUSES = frozenset({"none", "in_sync", "applying", "offline", "er
_SYNC_COUNT_KEYS = ("active", "error", "offline", "applying", "in_sync")
_PROJECT_ID_PATH_SEPARATORS = frozenset({"/", "\\"})
_PROJECT_ID_DOT_SEGMENTS = frozenset({".", ".."})
+_POLICY_SYNC_PROGRESS = {
+ "none": 0,
+ "offline": 1,
+ "error": 1,
+ "applying": 2,
+ "in_sync": 3,
+}
+_PROJECT_SYNC_PROGRESS = {
+ "offline": 0,
+ "error": 0,
+ "pending": 1,
+ "in_sync": 2,
+ "deleted": 3,
+}
logger = logging.getLogger(__name__)
_CACHE_LOCK = threading.RLock()
@@ -75,6 +90,7 @@ class PermissionsProjectionResult:
projection: dict[str, Any]
source: str
cached_at: int | None = None
+ cache_order: int = 0
@property
def offline(self) -> bool:
@@ -530,6 +546,10 @@ def _cache_path() -> Path:
return paths.get_state_dir() / CACHE_FILENAME
+def _cache_order_path() -> Path:
+ return paths.get_state_dir() / CACHE_ORDER_FILENAME
+
+
def _cache_file_lock(path: Path):
"""Return the cross-process lock for projection read-compare-write updates."""
@@ -539,27 +559,20 @@ def _cache_file_lock(path: Path):
return MigrationFileLock(path.with_name(f".{path.stem}.lock"))
-def _write_cache(instance_id: str, projection: dict[str, Any]) -> None:
- cache_path = _cache_path()
- cache_path.parent.mkdir(parents=True, exist_ok=True)
- envelope = {
- "cache_schema_version": CACHE_SCHEMA_VERSION,
- "instance_id": instance_id,
- "cached_at": int(time.time()),
- "projection": projection,
- }
+def _atomic_write_json(path: Path, value: Any) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary_name = tempfile.mkstemp(
- dir=cache_path.parent,
- prefix=f".{cache_path.name}.",
+ dir=path.parent,
+ prefix=f".{path.name}.",
)
try:
# mkstemp creates the file owner-private without relying on Unix-only APIs.
with os.fdopen(fd, "w", encoding="utf-8") as handle:
fd = -1
- json.dump(envelope, handle, ensure_ascii=True, separators=(",", ":"))
+ json.dump(value, handle, ensure_ascii=True, separators=(",", ":"))
handle.flush()
os.fsync(handle.fileno())
- os.replace(temporary_name, cache_path)
+ os.replace(temporary_name, path)
finally:
if fd >= 0:
os.close(fd)
@@ -569,6 +582,24 @@ def _write_cache(instance_id: str, projection: dict[str, Any]) -> None:
pass
+def _write_cache(
+ instance_id: str,
+ projection: dict[str, Any],
+ *,
+ cache_order: int = 0,
+) -> None:
+ _atomic_write_json(
+ _cache_path(),
+ {
+ "cache_schema_version": CACHE_SCHEMA_VERSION,
+ "instance_id": instance_id,
+ "cached_at": int(time.time()),
+ "cache_order": cache_order,
+ "projection": projection,
+ },
+ )
+
+
def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:
try:
envelope = json.loads(_cache_path().read_text(encoding="utf-8"))
@@ -583,6 +614,9 @@ def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:
cached_at = envelope.get("cached_at")
if not isinstance(cached_at, int) or isinstance(cached_at, bool) or cached_at < 0:
return None
+ cache_order = envelope.get("cache_order", 0)
+ if not isinstance(cache_order, int) or isinstance(cache_order, bool) or cache_order < 0:
+ return None
try:
projection = _validated_projection(envelope.get("projection"), instance_id)
except PermissionsInvalidResponseError:
@@ -591,12 +625,141 @@ def _read_cache(instance_id: str) -> PermissionsProjectionResult | None:
projection=projection,
source="cache",
cached_at=cached_at,
+ cache_order=cache_order,
+ )
+
+
+def _read_cache_order() -> int:
+ try:
+ value = json.loads(_cache_order_path().read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeDecodeError, json.JSONDecodeError):
+ return 0
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
+ return 0
+ return value
+
+
+def _cache_allocate_order(instance_id: str) -> int:
+ """Reserve a request-start order shared by controller and UI processes."""
+
+ with _CACHE_LOCK:
+ try:
+ cache_path = _cache_path()
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ with _cache_file_lock(cache_path):
+ cached = _read_cache(instance_id)
+ current = max(
+ _read_cache_order(),
+ cached.cache_order if cached is not None else 0,
+ )
+ reserved = current + 1
+ _atomic_write_json(_cache_order_path(), reserved)
+ return reserved
+ except (OSError, TimeoutError):
+ logger.warning(
+ "Unable to reserve the Permissions cache request order",
+ exc_info=True,
+ )
+ # The written cache envelope will make this fallback visible to later writers.
+ return max(time.time_ns(), 1)
+
+
+def _prefer_mapping(
+ preferred: Mapping[str, Any],
+ fallback: Mapping[str, Any],
+) -> dict[str, Any]:
+ """Prefer one mapping while retaining additive fields from the other."""
+
+ merged = dict(fallback)
+ for key, value in preferred.items():
+ previous = merged.get(key)
+ if isinstance(value, Mapping) and isinstance(previous, Mapping):
+ merged[key] = _prefer_mapping(value, previous)
+ else:
+ merged[key] = value
+ return merged
+
+
+def _project_progress(project: Mapping[str, Any]) -> tuple[int, int, int, int, str]:
+ sync = project["sync"]
+ access = project["access"]
+ return (
+ int(access["revision"]),
+ int(sync["desired_access_revision"]),
+ int(sync["applied_access_revision"]),
+ _PROJECT_SYNC_PROGRESS[str(sync["status"])],
+ str(sync.get("last_synced_at") or ""),
)
+def _merge_project_projection(
+ preferred: Mapping[str, Any],
+ fallback: Mapping[str, Any],
+) -> dict[str, Any]:
+ merged = _prefer_mapping(preferred, fallback)
+ advanced, other = (
+ (preferred, fallback)
+ if _project_progress(preferred) >= _project_progress(fallback)
+ else (fallback, preferred)
+ )
+ merged["access"] = _prefer_mapping(advanced["access"], other["access"])
+ merged["sync"] = _prefer_mapping(advanced["sync"], other["sync"])
+ return merged
+
+
+def _merge_projects(
+ preferred: list[Any],
+ fallback: list[Any],
+) -> list[dict[str, Any]]:
+ fallback_by_id = {project["project_id"]: project for project in fallback}
+ return [
+ _merge_project_projection(project, fallback_by_id[project["project_id"]])
+ if project["project_id"] in fallback_by_id
+ else dict(project)
+ for project in preferred
+ ]
+
+
+def _merge_policy_sync(
+ preferred: Mapping[str, Any],
+ fallback: Mapping[str, Any],
+) -> dict[str, Any]:
+ advanced, other = (
+ (preferred, fallback)
+ if _POLICY_SYNC_PROGRESS[str(preferred["status"])]
+ >= _POLICY_SYNC_PROGRESS[str(fallback["status"])]
+ else (fallback, preferred)
+ )
+ return _prefer_mapping(advanced, other)
+
+
+def _merge_equal_revision_projection(
+ cached: dict[str, Any],
+ candidate: dict[str, Any],
+ *,
+ prefer_candidate: bool,
+) -> dict[str, Any]:
+ preferred, fallback = (
+ (candidate, cached) if prefer_candidate else (cached, candidate)
+ )
+ merged = _prefer_mapping(preferred, fallback)
+ merged["projects"] = _merge_projects(
+ preferred["projects"],
+ fallback["projects"],
+ )
+ merged["policy_sync"] = _merge_policy_sync(
+ preferred["policy_sync"],
+ fallback["policy_sync"],
+ )
+ return merged
+
+
def _cache_read_merge_write(
instance_id: str,
merge: Callable[[dict[str, Any] | None], Any],
+ *,
+ request_order: int,
+ mutation_rebase: bool = False,
) -> None:
"""Read, merge, and atomically replace one instance cache under one lock."""
@@ -610,19 +773,45 @@ def _cache_read_merge_write(
if candidate is None:
return
validated = _validated_projection(candidate, instance_id)
- if (
- cached is not None
- and cached.projection["instance"]["authorization_revision"]
- > validated["instance"]["authorization_revision"]
- ):
- return
- _write_cache(instance_id, validated)
+ cache_order = request_order
+ if cached is not None:
+ cached_revision = cached.projection["instance"][
+ "authorization_revision"
+ ]
+ candidate_revision = validated["instance"][
+ "authorization_revision"
+ ]
+ if cached_revision > candidate_revision:
+ return
+ cache_order = max(cached.cache_order, request_order)
+ if cached_revision == candidate_revision and not mutation_rebase:
+ validated = _merge_equal_revision_projection(
+ cached.projection,
+ validated,
+ prefer_candidate=(
+ request_order >= cached.cache_order
+ if request_order and cached.cache_order
+ else request_order > 0
+ ),
+ )
+ validated = _validated_projection(validated, instance_id)
+ _write_cache(instance_id, validated, cache_order=cache_order)
except (OSError, TimeoutError):
logger.warning("Unable to cache the current Permissions projection", exc_info=True)
-def _cache_projection(instance_id: str, projection: Any) -> None:
- _cache_read_merge_write(instance_id, lambda _cached: projection)
+def _cache_projection(
+ instance_id: str,
+ projection: Any,
+ *,
+ request_order: int | None = None,
+) -> None:
+ order = _cache_allocate_order(instance_id) if request_order is None else request_order
+ _cache_read_merge_write(
+ instance_id,
+ lambda _cached: projection,
+ request_order=order,
+ )
def _cache_mutation_result(
@@ -631,6 +820,7 @@ def _cache_mutation_result(
*,
access_entries: list[Any] | None = None,
project: Mapping[str, Any] | None = None,
+ request_order: int | None = None,
) -> None:
def merge(cached: dict[str, Any] | None) -> dict[str, Any] | None:
if cached is None:
@@ -652,16 +842,35 @@ def _cache_mutation_result(
}
if project is not None:
project_id = project.get("project_id")
+ cached_project = next(
+ (
+ current
+ for current in cached["projects"]
+ if current.get("project_id") == project_id
+ ),
+ None,
+ )
+ merged_project = (
+ _merge_project_projection(project, cached_project)
+ if cached_project is not None
+ else project
+ )
projects = [
- project if current.get("project_id") == project_id else current
+ merged_project if current.get("project_id") == project_id else current
for current in cached["projects"]
]
if not any(current.get("project_id") == project_id for current in projects):
- projects.append(project)
+ projects.append(merged_project)
projection["projects"] = projects
return projection
- _cache_read_merge_write(instance_id, merge)
+ order = _cache_allocate_order(instance_id) if request_order is None else request_order
+ _cache_read_merge_write(
+ instance_id,
+ merge,
+ request_order=order,
+ mutation_rebase=True,
+ )
def _acknowledge_authorization_revision(config: V2Config, revision: int) -> None:
@@ -728,11 +937,16 @@ def _backend_request(
def get_current_permissions(config: V2Config | None = None) -> PermissionsProjectionResult:
config, load_current_config = _request_config(config)
_, instance_id, _ = _runtime_credentials(config)
+ request_order = _cache_allocate_order(instance_id)
try:
payload, _ = _backend_request(config, load_current_config, "GET", "")
projection = _validated_projection(payload, instance_id)
- _cache_projection(instance_id, projection)
- return PermissionsProjectionResult(projection=projection, source="live")
+ _cache_projection(instance_id, projection, request_order=request_order)
+ return PermissionsProjectionResult(
+ projection=projection,
+ source="live",
+ cache_order=request_order,
+ )
except PermissionsUnavailableError:
cached = _read_cache(instance_id)
if cached is not None:
@@ -752,6 +966,8 @@ def replace_authorized_users(
) -> dict[str, Any]:
config, load_current_config = _request_config(config)
expected_instance_id, backend_payload = _mutation_payload(payload)
+ _, request_instance_id, _ = _runtime_credentials(config)
+ request_order = _cache_allocate_order(request_instance_id)
payload_result, instance_id = _backend_request(
config,
load_current_config,
@@ -766,6 +982,7 @@ def replace_authorized_users(
instance_id,
result["authorization_revision"],
access_entries=result["entries"],
+ request_order=request_order,
)
return {**result, "instance_id": instance_id}
@@ -779,6 +996,8 @@ def update_project_access(
raise PermissionsInvalidResponseError("invalid_project_id")
config, load_current_config = _request_config(config)
expected_instance_id, backend_payload = _mutation_payload(payload)
+ _, request_instance_id, _ = _runtime_credentials(config)
+ request_order = _cache_allocate_order(request_instance_id)
payload_result, instance_id = _backend_request(
config,
load_current_config,
@@ -793,6 +1012,7 @@ def update_project_access(
instance_id,
result["authorization_revision"],
project=result["project"],
+ request_order=request_order,
)
return {**result, "instance_id": instance_id}
@@ -855,8 +1075,21 @@ def resolve_current_instance_ownership(
try:
config = config or V2Config.load()
credentials = config.remote_access.vibe_cloud.runtime_credentials()
- except (FileNotFoundError, OSError, TypeError, ValueError):
- credentials = None
+ except (
+ AttributeError,
+ FileNotFoundError,
+ IndexError,
+ KeyError,
+ OSError,
+ TypeError,
+ ValueError,
+ ):
+ return {
+ "mode": resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ "instance_id": None,
+ "organization_id": None,
+ "source": "config",
+ }
if credentials is None:
return {
"mode": "unmanaged",
@@ -864,9 +1097,25 @@ def resolve_current_instance_ownership(
"organization_id": None,
"source": "config",
}
+ if (
+ not isinstance(credentials, (tuple, list))
+ or len(credentials) != 3
+ or not isinstance(credentials[1], str)
+ or not credentials[1].strip()
+ ):
+ return {
+ "mode": resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ "instance_id": None,
+ "organization_id": None,
+ "source": "config",
+ }
current = resource_access_service.current_show_page_instance_ownership()
- if current["mode"] in {"personal", "organization"}:
+ if current["mode"] in {
+ "personal",
+ "organization",
+ resource_access_service.SHOW_PAGE_OWNERSHIP_CONFIGURATION_UNAVAILABLE,
+ }:
return current
try:
result = get_current_permissions(config)