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): close resource authorization races

Maxe0fe381158bb
diff --git a/core/show_pages.py b/core/show_pages.py
index 8920af11d..a4d71a66b 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -609,7 +609,7 @@ class ShowPageStore:
session_id = validate_session_id(session_id)
context = _resolve_resource_access_context(user_context)
- with self.engine.connect() as conn:
+ with self.engine.begin() as conn:
row = (
conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))
.mappings()
@@ -625,7 +625,7 @@ class ShowPageStore:
session_id = validate_session_id(session_id)
context = _resolve_resource_access_context(user_context)
- with self.engine.connect() as conn:
+ with self.engine.begin() as conn:
row = (
conn.execute(select(show_pages).where(show_pages.c.session_id == session_id).limit(1))
.mappings()
@@ -682,7 +682,7 @@ class ShowPageStore:
clauses.append(show_pages.c.offline_at.is_not(None))
statement = statement.where(or_(*clauses))
statement = statement.order_by(show_pages.c.updated_at.desc(), show_pages.c.session_id.asc())
- with self.engine.connect() as conn:
+ with self.engine.begin() as conn:
rows = conn.execute(statement).mappings().all()
rows = resource_access_service.filter_accessible_resources(
context,
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 956a40139..630e6a28b 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -337,7 +337,7 @@ def _connection(connection: Connection | None) -> Iterator[Connection]:
yield connection
return
engine = get_cached_sqlite_engine()
- with engine.connect() as active_connection:
+ with engine.begin() as active_connection:
yield active_connection
@@ -535,7 +535,7 @@ def _reconcile_show_page_resource_policy_locked(
raise ResourceAccessError("invalid_show_page_ownership")
if mode in {"personal", "organization"}:
_assert_show_page_pairing_current(ownership)
- fence = remember_show_page_instance_ownership(connection, ownership)
+ fence = _remember_show_page_instance_ownership_locked(connection, ownership)
else:
fence = current_show_page_instance_ownership(connection=connection)
mode = fence["mode"]
@@ -634,6 +634,71 @@ def _show_page_policy_matches_instance_ownership(
)
+def _resolve_authoritative_show_page_ownership(
+ ownership: Mapping[str, Any],
+) -> dict[str, Any]:
+ """Resolve a pending organization fence using the paired Permissions projection."""
+
+ if ownership.get("mode") != "organization_pending":
+ return dict(ownership)
+ try:
+ from vibe import permissions
+
+ resolved = permissions.resolve_current_instance_ownership()
+ except (
+ AttributeError,
+ FileNotFoundError,
+ OSError,
+ TypeError,
+ ValueError,
+ ):
+ return dict(ownership)
+ if resolved.get("mode") == "organization":
+ return dict(resolved)
+ return dict(ownership)
+
+
+def _show_page_authorization_snapshot(
+ connection: Connection,
+ resource_id: str,
+ *,
+ ownership: Mapping[str, Any] | None = None,
+) -> tuple[dict[str, Any], dict[str, Any] | None, list[str]]:
+ """Load one policy after adopting a legacy null-organization shape when safe."""
+
+ identifier = _required_identifier(resource_id, code="invalid_resource_id")
+ policy = _policy_row(connection, "show_page", identifier)
+ current_ownership = dict(
+ ownership
+ if ownership is not None
+ else current_show_page_instance_ownership(connection=connection)
+ )
+ policy_organization = _clean_optional_string(
+ policy.get("organization_id") if policy else None
+ )
+ if (
+ policy is not None
+ and policy_organization is None
+ and current_ownership.get("mode") in {"organization", "organization_pending"}
+ ):
+ resolved_ownership = _resolve_authoritative_show_page_ownership(current_ownership)
+ if resolved_ownership.get("mode") == "organization":
+ try:
+ reconciliation = reconcile_show_page_resource_policy(
+ connection,
+ resource_id=identifier,
+ ownership=resolved_ownership,
+ owner_user_id=_clean_optional_string(policy.get("owner_user_id")),
+ owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),
+ )
+ except ResourceAccessError:
+ return _configuration_unavailable_ownership(), policy, []
+ current_ownership = dict(reconciliation["ownership"])
+ policy = reconciliation["policy"]
+ groups = _policy_groups(connection, "show_page", identifier) if policy else []
+ return current_ownership, policy, groups
+
+
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)
@@ -1043,13 +1108,12 @@ def can_use_resource(
kind = _validate_resource_kind(resource_kind)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
with _connection(connection) as conn:
- policy = _policy_row(conn, kind, identifier)
- groups = _policy_groups(conn, kind, identifier) if policy else []
- ownership = (
- current_show_page_instance_ownership(connection=conn)
- if kind == "show_page"
- else None
- )
+ if kind == "show_page":
+ ownership, policy, groups = _show_page_authorization_snapshot(conn, identifier)
+ else:
+ policy = _policy_row(conn, kind, identifier)
+ groups = _policy_groups(conn, kind, identifier) if policy else []
+ ownership = None
return _policy_allows(
context,
kind,
@@ -1071,12 +1135,16 @@ def can_manage_resource_acl(
kind = _validate_resource_kind(resource_kind)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
with _connection(connection) as conn:
- policy = _policy_row(conn, kind, identifier)
+ if kind == "show_page":
+ ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)
+ else:
+ ownership = None
+ 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),
+ ownership or {},
policy,
)
):
@@ -1095,11 +1163,11 @@ def can_manage_show_page_access(
context = _as_context(user_context)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
with _connection(connection) as conn:
- policy = _policy_row(conn, "show_page", identifier)
+ ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)
if (
not context.is_instance_owner
and not _show_page_policy_matches_instance_ownership(
- current_show_page_instance_ownership(connection=conn),
+ ownership,
policy,
)
):
@@ -1120,12 +1188,16 @@ def can_control_resource_sharing(
kind = _validate_resource_kind(resource_kind)
identifier = _required_identifier(resource_id, code="invalid_resource_id")
with _connection(connection) as conn:
- policy = _policy_row(conn, kind, identifier)
+ if kind == "show_page":
+ ownership, policy, _groups = _show_page_authorization_snapshot(conn, identifier)
+ else:
+ ownership = None
+ 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),
+ ownership or {},
policy,
)
):
@@ -1179,11 +1251,27 @@ 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
- )
+ ownership = current_show_page_instance_ownership(connection=conn) if kind == "show_page" else None
+ if kind == "show_page":
+ resolved_ownership = _resolve_authoritative_show_page_ownership(ownership)
+ if resolved_ownership.get("mode") == "organization":
+ ownership = resolved_ownership
+ for identifier, policy in list(policies.items()):
+ if _clean_optional_string(policy.get("organization_id")) is not None:
+ continue
+ try:
+ reconciliation = reconcile_show_page_resource_policy(
+ conn,
+ resource_id=identifier,
+ ownership=ownership,
+ owner_user_id=_clean_optional_string(policy.get("owner_user_id")),
+ owner_email=_clean_optional_string(policy.get("owner_email"), limit=320),
+ )
+ except ResourceAccessError:
+ ownership = _configuration_unavailable_ownership()
+ break
+ policies[identifier] = reconciliation["policy"] or policy
+ groups[identifier] = _policy_groups(conn, kind, identifier)
return [
row
for row, identifier in candidates
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index a84eb3bdc..59be99b97 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -514,6 +514,54 @@ def test_resource_access_client_rejects_response_identity_mismatch(
permissions.get_resource_access("show_page", "page-1", _config())
[email protected]("operation", ["get", "put"])
+def test_resource_access_rechecks_pairing_after_response_validation(
+ monkeypatch,
+ operation: str,
+) -> None:
+ config = _config()
+ original_validate = permissions._validate_resource # noqa: SLF001
+
+ def validate_and_repair(*args, **kwargs):
+ result = original_validate(*args, **kwargs)
+ replacement = V2Config.load()
+ replacement.remote_access.vibe_cloud.instance_id = "inst-new"
+ replacement.save()
+ return result
+
+ monkeypatch.setattr(permissions, "_validate_resource", validate_and_repair)
+ monkeypatch.setattr(
+ permissions.requests,
+ "request",
+ lambda method, *_args, **_kwargs: _Response(
+ 200,
+ {
+ **({"ok": True} if method == "PUT" else {}),
+ "resource": _resource(revision=5 if method == "PUT" else 4),
+ },
+ ),
+ )
+
+ with pytest.raises(
+ permissions.PermissionsPairingChangedError,
+ match="permissions_pairing_changed",
+ ):
+ if operation == "get":
+ permissions.get_resource_access("show_page", "page-1", config)
+ else:
+ 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,
+ )
+
+
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"
@@ -892,6 +940,46 @@ def test_permissions_cache_mutation_rebase_preserves_newer_project_sync_state()
assert cached.projection["projects"][0]["sync"] == newer_project["sync"]
[email protected]("entity", ["access", "project"])
+def test_permissions_cache_replays_superseded_mutation_entity_without_lowering_revision(
+ entity: str,
+) -> None:
+ newer = _complete_projection()
+ newer["directory"]["members"][0]["email"] = "[email protected]"
+ newer["policy_sync"]["status"] = "in_sync"
+ newer["instance"]["authorization_revision"] = 4
+ permissions._cache_projection("inst-123", newer, request_order=20) # noqa: SLF001
+
+ if entity == "access":
+ entries = [{"kind": "email", "value": "[email protected]", "role": "editor"}]
+ permissions._cache_mutation_result( # noqa: SLF001
+ "inst-123",
+ 3,
+ access_entries=entries,
+ request_order=19,
+ )
+ else:
+ acknowledged = deepcopy(newer["projects"][0])
+ acknowledged["display_name"] = "Delayed Project"
+ acknowledged["access"]["revision"] = 5
+ permissions._cache_mutation_result( # noqa: SLF001
+ "inst-123",
+ 3,
+ project=acknowledged,
+ request_order=19,
+ )
+
+ cached = permissions._read_cache("inst-123") # noqa: SLF001
+ assert cached is not None
+ assert cached.projection["instance"]["authorization_revision"] == 4
+ assert cached.projection["directory"] == newer["directory"]
+ assert cached.projection["policy_sync"] == newer["policy_sync"]
+ if entity == "access":
+ assert cached.projection["access"]["entries"] == entries
+ else:
+ assert cached.projection["projects"][0]["display_name"] == "Delayed Project"
+
+
@pytest.mark.parametrize(
"status",
[*sorted(permissions._CACHE_FALLBACK_HTTP_STATUSES), 503], # noqa: SLF001
@@ -1687,7 +1775,7 @@ def test_mutation_result_is_sanitized_before_cache_write(monkeypatch) -> None:
assert cached.projection["access"]["entries"] == result["entries"]
-def test_older_mutation_result_cannot_mix_its_payload_into_a_newer_cache(monkeypatch) -> None:
+def test_older_mutation_result_replays_its_entity_without_lowering_cache_revision(monkeypatch) -> None:
live = _complete_projection()
live["instance"]["authorization_revision"] = 5
backend_available = True
@@ -1723,7 +1811,7 @@ def test_older_mutation_result_cannot_mix_its_payload_into_a_newer_cache(monkeyp
cached = permissions.get_current_permissions(config)
assert cached.projection["instance"]["authorization_revision"] == 5
- assert cached.projection["access"]["entries"] == live["access"]["entries"]
+ assert cached.projection["access"]["entries"] == stale_entries
def test_authorized_users_mutation_refreshes_offline_cache(monkeypatch) -> None:
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 24f734b08..7105324b0 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -246,6 +246,70 @@ def test_show_page_unpaired_configuration_remains_explicitly_unmanaged(
engine.dispose()
+def test_show_page_authorizers_adopt_legacy_policy_before_enforcing_organization_fence(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.backend_url = "https://backend.example"
+ cloud.instance_id = "inst-1"
+ cloud.instance_secret = "device-secret"
+ cloud.instance_kind = "organization"
+ config.save()
+ monkeypatch.setattr(
+ permissions,
+ "resolve_current_instance_ownership",
+ lambda: {
+ "mode": "organization",
+ "instance_id": "inst-1",
+ "organization_id": "org-1",
+ "source": "live",
+ },
+ )
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ owner = _context("owner-1", instance_role="editor")
+ 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="owner-1",
+ access_level="private",
+ )
+ assert resource_access_service.can_use_resource(
+ owner, "show_page", "legacy-page", connection=connection
+ )
+ assert resource_access_service.can_manage_resource_acl(
+ owner, "show_page", "legacy-page", connection=connection
+ )
+ assert resource_access_service.can_manage_show_page_access(
+ owner, "legacy-page", connection=connection
+ )
+ assert resource_access_service.can_control_resource_sharing(
+ owner, "show_page", "legacy-page", connection=connection
+ )
+ assert resource_access_service.filter_accessible_resources(
+ owner,
+ "show_page",
+ [{"session_id": "legacy-page"}],
+ connection=connection,
+ ) == [{"session_id": "legacy-page"}]
+ policy = resource_access_service.get_resource_policy(
+ "show_page", "legacy-page", connection=connection
+ )
+ assert policy is not None
+ assert policy["organization_id"] == "org-1"
+ finally:
+ engine.dispose()
+
+
@pytest.mark.parametrize(
("previous_level", "previous_groups", "updated_level", "updated_groups", "expected"),
[
diff --git a/ui/src/components/workbench/ShowPageShareControl.test.tsx b/ui/src/components/workbench/ShowPageShareControl.test.tsx
index 2249aa99e..7af24bdcc 100644
--- a/ui/src/components/workbench/ShowPageShareControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.test.tsx
@@ -405,6 +405,41 @@ describe('ShowPageShareControl payload sequencing without prior access', () => {
expect(api.setShowPageAvailability).not.toHaveBeenCalled();
});
+ it('shows a Personal ownership conflict through the Workspace control', async () => {
+ const conflict = showPageAccess({
+ mode: 'personal',
+ ownership_status: 'conflict',
+ instance_id: 'inst-1',
+ organization_id: null,
+ policy_organization_id: 'org-other',
+ can_use: true,
+ can_manage: true,
+ can_publish_public: false,
+ });
+ api.getShowPageAccess.mockResolvedValue(conflict);
+ api.ensureShowPage.mockResolvedValue({
+ session_id: 'ses-1',
+ visibility: 'private',
+ active_url: '/show/ses-1/',
+ share_id: null,
+ url_available: true,
+ offline: false,
+ title: null,
+ });
+
+ render(
+ <I18nextProvider i18n={i18n}>
+ <ShowPageShareControl sessionId="ses-1" initialAccess={conflict} canManageInstance />
+ </I18nextProvider>,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));
+
+ expect(await screen.findByText('This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.')).toBeTruthy();
+ expect(screen.queryByText('This Show Page belongs to a Personal Avibe.')).toBeNull();
+ expect(permissionsApi.getPermissions).not.toHaveBeenCalled();
+ expect(permissionsApi.getResourceAccess).not.toHaveBeenCalled();
+ });
+
it('keeps explicit custom-link saving while online and Workspace controls stay out', async () => {
api.getShowPageAccess.mockResolvedValue(showPageAccess({
can_use: true,
diff --git a/ui/src/components/workbench/ShowPageShareControl.tsx b/ui/src/components/workbench/ShowPageShareControl.tsx
index 87a5e2381..05ebe48e5 100644
--- a/ui/src/components/workbench/ShowPageShareControl.tsx
+++ b/ui/src/components/workbench/ShowPageShareControl.tsx
@@ -299,7 +299,8 @@ export const ShowPageShareControl: React.FC<{
) : null}
{access && (
- access.mode === 'organization'
+ access.ownership_status === 'conflict'
+ || access.mode === 'organization'
|| access.mode === 'organization_pending'
|| access.mode === 'configuration_unavailable'
) ? (
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
index 4b72e090b..ddbbf1a90 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.test.tsx
@@ -213,6 +213,42 @@ afterEach(() => {
});
describe('ShowPageWorkspaceAccessControl', () => {
+ it('prioritizes an ownership conflict over the Personal mode message', () => {
+ renderControl(showPageAccess({ mode: 'personal', ownership_status: 'conflict' }));
+
+ expect(screen.getByText('This Show Page is bound to a different ownership domain. Access remains private until the conflict is resolved.')).toBeTruthy();
+ expect(screen.queryByText('This Show Page belongs to a Personal Avibe.')).toBeNull();
+ expect(api.getPermissions).not.toHaveBeenCalled();
+ expect(api.getResourceAccess).not.toHaveBeenCalled();
+ });
+
+ it('polls a pending Resource until the exact instance reports a terminal sync state', async () => {
+ vi.useFakeTimers();
+ try {
+ api.getResourceAccess
+ .mockResolvedValueOnce({ resource: resource({ status: 'pending' }) })
+ .mockResolvedValueOnce({ resource: resource({ status: 'offline' }) });
+ renderControl();
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(api.getResourceAccess).toHaveBeenCalledTimes(1);
+ expect(screen.getByText('The policy is waiting for this Avibe to apply it.')).toBeTruthy();
+
+ await act(async () => {
+ vi.advanceTimersByTime(2_000);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(api.getResourceAccess).toHaveBeenCalledTimes(2);
+ expect(screen.getByText('This Avibe has not acknowledged the latest policy.')).toBeTruthy();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('classifies every Workspace policy reduction at the shared boundary', () => {
expect(requiresResourcePolicyNarrowing('public', [], 'private', [])).toBe(true);
expect(requiresResourcePolicyNarrowing('public', [], 'scope', ['group-active'])).toBe(true);
diff --git a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
index 5a5ee6826..62130364a 100644
--- a/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
+++ b/ui/src/components/workbench/ShowPageWorkspaceAccessControl.tsx
@@ -29,6 +29,8 @@ type Draft = {
groupIds: string[];
};
+const RESOURCE_SYNC_POLL_INTERVAL_MS = 2_000;
+
const uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();
const resourceIdentityMatches = (
@@ -71,12 +73,16 @@ export function ShowPageWorkspaceAccessControl({
const [errorCode, setErrorCode] = useState<string | null>(null);
const generationRef = useRef(0);
const sessionIdRef = useRef(sessionId);
+ const resourceRef = useRef<PermissionResource | null>(resource);
+ const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const draftRef = useRef<Draft>({ level, groupIds });
sessionIdRef.current = sessionId;
+ resourceRef.current = resource;
draftRef.current = { level, groupIds };
const instanceId = access?.instance_id ?? null;
const organizationId = access?.organization_id ?? null;
+ const resourceSyncStatus = resource?.sync.status;
const ownershipConflict = access?.ownership_status === 'conflict';
const organizationReady = access?.mode === 'organization'
&& !ownershipConflict
@@ -167,6 +173,72 @@ export function ShowPageWorkspaceAccessControl({
};
}, [active, load, organizationReady, sessionId]);
+ useEffect(() => {
+ if (
+ !active
+ || !organizationReady
+ || !instanceId
+ || resourceSyncStatus !== 'pending'
+ ) {
+ return undefined;
+ }
+ let cancelled = false;
+ const generation = generationRef.current;
+ const requestSessionId = sessionId;
+ const requestInstanceId = instanceId;
+
+ const schedule = () => {
+ if (!cancelled) {
+ pollTimerRef.current = setTimeout(() => void poll(), RESOURCE_SYNC_POLL_INTERVAL_MS);
+ }
+ };
+ const poll = async () => {
+ if (cancelled) return;
+ try {
+ const next = await getResourceAccess({
+ resource_kind: 'show_page',
+ resource_id: requestSessionId,
+ });
+ if (
+ cancelled
+ || generation !== generationRef.current
+ || requestSessionId !== sessionIdRef.current
+ || requestInstanceId !== instanceId
+ || !resourceIdentityMatches(next.resource, requestSessionId, requestInstanceId)
+ ) return;
+ const currentResource = resourceRef.current;
+ const currentDraft = draftRef.current;
+ const draftIsDirty = Boolean(
+ currentResource
+ && (
+ currentResource.access.access_level !== currentDraft.level
+ || uniqueSorted(currentResource.access.group_ids).join('\u0000')
+ !== uniqueSorted(currentDraft.groupIds).join('\u0000')
+ )
+ );
+ setResource(next.resource);
+ if (!draftIsDirty) {
+ setLevel(next.resource.access.access_level);
+ setGroupIds(uniqueSorted(next.resource.access.group_ids));
+ }
+ if (next.resource.sync.status === 'pending') schedule();
+ } catch {
+ // A transient transport failure must not discard the pending resource;
+ // retry while this exact instance remains mounted.
+ schedule();
+ }
+ };
+
+ schedule();
+ return () => {
+ cancelled = true;
+ if (pollTimerRef.current !== null) {
+ clearTimeout(pollTimerRef.current);
+ pollTimerRef.current = null;
+ }
+ };
+ }, [active, instanceId, organizationReady, resourceSyncStatus, sessionId]);
+
const visibleGroups = useMemo(() => {
const bound = new Set(resource?.access.group_ids ?? []);
return groups.filter((group) => group.archived_at === null || bound.has(group.id));
@@ -284,7 +356,12 @@ export function ShowPageWorkspaceAccessControl({
</p>
</div>
- {access?.mode === 'configuration_unavailable' ? (
+ {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>
+ ) : 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')}
@@ -300,11 +377,6 @@ export function ShowPageWorkspaceAccessControl({
<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" />
diff --git a/vibe/permissions.py b/vibe/permissions.py
index dfececff3..147222305 100644
--- a/vibe/permissions.py
+++ b/vibe/permissions.py
@@ -478,6 +478,7 @@ def _validated_resource_result(
resource_kind: str,
resource_id: str,
mutation: bool,
+ pairing_guard: Callable[[], None] | None = None,
) -> dict[str, Any]:
result = _require_mapping(_strip_sensitive(payload))
_require_keys(result, "resource")
@@ -491,6 +492,8 @@ def _validated_resource_result(
resource_kind=resource_kind,
resource_id=resource_id,
)
+ if pairing_guard is not None:
+ pairing_guard()
return result
@@ -853,13 +856,15 @@ def _cache_mutation_result(
if cached is None:
return None
current_revision = cached["instance"]["authorization_revision"]
- if authorization_revision < current_revision:
- return None
+ # A mutation acknowledgement can arrive after a newer global revision
+ # was cached by another mutation. Keep that newer fence while replaying
+ # the entity that this acknowledgement actually committed.
+ effective_revision = max(current_revision, authorization_revision)
projection = {
**cached,
"instance": {
**cached["instance"],
- "authorization_revision": authorization_revision,
+ "authorization_revision": effective_revision,
},
}
if access_entries is not None:
@@ -927,8 +932,9 @@ def _backend_request(
*,
expected_instance_id: str | None = None,
timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ credentials: tuple[str, str, str] | None = None,
) -> tuple[dict[str, Any], str]:
- credentials = _runtime_credentials(config)
+ credentials = credentials or _runtime_credentials(config)
backend_url, instance_id, instance_secret = credentials
if expected_instance_id is not None and expected_instance_id != instance_id:
raise PermissionsPairingChangedError("permissions_pairing_changed")
@@ -1086,11 +1092,14 @@ def get_resource_access(
) -> dict[str, Any]:
resource_kind, resource_id = _require_resource_identity(resource_kind, resource_id)
config, load_current_config = _request_config(config)
+ credentials = _runtime_credentials(config)
+ pairing_guard = lambda: _guard_current_pairing(credentials, load_current_config)
payload_result, instance_id = _backend_request(
config,
load_current_config,
"GET",
f"resources/{quote(resource_kind, safe='')}/{quote(resource_id, safe='')}/access",
+ credentials=credentials,
)
return _validated_resource_result(
payload_result,
@@ -1098,6 +1107,7 @@ def get_resource_access(
resource_kind=resource_kind,
resource_id=resource_id,
mutation=False,
+ pairing_guard=pairing_guard,
)
@@ -1109,6 +1119,8 @@ def update_resource_access(
) -> dict[str, Any]:
resource_kind, resource_id = _require_resource_identity(resource_kind, resource_id)
config, load_current_config = _request_config(config)
+ credentials = _runtime_credentials(config)
+ pairing_guard = lambda: _guard_current_pairing(credentials, load_current_config)
expected_instance_id, backend_payload = _mutation_payload(payload)
payload_result, instance_id = _backend_request(
config,
@@ -1117,6 +1129,7 @@ def update_resource_access(
f"resources/{quote(resource_kind, safe='')}/{quote(resource_id, safe='')}/access",
backend_payload,
expected_instance_id=expected_instance_id,
+ credentials=credentials,
)
return _validated_resource_result(
payload_result,
@@ -1124,6 +1137,7 @@ def update_resource_access(
resource_kind=resource_kind,
resource_id=resource_id,
mutation=True,
+ pairing_guard=pairing_guard,
)