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
fix(organization): bind async management state
Maxad339afad9e4
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex b17f6bd63..0bd838c77 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -161,27 +161,40 @@ class OrganizationManagementAuthScenarioTests(unittest.TestCase):def test_remote_callback_keeps_the_bound_subject(self):"""Scenario: AUTH-SETUP-307"""- client = self.harness.remote_client(subject="user-1")+ backend = SimpleNamespace(base_url="https://avibe.bot")+ with patch.object(cloud_management, "_validated_backend", return_value=backend):+ _, state = cloud_management.begin_authorization(+ self.harness.config,+ browser_id="browser-1",+ remote_subject="user-1",+ callback_origin=REMOTE_ORIGIN,+ next_path="/admin/organization/overview",+ silent=False,+ )+ client = self.harness.remote_client(subject="user-2")client.set_cookie(cloud_management.BROWSER_COOKIE_NAME, "browser-1", domain="alex.avibe.bot")- grant = cloud_management.ManagementGrant(- handle="grant-1",- browser_id="browser-1",- subject="user-1",- email="[email protected]",- token="not-exposed",- expires_at=4_102_444_800,- )- with patch.object(- cloud_management,- "complete_authorization",- return_value=(grant, "/admin/organization/overview"),- ) as complete:+ token_payload = {+ "access_token": "not-exposed",+ "token_type": "Bearer",+ "subject": "user-2",+ "vibe_instance_id": "inst_123",+ }+ token_claims = {+ "sub": "user-2",+ "email": "[email protected]",+ "vibe_instance_id": "inst_123",+ "exp": 4_102_444_800,+ }+ with (+ patch.object(cloud_management, "_backend_request", return_value=(200, token_payload)),+ patch.object(cloud_management, "_validate_management_token", return_value=token_claims),+ ):response = client.get(- "/auth/organization/callback?code=code-1&state=state-1",+ f"/auth/organization/callback?code=code-1&state={state}",base_url=REMOTE_ORIGIN,)self.assertEqual(response.status_code, 302)- self.assertEqual(complete.call_args.kwargs["remote_subject"], "user-1")+ self.assertIn("cloud_management_error=cloud_management_subject_mismatch", response.headers["location"])self.assertNotIn("not-exposed", response.text)def test_trusted_loopback_flow_can_establish_the_first_subject(self):diff --git a/ui/src/features/organization/pages/OrganizationMembersPage.tsx b/ui/src/features/organization/pages/OrganizationMembersPage.tsxindex 816692877..6f8dfec00 100644--- a/ui/src/features/organization/pages/OrganizationMembersPage.tsx+++ b/ui/src/features/organization/pages/OrganizationMembersPage.tsx@@ -1,4 +1,11 @@-import { useCallback, useEffect, useMemo, useState } from 'react';+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import {Download,Mail,@@ -49,6 +56,7 @@ import {TableFrame,} from '../components';import { useOrganization } from '../context';+import { isCurrentOrganizationLoad } from '../policy';type MemberFilter = 'all' | MemberStatus;@@ -212,39 +220,70 @@ function MemberDialog({export function OrganizationMembersPage() {const { t } = useTranslation();const { detail, selectedOrganizationId, request, dataVersion, invalidate } = useOrganization();- const [members, setMembers] = useState<OrganizationMember[] | null>(null);- const [groups, setGroups] = useState<OrganizationGroup[]>([]);+ const [directory, setDirectory] = useState<{+ organizationId: string;+ members: OrganizationMember[];+ groups: OrganizationGroup[];+ } | null>(null);const [filter, setFilter] = useState<MemberFilter>('all');const [search, setSearch] = useState('');- const [error, setError] = useState<string>();+ const [errorState, setErrorState] = useState<{ organizationId: string; code: string } | null>(null);const [dialogOpen, setDialogOpen] = useState(false);const [editing, setEditing] = useState<OrganizationMember | null>(null);const [removing, setRemoving] = useState<OrganizationMember | null>(null);+ const loadGeneration = useRef(0);+ const selectedOrganizationIdRef = useRef(selectedOrganizationId);+ const currentDirectory = directory?.organizationId === selectedOrganizationId ? directory : null;+ const members = currentDirectory?.members ?? null;+ const groups = currentDirectory?.groups ?? [];+ const error = errorState?.organizationId === selectedOrganizationId ? errorState.code : undefined;const canManage = detail?.capabilities.can_manage_organization === true;+ useLayoutEffect(() => {+ selectedOrganizationIdRef.current = selectedOrganizationId;+ loadGeneration.current += 1;+ }, [selectedOrganizationId]);+const load = useCallback(async (): Promise<OrganizationMember[]> => {if (!selectedOrganizationId) return [];- setError(undefined);+ const organizationId = selectedOrganizationId;+ const generation = ++loadGeneration.current;+ const isCurrent = () => isCurrentOrganizationLoad(+ organizationId,+ selectedOrganizationIdRef.current,+ generation,+ loadGeneration.current,+ );+ setErrorState(null);try {const [memberResult, groupResult] = await Promise.all([request<{ members: OrganizationMember[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/members`,+ `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/members`,),request<{ groups: OrganizationGroup[] }>(- `/api/cloud-management/organizations/${encodeURIComponent(selectedOrganizationId)}/groups`,+ `/api/cloud-management/organizations/${encodeURIComponent(organizationId)}/groups`,),]);- setMembers(memberResult.members);- setGroups(groupResult.groups);+ if (!isCurrent()) return [];+ setDirectory({+ organizationId,+ members: memberResult.members,+ groups: groupResult.groups,+ });return memberResult.members;} catch (caught) {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');+ if (!isCurrent()) return [];+ setErrorState({+ organizationId,+ code: caught instanceof OrganizationApiError ? caught.code : 'generic',+ });return [];}}, [request, selectedOrganizationId]);useEffect(() => {- void load();+ const timer = window.setTimeout(() => void load(), 0);+ return () => window.clearTimeout(timer);}, [dataVersion, load]);const filtered = useMemo(() => (members ?? []).filter((member) => (@@ -270,7 +309,10 @@ export function OrganizationMembersPage() {anchor.click();URL.revokeObjectURL(url);} catch (caught) {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');+ setErrorState({+ organizationId: selectedOrganizationId,+ code: caught instanceof OrganizationApiError ? caught.code : 'generic',+ });}};@@ -296,7 +338,10 @@ export function OrganizationMembersPage() {: null));}- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');+ setErrorState({+ organizationId: selectedOrganizationId,+ code: caught instanceof OrganizationApiError ? caught.code : 'generic',+ });}};@@ -308,7 +353,10 @@ export function OrganizationMembersPage() {{ method: 'POST', body: jsonBody({}) },);} catch (caught) {- setError(caught instanceof OrganizationApiError ? caught.code : 'generic');+ setErrorState({+ organizationId: selectedOrganizationId,+ code: caught instanceof OrganizationApiError ? caught.code : 'generic',+ });}};@@ -389,9 +437,15 @@ export function OrganizationMembersPage() {))}</TableFrame>)}- <MemberDialog open={dialogOpen} member={editing} groups={groups} onOpenChange={setDialogOpen} onSaved={load} />+ <MemberDialog+ open={dialogOpen && currentDirectory !== null}+ member={currentDirectory ? editing : null}+ groups={groups}+ onOpenChange={setDialogOpen}+ onSaved={load}+ /><ConfirmDialog- open={Boolean(removing)}+ open={Boolean(removing && currentDirectory)}onOpenChange={(open) => { if (!open) setRemoving(null); }}title={t('organization.members.removeTitle')}description={t('organization.members.removeBody', { email: removing?.email })}diff --git a/ui/src/features/organization/policy.test.ts b/ui/src/features/organization/policy.test.tsindex 0319a836a..54bb2a689 100644--- a/ui/src/features/organization/policy.test.ts+++ b/ui/src/features/organization/policy.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {aggregateSyncStatus,hasDuplicateProjectPrincipals,+ isCurrentOrganizationLoad,normalizeOrganizationPrincipal,} from './policy';@@ -31,4 +32,10 @@ describe('Organization policy helpers', () => {expect(aggregateSyncStatus({ active: 1, error: 0, offline: 0, applying: 0, in_sync: 1 })).toBe('in_sync');expect(aggregateSyncStatus({ active: 0, error: 0, offline: 0, applying: 0, in_sync: 0 })).toBe('none');});++ it('accepts only the latest load for the currently selected Organization', () => {+ expect(isCurrentOrganizationLoad('org-b', 'org-b', 4, 4)).toBe(true);+ expect(isCurrentOrganizationLoad('org-a', 'org-b', 4, 4)).toBe(false);+ expect(isCurrentOrganizationLoad('org-b', 'org-b', 3, 4)).toBe(false);+ });});diff --git a/ui/src/features/organization/policy.ts b/ui/src/features/organization/policy.tsindex 060d4f096..b24970eef 100644--- a/ui/src/features/organization/policy.ts+++ b/ui/src/features/organization/policy.ts@@ -25,3 +25,15 @@ export function aggregateSyncStatus(counts: SyncCounts): AggregateSyncStatus {if (counts.applying > 0) return 'applying';return counts.active > 0 ? 'in_sync' : 'none';}++export function isCurrentOrganizationLoad(+ requestedOrganizationId: string,+ selectedOrganizationId: string | null,+ requestGeneration: number,+ currentGeneration: number,+): boolean {+ return (+ requestedOrganizationId === selectedOrganizationId+ && requestGeneration === currentGeneration+ );+}diff --git a/vibe/cloud_management.py b/vibe/cloud_management.pyindex d24a8816a..cfacda885 100644--- a/vibe/cloud_management.py+++ b/vibe/cloud_management.py@@ -300,16 +300,18 @@ def complete_authorization(email = str(claims.get("email") or "")response_subject = str(payload.get("subject") or "")response_instance = str(payload.get("vibe_instance_id") or "")- expected = remote_subject or handshake.expected_subject+ subject_mismatch = any(+ expected is not None and not secrets.compare_digest(expected, subject)+ for expected in (handshake.expected_subject, remote_subject)+ )if (payload.get("token_type") != "Bearer"or response_subject != subjector response_instance != config.remote_access.vibe_cloud.instance_idor str(claims.get("vibe_instance_id") or "") != config.remote_access.vibe_cloud.instance_id- or expected is not None- and not secrets.compare_digest(expected, subject)+ or subject_mismatch):- if expected is not None and subject and not secrets.compare_digest(expected, subject):+ if subject_mismatch and subject:raise CloudManagementError("cloud_management_subject_mismatch", status=409)raise CloudManagementError("invalid_cloud_management_token", status=400)expires_at = float(claims["exp"])